1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
24 "git.arvados.org/arvados.git/lib/selfsigned"
25 "git.arvados.org/arvados.git/sdk/go/ctxlog"
26 "git.arvados.org/arvados.git/sdk/go/httpserver"
27 "github.com/creack/pty"
28 dockerclient "github.com/docker/docker/client"
29 "github.com/google/shlex"
30 "golang.org/x/crypto/ssh"
31 "golang.org/x/net/context"
35 DockerContainerID *string
37 Address string // listen host:port; if port=0, Start() will change it to the selected port
40 Printf(fmt string, args ...interface{})
42 // return local ip address of running container, or "" if not available
43 ContainerIPAddress func() (string, error)
45 sshConfig ssh.ServerConfig
50 // Start starts an http server that allows authenticated clients to open an
51 // interactive "docker exec" session and (in future) connect to tcp ports
52 // inside the docker container.
53 func (gw *Gateway) Start() error {
54 gw.sshConfig = ssh.ServerConfig{
56 PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
60 return nil, fmt.Errorf("cannot specify user %q via ssh client", c.User())
62 PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
64 return &ssh.Permissions{
65 Extensions: map[string]string{
66 "pubkey-fp": ssh.FingerprintSHA256(pubKey),
70 return nil, fmt.Errorf("cannot specify user %q via ssh client", c.User())
73 pvt, err := rsa.GenerateKey(rand.Reader, 2048)
81 signer, err := ssh.NewSignerFromKey(pvt)
85 gw.sshConfig.AddHostKey(signer)
87 // Address (typically provided by arvados-dispatch-cloud) is
88 // HOST:PORT where HOST is our IP address or hostname as seen
89 // from arvados-controller, and PORT is either the desired
90 // port where we should run our gateway server, or "0" if we
91 // should choose an available port.
92 host, port, err := net.SplitHostPort(gw.Address)
96 cert, err := selfsigned.CertGenerator{}.Generate()
100 h := hmac.New(sha256.New, []byte(gw.AuthSecret))
101 h.Write(cert.Certificate[0])
102 gw.requestAuth = fmt.Sprintf("%x", h.Sum(nil))
104 h.Write([]byte(gw.requestAuth))
105 gw.respondAuth = fmt.Sprintf("%x", h.Sum(nil))
107 srv := &httpserver.Server{
109 Handler: http.HandlerFunc(gw.handleSSH),
110 TLSConfig: &tls.Config{
111 Certificates: []tls.Certificate{cert},
120 // Get the port number we are listening on (the port might be
121 // "0" or a port name, in which case this will be different).
122 _, port, err = net.SplitHostPort(srv.Addr)
126 // When changing state to Running, we will set
127 // gateway_address to "HOST:PORT" where HOST is our
128 // external hostname/IP as provided by arvados-dispatch-cloud,
129 // and PORT is the port number we ended up listening on.
130 gw.Address = net.JoinHostPort(host, port)
134 // handleSSH connects to an SSH server that allows the caller to run
135 // interactive commands as root (or any other desired user) inside the
136 // container. The tunnel itself can only be created by an
137 // authenticated caller, so the SSH server itself is wide open (any
138 // password or key will be accepted).
140 // Requests must have path "/ssh" and the following headers:
142 // Connection: upgrade
144 // X-Arvados-Target-Uuid: uuid of container
145 // X-Arvados-Authorization: must match
146 // hmac(AuthSecret,certfingerprint) (this prevents other containers
147 // and shell nodes from connecting directly)
151 // X-Arvados-Detach-Keys: argument to "docker exec --detach-keys",
152 // e.g., "ctrl-p,ctrl-q"
153 // X-Arvados-Login-Username: argument to "docker exec --user": account
154 // used to run command(s) inside the container.
155 func (gw *Gateway) handleSSH(w http.ResponseWriter, req *http.Request) {
156 // In future we'll handle browser traffic too, but for now the
157 // only traffic we expect is an SSH tunnel from
158 // (*lib/controller/localdb.Conn)ContainerSSH()
159 if req.Method != "GET" || req.Header.Get("Upgrade") != "ssh" {
160 http.Error(w, "path not found", http.StatusNotFound)
163 if want := req.Header.Get("X-Arvados-Target-Uuid"); want != gw.ContainerUUID {
164 http.Error(w, fmt.Sprintf("misdirected request: meant for %q but received by crunch-run %q", want, gw.ContainerUUID), http.StatusBadGateway)
167 if req.Header.Get("X-Arvados-Authorization") != gw.requestAuth {
168 http.Error(w, "bad X-Arvados-Authorization header", http.StatusUnauthorized)
171 detachKeys := req.Header.Get("X-Arvados-Detach-Keys")
172 username := req.Header.Get("X-Arvados-Login-Username")
176 hj, ok := w.(http.Hijacker)
178 http.Error(w, "ResponseWriter does not support connection upgrade", http.StatusInternalServerError)
181 netconn, _, err := hj.Hijack()
183 http.Error(w, err.Error(), http.StatusInternalServerError)
186 defer netconn.Close()
187 w.Header().Set("Connection", "upgrade")
188 w.Header().Set("Upgrade", "ssh")
189 w.Header().Set("X-Arvados-Authorization-Response", gw.respondAuth)
190 netconn.Write([]byte("HTTP/1.1 101 Switching Protocols\r\n"))
191 w.Header().Write(netconn)
192 netconn.Write([]byte("\r\n"))
196 conn, newchans, reqs, err := ssh.NewServerConn(netconn, &gw.sshConfig)
198 gw.Log.Printf("ssh.NewServerConn: %s", err)
202 go ssh.DiscardRequests(reqs)
203 for newch := range newchans {
204 switch newch.ChannelType() {
206 go gw.handleDirectTCPIP(ctx, newch)
208 go gw.handleSession(ctx, newch, detachKeys, username)
210 go newch.Reject(ssh.UnknownChannelType, fmt.Sprintf("unsupported channel type %q", newch.ChannelType()))
215 func (gw *Gateway) handleDirectTCPIP(ctx context.Context, newch ssh.NewChannel) {
216 ch, reqs, err := newch.Accept()
218 gw.Log.Printf("accept direct-tcpip channel: %s", err)
222 go ssh.DiscardRequests(reqs)
224 // RFC 4254 7.2 (copy of channelOpenDirectMsg in
225 // golang.org/x/crypto/ssh)
232 err = ssh.Unmarshal(newch.ExtraData(), &msg)
234 fmt.Fprintf(ch.Stderr(), "unmarshal direct-tcpip extradata: %s\n", err)
238 case "localhost", "0.0.0.0", "127.0.0.1", "::1", "::":
240 fmt.Fprintf(ch.Stderr(), "cannot forward to ports on %q, only localhost\n", msg.Raddr)
245 if gw.ContainerIPAddress != nil {
246 dstaddr, err = gw.ContainerIPAddress()
248 fmt.Fprintf(ch.Stderr(), "container has no IP address: %s\n", err)
253 fmt.Fprintf(ch.Stderr(), "container has no IP address\n")
257 dst := net.JoinHostPort(dstaddr, fmt.Sprintf("%d", msg.Rport))
258 tcpconn, err := net.Dial("tcp", dst)
260 fmt.Fprintf(ch.Stderr(), "%s: %s\n", dst, err)
264 n, _ := io.Copy(ch, tcpconn)
265 ctxlog.FromContext(ctx).Debugf("tcpip: sent %d bytes\n", n)
268 n, _ := io.Copy(tcpconn, ch)
269 ctxlog.FromContext(ctx).Debugf("tcpip: received %d bytes\n", n)
272 func (gw *Gateway) handleSession(ctx context.Context, newch ssh.NewChannel, detachKeys, username string) {
273 ch, reqs, err := newch.Accept()
275 gw.Log.Printf("accept session channel: %s", err)
278 var pty0, tty0 *os.File
279 // Where to send errors/messages for the client to see
280 logw := io.Writer(ch.Stderr())
281 // How to end lines when sending errors/messages to the client
282 // (changes to \r\n when using a pty)
284 // Env vars to add to child process
285 termEnv := []string(nil)
286 for req := range reqs {
289 case "shell", "exec":
294 ssh.Unmarshal(req.Payload, &payload)
295 execargs, err := shlex.Split(payload.Command)
297 fmt.Fprintf(logw, "error parsing supplied command: %s"+eol, err)
300 if len(execargs) == 0 {
301 execargs = []string{"/bin/bash", "-login"}
304 cmd := exec.CommandContext(ctx, "docker", "exec", "-i", "--detach-keys="+detachKeys, "--user="+username)
307 cmd.Stderr = ch.Stderr()
309 cmd.Args = append(cmd.Args, "-t")
313 var wg sync.WaitGroup
316 go func() { io.Copy(ch, pty0); wg.Done() }()
317 go func() { io.Copy(pty0, ch); wg.Done() }()
318 // Send our own debug messages to tty as well.
321 cmd.Args = append(cmd.Args, *gw.DockerContainerID)
322 cmd.Args = append(cmd.Args, execargs...)
323 cmd.SysProcAttr = &syscall.SysProcAttr{
324 Setctty: tty0 != nil,
327 cmd.Env = append(os.Environ(), termEnv...)
332 if exiterr, ok := err.(*exec.ExitError); ok {
333 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
334 resp.Status = uint32(status.ExitStatus())
336 } else if err != nil {
337 // Propagate errors like `exec: "docker": executable file not found in $PATH`
338 fmt.Fprintln(ch.Stderr(), err)
340 errClose := ch.CloseWrite()
341 if resp.Status == 0 && (err != nil || errClose != nil) {
344 ch.SendRequest("exit-status", false, ssh.Marshal(&resp))
349 p, t, err := pty.Open()
351 fmt.Fprintf(ch.Stderr(), "pty failed: %s"+eol, err)
365 ssh.Unmarshal(req.Payload, &payload)
366 termEnv = []string{"TERM=" + payload.Term, "USE_TTY=1"}
367 err = pty.Setsize(pty0, &pty.Winsize{Rows: uint16(payload.Rows), Cols: uint16(payload.Cols), X: uint16(payload.X), Y: uint16(payload.Y)})
369 fmt.Fprintf(logw, "pty-req: setsize failed: %s"+eol, err)
371 case "window-change":
378 ssh.Unmarshal(req.Payload, &payload)
379 err := pty.Setsize(pty0, &pty.Winsize{Rows: uint16(payload.Rows), Cols: uint16(payload.Cols), X: uint16(payload.X), Y: uint16(payload.Y)})
381 fmt.Fprintf(logw, "window-change: setsize failed: %s"+eol, err)
386 // TODO: implement "env"
387 // requests by setting env
388 // vars in the docker-exec
389 // command (not docker-exec's
390 // own environment, which
391 // would be a gaping security
394 // fmt.Fprintf(logw, "declining %q req"+eol, req.Type)
402 func dockerContainerIPAddress(containerID *string) func() (string, error) {
403 var saved atomic.Value
404 return func() (string, error) {
405 if ip, ok := saved.Load().(*string); ok {
408 docker, err := dockerclient.NewClient(dockerclient.DefaultDockerHost, "1.21", nil, nil)
410 return "", fmt.Errorf("cannot create docker client: %s", err)
412 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
414 ctr, err := docker.ContainerInspect(ctx, *containerID)
416 return "", fmt.Errorf("cannot get docker container info: %s", err)
418 ip := ctr.NetworkSettings.IPAddress
420 // TODO: try to enable networking if it wasn't
421 // already enabled when the container was
423 return "", fmt.Errorf("container has no IP address")