1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
24 "git.arvados.org/arvados.git/lib/controller/rpc"
25 "git.arvados.org/arvados.git/lib/selfsigned"
26 "git.arvados.org/arvados.git/sdk/go/arvados"
27 "git.arvados.org/arvados.git/sdk/go/auth"
28 "git.arvados.org/arvados.git/sdk/go/ctxlog"
29 "git.arvados.org/arvados.git/sdk/go/httpserver"
30 "github.com/creack/pty"
31 "github.com/google/shlex"
32 "github.com/hashicorp/yamux"
33 "golang.org/x/crypto/ssh"
34 "golang.org/x/net/context"
37 type GatewayTarget interface {
38 // Command that will execute cmd inside the container
39 InjectCommand(ctx context.Context, detachKeys, username string, usingTTY bool, cmd []string) (*exec.Cmd, error)
41 // IP address inside container
42 IPAddress() (string, error)
45 type GatewayTargetStub struct{}
47 func (GatewayTargetStub) IPAddress() (string, error) { return "127.0.0.1", nil }
48 func (GatewayTargetStub) InjectCommand(ctx context.Context, detachKeys, username string, usingTTY bool, cmd []string) (*exec.Cmd, error) {
49 return exec.CommandContext(ctx, cmd[0], cmd[1:]...), nil
54 // Caller should set Address to "", or "host:0" or "host:port"
55 // where host is a known external IP address; port is a
56 // desired port number to listen on; and ":0" chooses an
57 // available dynamic port.
59 // If Address is "", Start() listens only on the loopback
60 // interface (and changes Address to "127.0.0.1:port").
61 // Otherwise it listens on all interfaces.
63 // If Address is "host:0", Start() updates Address to
69 Printf(fmt string, args ...interface{})
71 // If non-nil, set up a ContainerGatewayTunnel, so that the
72 // controller can connect to us even if our external IP
73 // address is unknown or not routable from controller.
74 ArvadosClient *arvados.Client
76 // When a tunnel is connected or reconnected, this func (if
77 // not nil) will be called with the InternalURL of the
78 // controller process at the other end of the tunnel.
79 UpdateTunnelURL func(url string)
81 sshConfig ssh.ServerConfig
86 // Start starts an http server that allows authenticated clients to open an
87 // interactive "docker exec" session and (in future) connect to tcp ports
88 // inside the docker container.
89 func (gw *Gateway) Start() error {
90 gw.sshConfig = ssh.ServerConfig{
92 PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
96 return nil, fmt.Errorf("cannot specify user %q via ssh client", c.User())
98 PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
100 return &ssh.Permissions{
101 Extensions: map[string]string{
102 "pubkey-fp": ssh.FingerprintSHA256(pubKey),
106 return nil, fmt.Errorf("cannot specify user %q via ssh client", c.User())
109 pvt, err := rsa.GenerateKey(rand.Reader, 2048)
117 signer, err := ssh.NewSignerFromKey(pvt)
121 gw.sshConfig.AddHostKey(signer)
123 // Address (typically provided by arvados-dispatch-cloud) is
124 // HOST:PORT where HOST is our IP address or hostname as seen
125 // from arvados-controller, and PORT is either the desired
126 // port where we should run our gateway server, or "0" if we
127 // should choose an available port.
128 extAddr := gw.Address
129 // Generally we can't know which local interface corresponds
130 // to an externally reachable IP address, so if we expect to
131 // be reachable by external hosts, we listen on all
135 // If the dispatcher doesn't tell us our external IP
136 // address, controller will only be able to connect
137 // through the tunnel (see runTunnel), so our gateway
138 // server only needs to listen on the loopback
140 extAddr = "127.0.0.1:0"
141 listenHost = "127.0.0.1"
143 extHost, extPort, err := net.SplitHostPort(extAddr)
147 cert, err := selfsigned.CertGenerator{}.Generate()
151 h := hmac.New(sha256.New, []byte(gw.AuthSecret))
152 h.Write(cert.Certificate[0])
153 gw.requestAuth = fmt.Sprintf("%x", h.Sum(nil))
155 h.Write([]byte(gw.requestAuth))
156 gw.respondAuth = fmt.Sprintf("%x", h.Sum(nil))
158 srv := &httpserver.Server{
160 Handler: http.HandlerFunc(gw.handleSSH),
161 TLSConfig: &tls.Config{
162 Certificates: []tls.Certificate{cert},
165 Addr: net.JoinHostPort(listenHost, extPort),
173 gw.Log.Printf("gateway server stopped: %s", err)
175 // Get the port number we are listening on (extPort might be
176 // "0" or a port name, in which case this will be different).
177 _, listenPort, err := net.SplitHostPort(srv.Addr)
181 // When changing state to Running, the caller will want to set
182 // gateway_address to a "HOST:PORT" that, if controller
183 // connects to it, will reach this gateway server.
185 // The most likely thing to work is: HOST is our external
186 // hostname/IP as provided by the caller
187 // (arvados-dispatch-cloud) or 127.0.0.1 to indicate
188 // non-tunnel connections aren't available; and PORT is the
189 // port number we are listening on.
190 gw.Address = net.JoinHostPort(extHost, listenPort)
191 gw.Log.Printf("gateway server listening at %s", gw.Address)
192 if gw.ArvadosClient != nil {
193 go gw.maintainTunnel(gw.Address)
198 func (gw *Gateway) maintainTunnel(addr string) {
199 for ; ; time.Sleep(5 * time.Second) {
200 err := gw.runTunnel(addr)
201 gw.Log.Printf("runTunnel: %s", err)
205 // runTunnel connects to controller and sets up a tunnel through
206 // which controller can connect to the gateway server at the given
208 func (gw *Gateway) runTunnel(addr string) error {
209 ctx := auth.NewContext(context.Background(), auth.NewCredentials(gw.ArvadosClient.AuthToken))
210 arpc := rpc.NewConn("", &url.URL{Scheme: "https", Host: gw.ArvadosClient.APIHost}, gw.ArvadosClient.Insecure, rpc.PassthroughTokenProvider)
211 tun, err := arpc.ContainerGatewayTunnel(ctx, arvados.ContainerGatewayTunnelOptions{
212 UUID: gw.ContainerUUID,
213 AuthSecret: gw.AuthSecret,
216 return fmt.Errorf("error creating gateway tunnel: %s", err)
218 mux, err := yamux.Client(tun.Conn, nil)
220 return fmt.Errorf("error setting up mux client end: %s", err)
222 if url := tun.Header.Get("X-Arvados-Internal-Url"); url != "" && gw.UpdateTunnelURL != nil {
223 gw.UpdateTunnelURL(url)
226 muxconn, err := mux.AcceptStream()
230 gw.Log.Printf("tunnel connection %d started", muxconn.StreamID())
232 defer muxconn.Close()
233 gwconn, err := net.Dial("tcp", addr)
235 gw.Log.Printf("tunnel connection %d: error connecting to %s: %s", muxconn.StreamID(), addr, err)
239 var wg sync.WaitGroup
243 _, err := io.Copy(gwconn, muxconn)
245 gw.Log.Printf("tunnel connection %d: tunnel: %s", muxconn.StreamID(), err)
252 _, err := io.Copy(muxconn, gwconn)
254 gw.Log.Printf("tunnel connection %d: gateway: %s", muxconn.StreamID(), err)
260 gw.Log.Printf("tunnel connection %d finished", muxconn.StreamID())
265 // handleSSH connects to an SSH server that allows the caller to run
266 // interactive commands as root (or any other desired user) inside the
267 // container. The tunnel itself can only be created by an
268 // authenticated caller, so the SSH server itself is wide open (any
269 // password or key will be accepted).
271 // Requests must have path "/ssh" and the following headers:
273 // Connection: upgrade
275 // X-Arvados-Target-Uuid: uuid of container
276 // X-Arvados-Authorization: must match
277 // hmac(AuthSecret,certfingerprint) (this prevents other containers
278 // and shell nodes from connecting directly)
282 // X-Arvados-Detach-Keys: argument to "docker exec --detach-keys",
283 // e.g., "ctrl-p,ctrl-q"
284 // X-Arvados-Login-Username: argument to "docker exec --user": account
285 // used to run command(s) inside the container.
286 func (gw *Gateway) handleSSH(w http.ResponseWriter, req *http.Request) {
287 // In future we'll handle browser traffic too, but for now the
288 // only traffic we expect is an SSH tunnel from
289 // (*lib/controller/localdb.Conn)ContainerSSH()
290 if req.Method != "POST" || req.Header.Get("Upgrade") != "ssh" {
291 http.Error(w, "path not found", http.StatusNotFound)
295 if want := req.Form.Get("uuid"); want != gw.ContainerUUID {
296 http.Error(w, fmt.Sprintf("misdirected request: meant for %q but received by crunch-run %q", want, gw.ContainerUUID), http.StatusBadGateway)
299 if req.Header.Get("X-Arvados-Authorization") != gw.requestAuth {
300 http.Error(w, "bad X-Arvados-Authorization header", http.StatusUnauthorized)
303 detachKeys := req.Form.Get("detach_keys")
304 username := req.Form.Get("login_username")
308 hj, ok := w.(http.Hijacker)
310 http.Error(w, "ResponseWriter does not support connection upgrade", http.StatusInternalServerError)
313 netconn, _, err := hj.Hijack()
315 http.Error(w, err.Error(), http.StatusInternalServerError)
318 defer netconn.Close()
319 w.Header().Set("Connection", "upgrade")
320 w.Header().Set("Upgrade", "ssh")
321 w.Header().Set("X-Arvados-Authorization-Response", gw.respondAuth)
322 netconn.Write([]byte("HTTP/1.1 101 Switching Protocols\r\n"))
323 w.Header().Write(netconn)
324 netconn.Write([]byte("\r\n"))
328 conn, newchans, reqs, err := ssh.NewServerConn(netconn, &gw.sshConfig)
331 } else if err != nil {
332 gw.Log.Printf("ssh.NewServerConn: %s", err)
336 go ssh.DiscardRequests(reqs)
337 for newch := range newchans {
338 switch newch.ChannelType() {
340 go gw.handleDirectTCPIP(ctx, newch)
342 go gw.handleSession(ctx, newch, detachKeys, username)
344 go newch.Reject(ssh.UnknownChannelType, fmt.Sprintf("unsupported channel type %q", newch.ChannelType()))
349 func (gw *Gateway) handleDirectTCPIP(ctx context.Context, newch ssh.NewChannel) {
350 ch, reqs, err := newch.Accept()
352 gw.Log.Printf("accept direct-tcpip channel: %s", err)
356 go ssh.DiscardRequests(reqs)
358 // RFC 4254 7.2 (copy of channelOpenDirectMsg in
359 // golang.org/x/crypto/ssh)
366 err = ssh.Unmarshal(newch.ExtraData(), &msg)
368 fmt.Fprintf(ch.Stderr(), "unmarshal direct-tcpip extradata: %s\n", err)
372 case "localhost", "0.0.0.0", "127.0.0.1", "::1", "::":
374 fmt.Fprintf(ch.Stderr(), "cannot forward to ports on %q, only localhost\n", msg.Raddr)
378 dstaddr, err := gw.Target.IPAddress()
380 fmt.Fprintf(ch.Stderr(), "container has no IP address: %s\n", err)
382 } else if dstaddr == "" {
383 fmt.Fprintf(ch.Stderr(), "container has no IP address\n")
387 dst := net.JoinHostPort(dstaddr, fmt.Sprintf("%d", msg.Rport))
388 tcpconn, err := net.Dial("tcp", dst)
390 fmt.Fprintf(ch.Stderr(), "%s: %s\n", dst, err)
394 n, _ := io.Copy(ch, tcpconn)
395 ctxlog.FromContext(ctx).Debugf("tcpip: sent %d bytes\n", n)
398 n, _ := io.Copy(tcpconn, ch)
399 ctxlog.FromContext(ctx).Debugf("tcpip: received %d bytes\n", n)
402 func (gw *Gateway) handleSession(ctx context.Context, newch ssh.NewChannel, detachKeys, username string) {
403 ch, reqs, err := newch.Accept()
405 gw.Log.Printf("accept session channel: %s", err)
408 var pty0, tty0 *os.File
409 // Where to send errors/messages for the client to see
410 logw := io.Writer(ch.Stderr())
411 // How to end lines when sending errors/messages to the client
412 // (changes to \r\n when using a pty)
414 // Env vars to add to child process
415 termEnv := []string(nil)
416 for req := range reqs {
419 case "shell", "exec":
424 ssh.Unmarshal(req.Payload, &payload)
425 execargs, err := shlex.Split(payload.Command)
427 fmt.Fprintf(logw, "error parsing supplied command: %s"+eol, err)
430 if len(execargs) == 0 {
431 execargs = []string{"/bin/bash", "-login"}
438 ch.SendRequest("exit-status", false, ssh.Marshal(&resp))
442 cmd, err := gw.Target.InjectCommand(ctx, detachKeys, username, tty0 != nil, execargs)
444 fmt.Fprintln(ch.Stderr(), err)
451 cmd.Stderr = ch.Stderr()
456 var wg sync.WaitGroup
459 go func() { io.Copy(ch, pty0); wg.Done() }()
460 go func() { io.Copy(pty0, ch); wg.Done() }()
461 // Send our own debug messages to tty as well.
464 cmd.SysProcAttr = &syscall.SysProcAttr{
465 Setctty: tty0 != nil,
468 cmd.Env = append(os.Environ(), termEnv...)
470 if exiterr, ok := err.(*exec.ExitError); ok {
471 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
472 resp.Status = uint32(status.ExitStatus())
474 } else if err != nil {
475 // Propagate errors like `exec: "docker": executable file not found in $PATH`
476 fmt.Fprintln(ch.Stderr(), err)
478 errClose := ch.CloseWrite()
479 if resp.Status == 0 && (err != nil || errClose != nil) {
485 p, t, err := pty.Open()
487 fmt.Fprintf(ch.Stderr(), "pty failed: %s"+eol, err)
501 ssh.Unmarshal(req.Payload, &payload)
502 termEnv = []string{"TERM=" + payload.Term, "USE_TTY=1"}
503 err = pty.Setsize(pty0, &pty.Winsize{Rows: uint16(payload.Rows), Cols: uint16(payload.Cols), X: uint16(payload.X), Y: uint16(payload.Y)})
505 fmt.Fprintf(logw, "pty-req: setsize failed: %s"+eol, err)
507 case "window-change":
514 ssh.Unmarshal(req.Payload, &payload)
515 err := pty.Setsize(pty0, &pty.Winsize{Rows: uint16(payload.Rows), Cols: uint16(payload.Cols), X: uint16(payload.X), Y: uint16(payload.Y)})
517 fmt.Fprintf(logw, "window-change: setsize failed: %s"+eol, err)
522 // TODO: implement "env"
523 // requests by setting env
524 // vars in the docker-exec
525 // command (not docker-exec's
526 // own environment, which
527 // would be a gaping security
530 // fmt.Fprintf(logw, "declining %q req"+eol, req.Type)