package docker import ( "fmt" "regexp" "strings" ) const maxRunInput = 8 << 10 var ( imageRefRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._/-]*(?::[a-zA-Z0-9._-]+)?(?:@sha256:[0-9a-fA-F]+)?$`) containerRefRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$`) containerIDRe = regexp.MustCompile(`^[0-9a-f]{12,64}$`) resourceNameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}$`) composePrivRe = regexp.MustCompile(`(?m)^\s*privileged\s*:\s*true\s*$`) ) // TokenizeDockerRun splits a pasted `docker run ...` command into argv without // invoking a shell. Shell control operators are rejected so a pasted command // can never chain a second program. func TokenizeDockerRun(input string) ([]string, error) { if len(input) > maxRunInput { return nil, fmt.Errorf("%w: 命令过长", ErrInvalid) } if strings.ContainsAny(input, "\n\r") { return nil, fmt.Errorf("%w: 命令不能包含换行", ErrInvalid) } var tokens []string var cur strings.Builder var quote rune escaped := false flush := func() { if cur.Len() > 0 { tokens = append(tokens, cur.String()) cur.Reset() } } for _, r := range input { if escaped { cur.WriteRune(r) escaped = false continue } if r == '\\' && quote != '\'' { escaped = true continue } if quote != 0 { if r == quote { quote = 0 continue } if r == '$' || r == '`' { return nil, fmt.Errorf("%w: 命令不能包含变量展开或反引号", ErrInvalid) } cur.WriteRune(r) continue } switch r { case '\'', '"': quote = r case ' ', '\t': flush() case ';', '&', '|', '>', '<', '`', '$', '(', ')', '{', '}', '[', ']', '#': return nil, fmt.Errorf("%w: 命令不能包含 shell 控制字符 %q", ErrInvalid, r) default: cur.WriteRune(r) } } if escaped || quote != 0 { return nil, fmt.Errorf("%w: 引号或转义未闭合", ErrInvalid) } flush() if len(tokens) > 64 { return nil, fmt.Errorf("%w: 参数过多", ErrInvalid) } if len(tokens) < 3 || tokens[0] != "docker" || tokens[1] != "run" { return nil, fmt.Errorf("%w: 命令必须以 docker run 开头", ErrInvalid) } if err := validateRunTokens(tokens[2:]); err != nil { return nil, err } return tokens, nil } var valueFlags = map[string]bool{ "-p": true, "--publish": true, "-e": true, "--env": true, "--env-file": true, "-v": true, "--volume": true, "--mount": true, "--name": true, "--network": true, "--net": true, "--restart": true, "-u": true, "--user": true, "-w": true, "--workdir": true, "--entrypoint": true, "--hostname": true, "-h": true, "--label": true, "-l": true, "--label-file": true, "--memory": true, "-m": true, "--cpus": true, "--cpu-shares": true, "--device": true, "--cap-add": true, "--cap-drop": true, "--log-driver": true, "--log-opt": true, "--ulimit": true, "--dns": true, "--add-host": true, "--tmpfs": true, "--shm-size": true, "--platform": true, "--pull": true, "--network-alias": true, "--expose": true, "--link": true, "--ipc": true, "--pid": true, "--uts": true, "--security-opt": true, "--sysctl": true, "--gpus": true, "--runtime": true, "--stop-signal": true, "--stop-timeout": true, "--cidfile": true, "--group-add": true, "--ip": true, "--mac-address": true, "--memory-swap": true, "--volumes-from": true, "--health-cmd": true, "--health-interval": true, "--health-timeout": true, "--health-retries": true, "--health-start-period": true, "--dns-search": true, "--dns-option": true, "--domainname": true, "--storage-opt": true, "--cgroup-parent": true, "--isolation": true, "--userns": true, "--annotation": true, } func validateRunTokens(tokens []string) error { detached := false imageFound := false for i := 0; i < len(tokens); i++ { tok := tokens[i] if tok == "-d" || tok == "--detach" || strings.HasPrefix(tok, "--detach=") { detached = true continue } if strings.HasPrefix(tok, "-") { name, value, hasValue := splitFlag(tok) switch name { case "--privileged": return fmt.Errorf("%w: 不允许 --privileged", ErrInvalid) case "--device": return fmt.Errorf("%w: 不允许 --device", ErrInvalid) case "--pid": if !hasValue && i+1 < len(tokens) { value = tokens[i+1] i++ } if value == "host" { return fmt.Errorf("%w: 不允许 --pid=host", ErrInvalid) } case "--network", "--net": if !hasValue && i+1 < len(tokens) { value = tokens[i+1] i++ } if value == "host" { return fmt.Errorf("%w: 不允许 --network=host", ErrInvalid) } case "--cap-add": if !hasValue && i+1 < len(tokens) { value = tokens[i+1] i++ } if strings.EqualFold(value, "all") { return fmt.Errorf("%w: 不允许 --cap-add=ALL", ErrInvalid) } } if !hasValue && valueFlags[name] && i+1 < len(tokens) { value = tokens[i+1] i++ } if name == "-v" || name == "--volume" || name == "--mount" { if err := validateMount(value); err != nil { return err } } continue } // First non-flag token is the image reference. if !imageRefRe.MatchString(tok) { return fmt.Errorf("%w: 镜像名称不合法", ErrInvalid) } imageFound = true break } if !imageFound { return fmt.Errorf("%w: 未找到镜像名称", ErrInvalid) } if !detached { return fmt.Errorf("%w: 请加上 -d 或 --detach,面板无法托管交互式容器", ErrInvalid) } return nil } func splitFlag(tok string) (string, string, bool) { if i := strings.Index(tok, "="); i >= 0 { return tok[:i], tok[i+1:], true } return tok, "", false } func validateMount(value string) error { value = strings.TrimSpace(value) if name, rest, ok := strings.Cut(value, "="); ok && name != "" { // --mount=type=bind,source=/host,target=/container for _, part := range strings.Split(rest, ",") { part = strings.TrimSpace(part) if strings.HasPrefix(part, "source=/") || strings.HasPrefix(part, "src=/") { src := strings.TrimPrefix(strings.TrimPrefix(part, "source="), "src=") if src == "/" || src == "/etc" { return fmt.Errorf("%w: 不允许挂载根目录或 /etc", ErrInvalid) } } } return nil } // -v /host:/container[:mode] parts := strings.Split(value, ":") if len(parts) >= 2 && strings.HasPrefix(parts[0], "/") { if parts[0] == "/" || parts[0] == "/etc" { return fmt.Errorf("%w: 不允许挂载根目录或 /etc", ErrInvalid) } } return nil } // ValidateCompose applies a small set of safety checks before writing YAML. func ValidateCompose(yaml string) error { if len(yaml) > 64<<10 { return fmt.Errorf("%w: compose 文件超过 64KB", ErrInvalid) } if !strings.Contains(yaml, "services:") { return fmt.Errorf("%w: compose 文件必须包含 services", ErrInvalid) } if composePrivRe.MatchString(yaml) { return fmt.Errorf("%w: compose 中不允许 privileged: true", ErrInvalid) } return nil } func validContainerRef(ref string) bool { ref = strings.TrimSpace(ref) return containerIDRe.MatchString(ref) || containerRefRe.MatchString(ref) } func validResourceName(name string) bool { return resourceNameRe.MatchString(strings.TrimSpace(name)) }