02df06cf2159fe6c16802485c8215c37468dd0e1
[arvados.git] / lib / crunchrun / container_gateway.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package crunchrun
6
7 import (
8         "crypto/hmac"
9         "crypto/rand"
10         "crypto/rsa"
11         "crypto/sha256"
12         "crypto/tls"
13         "fmt"
14         "io"
15         "net"
16         "net/http"
17         "net/url"
18         "os"
19         "os/exec"
20         "sync"
21         "syscall"
22         "time"
23
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"
35 )
36
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)
40
41         // IP address inside container
42         IPAddress() (string, error)
43 }
44
45 type GatewayTargetStub struct{}
46
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
50 }
51
52 type Gateway struct {
53         ContainerUUID string
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.
58         //
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.
62         //
63         // If Address is "host:0", Start() updates Address to
64         // "host:port".
65         Address    string
66         AuthSecret string
67         Target     GatewayTarget
68         Log        interface {
69                 Printf(fmt string, args ...interface{})
70         }
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
75
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)
80
81         sshConfig   ssh.ServerConfig
82         requestAuth string
83         respondAuth string
84 }
85
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{
91                 NoClientAuth: true,
92                 PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
93                         if c.User() == "_" {
94                                 return nil, nil
95                         }
96                         return nil, fmt.Errorf("cannot specify user %q via ssh client", c.User())
97                 },
98                 PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
99                         if c.User() == "_" {
100                                 return &ssh.Permissions{
101                                         Extensions: map[string]string{
102                                                 "pubkey-fp": ssh.FingerprintSHA256(pubKey),
103                                         },
104                                 }, nil
105                         }
106                         return nil, fmt.Errorf("cannot specify user %q via ssh client", c.User())
107                 },
108         }
109         pvt, err := rsa.GenerateKey(rand.Reader, 2048)
110         if err != nil {
111                 return err
112         }
113         err = pvt.Validate()
114         if err != nil {
115                 return err
116         }
117         signer, err := ssh.NewSignerFromKey(pvt)
118         if err != nil {
119                 return err
120         }
121         gw.sshConfig.AddHostKey(signer)
122
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
132         // interfaces.
133         listenHost := ""
134         if extAddr == "" {
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
139                 // interface.
140                 extAddr = "127.0.0.1:0"
141                 listenHost = "127.0.0.1"
142         }
143         extHost, extPort, err := net.SplitHostPort(extAddr)
144         if err != nil {
145                 return err
146         }
147         cert, err := selfsigned.CertGenerator{}.Generate()
148         if err != nil {
149                 return err
150         }
151         h := hmac.New(sha256.New, []byte(gw.AuthSecret))
152         h.Write(cert.Certificate[0])
153         gw.requestAuth = fmt.Sprintf("%x", h.Sum(nil))
154         h.Reset()
155         h.Write([]byte(gw.requestAuth))
156         gw.respondAuth = fmt.Sprintf("%x", h.Sum(nil))
157
158         srv := &httpserver.Server{
159                 Server: http.Server{
160                         Handler: http.HandlerFunc(gw.handleSSH),
161                         TLSConfig: &tls.Config{
162                                 Certificates: []tls.Certificate{cert},
163                         },
164                 },
165                 Addr: net.JoinHostPort(listenHost, extPort),
166         }
167         err = srv.Start()
168         if err != nil {
169                 return err
170         }
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)
174         if err != nil {
175                 return err
176         }
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.
180         //
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)
189         }
190         return nil
191 }
192
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)
197         }
198 }
199
200 // runTunnel connects to controller and sets up a tunnel through
201 // which controller can connect to the gateway server at the given
202 // addr.
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,
209         })
210         if err != nil {
211                 return fmt.Errorf("error creating gateway tunnel: %s", err)
212         }
213         mux, err := yamux.Client(tun.Conn, nil)
214         if err != nil {
215                 return fmt.Errorf("error setting up mux client end: %s", err)
216         }
217         if url := tun.Header.Get("X-Arvados-Internal-Url"); url != "" && gw.UpdateTunnelURL != nil {
218                 gw.UpdateTunnelURL(url)
219         }
220         for {
221                 muxconn, err := mux.Accept()
222                 if err != nil {
223                         return err
224                 }
225                 gw.Log.Printf("receiving connection from tunnel, remoteAddr %s", muxconn.RemoteAddr().String())
226                 go func() {
227                         defer muxconn.Close()
228                         gwconn, err := net.Dial("tcp", addr)
229                         if err != nil {
230                                 gw.Log.Printf("error connecting to %s on behalf of tunnel connection: %s", addr, err)
231                                 return
232                         }
233                         defer gwconn.Close()
234                         var wg sync.WaitGroup
235                         wg.Add(2)
236                         go func() {
237                                 defer wg.Done()
238                                 io.Copy(gwconn, muxconn)
239                         }()
240                         go func() {
241                                 defer wg.Done()
242                                 io.Copy(muxconn, gwconn)
243                         }()
244                         wg.Wait()
245                 }()
246         }
247 }
248
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).
254 //
255 // Requests must have path "/ssh" and the following headers:
256 //
257 // Connection: upgrade
258 // Upgrade: ssh
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)
263 //
264 // Optional headers:
265 //
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)
276                 return
277         }
278         req.ParseForm()
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)
281                 return
282         }
283         if req.Header.Get("X-Arvados-Authorization") != gw.requestAuth {
284                 http.Error(w, "bad X-Arvados-Authorization header", http.StatusUnauthorized)
285                 return
286         }
287         detachKeys := req.Form.Get("detach_keys")
288         username := req.Form.Get("login_username")
289         if username == "" {
290                 username = "root"
291         }
292         hj, ok := w.(http.Hijacker)
293         if !ok {
294                 http.Error(w, "ResponseWriter does not support connection upgrade", http.StatusInternalServerError)
295                 return
296         }
297         netconn, _, err := hj.Hijack()
298         if !ok {
299                 http.Error(w, err.Error(), http.StatusInternalServerError)
300                 return
301         }
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"))
309
310         ctx := req.Context()
311
312         conn, newchans, reqs, err := ssh.NewServerConn(netconn, &gw.sshConfig)
313         if err == io.EOF {
314                 return
315         } else if err != nil {
316                 gw.Log.Printf("ssh.NewServerConn: %s", err)
317                 return
318         }
319         defer conn.Close()
320         go ssh.DiscardRequests(reqs)
321         for newch := range newchans {
322                 switch newch.ChannelType() {
323                 case "direct-tcpip":
324                         go gw.handleDirectTCPIP(ctx, newch)
325                 case "session":
326                         go gw.handleSession(ctx, newch, detachKeys, username)
327                 default:
328                         go newch.Reject(ssh.UnknownChannelType, fmt.Sprintf("unsupported channel type %q", newch.ChannelType()))
329                 }
330         }
331 }
332
333 func (gw *Gateway) handleDirectTCPIP(ctx context.Context, newch ssh.NewChannel) {
334         ch, reqs, err := newch.Accept()
335         if err != nil {
336                 gw.Log.Printf("accept direct-tcpip channel: %s", err)
337                 return
338         }
339         defer ch.Close()
340         go ssh.DiscardRequests(reqs)
341
342         // RFC 4254 7.2 (copy of channelOpenDirectMsg in
343         // golang.org/x/crypto/ssh)
344         var msg struct {
345                 Raddr string
346                 Rport uint32
347                 Laddr string
348                 Lport uint32
349         }
350         err = ssh.Unmarshal(newch.ExtraData(), &msg)
351         if err != nil {
352                 fmt.Fprintf(ch.Stderr(), "unmarshal direct-tcpip extradata: %s\n", err)
353                 return
354         }
355         switch msg.Raddr {
356         case "localhost", "0.0.0.0", "127.0.0.1", "::1", "::":
357         default:
358                 fmt.Fprintf(ch.Stderr(), "cannot forward to ports on %q, only localhost\n", msg.Raddr)
359                 return
360         }
361
362         dstaddr, err := gw.Target.IPAddress()
363         if err != nil {
364                 fmt.Fprintf(ch.Stderr(), "container has no IP address: %s\n", err)
365                 return
366         } else if dstaddr == "" {
367                 fmt.Fprintf(ch.Stderr(), "container has no IP address\n")
368                 return
369         }
370
371         dst := net.JoinHostPort(dstaddr, fmt.Sprintf("%d", msg.Rport))
372         tcpconn, err := net.Dial("tcp", dst)
373         if err != nil {
374                 fmt.Fprintf(ch.Stderr(), "%s: %s\n", dst, err)
375                 return
376         }
377         go func() {
378                 n, _ := io.Copy(ch, tcpconn)
379                 ctxlog.FromContext(ctx).Debugf("tcpip: sent %d bytes\n", n)
380                 ch.CloseWrite()
381         }()
382         n, _ := io.Copy(tcpconn, ch)
383         ctxlog.FromContext(ctx).Debugf("tcpip: received %d bytes\n", n)
384 }
385
386 func (gw *Gateway) handleSession(ctx context.Context, newch ssh.NewChannel, detachKeys, username string) {
387         ch, reqs, err := newch.Accept()
388         if err != nil {
389                 gw.Log.Printf("accept session channel: %s", err)
390                 return
391         }
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)
397         eol := "\n"
398         // Env vars to add to child process
399         termEnv := []string(nil)
400         for req := range reqs {
401                 ok := false
402                 switch req.Type {
403                 case "shell", "exec":
404                         ok = true
405                         var payload struct {
406                                 Command string
407                         }
408                         ssh.Unmarshal(req.Payload, &payload)
409                         execargs, err := shlex.Split(payload.Command)
410                         if err != nil {
411                                 fmt.Fprintf(logw, "error parsing supplied command: %s"+eol, err)
412                                 return
413                         }
414                         if len(execargs) == 0 {
415                                 execargs = []string{"/bin/bash", "-login"}
416                         }
417                         go func() {
418                                 var resp struct {
419                                         Status uint32
420                                 }
421                                 defer func() {
422                                         ch.SendRequest("exit-status", false, ssh.Marshal(&resp))
423                                         ch.Close()
424                                 }()
425
426                                 cmd, err := gw.Target.InjectCommand(ctx, detachKeys, username, tty0 != nil, execargs)
427                                 if err != nil {
428                                         fmt.Fprintln(ch.Stderr(), err)
429                                         ch.CloseWrite()
430                                         resp.Status = 1
431                                         return
432                                 }
433                                 cmd.Stdin = ch
434                                 cmd.Stdout = ch
435                                 cmd.Stderr = ch.Stderr()
436                                 if tty0 != nil {
437                                         cmd.Stdin = tty0
438                                         cmd.Stdout = tty0
439                                         cmd.Stderr = tty0
440                                         var wg sync.WaitGroup
441                                         defer wg.Wait()
442                                         wg.Add(2)
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.
446                                         logw = tty0
447                                 }
448                                 cmd.SysProcAttr = &syscall.SysProcAttr{
449                                         Setctty: tty0 != nil,
450                                         Setsid:  true,
451                                 }
452                                 cmd.Env = append(os.Environ(), termEnv...)
453                                 err = cmd.Run()
454                                 if exiterr, ok := err.(*exec.ExitError); ok {
455                                         if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
456                                                 resp.Status = uint32(status.ExitStatus())
457                                         }
458                                 } else if err != nil {
459                                         // Propagate errors like `exec: "docker": executable file not found in $PATH`
460                                         fmt.Fprintln(ch.Stderr(), err)
461                                 }
462                                 errClose := ch.CloseWrite()
463                                 if resp.Status == 0 && (err != nil || errClose != nil) {
464                                         resp.Status = 1
465                                 }
466                         }()
467                 case "pty-req":
468                         eol = "\r\n"
469                         p, t, err := pty.Open()
470                         if err != nil {
471                                 fmt.Fprintf(ch.Stderr(), "pty failed: %s"+eol, err)
472                                 break
473                         }
474                         defer p.Close()
475                         defer t.Close()
476                         pty0, tty0 = p, t
477                         ok = true
478                         var payload struct {
479                                 Term string
480                                 Cols uint32
481                                 Rows uint32
482                                 X    uint32
483                                 Y    uint32
484                         }
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)})
488                         if err != nil {
489                                 fmt.Fprintf(logw, "pty-req: setsize failed: %s"+eol, err)
490                         }
491                 case "window-change":
492                         var payload struct {
493                                 Cols uint32
494                                 Rows uint32
495                                 X    uint32
496                                 Y    uint32
497                         }
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)})
500                         if err != nil {
501                                 fmt.Fprintf(logw, "window-change: setsize failed: %s"+eol, err)
502                                 break
503                         }
504                         ok = true
505                 case "env":
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
512                         // hole).
513                 default:
514                         // fmt.Fprintf(logw, "declining %q req"+eol, req.Type)
515                 }
516                 if req.WantReply {
517                         req.Reply(ok, nil)
518                 }
519         }
520 }