File: api_system_volumes.go

package info (click to toggle)
snapd 2.72-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 80,412 kB
  • sloc: sh: 16,506; ansic: 16,211; python: 11,213; makefile: 1,919; exp: 190; awk: 58; xml: 22
file content (404 lines) | stat: -rw-r--r-- 13,240 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
// -*- Mode: Go; indent-tabs-mode: t -*-

/*
 * Copyright (C) 2025 Canonical Ltd
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package daemon

import (
	"encoding/json"
	"errors"
	"net/http"
	"net/url"

	"github.com/snapcore/snapd/client"
	"github.com/snapcore/snapd/gadget/device"
	"github.com/snapcore/snapd/overlord/auth"
	"github.com/snapcore/snapd/overlord/devicestate"
	"github.com/snapcore/snapd/overlord/fdestate"
	"github.com/snapcore/snapd/overlord/state"
	"github.com/snapcore/snapd/overlord/swfeats"
	"github.com/snapcore/snapd/secboot/keys"
	"github.com/snapcore/snapd/strutil"
)

var systemVolumesCmd = &Command{
	Path: "/v2/system-volumes",
	GET:  getSystemVolumes,
	POST: postSystemVolumesAction,
	Actions: []string{
		"generate-recovery-key", "check-recovery-key", "replace-recovery-key",
		"replace-platform-key", "check-passphrase", "check-pin", "change-passphrase"},
	// anyone can enumerate key slots.
	ReadAccess: interfaceOpenAccess{Interfaces: []string{"snap-fde-control"}},
	WriteAccess: byActionAccess{
		ByAction: map[string]accessChecker{
			// anyone check passphrase/pin quality
			"check-passphrase": interfaceOpenAccess{Interfaces: []string{"snap-fde-control"}},
			"check-pin":        interfaceOpenAccess{Interfaces: []string{"snap-fde-control"}},
			// anyone can change passphrase given they know the old passphrase
			// TODO:FDEM: rate limiting is needed to avoid DA lockout.
			"change-passphrase": interfaceOpenAccess{Interfaces: []string{"snap-fde-control"}},
			// only root and admins (authenticated via Polkit) can do recovery key
			// related actions.
			"check-recovery-key": interfaceRootAccess{
				// firmware-updater-support is allowed so that a user can verify
				// their recovery key is valid before doing the firmware update
				// which might require entering their recovery key on next boot.
				Interfaces: []string{"snap-fde-control", "firmware-updater-support"},
				Polkit:     polkitActionManageFDE,
			},
			"generate-recovery-key": interfaceRootAccess{
				Interfaces: []string{"snap-fde-control"},
				Polkit:     polkitActionManageFDE,
			},
			"replace-recovery-key": interfaceRootAccess{
				Interfaces: []string{"snap-fde-control"},
				Polkit:     polkitActionManageFDE,
			},
			"replace-platform-key": interfaceRootAccess{
				Interfaces: []string{"snap-fde-control"},
				Polkit:     polkitActionManageFDE,
			},
		},
		// by default, all actions are only allowed for root.
		Default: rootAccess{},
	},
}

var fdeReplaceRecoveryKeyChangeKind = swfeats.RegisterChangeKind("fde-replace-recovery-key")
var fdeReplacePlatformKeyChangeKind = swfeats.RegisterChangeKind("fde-replace-platform-key")
var fdeChangePassphraseChangeKind = swfeats.RegisterChangeKind("fde-change-passphrase")

var (
	fdestateReplaceRecoveryKey = fdestate.ReplaceRecoveryKey
	fdestateReplacePlatformKey = fdestate.ReplacePlatformKey
	fdestateChangeAuth         = fdestate.ChangeAuth
	fdeMgrGenerateRecoveryKey  = (*fdestate.FDEManager).GenerateRecoveryKey
	fdeMgrCheckRecoveryKey     = (*fdestate.FDEManager).CheckRecoveryKey

	devicestateGetVolumeStructuresWithKeyslots = devicestate.GetVolumeStructuresWithKeyslots
)

func parseSystemVolumesOptionsFromURL(q url.Values) (opts *client.SystemVolumesOptions, err error) {
	opts = &client.SystemVolumesOptions{
		ContainerRoles: q["container-role"],
	}
	switch q.Get("by-container-role") {
	case "true", "false", "":
		opts.ByContainerRole = q.Get("by-container-role") == "true"
	default:
		return nil, errors.New(`"by-container-role" query parameter when used must be set to "true" or "false" or left unset`)
	}
	if len(opts.ContainerRoles) > 0 && opts.ByContainerRole {
		return nil, errors.New(`"container-role" query parameter conflicts with "by-container-role"`)
	}
	return opts, nil
}

func structureInfoFromVolumeStructure(structure *devicestate.VolumeStructureWithKeyslots) (*client.SystemVolumesStructureInfo, error) {
	structureInfo := &client.SystemVolumesStructureInfo{
		VolumeName: structure.VolumeName,
		Name:       structure.Name,
		Encrypted:  len(structure.Keyslots) > 0,
	}
	if structureInfo.Encrypted {
		structureInfo.Keyslots = make(map[string]client.KeyslotInfo, len(structure.Keyslots))
	}
	for _, keyslot := range structure.Keyslots {
		keyslotInfo := client.KeyslotInfo{
			Type: client.KeyslotType(keyslot.Type),
		}
		if keyslot.Type == fdestate.KeyslotTypePlatform {
			kd, err := keyslot.KeyData()
			if err != nil {
				return nil, err
			}
			keyslotInfo.PlatformName = kd.PlatformName()
			keyslotInfo.Roles = kd.Roles()
			keyslotInfo.AuthMode = kd.AuthMode()
		}
		structureInfo.Keyslots[keyslot.Name] = keyslotInfo
	}
	return structureInfo, nil
}

func getSystemVolumes(c *Command, r *http.Request, user *auth.UserState) Response {
	supported, respErr := systemVolumesAPISupportedLocking(c.d.overlord.State())
	if respErr != nil {
		return respErr
	}

	if !supported {
		return BadRequest("this action is not supported on this system")
	}

	opts, err := parseSystemVolumesOptionsFromURL(r.URL.Query())
	if err != nil {
		return BadRequest(err.Error())
	}

	structures, err := func() ([]devicestate.VolumeStructureWithKeyslots, error) {
		c.d.state.Lock()
		defer c.d.state.Unlock()

		return devicestateGetVolumeStructuresWithKeyslots(c.d.state)

	}()
	if err != nil {
		return InternalError("cannot get encryption information for gadget volumes: %v", err)
	}

	res := client.SystemVolumesResult{
		ByContainerRole: make(map[string]client.SystemVolumesStructureInfo),
	}
	for _, structure := range structures {
		if structure.Role == "" {
			// ignore structures without a role until other grouping
			// requires them.
			continue
		}
		switch {
		// conversion is done only on a match do as little key data loading
		// as possible since it is lazy loaded.
		case len(opts.ContainerRoles) > 0:
			if strutil.ListContains(opts.ContainerRoles, structure.Role) {
				structureInfo, err := structureInfoFromVolumeStructure(&structure)
				if err != nil {
					return InternalError("cannot convert volume structure: %v", err)
				}
				res.ByContainerRole[structure.Role] = *structureInfo
			}
		case opts.ByContainerRole:
			structureInfo, err := structureInfoFromVolumeStructure(&structure)
			if err != nil {
				return InternalError("cannot convert volume structure: %v", err)
			}
			res.ByContainerRole[structure.Role] = *structureInfo
		default:
			// all groupings, currently only by-container-role is supported.
			structureInfo, err := structureInfoFromVolumeStructure(&structure)
			if err != nil {
				return InternalError("cannot convert volume structure: %v", err)
			}
			res.ByContainerRole[structure.Role] = *structureInfo
		}
	}
	return SyncResponse(res)
}

type systemVolumesActionRequest struct {
	Action string `json:"action"`

	Keyslots []fdestate.KeyslotRef `json:"keyslots"`

	RecoveryKey    string   `json:"recovery-key"`
	ContainerRoles []string `json:"container-roles"`
	// KeyID is the recovery key id.
	KeyID string `json:"key-id"`

	client.PlatformKeyOptions
	client.ChangePassphraseOptions
}

func postSystemVolumesAction(c *Command, r *http.Request, user *auth.UserState) Response {
	supported, respErr := systemVolumesAPISupportedLocking(c.d.overlord.State())
	if respErr != nil {
		return respErr
	}

	if !supported {
		return BadRequest("this action is not supported on this system")
	}

	contentType := r.Header.Get("Content-Type")
	switch contentType {
	case "application/json":
		return postSystemVolumesActionJSON(c, r)
	default:
		return BadRequest("unexpected content type: %q", contentType)
	}
}

func postSystemVolumesActionJSON(c *Command, r *http.Request) Response {
	var req systemVolumesActionRequest

	decoder := json.NewDecoder(r.Body)

	if err := decoder.Decode(&req); err != nil {
		return BadRequest("cannot decode request body: %v", err)
	}

	if decoder.More() {
		return BadRequest("extra content found in request body")
	}

	switch req.Action {
	case "generate-recovery-key":
		return postSystemVolumesActionGenerateRecoveryKey(c)
	case "check-recovery-key":
		return postSystemVolumesActionCheckRecoveryKey(c, &req)
	case "replace-recovery-key":
		return postSystemVolumesActionReplaceRecoveryKey(c, &req)
	case "replace-platform-key":
		return postSystemVolumesActionReplacePlatformKey(c, &req)
	case "check-passphrase":
		return postSystemVolumesCheckPassphrase(&req)
	case "check-pin":
		return postSystemVolumesCheckPIN(&req)
	case "change-passphrase":
		return postSystemVolumesActionChangePassphrase(c, &req)
	default:
		return BadRequest("unsupported system volumes action %q", req.Action)
	}
}

func postSystemVolumesActionGenerateRecoveryKey(c *Command) Response {
	fdemgr := c.d.overlord.FDEManager()

	rkey, keyID, err := fdeMgrGenerateRecoveryKey(fdemgr)
	if err != nil {
		return InternalError(err.Error())
	}

	return SyncResponse(map[string]string{
		"recovery-key": rkey.String(),
		"key-id":       keyID,
	})
}

func postSystemVolumesActionCheckRecoveryKey(c *Command, req *systemVolumesActionRequest) Response {
	if req.RecoveryKey == "" {
		return BadRequest("system volume action requires recovery-key to be provided")
	}

	rkey, err := keys.ParseRecoveryKey(req.RecoveryKey)
	if err != nil {
		return BadRequest("cannot parse recovery key: %v", err)
	}

	st := c.d.overlord.State()
	st.Lock()
	defer st.Unlock()

	fdemgr := c.d.overlord.FDEManager()
	if err := fdeMgrCheckRecoveryKey(fdemgr, rkey, req.ContainerRoles); err != nil {
		// TODO:FDEM: distinguish between failure due to a bad key and an
		// actual internal error where snapd fails to do the check.
		return BadRequest("cannot find matching recovery key: %v", err)
	}

	return SyncResponse(nil)
}

func postSystemVolumesActionReplaceRecoveryKey(c *Command, req *systemVolumesActionRequest) Response {
	if req.KeyID == "" {
		return BadRequest("system volume action requires key-id to be provided")
	}

	st := c.d.overlord.State()
	st.Lock()
	defer st.Unlock()

	ts, err := fdestateReplaceRecoveryKey(st, req.KeyID, req.Keyslots)
	if err != nil {
		return errToResponse(err, nil, BadRequest, "cannot replace recovery key: %v")
	}

	chg := newChange(st, fdeReplaceRecoveryKeyChangeKind, "Replace recovery key", []*state.TaskSet{ts}, nil)

	st.EnsureBefore(0)

	return AsyncResponse(nil, chg.ID())
}

func postSystemVolumesActionReplacePlatformKey(c *Command, req *systemVolumesActionRequest) Response {
	// XXX: Only support passphrase auth mode for now?
	if req.AuthMode == "" {
		return BadRequest("system volume action requires auth-mode to be provided")
	}

	var volumesAuth *device.VolumesAuthOptions
	if req.AuthMode != device.AuthModeNone {
		volumesAuth = &device.VolumesAuthOptions{
			Mode:       req.AuthMode,
			PIN:        req.PIN,
			Passphrase: req.Passphrase,
			KDFType:    req.KDFType,
			KDFTime:    req.KDFTime,
		}
		if err := volumesAuth.Validate(); err != nil {
			return BadRequest("invalid platform key options: %v", err)
		}
	}

	st := c.d.overlord.State()
	st.Lock()
	defer st.Unlock()

	ts, err := fdestateReplacePlatformKey(st, volumesAuth, req.Keyslots)
	if err != nil {
		return errToResponse(err, nil, BadRequest, "cannot replace platform key: %v")
	}

	chg := newChange(st, fdeReplacePlatformKeyChangeKind, "Replace platform key", []*state.TaskSet{ts}, nil)

	st.EnsureBefore(0)

	return AsyncResponse(nil, chg.ID())
}

func postSystemVolumesCheckPassphrase(req *systemVolumesActionRequest) Response {
	if req.Passphrase == "" {
		return BadRequest("passphrase must be provided in request body for action %q", req.Action)
	}

	return postValidatePassphrase(device.AuthModePassphrase, req.Passphrase)
}

func postSystemVolumesCheckPIN(req *systemVolumesActionRequest) Response {
	if req.PIN == "" {
		return BadRequest("pin must be provided in request body for action %q", req.Action)
	}

	return postValidatePassphrase(device.AuthModePIN, req.PIN)
}

func postSystemVolumesActionChangePassphrase(c *Command, req *systemVolumesActionRequest) Response {
	// TODO:FDEM: allow root to reset passphrase without providing old passphrase.
	if req.OldPassphrase == "" {
		return BadRequest("system volume action requires old-passphrase to be provided")
	}
	if req.NewPassphrase == "" {
		return BadRequest("system volume action requires new-passphrase to be provided")
	}

	st := c.d.overlord.State()
	st.Lock()
	defer st.Unlock()

	ts, err := fdestateChangeAuth(st, device.AuthModePassphrase, req.OldPassphrase, req.NewPassphrase, req.Keyslots)
	if err != nil {
		return errToResponse(err, nil, BadRequest, "cannot change passphrase: %v")
	}

	chg := newChange(st, fdeChangePassphraseChangeKind, "Change passphrase", []*state.TaskSet{ts}, nil)

	st.EnsureBefore(0)

	return AsyncResponse(nil, chg.ID())
}