-
Notifications
You must be signed in to change notification settings - Fork 1k
/
container_create_linux.go
1340 lines (1188 loc) · 43.3 KB
/
container_create_linux.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package server
import (
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/containers/common/pkg/subscriptions"
"github.com/containers/common/pkg/timezone"
cstorage "github.com/containers/storage"
"github.com/containers/storage/pkg/idtools"
"github.com/containers/storage/pkg/mount"
"github.com/containers/storage/pkg/unshare"
"github.com/cri-o/cri-o/internal/config/cgmgr"
"github.com/cri-o/cri-o/internal/config/device"
"github.com/cri-o/cri-o/internal/config/node"
"github.com/cri-o/cri-o/internal/config/rdt"
ctrfactory "github.com/cri-o/cri-o/internal/factory/container"
"github.com/cri-o/cri-o/internal/lib/sandbox"
"github.com/cri-o/cri-o/internal/linklogs"
"github.com/cri-o/cri-o/internal/log"
oci "github.com/cri-o/cri-o/internal/oci"
"github.com/cri-o/cri-o/internal/runtimehandlerhooks"
"github.com/cri-o/cri-o/internal/storage"
crioann "github.com/cri-o/cri-o/pkg/annotations"
securejoin "github.com/cyphar/filepath-securejoin"
rspec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/opencontainers/runtime-tools/generate"
"golang.org/x/net/context"
"golang.org/x/sys/unix"
types "k8s.io/cri-api/pkg/apis/runtime/v1"
kubeletTypes "k8s.io/kubelet/pkg/types"
"github.com/intel/goresctrl/pkg/blockio"
)
const (
cgroupSysFsPath = "/sys/fs/cgroup"
cgroupSysFsSystemdPath = "/sys/fs/cgroup/systemd"
)
// createContainerPlatform performs platform dependent intermediate steps before calling the container's oci.Runtime().CreateContainer()
func (s *Server) createContainerPlatform(ctx context.Context, container *oci.Container, cgroupParent string, idMappings *idtools.IDMappings) error {
ctx, span := log.StartSpan(ctx)
defer span.End()
if idMappings != nil && !container.Spoofed() {
rootPair := idMappings.RootPair()
for _, path := range []string{container.BundlePath(), container.MountPoint()} {
if err := makeAccessible(path, rootPair.UID, rootPair.GID); err != nil {
return fmt.Errorf("cannot make %s accessible to %d:%d: %w", path, rootPair.UID, rootPair.GID, err)
}
}
}
return s.Runtime().CreateContainer(ctx, container, cgroupParent, false)
}
// makeAccessible changes the path permission and each parent directory to have --x--x--x
func makeAccessible(path string, uid, gid int) error {
for ; path != "/"; path = filepath.Dir(path) {
var st unix.Stat_t
err := unix.Stat(path, &st)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
if int(st.Uid) == uid && int(st.Gid) == gid {
continue
}
perm := os.FileMode(st.Mode) & os.ModePerm
if perm&0o111 != 0o111 {
if err := os.Chmod(path, perm|0o111); err != nil {
return err
}
}
}
return nil
}
func toContainer(id uint32, idMap []idtools.IDMap) uint32 {
hostID := int(id)
if idMap == nil {
return uint32(hostID)
}
for _, m := range idMap {
if hostID >= m.HostID && hostID < m.HostID+m.Size {
contID := m.ContainerID + (hostID - m.HostID)
return uint32(contID)
}
}
// If the ID cannot be mapped, it means the RunAsUser or RunAsGroup was not specified
// so just use the original value.
return id
}
// finalizeUserMapping changes the UID, GID and additional GIDs to reflect the new value in the user namespace.
func (s *Server) finalizeUserMapping(sb *sandbox.Sandbox, specgen *generate.Generator, mappings *idtools.IDMappings) {
if mappings == nil {
return
}
// if the namespace was configured because of a static configuration, do not attempt any mapping
if s.defaultIDMappings != nil && !s.defaultIDMappings.Empty() {
return
}
if sb.Annotations()[crioann.UsernsModeAnnotation] == "" {
return
}
specgen.Config.Process.User.UID = toContainer(specgen.Config.Process.User.UID, mappings.UIDs())
gids := mappings.GIDs()
specgen.Config.Process.User.GID = toContainer(specgen.Config.Process.User.GID, gids)
for i := range specgen.Config.Process.User.AdditionalGids {
gid := toContainer(specgen.Config.Process.User.AdditionalGids[i], gids)
specgen.Config.Process.User.AdditionalGids[i] = gid
}
}
func (s *Server) createSandboxContainer(ctx context.Context, ctr ctrfactory.Container, sb *sandbox.Sandbox) (cntr *oci.Container, retErr error) {
ctx, span := log.StartSpan(ctx)
defer span.End()
// TODO: simplify this function (cyclomatic complexity here is high)
// TODO: factor generating/updating the spec into something other projects can vendor
// eventually, we'd like to access all of these variables through the interface themselves, and do most
// of the translation between CRI config -> oci/storage container in the container package
// TODO: eventually, this should be in the container package, but it's going through a lot of churn
// and SpecAddAnnotations is already being passed too many arguments
// Filter early so any use of the annotations don't use the wrong values
if err := s.FilterDisallowedAnnotations(sb.Annotations(), ctr.Config().Annotations, sb.RuntimeHandler()); err != nil {
return nil, err
}
containerID := ctr.ID()
containerName := ctr.Name()
containerConfig := ctr.Config()
if err := ctr.SetPrivileged(); err != nil {
return nil, err
}
if containerConfig.Linux == nil {
containerConfig.Linux = &types.LinuxContainerConfig{}
}
if containerConfig.Linux.SecurityContext == nil {
containerConfig.Linux.SecurityContext = newLinuxContainerSecurityContext()
}
securityContext := containerConfig.Linux.SecurityContext
// creates a spec Generator with the default spec.
specgen := ctr.Spec()
specgen.HostSpecific = true
specgen.ClearProcessRlimits()
for _, u := range s.config.Ulimits() {
specgen.AddProcessRlimits(u.Name, u.Hard, u.Soft)
}
readOnlyRootfs := ctr.ReadOnly(s.config.ReadOnly)
specgen.SetRootReadonly(readOnlyRootfs)
if s.config.ReadOnly {
// tmpcopyup is a runc extension and is not part of the OCI spec.
// WORK ON: Use "overlay" mounts as an alternative to tmpfs with tmpcopyup
// Look at https://github.com/cri-o/cri-o/pull/1434#discussion_r177200245 for more info on this
options := []string{"rw", "noexec", "nosuid", "nodev", "tmpcopyup"}
mounts := map[string]string{
"/run": "mode=0755",
"/tmp": "mode=1777",
"/var/tmp": "mode=1777",
}
for target, mode := range mounts {
if !isInCRIMounts(target, containerConfig.Mounts) {
ctr.SpecAddMount(rspec.Mount{
Destination: target,
Type: "tmpfs",
Source: "tmpfs",
Options: append(options, mode),
})
}
}
}
userRequestedImage, err := ctr.UserRequestedImage()
if err != nil {
return nil, err
}
// Get imageName and imageID that are later requested in container status
var imgResult *storage.ImageResult
if id := s.StorageImageServer().HeuristicallyTryResolvingStringAsIDPrefix(userRequestedImage); id != nil {
imgResult, err = s.StorageImageServer().ImageStatusByID(s.config.SystemContext, *id)
if err != nil {
return nil, err
}
} else {
potentialMatches, err := s.StorageImageServer().CandidatesForPotentiallyShortImageName(s.config.SystemContext, userRequestedImage)
if err != nil {
return nil, err
}
var imgResultErr error
for _, name := range potentialMatches {
imgResult, imgResultErr = s.StorageImageServer().ImageStatusByName(s.config.SystemContext, name)
if imgResultErr == nil {
break
}
}
if imgResultErr != nil {
return nil, imgResultErr
}
}
// At this point we know userRequestedImage is not empty; "" is accepted by neither HeuristicallyTryResolvingStringAsIDPrefix
// nor CandidatesForPotentiallyShortImageName. Just to be sure:
if userRequestedImage == "" {
return nil, errors.New("internal error: successfully found an image, but userRequestedImage is empty")
}
imageName := imgResult.SomeNameOfThisImage
imageID := imgResult.ID
someRepoDigest := ""
if len(imgResult.RepoDigests) > 0 {
someRepoDigest = imgResult.RepoDigests[0]
}
labelOptions, err := ctr.SelinuxLabel(sb.ProcessLabel())
if err != nil {
return nil, err
}
containerIDMappings, err := s.getSandboxIDMappings(ctx, sb)
if err != nil {
return nil, err
}
var idMappingOptions *cstorage.IDMappingOptions
if containerIDMappings != nil {
idMappingOptions = &cstorage.IDMappingOptions{UIDMap: containerIDMappings.UIDs(), GIDMap: containerIDMappings.GIDs()}
}
metadata := containerConfig.Metadata
s.resourceStore.SetStageForResource(ctx, ctr.Name(), "container storage creation")
containerInfo, err := s.StorageRuntimeServer().CreateContainer(s.config.SystemContext,
sb.Name(), sb.ID(),
userRequestedImage, imageID,
containerName, containerID,
metadata.Name,
metadata.Attempt,
idMappingOptions,
labelOptions,
ctr.Privileged(),
)
if err != nil {
return nil, err
}
defer func() {
if retErr != nil {
log.Infof(ctx, "CreateCtrLinux: deleting container %s from storage", containerInfo.ID)
if err := s.StorageRuntimeServer().DeleteContainer(ctx, containerInfo.ID); err != nil {
log.Warnf(ctx, "Failed to cleanup container directory: %v", err)
}
}
}()
mountLabel := containerInfo.MountLabel
var processLabel string
if !ctr.Privileged() {
processLabel = containerInfo.ProcessLabel
}
if securityContext.NamespaceOptions == nil {
securityContext.NamespaceOptions = &types.NamespaceOption{}
}
hostIPC := securityContext.NamespaceOptions.Ipc == types.NamespaceMode_NODE
hostPID := securityContext.NamespaceOptions.Pid == types.NamespaceMode_NODE
hostNet := securityContext.NamespaceOptions.Network == types.NamespaceMode_NODE
// Don't use SELinux separation with Host Pid or IPC Namespace or privileged.
if hostPID || hostIPC {
processLabel, mountLabel = "", ""
}
if hostNet && s.config.RuntimeConfig.HostNetworkDisableSELinux {
processLabel = ""
}
maybeRelabel := false
if val, present := sb.Annotations()[crioann.TrySkipVolumeSELinuxLabelAnnotation]; present && val == "true" {
maybeRelabel = true
}
skipRelabel := false
const superPrivilegedType = "spc_t"
if securityContext.SelinuxOptions == nil {
securityContext.SelinuxOptions = &types.SELinuxOption{}
}
if securityContext.SelinuxOptions.Type == superPrivilegedType || // super privileged container
(ctr.SandboxConfig().Linux != nil &&
ctr.SandboxConfig().Linux.SecurityContext != nil &&
ctr.SandboxConfig().Linux.SecurityContext.SelinuxOptions != nil &&
ctr.SandboxConfig().Linux.SecurityContext.SelinuxOptions.Type == superPrivilegedType && // super privileged pod
securityContext.SelinuxOptions.Type == "") {
skipRelabel = true
}
cgroup2RW := node.CgroupIsV2() && sb.Annotations()[crioann.Cgroup2RWAnnotation] == "true"
s.resourceStore.SetStageForResource(ctx, ctr.Name(), "container volume configuration")
idMapSupport := s.Runtime().RuntimeSupportsIDMap(sb.RuntimeHandler())
rroSupport := s.Runtime().RuntimeSupportsRROMounts(sb.RuntimeHandler())
containerVolumes, ociMounts, err := addOCIBindMounts(ctx, ctr, mountLabel, s.config.RuntimeConfig.BindMountPrefix, s.config.AbsentMountSourcesToReject, maybeRelabel, skipRelabel, cgroup2RW, idMapSupport, rroSupport, s.Config().Root)
if err != nil {
return nil, err
}
s.resourceStore.SetStageForResource(ctx, ctr.Name(), "container device creation")
configuredDevices := s.config.Devices()
privilegedWithoutHostDevices, err := s.Runtime().PrivilegedWithoutHostDevices(sb.RuntimeHandler())
if err != nil {
return nil, err
}
annotationDevices, err := device.DevicesFromAnnotation(sb.Annotations()[crioann.DevicesAnnotation], s.config.AllowedDevices)
if err != nil {
return nil, err
}
if err := ctr.SpecAddDevices(configuredDevices, annotationDevices, privilegedWithoutHostDevices, s.config.DeviceOwnershipFromSecurityContext); err != nil {
return nil, err
}
s.resourceStore.SetStageForResource(ctx, ctr.Name(), "container storage start")
mountPoint, err := s.StorageRuntimeServer().StartContainer(containerID)
if err != nil {
return nil, fmt.Errorf("failed to mount container %s(%s): %w", containerName, containerID, err)
}
defer func() {
if retErr != nil {
log.Infof(ctx, "CreateCtrLinux: stopping storage container %s", containerID)
if err := s.StorageRuntimeServer().StopContainer(ctx, containerID); err != nil {
log.Warnf(ctx, "Couldn't stop storage container: %v: %v", containerID, err)
}
}
}()
s.resourceStore.SetStageForResource(ctx, ctr.Name(), "container spec configuration")
labels := containerConfig.Labels
if err := validateLabels(labels); err != nil {
return nil, err
}
// set this container's apparmor profile if it is set by sandbox
if s.Config().AppArmor().IsEnabled() && !ctr.Privileged() {
profile, err := s.Config().AppArmor().Apply(securityContext)
if err != nil {
return nil, fmt.Errorf("applying apparmor profile to container %s: %w", containerID, err)
}
log.Debugf(ctx, "Applied AppArmor profile %s to container %s", profile, containerID)
specgen.SetProcessApparmorProfile(profile)
}
// Get blockio class
if s.Config().BlockIO().Enabled() {
if blockioClass, err := blockio.ContainerClassFromAnnotations(metadata.Name, containerConfig.Annotations, sb.Annotations()); blockioClass != "" && err == nil {
if s.Config().BlockIO().ReloadRequired() {
if err := s.Config().BlockIO().Reload(); err != nil {
log.Warnf(ctx, "Reconfiguring blockio for container %s failed: %v", containerID, err)
}
}
if linuxBlockIO, err := blockio.OciLinuxBlockIO(blockioClass); err == nil {
if specgen.Config.Linux.Resources == nil {
specgen.Config.Linux.Resources = &rspec.LinuxResources{}
}
specgen.Config.Linux.Resources.BlockIO = linuxBlockIO
}
}
}
logPath, err := ctr.LogPath(sb.LogDir())
if err != nil {
return nil, err
}
specgen.SetProcessTerminal(containerConfig.Tty)
if containerConfig.Tty {
specgen.AddProcessEnv("TERM", "xterm")
}
linux := containerConfig.Linux
if linux != nil {
resources := linux.Resources
if resources != nil {
specgen.SetLinuxResourcesCPUPeriod(uint64(resources.CpuPeriod))
specgen.SetLinuxResourcesCPUQuota(resources.CpuQuota)
specgen.SetLinuxResourcesCPUShares(uint64(resources.CpuShares))
memoryLimit := resources.MemoryLimitInBytes
if memoryLimit != 0 {
containerMinMemory, err := s.Runtime().GetContainerMinMemory(sb.RuntimeHandler())
if err != nil {
return nil, err
}
if err := cgmgr.VerifyMemoryIsEnough(memoryLimit, containerMinMemory); err != nil {
return nil, err
}
specgen.SetLinuxResourcesMemoryLimit(memoryLimit)
if resources.MemorySwapLimitInBytes != 0 {
if resources.MemorySwapLimitInBytes > 0 && resources.MemorySwapLimitInBytes < resources.MemoryLimitInBytes {
return nil, fmt.Errorf(
"container %s create failed because memory swap limit (%d) cannot be lower than memory limit (%d)",
ctr.ID(),
resources.MemorySwapLimitInBytes,
resources.MemoryLimitInBytes,
)
}
memoryLimit = resources.MemorySwapLimitInBytes
}
// If node doesn't have memory swap, then skip setting
// otherwise the container creation fails.
if node.CgroupHasMemorySwap() {
specgen.SetLinuxResourcesMemorySwap(memoryLimit)
}
}
specgen.SetProcessOOMScoreAdj(int(resources.OomScoreAdj))
specgen.SetLinuxResourcesCPUCpus(resources.CpusetCpus)
specgen.SetLinuxResourcesCPUMems(resources.CpusetMems)
// If the kernel has no support for hugetlb, silently ignore the limits
if node.CgroupHasHugetlb() {
hugepageLimits := resources.HugepageLimits
for _, limit := range hugepageLimits {
specgen.AddLinuxResourcesHugepageLimit(limit.PageSize, limit.Limit)
}
}
if node.CgroupIsV2() && len(resources.Unified) != 0 {
if specgen.Config.Linux.Resources.Unified == nil {
specgen.Config.Linux.Resources.Unified = make(map[string]string, len(resources.Unified))
}
for key, value := range resources.Unified {
specgen.Config.Linux.Resources.Unified[key] = value
}
}
}
specgen.SetLinuxCgroupsPath(s.config.CgroupManager().ContainerCgroupPath(sb.CgroupParent(), containerID))
if ctr.Privileged() {
specgen.SetupPrivileged(true)
} else {
capabilities := securityContext.Capabilities
if err := ctr.SpecSetupCapabilities(capabilities, s.config.DefaultCapabilities, s.config.AddInheritableCapabilities); err != nil {
return nil, err
}
}
if securityContext.NoNewPrivs {
const sysAdminCap = "CAP_SYS_ADMIN"
for _, cap := range specgen.Config.Process.Capabilities.Bounding {
if cap == sysAdminCap {
log.Warnf(ctx, "Setting `noNewPrivileges` flag has no effect because container has %s capability", sysAdminCap)
}
}
if ctr.Privileged() {
log.Warnf(ctx, "Setting `noNewPrivileges` flag has no effect because container is privileged")
}
}
specgen.SetProcessNoNewPrivileges(securityContext.NoNewPrivs)
if !ctr.Privileged() {
if securityContext.MaskedPaths != nil {
for _, path := range securityContext.MaskedPaths {
specgen.AddLinuxMaskedPaths(path)
}
}
if securityContext.ReadonlyPaths != nil {
for _, path := range securityContext.ReadonlyPaths {
specgen.AddLinuxReadonlyPaths(path)
}
}
}
}
if err := ctr.AddUnifiedResourcesFromAnnotations(sb.Annotations()); err != nil {
return nil, err
}
var nsTargetCtr *oci.Container
if target := containerConfig.Linux.SecurityContext.NamespaceOptions.TargetId; target != "" {
nsTargetCtr = s.GetContainer(ctx, target)
}
if err := ctr.SpecAddNamespaces(sb, nsTargetCtr, &s.config); err != nil {
return nil, err
}
defer func() {
if retErr != nil && ctr.PidNamespace() != nil {
log.Infof(ctx, "CreateCtrLinux: clearing PID namespace for container %s", containerInfo.ID)
if err := ctr.PidNamespace().Remove(); err != nil {
log.Warnf(ctx, "Failed to remove PID namespace: %v", err)
}
}
}()
// If the sandbox is configured to run in the host network, do not create a new network namespace
if hostNet {
if !isInCRIMounts("/sys", containerConfig.Mounts) {
ctr.SpecAddMount(rspec.Mount{
Destination: "/sys",
Type: "sysfs",
Source: "sysfs",
Options: []string{"nosuid", "noexec", "nodev", "ro"},
})
ctr.SpecAddMount(rspec.Mount{
Destination: cgroupSysFsPath,
Type: "cgroup",
Source: "cgroup",
Options: []string{"nosuid", "noexec", "nodev", "relatime", "ro"},
})
}
}
if ctr.Privileged() {
ctr.SpecAddMount(rspec.Mount{
Destination: "/sys",
Type: "sysfs",
Source: "sysfs",
Options: []string{"nosuid", "noexec", "nodev", "rw", "rslave"},
})
ctr.SpecAddMount(rspec.Mount{
Destination: cgroupSysFsPath,
Type: "cgroup",
Source: "cgroup",
Options: []string{"nosuid", "noexec", "nodev", "rw", "relatime", "rslave"},
})
}
containerImageConfig := containerInfo.Config
if containerImageConfig == nil {
err = fmt.Errorf("empty image config for %s", userRequestedImage)
return nil, err
}
if err := ctr.SpecSetProcessArgs(containerImageConfig); err != nil {
return nil, err
}
// When running on cgroupv2, automatically add a cgroup namespace for not privileged containers.
if !ctr.Privileged() && node.CgroupIsV2() {
if err := specgen.AddOrReplaceLinuxNamespace(string(rspec.CgroupNamespace), ""); err != nil {
return nil, err
}
}
ctr.SpecAddMount(rspec.Mount{
Destination: "/dev/shm",
Type: "bind",
Source: sb.ShmPath(),
Options: []string{"rw", "bind"},
})
options := []string{"rw"}
if readOnlyRootfs {
options = []string{"ro"}
}
if sb.ResolvPath() != "" {
if err := securityLabel(sb.ResolvPath(), mountLabel, false, false); err != nil {
return nil, err
}
ctr.SpecAddMount(rspec.Mount{
Destination: "/etc/resolv.conf",
Type: "bind",
Source: sb.ResolvPath(),
Options: append(options, []string{"bind", "nodev", "nosuid", "noexec"}...),
})
}
if sb.HostnamePath() != "" {
if err := securityLabel(sb.HostnamePath(), mountLabel, false, false); err != nil {
return nil, err
}
ctr.SpecAddMount(rspec.Mount{
Destination: "/etc/hostname",
Type: "bind",
Source: sb.HostnamePath(),
Options: append(options, "bind"),
})
}
if sb.ContainerEnvPath() != "" {
if err := securityLabel(sb.ContainerEnvPath(), mountLabel, false, false); err != nil {
return nil, err
}
ctr.SpecAddMount(rspec.Mount{
Destination: "/run/.containerenv",
Type: "bind",
Source: sb.ContainerEnvPath(),
Options: append(options, "bind"),
})
}
if !isInCRIMounts("/etc/hosts", containerConfig.Mounts) && hostNet {
// Only bind mount for host netns and when CRI does not give us any hosts file
ctr.SpecAddMount(rspec.Mount{
Destination: "/etc/hosts",
Type: "bind",
Source: "/etc/hosts",
Options: append(options, "bind"),
})
}
if ctr.Privileged() {
setOCIBindMountsPrivileged(specgen)
}
// Set hostname and add env for hostname
specgen.SetHostname(sb.Hostname())
specgen.AddProcessEnv("HOSTNAME", sb.Hostname())
created := time.Now()
seccompRef := types.SecurityProfile_Unconfined.String()
if err := s.FilterDisallowedAnnotations(sb.Annotations(), imgResult.Annotations, sb.RuntimeHandler()); err != nil {
return nil, fmt.Errorf("filter image annotations: %w", err)
}
if !ctr.Privileged() {
notifier, ref, err := s.config.Seccomp().Setup(
ctx,
s.config.SystemContext,
s.seccompNotifierChan,
containerID,
ctr.Config().Metadata.Name,
sb.Annotations(),
imgResult.Annotations,
specgen,
securityContext.Seccomp,
)
if err != nil {
return nil, fmt.Errorf("setup seccomp: %w", err)
}
if notifier != nil {
s.seccompNotifiers.Store(containerID, notifier)
}
seccompRef = ref
}
// Get RDT class
rdtClass, err := s.Config().Rdt().ContainerClassFromAnnotations(metadata.Name, containerConfig.Annotations, sb.Annotations())
if err != nil {
return nil, err
}
if rdtClass != "" {
log.Debugf(ctx, "Setting RDT ClosID of container %s to %q", containerID, rdt.ResctrlPrefix+rdtClass)
// TODO: patch runtime-tools to support setting ClosID via a helper func similar to SetLinuxIntelRdtL3CacheSchema()
specgen.Config.Linux.IntelRdt = &rspec.LinuxIntelRdt{ClosID: rdt.ResctrlPrefix + rdtClass}
}
// compute the runtime path for a given container
platform := containerInfo.Config.Platform.OS + "/" + containerInfo.Config.Platform.Architecture
runtimePath, err := s.Runtime().PlatformRuntimePath(sb.RuntimeHandler(), platform)
if err != nil {
return nil, err
}
err = ctr.SpecAddAnnotations(ctx, sb, containerVolumes, mountPoint, containerImageConfig.Config.StopSignal, imgResult, s.config.CgroupManager().IsSystemd(), seccompRef, runtimePath)
if err != nil {
return nil, err
}
if err := s.config.Workloads.MutateSpecGivenAnnotations(ctr.Config().Metadata.Name, ctr.Spec(), sb.Annotations()); err != nil {
return nil, err
}
// First add any configured environment variables from crio config.
// They will get overridden if specified in the image or container config.
specgen.AddMultipleProcessEnv(s.Config().DefaultEnv)
// Add environment variables from image the CRI configuration
envs := mergeEnvs(containerImageConfig, containerConfig.Envs)
for _, e := range envs {
parts := strings.SplitN(e, "=", 2)
specgen.AddProcessEnv(parts[0], parts[1])
}
// Setup user and groups
if linux != nil {
if err := setupContainerUser(ctx, specgen, mountPoint, mountLabel, containerInfo.RunDir, securityContext, containerImageConfig); err != nil {
return nil, err
}
}
// Add image volumes
volumeMounts, err := addImageVolumes(ctx, mountPoint, s, &containerInfo, mountLabel, specgen)
if err != nil {
return nil, err
}
// Set working directory
// Pick it up from image config first and override if specified in CRI
containerCwd := "/"
imageCwd := containerImageConfig.Config.WorkingDir
if imageCwd != "" {
containerCwd = imageCwd
}
runtimeCwd := containerConfig.WorkingDir
if runtimeCwd != "" {
containerCwd = runtimeCwd
}
specgen.SetProcessCwd(containerCwd)
if err := setupWorkingDirectory(mountPoint, mountLabel, containerCwd); err != nil {
return nil, err
}
rootUID, rootGID := 0, 0
if containerIDMappings != nil {
rootPair := containerIDMappings.RootPair()
rootUID, rootGID = rootPair.UID, rootPair.GID
}
// Add secrets from the default and override mounts.conf files
secretMounts := subscriptions.MountsWithUIDGID(
mountLabel,
containerInfo.RunDir,
s.config.DefaultMountsFile,
mountPoint,
rootUID,
rootGID,
unshare.IsRootless(),
ctr.DisableFips(),
)
if ctr.DisableFips() && sb.Annotations()[crioann.DisableFIPSAnnotation] == "true" {
if err := disableFipsForContainer(ctr, containerInfo.RunDir); err != nil {
return nil, fmt.Errorf("failed to disable FIPS for container %s: %w", containerID, err)
}
}
mounts := []rspec.Mount{}
mounts = append(mounts, ociMounts...)
mounts = append(mounts, volumeMounts...)
mounts = append(mounts, secretMounts...)
sort.Sort(orderedMounts(mounts))
for _, m := range mounts {
rspecMount := rspec.Mount{
Type: "bind",
Options: append(m.Options, "bind"),
Destination: m.Destination,
Source: m.Source,
UIDMappings: m.UIDMappings,
GIDMappings: m.GIDMappings,
}
ctr.SpecAddMount(rspecMount)
}
if ctr.WillRunSystemd() {
processLabel, err = InitLabel(processLabel)
if err != nil {
return nil, err
}
setupSystemd(specgen.Mounts(), *specgen)
}
if s.ContainerServer.Hooks != nil {
newAnnotations := map[string]string{}
for key, value := range containerConfig.Annotations {
newAnnotations[key] = value
}
for key, value := range sb.Annotations() {
newAnnotations[key] = value
}
if _, err := s.ContainerServer.Hooks.Hooks(specgen.Config, newAnnotations, len(containerConfig.Mounts) > 0); err != nil {
return nil, err
}
}
// Set up pids limit if pids cgroup is mounted
if node.CgroupHasPid() {
specgen.SetLinuxResourcesPidsLimit(s.config.PidsLimit)
}
// by default, the root path is an empty string. set it now.
specgen.SetRootPath(mountPoint)
crioAnnotations := specgen.Config.Annotations
criMetadata := &types.ContainerMetadata{
Name: metadata.Name,
Attempt: metadata.Attempt,
}
ociContainer, err := oci.NewContainer(containerID, containerName, containerInfo.RunDir, logPath, labels, crioAnnotations, ctr.Config().Annotations, userRequestedImage, imageName, &imageID, someRepoDigest, criMetadata, sb.ID(), containerConfig.Tty, containerConfig.Stdin, containerConfig.StdinOnce, sb.RuntimeHandler(), containerInfo.Dir, created, containerImageConfig.Config.StopSignal)
if err != nil {
return nil, err
}
specgen.SetLinuxMountLabel(mountLabel)
specgen.SetProcessSelinuxLabel(processLabel)
ociContainer.AddManagedPIDNamespace(ctr.PidNamespace())
ociContainer.SetIDMappings(containerIDMappings)
if containerIDMappings != nil {
s.finalizeUserMapping(sb, specgen, containerIDMappings)
for _, uidmap := range containerIDMappings.UIDs() {
specgen.AddLinuxUIDMapping(uint32(uidmap.HostID), uint32(uidmap.ContainerID), uint32(uidmap.Size))
}
for _, gidmap := range containerIDMappings.GIDs() {
specgen.AddLinuxGIDMapping(uint32(gidmap.HostID), uint32(gidmap.ContainerID), uint32(gidmap.Size))
}
for _, path := range []string{mountPoint, containerInfo.RunDir} {
if err := makeAccessible(path, rootUID, rootGID); err != nil {
return nil, fmt.Errorf("cannot make %s accessible to %d:%d: %w", path, rootUID, rootGID, err)
}
}
} else if err := specgen.RemoveLinuxNamespace(string(rspec.UserNamespace)); err != nil {
return nil, err
}
if v := sb.Annotations()[crioann.UmaskAnnotation]; v != "" {
umaskRegexp := regexp.MustCompile(`^[0-7]{1,4}$`)
if !umaskRegexp.MatchString(v) {
return nil, fmt.Errorf("invalid umask string %s", v)
}
decVal, err := strconv.ParseUint(sb.Annotations()[crioann.UmaskAnnotation], 8, 32)
if err != nil {
return nil, err
}
umask := uint32(decVal)
specgen.Config.Process.User.Umask = &umask
}
etc := filepath.Join(mountPoint, "/etc")
// create the `/etc` folder only when it doesn't exist
if _, err := os.Stat(etc); err != nil && os.IsNotExist(err) {
rootPair := idtools.IDPair{UID: 0, GID: 0}
if containerIDMappings != nil {
rootPair = containerIDMappings.RootPair()
}
if err := idtools.MkdirAllAndChown(etc, 0o755, rootPair); err != nil {
return nil, fmt.Errorf("error creating mtab directory: %w", err)
}
}
// add symlink /etc/mtab to /proc/mounts allow looking for mountfiles there in the container
// compatible with Docker
if err := os.Symlink("/proc/mounts", filepath.Join(etc, "mtab")); err != nil && !os.IsExist(err) {
return nil, err
}
// Configure timezone for the container if it is set.
if err := configureTimezone(s.Runtime().Timezone(), ociContainer.BundlePath(), mountPoint, mountLabel, etc, ociContainer.ID(), options, ctr); err != nil {
return nil, fmt.Errorf("failed to configure timezone for container %s: %w", ociContainer.ID(), err)
}
if os.Getenv(rootlessEnvName) != "" {
makeOCIConfigurationRootless(specgen)
}
hooks, err := runtimehandlerhooks.GetRuntimeHandlerHooks(ctx, &s.config, sb.RuntimeHandler(), sb.Annotations())
if err != nil {
return nil, fmt.Errorf("failed to get runtime handler %q hooks", sb.RuntimeHandler())
}
if err := s.nri.createContainer(ctx, specgen, sb, ociContainer); err != nil {
return nil, err
}
defer func() {
if retErr != nil {
s.nri.undoCreateContainer(ctx, specgen, sb, ociContainer)
}
}()
if hooks != nil {
if err := hooks.PreCreate(ctx, specgen, sb, ociContainer); err != nil {
return nil, fmt.Errorf("failed to run pre-create hook for container %q: %w", ociContainer.ID(), err)
}
}
if emptyDirVolName, ok := sb.Annotations()[crioann.LinkLogsAnnotation]; ok {
if err := linklogs.LinkContainerLogs(ctx, sb.Labels()[kubeletTypes.KubernetesPodUIDLabel], emptyDirVolName, ctr.ID(), containerConfig.Metadata); err != nil {
log.Warnf(ctx, "Failed to link container logs: %v", err)
}
}
saveOptions := generate.ExportOptions{}
if err := specgen.SaveToFile(filepath.Join(containerInfo.Dir, "config.json"), saveOptions); err != nil {
return nil, err
}
if err := specgen.SaveToFile(filepath.Join(containerInfo.RunDir, "config.json"), saveOptions); err != nil {
return nil, err
}
ociContainer.SetSpec(specgen.Config)
ociContainer.SetMountPoint(mountPoint)
ociContainer.SetSeccompProfilePath(seccompRef)
if runtimePath != "" {
ociContainer.SetRuntimePathForPlatform(runtimePath)
}
for _, cv := range containerVolumes {
ociContainer.AddVolume(cv)
}
return ociContainer, nil
}
func disableFipsForContainer(ctr ctrfactory.Container, containerDir string) error {
// Create a unique filename for the FIPS setting file.
fileName := filepath.Join(containerDir, "sysctl-fips")
content := []byte("0\n")
// Write the value '0' to disable FIPS directly to the file.
if err := os.WriteFile(fileName, content, 0o444); err != nil {
return fmt.Errorf("failed to write to file: %w", err)
}
ctr.SpecAddMount(rspec.Mount{
Destination: "/proc/sys/crypto/fips_enabled",
Source: fileName,
Type: "bind",
Options: []string{"noexec", "nosuid", "nodev", "ro", "bind"},
})
return nil
}
func configureTimezone(tz, containerRunDir, mountPoint, mountLabel, etcPath, containerID string, options []string, ctr ctrfactory.Container) error {
localTimePath, err := timezone.ConfigureContainerTimeZone(tz, containerRunDir, mountPoint, etcPath, containerID)
if err != nil {
return fmt.Errorf("setting timezone for container %s: %w", containerID, err)
}
if localTimePath != "" {
if err := securityLabel(localTimePath, mountLabel, false, false); err != nil {
return err
}
ctr.SpecAddMount(rspec.Mount{
Destination: "/etc/localtime",
Type: "bind",
Source: localTimePath,
Options: append(options, []string{"bind", "nodev", "nosuid", "noexec"}...),
})
}
return nil
}
func setupWorkingDirectory(rootfs, mountLabel, containerCwd string) error {
fp, err := securejoin.SecureJoin(rootfs, containerCwd)
if err != nil {
return err
}
if err := os.MkdirAll(fp, 0o755); err != nil {
return err
}
if mountLabel != "" {
if err1 := securityLabel(fp, mountLabel, false, false); err1 != nil {
return err1
}
}
return nil
}
func setOCIBindMountsPrivileged(g *generate.Generator) {
spec := g.Config
// clear readonly for /sys and cgroup
for i := range spec.Mounts {
clearReadOnly(&spec.Mounts[i])
}
spec.Linux.ReadonlyPaths = nil
spec.Linux.MaskedPaths = nil
}
func clearReadOnly(m *rspec.Mount) {
var opt []string
for _, o := range m.Options {
if o == "rw" {
return
} else if o != "ro" {
opt = append(opt, o)
}
}
m.Options = opt
m.Options = append(m.Options, "rw")
}