File: preinstall_sb_test.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 (522 lines) | stat: -rw-r--r-- 18,190 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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
// -*- Mode: Go; indent-tabs-mode: t -*-
//go:build !nosecboot

/*
 * 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 secboot_test

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"os"
	"path/filepath"

	"github.com/canonical/go-tpm2"
	sb_efi "github.com/snapcore/secboot/efi"
	sb_preinstall "github.com/snapcore/secboot/efi/preinstall"
	. "gopkg.in/check.v1"

	"github.com/snapcore/snapd/logger"
	"github.com/snapcore/snapd/secboot"
	"github.com/snapcore/snapd/testutil"
)

type preinstallSuite struct {
	testutil.BaseTest
}

var _ = Suite(&preinstallSuite{})

func (s *preinstallSuite) SetUpTest(c *C) {
}

// CompoundPreinstallCheckError implements sb_preinstall.CompoundError and is
// used to mimic compound errors that would normally be returned by secboot.
type CompoundPreinstallCheckError struct {
	Errs []error
}

func (e *CompoundPreinstallCheckError) Error() string {
	return "n/a"
}

func (e *CompoundPreinstallCheckError) Unwrap() []error {
	return e.Errs
}

func (s *preinstallSuite) TestConvertPreinstallCheckErrorActions(c *C) {
	testCases := []struct {
		actions  []sb_preinstall.Action
		expected []string
	}{
		{nil, nil},
		{[]sb_preinstall.Action{}, []string{}},
		{[]sb_preinstall.Action{sb_preinstall.ActionReboot, sb_preinstall.ActionShutdown}, []string{"reboot", "shutdown"}},
	}

	for _, tc := range testCases {
		convertedActions := secboot.ConvertPreinstallCheckErrorActions(tc.actions)
		c.Check(convertedActions, DeepEquals, tc.expected)
	}
}

func (s *preinstallSuite) TestConvertPreinstallCheckErrorType(c *C) {
	kindAndActionsErr := sb_preinstall.NewWithKindAndActionsError(
		sb_preinstall.ErrorKindTPMHierarchiesOwned,
		sb_preinstall.TPM2OwnedHierarchiesError{WithAuthValue: tpm2.HandleList{tpm2.HandleLockout}, WithAuthPolicy: tpm2.HandleList{tpm2.HandleOwner}},
		[]sb_preinstall.Action{sb_preinstall.ActionRebootToFWSettings},
		errors.New("error with TPM2 device: one or more of the TPM hierarchies is already owned"),
	)

	var errorDetails secboot.PreinstallErrorDetails
	c.Assert(func() { errorDetails = secboot.ConvertPreinstallCheckErrorType(nil) }, PanicMatches, "runtime error: invalid memory address or nil pointer dereference")
	errorDetails = secboot.ConvertPreinstallCheckErrorType(kindAndActionsErr)
	c.Assert(errorDetails, DeepEquals, secboot.PreinstallErrorDetails{
		Kind:    "tpm-hierarchies-owned",
		Message: "error with TPM2 device: one or more of the TPM hierarchies is already owned",
		Args: map[string]json.RawMessage{
			"with-auth-value":  json.RawMessage(`[1073741834]`),
			"with-auth-policy": json.RawMessage(`[1073741825]`),
		},
		Actions: []string{"reboot-to-fw-settings"},
	})
}

func (s *preinstallSuite) TestUnwrapPreinstallCheckErrorCompound(c *C) {
	compoundError := &CompoundPreinstallCheckError{
		[]error{
			sb_preinstall.NewWithKindAndActionsError(
				sb_preinstall.ErrorKindTPMHierarchiesOwned,
				sb_preinstall.TPM2OwnedHierarchiesError{WithAuthValue: tpm2.HandleList{tpm2.HandleLockout}},
				[]sb_preinstall.Action{sb_preinstall.ActionRebootToFWSettings},
				errors.New("error with TPM2 device: one or more of the TPM hierarchies is already owned"),
			),
			sb_preinstall.NewWithKindAndActionsError(
				sb_preinstall.ErrorKindTPMDeviceLockout,
				&sb_preinstall.TPMDeviceLockoutArgs{IntervalDuration: 7200000000000, TotalDuration: 230400000000000},
				[]sb_preinstall.Action{sb_preinstall.ActionRebootToFWSettings},
				errors.New("error with TPM2 device: TPM is in DA lockout mode"),
			),
			sb_preinstall.NewWithKindAndActionsError(
				sb_preinstall.ErrorKindNone,
				nil,
				nil,
				nil,
			),
		},
	}

	errorDetails, err := secboot.UnwrapPreinstallCheckError(compoundError)
	c.Assert(err, IsNil)
	c.Assert(errorDetails, DeepEquals, []secboot.PreinstallErrorDetails{
		{
			Kind:    "tpm-hierarchies-owned",
			Message: "error with TPM2 device: one or more of the TPM hierarchies is already owned",
			Args: map[string]json.RawMessage{
				"with-auth-value":  json.RawMessage(`[1073741834]`),
				"with-auth-policy": json.RawMessage(`null`),
			},
			Actions: []string{"reboot-to-fw-settings"},
		},
		{
			Kind:    "tpm-device-lockout",
			Message: "error with TPM2 device: TPM is in DA lockout mode",
			Args: map[string]json.RawMessage{
				"interval-duration": json.RawMessage(`7200000000000`),
				"total-duration":    json.RawMessage(`230400000000000`),
			},
			Actions: []string{"reboot-to-fw-settings"},
		},
		{
			Kind:    "",
			Message: "<nil>",
			Args:    nil,
			Actions: nil,
		},
	})

	jsn, err := json.MarshalIndent(errorDetails, "", "  ")
	c.Assert(err, IsNil)
	const expectedJson = `[
  {
    "kind": "tpm-hierarchies-owned",
    "message": "error with TPM2 device: one or more of the TPM hierarchies is already owned",
    "args": {
      "with-auth-policy": null,
      "with-auth-value": [
        1073741834
      ]
    },
    "actions": [
      "reboot-to-fw-settings"
    ]
  },
  {
    "kind": "tpm-device-lockout",
    "message": "error with TPM2 device: TPM is in DA lockout mode",
    "args": {
      "interval-duration": 7200000000000,
      "total-duration": 230400000000000
    },
    "actions": [
      "reboot-to-fw-settings"
    ]
  },
  {
    "kind": "",
    "message": "\u003cnil\u003e"
  }
]`
	c.Assert(string(jsn), Equals, expectedJson)
}

func (s *preinstallSuite) TestUnwrapPreinstallCheckErrorFailCompoundUnexpectedType(c *C) {
	compoundError := &CompoundPreinstallCheckError{
		[]error{
			sb_preinstall.NewWithKindAndActionsError(
				sb_preinstall.ErrorKindTPMHierarchiesOwned,
				sb_preinstall.TPM2OwnedHierarchiesError{WithAuthValue: tpm2.HandleList{tpm2.HandleLockout}},
				[]sb_preinstall.Action{sb_preinstall.ActionRebootToFWSettings},
				errors.New("error with TPM2 device: one or more of the TPM hierarchies is already owned"),
			),
			sb_preinstall.ErrInsufficientDMAProtection,
		},
	}

	errorDetails, err := secboot.UnwrapPreinstallCheckError(compoundError)
	c.Assert(err, ErrorMatches, `cannot unwrap error of unexpected type \*errors\.errorString \(the platform firmware indicates that DMA protections are insufficient\)`)
	c.Assert(errorDetails, IsNil)
}

func (s *preinstallSuite) TestUnwrapPreinstallCheckErrorFailCompoundWrapsNil(c *C) {
	compoundError := &CompoundPreinstallCheckError{nil}

	errorDetails, err := secboot.UnwrapPreinstallCheckError(compoundError)
	c.Assert(err, ErrorMatches, "compound error does not wrap any error")
	c.Assert(errorDetails, IsNil)
}

func (s *preinstallSuite) TestUnwrapPreinstallCheckErrorSingle(c *C) {
	singleError := sb_preinstall.NewWithKindAndActionsError(
		sb_preinstall.ErrorKindTPMDeviceDisabled,
		nil,
		[]sb_preinstall.Action{sb_preinstall.ActionRebootToFWSettings},
		errors.New("error with TPM2 device: TPM2 device is present but is currently disabled by the platform firmware"),
	)

	errorDetails, err := secboot.UnwrapPreinstallCheckError(singleError)
	c.Assert(err, IsNil)
	c.Assert(errorDetails, DeepEquals, []secboot.PreinstallErrorDetails{
		{
			Kind:    "tpm-device-disabled",
			Message: "error with TPM2 device: TPM2 device is present but is currently disabled by the platform firmware",
			Actions: []string{"reboot-to-fw-settings"},
		},
	})

	jsn, err := json.MarshalIndent(errorDetails, "", "  ")
	c.Assert(err, IsNil)
	const expectedJson = `[
  {
    "kind": "tpm-device-disabled",
    "message": "error with TPM2 device: TPM2 device is present but is currently disabled by the platform firmware",
    "actions": [
      "reboot-to-fw-settings"
    ]
  }
]`
	c.Assert(string(jsn), Equals, expectedJson)
}

func (s *preinstallSuite) TestUnwrapPreinstallCheckErrorFailSingleUnexpectedType(c *C) {
	errorDetails, err := secboot.UnwrapPreinstallCheckError(sb_preinstall.ErrInsufficientDMAProtection)
	c.Assert(err, ErrorMatches, `cannot unwrap error of unexpected type \*errors\.errorString \(the platform firmware indicates that DMA protections are insufficient\)`)
	c.Assert(errorDetails, IsNil)
}

func (s *preinstallSuite) testPreinstallCheckConfig(c *C, isVM, permitVM bool) {
	cmdExit := `exit 1`
	if isVM {
		cmdExit = `exit 0`
	}
	systemdCmd := testutil.MockCommand(c, "systemd-detect-virt", cmdExit)
	s.AddCleanup(systemdCmd.Restore)

	restore := secboot.MockSbPreinstallNewRunChecksContext(
		func(initialFlags sb_preinstall.CheckFlags, loadedImages []sb_efi.Image, profileOpts sb_preinstall.PCRProfileOptionsFlags) *sb_preinstall.RunChecksContext {
			if permitVM {
				c.Assert(initialFlags, Equals, sb_preinstall.PermitVirtualMachine|sb_preinstall.PermitVARSuppliedDrivers)
			} else {
				c.Assert(initialFlags, Equals, sb_preinstall.PermitVARSuppliedDrivers)
			}
			c.Assert(profileOpts, Equals, sb_preinstall.PCRProfileOptionsDefault)
			c.Assert(loadedImages, IsNil)

			return nil
		})
	s.AddCleanup(restore)

	restore = secboot.MockSbPreinstallRun(
		func(checkCtx *sb_preinstall.RunChecksContext, ctx context.Context, action sb_preinstall.Action, args ...any) (*sb_preinstall.CheckResult, error) {
			c.Assert(checkCtx, IsNil)
			c.Assert(ctx, NotNil)
			c.Assert(action, Equals, sb_preinstall.ActionNone)
			c.Assert(args, IsNil)

			return &sb_preinstall.CheckResult{}, nil
		})
	s.AddCleanup(restore)

	checkContext, errorDetails, err := secboot.PreinstallCheck(context.Background(), nil)
	c.Assert(checkContext, NotNil)
	c.Assert(err, IsNil)
	c.Assert(errorDetails, IsNil)
}

func (s *preinstallSuite) TestPreinstallCheckConfig(c *C) {
	testCases := []struct {
		isVM     bool
		permitVM bool
	}{
		{false, false}, // default config
		{true, true},   // modify default config to permit VM
	}

	for _, tc := range testCases {
		s.testPreinstallCheckConfig(c, tc.isVM, tc.permitVM)
	}
}

// testPreinstallCheckAndAction is a helper to test PreinstallCheck and PreinstallCheckAction
func (s *preinstallSuite) testPreinstallCheckAndAction(c *C, checkAction *secboot.PreinstallAction, detectErrors, failUnwrap bool) {
	bootImagePaths := []string{
		"/cdrom/EFI/boot/bootXXX.efi",
		"/cdrom/EFI/boot/grubXXX.efi",
		"/cdrom/casper/vmlinuz",
	}

	systemdCmd := testutil.MockCommand(c, "systemd-detect-virt", "exit 1")
	s.AddCleanup(systemdCmd.Restore)

	var expectedRunChecksContext *sb_preinstall.RunChecksContext

	restore := secboot.MockSbPreinstallNewRunChecksContext(
		func(initialFlags sb_preinstall.CheckFlags, loadedImages []sb_efi.Image, profileOpts sb_preinstall.PCRProfileOptionsFlags) *sb_preinstall.RunChecksContext {
			c.Assert(checkAction, IsNil)
			c.Assert(initialFlags, Equals, sb_preinstall.PermitVARSuppliedDrivers)
			c.Assert(profileOpts, Equals, sb_preinstall.PCRProfileOptionsDefault)
			c.Assert(loadedImages, HasLen, len(bootImagePaths))
			for i, image := range loadedImages {
				c.Check(image.String(), Equals, bootImagePaths[i])
			}
			return expectedRunChecksContext
		})
	s.AddCleanup(restore)

	var expectedAction sb_preinstall.Action

	restore = secboot.MockSbPreinstallRun(
		func(checkCtx *sb_preinstall.RunChecksContext, ctx context.Context, action sb_preinstall.Action, args ...any) (*sb_preinstall.CheckResult, error) {
			c.Assert(checkCtx, Equals, expectedRunChecksContext)
			c.Assert(checkCtx.Errors(), IsNil)
			c.Assert(checkCtx.Result(), IsNil)
			c.Assert(ctx, NotNil)
			c.Assert(action, Equals, expectedAction)
			c.Assert(args, IsNil)

			if detectErrors {
				return nil, &CompoundPreinstallCheckError{
					[]error{
						sb_preinstall.NewWithKindAndActionsError(
							sb_preinstall.ErrorKindTPMHierarchiesOwned,
							sb_preinstall.TPM2OwnedHierarchiesError{WithAuthValue: tpm2.HandleList{tpm2.HandleLockout},
								WithAuthPolicy: tpm2.HandleList{tpm2.HandleOwner}},
							[]sb_preinstall.Action{sb_preinstall.ActionRebootToFWSettings},
							errors.New("error with TPM2 device: one or more of the TPM hierarchies is already owned"),
						),
						sb_preinstall.NewWithKindAndActionsError(
							sb_preinstall.ErrorKindTPMDeviceLockout,
							&sb_preinstall.TPMDeviceLockoutArgs{IntervalDuration: 7200000000000, TotalDuration: 230400000000000},
							[]sb_preinstall.Action{sb_preinstall.ActionRebootToFWSettings},
							errors.New("error with TPM2 device: TPM is in DA lockout mode"),
						),
					},
				}
				// if we test with an action then only apply failure when called from PreinstallCheckAction
				// to ensure
			} else if failUnwrap {
				return nil, sb_preinstall.ErrInsufficientDMAProtection
			} else {
				return &sb_preinstall.CheckResult{
					Warnings: &CompoundPreinstallCheckError{
						[]error{
							errors.New("warning 1"),
							errors.New("warning 2"),
						},
					},
				}, nil
			}
		})
	s.AddCleanup(restore)

	logbuf, restore := logger.MockLogger()
	s.AddCleanup(restore)

	var (
		checkContext *secboot.PreinstallCheckContext
		errorDetails []secboot.PreinstallErrorDetails
		err          error
	)

	expectedRunChecksContext = &sb_preinstall.RunChecksContext{}
	if checkAction == nil {
		// test PreinstallCheck
		expectedAction = sb_preinstall.ActionNone
		checkContext, errorDetails, err = secboot.PreinstallCheck(context.Background(), bootImagePaths)
		if failUnwrap {
			c.Assert(checkContext, IsNil)
		} else {
			c.Assert(secboot.ExtractSbRunChecksContext(checkContext), Equals, expectedRunChecksContext)
		}
	} else {
		// test PreinstallCheckAction
		checkContext = secboot.NewPreinstallChecksContext(expectedRunChecksContext)
		expectedAction = sb_preinstall.Action(checkAction.Action)
		errorDetails, err = checkContext.PreinstallCheckAction(context.Background(), checkAction)
	}

	// errorDetails and err should behave the same for PreinstallCheck and PreinstallCheckAction
	if detectErrors {
		c.Assert(err, IsNil)
		c.Assert(logbuf.String(), Equals, "")
		c.Assert(errorDetails, DeepEquals, []secboot.PreinstallErrorDetails{
			{
				Kind:    "tpm-hierarchies-owned",
				Message: "error with TPM2 device: one or more of the TPM hierarchies is already owned",
				Args: map[string]json.RawMessage{
					"with-auth-value":  json.RawMessage(`[1073741834]`),
					"with-auth-policy": json.RawMessage(`[1073741825]`),
				},
				Actions: []string{"reboot-to-fw-settings"},
			},
			{
				Kind:    "tpm-device-lockout",
				Message: "error with TPM2 device: TPM is in DA lockout mode",
				Args: map[string]json.RawMessage{
					"interval-duration": json.RawMessage(`7200000000000`),
					"total-duration":    json.RawMessage(`230400000000000`),
				},
				Actions: []string{"reboot-to-fw-settings"},
			},
		})
	} else if failUnwrap {
		c.Assert(err, ErrorMatches, `cannot unwrap error of unexpected type \*errors\.errorString \(the platform firmware indicates that DMA protections are insufficient\)`)
		c.Assert(errorDetails, IsNil)
	} else {
		c.Assert(err, IsNil)
		c.Assert(errorDetails, IsNil)
		c.Assert(logbuf.String(), testutil.Contains, "preinstall check warning: warning 1")
		c.Assert(logbuf.String(), testutil.Contains, "preinstall check warning: warning 2")
	}
}

func (s *preinstallSuite) TestPreinstallCheckWithWarningsAndErrors(c *C) {
	detectErrors := false // warnings and no errors
	s.testPreinstallCheckAndAction(c, nil, detectErrors, false)

	detectErrors = true // errors and no warnings
	s.testPreinstallCheckAndAction(c, nil, detectErrors, false)
}

func (s *preinstallSuite) TestPreinstallCheckFailUnwrap(c *C) {
	failUnwrap := true
	s.testPreinstallCheckAndAction(c, nil, false, failUnwrap)
}

func (s *preinstallSuite) TestPreinstallCheckActionWithWarningsAndErrors(c *C) {
	action := &secboot.PreinstallAction{
		Action: string(sb_preinstall.ActionReboot),
	}
	detectErrors := false // warnings and no errors
	s.testPreinstallCheckAndAction(c, action, detectErrors, false)

	detectErrors = true // errors and no warnings
	s.testPreinstallCheckAndAction(c, action, detectErrors, false)
}

func (s *preinstallSuite) TestPreinstallActionFailUnwrap(c *C) {
	action := &secboot.PreinstallAction{
		Action: string(sb_preinstall.ActionReboot),
	}
	failUnwrap := true
	s.testPreinstallCheckAndAction(c, action, false, failUnwrap)
}

func (s *preinstallSuite) TestSaveCheckResultErrorContextNotAvailable(c *C) {
	checkContext := secboot.NewPreinstallChecksContext(nil)
	err := checkContext.SaveCheckResult("preinstall")
	c.Assert(err, ErrorMatches, "preinstall check context unavailable")
}

func (s *preinstallSuite) TestSaveCheckResultErrorResultNotAvailable(c *C) {
	checkContext := secboot.NewPreinstallChecksContext(&sb_preinstall.RunChecksContext{})
	err := checkContext.SaveCheckResult("preinstall")
	c.Assert(err, ErrorMatches, "preinstall check result unavailable: 0 unresolved errors")
}

func (s *preinstallSuite) TestSave(c *C) {
	filename := filepath.Join(c.MkDir(), "/run/mnt/ubuntu-save/device/fde/preinstall")
	expectedCheckResult := secboot.PreinstallCheckResult{
		Result: &sb_preinstall.CheckResult{
			PCRAlg: tpm2.HashAlgorithmSHA512,
			Flags:  sb_preinstall.NoPlatformConfigProfileSupport | sb_preinstall.NoDriversAndAppsProfileSupport,
		},
		PCRProfileOpts: sb_preinstall.PCRProfileOptionsDefault,
	}
	expectedData :=
		`{
  "result": {
    "pcr-alg": "sha512",
    "used-secure-boot-cas": null,
    "flags": [
      "no-platform-config-profile-support",
      "no-drivers-and-apps-profile-support"
    ]
  },
  "pcr-profile-opts": 0
}`

	err := secboot.Save(&expectedCheckResult, filename)
	c.Assert(err, IsNil)

	data, err := os.ReadFile(filename)
	c.Assert(err, IsNil)

	var readable bytes.Buffer
	err = json.Indent(&readable, data, "", "  ")
	c.Assert(err, IsNil)
	c.Assert(readable.String(), Equals, expectedData)

	var checkResult secboot.PreinstallCheckResult
	err = json.Unmarshal(data, &checkResult)
	c.Assert(err, IsNil)

	c.Assert(checkResult, DeepEquals, expectedCheckResult)
}