-
Notifications
You must be signed in to change notification settings - Fork 301
Expand file tree
/
Copy pathuvm.go
More file actions
1606 lines (1426 loc) · 53.2 KB
/
Copy pathuvm.go
File metadata and controls
1606 lines (1426 loc) · 53.2 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
//go:build linux
// +build linux
package hcsv2
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strings"
"sync"
"syscall"
"time"
cgroup1stats "github.com/containerd/cgroups/v3/cgroup1/stats"
"github.com/mattn/go-shellwords"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
"github.com/Microsoft/hcsshim/internal/bridgeutils/gcserr"
"github.com/Microsoft/hcsshim/internal/debug"
"github.com/Microsoft/hcsshim/internal/guest/cgroup"
"github.com/Microsoft/hcsshim/internal/guest/prot"
"github.com/Microsoft/hcsshim/internal/guest/runtime"
specGuest "github.com/Microsoft/hcsshim/internal/guest/spec"
"github.com/Microsoft/hcsshim/internal/guest/stdio"
"github.com/Microsoft/hcsshim/internal/guest/storage"
"github.com/Microsoft/hcsshim/internal/guest/storage/overlay"
"github.com/Microsoft/hcsshim/internal/guest/storage/pci"
"github.com/Microsoft/hcsshim/internal/guest/storage/plan9"
"github.com/Microsoft/hcsshim/internal/guest/storage/pmem"
"github.com/Microsoft/hcsshim/internal/guest/storage/scsi"
"github.com/Microsoft/hcsshim/internal/guest/transport"
"github.com/Microsoft/hcsshim/internal/guestpath"
"github.com/Microsoft/hcsshim/internal/log"
"github.com/Microsoft/hcsshim/internal/logfields"
"github.com/Microsoft/hcsshim/internal/oci"
"github.com/Microsoft/hcsshim/internal/protocol/guestrequest"
"github.com/Microsoft/hcsshim/internal/protocol/guestresource"
"github.com/Microsoft/hcsshim/internal/verity"
"github.com/Microsoft/hcsshim/pkg/annotations"
"github.com/Microsoft/hcsshim/pkg/securitypolicy"
)
// UVMContainerID is the ContainerID that will be sent on any prot.MessageBase
// for V2 where the specific message is targeted at the UVM itself.
const UVMContainerID = "00000000-0000-0000-0000-000000000000"
// Prevent path traversal via malformed container / sandbox IDs. Container IDs
// can be either UVMContainerID, or a 64 character hex string. This is also used
// to check that sandbox IDs (which is also used in paths) are valid, which has
// the same format.
const validContainerIDRegexRaw = `[0-9a-fA-F]{64}`
var validContainerIDRegex = regexp.MustCompile("^" + validContainerIDRegexRaw + "$")
// idType just changes the error message
func checkValidContainerID(id string, idType string) error {
if id == UVMContainerID || validContainerIDRegex.MatchString(id) {
return nil
}
return errors.Errorf("invalid %s id: %s (must match %s)", idType, id, validContainerIDRegex.String())
}
// Cgroup path formats for pod and container cgroups within the UVM.
const (
// podCgroupPathFmt is the cgroup path for a pod (sandbox or standalone): /pods/{sandboxID}.
podCgroupPathFmt = "/pods/%s"
// containerCgroupPathFmt is the cgroup path for a workload container nested under its pod: /pods/{sandboxID}/{containerID}.
containerCgroupPathFmt = "/pods/%s/%s"
)
// pod tracks pod-level state within the UVM.
type pod struct {
sandboxID string
cgroupControl cgroup.Manager
containers map[string]bool
}
// Host is the structure tracking all UVM host state including all containers
// and processes.
type Host struct {
// containersMutex guards both containers and pods maps.
containersMutex sync.Mutex
containers map[string]*Container
pods map[string]*pod
stdioSlots []*stdio.ConnSlot
externalProcessesMutex sync.Mutex
externalProcesses map[int]*externalProcess
// sandboxRoots maps sandboxID to the resolved sandbox root directory.
// Populated via registerSandboxRoot during sandbox creation using
// the host-provided OCIBundlePath as source of truth.
// Lock ordering: containersMutex -> sandboxRootsMutex (never reverse).
sandboxRootsMutex sync.RWMutex
sandboxRoots map[string]string
rtime runtime.Runtime
vsock transport.Transport
devNullTransport transport.Transport
// state required for the security policy enforcement
securityOptions *securitypolicy.SecurityOptions
// hostMounts keeps the state of currently mounted devices and file systems,
// which is used for GCS hardening.
hostMounts *hostMounts
}
func NewHost(rtime runtime.Runtime, vsock transport.Transport, initialEnforcer securitypolicy.SecurityPolicyEnforcer, logWriter io.Writer) *Host {
securityPolicyOptions := securitypolicy.NewSecurityOptions(
initialEnforcer,
false,
"",
logWriter,
)
return &Host{
containers: make(map[string]*Container),
externalProcesses: make(map[int]*externalProcess),
pods: make(map[string]*pod),
sandboxRoots: make(map[string]string),
rtime: rtime,
vsock: vsock,
devNullTransport: &transport.DevNullTransport{},
hostMounts: newHostMounts(),
securityOptions: securityPolicyOptions,
}
}
// registerSandboxRoot stores the resolved sandbox root directory for a given sandbox ID.
// For virtual pods, it derives the shared root from OCIBundlePath's parent directory.
func (h *Host) registerSandboxRoot(sandboxID, ociBundlePath, virtualPodID string) (string, error) {
var sandboxRoot string
if virtualPodID != "" {
// Validate virtualPodID to prevent path traversal.
cleanID := filepath.Clean(virtualPodID)
if filepath.IsAbs(cleanID) || strings.Contains(cleanID, "..") {
return "", errors.Errorf("invalid virtual pod ID %q: path traversal attempt", virtualPodID)
}
sandboxRoot = filepath.Join(filepath.Dir(ociBundlePath), "virtual-pods", cleanID)
} else {
sandboxRoot = ociBundlePath
}
h.sandboxRootsMutex.Lock()
defer h.sandboxRootsMutex.Unlock()
h.sandboxRoots[sandboxID] = sandboxRoot
logrus.WithFields(logrus.Fields{
"sandboxID": sandboxID,
"sandboxRoot": sandboxRoot,
}).Debug("registered sandbox root")
return sandboxRoot, nil
}
// resolveSandboxRoot returns the resolved sandbox root for the given sandbox ID.
// Falls back to legacy path derivation if no mapping exists.
func (h *Host) resolveSandboxRoot(sandboxID string) string {
h.sandboxRootsMutex.RLock()
root, ok := h.sandboxRoots[sandboxID]
h.sandboxRootsMutex.RUnlock()
if ok {
return root
}
// Fallback to legacy derivation for backwards compatibility.
// TODO: remove fallback after shim v1 sunset
fallback := specGuest.SandboxRootDir(sandboxID)
logrus.WithFields(logrus.Fields{
"sandboxID": sandboxID,
"fallback": fallback,
}).Warn("sandbox root not found in mapping, falling back to legacy path derivation")
return fallback
}
// unregisterSandboxRoot removes the sandbox root mapping for a given sandbox ID.
func (h *Host) unregisterSandboxRoot(sandboxID string) {
h.sandboxRootsMutex.Lock()
defer h.sandboxRootsMutex.Unlock()
delete(h.sandboxRoots, sandboxID)
}
func (h *Host) SecurityPolicyEnforcer() securitypolicy.SecurityPolicyEnforcer {
return h.securityOptions.PolicyEnforcer
}
func (h *Host) SecurityOptions() *securitypolicy.SecurityOptions {
return h.securityOptions
}
func (h *Host) Transport() transport.Transport {
return h.vsock
}
// RegisterStdioSlots tracks per-process stdio so the bridge reconnect loop
// can disconnect them after live migration. Called from container Start,
// ExecProcess, and runExternalProcess after stdio.Connect. Any
// *stdio.ConnSlot in the set is added to the registry; nil entries and
// other transport.Connection types are ignored. Already-closed slots are
// compacted out on each call to bound the slice's growth.
func (h *Host) RegisterStdioSlots(set *stdio.ConnectionSet) {
if set == nil {
return
}
incoming := make([]*stdio.ConnSlot, 0, 3)
for _, c := range []transport.Connection{set.In, set.Out, set.Err} {
if slot, ok := c.(*stdio.ConnSlot); ok && slot != nil {
incoming = append(incoming, slot)
}
}
if len(incoming) == 0 {
return
}
h.containersMutex.Lock()
defer h.containersMutex.Unlock()
h.stdioSlots = compactStdioSlots(h.stdioSlots)
h.stdioSlots = append(h.stdioSlots, incoming...)
}
// DisconnectAllStdio drops the current connection on every tracked stdio
// slot. Called from the GCS reconnect loop after the bridge connection is
// lost. Relays park inside slot.Write until the host re-attaches stdio with
// a fresh connection; the producing process pauses naturally when its
// kernel pipe buffer fills.
//
// Each slot's Disconnect is wrapped in a recover so a single bad slot
// cannot break the loop and leave the rest of the container stdio without
// back pressure.
func (h *Host) DisconnectAllStdio() {
h.containersMutex.Lock()
h.stdioSlots = compactStdioSlots(h.stdioSlots)
slots := append([]*stdio.ConnSlot(nil), h.stdioSlots...)
h.containersMutex.Unlock()
for _, s := range slots {
func() {
defer func() {
if r := recover(); r != nil {
logrus.WithField("panic", r).Error("ConnSlot: Disconnect panicked")
}
}()
s.Disconnect()
}()
}
}
// compactStdioSlots returns a new slice with closed slots filtered out so
// the registry does not grow unbounded over the UVM lifetime.
func compactStdioSlots(slots []*stdio.ConnSlot) []*stdio.ConnSlot {
if len(slots) == 0 {
return slots[:0]
}
out := slots[:0]
for _, s := range slots {
if s.IsAlive() {
out = append(out, s)
}
}
return out
}
func (h *Host) RemoveContainer(id string) {
h.containersMutex.Lock()
defer h.containersMutex.Unlock()
c, ok := h.containers[id]
if !ok {
return
}
criType, isCRI := c.spec.Annotations[annotations.KubernetesContainerType]
// Do NOT call RemoveNetworkNamespace for virtual pod sandbox containers.
// The host-driven teardown path (TearDownNetworking → RemoveNetNS → removeNIC)
// removes adapters first and then the namespace. Calling it here would fail
// with "contains adapters" because the host hasn't removed them yet.
virtualPodID := c.spec.Annotations[annotations.VirtualPodID]
isVirtualPodSandbox := virtualPodID != "" && id == virtualPodID
if !isVirtualPodSandbox && (!isCRI || criType == "sandbox") {
if err := RemoveNetworkNamespace(context.Background(), id); err != nil {
logrus.WithError(err).WithField(logfields.ContainerID, id).Warn("failed to remove network namespace")
}
}
delete(h.containers, id)
// Clean up pod tracking. For standalone containers, sandboxID == id but
// no pod entry exists (createPodInUVM is only called for CRI sandboxes),
// so the lookup returns false and the block is skipped.
if pod, exists := h.pods[c.sandboxID]; exists {
delete(pod.containers, id)
// When the sandbox container itself is removed, tear down the pod.
if id == c.sandboxID {
if pod.cgroupControl != nil {
if err := pod.cgroupControl.Delete(); err != nil {
logrus.WithFields(logrus.Fields{
"sandboxID": c.sandboxID,
}).WithError(err).Warn("failed to delete pod cgroup")
}
}
delete(h.pods, c.sandboxID)
}
}
// Clean up the sandbox root mapping for sandbox containers.
if c.isSandbox {
h.unregisterSandboxRoot(id)
}
}
func (h *Host) GetCreatedContainer(id string) (*Container, error) {
h.containersMutex.Lock()
defer h.containersMutex.Unlock()
c, ok := h.containers[id]
if !ok {
return nil, gcserr.NewHresultError(gcserr.HrVmcomputeSystemNotFound)
}
if c.getStatus() != containerCreated {
return nil, fmt.Errorf("container is not in state \"created\": %w",
gcserr.NewHresultError(gcserr.HrVmcomputeInvalidState))
}
return c, nil
}
func (h *Host) AddContainer(id string, c *Container) error {
h.containersMutex.Lock()
defer h.containersMutex.Unlock()
if _, ok := h.containers[id]; ok {
return gcserr.NewHresultError(gcserr.HrVmcomputeSystemAlreadyExists)
}
h.containers[id] = c
return nil
}
// setupSandboxMountsPath creates the sandboxMounts directory from a resolved root.
func setupSandboxMountsPath(sandboxRoot string) (err error) {
mountPath := specGuest.SandboxMountsDirFromRoot(sandboxRoot)
if err := os.MkdirAll(mountPath, 0755); err != nil {
return errors.Wrapf(err, "failed to create sandboxMounts dir at %v", mountPath)
}
defer func() {
if err != nil {
_ = os.RemoveAll(mountPath)
}
}()
return storage.MountRShared(mountPath)
}
// setupSandboxTmpfsMountsPath creates the sandbox tmpfs mounts directory from a resolved root.
func setupSandboxTmpfsMountsPath(sandboxRoot string) (err error) {
tmpfsDir := specGuest.SandboxTmpfsMountsDirFromRoot(sandboxRoot)
if err := os.MkdirAll(tmpfsDir, 0755); err != nil {
return errors.Wrapf(err, "failed to create sandbox tmpfs mounts dir at %v", tmpfsDir)
}
defer func() {
if err != nil {
_ = os.RemoveAll(tmpfsDir)
}
}()
// mount a tmpfs at the tmpfsDir
// this ensures that the tmpfsDir is a mount point and not just a directory
// we don't care if it is already mounted, so ignore EBUSY
if err := unix.Mount("tmpfs", tmpfsDir, "tmpfs", 0, ""); err != nil && !errors.Is(err, unix.EBUSY) {
return errors.Wrapf(err, "failed to mount tmpfs at %s", tmpfsDir)
}
//TODO: should tmpfs be mounted as noexec?
return storage.MountRShared(tmpfsDir)
}
// setupSandboxHugePageMountsPath creates the hugepages mounts directory from a resolved root.
func setupSandboxHugePageMountsPath(sandboxRoot string) error {
mountPath := specGuest.SandboxHugePagesMountsDirFromRoot(sandboxRoot)
if err := os.MkdirAll(mountPath, 0755); err != nil {
return errors.Wrapf(err, "failed to create hugepage mounts dir at %v", mountPath)
}
return storage.MountRShared(mountPath)
}
// setupSandboxLogDir creates the directory to house all redirected stdio logs from a resolved root.
func setupSandboxLogDir(sandboxRoot string) error {
mountPath := specGuest.SandboxLogsDirFromRoot(sandboxRoot)
if err := mkdirAllModePerm(mountPath); err != nil {
return errors.Wrapf(err, "failed to create sandbox logs dir at %v", mountPath)
}
return nil
}
// TODO: unify workload and standalone logic for non-sandbox features (e.g., block devices, huge pages, uVM mounts)
// TODO(go1.24): use [os.Root] instead of `!strings.HasPrefix(<path>, <root>)`
// Returns whether this host has a security policy set, i.e. if it's running
// confidential containers.
func (h *Host) HasSecurityPolicy() bool {
return len(h.securityOptions.PolicyEnforcer.EncodedSecurityPolicy()) > 0
}
// For confidential containers, make sure that the host can't use unexpected
// bundle paths / scratch dir / rootfs
func checkContainerSettings(sandboxID, containerID string, settings *prot.VMHostedContainerSettingsV2) error {
if settings.OCISpecification == nil {
return errors.Errorf("OCISpecification is nil")
}
if settings.OCISpecification.Root == nil {
return errors.Errorf("OCISpecification.Root is nil")
}
// matches with CreateContainer / createLinuxContainerDocument in internal/hcsoci
containerRootInUVM := path.Join(guestpath.LCOWRootPrefixInUVM, containerID)
if settings.OCIBundlePath != containerRootInUVM {
return errors.Errorf("OCIBundlePath %q must equal expected %q",
settings.OCIBundlePath, containerRootInUVM)
}
expectedContainerRootfs := path.Join(containerRootInUVM, guestpath.RootfsPath)
if settings.OCISpecification.Root.Path != expectedContainerRootfs {
return errors.Errorf("OCISpecification.Root.Path %q must equal expected %q",
settings.OCISpecification.Root.Path, expectedContainerRootfs)
}
// matches with MountLCOWLayers
scratchDirPath := settings.ScratchDirPath
expectedScratchDirPathNonShared := path.Join(containerRootInUVM, guestpath.ScratchDir, containerID)
expectedScratchDirPathShared := path.Join(guestpath.LCOWRootPrefixInUVM, sandboxID, guestpath.ScratchDir, containerID)
if scratchDirPath != expectedScratchDirPathNonShared &&
scratchDirPath != expectedScratchDirPathShared {
return errors.Errorf("ScratchDirPath %q must be either %q or %q",
scratchDirPath, expectedScratchDirPathNonShared, expectedScratchDirPathShared)
}
if settings.OCISpecification.Hooks != nil {
return errors.Errorf("OCISpecification.Hooks must be nil.")
}
return nil
}
func (h *Host) CreateContainer(ctx context.Context, id string, settings *prot.VMHostedContainerSettingsV2) (_ *Container, err error) {
criType, isCRI := settings.OCISpecification.Annotations[annotations.KubernetesContainerType]
// Check for virtual pod annotation
virtualPodID := settings.OCISpecification.Annotations[annotations.VirtualPodID]
isVirtualPod := virtualPodID != ""
if h.HasSecurityPolicy() {
if err = checkValidContainerID(id, "container"); err != nil {
return nil, err
}
if virtualPodID != "" {
if err = checkValidContainerID(virtualPodID, "virtual pod"); err != nil {
return nil, err
}
}
}
// Special handling for virtual pod sandbox containers:
// The first container in a virtual pod (containerID == virtualPodID) should be treated as a sandbox
// even if the CRI annotation might indicate otherwise due to host-side UVM setup differences
if isVirtualPod && id == virtualPodID {
criType = "sandbox"
isCRI = true
logrus.WithFields(logrus.Fields{
logfields.ContainerID: id,
logfields.VirtualSandboxID: virtualPodID,
"originalCriType": settings.OCISpecification.Annotations[annotations.KubernetesContainerType],
}).Info("Virtual pod first container detected - treating as sandbox container")
}
c := &Container{
id: id,
vsock: h.vsock,
slotRegistry: h,
spec: settings.OCISpecification,
ociBundlePath: settings.OCIBundlePath,
isSandbox: criType == "sandbox",
exitType: prot.NtUnexpectedExit,
processes: make(map[uint32]*containerProcess),
scratchDirPath: settings.ScratchDirPath,
}
c.setStatus(containerCreating)
// Resolve sandboxID early so all downstream code uses the correct value.
// For sandbox containers, sandboxID == id (or virtualPodID for virtual pods).
// For workload containers, sandboxID comes from the KubernetesSandboxID annotation.
// For standalone containers, sandboxID == id.
sandboxID := id
if isVirtualPod {
sandboxID = virtualPodID
} else if criType == "container" {
sandboxID = settings.OCISpecification.Annotations[annotations.KubernetesSandboxID]
}
c.sandboxID = sandboxID
if err := h.AddContainer(id, c); err != nil {
return nil, err
}
defer func() {
if err != nil {
h.RemoveContainer(id)
}
}()
var namespaceID string
if isCRI {
switch criType {
case "sandbox":
namespaceID = specGuest.GetNetworkNamespaceID(settings.OCISpecification)
// Resolve the sandbox root from OCIBundlePath.
sandboxRoot, err := h.registerSandboxRoot(id, settings.OCIBundlePath, virtualPodID)
if err != nil {
return nil, err
}
c.sandboxRoot = sandboxRoot
err = setupSandboxContainerSpec(ctx, id, sandboxRoot, settings.OCISpecification)
if err != nil {
return nil, err
}
defer func() {
if err != nil {
_ = os.RemoveAll(settings.OCIBundlePath)
}
}()
if err = setupSandboxMountsPath(sandboxRoot); err != nil {
return nil, err
}
if err = setupSandboxTmpfsMountsPath(sandboxRoot); err != nil {
return nil, err
}
if err = setupSandboxHugePageMountsPath(sandboxRoot); err != nil {
return nil, err
}
if err = setupSandboxLogDir(sandboxRoot); err != nil {
return nil, err
}
if err := securitypolicy.ExtendPolicyWithNetworkingMounts(sandboxRoot, h.securityOptions.PolicyEnforcer, settings.OCISpecification); err != nil {
return nil, err
}
if err := h.createPodInUVM(sandboxID, settings.OCISpecification); err != nil {
return nil, err
}
case "container":
if h.HasSecurityPolicy() {
if err = checkValidContainerID(sandboxID, "sandbox"); err != nil {
return nil, err
}
}
if sandboxID == "" {
return nil, errors.Errorf("unsupported 'io.kubernetes.cri.sandbox-id': '%s'", sandboxID)
}
if err = h.createContainerInPod(sandboxID, id); err != nil {
return nil, err
}
sandboxRoot := h.resolveSandboxRoot(sandboxID)
c.sandboxRoot = sandboxRoot
if err = setupWorkloadContainerSpec(ctx, sandboxID, id, sandboxRoot, settings.OCISpecification, settings.OCIBundlePath); err != nil {
return nil, err
}
// Add SEV device when security policy is not empty, except when privileged annotation is
// set to "true", in which case all UVMs devices are added.
if h.HasSecurityPolicy() && !oci.ParseAnnotationsBool(ctx,
settings.OCISpecification.Annotations, annotations.LCOWPrivileged, false) {
if err := specGuest.AddDevSev(ctx, settings.OCISpecification); err != nil {
log.G(ctx).WithError(err).Debug("failed to add SEV device")
}
}
defer func() {
if err != nil {
_ = os.RemoveAll(settings.OCIBundlePath)
}
}()
if err := securitypolicy.ExtendPolicyWithNetworkingMounts(sandboxRoot, h.securityOptions.PolicyEnforcer, settings.OCISpecification); err != nil {
return nil, err
}
default:
return nil, errors.Errorf("unsupported 'io.kubernetes.cri.container-type': '%s'", criType)
}
} else {
// Standalone container: no pod entry is created.
namespaceID = specGuest.GetNetworkNamespaceID(settings.OCISpecification)
// Standalone uses OCIBundlePath directly as its root.
c.sandboxRoot = settings.OCIBundlePath
if err := setupStandaloneContainerSpec(ctx, id, settings.OCIBundlePath, settings.OCISpecification); err != nil {
return nil, err
}
defer func() {
if err != nil {
_ = os.RemoveAll(settings.OCIBundlePath)
}
}()
if err := securitypolicy.ExtendPolicyWithNetworkingMounts(c.sandboxRoot, h.securityOptions.PolicyEnforcer,
settings.OCISpecification); err != nil {
return nil, err
}
}
// don't specialize tee logs (both files and mounts) just for workload containers
// add log directory mount before enforcing (mount) policy
if logDirMount := settings.OCISpecification.Annotations[annotations.LCOWTeeLogDirMount]; logDirMount != "" {
settings.OCISpecification.Mounts = append(settings.OCISpecification.Mounts, specs.Mount{
Destination: logDirMount,
Type: "bind",
Source: specGuest.SandboxLogsDirFromRoot(c.sandboxRoot),
Options: []string{"bind"},
})
}
if h.HasSecurityPolicy() {
if err = checkContainerSettings(sandboxID, id, settings); err != nil {
return nil, err
}
}
user, groups, umask, err := h.securityOptions.PolicyEnforcer.GetUserInfo(settings.OCISpecification.Process, settings.OCISpecification.Root.Path)
if err != nil {
return nil, err
}
seccomp, err := securitypolicy.MeasureSeccompProfile(settings.OCISpecification.Linux.Seccomp)
if err != nil {
return nil, err
}
envToKeep, capsToKeep, allowStdio, err := h.securityOptions.PolicyEnforcer.EnforceCreateContainerPolicy(
ctx,
sandboxID,
id,
settings.OCISpecification.Process.Args,
settings.OCISpecification.Process.Env,
settings.OCISpecification.Process.Cwd,
settings.OCISpecification.Mounts,
isPrivilegedContainerCreationRequest(ctx, settings.OCISpecification),
settings.OCISpecification.Process.NoNewPrivileges,
user,
groups,
umask,
settings.OCISpecification.Process.Capabilities,
seccomp,
)
if err != nil {
return nil, errors.Wrapf(err, "container creation denied due to policy")
}
if !allowStdio {
// stdio access isn't allow for this container. Switch to the /dev/null
// transport that will eat all input/ouput.
c.vsock = h.devNullTransport
}
// delay creating the directory to house the container's stdio until after we've verified
// policy on log settings.
// TODO: is using allowStdio appropriate here, since longs aren't leaving the uVM?
if logPath := settings.OCISpecification.Annotations[annotations.LCOWTeeLogPath]; logPath != "" {
if !allowStdio {
return nil, errors.Errorf("teeing container stdio to log path %q denied due to policy not allowing stdio access", logPath)
}
logsDir := specGuest.SandboxLogsDirFromRoot(c.sandboxRoot)
c.logPath = filepath.Join(logsDir, logPath)
// verify the logpath is still under the correct directory
if !strings.HasPrefix(c.logPath, logsDir+"/") {
return nil, errors.Errorf("log path %v is not within sandbox's log dir", c.logPath)
}
dir := filepath.Dir(c.logPath)
log.G(ctx).WithFields(logrus.Fields{
logfields.Path: dir,
logfields.ContainerID: id,
}).Debug("creating container log file parent directory in uVM")
if err := mkdirAllModePerm(dir); err != nil {
return nil, errors.Wrapf(err, "failed to create log file parent directory: %s", dir)
}
}
if envToKeep != nil {
settings.OCISpecification.Process.Env = []string(envToKeep)
}
if capsToKeep != nil {
settings.OCISpecification.Process.Capabilities = capsToKeep
}
if oci.ParseAnnotationsBool(ctx, settings.OCISpecification.Annotations, annotations.LCOWSecurityPolicyEnv, true) {
if err := h.securityOptions.WriteSecurityContextDir(settings.OCISpecification); err != nil {
return nil, fmt.Errorf("failed to write security context dir: %w", err)
}
}
// Create the BundlePath
if err := os.MkdirAll(settings.OCIBundlePath, 0700); err != nil {
return nil, errors.Wrapf(err, "failed to create OCIBundlePath: '%s'", settings.OCIBundlePath)
}
if err := writeSpecToFile(ctx, path.Join(settings.OCIBundlePath, "config.json"), settings.OCISpecification); err != nil {
return nil, err
}
con, err := h.rtime.CreateContainer(sandboxID, id, settings.OCIBundlePath, nil)
if err != nil {
return nil, errors.Wrapf(err, "failed to create container")
}
init, err := con.GetInitProcess()
if err != nil {
return nil, errors.Wrapf(err, "failed to get container init process")
}
c.container = con
c.initProcess = newProcess(c, settings.OCISpecification.Process, init, uint32(c.container.Pid()), true)
// Sandbox or standalone, move the networks to the container namespace
if criType == "sandbox" || !isCRI {
ns, err := getNetworkNamespace(namespaceID)
// skip network activity for sandbox containers marked with skip uvm networking annotation
if isCRI && err != nil && !strings.EqualFold(settings.OCISpecification.Annotations[annotations.SkipPodNetworking], "true") {
return nil, err
}
// standalone is not required to have a networking namespace setup
if ns != nil {
if err := ns.AssignContainerPid(ctx, c.container.Pid()); err != nil {
return nil, err
}
if err := ns.Sync(ctx); err != nil {
return nil, err
}
}
}
c.setStatus(containerCreated)
return c, nil
}
func writeSpecToFile(ctx context.Context, configFile string, spec *specs.Spec) error {
f, err := os.Create(configFile)
if err != nil {
return errors.Wrapf(err, "failed to create config.json at: '%s'", configFile)
}
defer f.Close()
writer := bufio.NewWriter(f)
// capture what we write to the config file in a byte buffer so we can log it later
var w io.Writer = writer
buf := &bytes.Buffer{}
if logrus.IsLevelEnabled(logrus.TraceLevel) {
w = io.MultiWriter(writer, buf)
}
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false) // not embedding JSON into HTML, so no need to escape
if err := enc.Encode(spec); err != nil {
return errors.Wrapf(err, "failed to write OCISpecification to config.json at: '%s'", configFile)
}
if err := writer.Flush(); err != nil {
return errors.Wrapf(err, "failed to flush writer for config.json at: '%s'", configFile)
}
if logrus.IsLevelEnabled(logrus.TraceLevel) {
entry := log.G(ctx).WithField(logfields.Path, configFile)
if b, err := log.ScrubOCISpec(buf.Bytes()); err != nil {
entry.WithError(err).Warning("could not scrub OCI spec written to config.json")
} else {
log.G(ctx).WithField(
"config", string(bytes.TrimSpace(b)),
).Trace("wrote OCI spec to config.json")
}
}
return nil
}
func (h *Host) modifyHostSettings(ctx context.Context, containerID string, req *guestrequest.ModificationRequest) (retErr error) {
if h.HasSecurityPolicy() {
if err := checkValidContainerID(containerID, "container"); err != nil {
return err
}
}
switch req.ResourceType {
case guestresource.ResourceTypeSCSIDevice:
return modifySCSIDevice(ctx, req.RequestType, req.Settings.(*guestresource.SCSIDevice))
case guestresource.ResourceTypeMappedVirtualDisk:
mvd := req.Settings.(*guestresource.LCOWMappedVirtualDisk)
// find the actual controller number on the bus and update the incoming request.
var cNum uint8
cNum, err := scsi.ActualControllerNumber(ctx, mvd.Controller)
if err != nil {
return err
}
mvd.Controller = cNum
// first we try to update the internal state for read-write attachments.
if !mvd.ReadOnly {
localCtx, cancel := context.WithTimeout(ctx, time.Second*5)
defer cancel()
source, err := scsi.GetDevicePath(localCtx, mvd.Controller, mvd.Lun, mvd.Partition)
if err != nil {
return err
}
switch req.RequestType {
case guestrequest.RequestTypeAdd:
if err := h.hostMounts.AddRWDevice(mvd.MountPath, source, mvd.Encrypted); err != nil {
return err
}
defer func() {
if retErr != nil {
_ = h.hostMounts.RemoveRWDevice(mvd.MountPath, source)
}
}()
case guestrequest.RequestTypeRemove:
if err := h.hostMounts.RemoveRWDevice(mvd.MountPath, source); err != nil {
return err
}
defer func() {
if retErr != nil {
_ = h.hostMounts.AddRWDevice(mvd.MountPath, source, mvd.Encrypted)
}
}()
}
}
return modifyMappedVirtualDisk(ctx, req.RequestType, mvd, h.securityOptions.PolicyEnforcer)
case guestresource.ResourceTypeMappedDirectory:
return modifyMappedDirectory(ctx, h.vsock, req.RequestType, req.Settings.(*guestresource.LCOWMappedDirectory), h.securityOptions.PolicyEnforcer)
case guestresource.ResourceTypeVPMemDevice:
return modifyMappedVPMemDevice(ctx, req.RequestType, req.Settings.(*guestresource.LCOWMappedVPMemDevice), h.securityOptions.PolicyEnforcer)
case guestresource.ResourceTypeCombinedLayers:
cl := req.Settings.(*guestresource.LCOWCombinedLayers)
// when cl.ScratchPath == "", we mount overlay as read-only, in which case
// we don't really care about scratch encryption, since the host already
// knows about the layers and the overlayfs.
encryptedScratch := cl.ScratchPath != "" && h.hostMounts.IsEncrypted(cl.ScratchPath)
return modifyCombinedLayers(ctx, req.RequestType, req.Settings.(*guestresource.LCOWCombinedLayers), encryptedScratch, h.securityOptions.PolicyEnforcer)
case guestresource.ResourceTypeNetwork:
return modifyNetwork(ctx, req.RequestType, req.Settings.(*guestresource.LCOWNetworkAdapter))
case guestresource.ResourceTypeVPCIDevice:
return modifyMappedVPCIDevice(ctx, req.RequestType, req.Settings.(*guestresource.LCOWMappedVPCIDevice))
case guestresource.ResourceTypeContainerConstraints:
c, err := h.GetCreatedContainer(containerID)
if err != nil {
return err
}
return c.modifyContainerConstraints(ctx, req.RequestType, req.Settings.(*guestresource.LCOWContainerConstraints))
case guestresource.ResourceTypeSecurityPolicy:
r, ok := req.Settings.(*guestresource.ConfidentialOptions)
if !ok {
return errors.New("the request's settings are not of type ConfidentialOptions")
}
return h.securityOptions.SetConfidentialOptions(ctx,
r.EnforcerType,
r.EncodedSecurityPolicy,
r.EncodedUVMReference)
case guestresource.ResourceTypePolicyFragment:
r, ok := req.Settings.(*guestresource.SecurityPolicyFragment)
if !ok {
return errors.New("the request settings are not of type SecurityPolicyFragment")
}
return h.securityOptions.InjectFragment(ctx, r)
default:
return errors.Errorf("the ResourceType %q is not supported for UVM", req.ResourceType)
}
}
func (h *Host) modifyContainerSettings(ctx context.Context, containerID string, req *guestrequest.ModificationRequest) error {
if h.HasSecurityPolicy() {
if err := checkValidContainerID(containerID, "container"); err != nil {
return err
}
}
c, err := h.GetCreatedContainer(containerID)
if err != nil {
return err
}
switch req.ResourceType {
case guestresource.ResourceTypeContainerConstraints:
return c.modifyContainerConstraints(ctx, req.RequestType, req.Settings.(*guestresource.LCOWContainerConstraints))
default:
return errors.Errorf("the ResourceType \"%s\" is not supported for containers", req.ResourceType)
}
}
func (h *Host) ModifySettings(ctx context.Context, containerID string, req *guestrequest.ModificationRequest) error {
if containerID == UVMContainerID {
return h.modifyHostSettings(ctx, containerID, req)
}
return h.modifyContainerSettings(ctx, containerID, req)
}
// Shutdown terminates this UVM. This is a destructive call and will destroy all
// state that has not been cleaned before calling this function.
func (*Host) Shutdown() {
_ = syscall.Reboot(syscall.LINUX_REBOOT_CMD_POWER_OFF)
}
// Called to shutdown a container
func (h *Host) ShutdownContainer(ctx context.Context, containerID string, graceful bool) error {
c, err := h.GetCreatedContainer(containerID)
if err != nil {
return err
}
err = h.securityOptions.PolicyEnforcer.EnforceShutdownContainerPolicy(ctx, containerID)
if err != nil {
return err
}
signal := unix.SIGTERM
if !graceful {
signal = unix.SIGKILL
}
return c.Kill(ctx, signal)
}
func (h *Host) SignalContainerProcess(ctx context.Context, containerID string, processID uint32, signal syscall.Signal) error {
c, err := h.GetCreatedContainer(containerID)
if err != nil {
return err
}
p, err := c.GetProcess(processID)
if err != nil {
return err
}
signalingInitProcess := processID == c.initProcess.pid
startupArgList := p.(*containerProcess).spec.Args
err = h.securityOptions.PolicyEnforcer.EnforceSignalContainerProcessPolicy(ctx, containerID, signal, signalingInitProcess, startupArgList)
if err != nil {
return err
}
return p.Kill(ctx, signal)
}
func (h *Host) ExecProcess(ctx context.Context, containerID string, params prot.ProcessParameters, conSettings stdio.ConnectionSettings) (_ int, err error) {
var pid int
var c *Container
if params.IsExternal || containerID == UVMContainerID {
var envToKeep securitypolicy.EnvList
var allowStdioAccess bool
envToKeep, allowStdioAccess, err = h.securityOptions.PolicyEnforcer.EnforceExecExternalProcessPolicy(
ctx,
params.CommandArgs,
processParamEnvToOCIEnv(params.Environment),
params.WorkingDirectory,
)
if err != nil {
return pid, errors.Wrapf(err, "exec is denied due to policy")
}
// It makes no sense to allow access if stdio access is denied and the
// process requires a terminal.
if params.EmulateConsole && !allowStdioAccess {
return pid, errors.New("exec of process that requires terminal access denied due to policy not allowing stdio access")
}
if envToKeep != nil {
params.Environment = processOCIEnvToParam(envToKeep)
}
var tport = h.vsock
if !allowStdioAccess {
tport = h.devNullTransport
}
pid, err = h.runExternalProcess(ctx, params, conSettings, tport)
} else if c, err = h.GetCreatedContainer(containerID); err == nil {
// We found a V2 container. Treat this as a V2 process.
if params.OCIProcess == nil {
// We've already done policy enforcement for creating a container so
// there's no policy enforcement to do for starting
pid, err = c.Start(ctx, conSettings)