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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
|
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2016-2023 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 asserts
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/snapcore/snapd/release"
"github.com/snapcore/snapd/snap/channel"
"github.com/snapcore/snapd/snap/naming"
"github.com/snapcore/snapd/strutil"
)
// ModelComponent holds details for components specified by a model assertion.
type ModelComponent struct {
// Presence can be optional or required
Presence string
// Modes is an optional list of modes, which must be a subset
// of the ones for the snap
Modes []string
}
// TODO: for ModelSnap
// * consider moving snap.Type out of snap and using it in ModelSnap
// but remember assertions use "core" (never "os") for TypeOS
// * consider having a first-class Presence type
// ModelSnap holds the details about a snap specified by a model assertion.
type ModelSnap struct {
Name string
SnapID string
// SnapType is one of: app|base|gadget|kernel|core, default is app
SnapType string
// Modes in which the snap must be made available
Modes []string
// DefaultChannel is the initial tracking channel,
// default is latest/stable in an extended model
DefaultChannel string
// PinnedTrack is a pinned track for the snap, if set DefaultChannel
// cannot be set at the same time (Core 18 models feature)
PinnedTrack string
// Presence is one of: required|optional
Presence string
// Classic indicates that this classic snap is intentionally
// included in a classic model
Classic bool
// Components is a map of component names to ModelComponent
Components map[string]ModelComponent
}
// SnapName implements naming.SnapRef.
func (s *ModelSnap) SnapName() string {
return s.Name
}
// ID implements naming.SnapRef.
func (s *ModelSnap) ID() string {
return s.SnapID
}
type modelSnaps struct {
snapd *ModelSnap
base *ModelSnap
gadget *ModelSnap
kernel *ModelSnap
snapsNoEssential []*ModelSnap
}
func (ms *modelSnaps) list() (allSnaps []*ModelSnap, requiredWithEssentialSnaps []naming.SnapRef, numEssentialSnaps int) {
addSnap := func(snap *ModelSnap, essentialSnap int) {
if snap == nil {
return
}
numEssentialSnaps += essentialSnap
allSnaps = append(allSnaps, snap)
if snap.Presence == "required" {
requiredWithEssentialSnaps = append(requiredWithEssentialSnaps, snap)
}
}
addSnap(ms.snapd, 1)
addSnap(ms.kernel, 1)
addSnap(ms.base, 1)
addSnap(ms.gadget, 1)
for _, snap := range ms.snapsNoEssential {
addSnap(snap, 0)
}
return allSnaps, requiredWithEssentialSnaps, numEssentialSnaps
}
var (
essentialSnapModes = []string{"run", "ephemeral"}
defaultModes = []string{"run"}
)
func checkExtendedSnaps(extendedSnaps any, base string, grade ModelGrade, modelIsClassic bool) (*modelSnaps, error) {
const wrongHeaderType = `"snaps" header must be a list of maps`
entries, ok := extendedSnaps.([]any)
if !ok {
return nil, fmt.Errorf(wrongHeaderType)
}
var modelSnaps modelSnaps
seen := make(map[string]bool, len(entries))
seenIDs := make(map[string]string, len(entries))
for _, entry := range entries {
snap, ok := entry.(map[string]any)
if !ok {
return nil, fmt.Errorf(wrongHeaderType)
}
modelSnap, err := checkModelSnap(snap, base, grade, modelIsClassic)
if err != nil {
return nil, err
}
if seen[modelSnap.Name] {
return nil, fmt.Errorf("cannot list the same snap %q multiple times", modelSnap.Name)
}
seen[modelSnap.Name] = true
// at this time we do not support parallel installing
// from model/seed
if snapID := modelSnap.SnapID; snapID != "" {
if underName := seenIDs[snapID]; underName != "" {
return nil, fmt.Errorf("cannot specify the same snap id %q multiple times, specified for snaps %q and %q", snapID, underName, modelSnap.Name)
}
seenIDs[snapID] = modelSnap.Name
}
switch {
case modelSnap.SnapType == "snapd":
// TODO: allow to be explicit only in grade: dangerous?
if modelSnaps.snapd != nil {
return nil, fmt.Errorf("cannot specify multiple snapd snaps: %q and %q", modelSnaps.snapd.Name, modelSnap.Name)
}
modelSnaps.snapd = modelSnap
case modelSnap.SnapType == "kernel":
if modelSnaps.kernel != nil {
return nil, fmt.Errorf("cannot specify multiple kernel snaps: %q and %q", modelSnaps.kernel.Name, modelSnap.Name)
}
modelSnaps.kernel = modelSnap
case modelSnap.SnapType == "gadget":
if modelSnaps.gadget != nil {
return nil, fmt.Errorf("cannot specify multiple gadget snaps: %q and %q", modelSnaps.gadget.Name, modelSnap.Name)
}
modelSnaps.gadget = modelSnap
case modelSnap.Name == base:
if modelSnap.SnapType != "base" {
return nil, fmt.Errorf(`boot base %q must specify type "base", not %q`, base, modelSnap.SnapType)
}
modelSnaps.base = modelSnap
}
if !isEssentialSnap(modelSnap.Name, modelSnap.SnapType, base) {
modelSnaps.snapsNoEssential = append(modelSnaps.snapsNoEssential, modelSnap)
}
}
return &modelSnaps, nil
}
var (
validSnapTypes = []string{"app", "base", "gadget", "kernel", "core", "snapd"}
validSnapMode = regexp.MustCompile("^[a-z][-a-z]+$")
validSnapPresences = []string{"required", "optional"}
)
func isEssentialSnap(snapName, snapType, modelBase string) bool {
switch snapType {
case "snapd", "kernel", "gadget":
return true
}
if snapName == modelBase {
return true
}
return false
}
func checkModesForSnap(snap map[string]any, isEssential bool, what string) ([]string, error) {
modes, err := checkStringListInMap(snap, "modes", fmt.Sprintf("%q %s", "modes", what),
validSnapMode)
if err != nil {
return nil, err
}
if isEssential {
if len(modes) != 0 {
return nil, fmt.Errorf("essential snaps are always available, cannot specify modes %s", what)
}
modes = essentialSnapModes
}
if len(modes) == 0 {
modes = defaultModes
}
return modes, nil
}
func checkModelSnap(snap map[string]any, modelBase string, grade ModelGrade, modelIsClassic bool) (*ModelSnap, error) {
name, err := checkNotEmptyStringWhat(snap, "name", "of snap")
if err != nil {
return nil, err
}
if err := naming.ValidateSnap(name); err != nil {
return nil, fmt.Errorf("invalid snap name %q", name)
}
what := fmt.Sprintf("of snap %q", name)
var snapID string
_, ok := snap["id"]
if ok {
var err error
snapID, err = checkStringMatchesWhat(snap, "id", what, naming.ValidSnapID)
if err != nil {
return nil, err
}
} else {
// snap ids are optional with grade dangerous to allow working
// with local/not pushed yet to the store snaps
if grade != ModelDangerous {
return nil, fmt.Errorf(`"id" %s is mandatory for %s grade model`, what, grade)
}
}
typ, err := checkOptionalStringWhat(snap, "type", what)
if err != nil {
return nil, err
}
if typ == "" {
typ = "app"
}
if !strutil.ListContains(validSnapTypes, typ) {
return nil, fmt.Errorf("type of snap %q must be one of %s", name, strings.Join(validSnapTypes, "|"))
}
presence, err := checkOptionalStringWhat(snap, "presence", what)
if err != nil {
return nil, err
}
if presence != "" && !strutil.ListContains(validSnapPresences, presence) {
return nil, fmt.Errorf("presence of snap %q must be one of required|optional", name)
}
essential := isEssentialSnap(name, typ, modelBase)
if essential && presence != "" {
return nil, fmt.Errorf("essential snaps are always available, cannot specify presence for snap %q", name)
}
if presence == "" {
presence = "required"
}
modes, err := checkModesForSnap(snap, essential, what)
if err != nil {
return nil, err
}
defaultChannel, err := checkOptionalStringWhat(snap, "default-channel", what)
if err != nil {
return nil, err
}
if defaultChannel == "" {
defaultChannel = "latest/stable"
}
defCh, err := channel.ParseVerbatim(defaultChannel, "-")
if err != nil {
return nil, fmt.Errorf("invalid default channel for snap %q: %v", name, err)
}
if defCh.Track == "" {
return nil, fmt.Errorf("default channel for snap %q must specify a track", name)
}
isClassic, err := checkOptionalBoolWhat(snap, "classic", what)
if err != nil {
return nil, err
}
if isClassic && !modelIsClassic {
return nil, fmt.Errorf("snap %q cannot be classic in non-classic model", name)
}
if isClassic && typ != "app" {
return nil, fmt.Errorf("snap %q cannot be classic with type %q instead of app", name, typ)
}
if isClassic && (len(modes) != 1 || modes[0] != "run") {
return nil, fmt.Errorf("classic snap %q not allowed outside of run mode: %v",
name, modes)
}
components, err := checkComponentsForMaps(snap, modes, what)
if err != nil {
return nil, err
}
return &ModelSnap{
Name: name,
SnapID: snapID,
SnapType: typ,
Modes: modes, // can be empty
DefaultChannel: defaultChannel,
Presence: presence, // can be empty
Classic: isClassic,
Components: components, // can be empty
}, nil
}
// This is what we expect for components:
/**
snaps:
- name: <snap-name>
...
presence: "optional"|"required" # optional, defaults to "required"
modes: [<mode-specifier>] # list of modes
components: # optional
<component-name-1>:
presence: "optional"|"required"
modes: [<mode-specifier>] # list of modes, optional
# must be a subset of snap modes
# defaults to the same modes
# as the snap
<component-name-2>: "required"|"optional" # presence, shortcut syntax
**/
func checkComponentsForMaps(m map[string]any, validModes []string, what string) (map[string]ModelComponent, error) {
const compsField = "components"
value, ok := m[compsField]
if !ok {
return nil, nil
}
comps, ok := value.(map[string]any)
if !ok {
return nil, fmt.Errorf("%q %s must be a map from strings to components",
compsField, what)
}
res := make(map[string]ModelComponent, len(comps))
for name, comp := range comps {
// Name of component follows the same rules as snap components
if err := naming.ValidateSnap(name); err != nil {
return nil, fmt.Errorf("invalid component name %s", name)
}
// "comp: required|optional" case
compWhat := fmt.Sprintf("of component %q %s", name, what)
presence, ok := comp.(string)
if ok {
if !strutil.ListContains(validSnapPresences, presence) {
return nil, fmt.Errorf("presence %s must be one of required|optional", compWhat)
}
res[name] = ModelComponent{Presence: presence,
Modes: append([]string(nil), validModes...)}
continue
}
// try map otherwise
compFields, ok := comp.(map[string]any)
if !ok {
return nil, fmt.Errorf("%s must be a map of strings to components or one of required|optional",
compWhat)
}
// Error out if unexpected entry
for key := range compFields {
if !strutil.ListContains([]string{"presence", "modes"}, key) {
return nil, fmt.Errorf("entry %q %s is unknown", key, compWhat)
}
}
presence, err := checkNotEmptyStringWhat(compFields, "presence", compWhat)
if err != nil {
return nil, err
}
if !strutil.ListContains(validSnapPresences, presence) {
return nil, fmt.Errorf("presence %s must be one of required|optional", compWhat)
}
modes, err := checkStringListInMap(compFields, "modes",
fmt.Sprintf("modes %s", compWhat), validSnapMode)
if err != nil {
return nil, err
}
if len(modes) == 0 {
modes = append([]string(nil), validModes...)
} else {
for _, m := range modes {
if !strutil.ListContains(validModes, m) {
return nil, fmt.Errorf("mode %q %s is incompatible with the snap modes", m, compWhat)
}
}
}
res[name] = ModelComponent{Presence: presence, Modes: modes}
}
return res, nil
}
// unextended case support
func checkSnapWithTrack(headers map[string]any, which string) (*ModelSnap, error) {
_, ok := headers[which]
if !ok {
return nil, nil
}
value, ok := headers[which].(string)
if !ok {
return nil, fmt.Errorf(`%q header must be a string`, which)
}
l := strings.SplitN(value, "=", 2)
name := l[0]
track := ""
if err := validateSnapName(name, which); err != nil {
return nil, err
}
if len(l) > 1 {
track = l[1]
if strings.Count(track, "/") != 0 {
return nil, fmt.Errorf(`%q channel selector must be a track name only`, which)
}
channelRisks := []string{"stable", "candidate", "beta", "edge"}
if strutil.ListContains(channelRisks, track) {
return nil, fmt.Errorf(`%q channel selector must be a track name`, which)
}
}
return &ModelSnap{
Name: name,
SnapType: which,
Modes: defaultModes,
PinnedTrack: track,
Presence: "required",
}, nil
}
func validateSnapName(name string, headerName string) error {
if err := naming.ValidateSnap(name); err != nil {
return fmt.Errorf("invalid snap name in %q header: %s", headerName, name)
}
return nil
}
func checkRequiredSnap(name string, headerName string, snapType string) (*ModelSnap, error) {
if err := validateSnapName(name, headerName); err != nil {
return nil, err
}
return &ModelSnap{
Name: name,
SnapType: snapType,
Modes: defaultModes,
Presence: "required",
}, nil
}
// ModelGrade characterizes the security of the model which then
// controls related policy.
type ModelGrade string
const (
ModelGradeUnset ModelGrade = "unset"
// ModelSecured implies mandatory full disk encryption and secure boot.
ModelSecured ModelGrade = "secured"
// ModelSigned implies all seed snaps are signed and mentioned
// in the model, i.e. no unasserted or extra snaps.
ModelSigned ModelGrade = "signed"
// ModelDangerous allows unasserted snaps and extra snaps.
ModelDangerous ModelGrade = "dangerous"
)
// StorageSafety characterizes the requested storage safety of
// the model which then controls what encryption is used
type StorageSafety string
const (
StorageSafetyUnset StorageSafety = "unset"
// StorageSafetyEncrypted implies mandatory full disk encryption.
StorageSafetyEncrypted StorageSafety = "encrypted"
// StorageSafetyPreferEncrypted implies full disk
// encryption when the system supports it.
StorageSafetyPreferEncrypted StorageSafety = "prefer-encrypted"
// StorageSafetyPreferUnencrypted implies no full disk
// encryption by default even if the system supports
// encryption.
StorageSafetyPreferUnencrypted StorageSafety = "prefer-unencrypted"
)
var validStorageSafeties = []string{string(StorageSafetyEncrypted), string(StorageSafetyPreferEncrypted), string(StorageSafetyPreferUnencrypted)}
var validModelGrades = []string{string(ModelSecured), string(ModelSigned), string(ModelDangerous)}
// gradeToCode encodes grades into 32 bits, trying to be slightly future-proof:
// - lower 16 bits are reserved
// - in the higher bits use the sequence 1, 8, 16 to have some space
// to possibly add new grades in between
var gradeToCode = map[ModelGrade]uint32{
ModelGradeUnset: 0,
ModelDangerous: 0x10000,
ModelSigned: 0x80000,
ModelSecured: 0x100000,
// reserved by secboot to measure classic models
// "ClassicModelGradeMask": 0x80000000
}
// Code returns a bit representation of the grade, for example for
// measuring it in a full disk encryption implementation.
func (mg ModelGrade) Code() uint32 {
code, ok := gradeToCode[mg]
if !ok {
panic(fmt.Sprintf("unknown model grade: %s", mg))
}
return code
}
type ModelValidationSetMode string
const (
ModelValidationSetModePreferEnforced ModelValidationSetMode = "prefer-enforce"
ModelValidationSetModeEnforced ModelValidationSetMode = "enforce"
)
var validModelValidationSetModes = []string{
string(ModelValidationSetModePreferEnforced),
string(ModelValidationSetModeEnforced),
}
// ModelValidationSet represents a reference to a validation set assertion.
// The structure also describes how the validation set will be applied
// to the device, and whether the validation set should be pinned to
// a specific sequence.
type ModelValidationSet struct {
// AccountID is the account ID the validation set originates from.
// If this was not explicitly set in the stanza, this will instead
// be set to the brand ID.
AccountID string
// Name is the name of the validation set from the account ID.
Name string
// Sequence, if non-zero, specifies that the validation set should be
// pinned at this sequence number.
Sequence int
// Mode is the enforcement mode the validation set should be applied with.
Mode ModelValidationSetMode
}
// SequenceKey returns the sequence key for this validation set.
func (mvs *ModelValidationSet) SequenceKey() string {
return vsSequenceKey(release.Series, mvs.AccountID, mvs.Name)
}
func (mvs *ModelValidationSet) AtSequence() *AtSequence {
return &AtSequence{
Type: ValidationSetType,
SequenceKey: []string{release.Series, mvs.AccountID, mvs.Name},
Sequence: mvs.Sequence,
Pinned: mvs.Sequence > 0,
Revision: RevisionNotKnown,
}
}
// Model holds a model assertion, which is a statement by a brand
// about the properties of a device model.
type Model struct {
assertionBase
classic bool
baseSnap *ModelSnap
gadgetSnap *ModelSnap
kernelSnap *ModelSnap
grade ModelGrade
storageSafety StorageSafety
allSnaps []*ModelSnap
// consumers of this info should care only about snap identity =>
// snapRef
requiredWithEssentialSnaps []naming.SnapRef
numEssentialSnaps int
validationSets []*ModelValidationSet
serialAuthority []string
sysUserAuthority []string
preseedAuthority []string
timestamp time.Time
}
// BrandID returns the brand identifier. Same as the authority id.
func (mod *Model) BrandID() string {
return mod.HeaderString("brand-id")
}
// Model returns the model name identifier.
func (mod *Model) Model() string {
return mod.HeaderString("model")
}
// DisplayName returns the human-friendly name of the model or
// falls back to Model if this was not set.
func (mod *Model) DisplayName() string {
display := mod.HeaderString("display-name")
if display == "" {
return mod.Model()
}
return display
}
// Series returns the series of the core software the model uses.
func (mod *Model) Series() string {
return mod.HeaderString("series")
}
// Classic returns whether the model is a classic system.
func (mod *Model) Classic() bool {
return mod.classic
}
// HybridClassic returns whether the model is a hybrid classic system, meaning
// it is both classic and has an associated kernel snap.
func (mod *Model) HybridClassic() bool {
return mod.classic && mod.kernelSnap != nil
}
// Distribution returns the linux distro specified in the model.
func (mod *Model) Distribution() string {
return mod.HeaderString("distribution")
}
// Architecture returns the architecture the model is based on.
func (mod *Model) Architecture() string {
return mod.HeaderString("architecture")
}
// Grade returns the stability grade of the model. Will be ModelGradeUnset
// for Core 16/18 models.
func (mod *Model) Grade() ModelGrade {
return mod.grade
}
// StorageSafety returns the storage safety for the model. Will be
// StorageSafetyUnset for Core 16/18 models.
func (mod *Model) StorageSafety() StorageSafety {
return mod.storageSafety
}
// GadgetSnap returns the details of the gadget snap the model uses.
func (mod *Model) GadgetSnap() *ModelSnap {
return mod.gadgetSnap
}
// Gadget returns the gadget snap the model uses.
func (mod *Model) Gadget() string {
if mod.gadgetSnap == nil {
return ""
}
return mod.gadgetSnap.Name
}
// GadgetTrack returns the gadget track the model uses.
// XXX this should go away
func (mod *Model) GadgetTrack() string {
if mod.gadgetSnap == nil {
return ""
}
return mod.gadgetSnap.PinnedTrack
}
// KernelSnap returns the details of the kernel snap the model uses.
func (mod *Model) KernelSnap() *ModelSnap {
return mod.kernelSnap
}
// Kernel returns the kernel snap the model uses.
// XXX this should go away
func (mod *Model) Kernel() string {
if mod.kernelSnap == nil {
return ""
}
return mod.kernelSnap.Name
}
// KernelTrack returns the kernel track the model uses.
// XXX this should go away
func (mod *Model) KernelTrack() string {
if mod.kernelSnap == nil {
return ""
}
return mod.kernelSnap.PinnedTrack
}
// Base returns the base snap the model uses.
func (mod *Model) Base() string {
return mod.HeaderString("base")
}
// BaseSnap returns the details of the base snap the model uses.
func (mod *Model) BaseSnap() *ModelSnap {
return mod.baseSnap
}
// Store returns the snap store the model uses.
func (mod *Model) Store() string {
return mod.HeaderString("store")
}
// RequiredNoEssentialSnaps returns the snaps that must be installed at all times and cannot be removed for this model, excluding the essential snaps (gadget, kernel, boot base, snapd).
func (mod *Model) RequiredNoEssentialSnaps() []naming.SnapRef {
return mod.requiredWithEssentialSnaps[mod.numEssentialSnaps:]
}
// RequiredWithEssentialSnaps returns the snaps that must be installed at all times and cannot be removed for this model, including any essential snaps (gadget, kernel, boot base, snapd).
func (mod *Model) RequiredWithEssentialSnaps() []naming.SnapRef {
return mod.requiredWithEssentialSnaps
}
// EssentialSnaps returns all essential snaps explicitly mentioned by
// the model.
// They are always returned according to this order with some skipped
// if not mentioned: snapd, kernel, boot base, gadget.
func (mod *Model) EssentialSnaps() []*ModelSnap {
return mod.allSnaps[:mod.numEssentialSnaps]
}
// SnapsWithoutEssential returns all the snaps listed by the model
// without any of the essential snaps (as returned by EssentialSnaps).
// They are returned in the order of mention by the model.
func (mod *Model) SnapsWithoutEssential() []*ModelSnap {
return mod.allSnaps[mod.numEssentialSnaps:]
}
// AllSnaps returns all the snaps listed by the model, across all modes.
// Essential snaps are at the front of the slice, followed by the non-essential
// snaps. The essential snaps follow the same order as returned by
// EssentialSnaps. The non-essential snaps are returned in the order they are
// mentioned in the model.
func (mod *Model) AllSnaps() []*ModelSnap {
return mod.allSnaps
}
// ValidationSets returns all the validation-sets listed by the model.
func (mod *Model) ValidationSets() []*ModelValidationSet {
return mod.validationSets
}
// SerialAuthority returns the authority ids that are accepted as
// signers for serial assertions for this model. It always includes the
// brand of the model.
func (mod *Model) SerialAuthority() []string {
return mod.serialAuthority
}
// SystemUserAuthority returns the authority ids that are accepted as
// signers of system-user assertions for this model. Empty list means
// any, otherwise it always includes the brand of the model.
func (mod *Model) SystemUserAuthority() []string {
return mod.sysUserAuthority
}
// PreseedAuthority returns the authority ids that are accepted as
// signers of the preseed binary blob for this model. It always includes the
// brand of the model.
func (mod *Model) PreseedAuthority() []string {
return mod.preseedAuthority
}
// Timestamp returns the time when the model assertion was issued.
func (mod *Model) Timestamp() time.Time {
return mod.timestamp
}
// Implement further consistency checks.
func (mod *Model) checkConsistency(db RODatabase, acck *AccountKey) error {
// TODO: double check trust level of authority depending on class and possibly allowed-modes
return nil
}
// expected interface is implemented
var _ consistencyChecker = (*Model)(nil)
// limit model to only lowercase for now
var validModel = regexp.MustCompile("^[a-zA-Z0-9](?:-?[a-zA-Z0-9])*$")
func checkModel(headers map[string]any) (string, error) {
s, err := checkStringMatches(headers, "model", validModel)
if err != nil {
return "", err
}
// TODO: support the concept of case insensitive/preserving string headers
if strings.ToLower(s) != s {
return "", fmt.Errorf(`"model" header cannot contain uppercase letters`)
}
return s, nil
}
func checkAuthorityMatchesBrand(a Assertion) error {
typeName := a.Type().Name
authorityID := a.AuthorityID()
brand := a.HeaderString("brand-id")
if brand != authorityID {
return fmt.Errorf("authority-id and brand-id must match, %s assertions are expected to be signed by the brand: %q != %q", typeName, authorityID, brand)
}
return nil
}
func checkOptionalAuthority(headers map[string]any, name string, brandID string, acceptsWildcard bool) ([]string, error) {
ids := []string{brandID}
v, ok := headers[name]
if !ok {
return ids, nil
}
switch x := v.(type) {
case string:
if acceptsWildcard && x == "*" {
return nil, nil
}
case []any:
lst, err := checkStringListMatches(headers, name, validAccountID)
if err == nil {
if !strutil.ListContains(lst, brandID) {
lst = append(ids, lst...)
}
return lst, nil
}
}
if acceptsWildcard {
return nil, fmt.Errorf("%q header must be '*' or a list of account ids", name)
} else {
return nil, fmt.Errorf("%q header must be a list of account ids", name)
}
}
func checkOptionalSerialAuthority(headers map[string]any, brandID string) ([]string, error) {
const acceptsWildcard = false
return checkOptionalAuthority(headers, "serial-authority", brandID, acceptsWildcard)
}
func checkOptionalSystemUserAuthority(headers map[string]any, brandID string) ([]string, error) {
const acceptsWildcard = true
return checkOptionalAuthority(headers, "system-user-authority", brandID, acceptsWildcard)
}
func checkOptionalPreseedAuthority(headers map[string]any, brandID string) ([]string, error) {
const acceptsWildcard = false
return checkOptionalAuthority(headers, "preseed-authority", brandID, acceptsWildcard)
}
func checkModelValidationSetAccountID(headers map[string]any, what, brandID string) (string, error) {
accountID, err := checkOptionalStringWhat(headers, "account-id", what)
if err != nil {
return "", err
}
// default to brand ID if account ID is not provided
if accountID == "" {
return brandID, nil
}
return accountID, nil
}
// checkOptionalModelValidationSetSequence reads the optional 'sequence' member, if
// not set, returns 0 as this means unpinned. Unfortunately we are not able
// to reuse `checkSequence` as it operates inside different parameters.
func checkOptionalModelValidationSetSequence(headers map[string]any, what string) (int, error) {
// Default to 0 when the sequence header is not present
if _, ok := headers["sequence"]; !ok {
return 0, nil
}
seq, err := checkIntWhat(headers, "sequence", what)
if err != nil {
return 0, err
}
// If sequence is provided, only accept positive values above 0
if seq <= 0 {
return 0, fmt.Errorf("\"sequence\" %s must be larger than 0 or left unspecified (meaning tracking latest)", what)
}
return seq, nil
}
func checkModelValidationSetMode(headers map[string]any, what string) (ModelValidationSetMode, error) {
modeStr, err := checkNotEmptyStringWhat(headers, "mode", what)
if err != nil {
return "", err
}
if modeStr != "" && !strutil.ListContains(validModelValidationSetModes, modeStr) {
return "", fmt.Errorf("\"mode\" %s must be %s, not %q", what, strings.Join(validModelValidationSetModes, "|"), modeStr)
}
return ModelValidationSetMode(modeStr), nil
}
func checkModelValidationSet(headers map[string]any, brandID string) (*ModelValidationSet, error) {
name, err := checkStringMatchesWhat(headers, "name", "of validation-set", validValidationSetName)
if err != nil {
return nil, err
}
what := fmt.Sprintf("of validation-set %q", name)
accountID, err := checkModelValidationSetAccountID(headers, what, brandID)
if err != nil {
return nil, err
}
what = fmt.Sprintf("of validation-set \"%s/%s\"", accountID, name)
seq, err := checkOptionalModelValidationSetSequence(headers, what)
if err != nil {
return nil, err
}
mode, err := checkModelValidationSetMode(headers, what)
if err != nil {
return nil, err
}
return &ModelValidationSet{
AccountID: accountID,
Name: name,
Sequence: seq,
Mode: mode,
}, nil
}
func checkOptionalModelValidationSets(headers map[string]any, brandID string) ([]*ModelValidationSet, error) {
valSets, ok := headers["validation-sets"]
if !ok {
return nil, nil
}
entries, ok := valSets.([]any)
if !ok {
return nil, fmt.Errorf(`"validation-sets" must be a list of validation sets`)
}
vss := make([]*ModelValidationSet, len(entries))
seen := make(map[string]bool, len(entries))
for i, entry := range entries {
data, ok := entry.(map[string]any)
if !ok {
return nil, fmt.Errorf(`entry in "validation-sets" is not a valid validation-set`)
}
vs, err := checkModelValidationSet(data, brandID)
if err != nil {
return nil, err
}
vsKey := fmt.Sprintf("%s/%s", vs.AccountID, vs.Name)
if seen[vsKey] {
return nil, fmt.Errorf("cannot add validation set %q twice", vsKey)
}
vss[i] = vs
seen[vsKey] = true
}
return vss, nil
}
var (
modelMandatory = []string{"architecture", "gadget", "kernel"}
extendedMandatory = []string{"architecture", "base"}
extendedSnapsConflicting = []string{"gadget", "kernel", "required-snaps"}
classicModelOptional = []string{"architecture", "gadget"}
// The distribution header must be a valid ID according to
// https://www.freedesktop.org/software/systemd/man/os-release.html#ID=
validDistribution = regexp.MustCompile(`^[a-z0-9._-]*$`)
)
func assembleModel(assert assertionBase) (Assertion, error) {
err := checkAuthorityMatchesBrand(&assert)
if err != nil {
return nil, err
}
_, err = checkModel(assert.headers)
if err != nil {
return nil, err
}
classic, err := checkOptionalBool(assert.headers, "classic")
if err != nil {
return nil, err
}
// Core 20 extended snaps header
extendedSnaps, extended := assert.headers["snaps"]
if extended {
for _, conflicting := range extendedSnapsConflicting {
if _, ok := assert.headers[conflicting]; ok {
return nil, fmt.Errorf("cannot specify separate %q header once using the extended snaps header", conflicting)
}
}
} else {
if _, ok := assert.headers["grade"]; ok {
return nil, fmt.Errorf("cannot specify a grade for model without the extended snaps header")
}
if _, ok := assert.headers["storage-safety"]; ok {
return nil, fmt.Errorf("cannot specify storage-safety for model without the extended snaps header")
}
}
if classic && !extended {
if _, ok := assert.headers["kernel"]; ok {
return nil, fmt.Errorf("cannot specify a kernel with a non-extended classic model")
}
if _, ok := assert.headers["base"]; ok {
return nil, fmt.Errorf("cannot specify a base with a non-extended classic model")
}
}
// distribution mandatory for classic with extended snaps, not
// allowed otherwise.
if classic && extended {
_, err := checkStringMatches(assert.headers, "distribution", validDistribution)
if err != nil {
return nil, fmt.Errorf("%v, see distribution ID in os-release spec", err)
}
} else if _, ok := assert.headers["distribution"]; ok {
return nil, fmt.Errorf("cannot specify distribution for model unless it is classic and has an extended snaps header")
}
checker := checkNotEmptyString
toCheck := modelMandatory
if extended {
toCheck = extendedMandatory
} else if classic {
checker = checkOptionalString
toCheck = classicModelOptional
}
for _, h := range toCheck {
if _, err := checker(assert.headers, h); err != nil {
return nil, err
}
}
// base, if provided, must be a valid snap name too
var baseSnap *ModelSnap
base, err := checkOptionalString(assert.headers, "base")
if err != nil {
return nil, err
}
if base != "" {
baseSnap, err = checkRequiredSnap(base, "base", "base")
if err != nil {
return nil, err
}
}
// store is optional but must be a string, defaults to the ubuntu store
if _, err = checkOptionalString(assert.headers, "store"); err != nil {
return nil, err
}
// display-name is optional but must be a string
if _, err = checkOptionalString(assert.headers, "display-name"); err != nil {
return nil, err
}
var modSnaps *modelSnaps
grade := ModelGradeUnset
storageSafety := StorageSafetyUnset
if extended {
gradeStr, err := checkOptionalString(assert.headers, "grade")
if err != nil {
return nil, err
}
if gradeStr != "" && !strutil.ListContains(validModelGrades, gradeStr) {
return nil, fmt.Errorf("grade for model must be %s, not %q", strings.Join(validModelGrades, "|"), gradeStr)
}
grade = ModelSigned
if gradeStr != "" {
grade = ModelGrade(gradeStr)
}
storageSafetyStr, err := checkOptionalString(assert.headers, "storage-safety")
if err != nil {
return nil, err
}
if storageSafetyStr != "" && !strutil.ListContains(validStorageSafeties, storageSafetyStr) {
return nil, fmt.Errorf("storage-safety for model must be %s, not %q", strings.Join(validStorageSafeties, "|"), storageSafetyStr)
}
if storageSafetyStr != "" {
storageSafety = StorageSafety(storageSafetyStr)
} else {
if grade == ModelSecured {
storageSafety = StorageSafetyEncrypted
} else {
storageSafety = StorageSafetyPreferEncrypted
}
}
if grade == ModelSecured && storageSafety != StorageSafetyEncrypted {
return nil, fmt.Errorf(`secured grade model must not have storage-safety overridden, only "encrypted" is valid`)
}
modSnaps, err = checkExtendedSnaps(extendedSnaps, base, grade, classic)
if err != nil {
return nil, err
}
hasKernel := modSnaps.kernel != nil
hasGadget := modSnaps.gadget != nil
if !classic {
if !hasGadget {
return nil, fmt.Errorf(`one "snaps" header entry must specify the model gadget`)
}
if !hasKernel {
return nil, fmt.Errorf(`one "snaps" header entry must specify the model kernel`)
}
} else {
if hasKernel && !hasGadget {
return nil, fmt.Errorf("cannot specify a kernel in an extended classic model without a model gadget")
}
}
if modSnaps.base == nil {
// complete with defaults,
// the assumption is that base names are very stable
// essentially fixed
modSnaps.base = baseSnap
snapID := naming.WellKnownSnapID(modSnaps.base.Name)
if snapID == "" && grade != ModelDangerous {
return nil, fmt.Errorf(`cannot specify not well-known base %q without a corresponding "snaps" header entry`, modSnaps.base.Name)
}
modSnaps.base.SnapID = snapID
modSnaps.base.Modes = essentialSnapModes
modSnaps.base.DefaultChannel = "latest/stable"
}
} else {
modSnaps = &modelSnaps{
base: baseSnap,
}
// kernel/gadget must be valid snap names and can have (optional) tracks
// - validate those
modSnaps.kernel, err = checkSnapWithTrack(assert.headers, "kernel")
if err != nil {
return nil, err
}
modSnaps.gadget, err = checkSnapWithTrack(assert.headers, "gadget")
if err != nil {
return nil, err
}
// required snap must be valid snap names
reqSnaps, err := checkStringList(assert.headers, "required-snaps")
if err != nil {
return nil, err
}
for _, name := range reqSnaps {
reqSnap, err := checkRequiredSnap(name, "required-snaps", "")
if err != nil {
return nil, err
}
modSnaps.snapsNoEssential = append(modSnaps.snapsNoEssential, reqSnap)
}
}
brandID := assert.HeaderString("brand-id")
serialAuthority, err := checkOptionalSerialAuthority(assert.headers, brandID)
if err != nil {
return nil, err
}
sysUserAuthority, err := checkOptionalSystemUserAuthority(assert.headers, brandID)
if err != nil {
return nil, err
}
preseedAuthority, err := checkOptionalPreseedAuthority(assert.headers, brandID)
if err != nil {
return nil, err
}
timestamp, err := checkRFC3339Date(assert.headers, "timestamp")
if err != nil {
return nil, err
}
allSnaps, requiredWithEssentialSnaps, numEssentialSnaps := modSnaps.list()
valSets, err := checkOptionalModelValidationSets(assert.headers, brandID)
if err != nil {
return nil, err
}
// NB:
// * core is not supported at this time, it defaults to ubuntu-core
// in prepare-image until rename and/or introduction of the header.
// * some form of allowed-modes, class are postponed,
//
// prepare-image takes care of not allowing them for now
// ignore extra headers and non-empty body for future compatibility
return &Model{
assertionBase: assert,
classic: classic,
baseSnap: modSnaps.base,
gadgetSnap: modSnaps.gadget,
kernelSnap: modSnaps.kernel,
grade: grade,
storageSafety: storageSafety,
allSnaps: allSnaps,
requiredWithEssentialSnaps: requiredWithEssentialSnaps,
numEssentialSnaps: numEssentialSnaps,
validationSets: valSets,
serialAuthority: serialAuthority,
sysUserAuthority: sysUserAuthority,
preseedAuthority: preseedAuthority,
timestamp: timestamp,
}, nil
}
|