| 1 | package containerenv |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/ed25519" |
| 7 | "crypto/rand" |
| 8 | "encoding/pem" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "time" |
| 15 | |
| 16 | "github.com/sylvinus/agent-vm/internal/cage" |
| 17 | "github.com/sylvinus/agent-vm/internal/host" |
| 18 | "golang.org/x/crypto/ssh" |
| 19 | ) |
| 20 | |
| 21 | func (r *Runtime) ensureSSHKey() ([]byte, error) { |
| 22 | if err := host.EnsurePrivateDir(r.InstanceDir()); err != nil { |
| 23 | return nil, err |
| 24 | } |
| 25 | path := filepath.Join(r.InstanceDir(), "id_ed25519") |
| 26 | if data, err := os.ReadFile(path); err == nil { |
| 27 | if err := host.CheckPrivateFile(path); err != nil { |
| 28 | return nil, err |
| 29 | } |
| 30 | key, err := ssh.ParsePrivateKey(data) |
| 31 | if err != nil { |
| 32 | return nil, errors.New("容器 SSH 密钥无效;未覆盖现有密钥") |
| 33 | } |
| 34 | return ssh.MarshalAuthorizedKey(key.PublicKey()), nil |
| 35 | } else if !os.IsNotExist(err) { |
| 36 | return nil, err |
| 37 | } |
| 38 | _, private, err := ed25519.GenerateKey(rand.Reader) |
| 39 | if err != nil { |
| 40 | return nil, err |
| 41 | } |
| 42 | block, err := ssh.MarshalPrivateKey(private, "Cage container") |
| 43 | if err != nil { |
| 44 | return nil, err |
| 45 | } |
| 46 | file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) |
| 47 | if err != nil { |
| 48 | return nil, err |
| 49 | } |
| 50 | err = pem.Encode(file, block) |
| 51 | if closeErr := file.Close(); err == nil { |
| 52 | err = closeErr |
| 53 | } |
| 54 | if err != nil { |
| 55 | return nil, err |
| 56 | } |
| 57 | key, err := ssh.NewPublicKey(private.Public()) |
| 58 | if err != nil { |
| 59 | return nil, err |
| 60 | } |
| 61 | return ssh.MarshalAuthorizedKey(key), nil |
| 62 | } |
| 63 | |
| 64 | |
| 65 | |
| 66 | func (r *Runtime) InstallAccess(ctx context.Context) error { |
| 67 | inspection, err := r.Inspect(ctx) |
| 68 | if err != nil { |
| 69 | return err |
| 70 | } |
| 71 | if !inspection.State.Running { |
| 72 | return errors.New("请先启动容器") |
| 73 | } |
| 74 | public, err := r.ensureSSHKey() |
| 75 | if err != nil { |
| 76 | return err |
| 77 | } |
| 78 | command := r.command(ctx, "exec", "-i", "--user", "0", inspection.State.ContainerID, "/bin/sh", "-c", `set -eu |
| 79 | test -d /home/cage |
| 80 | umask 077 |
| 81 | cat > /etc/ssh/cage_authorized_keys |
| 82 | chmod 0644 /etc/ssh/cage_authorized_keys |
| 83 | ssh-keygen -A |
| 84 | cat /etc/ssh/ssh_host_ed25519_key.pub |
| 85 | `) |
| 86 | command.Stdin = bytes.NewReader(public) |
| 87 | var output bytes.Buffer |
| 88 | command.Stdout = &limitedWriter{writer: &output, left: 4096} |
| 89 | if err := command.Run(); err != nil { |
| 90 | return errors.New("无法配置容器 SSH 访问") |
| 91 | } |
| 92 | key, _, _, rest, err := ssh.ParseAuthorizedKey(output.Bytes()) |
| 93 | if err != nil || len(bytes.TrimSpace(rest)) != 0 || key.Type() != ssh.KeyAlgoED25519 { |
| 94 | return errors.New("容器 SSH 主机密钥无效") |
| 95 | } |
| 96 | line := "cage-container-" + r.identity + " " + strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))) + "\n" |
| 97 | path := filepath.Join(r.InstanceDir(), "known_hosts") |
| 98 | if old, err := os.ReadFile(path); err == nil { |
| 99 | if err := host.CheckPrivateFile(path); err != nil { |
| 100 | return err |
| 101 | } |
| 102 | if !bytes.Equal(old, []byte(line)) { |
| 103 | return errors.New("容器 SSH 主机密钥已变化;拒绝覆盖信任记录") |
| 104 | } |
| 105 | return nil |
| 106 | } else if !os.IsNotExist(err) { |
| 107 | return err |
| 108 | } |
| 109 | return os.WriteFile(path, []byte(line), 0600) |
| 110 | } |
| 111 | |
| 112 | func sshConfigValue(value string) (string, error) { |
| 113 | if strings.ContainsAny(value, "\x00\r\n") { |
| 114 | return "", errors.New("SSH 配置路径无效") |
| 115 | } |
| 116 | return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(value) + `"`, nil |
| 117 | } |
| 118 | |
| 119 | func (r *Runtime) writeSSHConfig(port int) error { |
| 120 | if port < 1024 || port > 65535 { |
| 121 | return errors.New("容器 SSH 入口端口无效") |
| 122 | } |
| 123 | identity, err := sshConfigValue(filepath.Join(r.InstanceDir(), "id_ed25519")) |
| 124 | if err != nil { |
| 125 | return err |
| 126 | } |
| 127 | known, err := sshConfigValue(filepath.Join(r.InstanceDir(), "known_hosts")) |
| 128 | if err != nil { |
| 129 | return err |
| 130 | } |
| 131 | data := fmt.Sprintf("Host cage-container\n HostName 127.0.0.1\n Port %d\n User cage\n IdentityFile %s\n IdentitiesOnly yes\n HostKeyAlias cage-container-%s\n HostKeyAlgorithms ssh-ed25519\n UserKnownHostsFile %s\n StrictHostKeyChecking yes\n PasswordAuthentication no\n KbdInteractiveAuthentication no\n ForwardAgent no\n ForwardX11 no\n PermitLocalCommand no\n", port, identity, r.identity, known) |
| 132 | return os.WriteFile(r.SSHConfig(), []byte(data), 0600) |
| 133 | } |
| 134 | |
| 135 | |
| 136 | |
| 137 | func (r *Runtime) Stop(ctx context.Context) error { |
| 138 | if err := host.EnsurePrivateDir(r.InstanceDir()); err != nil { |
| 139 | return err |
| 140 | } |
| 141 | unlock, err := lockRuntime(ctx, filepath.Join(r.InstanceDir(), "lifecycle.lock")) |
| 142 | if err != nil { |
| 143 | return err |
| 144 | } |
| 145 | defer unlock() |
| 146 | rootless, _, err := r.engineSecurity(ctx) |
| 147 | if err != nil { |
| 148 | return err |
| 149 | } |
| 150 | if !rootless { |
| 151 | return errors.New("拒绝操作非 rootless 容器引擎") |
| 152 | } |
| 153 | container, err := r.inspectContainer(ctx) |
| 154 | if err != nil { |
| 155 | return err |
| 156 | } |
| 157 | if container == nil { |
| 158 | return nil |
| 159 | } |
| 160 | if client, err := cage.OpenGateClient(r.InstanceDir()); err == nil { |
| 161 | closeCtx, cancel := context.WithTimeout(ctx, 3*time.Second) |
| 162 | _, _ = client.Close(closeCtx, "容器正在停止") |
| 163 | cancel() |
| 164 | } |
| 165 | if container.State.Running { |
| 166 | if _, err = r.output(ctx, "stop", "--time", "20", container.ID); err != nil { |
| 167 | return err |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | |
| 172 | cleanupCtx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| 173 | defer cancel() |
| 174 | release, err := lockRuntime(cleanupCtx, filepath.Join(r.InstanceDir(), "network.lock")) |
| 175 | if err != nil { |
| 176 | return errors.New("容器已停止,网络服务仍在退出;原文件保留,请稍后重试") |
| 177 | } |
| 178 | defer release() |
| 179 | for _, name := range []string{"network.json", "cage-running.json"} { |
| 180 | if err := os.Remove(filepath.Join(r.InstanceDir(), name)); err != nil && !os.IsNotExist(err) { |
| 181 | return err |
| 182 | } |
| 183 | } |
| 184 | return nil |
| 185 | } |