github.com/stolowski/snapd@v0.0.0-20210407085831-115137ce5a22/bootloader/bootloader.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2014-2020 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package bootloader
    21  
    22  import (
    23  	"errors"
    24  	"fmt"
    25  	"os"
    26  	"path/filepath"
    27  
    28  	"github.com/snapcore/snapd/bootloader/assets"
    29  	"github.com/snapcore/snapd/dirs"
    30  	"github.com/snapcore/snapd/osutil"
    31  	"github.com/snapcore/snapd/snap"
    32  )
    33  
    34  var (
    35  	// ErrBootloader is returned if the bootloader can not be determined.
    36  	ErrBootloader = errors.New("cannot determine bootloader")
    37  
    38  	// ErrNoTryKernelRef is returned if the bootloader finds no enabled
    39  	// try-kernel.
    40  	ErrNoTryKernelRef = errors.New("no try-kernel referenced")
    41  )
    42  
    43  // Role indicates whether the bootloader is used for recovery or run mode.
    44  type Role string
    45  
    46  const (
    47  	// RoleSole applies to the sole bootloader used by UC16/18.
    48  	RoleSole Role = ""
    49  	// RoleRunMode applies to the run mode booloader.
    50  	RoleRunMode Role = "run-mode"
    51  	// RoleRecovery apllies to the recovery bootloader.
    52  	RoleRecovery Role = "recovery"
    53  )
    54  
    55  // Options carries bootloader options.
    56  type Options struct {
    57  	// PrepareImageTime indicates whether the booloader is being
    58  	// used at prepare-image time, that means not on a runtime
    59  	// system.
    60  	PrepareImageTime bool
    61  
    62  	// Role specifies to use the bootloader for the given role.
    63  	Role Role
    64  
    65  	// NoSlashBoot indicates to use the native layout of the
    66  	// bootloader partition and not the /boot mount.
    67  	// It applies only for RoleRunMode.
    68  	// It is implied and ignored for RoleRecovery.
    69  	// It is an error to set it for RoleSole.
    70  	NoSlashBoot bool
    71  }
    72  
    73  func (o *Options) validate() error {
    74  	if o == nil {
    75  		return nil
    76  	}
    77  	if o.NoSlashBoot && o.Role == RoleSole {
    78  		return fmt.Errorf("internal error: bootloader.RoleSole doesn't expect NoSlashBoot set")
    79  	}
    80  	if o.PrepareImageTime && o.Role == RoleRunMode {
    81  		return fmt.Errorf("internal error: cannot use run mode bootloader at prepare-image time")
    82  	}
    83  	return nil
    84  }
    85  
    86  // Bootloader provides an interface to interact with the system
    87  // bootloader.
    88  type Bootloader interface {
    89  	// Return the value of the specified bootloader variable.
    90  	GetBootVars(names ...string) (map[string]string, error)
    91  
    92  	// Set the value of the specified bootloader variable.
    93  	SetBootVars(values map[string]string) error
    94  
    95  	// Name returns the bootloader name.
    96  	Name() string
    97  
    98  	// Present returns whether the bootloader is currently present on the
    99  	// system - in other words whether this bootloader has been installed to the
   100  	// current system. Implementations should only return non-nil error if they
   101  	// can positively identify that the bootloader is installed, but there is
   102  	// actually an error with the installation.
   103  	Present() (bool, error)
   104  
   105  	// InstallBootConfig will try to install the boot config in the
   106  	// given gadgetDir to rootdir.
   107  	InstallBootConfig(gadgetDir string, opts *Options) error
   108  
   109  	// ExtractKernelAssets extracts kernel assets from the given kernel snap.
   110  	ExtractKernelAssets(s snap.PlaceInfo, snapf snap.Container) error
   111  
   112  	// RemoveKernelAssets removes the assets for the given kernel snap.
   113  	RemoveKernelAssets(s snap.PlaceInfo) error
   114  }
   115  
   116  type RecoveryAwareBootloader interface {
   117  	Bootloader
   118  	SetRecoverySystemEnv(recoverySystemDir string, values map[string]string) error
   119  	GetRecoverySystemEnv(recoverySystemDir string, key string) (string, error)
   120  }
   121  
   122  type ExtractedRecoveryKernelImageBootloader interface {
   123  	Bootloader
   124  	ExtractRecoveryKernelAssets(recoverySystemDir string, s snap.PlaceInfo, snapf snap.Container) error
   125  }
   126  
   127  // ExtractedRunKernelImageBootloader is a Bootloader that also supports specific
   128  // methods needed to setup booting from an extracted kernel, which is needed to
   129  // implement encryption and/or secure boot. Prototypical implementation is UC20
   130  // grub implementation with FDE.
   131  type ExtractedRunKernelImageBootloader interface {
   132  	Bootloader
   133  
   134  	// EnableKernel enables the specified kernel on ubuntu-boot to be used
   135  	// during normal boots. The specified kernel should already have been
   136  	// extracted. This is usually implemented with a "kernel.efi" symlink
   137  	// pointing to the extracted kernel image.
   138  	EnableKernel(snap.PlaceInfo) error
   139  
   140  	// EnableTryKernel enables the specified kernel on ubuntu-boot to be
   141  	// tried by the bootloader on a reboot, to be used in conjunction with
   142  	// setting "kernel_status" to "try". The specified kernel should already
   143  	// have been extracted. This is usually implemented with a
   144  	// "try-kernel.efi" symlink pointing to the extracted kernel image.
   145  	EnableTryKernel(snap.PlaceInfo) error
   146  
   147  	// Kernel returns the current enabled kernel on the bootloader, not
   148  	// necessarily the kernel that was used to boot the current session, but the
   149  	// kernel that is enabled to boot on "normal" boots.
   150  	// If error is not nil, the first argument shall be non-nil.
   151  	Kernel() (snap.PlaceInfo, error)
   152  
   153  	// TryKernel returns the current enabled try-kernel on the bootloader, if
   154  	// there is no such enabled try-kernel, then ErrNoTryKernelRef is returned.
   155  	// If error is not nil, the first argument shall be non-nil.
   156  	TryKernel() (snap.PlaceInfo, error)
   157  
   158  	// DisableTryKernel disables the current enabled try-kernel on the
   159  	// bootloader, if it exists. It does not need to return an error if the
   160  	// enabled try-kernel does not exist or is in an inconsistent state before
   161  	// disabling it, errors should only be returned when the implementation
   162  	// fails to disable the try-kernel.
   163  	DisableTryKernel() error
   164  }
   165  
   166  // TrustedAssetsBootloader has boot assets that take part in the secure boot
   167  // process and need to be tracked, while other boot assets (typically boot
   168  // config) are managed by snapd.
   169  type TrustedAssetsBootloader interface {
   170  	Bootloader
   171  
   172  	// ManagedAssets returns a list of boot assets managed by the bootloader
   173  	// in the boot filesystem. Does not require rootdir to be set.
   174  	ManagedAssets() []string
   175  	// UpdateBootConfig attempts to update the boot config assets used by
   176  	// the bootloader. Returns true when assets were updated.
   177  	UpdateBootConfig() (bool, error)
   178  	// CommandLine returns the kernel command line composed of mode and
   179  	// system arguments, built-in bootloader specific static arguments
   180  	// corresponding to the on-disk boot asset edition, followed by any
   181  	// extra arguments. The command line may be different when using a
   182  	// recovery bootloader.
   183  	CommandLine(modeArg, systemArg, extraArgs string) (string, error)
   184  	// CandidateCommandLine is similar to CommandLine, but uses the current
   185  	// edition of managed built-in boot assets as reference.
   186  	CandidateCommandLine(modeArg, systemArg, extraArgs string) (string, error)
   187  
   188  	// TrustedAssets returns the list of relative paths to assets inside the
   189  	// bootloader's rootdir that are measured in the boot process in the
   190  	// order of loading during the boot. Does not require rootdir to be set.
   191  	TrustedAssets() ([]string, error)
   192  
   193  	// RecoveryBootChain returns the load chain for recovery modes.
   194  	// It should be called on a RoleRecovery bootloader.
   195  	RecoveryBootChain(kernelPath string) ([]BootFile, error)
   196  
   197  	// BootChain returns the load chain for run mode.
   198  	// It should be called on a RoleRecovery bootloader passing the
   199  	// RoleRunMode bootloader.
   200  	BootChain(runBl Bootloader, kernelPath string) ([]BootFile, error)
   201  }
   202  
   203  func genericInstallBootConfig(gadgetFile, systemFile string) error {
   204  	if err := os.MkdirAll(filepath.Dir(systemFile), 0755); err != nil {
   205  		return err
   206  	}
   207  	return osutil.CopyFile(gadgetFile, systemFile, osutil.CopyFlagOverwrite)
   208  }
   209  
   210  func genericSetBootConfigFromAsset(systemFile, assetName string) error {
   211  	bootConfig := assets.Internal(assetName)
   212  	if bootConfig == nil {
   213  		return fmt.Errorf("internal error: no boot asset for %q", assetName)
   214  	}
   215  	if err := os.MkdirAll(filepath.Dir(systemFile), 0755); err != nil {
   216  		return err
   217  	}
   218  	return osutil.AtomicWriteFile(systemFile, bootConfig, 0644, 0)
   219  }
   220  
   221  func genericUpdateBootConfigFromAssets(systemFile string, assetName string) (updated bool, err error) {
   222  	currentBootConfigEdition, err := editionFromDiskConfigAsset(systemFile)
   223  	if err != nil && err != errNoEdition {
   224  		return false, err
   225  	}
   226  	if err == errNoEdition {
   227  		return false, nil
   228  	}
   229  	newBootConfig := assets.Internal(assetName)
   230  	if len(newBootConfig) == 0 {
   231  		return false, fmt.Errorf("no boot config asset with name %q", assetName)
   232  	}
   233  	bc, err := configAssetFrom(newBootConfig)
   234  	if err != nil {
   235  		return false, err
   236  	}
   237  	if bc.Edition() <= currentBootConfigEdition {
   238  		// edition of the candidate boot config is lower than or equal
   239  		// to one currently installed
   240  		return false, nil
   241  	}
   242  	if err := osutil.AtomicWriteFile(systemFile, bc.Raw(), 0644, 0); err != nil {
   243  		return false, err
   244  	}
   245  	return true, nil
   246  }
   247  
   248  // InstallBootConfig installs the bootloader config from the gadget
   249  // snap dir into the right place.
   250  func InstallBootConfig(gadgetDir, rootDir string, opts *Options) error {
   251  	if err := opts.validate(); err != nil {
   252  		return err
   253  	}
   254  	bl, err := ForGadget(gadgetDir, rootDir, opts)
   255  	if err != nil {
   256  		return fmt.Errorf("cannot find boot config in %q", gadgetDir)
   257  	}
   258  	return bl.InstallBootConfig(gadgetDir, opts)
   259  }
   260  
   261  type bootloaderNewFunc func(rootdir string, opts *Options) Bootloader
   262  
   263  var (
   264  	//  bootloaders list all possible bootloaders by their constructor
   265  	//  function.
   266  	bootloaders = []bootloaderNewFunc{
   267  		newUboot,
   268  		newGrub,
   269  		newAndroidBoot,
   270  		newLk,
   271  	}
   272  )
   273  
   274  var (
   275  	forcedBootloader Bootloader
   276  	forcedError      error
   277  )
   278  
   279  // Find returns the bootloader for the system
   280  // or an error if no bootloader is found.
   281  //
   282  // The rootdir option is useful for image creation operations. It
   283  // can also be used to find the recovery bootloader, e.g. on uc20:
   284  //   bootloader.Find("/run/mnt/ubuntu-seed")
   285  func Find(rootdir string, opts *Options) (Bootloader, error) {
   286  	if err := opts.validate(); err != nil {
   287  		return nil, err
   288  	}
   289  	if forcedBootloader != nil || forcedError != nil {
   290  		return forcedBootloader, forcedError
   291  	}
   292  
   293  	if rootdir == "" {
   294  		rootdir = dirs.GlobalRootDir
   295  	}
   296  	if opts == nil {
   297  		opts = &Options{}
   298  	}
   299  
   300  	// note that the order of this is not deterministic
   301  	for _, blNew := range bootloaders {
   302  		bl := blNew(rootdir, opts)
   303  		present, err := bl.Present()
   304  		if err != nil {
   305  			return nil, fmt.Errorf("bootloader %q found but not usable: %v", bl.Name(), err)
   306  		}
   307  		if present {
   308  			return bl, nil
   309  		}
   310  	}
   311  	// no, weeeee
   312  	return nil, ErrBootloader
   313  }
   314  
   315  // Force can be used to force Find to always find the specified bootloader; use
   316  // nil to reset to normal lookup.
   317  func Force(booloader Bootloader) {
   318  	forcedBootloader = booloader
   319  	forcedError = nil
   320  }
   321  
   322  // ForceError can be used to force Find to return an error; use nil to
   323  // reset to normal lookup.
   324  func ForceError(err error) {
   325  	forcedBootloader = nil
   326  	forcedError = err
   327  }
   328  
   329  func extractKernelAssetsToBootDir(dstDir string, snapf snap.Container, assets []string) error {
   330  	// now do the kernel specific bits
   331  	if err := os.MkdirAll(dstDir, 0755); err != nil {
   332  		return err
   333  	}
   334  	dir, err := os.Open(dstDir)
   335  	if err != nil {
   336  		return err
   337  	}
   338  	defer dir.Close()
   339  
   340  	for _, src := range assets {
   341  		if err := snapf.Unpack(src, dstDir); err != nil {
   342  			return err
   343  		}
   344  		if err := dir.Sync(); err != nil {
   345  			return err
   346  		}
   347  	}
   348  	return nil
   349  }
   350  
   351  func removeKernelAssetsFromBootDir(bootDir string, s snap.PlaceInfo) error {
   352  	// remove the kernel blob
   353  	blobName := s.Filename()
   354  	dstDir := filepath.Join(bootDir, blobName)
   355  	if err := os.RemoveAll(dstDir); err != nil {
   356  		return err
   357  	}
   358  
   359  	return nil
   360  }
   361  
   362  // ForGadget returns a bootloader matching a given gadget by inspecting the
   363  // contents of gadget directory or an error if no matching bootloader is found.
   364  func ForGadget(gadgetDir, rootDir string, opts *Options) (Bootloader, error) {
   365  	if err := opts.validate(); err != nil {
   366  		return nil, err
   367  	}
   368  	if forcedBootloader != nil || forcedError != nil {
   369  		return forcedBootloader, forcedError
   370  	}
   371  	for _, blNew := range bootloaders {
   372  		bl := blNew(rootDir, opts)
   373  		markerConf := filepath.Join(gadgetDir, bl.Name()+".conf")
   374  		// do we have a marker file?
   375  		if osutil.FileExists(markerConf) {
   376  			return bl, nil
   377  		}
   378  	}
   379  	return nil, ErrBootloader
   380  }
   381  
   382  // BootFile represents each file in the chains of trusted assets and
   383  // kernels used in the boot process. For example a boot file can be an
   384  // EFI binary or a snap file containing an EFI binary.
   385  type BootFile struct {
   386  	// Path is the path to the file in the filesystem or, if Snap
   387  	// is set, the relative path inside the snap file.
   388  	Path string
   389  	// Snap contains the path to the snap file if a snap file is used.
   390  	Snap string
   391  	// Role is set to the role of the bootloader this boot file
   392  	// originates from.
   393  	Role Role
   394  }
   395  
   396  func NewBootFile(snap, path string, role Role) BootFile {
   397  	return BootFile{
   398  		Snap: snap,
   399  		Path: path,
   400  		Role: role,
   401  	}
   402  }
   403  
   404  // WithPath returns a copy of the BootFile with path updated to the
   405  // specified value.
   406  func (b BootFile) WithPath(path string) BootFile {
   407  	b.Path = path
   408  	return b
   409  }