forked from canonical/snapd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.go
More file actions
1777 lines (1576 loc) · 55.3 KB
/
Copy pathhelpers.go
File metadata and controls
1777 lines (1576 loc) · 55.3 KB
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) 2016-2024 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 ifacestate
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"sort"
"strings"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/features"
"github.com/snapcore/snapd/interfaces"
"github.com/snapcore/snapd/interfaces/builtin"
"github.com/snapcore/snapd/interfaces/policy"
"github.com/snapcore/snapd/interfaces/utils"
"github.com/snapcore/snapd/jsonutil"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/overlord/assertstate"
"github.com/snapcore/snapd/overlord/configstate/config"
"github.com/snapcore/snapd/overlord/ifacestate/schema"
"github.com/snapcore/snapd/overlord/snapstate"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/systemd"
"github.com/snapcore/snapd/timings"
)
func init() {
snapstate.HasActiveConnection = hasActiveConnection
}
var (
snapdAppArmorServiceIsDisabled = snapdAppArmorServiceIsDisabledImpl
writeSystemKey = interfaces.WriteSystemKey
)
func (m *InterfaceManager) selectInterfaceMapper(appSets []*interfaces.SnapAppSet) {
for _, set := range appSets {
if set.Info().Type() == snap.TypeSnapd {
mapper = &CoreSnapdSystemMapper{}
break
}
}
}
func (m *InterfaceManager) addInterfaces(extra []interfaces.Interface) error {
for _, iface := range builtin.Interfaces() {
if err := m.repo.AddInterface(iface); err != nil {
return err
}
}
for _, iface := range extra {
if err := m.repo.AddInterface(iface); err != nil {
return err
}
}
return nil
}
func (m *InterfaceManager) securityBackendOpts() (*interfaces.SecurityBackendOptions, error) {
// get the snapd snap info if it is installed
var snapdSnap snapstate.SnapState
var snapdSnapInfo *snap.Info
err := snapstate.Get(m.state, "snapd", &snapdSnap)
if err != nil && !errors.Is(err, state.ErrNoState) {
return nil, fmt.Errorf("cannot access snapd snap state: %w", err)
}
if err == nil {
snapdSnapInfo, err = snapdSnap.CurrentInfo()
if err != nil && err != snapstate.ErrNoCurrent {
return nil, fmt.Errorf("cannot access snapd snap info: %w", err)
}
}
// get the core snap info if it is installed
var coreSnap snapstate.SnapState
var coreSnapInfo *snap.Info
err = snapstate.Get(m.state, "core", &coreSnap)
if err != nil && !errors.Is(err, state.ErrNoState) {
return nil, fmt.Errorf("cannot access core snap state: %w", err)
}
if err == nil {
coreSnapInfo, err = coreSnap.CurrentInfo()
if err != nil && err != snapstate.ErrNoCurrent {
return nil, fmt.Errorf("cannot access core snap info: %w", err)
}
}
opts := interfaces.SecurityBackendOptions{
Preseed: m.preseed,
CoreSnapInfo: coreSnapInfo,
SnapdSnapInfo: snapdSnapInfo,
}
return &opts, nil
}
func (m *InterfaceManager) addBackends(extra []interfaces.SecurityBackend) error {
opts, err := m.securityBackendOpts()
if err != nil {
return err
}
for _, backend := range allSecurityBackends() {
if err := backend.Initialize(opts); err != nil {
return err
}
if err := m.repo.AddBackend(backend); err != nil {
return err
}
}
for _, backend := range extra {
if err := backend.Initialize(opts); err != nil {
return err
}
if err := m.repo.AddBackend(backend); err != nil {
return err
}
}
return nil
}
// Reinitializes compatible backends which have previously been added to the
// repository.
func (m *InterfaceManager) reinitializeBackends(tm timings.Measurer) error {
for _, b := range m.repo.Backends() {
rb, ok := b.(interfaces.ReinitializableSecurityBackend)
if !ok {
continue
}
var err error
timings.Run(tm, "reinitialize-security-backend", fmt.Sprintf("reinitialize %q security backend", b.Name()),
func(nesttm timings.Measurer) {
err = rb.Reinitialize()
})
if err != nil {
return fmt.Errorf("cannot reinitialize backend %q: %w", b.Name(), err)
}
}
return nil
}
func (m *InterfaceManager) addAppSets(appSets []*interfaces.SnapAppSet) error {
for _, set := range appSets {
if err := addImplicitInterfaces(m.state, set.Info()); err != nil {
return err
}
if err := m.repo.AddAppSet(set); err != nil {
logger.Noticef("cannot add app set for snap %q to interface repository: %s", set.Info().InstanceName(), err)
}
}
return nil
}
func (m *InterfaceManager) profilesNeedRegeneration() bool {
return profilesNeedRegenerationImpl(m)
}
var profilesNeedRegenerationImpl = func(m *InterfaceManager) bool {
extraData := interfaces.SystemKeyExtraData{
AppArmorPrompting: m.useAppArmorPrompting,
}
mismatch, _, err := interfaces.SystemKeyMismatch(extraData)
if err != nil {
logger.Noticef("error trying to compare the snap system key: %v", err)
return true
}
return mismatch
}
// Checks whether AppArmor Prompting should be used. Caller must lock m.state.
func (m *InterfaceManager) assessAppArmorPrompting() bool {
tr := config.NewTransaction(m.state)
if promptingEnabled, err := features.Flag(tr, features.AppArmorPrompting); err == nil {
supported, _ := features.AppArmorPrompting.IsSupported()
// If error while getting AppArmorPrompting flag, don't include it
return promptingEnabled && supported
}
return false
}
// snapdAppArmorServiceIsDisabledImpl returns true if the snapd.apparmor
// service unit exists but is disabled
func snapdAppArmorServiceIsDisabledImpl() bool {
sysd := systemd.New(systemd.SystemMode, nil)
isEnabled, err := sysd.IsEnabled("snapd.apparmor")
return err == nil && !isEnabled
}
// regenerateAllSecurityProfiles will regenerate all security profiles. This
// function is expected to be called with the state locked, though in some
// scenarios one may want to temporarily unlock the state for the duration of
// security backends executing their setup.
func (m *InterfaceManager) regenerateAllSecurityProfiles(tm timings.Measurer, unlockState bool) error {
// Get all the security backends
securityBackends := m.repo.Backends()
// Get all the snap infos
appSets, err := snapsWithSecurityProfiles(m.state)
if err != nil {
return err
}
precompOpts := make(map[string]interfaces.ConfinementOptions, len(appSets))
computeConfinementOpts := func(instanceName string) (interfaces.ConfinementOptions, error) {
var snapst snapstate.SnapState
if err := snapstate.Get(m.state, instanceName, &snapst); err != nil {
return interfaces.ConfinementOptions{}, err
}
snapInfo, err := snapst.CurrentInfo()
if err != nil {
return interfaces.ConfinementOptions{}, err
}
opts, err := m.buildConfinementOptions(m.state, nil, snapInfo, snapst.Flags)
if err != nil {
return interfaces.ConfinementOptions{}, err
}
return opts, nil
}
for _, set := range appSets {
if err := addImplicitInterfaces(m.state, set.Info()); err != nil {
return err
}
instanceName := set.InstanceName()
optsForAppSet, err := computeConfinementOpts(instanceName)
if err != nil {
logger.Noticef("cannot get confinement options for snap %q: %v", instanceName, err)
continue
}
precompOpts[instanceName] = optsForAppSet
}
// The reason the system key is unlinked is to prevent snapd from believing
// that an old system key is valid and represents security setup
// established in the system. If snapd is reverted following a failed
// startup then system key may match the system key that used to be on disk
// but some of the system security may have been changed by the new snapd,
// the one that was reverted. Unlinking avoids such possibility, forcing
// old snapd to re-establish proper security view.
shouldWriteSystemKey := true
os.Remove(dirs.SnapSystemKeyFile)
precomputedConfinementOpts := func(instanceName string) interfaces.ConfinementOptions {
// options or default zero value
return precompOpts[instanceName]
}
func() {
if unlockState {
m.state.Unlock()
defer m.state.Lock()
}
// For each backend:
for _, backend := range securityBackends {
if backend.Name() == "" {
continue // Test backends have no name, skip them to simplify testing.
}
// Default setup context for regeneration
defaultSetupCtx := func(snapName string) interfaces.SetupContext {
return interfaces.SetupContext{
Reason: interfaces.SnapSetupReasonOther,
// not running in task context, nothing can be deferred
CanDelayEffects: false,
}
}
if errors := interfaces.SetupMany(m.repo, backend, appSets, precomputedConfinementOpts, defaultSetupCtx, tm); len(errors) > 0 {
logger.Noticef("cannot regenerate %s profiles", backend.Name())
for _, err := range errors {
logger.Notice(err.Error())
}
shouldWriteSystemKey = false
}
}
}()
if shouldWriteSystemKey {
extraData := interfaces.SystemKeyExtraData{
AppArmorPrompting: m.useAppArmorPrompting,
}
if err := writeSystemKey(extraData); err != nil {
logger.Noticef("cannot write system key: %v", err)
}
}
return nil
}
// renameCorePlugConnection renames one connection from "core-support" plug to
// slot so that the plug name is "core-support-plug" while the slot is
// unchanged. This matches a change introduced in 2.24, where the core snap no
// longer has the "core-support" plug as that was clashing with the slot with
// the same name.
func (m *InterfaceManager) renameCorePlugConnection() error {
conns, err := getConns(m.state)
if err != nil {
return err
}
const oldPlugName = "core-support"
const newPlugName = "core-support-plug"
// old connection, note that slotRef is the same in both
slotRef := interfaces.SlotRef{Snap: "core", Name: oldPlugName}
oldPlugRef := interfaces.PlugRef{Snap: "core", Name: oldPlugName}
oldConnRef := interfaces.ConnRef{PlugRef: oldPlugRef, SlotRef: slotRef}
oldID := oldConnRef.ID()
// if the old connection is saved, replace it with the new connection
if cState, ok := conns[oldID]; ok {
newPlugRef := interfaces.PlugRef{Snap: "core", Name: newPlugName}
newConnRef := interfaces.ConnRef{PlugRef: newPlugRef, SlotRef: slotRef}
newID := newConnRef.ID()
delete(conns, oldID)
conns[newID] = cState
setConns(m.state, conns)
}
return nil
}
// removeStaleConnections removes stale connections left by some older versions of snapd.
// Connection is considered stale if the snap on either end of the connection doesn't exist anymore.
// XXX: this code should eventually go away.
var removeStaleConnections = func(st *state.State) error {
conns, err := getConns(st)
if err != nil {
return err
}
var staleConns []string
brokenCache := make(map[string]bool)
isBrokenCached := func(snapName string) (bool, error) {
broken, ok := brokenCache[snapName]
if ok {
return broken, nil
}
broken, err := isBroken(st, snapName)
if err != nil {
return false, err
}
brokenCache[snapName] = broken
return broken, nil
}
for id := range conns {
connRef, err := interfaces.ParseConnRef(id)
if err != nil {
return err
}
var snapst snapstate.SnapState
if err := snapstate.Get(st, connRef.PlugRef.Snap, &snapst); err != nil {
if !errors.Is(err, state.ErrNoState) {
return err
}
broken, err := isBrokenCached(connRef.SlotRef.Snap)
if err != nil {
return err
}
if broken {
continue
}
staleConns = append(staleConns, id)
continue
}
if err := snapstate.Get(st, connRef.SlotRef.Snap, &snapst); err != nil {
if !errors.Is(err, state.ErrNoState) {
return err
}
broken, err := isBrokenCached(connRef.PlugRef.Snap)
if err != nil {
return err
}
if broken {
continue
}
staleConns = append(staleConns, id)
continue
}
}
if len(staleConns) > 0 {
for _, id := range staleConns {
delete(conns, id)
}
setConns(st, conns)
logger.Noticef("removed stale connections: %s", strings.Join(staleConns, ", "))
}
return nil
}
func isBroken(st *state.State, snapName string) (bool, error) {
var snapst snapstate.SnapState
err := snapstate.Get(st, snapName, &snapst)
if errors.Is(err, state.ErrNoState) {
return false, nil
}
if err != nil {
return false, err
}
snapInfo, _ := snapst.CurrentInfo()
if snapInfo != nil && snapInfo.Broken != "" {
return true, nil
}
return false, nil
}
func cloneConnState(connState *schema.ConnState) *schema.ConnState {
clone := *connState
cloneAttrs := func(attrs map[string]any) map[string]any {
if attrs == nil {
return nil
}
return utils.CopyAttributes(attrs)
}
clone.StaticPlugAttrs = cloneAttrs(connState.StaticPlugAttrs)
clone.DynamicPlugAttrs = cloneAttrs(connState.DynamicPlugAttrs)
clone.StaticSlotAttrs = cloneAttrs(connState.StaticSlotAttrs)
clone.DynamicSlotAttrs = cloneAttrs(connState.DynamicSlotAttrs)
return &clone
}
// snapshotChangedConnectionsForUndo records original states for connections
// changed by setup-profiles so undo can restore them, if needed.
func snapshotChangedConnectionsForUndo(task *state.Task, instanceName string, changedConns map[string]*schema.ConnState) error {
if len(changedConns) == 0 {
return nil
}
// if this isn't the setup-profiles task that is going to handle the undo,
// then we don't need to keep track of these on the task
if !shouldUndoSetupProfiles(task, instanceName) {
return nil
}
var connectionSnapshot map[string]*schema.ConnState
err := task.Get("changed-connection-snapshot", &connectionSnapshot)
if err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
if connectionSnapshot == nil {
connectionSnapshot = make(map[string]*schema.ConnState)
}
for connID, connState := range changedConns {
if connectionSnapshot[connID] != nil {
// a setup-profiles task can be retried after saving the connection
// states and unlocking for backend setup. keep the first snapshot.
continue
}
connectionSnapshot[connID] = connState
}
task.Set("changed-connection-snapshot", connectionSnapshot)
return nil
}
// restoreConnectionsForSetupProfiles restores connection states saved on a
// setup-profiles task.
func restoreConnectionsForSetupProfiles(task *state.Task) error {
var connectionSnapshot map[string]*schema.ConnState
err := task.Get("changed-connection-snapshot", &connectionSnapshot)
if errors.Is(err, state.ErrNoState) {
return nil
}
if err != nil {
return err
}
st := task.State()
conns, err := getConns(st)
if err != nil {
return err
}
for connID, connState := range connectionSnapshot {
conns[connID] = connState
}
setConns(st, conns)
return nil
}
// reloadConnections reloads connections stored in the state in the repository.
// Using non-empty snapName the operation can be scoped to connections
// affecting a given snap.
//
// The return value is the list of reloaded connection IDs, plus the original
// connection states whose persisted state was changed.
func (m *InterfaceManager) reloadConnections(snapName string) (reloadedConnectionIDs []string, changedConns map[string]*schema.ConnState, err error) {
conns, err := getConns(m.state)
if err != nil {
return nil, nil, err
}
var policyChecker interfaces.PolicyFunc
var autoChecker *autoConnectChecker
var connChecker *connectChecker
deviceCtx, err := snapstate.DeviceCtx(m.state, nil, nil)
if errors.Is(err, state.ErrNoState) {
// everything else is a noop, as no model means no connections
// to reload
return nil, nil, nil
} else if err != nil {
return nil, nil, err
}
autoChecker, err = newAutoConnectChecker(m.state, m.repo, deviceCtx)
if err != nil {
return nil, nil, err
}
connChecker, err = newConnectChecker(m.state, deviceCtx)
if err != nil {
return nil, nil, err
}
connStateChanged := false
changedConns = make(map[string]*schema.ConnState)
var reloadedConnections []string
ConnsLoop:
for connId, connState := range conns {
// Skip entries that just mark a connection as undesired. Those don't
// carry attributes that can go stale. In the same spirit, skip
// information about hotplug connections that don't have the associated
// hotplug hardware.
if connState.Undesired || connState.HotplugGone {
continue
}
connRef, err := interfaces.ParseConnRef(connId)
if err != nil {
return nil, nil, err
}
// Apply filtering, this allows us to reload only a subset of
// connections (and similarly, refresh the static attributes of only a
// subset of connections).
if snapName != "" && connRef.PlugRef.Snap != snapName && connRef.SlotRef.Snap != snapName {
continue
}
plugInfo := m.repo.Plug(connRef.PlugRef.Snap, connRef.PlugRef.Name)
slotInfo := m.repo.Slot(connRef.SlotRef.Snap, connRef.SlotRef.Name)
// The connection refers to a plug or slot that doesn't exist anymore, e.g. because of a refresh
// to a new snap revision that doesn't have the given plug/slot.
if plugInfo == nil || slotInfo == nil {
// automatic connection can simply be removed (it will be re-created automatically if needed)
// as long as it wasn't disconnected manually; note that undesired flag is taken care of at
// the beginning of the loop.
if connState.Auto && !connState.ByGadget && connState.Interface != "core-support" {
// only do anything about this connection if snap isn't in a broken state, otherwise
// leave the connection untouched.
for _, snapName := range []string{connRef.PlugRef.Snap, connRef.SlotRef.Snap} {
broken, err := isBroken(m.state, snapName)
if err != nil {
return nil, nil, err
}
if broken {
logger.Noticef("Snap %q is broken, ignored by reloadConnections", snapName)
continue ConnsLoop
}
}
changedConns[connId] = cloneConnState(connState)
delete(conns, connId)
connStateChanged = true
}
// otherwise keep it and silently ignore, e.g. in case of a revert.
continue
}
var updateStaticAttrs bool
staticPlugAttrs := connState.StaticPlugAttrs
staticSlotAttrs := connState.StaticSlotAttrs
newStaticPlugAttrs := utils.NormalizeInterfaceAttributes(plugInfo.Attrs).(map[string]any)
newStaticSlotAttrs := utils.NormalizeInterfaceAttributes(slotInfo.Attrs).(map[string]any)
// if the interface was originally autoconnected, update the static attrs if it would
// still be allowed to autoconnect. Otherwise, update the static attrs if it would still
// be allowed to regular connect.
if connState.Auto && !connState.ByGadget {
policyChecker = func(cplug *interfaces.ConnectedPlug, cslot *interfaces.ConnectedSlot) (bool, error) {
iface, err := interfaces.ByName(cplug.Interface())
if err != nil {
return false, err
}
if !iface.AutoConnect(plugInfo, slotInfo) {
return false, nil
}
ok, _, err := autoChecker.check(cplug, cslot)
return ok, err
}
} else {
policyChecker = connChecker.check
}
plugAppSet, err := interfaces.NewSnapAppSet(plugInfo.Snap, nil)
if err != nil {
return nil, nil, err
}
slotAppSet, err := interfaces.NewSnapAppSet(slotInfo.Snap, nil)
if err != nil {
return nil, nil, err
}
cplug := interfaces.NewConnectedPlug(plugInfo, plugAppSet, newStaticPlugAttrs, connState.DynamicPlugAttrs)
cslot := interfaces.NewConnectedSlot(slotInfo, slotAppSet, newStaticSlotAttrs, connState.DynamicSlotAttrs)
ok, err := policyChecker(cplug, cslot)
if !ok || err != nil {
logger.Noticef("cannot refresh static attributes of the connection %q", connId)
} else {
staticPlugAttrs = newStaticPlugAttrs
staticSlotAttrs = newStaticSlotAttrs
updateStaticAttrs = true
}
// Note: reloaded connections are not checked against policy again, and also we don't call BeforeConnect* methods on them.
if _, err := m.repo.Connect(connRef, staticPlugAttrs, connState.DynamicPlugAttrs, staticSlotAttrs, connState.DynamicSlotAttrs, nil); err != nil {
logger.Noticef("%s", err)
} else {
// If the connection succeeded update the connection state and keep
// track of the snaps that were affected.
reloadedConnections = append(reloadedConnections, connId)
if updateStaticAttrs {
changedConns[connId] = cloneConnState(connState)
connState.StaticPlugAttrs = staticPlugAttrs
connState.StaticSlotAttrs = staticSlotAttrs
connStateChanged = true
}
}
}
if connStateChanged {
setConns(m.state, conns)
}
return reloadedConnections, changedConns, nil
}
// removeConnections disconnects all connections of the snap in the repo. It should only be used if the snap
// has no connections in the state. State must be locked by the caller.
func (m *InterfaceManager) removeConnections(snapName string) error {
conns, err := getConns(m.state)
if err != nil {
return err
}
for id := range conns {
connRef, err := interfaces.ParseConnRef(id)
if err != nil {
return err
}
if connRef.PlugRef.Snap == snapName || connRef.SlotRef.Snap == snapName {
return fmt.Errorf("internal error: cannot remove connections of snap %s from the repository while its connections are present in the state", snapName)
}
}
repoConns, err := m.repo.Connections(snapName)
if err != nil {
return fmt.Errorf("internal error: %v", err)
}
for _, conn := range repoConns {
if err := m.repo.Disconnect(conn.PlugRef.Snap, conn.PlugRef.Name, conn.SlotRef.Snap, conn.SlotRef.Name); err != nil {
return fmt.Errorf("internal error: %v", err)
}
}
return nil
}
func (m *InterfaceManager) setupSecurityByBackend(task *state.Task, appSets []*interfaces.SnapAppSet, opts []interfaces.ConfinementOptions, sctxs map[string]interfaces.SetupContext, tm timings.Measurer) error {
if len(appSets) != len(opts) {
return fmt.Errorf("internal error: setupSecurityByBackend received an unexpected number of snaps (expected: %d, got %d)", len(opts), len(appSets))
}
confOpts := make(map[string]interfaces.ConfinementOptions, len(appSets))
for i, set := range appSets {
confOpts[set.InstanceName()] = opts[i]
}
st := task.State()
st.Unlock()
defer st.Lock()
// Setup all affected snaps, start with the most important security
// backend and run it for all snaps. See LP: 1802581
for _, backend := range m.repo.Backends() {
errs := interfaces.SetupMany(m.repo, backend, appSets, func(snapName string) interfaces.ConfinementOptions {
return confOpts[snapName]
}, func(snapName string) interfaces.SetupContext {
if ctx, ok := sctxs[snapName]; ok {
return ctx
}
return interfaces.SetupContext{}
}, tm)
if len(errs) > 0 {
// SetupMany processes all profiles and returns all encountered errors; report just the first one
return errs[0]
}
}
return nil
}
func (m *InterfaceManager) setupSnapSecurity(task *state.Task, appSet *interfaces.SnapAppSet, opts interfaces.ConfinementOptions, tm timings.Measurer) error {
sctxs := map[string]interfaces.SetupContext{
appSet.InstanceName(): {
Reason: interfaces.SnapSetupReasonOther,
// this is called only in the contexts where all backend effects
// are expected to be immediate
CanDelayEffects: false,
},
}
return m.setupSecurityByBackend(task, []*interfaces.SnapAppSet{appSet}, []interfaces.ConfinementOptions{opts}, sctxs, tm)
}
func (m *InterfaceManager) removeSnapSecurity(task *state.Task, instanceName string) error {
st := task.State()
for _, backend := range m.repo.Backends() {
st.Unlock()
err := backend.Remove(instanceName)
st.Lock()
if err != nil {
task.Errorf("cannot setup %s for snap %q: %s", backend.Name(), instanceName, err)
return err
}
}
return nil
}
func addHotplugSlot(st *state.State, repo *interfaces.Repository, stateSlots map[string]*HotplugSlotInfo, iface interfaces.Interface, slot *snap.SlotInfo) error {
if slot.HotplugKey == "" {
return fmt.Errorf("internal error: cannot store slot %q, not a hotplug slot", slot.Name)
}
if iface, ok := iface.(interfaces.SlotSanitizer); ok {
if err := iface.BeforePrepareSlot(slot); err != nil {
return fmt.Errorf("cannot sanitize hotplug slot %q for interface %s: %s", slot.Name, slot.Interface, err)
}
}
if err := repo.AddSlot(slot); err != nil {
return fmt.Errorf("cannot add hotplug slot %q for interface %s: %s", slot.Name, slot.Interface, err)
}
stateSlots[slot.Name] = &HotplugSlotInfo{
Name: slot.Name,
Interface: slot.Interface,
StaticAttrs: slot.Attrs,
HotplugKey: slot.HotplugKey,
HotplugGone: false,
}
setHotplugSlots(st, stateSlots)
logger.Debugf("added hotplug slot %s:%s of interface %s, hotplug key %q", slot.Snap.InstanceName(), slot.Name, slot.Interface, slot.HotplugKey)
return nil
}
type gadgetConnect struct {
st *state.State
task *state.Task
repo *interfaces.Repository
instanceName string
deviceCtx snapstate.DeviceContext
}
func newGadgetConnect(s *state.State, task *state.Task, repo *interfaces.Repository, instanceName string, deviceCtx snapstate.DeviceContext) *gadgetConnect {
return &gadgetConnect{
st: s,
task: task,
repo: repo,
instanceName: instanceName,
deviceCtx: deviceCtx,
}
}
// addGadgetConnections adds to newconns any applicable connections
// from the gadget connections stanza.
// conflictError is called to handle checkAutoconnectConflicts errors.
func (gc *gadgetConnect) addGadgetConnections(newconns map[string]*interfaces.ConnRef, conns map[string]*schema.ConnState, conflictError func(*state.Retry, error) error) error {
var seeded bool
err := gc.st.Get("seeded", &seeded)
if err != nil && !errors.Is(err, state.ErrNoState) {
return err
}
// we apply gadget connections only during seeding or a remodeling
if seeded && !gc.deviceCtx.ForRemodeling() {
return nil
}
task := gc.task
snapName := gc.instanceName
var snapst snapstate.SnapState
if err := snapstate.Get(gc.st, snapName, &snapst); err != nil {
return err
}
snapInfo, err := snapst.CurrentInfo()
if err != nil {
return err
}
snapID := snapInfo.SnapID
if snapID == "" {
// not a snap-id identifiable snap, skip
return nil
}
gconns, err := snapstate.GadgetConnections(gc.st, gc.deviceCtx)
if err != nil {
if errors.Is(err, state.ErrNoState) {
// no gadget yet, nothing to do
return nil
}
return err
}
// consider the gadget connect instructions
for _, gconn := range gconns {
var plugSnapName, slotSnapName string
if gconn.Plug.SnapID == snapID {
plugSnapName = snapName
}
if gconn.Slot.SnapID == snapID {
slotSnapName = snapName
}
if plugSnapName == "" && slotSnapName == "" {
// no match, nothing to do
continue
}
if plugSnapName == "" {
var err error
plugSnapName, err = resolveSnapIDToName(gc.st, gconn.Plug.SnapID)
if err != nil {
return err
}
}
plug := gc.repo.Plug(plugSnapName, gconn.Plug.Plug)
if plug == nil {
task.Logf("gadget connections: ignoring missing plug %s:%s", gconn.Plug.SnapID, gconn.Plug.Plug)
continue
}
if slotSnapName == "" {
var err error
slotSnapName, err = resolveSnapIDToName(gc.st, gconn.Slot.SnapID)
if err != nil {
return err
}
}
slot := gc.repo.Slot(slotSnapName, gconn.Slot.Slot)
if slot == nil {
task.Logf("gadget connections: ignoring missing slot %s:%s", gconn.Slot.SnapID, gconn.Slot.Slot)
continue
}
if err := addNewConnection(gc.st, task, newconns, conns, plug, slot, conflictError); err != nil {
return err
}
}
return nil
}
func addNewConnection(st *state.State, task *state.Task, newconns map[string]*interfaces.ConnRef, conns map[string]*schema.ConnState, plug *snap.PlugInfo, slot *snap.SlotInfo, conflictError func(*state.Retry, error) error) error {
connRef := interfaces.NewConnRef(plug, slot)
key := connRef.ID()
if _, ok := conns[key]; ok {
// Suggested connection already exist (or has
// Undesired flag set) so don't clobber it.
// NOTE: we don't log anything here as this is
// a normal and common condition.
return nil
}
if _, ok := newconns[key]; ok {
return nil
}
if task.Kind() == "auto-connect" {
ignore, err := findSymmetricAutoconnectTask(st, plug.Snap.InstanceName(), slot.Snap.InstanceName(), task)
if err != nil {
return err
}
if ignore {
return nil
}
}
if err := checkAutoconnectConflicts(st, task, plug.Snap.InstanceName(), slot.Snap.InstanceName()); err != nil {
retry, _ := err.(*state.Retry)
return conflictError(retry, err)
}
newconns[key] = connRef
return nil
}
func isContentCompatLabelEnabled(st *state.State) bool {
tr := config.NewTransaction(st)
enabled, err := features.Flag(tr, features.ContentCompatLabel)
if err != nil && !config.IsNoOption(err) {
_, confName := features.ContentCompatLabel.ConfigOption()
logger.Noticef("internal error: cannot check %q feature flag: %v", confName, err)
return false
}
return enabled
}
func allowCompatLabel(featureEnabled bool, interfaceName string) bool {
return featureEnabled || interfaceName != "content"
}
// DebugAutoConnectCheck is a hook that can be set to debug auto-connection
// candidates as they are checked.
var DebugAutoConnectCheck func(*policy.ConnectCandidate, interfaces.SideArity, error)
type autoConnectChecker struct {
st *state.State
repo *interfaces.Repository
deviceCtx snapstate.DeviceContext
cache map[string]*asserts.SnapDeclaration
baseDecl *asserts.BaseDeclaration
contentCompatEnabled bool
}
func newAutoConnectChecker(s *state.State, repo *interfaces.Repository, deviceCtx snapstate.DeviceContext) (*autoConnectChecker, error) {
baseDecl, err := assertstate.BaseDeclaration(s)
if err != nil {
return nil, fmt.Errorf("internal error: cannot find base declaration: %v", err)
}
return &autoConnectChecker{
st: s,
repo: repo,
deviceCtx: deviceCtx,
cache: make(map[string]*asserts.SnapDeclaration),
baseDecl: baseDecl,
contentCompatEnabled: isContentCompatLabelEnabled(s),
}, nil
}
func (c *autoConnectChecker) snapDeclaration(snapID string) (*asserts.SnapDeclaration, error) {
snapDecl := c.cache[snapID]
if snapDecl != nil {
return snapDecl, nil
}
snapDecl, err := assertstate.SnapDeclaration(c.st, snapID)
if err != nil {
return nil, err
}
c.cache[snapID] = snapDecl
return snapDecl, nil
}
func (c *autoConnectChecker) check(plug *interfaces.ConnectedPlug, slot *interfaces.ConnectedSlot) (bool, interfaces.SideArity, error) {
modelAs := c.deviceCtx.Model()
var storeAs *asserts.Store
if modelAs.Store() != "" {
var err error
storeAs, err = assertstate.Store(c.st, modelAs.Store())
if err != nil && !errors.Is(err, &asserts.NotFoundError{}) {
return false, nil, err
}
}
var plugDecl *asserts.SnapDeclaration
if plug.Snap().SnapID != "" {
var err error
plugDecl, err = c.snapDeclaration(plug.Snap().SnapID)
if err != nil {