6fae73798cc6263e330614103196f156e149ee39
[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         go func() {
172                 err := srv.Wait()
173                 gw.Log.Printf("gateway server stopped: %s", err)
174         }()
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)
178         if err != nil {
179                 return err
180         }
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.
184         //
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)
194         }
195         return nil
196 }
197
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)
202         }
203 }
204
205 // runTunnel connects to controller and sets up a tunnel through
206 // which controller can connect to the gateway server at the given
207 // addr.
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,
214         })
215         if err != nil {
216                 return fmt.Errorf("error creating gateway tunnel: %s", err)
217         }
218         mux, err := yamux.Client(tun.Conn, nil)
219         if err != nil {
220                 return fmt.Errorf("error setting up mux client end: %s", err)
221         }
222         if url := tun.Header.Get("X-Arvados-Internal-Url"); url != "" && gw.UpdateTunnelURL != nil {
223                 gw.UpdateTunnelURL(url)
224         }
225         for {
226                 muxconn, err := mux.AcceptStream()
227                 if err != nil {
228                         return err
229                 }
230                 gw.Log.Printf("tunnel connection %d started", muxconn.StreamID())
231                 go func() {
232                         defer muxconn.Close()
233                         gwconn, err := net.Dial("tcp", addr)
234                         if err != nil {
235                                 gw.Log.Printf("tunnel connection %d: error connecting to %s: %s", muxconn.StreamID(), addr, err)
236                                 return
237                         }
238                         defer gwconn.Close()
239                         var wg sync.WaitGroup
240                         wg.Add(2)
241                         go func() {
242                                 defer wg.Done()
243                                 _, err := io.Copy(gwconn, muxconn)
244                                 if err != nil {
245                                         gw.Log.Printf("tunnel connection %d: tunnel: %s", muxconn.StreamID(), err)
246                                 }
247                                 muxconn.Close()
248                                 gwconn.Close()
249                         }()
250                         go func() {
251                                 defer wg.Done()
252                                 _, err := io.Copy(muxconn, gwconn)
253                                 if err != nil {
254                                         gw.Log.Printf("tunnel connection %d: gateway: %s", muxconn.StreamID(), err)
255                                 }
256                                 gwconn.Close()
257                                 muxconn.Close()
258                         }()
259                         wg.Wait()
260                         gw.Log.Printf("tunnel connection %d finished", muxconn.StreamID())
261                 }()
262         }
263 }
264
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).
270 //
271 // Requests must have path "/ssh" and the following headers:
272 //
273 // Connection: upgrade
274 // Upgrade: ssh
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)
279 //
280 // Optional headers:
281 //
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)
292                 return
293         }
294         req.ParseForm()
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)
297                 return
298         }
299         if req.Header.Get("X-Arvados-Authorization") != gw.requestAuth {
300                 http.Error(w, "bad X-Arvados-Authorization header", http.StatusUnauthorized)
301                 return
302         }
303         detachKeys := req.Form.Get("detach_keys")
304         username := req.Form.Get("login_username")
305         if username == "" {
306                 username = "root"
307         }
308         hj, ok := w.(http.Hijacker)
309         if !ok {
310                 http.Error(w, "ResponseWriter does not support connection upgrade", http.StatusInternalServerError)
311                 return
312         }
313         netconn, _, err := hj.Hijack()
314         if !ok {
315                 http.Error(w, err.Error(), http.StatusInternalServerError)
316                 return
317         }
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"))
325
326         ctx := req.Context()
327
328         conn, newchans, reqs, err := ssh.NewServerConn(netconn, &gw.sshConfig)
329         if err == io.EOF {
330                 return
331         } else if err != nil {
332                 gw.Log.Printf("ssh.NewServerConn: %s", err)
333                 return
334         }
335         defer conn.Close()
336         go ssh.DiscardRequests(reqs)
337         for newch := range newchans {
338                 switch newch.ChannelType() {
339                 case "direct-tcpip":
340                         go gw.handleDirectTCPIP(ctx, newch)
341                 case "session":
342                         go gw.handleSession(ctx, newch, detachKeys, username)
343                 default:
344                         go newch.Reject(ssh.UnknownChannelType, fmt.Sprintf("unsupported channel type %q", newch.ChannelType()))
345                 }
346         }
347 }
348
349 func (gw *Gateway) handleDirectTCPIP(ctx context.Context, newch ssh.NewChannel) {
350         ch, reqs, err := newch.Accept()
351         if err != nil {
352                 gw.Log.Printf("accept direct-tcpip channel: %s", err)
353                 return
354         }
355         defer ch.Close()
356         go ssh.DiscardRequests(reqs)
357
358         // RFC 4254 7.2 (copy of channelOpenDirectMsg in
359         // golang.org/x/crypto/ssh)
360         var msg struct {
361                 Raddr string
362                 Rport uint32
363                 Laddr string
364                 Lport uint32
365         }
366         err = ssh.Unmarshal(newch.ExtraData(), &msg)
367         if err != nil {
368                 fmt.Fprintf(ch.Stderr(), "unmarshal direct-tcpip extradata: %s\n", err)
369                 return
370         }
371         switch msg.Raddr {
372         case "localhost", "0.0.0.0", "127.0.0.1", "::1", "::":
373         default:
374                 fmt.Fprintf(ch.Stderr(), "cannot forward to ports on %q, only localhost\n", msg.Raddr)
375                 return
376         }
377
378         dstaddr, err := gw.Target.IPAddress()
379         if err != nil {
380                 fmt.Fprintf(ch.Stderr(), "container has no IP address: %s\n", err)
381                 return
382         } else if dstaddr == "" {
383                 fmt.Fprintf(ch.Stderr(), "container has no IP address\n")
384                 return
385         }
386
387         dst := net.JoinHostPort(dstaddr, fmt.Sprintf("%d", msg.Rport))
388         tcpconn, err := net.Dial("tcp", dst)
389         if err != nil {
390                 fmt.Fprintf(ch.Stderr(), "%s: %s\n", dst, err)
391                 return
392         }
393         go func() {
394                 n, _ := io.Copy(ch, tcpconn)
395                 ctxlog.FromContext(ctx).Debugf("tcpip: sent %d bytes\n", n)
396                 ch.CloseWrite()
397         }()
398         n, _ := io.Copy(tcpconn, ch)
399         ctxlog.FromContext(ctx).Debugf("tcpip: received %d bytes\n", n)
400 }
401
402 func (gw *Gateway) handleSession(ctx context.Context, newch ssh.NewChannel, detachKeys, username string) {
403         ch, reqs, err := newch.Accept()
404         if err != nil {
405                 gw.Log.Printf("accept session channel: %s", err)
406                 return
407         }
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)
413         eol := "\n"
414         // Env vars to add to child process
415         termEnv := []string(nil)
416         for req := range reqs {
417                 ok := false
418                 switch req.Type {
419                 case "shell", "exec":
420                         ok = true
421                         var payload struct {
422                                 Command string
423                         }
424                         ssh.Unmarshal(req.Payload, &payload)
425                         execargs, err := shlex.Split(payload.Command)
426                         if err != nil {
427                                 fmt.Fprintf(logw, "error parsing supplied command: %s"+eol, err)
428                                 return
429                         }
430                         if len(execargs) == 0 {
431                                 execargs = []string{"/bin/bash", "-login"}
432                         }
433                         go func() {
434                                 var resp struct {
435                                         Status uint32
436                                 }
437                                 defer func() {
438                                         ch.SendRequest("exit-status", false, ssh.Marshal(&resp))
439                                         ch.Close()
440                                 }()
441
442                                 cmd, err := gw.Target.InjectCommand(ctx, detachKeys, username, tty0 != nil, execargs)
443                                 if err != nil {
444                                         fmt.Fprintln(ch.Stderr(), err)
445                                         ch.CloseWrite()
446                                         resp.Status = 1
447                                         return
448                                 }
449                                 cmd.Stdin = ch
450                                 cmd.Stdout = ch
451                                 cmd.Stderr = ch.Stderr()
452                                 if tty0 != nil {
453                                         cmd.Stdin = tty0
454                                         cmd.Stdout = tty0
455                                         cmd.Stderr = tty0
456                                         var wg sync.WaitGroup
457                                         defer wg.Wait()
458                                         wg.Add(2)
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.
462                                         logw = tty0
463                                 }
464                                 cmd.SysProcAttr = &syscall.SysProcAttr{
465                                         Setctty: tty0 != nil,
466                                         Setsid:  true,
467                                 }
468                                 cmd.Env = append(os.Environ(), termEnv...)
469                                 err = cmd.Run()
470                                 if exiterr, ok := err.(*exec.ExitError); ok {
471                                         if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
472                                                 resp.Status = uint32(status.ExitStatus())
473                                         }
474                                 } else if err != nil {
475                                         // Propagate errors like `exec: "docker": executable file not found in $PATH`
476                                         fmt.Fprintln(ch.Stderr(), err)
477                                 }
478                                 errClose := ch.CloseWrite()
479                                 if resp.Status == 0 && (err != nil || errClose != nil) {
480                                         resp.Status = 1
481                                 }
482                         }()
483                 case "pty-req":
484                         eol = "\r\n"
485                         p, t, err := pty.Open()
486                         if err != nil {
487                                 fmt.Fprintf(ch.Stderr(), "pty failed: %s"+eol, err)
488                                 break
489                         }
490                         defer p.Close()
491                         defer t.Close()
492                         pty0, tty0 = p, t
493                         ok = true
494                         var payload struct {
495                                 Term string
496                                 Cols uint32
497                                 Rows uint32
498                                 X    uint32
499                                 Y    uint32
500                         }
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)})
504                         if err != nil {
505                                 fmt.Fprintf(logw, "pty-req: setsize failed: %s"+eol, err)
506                         }
507                 case "window-change":
508                         var payload struct {
509                                 Cols uint32
510                                 Rows uint32
511                                 X    uint32
512                                 Y    uint32
513                         }
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)})
516                         if err != nil {
517                                 fmt.Fprintf(logw, "window-change: setsize failed: %s"+eol, err)
518                                 break
519                         }
520                         ok = true
521                 case "env":
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
528                         // hole).
529                 default:
530                         // fmt.Fprintf(logw, "declining %q req"+eol, req.Type)
531                 }
532                 if req.WantReply {
533                         req.Reply(ok, nil)
534                 }
535         }
536 }