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),
171 // Get the port number we are listening on (extPort might be
172 // "0" or a port name, in which case this will be different).
173 _, listenPort, err := net.SplitHostPort(srv.Addr)
177 // When changing state to Running, the caller will want to set
178 // gateway_address to a "HOST:PORT" that, if controller
179 // connects to it, will reach this gateway server.
181 // The most likely thing to work is: HOST is our external
182 // hostname/IP as provided by the caller
183 // (arvados-dispatch-cloud) or 127.0.0.1 to indicate
184 // non-tunnel connections aren't available; and PORT is the
185 // port number we are listening on.
186 gw.Address = net.JoinHostPort(extHost, listenPort)
187 if gw.ArvadosClient != nil {
188 go gw.maintainTunnel(gw.Address)
193 func (gw *Gateway) maintainTunnel(addr string) {
194 for ; ; time.Sleep(5 * time.Second) {
195 err := gw.runTunnel(addr)
196 gw.Log.Printf("runTunnel: %s", err)
200 // runTunnel connects to controller and sets up a tunnel through
201 // which controller can connect to the gateway server at the given
203 func (gw *Gateway) runTunnel(addr string) error {
204 ctx := auth.NewContext(context.Background(), auth.NewCredentials(gw.ArvadosClient.AuthToken))
205 arpc := rpc.NewConn("", &url.URL{Scheme: "https", Host: gw.ArvadosClient.APIHost}, gw.ArvadosClient.Insecure, rpc.PassthroughTokenProvider)
206 tun, err := arpc.ContainerGatewayTunnel(ctx, arvados.ContainerGatewayTunnelOptions{
207 UUID: gw.ContainerUUID,
208 AuthSecret: gw.AuthSecret,
211 return fmt.Errorf("error creating gateway tunnel: %s", err)
213 mux, err := yamux.Client(tun.Conn, nil)
215 return fmt.Errorf("error setting up mux client end: %s", err)
217 if url := tun.Header.Get("X-Arvados-Internal-Url"); url != "" && gw.UpdateTunnelURL != nil {
218 gw.UpdateTunnelURL(url)
221 muxconn, err := mux.Accept()
225 gw.Log.Printf("receiving connection from tunnel, remoteAddr %s", muxconn.RemoteAddr().String())
227 defer muxconn.Close()
228 gwconn, err := net.Dial("tcp", addr)
230 gw.Log.Printf("error connecting to %s on behalf of tunnel connection: %s", addr, err)
234 var wg sync.WaitGroup
238 io.Copy(gwconn, muxconn)
242 io.Copy(muxconn, gwconn)
249 // handleSSH connects to an SSH server that allows the caller to run
250 // interactive commands as root (or any other desired user) inside the
251 // container. The tunnel itself can only be created by an
252 // authenticated caller, so the SSH server itself is wide open (any
253 // password or key will be accepted).
255 // Requests must have path "/ssh" and the following headers:
257 // Connection: upgrade
259 // X-Arvados-Target-Uuid: uuid of container
260 // X-Arvados-Authorization: must match
261 // hmac(AuthSecret,certfingerprint) (this prevents other containers
262 // and shell nodes from connecting directly)
266 // X-Arvados-Detach-Keys: argument to "docker exec --detach-keys",
267 // e.g., "ctrl-p,ctrl-q"
268 // X-Arvados-Login-Username: argument to "docker exec --user": account
269 // used to run command(s) inside the container.
270 func (gw *Gateway) handleSSH(w http.ResponseWriter, req *http.Request) {
271 // In future we'll handle browser traffic too, but for now the
272 // only traffic we expect is an SSH tunnel from
273 // (*lib/controller/localdb.Conn)ContainerSSH()
274 if req.Method != "POST" || req.Header.Get("Upgrade") != "ssh" {
275 http.Error(w, "path not found", http.StatusNotFound)
279 if want := req.Form.Get("uuid"); want != gw.ContainerUUID {
280 http.Error(w, fmt.Sprintf("misdirected request: meant for %q but received by crunch-run %q", want, gw.ContainerUUID), http.StatusBadGateway)
283 if req.Header.Get("X-Arvados-Authorization") != gw.requestAuth {
284 http.Error(w, "bad X-Arvados-Authorization header", http.StatusUnauthorized)
287 detachKeys := req.Form.Get("detach_keys")
288 username := req.Form.Get("login_username")
292 hj, ok := w.(http.Hijacker)
294 http.Error(w, "ResponseWriter does not support connection upgrade", http.StatusInternalServerError)
297 netconn, _, err := hj.Hijack()
299 http.Error(w, err.Error(), http.StatusInternalServerError)
302 defer netconn.Close()
303 w.Header().Set("Connection", "upgrade")
304 w.Header().Set("Upgrade", "ssh")
305 w.Header().Set("X-Arvados-Authorization-Response", gw.respondAuth)
306 netconn.Write([]byte("HTTP/1.1 101 Switching Protocols\r\n"))
307 w.Header().Write(netconn)
308 netconn.Write([]byte("\r\n"))
312 conn, newchans, reqs, err := ssh.NewServerConn(netconn, &gw.sshConfig)
315 } else if err != nil {
316 gw.Log.Printf("ssh.NewServerConn: %s", err)
320 go ssh.DiscardRequests(reqs)
321 for newch := range newchans {
322 switch newch.ChannelType() {
324 go gw.handleDirectTCPIP(ctx, newch)
326 go gw.handleSession(ctx, newch, detachKeys, username)
328 go newch.Reject(ssh.UnknownChannelType, fmt.Sprintf("unsupported channel type %q", newch.ChannelType()))
333 func (gw *Gateway) handleDirectTCPIP(ctx context.Context, newch ssh.NewChannel) {
334 ch, reqs, err := newch.Accept()
336 gw.Log.Printf("accept direct-tcpip channel: %s", err)
340 go ssh.DiscardRequests(reqs)
342 // RFC 4254 7.2 (copy of channelOpenDirectMsg in
343 // golang.org/x/crypto/ssh)
350 err = ssh.Unmarshal(newch.ExtraData(), &msg)
352 fmt.Fprintf(ch.Stderr(), "unmarshal direct-tcpip extradata: %s\n", err)
356 case "localhost", "0.0.0.0", "127.0.0.1", "::1", "::":
358 fmt.Fprintf(ch.Stderr(), "cannot forward to ports on %q, only localhost\n", msg.Raddr)
362 dstaddr, err := gw.Target.IPAddress()
364 fmt.Fprintf(ch.Stderr(), "container has no IP address: %s\n", err)
366 } else if dstaddr == "" {
367 fmt.Fprintf(ch.Stderr(), "container has no IP address\n")
371 dst := net.JoinHostPort(dstaddr, fmt.Sprintf("%d", msg.Rport))
372 tcpconn, err := net.Dial("tcp", dst)
374 fmt.Fprintf(ch.Stderr(), "%s: %s\n", dst, err)
378 n, _ := io.Copy(ch, tcpconn)
379 ctxlog.FromContext(ctx).Debugf("tcpip: sent %d bytes\n", n)
382 n, _ := io.Copy(tcpconn, ch)
383 ctxlog.FromContext(ctx).Debugf("tcpip: received %d bytes\n", n)
386 func (gw *Gateway) handleSession(ctx context.Context, newch ssh.NewChannel, detachKeys, username string) {
387 ch, reqs, err := newch.Accept()
389 gw.Log.Printf("accept session channel: %s", err)
392 var pty0, tty0 *os.File
393 // Where to send errors/messages for the client to see
394 logw := io.Writer(ch.Stderr())
395 // How to end lines when sending errors/messages to the client
396 // (changes to \r\n when using a pty)
398 // Env vars to add to child process
399 termEnv := []string(nil)
400 for req := range reqs {
403 case "shell", "exec":
408 ssh.Unmarshal(req.Payload, &payload)
409 execargs, err := shlex.Split(payload.Command)
411 fmt.Fprintf(logw, "error parsing supplied command: %s"+eol, err)
414 if len(execargs) == 0 {
415 execargs = []string{"/bin/bash", "-login"}
422 ch.SendRequest("exit-status", false, ssh.Marshal(&resp))
426 cmd, err := gw.Target.InjectCommand(ctx, detachKeys, username, tty0 != nil, execargs)
428 fmt.Fprintln(ch.Stderr(), err)
435 cmd.Stderr = ch.Stderr()
440 var wg sync.WaitGroup
443 go func() { io.Copy(ch, pty0); wg.Done() }()
444 go func() { io.Copy(pty0, ch); wg.Done() }()
445 // Send our own debug messages to tty as well.
448 cmd.SysProcAttr = &syscall.SysProcAttr{
449 Setctty: tty0 != nil,
452 cmd.Env = append(os.Environ(), termEnv...)
454 if exiterr, ok := err.(*exec.ExitError); ok {
455 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
456 resp.Status = uint32(status.ExitStatus())
458 } else if err != nil {
459 // Propagate errors like `exec: "docker": executable file not found in $PATH`
460 fmt.Fprintln(ch.Stderr(), err)
462 errClose := ch.CloseWrite()
463 if resp.Status == 0 && (err != nil || errClose != nil) {
469 p, t, err := pty.Open()
471 fmt.Fprintf(ch.Stderr(), "pty failed: %s"+eol, err)
485 ssh.Unmarshal(req.Payload, &payload)
486 termEnv = []string{"TERM=" + payload.Term, "USE_TTY=1"}
487 err = pty.Setsize(pty0, &pty.Winsize{Rows: uint16(payload.Rows), Cols: uint16(payload.Cols), X: uint16(payload.X), Y: uint16(payload.Y)})
489 fmt.Fprintf(logw, "pty-req: setsize failed: %s"+eol, err)
491 case "window-change":
498 ssh.Unmarshal(req.Payload, &payload)
499 err := pty.Setsize(pty0, &pty.Winsize{Rows: uint16(payload.Rows), Cols: uint16(payload.Cols), X: uint16(payload.X), Y: uint16(payload.Y)})
501 fmt.Fprintf(logw, "window-change: setsize failed: %s"+eol, err)
506 // TODO: implement "env"
507 // requests by setting env
508 // vars in the docker-exec
509 // command (not docker-exec's
510 // own environment, which
511 // would be a gaping security
514 // fmt.Fprintf(logw, "declining %q req"+eol, req.Type)