/
gadget.go
1933 lines (1717 loc) · 61.6 KB
/
gadget.go
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2019-2020 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 gadget
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"math"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"gopkg.in/yaml.v2"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/gadget/edition"
"github.com/snapcore/snapd/gadget/quantity"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/metautil"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/osutil/disks"
"github.com/snapcore/snapd/osutil/kcmdline"
"github.com/snapcore/snapd/secboot"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/snap/naming"
"github.com/snapcore/snapd/snap/snapfile"
"github.com/snapcore/snapd/strutil"
)
const (
// schemaMBR identifies a Master Boot Record partitioning schema, or an
// MBR like role
schemaMBR = "mbr"
// schemaGPT identifies a GUID Partition Table partitioning schema
schemaGPT = "gpt"
SystemBoot = "system-boot"
SystemData = "system-data"
SystemSeed = "system-seed"
SystemSeedNull = "system-seed-null"
SystemSave = "system-save"
// extracted kernels for all uc systems
bootImage = "system-boot-image"
// extracted kernels for recovery kernels for uc20 specifically
seedBootImage = "system-seed-image"
// bootloader specific partition which stores bootloader environment vars
// for purposes of booting normal run mode on uc20 and all modes on
// uc16 and uc18
bootSelect = "system-boot-select"
// bootloader specific partition which stores bootloader environment vars
// for purposes of booting recovery systems on uc20, i.e. recover or install
seedBootSelect = "system-seed-select"
// implicitSystemDataLabel is the implicit filesystem label of structure
// of system-data role
implicitSystemDataLabel = "writable"
// UC20 filesystem labels for roles
ubuntuBootLabel = "ubuntu-boot"
ubuntuSeedLabel = "ubuntu-seed"
ubuntuDataLabel = "ubuntu-data"
ubuntuSaveLabel = "ubuntu-save"
// only supported for legacy reasons
legacyBootImage = "bootimg"
legacyBootSelect = "bootselect"
// UnboundedStructureOffset is the maximum effective partition offset
// that we can handle.
UnboundedStructureOffset = quantity.Offset(math.MaxUint64)
// UnboundedStructureSize is the maximum effective partition size
// that we can handle.
UnboundedStructureSize = quantity.Size(math.MaxUint64)
)
var (
validVolumeName = regexp.MustCompile("^[a-zA-Z0-9][a-zA-Z0-9-]+$")
validTypeID = regexp.MustCompile("^[0-9A-F]{2}$")
validGUUID = regexp.MustCompile("^(?i)[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$")
)
type KernelCmdline struct {
// Allow is the list of allowed parameters for the system.kernel.cmdline-append
// system option
Allow []kcmdline.ArgumentPattern `yaml:"allow"`
// Append are kernel parameters added by the gadget
Append []kcmdline.Argument `yaml:"append"`
// Remove are patterns to be removed from default command line
Remove []kcmdline.ArgumentPattern `yaml:"remove"`
}
type Info struct {
Volumes map[string]*Volume `yaml:"volumes,omitempty"`
// Default configuration for snaps (snap-id => key => value).
Defaults map[string]map[string]interface{} `yaml:"defaults,omitempty"`
Connections []Connection `yaml:"connections"`
KernelCmdline KernelCmdline `yaml:"kernel-cmdline"`
}
// HasRole returns true if any of the volume structures in this Info has the
// given role.
func (i *Info) HasRole(role string) bool {
for _, v := range i.Volumes {
for _, s := range v.Structure {
if s.Role == role {
return true
}
}
}
return false
}
// PartialProperty is a gadget property that can be partially defined.
type PartialProperty string
// These are the different properties of the gadget that can be partially
// defined.
// TODO What is the exact meaning of having a partial "structure" is not yet
// fully defined, so enforcing it has not been implemented yet.
const (
PartialSize PartialProperty = "size"
PartialFilesystem PartialProperty = "filesystem"
PartialSchema PartialProperty = "schema"
PartialStructure PartialProperty = "structure"
)
var validPartialProperties = [...]PartialProperty{PartialSize, PartialFilesystem, PartialSchema, PartialStructure}
// Volume defines the structure and content for the image to be written into a
// block device.
type Volume struct {
// Partial is a list of properties that are only only partially
// described in the gadget and that need to be filled by an
// installer.
Partial []PartialProperty `yaml:"partial,omitempty" json:"partial,omitempty"`
// Schema for the volume can be either gpt or mbr.
Schema string `yaml:"schema" json:"schema"`
// Bootloader names the bootloader used by the volume
Bootloader string `yaml:"bootloader" json:"bootloader"`
// ID is a 2-hex digit disk ID or GPT GUID
ID string `yaml:"id" json:"id"`
// Structure describes the structures that are part of the volume
Structure []VolumeStructure `yaml:"structure" json:"structure"`
// Name is the name of the volume from the gadget.yaml
Name string `json:"-"`
}
// HasPartial checks if the volume has a partially defined part.
func (v *Volume) HasPartial(pp PartialProperty) bool {
for _, vp := range v.Partial {
if vp == pp {
return true
}
}
return false
}
// MinSize returns the minimum size required by a volume, as implicitly
// defined by the size structures. It assumes sorted structures.
func (v *Volume) MinSize() quantity.Size {
endVol := quantity.Offset(0)
for _, s := range v.Structure {
if s.Offset != nil {
endVol = *s.Offset + quantity.Offset(s.MinSize)
} else {
endVol += quantity.Offset(s.MinSize)
}
}
return quantity.Size(endVol)
}
// StructFromYamlIndex returns the structure defined at a given yaml index from
// the original yaml file.
func (v *Volume) StructFromYamlIndex(yamlIdx int) *VolumeStructure {
i, err := v.yamlIdxToStructureIdx(yamlIdx)
if err != nil {
return nil
}
return &v.Structure[i]
}
// yamlIdxToStructureIdx returns the index to Volume.Structure that matches the
// yaml index from the original yaml file.
func (v *Volume) yamlIdxToStructureIdx(yamlIdx int) (int, error) {
for i := range v.Structure {
if v.Structure[i].YamlIndex == yamlIdx {
return i, nil
}
}
return -1, fmt.Errorf("structure with yaml index %d not found", yamlIdx)
}
// Copy makes a deep copy of the volume structure.
func (vs *VolumeStructure) Copy() *VolumeStructure {
newVs := *vs
if vs.Offset != nil {
newVs.Offset = asOffsetPtr(*vs.Offset)
}
if vs.OffsetWrite != nil {
offsetWr := *vs.OffsetWrite
newVs.OffsetWrite = &offsetWr
}
if vs.Content != nil {
newVs.Content = make([]VolumeContent, len(vs.Content))
copy(newVs.Content, vs.Content)
for i, c := range vs.Content {
if c.Offset != nil {
newC := &newVs.Content[i]
newC.Offset = asOffsetPtr(*c.Offset)
}
}
}
return &newVs
}
// Copy makes a deep copy of the volume.
func (v *Volume) Copy() *Volume {
newV := *v
if v.Partial != nil {
newV.Partial = make([]PartialProperty, len(v.Partial))
copy(newV.Partial, v.Partial)
}
if v.Structure != nil {
newV.Structure = make([]VolumeStructure, len(v.Structure))
for i, vs := range v.Structure {
newVs := vs.Copy()
newVs.EnclosingVolume = &newV
newV.Structure[i] = *newVs
}
}
return &newV
}
const GPTPartitionGUIDESP = "C12A7328-F81F-11D2-BA4B-00A0C93EC93B"
// VolumeStructure describes a single structure inside a volume. A structure can
// represent a partition, Master Boot Record, or any other contiguous range
// within the volume.
type VolumeStructure struct {
// VolumeName is the name of the volume that this structure belongs to.
VolumeName string `json:"-"`
// Name, when non empty, provides the name of the structure
Name string `yaml:"name" json:"name"`
// Label provides the filesystem label
Label string `yaml:"filesystem-label" json:"filesystem-label"`
// Offset defines a starting offset of the structure
Offset *quantity.Offset `yaml:"offset" json:"offset"`
// OffsetWrite describes a 32-bit address, within the volume, at which
// the offset of the current structure will be written. Initially, the
// position could be specified as a byte offset relative to the start
// of any named structure in the volume, but now the scope has been
// limited and the only accepted structure would be one with offset
// 0. Which implies that actually this offset will be always absolute,
// which should be fine as the only known use case for this is to set
// an address in an MBR. Furthermore, writes outside of the first
// structure are now not allowed.
OffsetWrite *RelativeOffset `yaml:"offset-write" json:"offset-write"`
// Minimum size of the structure (optional)
MinSize quantity.Size `yaml:"min-size" json:"min-size"`
// Size of the structure
Size quantity.Size `yaml:"size" json:"size"`
// Type of the structure, which can be 2-hex digit MBR partition,
// 36-char GUID partition, comma separated <mbr>,<guid> for hybrid
// partitioning schemes, or 'bare' when the structure is not considered
// a partition.
//
// For backwards compatibility type 'mbr' is also accepted, and the
// structure is treated as if it is of role 'mbr'.
Type string `yaml:"type" json:"type"`
// Role describes the role of given structure, can be one of
// 'mbr', 'system-data', 'system-boot', 'system-boot-image',
// 'system-boot-select' or 'system-recovery-select'. Structures of type 'mbr', must have a
// size of 446 bytes and must start at 0 offset.
Role string `yaml:"role" json:"role"`
// ID is the GPT partition ID, this should always be made upper case for
// comparison purposes.
ID string `yaml:"id" json:"id"`
// Filesystem used for the partition, 'vfat', 'vfat-{16,32}', 'ext4' or 'none' for
// structures of type 'bare'. 'vfat' is a synonymous for 'vfat-32'.
Filesystem string `yaml:"filesystem" json:"filesystem"`
// Content of the structure
Content []VolumeContent `yaml:"content" json:"content"`
Update VolumeUpdate `yaml:"update" json:"update"`
// Note that the Device field will never be part of the yaml
// and just used as part of the POST /systems/<label> API that
// is used by an installer.
Device string `yaml:"-" json:"device,omitempty"`
// Index of the structure definition in gadget YAML, note this starts at 0.
YamlIndex int `yaml:"-" json:"-"`
// EnclosingVolume is a pointer to the enclosing Volume, and should be used
// exclusively to check for partial information that affects the
// structure properties.
EnclosingVolume *Volume `yaml:"-" json:"-"`
}
// SetEnclosingVolumeInStructs is a helper that sets the pointer to
// the Volume in all VolumeStructure objects it contains.
func SetEnclosingVolumeInStructs(vv map[string]*Volume) {
for _, v := range vv {
for sidx := range v.Structure {
v.Structure[sidx].EnclosingVolume = v
}
}
}
// IsRoleMBR tells us if v has MBR role or not.
func (v *VolumeStructure) IsRoleMBR() bool {
return v.Role == schemaMBR
}
// HasFilesystem tells us if the structure definition expects a filesystem.
func (vs *VolumeStructure) HasFilesystem() bool {
switch {
case vs.Filesystem != "none" && vs.Filesystem != "":
return true
case vs.Type == "bare" || vs.Type == "mbr":
return false
default:
return vs.EnclosingVolume.HasPartial(PartialFilesystem)
}
}
// IsPartition returns true when the structure describes a partition in a block
// device.
func (vs *VolumeStructure) IsPartition() bool {
return vs.Type != "bare" && vs.Role != schemaMBR
}
// LinuxFilesystem returns the linux filesystem that corresponds to the
// one specified in the gadget.
func (vs *VolumeStructure) LinuxFilesystem() string {
switch vs.Filesystem {
case "vfat-16", "vfat-32":
return "vfat"
default:
return vs.Filesystem
}
}
// HasLabel checks if label matches the VolumeStructure label. It ignores
// capitals if the structure has a fat filesystem.
func (vs *VolumeStructure) HasLabel(label string) bool {
if vs.LinuxFilesystem() == "vfat" {
return strings.EqualFold(vs.Label, label)
}
return vs.Label == label
}
// isFixedSize tells us if size is fixed or if there is range.
func (vs *VolumeStructure) isFixedSize() bool {
if vs.hasPartialSize() {
return false
}
return vs.Size == vs.MinSize
}
// hasPartialSize tells us if the structure has partially defined size.
func (vs *VolumeStructure) hasPartialSize() bool {
if !vs.EnclosingVolume.HasPartial(PartialSize) {
return false
}
return vs.Size == 0
}
// minStructureOffset works out the minimum start offset of an structure, which
// depends on previous volume structures.
func minStructureOffset(vss []VolumeStructure, idx int) quantity.Offset {
if vss[idx].Offset != nil {
return *vss[idx].Offset
}
// Move to lower indices in the slice for minimum: the minimum offset
// will be the first fixed offset that we find plus all the minimum
// sizes of the structures up to that point.
min := quantity.Offset(0)
othersSz := quantity.Size(0)
for i := idx - 1; i >= 0; i-- {
othersSz += vss[i].MinSize
if vss[i].Offset != nil {
min = *vss[i].Offset + quantity.Offset(othersSz)
break
}
}
return min
}
// maxStructureOffset works out the maximum start offset of an structure, which
// depends on surrounding volume structures.
func maxStructureOffset(vss []VolumeStructure, idx int) quantity.Offset {
if vss[idx].Offset != nil {
return *vss[idx].Offset
}
// There are two restrictions on the maximum:
// 1. There is an implicit assumption that structures are contiguous if
// no offset is specified, so the max offset would be the first fixed
// offset while moving to previous structures in the slice plus the
// (max) size of each structure up to that point.
// 2. There is also a restriction if we find a fixed offset in following
// structures in the slice - in that case the maximum offset needs to
// be smaller than that offset minus all the minimum sizes of
// structures up to that point.
// The final max offset will be the smaller of the two.
// Move backwards in the slice for the first restriction
max := quantity.Offset(0)
othersSz := quantity.Size(0)
for i := idx - 1; i >= 0; i-- {
if vss[i].hasPartialSize() {
// If a previous partition has not a defined size, the
// allowed offset is not really bounded.
max = UnboundedStructureOffset
break
}
othersSz += vss[i].Size
if vss[i].Offset != nil {
max = *vss[i].Offset + quantity.Offset(othersSz)
break
}
}
// Move forward in the slice for the second restriction
maxFw := UnboundedStructureOffset
downSz := quantity.Size(0)
for i := idx; i < len(vss); i++ {
if vss[i].Offset != nil {
maxFw = *vss[i].Offset - quantity.Offset(downSz)
break
}
downSz += vss[i].MinSize
}
if maxFw < max {
max = maxFw
}
return max
}
type invalidOffsetError struct {
offset quantity.Offset
lowerBound quantity.Offset
upperBound quantity.Offset
}
func (e *invalidOffsetError) Error() string {
maxDesc := "unbounded"
if e.upperBound != UnboundedStructureOffset {
maxDesc = fmt.Sprintf("%d (%s)", e.upperBound, e.upperBound.IECString())
}
return fmt.Sprintf("offset %d (%s) is not in the valid gadget interval (min: %d (%s): max: %s)",
e.offset, e.offset.IECString(), e.lowerBound, e.lowerBound.IECString(), maxDesc)
}
// CheckValidStartOffset returns an error if the input offset is not valid for
// the structure at idx, nil otherwise.
func CheckValidStartOffset(off quantity.Offset, vss []VolumeStructure, idx int) error {
min := minStructureOffset(vss, idx)
max := maxStructureOffset(vss, idx)
if min <= off && off <= max {
return nil
}
return &invalidOffsetError{offset: off, lowerBound: min, upperBound: max}
}
// VolumeContent defines the contents of the structure. The content can be
// either files within a filesystem described by the structure or raw images
// written into the area of a bare structure.
type VolumeContent struct {
// UnresovedSource is the data of the partition relative to
// the gadget base directory
UnresolvedSource string `yaml:"source" json:"source"`
// Target is the location of the data inside the root filesystem
Target string `yaml:"target" json:"target"`
// Image names the image, relative to gadget base directory, to be used
// for a 'bare' type structure
Image string `yaml:"image" json:"image"`
// Offset the image is written at
Offset *quantity.Offset `yaml:"offset" json:"offset"`
// Size of the image, when empty size is calculated by looking at the
// image
Size quantity.Size `yaml:"size" json:"size"`
Unpack bool `yaml:"unpack" json:"unpack"`
}
func (vc VolumeContent) String() string {
if vc.Image != "" {
return fmt.Sprintf("image:%s", vc.Image)
}
return fmt.Sprintf("source:%s", vc.UnresolvedSource)
}
type VolumeUpdate struct {
Edition edition.Number `yaml:"edition" json:"edition"`
Preserve []string `yaml:"preserve" json:"preserve"`
}
// DiskVolumeDeviceTraits is a set of traits about a disk that were measured at
// a previous point in time on the same device, and is used primarily to try and
// map a volume in the gadget.yaml to a physical device on the system after the
// initial installation is done. We don't have a steadfast and predictable way
// to always find the device again, so we need to do a search, trying to find a
// device which matches each trait in turn, and verify it matches the physical
// structure layout and if not move on to using the next trait.
type DiskVolumeDeviceTraits struct {
// each member here is presented in descending order of certainty about the
// likelihood of being compatible if a candidate physical device matches the
// member. I.e. OriginalDevicePath is more trusted than OriginalKernelPath is
// more trusted than DiskID is more trusted than using the MappedStructures
// OriginalDevicePath is the device path in sysfs and in /dev/disk/by-path
// the volume was measured and observed at during UC20+ install mode.
OriginalDevicePath string `json:"device-path"`
// OriginalKernelPath is the device path like /dev/vda the volume was
// measured and observed at during UC20+ install mode.
OriginalKernelPath string `json:"kernel-path"`
// DiskID is the disk's identifier, it is a UUID for GPT disks or an
// unsigned integer for DOS disks encoded as a string in hexadecimal as in
// "0x1212e868".
DiskID string `json:"disk-id"`
// Size is the physical size of the disk, regardless of usable space
// considerations.
Size quantity.Size `json:"size"`
// SectorSize is the physical sector size of the disk, typically 512 or
// 4096.
SectorSize quantity.Size `json:"sector-size"`
// Schema is the disk schema, either dos or gpt in lowercase.
Schema string `json:"schema"`
// Structure contains trait information about each individual structure in
// the volume that may be useful in identifying whether a disk matches a
// volume or not.
Structure []DiskStructureDeviceTraits `json:"structure"`
// StructureEncryption is the set of partitions that are encrypted on the
// volume - this should only ever have ubuntu-data or ubuntu-save keys for
// now in the map. The value indicates parameters of the encryption present
// that enable matching/identifying encrypted structures with their laid out
// counterparts in the gadget.yaml.
StructureEncryption map[string]StructureEncryptionParameters `json:"structure-encryption"`
}
// StructureEncryptionParameters contains information about an encrypted
// structure, used to match encrypted structures on disk with their abstract,
// laid out counterparts in the gadget.yaml.
type StructureEncryptionParameters struct {
// Method is the method of encryption used, currently only EncryptionLUKS is
// recognized.
Method DiskEncryptionMethod `json:"method"`
// unknownKeys is used to log messages about unknown, unrecognized keys that
// we may encounter and may be used in the future
unknownKeys map[string]string
}
func (s *StructureEncryptionParameters) UnmarshalJSON(b []byte) error {
m := map[string]string{}
if err := json.Unmarshal(b, &m); err != nil {
return err
}
for key, val := range m {
if key == "method" {
s.Method = DiskEncryptionMethod(val)
} else {
if s.unknownKeys == nil {
s.unknownKeys = make(map[string]string)
}
s.unknownKeys[key] = val
}
}
return nil
}
// DiskStructureDeviceTraits is a similar to DiskVolumeDeviceTraits, but is a
// set of traits for a specific structure on a disk rather than the full disk
// itself. Structures can be full partitions or just raw slices on a disk like
// the "BIOS Boot" structure on default amd64 grub Ubuntu Core systems.
type DiskStructureDeviceTraits struct {
// OriginalDevicePath is the device path in sysfs and in /dev/disk/by-path the
// partition was measured and observed at during UC20+ install mode.
OriginalDevicePath string `json:"device-path"`
// OriginalKernelPath is the device path like /dev/vda1 the partition was
// measured and observed at during UC20+ install mode.
OriginalKernelPath string `json:"kernel-path"`
// PartitionUUID is the partuuid as defined by i.e. /dev/disk/by-partuuid
PartitionUUID string `json:"partition-uuid"`
// PartitionLabel is the label of the partition for GPT disks, i.e.
// /dev/disk/by-partlabel
PartitionLabel string `json:"partition-label"`
// PartitionType is the type of the partition i.e. 0x83 for a
// Linux native partition on DOS, or
// 0FC63DAF-8483-4772-8E79-3D69D8477DE4 for a Linux filesystem
// data partition on GPT.
PartitionType string `json:"partition-type"`
// FilesystemUUID is the UUID of the filesystem on the partition, i.e.
// /dev/disk/by-uuid
FilesystemUUID string `json:"filesystem-uuid"`
// FilesystemLabel is the label of the filesystem for structures that have
// filesystems, i.e. /dev/disk/by-label
FilesystemLabel string `json:"filesystem-label"`
// FilesystemType is the type of the filesystem, i.e. vfat or ext4, etc.
FilesystemType string `json:"filesystem-type"`
// Offset is the offset of the structure
Offset quantity.Offset `json:"offset"`
// Size is the size of the structure
Size quantity.Size `json:"size"`
}
// SaveDiskVolumesDeviceTraits saves the mapping of volume names to volume /
// device traits to a file inside the provided directory on disk for
// later loading and verification.
func SaveDiskVolumesDeviceTraits(dir string, mapping map[string]DiskVolumeDeviceTraits) error {
b, err := json.Marshal(mapping)
if err != nil {
return err
}
filename := filepath.Join(dir, "disk-mapping.json")
if err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {
return err
}
return osutil.AtomicWriteFile(filename, b, 0644, 0)
}
// LoadDiskVolumesDeviceTraits loads the mapping of volumes to disk traits if
// there is any. If there is no file with the mapping available, nil is
// returned.
func LoadDiskVolumesDeviceTraits(dir string) (map[string]DiskVolumeDeviceTraits, error) {
var mapping map[string]DiskVolumeDeviceTraits
filename := filepath.Join(dir, "disk-mapping.json")
if !osutil.FileExists(filename) {
return nil, nil
}
b, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
if len(b) == 0 {
// if the file is empty, it is safe to ignore it
logger.Noticef("WARNING: ignoring zero sized device traits file\n")
return nil, nil
}
if err := json.Unmarshal(b, &mapping); err != nil {
return nil, err
}
return mapping, nil
}
// AllDiskVolumeDeviceTraits takes a mapping of volume name to Volume
// and produces a map of volume name to DiskVolumeDeviceTraits. Since
// doing so uses DiskVolumeDeviceTraitsForDevice, it will also
// validate that disk devices identified for the volume are compatible
// and matching before returning.
func AllDiskVolumeDeviceTraits(allVols map[string]*Volume, optsPerVolume map[string]*DiskVolumeValidationOptions) (map[string]DiskVolumeDeviceTraits, error) {
// build up the mapping of volumes to disk device traits
allTraits := map[string]DiskVolumeDeviceTraits{}
// find all devices which map to volumes to save the current state of the
// system
for name, vol := range allVols {
// try to find a device for a structure inside the volume, we have a
// loop to attempt to use all structures in the volume in case there are
// partitions we can't map to a device directly at first using the
// device symlinks that FindDeviceForStructure uses
dev := ""
for _, vs := range vol.Structure {
// TODO: This code works for volumes that have at least one
// partition (i.e. not type: bare structure), but does not work for
// volumes which contain only type: bare structures with no other
// structures on them. It is entirely unclear how to identify such
// a volume, since there is no information on the disk about where
// such raw structures begin and end and thus no way to validate
// that a given disk "has" such raw structures at particular
// locations, aside from potentially reading and comparing the bytes
// at the expected locations, but that is probably fragile and very
// non-performant.
if !vs.IsPartition() {
// skip trying to find non-partitions on disk, it won't work
continue
}
structureDevice, err := FindDeviceForStructure(&vs)
if err != nil && err != ErrDeviceNotFound {
return nil, err
}
if structureDevice != "" {
// we found a device for this structure, get the parent disk
// and save that as the device for this volume
disk, err := disks.DiskFromPartitionDeviceNode(structureDevice)
if err != nil {
return nil, err
}
dev = disk.KernelDeviceNode()
break
}
}
if dev == "" {
return nil, fmt.Errorf("cannot find disk for volume %s from gadget", name)
}
// now that we have a candidate device for this disk, build up the
// traits for it, this will also validate concretely that the
// device we picked and the volume are compatible
opts := optsPerVolume[name]
if opts == nil {
opts = &DiskVolumeValidationOptions{}
}
traits, err := DiskTraitsFromDeviceAndValidate(vol, dev, opts)
if err != nil {
return nil, fmt.Errorf("cannot gather disk traits for device %s to use with volume %s: %v", dev, name, err)
}
allTraits[name] = traits
}
return allTraits, nil
}
// GadgetConnect describes an interface connection requested by the gadget
// between seeded snaps. The syntax is of a mapping like:
//
// plug: (<plug-snap-id>|system):plug
// [slot: (<slot-snap-id>|system):slot]
//
// "system" indicates a system plug or slot.
// Fully omitting the slot part indicates a system slot with the same name
// as the plug.
type Connection struct {
Plug ConnectionPlug `yaml:"plug"`
Slot ConnectionSlot `yaml:"slot"`
}
type ConnectionPlug struct {
SnapID string
Plug string
}
func (gcplug *ConnectionPlug) Empty() bool {
return gcplug.SnapID == "" && gcplug.Plug == ""
}
func (gcplug *ConnectionPlug) UnmarshalYAML(unmarshal func(interface{}) error) error {
var s string
if err := unmarshal(&s); err != nil {
return err
}
snapID, name, err := parseSnapIDColonName(s)
if err != nil {
return fmt.Errorf("in gadget connection plug: %v", err)
}
gcplug.SnapID = snapID
gcplug.Plug = name
return nil
}
type ConnectionSlot struct {
SnapID string
Slot string
}
func (gcslot *ConnectionSlot) Empty() bool {
return gcslot.SnapID == "" && gcslot.Slot == ""
}
func (gcslot *ConnectionSlot) UnmarshalYAML(unmarshal func(interface{}) error) error {
var s string
if err := unmarshal(&s); err != nil {
return err
}
snapID, name, err := parseSnapIDColonName(s)
if err != nil {
return fmt.Errorf("in gadget connection slot: %v", err)
}
gcslot.SnapID = snapID
gcslot.Slot = name
return nil
}
func parseSnapIDColonName(s string) (snapID, name string, err error) {
parts := strings.Split(s, ":")
if len(parts) == 2 {
snapID = parts[0]
name = parts[1]
}
if snapID == "" || name == "" {
return "", "", fmt.Errorf(`expected "(<snap-id>|system):name" not %q`, s)
}
return snapID, name, nil
}
func systemOrSnapID(s string) bool {
if s != "system" && naming.ValidateSnapID(s) != nil {
return false
}
return true
}
// Model carries characteristics about the model that are relevant to gadget.
// Note *asserts.Model implements this, and that's the expected use case.
type Model interface {
Classic() bool
Grade() asserts.ModelGrade
}
func classicOrUndetermined(m Model) bool {
return m == nil || m.Classic()
}
func hasGrade(m Model) bool {
return m != nil && m.Grade() != asserts.ModelGradeUnset
}
func compatWithPibootOrIndeterminate(m Model) bool {
return m == nil || m.Grade() != asserts.ModelGradeUnset
}
// Ancillary structs to sort volume structures. We split volumes in
// contiguousStructs slices, with each of these beginning with a structure with
// a known fixed offset, followed by structures for which the offset is unknown
// so we can know for sure that they appear after the first structure in
// contiguousStruct. The unknown offsets appear because of min-size use. The
// contiguousStructs are the things that we need to order, as all have a known
// starting offset, which is not true for all the volume structures.
type contiguousStructs struct {
// vss contains contiguous structures with the first one
// containing a valid Offset
vss []VolumeStructure
}
type contiguousStructsSet []*contiguousStructs
func (scss contiguousStructsSet) Len() int {
return len(scss)
}
func (scss contiguousStructsSet) Less(i, j int) bool {
return *scss[i].vss[0].Offset < *scss[j].vss[0].Offset
}
func (scss contiguousStructsSet) Swap(i, j int) {
scss[i], scss[j] = scss[j], scss[i]
}
func orderStructuresByOffset(vss []VolumeStructure) []VolumeStructure {
if vss == nil {
return nil
}
// Build contiguous structures
scss := contiguousStructsSet{}
var currentCont *contiguousStructs
for _, s := range vss {
// If offset is set we can start a new "block", otherwise the
// structure goes right after the latest structure of the
// current block. Note that currentCont will never be accessed
// as nil as necessarily the first structure in gadget.yaml will
// have offset explicitly or implicitly (the only way for a
// structure to have nil offset is when the current structure
// does not have explicit offset and the previous one either
// does not have itself offset or has min-size set).
if s.Offset != nil {
currentCont = &contiguousStructs{}
scss = append(scss, currentCont)
}
currentCont.vss = append(currentCont.vss, s)
}
sort.Sort(scss)
// Build plain list of structures now
ordVss := []VolumeStructure{}
for _, cs := range scss {
ordVss = append(ordVss, cs.vss...)
}
return ordVss
}
func validatePartial(v *Volume) error {
var foundCache [len(validPartialProperties)]bool
for _, p := range v.Partial {
found := false
for vpvIdx, valid := range validPartialProperties {
if p == valid {
if foundCache[vpvIdx] == true {
return fmt.Errorf("partial value %q is repeated", p)
}
foundCache[vpvIdx] = true
found = true
break
}
}
if !found {
return fmt.Errorf("%q is not a valid partial value", p)
}
}
return nil
}
// InfoFromGadgetYaml parses the provided gadget metadata.
// If model is nil only self-consistency checks are performed.
// If model is not nil implied values for filesystem labels will be set
// as well, based on whether the model is for classic, UC16/18 or UC20.
// UC gadget metadata is expected to have volumes definitions.
func InfoFromGadgetYaml(gadgetYaml []byte, model Model) (*Info, error) {
var gi Info
if err := yaml.Unmarshal(gadgetYaml, &gi); err != nil {
return nil, fmt.Errorf("cannot parse gadget metadata: %v", err)
}
for k, v := range gi.Defaults {
if !systemOrSnapID(k) {
return nil, fmt.Errorf(`default stanza not keyed by "system" or snap-id: %s`, k)
}
dflt, err := metautil.NormalizeValue(v)
if err != nil {
return nil, fmt.Errorf("default value %q of %q: %v", v, k, err)
}
gi.Defaults[k] = dflt.(map[string]interface{})
}
for i, gconn := range gi.Connections {
if gconn.Plug.Empty() {
return nil, errors.New("gadget connection plug cannot be empty")
}
if gconn.Slot.Empty() {
gi.Connections[i].Slot.SnapID = "system"
gi.Connections[i].Slot.Slot = gconn.Plug.Plug
}
}
if len(gi.Volumes) == 0 && classicOrUndetermined(model) {
// volumes can be left out on classic
// can still specify defaults though
return &gi, nil
}
// basic validation
var bootloadersFound int
for name := range gi.Volumes {
v := gi.Volumes[name]
if v == nil {
return nil, fmt.Errorf("volume %q stanza is empty", name)
}