| 1 | package containerenv |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "strconv" |
| 6 | "strings" |
| 7 | ) |
| 8 | |
| 9 | type MountPropagation struct { |
| 10 | PrivateNamespace bool `json:"private_namespace"` |
| 11 | SharedGroup uint64 `json:"shared_group,omitempty"` |
| 12 | DetachedFromHost bool `json:"detached_from_host"` |
| 13 | } |
| 14 | |
| 15 | func (m MountPropagation) Ready() bool { |
| 16 | return m.PrivateNamespace && m.DetachedFromHost && m.SharedGroup != 0 |
| 17 | } |
| 18 | |
| 19 | func rootMountPropagation(containerMounts, hostMounts string) (MountPropagation, error) { |
| 20 | var root []string |
| 21 | for _, line := range strings.Split(containerMounts, "\n") { |
| 22 | fields := strings.Fields(line) |
| 23 | if len(fields) > 6 && fields[4] == "/" { |
| 24 | root = fields |
| 25 | break |
| 26 | } |
| 27 | } |
| 28 | if root == nil { |
| 29 | return MountPropagation{}, errors.New("无法核验容器根挂载") |
| 30 | } |
| 31 | result := MountPropagation{DetachedFromHost: true} |
| 32 | for _, field := range root[6:] { |
| 33 | if field == "-" { |
| 34 | break |
| 35 | } |
| 36 | if strings.HasPrefix(field, "master:") || strings.HasPrefix(field, "propagate_from:") { |
| 37 | return MountPropagation{}, errors.New("容器根仍有外部挂载传播关系") |
| 38 | } |
| 39 | if strings.HasPrefix(field, "shared:") { |
| 40 | group, err := strconv.ParseUint(strings.TrimPrefix(field, "shared:"), 10, 64) |
| 41 | if err != nil || group == 0 { |
| 42 | return MountPropagation{}, errors.New("容器共享挂载组无效") |
| 43 | } |
| 44 | result.SharedGroup = group |
| 45 | } |
| 46 | } |
| 47 | if result.SharedGroup != 0 { |
| 48 | group := strconv.FormatUint(result.SharedGroup, 10) |
| 49 | for _, line := range strings.Split(hostMounts, "\n") { |
| 50 | fields := strings.Fields(line) |
| 51 | if len(fields) < 7 { |
| 52 | continue |
| 53 | } |
| 54 | for _, field := range fields[6:] { |
| 55 | if field == "-" { |
| 56 | break |
| 57 | } |
| 58 | if field == "shared:"+group || field == "master:"+group || field == "propagate_from:"+group { |
| 59 | return MountPropagation{}, errors.New("容器共享挂载组与宿主关联,拒绝连接") |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | return result, nil |
| 65 | } |