2022-02-15 19:59:21 +00:00
|
|
|
// Copyright (c) 2021 Tailscale Inc & AUTHORS All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2022-02-24 20:27:42 +00:00
|
|
|
//go:build linux || (darwin && !ios)
|
|
|
|
// +build linux darwin,!ios
|
2022-02-15 19:59:21 +00:00
|
|
|
|
|
|
|
// Package tailssh is an SSH server integrated into Tailscale.
|
|
|
|
package tailssh
|
|
|
|
|
|
|
|
import (
|
2022-02-23 23:47:57 +00:00
|
|
|
"context"
|
2022-03-13 20:01:59 +00:00
|
|
|
"crypto/rand"
|
2022-02-15 19:59:21 +00:00
|
|
|
"encoding/json"
|
2022-02-18 22:10:26 +00:00
|
|
|
"errors"
|
2022-02-15 19:59:21 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2022-03-13 05:32:17 +00:00
|
|
|
"io/ioutil"
|
2022-02-15 19:59:21 +00:00
|
|
|
"net"
|
2022-03-10 18:28:42 +00:00
|
|
|
"net/http"
|
2022-02-15 19:59:21 +00:00
|
|
|
"os"
|
|
|
|
"os/exec"
|
2022-02-19 03:07:04 +00:00
|
|
|
"os/user"
|
2022-03-14 20:26:06 +00:00
|
|
|
"path/filepath"
|
2022-03-13 05:32:17 +00:00
|
|
|
"runtime"
|
2022-03-14 20:26:06 +00:00
|
|
|
"strconv"
|
2022-02-19 03:07:04 +00:00
|
|
|
"strings"
|
2022-03-09 05:35:55 +00:00
|
|
|
"sync"
|
2022-02-18 22:10:26 +00:00
|
|
|
"time"
|
2022-02-15 19:59:21 +00:00
|
|
|
|
2022-03-13 01:25:00 +00:00
|
|
|
"github.com/tailscale/ssh"
|
2022-02-15 19:59:21 +00:00
|
|
|
"inet.af/netaddr"
|
|
|
|
"tailscale.com/envknob"
|
|
|
|
"tailscale.com/ipn/ipnlocal"
|
2022-03-10 18:28:42 +00:00
|
|
|
"tailscale.com/logtail/backoff"
|
2022-02-15 19:59:21 +00:00
|
|
|
"tailscale.com/net/tsaddr"
|
2022-02-18 22:10:26 +00:00
|
|
|
"tailscale.com/tailcfg"
|
2022-02-15 19:59:21 +00:00
|
|
|
"tailscale.com/types/logger"
|
|
|
|
)
|
|
|
|
|
|
|
|
// TODO(bradfitz): this is all very temporary as code is temporarily
|
|
|
|
// being moved around; it will be restructured and documented in
|
|
|
|
// following commits.
|
|
|
|
|
|
|
|
// Handle handles an SSH connection from c.
|
|
|
|
func Handle(logf logger.Logf, lb *ipnlocal.LocalBackend, c net.Conn) error {
|
2022-03-09 05:35:55 +00:00
|
|
|
tsd, err := os.Executable()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-03-09 19:25:07 +00:00
|
|
|
srv := &server{
|
|
|
|
lb: lb,
|
|
|
|
logf: logf,
|
|
|
|
tailscaledPath: tsd,
|
|
|
|
}
|
2022-02-24 21:31:54 +00:00
|
|
|
ss, err := srv.newSSHServer()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
ss.HandleConn(c)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (srv *server) newSSHServer() (*ssh.Server, error) {
|
|
|
|
ss := &ssh.Server{
|
|
|
|
Handler: srv.handleSSH,
|
2022-02-15 19:59:21 +00:00
|
|
|
RequestHandlers: map[string]ssh.RequestHandler{},
|
|
|
|
SubsystemHandlers: map[string]ssh.SubsystemHandler{},
|
2022-03-09 19:25:07 +00:00
|
|
|
// Note: the direct-tcpip channel handler and LocalPortForwardingCallback
|
|
|
|
// only adds support for forwarding ports from the local machine.
|
|
|
|
// TODO(maisem/bradfitz): add remote port forwarding support.
|
|
|
|
ChannelHandlers: map[string]ssh.ChannelHandler{
|
|
|
|
"direct-tcpip": ssh.DirectTCPIPHandler,
|
|
|
|
},
|
2022-03-12 16:46:46 +00:00
|
|
|
Version: "SSH-2.0-Tailscale",
|
2022-03-14 20:23:17 +00:00
|
|
|
LocalPortForwardingCallback: srv.mayForwardLocalPortTo,
|
2022-02-15 19:59:21 +00:00
|
|
|
}
|
|
|
|
for k, v := range ssh.DefaultRequestHandlers {
|
2022-02-24 21:31:54 +00:00
|
|
|
ss.RequestHandlers[k] = v
|
2022-02-15 19:59:21 +00:00
|
|
|
}
|
|
|
|
for k, v := range ssh.DefaultChannelHandlers {
|
2022-02-24 21:31:54 +00:00
|
|
|
ss.ChannelHandlers[k] = v
|
2022-02-15 19:59:21 +00:00
|
|
|
}
|
|
|
|
for k, v := range ssh.DefaultSubsystemHandlers {
|
2022-02-24 21:31:54 +00:00
|
|
|
ss.SubsystemHandlers[k] = v
|
2022-02-15 19:59:21 +00:00
|
|
|
}
|
2022-02-24 21:31:54 +00:00
|
|
|
keys, err := srv.lb.GetSSH_HostKeys()
|
2022-02-17 21:28:14 +00:00
|
|
|
if err != nil {
|
2022-02-24 21:31:54 +00:00
|
|
|
return nil, err
|
2022-02-17 21:28:14 +00:00
|
|
|
}
|
|
|
|
for _, signer := range keys {
|
2022-02-24 21:31:54 +00:00
|
|
|
ss.AddHostKey(signer)
|
2022-02-17 21:28:14 +00:00
|
|
|
}
|
2022-02-24 21:31:54 +00:00
|
|
|
return ss, nil
|
2022-02-15 19:59:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type server struct {
|
2022-03-09 05:35:55 +00:00
|
|
|
lb *ipnlocal.LocalBackend
|
|
|
|
logf logger.Logf
|
|
|
|
tailscaledPath string
|
2022-03-09 19:25:07 +00:00
|
|
|
|
|
|
|
// mu protects activeSessions.
|
2022-03-13 20:01:59 +00:00
|
|
|
mu sync.Mutex
|
|
|
|
activeSessionByH map[string]*sshSession // ssh.SessionID (DH H) => that session
|
|
|
|
activeSessionBySharedID map[string]*sshSession // yyymmddThhmmss-XXXXX => session
|
2022-02-15 19:59:21 +00:00
|
|
|
}
|
|
|
|
|
2022-02-18 22:10:26 +00:00
|
|
|
var debugPolicyFile = envknob.String("TS_DEBUG_SSH_POLICY_FILE")
|
|
|
|
|
2022-03-14 20:23:17 +00:00
|
|
|
// mayForwardLocalPortTo reports whether the ctx should be allowed to port forward
|
2022-03-09 19:25:07 +00:00
|
|
|
// to the specified host and port.
|
|
|
|
// TODO(bradfitz/maisem): should we have more checks on host/port?
|
2022-03-14 20:23:17 +00:00
|
|
|
func (srv *server) mayForwardLocalPortTo(ctx ssh.Context, destinationHost string, destinationPort uint32) bool {
|
|
|
|
ss, ok := srv.getSessionForContext(ctx)
|
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return ss.action.AllowLocalPortForwarding
|
2022-03-09 19:25:07 +00:00
|
|
|
}
|
|
|
|
|
2022-03-09 05:35:55 +00:00
|
|
|
// sshPolicy returns the SSHPolicy for current node.
|
|
|
|
// If there is no SSHPolicy in the netmap, it returns a debugPolicy
|
|
|
|
// if one is defined.
|
2022-02-18 22:10:26 +00:00
|
|
|
func (srv *server) sshPolicy() (_ *tailcfg.SSHPolicy, ok bool) {
|
|
|
|
lb := srv.lb
|
|
|
|
nm := lb.NetMap()
|
|
|
|
if nm == nil {
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
if pol := nm.SSHPolicy; pol != nil {
|
|
|
|
return pol, true
|
|
|
|
}
|
|
|
|
if debugPolicyFile != "" {
|
|
|
|
f, err := os.ReadFile(debugPolicyFile)
|
|
|
|
if err != nil {
|
|
|
|
srv.logf("error reading debug SSH policy file: %v", err)
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
p := new(tailcfg.SSHPolicy)
|
|
|
|
if err := json.Unmarshal(f, p); err != nil {
|
|
|
|
srv.logf("invalid JSON in %v: %v", debugPolicyFile, err)
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
return p, true
|
|
|
|
}
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
2022-03-09 05:35:55 +00:00
|
|
|
func asTailscaleIPPort(a net.Addr) (netaddr.IPPort, error) {
|
|
|
|
ta, ok := a.(*net.TCPAddr)
|
2022-02-15 19:59:21 +00:00
|
|
|
if !ok {
|
2022-03-09 05:35:55 +00:00
|
|
|
return netaddr.IPPort{}, fmt.Errorf("non-TCP addr %T %v", a, a)
|
2022-02-15 19:59:21 +00:00
|
|
|
}
|
|
|
|
tanetaddr, ok := netaddr.FromStdIP(ta.IP)
|
|
|
|
if !ok {
|
2022-03-09 05:35:55 +00:00
|
|
|
return netaddr.IPPort{}, fmt.Errorf("unparseable addr %v", ta.IP)
|
2022-02-15 19:59:21 +00:00
|
|
|
}
|
|
|
|
if !tsaddr.IsTailscaleIP(tanetaddr) {
|
2022-03-09 05:35:55 +00:00
|
|
|
return netaddr.IPPort{}, fmt.Errorf("non-Tailscale addr %v", ta.IP)
|
2022-02-15 19:59:21 +00:00
|
|
|
}
|
2022-03-09 05:35:55 +00:00
|
|
|
return netaddr.IPPortFrom(tanetaddr, uint16(ta.Port)), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// evaluatePolicy returns the SSHAction, sshConnInfo and localUser
|
|
|
|
// after evaluating the sshUser and remoteAddr against the SSHPolicy.
|
|
|
|
// The remoteAddr and localAddr params must be Tailscale IPs.
|
|
|
|
func (srv *server) evaluatePolicy(sshUser string, localAddr, remoteAddr net.Addr) (_ *tailcfg.SSHAction, _ *sshConnInfo, localUser string, _ error) {
|
|
|
|
logf := srv.logf
|
|
|
|
lb := srv.lb
|
|
|
|
logf("Handling SSH from %v for user %v", remoteAddr, sshUser)
|
2022-02-15 19:59:21 +00:00
|
|
|
|
2022-02-18 22:10:26 +00:00
|
|
|
pol, ok := srv.sshPolicy()
|
|
|
|
if !ok {
|
2022-03-09 05:35:55 +00:00
|
|
|
return nil, nil, "", fmt.Errorf("tsshd: rejecting connection; no SSH policy")
|
2022-02-15 19:59:21 +00:00
|
|
|
}
|
2022-02-18 22:10:26 +00:00
|
|
|
|
2022-03-09 05:35:55 +00:00
|
|
|
srcIPP, err := asTailscaleIPPort(remoteAddr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, "", fmt.Errorf("tsshd: rejecting: %w", err)
|
|
|
|
}
|
|
|
|
dstIPP, err := asTailscaleIPPort(localAddr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, "", err
|
|
|
|
}
|
2022-02-15 19:59:21 +00:00
|
|
|
node, uprof, ok := lb.WhoIs(srcIPP)
|
|
|
|
if !ok {
|
2022-03-09 05:35:55 +00:00
|
|
|
return nil, nil, "", fmt.Errorf("Hello, %v. I don't know who you are.\n", srcIPP)
|
2022-02-15 19:59:21 +00:00
|
|
|
}
|
2022-02-18 22:10:26 +00:00
|
|
|
|
2022-02-24 16:58:53 +00:00
|
|
|
ci := &sshConnInfo{
|
2022-02-18 22:10:26 +00:00
|
|
|
now: time.Now(),
|
2022-02-19 03:07:04 +00:00
|
|
|
sshUser: sshUser,
|
2022-03-09 05:35:55 +00:00
|
|
|
src: srcIPP,
|
|
|
|
dst: dstIPP,
|
2022-02-18 22:10:26 +00:00
|
|
|
node: node,
|
|
|
|
uprof: &uprof,
|
|
|
|
}
|
2022-03-09 05:35:55 +00:00
|
|
|
a, localUser, ok := evalSSHPolicy(pol, ci)
|
|
|
|
if !ok {
|
|
|
|
return nil, nil, "", fmt.Errorf("ssh: access denied for %q from %v", uprof.LoginName, ci.src.IP())
|
|
|
|
}
|
|
|
|
return a, ci, localUser, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleSSH is invoked when a new SSH connection attempt is made.
|
|
|
|
func (srv *server) handleSSH(s ssh.Session) {
|
|
|
|
logf := srv.logf
|
|
|
|
|
|
|
|
sshUser := s.User()
|
|
|
|
action, ci, localUser, err := srv.evaluatePolicy(sshUser, s.LocalAddr(), s.RemoteAddr())
|
|
|
|
if err != nil {
|
|
|
|
logf(err.Error())
|
|
|
|
s.Exit(1)
|
|
|
|
return
|
|
|
|
}
|
2022-03-10 18:28:42 +00:00
|
|
|
|
|
|
|
// Loop processing/fetching Actions until one reaches a
|
|
|
|
// terminal state (Accept, Reject, or invalid Action), or
|
|
|
|
// until fetchSSHAction times out due to the context being
|
|
|
|
// done (client disconnect) or its 30 minute timeout passes.
|
|
|
|
// (Which is a long time for somebody to see login
|
|
|
|
// instructions and go to a URL to do something.)
|
|
|
|
ProcessAction:
|
|
|
|
for {
|
|
|
|
if action.Message != "" {
|
|
|
|
io.WriteString(s.Stderr(), strings.Replace(action.Message, "\n", "\r\n", -1))
|
|
|
|
}
|
|
|
|
if action.Reject {
|
|
|
|
logf("ssh: access denied for %q from %v", ci.uprof.LoginName, ci.src.IP())
|
|
|
|
s.Exit(1)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if action.Accept {
|
|
|
|
break ProcessAction
|
|
|
|
}
|
|
|
|
url := action.HoldAndDelegate
|
|
|
|
if url == "" {
|
|
|
|
logf("ssh: access denied; SSHAction has neither Reject, Accept, or next step URL")
|
|
|
|
s.Exit(1)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
action, err = srv.fetchSSHAction(s.Context(), url)
|
|
|
|
if err != nil {
|
|
|
|
logf("ssh: fetching SSAction from %s: %v", url, err)
|
|
|
|
s.Exit(1)
|
|
|
|
return
|
|
|
|
}
|
2022-02-18 22:10:26 +00:00
|
|
|
}
|
2022-03-10 18:28:42 +00:00
|
|
|
|
2022-02-19 23:37:13 +00:00
|
|
|
lu, err := user.Lookup(localUser)
|
|
|
|
if err != nil {
|
|
|
|
logf("ssh: user Lookup %q: %v", localUser, err)
|
2022-02-18 22:10:26 +00:00
|
|
|
s.Exit(1)
|
2022-03-09 05:35:55 +00:00
|
|
|
return
|
2022-02-18 22:10:26 +00:00
|
|
|
}
|
2022-02-19 23:37:13 +00:00
|
|
|
|
2022-03-13 20:01:59 +00:00
|
|
|
ss := srv.newSSHSession(s, ci, lu, action)
|
|
|
|
ss.run()
|
|
|
|
}
|
|
|
|
|
|
|
|
// sshSession is an accepted Tailscale SSH session.
|
|
|
|
type sshSession struct {
|
|
|
|
ssh.Session
|
|
|
|
idH string // the RFC4253 sec8 hash H; don't share outside process
|
|
|
|
sharedID string // ID that's shared with control
|
|
|
|
logf logger.Logf
|
|
|
|
|
2022-03-14 20:26:06 +00:00
|
|
|
ctx *sshContext // implements context.Context
|
|
|
|
srv *server
|
|
|
|
connInfo *sshConnInfo
|
|
|
|
action *tailcfg.SSHAction
|
|
|
|
localUser *user.User
|
|
|
|
agentListener net.Listener // non-nil if agent-forwarding requested+allowed
|
2022-03-13 20:01:59 +00:00
|
|
|
|
|
|
|
// initialized by launchProcess:
|
|
|
|
cmd *exec.Cmd
|
|
|
|
stdin io.WriteCloser
|
|
|
|
stdout io.Reader
|
|
|
|
stderr io.Reader // nil for pty sessions
|
|
|
|
ptyReq *ssh.Pty // non-nil for pty sessions
|
|
|
|
|
|
|
|
// We use this sync.Once to ensure that we only terminate the process once,
|
|
|
|
// either it exits itself or is terminated
|
|
|
|
exitOnce sync.Once
|
|
|
|
}
|
|
|
|
|
|
|
|
func (srv *server) newSSHSession(s ssh.Session, ci *sshConnInfo, lu *user.User, action *tailcfg.SSHAction) *sshSession {
|
|
|
|
sharedID := fmt.Sprintf("%s-%02x", ci.now.UTC().Format("20060102T150405"), randBytes(5))
|
|
|
|
return &sshSession{
|
|
|
|
Session: s,
|
|
|
|
idH: s.Context().(ssh.Context).SessionID(),
|
|
|
|
sharedID: sharedID,
|
|
|
|
ctx: newSSHContext(),
|
|
|
|
srv: srv,
|
|
|
|
action: action,
|
|
|
|
localUser: lu,
|
|
|
|
connInfo: ci,
|
|
|
|
logf: logger.WithPrefix(srv.logf, "ssh-session("+sharedID+"): "),
|
2022-02-23 23:47:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-10 18:28:42 +00:00
|
|
|
func (srv *server) fetchSSHAction(ctx context.Context, url string) (*tailcfg.SSHAction, error) {
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, 30*time.Minute)
|
|
|
|
defer cancel()
|
|
|
|
bo := backoff.NewBackoff("fetch-ssh-action", srv.logf, 10*time.Second)
|
|
|
|
for {
|
|
|
|
if err := ctx.Err(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
res, err := srv.lb.DoNoiseRequest(req)
|
|
|
|
if err != nil {
|
|
|
|
bo.BackOff(ctx, err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if res.StatusCode != 200 {
|
|
|
|
res.Body.Close()
|
|
|
|
bo.BackOff(ctx, fmt.Errorf("unexpected status: %v", res.Status))
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
a := new(tailcfg.SSHAction)
|
|
|
|
if err := json.NewDecoder(res.Body).Decode(a); err != nil {
|
|
|
|
bo.BackOff(ctx, err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
return a, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-13 20:01:59 +00:00
|
|
|
// killProcessOnContextDone waits for ss.ctx to be done and kills the process,
|
|
|
|
// unless the process has already exited.
|
|
|
|
func (ss *sshSession) killProcessOnContextDone() {
|
|
|
|
<-ss.ctx.Done()
|
2022-03-09 05:35:55 +00:00
|
|
|
// Either the process has already existed, in which case this does nothing.
|
|
|
|
// Or, the process is still running in which case this will kill it.
|
2022-03-13 20:01:59 +00:00
|
|
|
ss.exitOnce.Do(func() {
|
|
|
|
err := ss.ctx.Err()
|
2022-03-09 05:35:55 +00:00
|
|
|
if serr, ok := err.(SSHTerminationError); ok {
|
|
|
|
msg := serr.SSHTerminationMessage()
|
|
|
|
if msg != "" {
|
2022-03-13 20:01:59 +00:00
|
|
|
io.WriteString(ss.Stderr(), "\r\n\r\n"+msg+"\r\n\r\n")
|
2022-03-09 05:35:55 +00:00
|
|
|
}
|
|
|
|
}
|
2022-03-13 20:01:59 +00:00
|
|
|
ss.logf("terminating SSH session from %v: %v", ss.connInfo.src.IP(), err)
|
|
|
|
ss.cmd.Process.Kill()
|
2022-03-09 05:35:55 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-03-14 20:23:17 +00:00
|
|
|
// sessionAction returns the SSHAction associated with the session.
|
|
|
|
func (srv *server) getSessionForContext(sctx ssh.Context) (ss *sshSession, ok bool) {
|
2022-03-09 19:25:07 +00:00
|
|
|
srv.mu.Lock()
|
|
|
|
defer srv.mu.Unlock()
|
2022-03-14 20:23:17 +00:00
|
|
|
ss, ok = srv.activeSessionByH[sctx.SessionID()]
|
|
|
|
return
|
2022-03-09 19:25:07 +00:00
|
|
|
}
|
|
|
|
|
2022-03-13 20:01:59 +00:00
|
|
|
// startSession registers ss as an active session.
|
|
|
|
func (srv *server) startSession(ss *sshSession) {
|
2022-03-09 19:25:07 +00:00
|
|
|
srv.mu.Lock()
|
|
|
|
defer srv.mu.Unlock()
|
2022-03-13 20:01:59 +00:00
|
|
|
if srv.activeSessionByH == nil {
|
|
|
|
srv.activeSessionByH = make(map[string]*sshSession)
|
|
|
|
}
|
|
|
|
if srv.activeSessionBySharedID == nil {
|
|
|
|
srv.activeSessionBySharedID = make(map[string]*sshSession)
|
|
|
|
}
|
|
|
|
if ss.idH == "" {
|
|
|
|
panic("empty idH")
|
2022-03-09 19:25:07 +00:00
|
|
|
}
|
2022-03-13 20:01:59 +00:00
|
|
|
if _, dup := srv.activeSessionByH[ss.idH]; dup {
|
|
|
|
panic("dup idH")
|
|
|
|
}
|
|
|
|
if ss.sharedID == "" {
|
|
|
|
panic("empty sharedID")
|
|
|
|
}
|
|
|
|
if _, dup := srv.activeSessionBySharedID[ss.sharedID]; dup {
|
|
|
|
panic("dup sharedID")
|
|
|
|
}
|
|
|
|
srv.activeSessionByH[ss.idH] = ss
|
|
|
|
srv.activeSessionBySharedID[ss.sharedID] = ss
|
2022-03-09 19:25:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// endSession unregisters s from the list of active sessions.
|
2022-03-13 20:01:59 +00:00
|
|
|
func (srv *server) endSession(ss *sshSession) {
|
2022-03-09 19:25:07 +00:00
|
|
|
srv.mu.Lock()
|
|
|
|
defer srv.mu.Unlock()
|
2022-03-13 20:01:59 +00:00
|
|
|
delete(srv.activeSessionByH, ss.idH)
|
|
|
|
delete(srv.activeSessionBySharedID, ss.sharedID)
|
2022-03-09 19:25:07 +00:00
|
|
|
}
|
|
|
|
|
2022-03-13 20:01:59 +00:00
|
|
|
var errSessionDone = errors.New("session is done")
|
|
|
|
|
2022-03-14 20:26:06 +00:00
|
|
|
// handleSSHAgentForwarding starts a Unix socket listener and in the background
|
|
|
|
// forwards agent connections between the listenr and the ssh.Session.
|
|
|
|
// On success, it assigns ss.agentListener.
|
|
|
|
func (ss *sshSession) handleSSHAgentForwarding(s ssh.Session, lu *user.User) error {
|
|
|
|
if !ssh.AgentRequested(ss) || !ss.action.AllowAgentForwarding {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
ss.logf("ssh: agent forwarding requested")
|
|
|
|
ln, err := ssh.NewAgentListener()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
if err != nil && ln != nil {
|
|
|
|
ln.Close()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
uid, err := strconv.ParseUint(lu.Uid, 10, 32)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
gid, err := strconv.ParseUint(lu.Gid, 10, 32)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
socket := ln.Addr().String()
|
|
|
|
dir := filepath.Dir(socket)
|
|
|
|
// Make sure the socket is accessible by the user.
|
|
|
|
if err := os.Chown(socket, int(uid), int(gid)); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := os.Chmod(dir, 0755); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
go ssh.ForwardAgentConnections(ln, s)
|
|
|
|
ss.agentListener = ln
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-03-13 05:32:17 +00:00
|
|
|
// recordSSH is a temporary dev knob to test the SSH recording
|
|
|
|
// functionality and support off-node streaming.
|
|
|
|
//
|
|
|
|
// TODO(bradfitz,maisem): move this to SSHPolicy.
|
|
|
|
var recordSSH = envknob.Bool("TS_DEBUG_LOG_SSH")
|
|
|
|
|
2022-03-13 20:01:59 +00:00
|
|
|
// run is the entrypoint for a newly accepted SSH session.
|
2022-02-23 23:47:57 +00:00
|
|
|
//
|
2022-03-13 05:32:17 +00:00
|
|
|
// It handles ss once it's been accepted and determined
|
|
|
|
// that it should run.
|
2022-03-13 20:01:59 +00:00
|
|
|
func (ss *sshSession) run() {
|
|
|
|
srv := ss.srv
|
|
|
|
srv.startSession(ss)
|
|
|
|
defer srv.endSession(ss)
|
|
|
|
|
|
|
|
defer ss.ctx.CloseWithError(errSessionDone)
|
|
|
|
|
|
|
|
if ss.action.SesssionDuration != 0 {
|
|
|
|
t := time.AfterFunc(ss.action.SesssionDuration, func() {
|
|
|
|
ss.ctx.CloseWithError(userVisibleError{
|
|
|
|
fmt.Sprintf("Session timeout of %v elapsed.", ss.action.SesssionDuration),
|
|
|
|
context.DeadlineExceeded,
|
|
|
|
})
|
|
|
|
})
|
|
|
|
defer t.Stop()
|
|
|
|
}
|
|
|
|
|
2022-02-23 23:47:57 +00:00
|
|
|
logf := srv.logf
|
2022-03-13 20:01:59 +00:00
|
|
|
lu := ss.localUser
|
2022-02-23 23:47:57 +00:00
|
|
|
localUser := lu.Username
|
|
|
|
|
2022-02-19 23:37:13 +00:00
|
|
|
if euid := os.Geteuid(); euid != 0 {
|
|
|
|
if lu.Uid != fmt.Sprint(euid) {
|
|
|
|
logf("ssh: can't switch to user %q from process euid %v", localUser, euid)
|
2022-03-13 20:01:59 +00:00
|
|
|
fmt.Fprintf(ss, "can't switch user\n")
|
|
|
|
ss.Exit(1)
|
2022-02-19 03:07:04 +00:00
|
|
|
return
|
|
|
|
}
|
2022-02-19 23:37:13 +00:00
|
|
|
}
|
2022-03-09 05:35:55 +00:00
|
|
|
|
2022-03-13 01:40:40 +00:00
|
|
|
// Take control of the PTY so that we can configure it below.
|
|
|
|
// See https://github.com/tailscale/tailscale/issues/4146
|
2022-03-13 20:01:59 +00:00
|
|
|
ss.DisablePTYEmulation()
|
2022-03-13 01:40:40 +00:00
|
|
|
|
2022-03-14 20:26:06 +00:00
|
|
|
if err := ss.handleSSHAgentForwarding(ss, lu); err != nil {
|
|
|
|
logf("ssh: agent forwarding failed: %v", err)
|
|
|
|
} else if ss.agentListener != nil {
|
|
|
|
// TODO(maisem/bradfitz): add a way to close all session resources
|
|
|
|
defer ss.agentListener.Close()
|
|
|
|
}
|
2022-03-13 05:32:17 +00:00
|
|
|
|
|
|
|
var rec *recording // or nil if disabled
|
|
|
|
if ss.shouldRecord() {
|
|
|
|
var err error
|
|
|
|
rec, err = ss.startNewRecording()
|
|
|
|
if err != nil {
|
|
|
|
fmt.Fprintf(ss, "can't start new recording\n")
|
|
|
|
logf("startNewRecording: %v", err)
|
|
|
|
ss.Exit(1)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer rec.Close()
|
|
|
|
}
|
|
|
|
|
2022-03-13 20:01:59 +00:00
|
|
|
err := ss.launchProcess(ss.ctx)
|
2022-03-09 05:35:55 +00:00
|
|
|
if err != nil {
|
|
|
|
logf("start failed: %v", err.Error())
|
2022-03-13 20:01:59 +00:00
|
|
|
ss.Exit(1)
|
2022-03-09 05:35:55 +00:00
|
|
|
return
|
|
|
|
}
|
2022-03-13 20:01:59 +00:00
|
|
|
go ss.killProcessOnContextDone()
|
|
|
|
|
2022-03-09 05:35:55 +00:00
|
|
|
go func() {
|
2022-03-13 05:32:17 +00:00
|
|
|
_, err := io.Copy(rec.writer("i", ss.stdin), ss)
|
2022-02-19 23:37:13 +00:00
|
|
|
if err != nil {
|
2022-03-09 05:35:55 +00:00
|
|
|
// TODO: don't log in the success case.
|
|
|
|
logf("ssh: stdin copy: %v", err)
|
2022-02-19 03:07:04 +00:00
|
|
|
}
|
2022-03-13 20:01:59 +00:00
|
|
|
ss.stdin.Close()
|
2022-03-09 05:35:55 +00:00
|
|
|
}()
|
|
|
|
go func() {
|
2022-03-13 05:32:17 +00:00
|
|
|
_, err := io.Copy(rec.writer("o", ss), ss.stdout)
|
2022-02-19 23:37:13 +00:00
|
|
|
if err != nil {
|
2022-03-09 05:35:55 +00:00
|
|
|
// TODO: don't log in the success case.
|
|
|
|
logf("ssh: stdout copy: %v", err)
|
2022-02-19 23:37:13 +00:00
|
|
|
}
|
2022-03-09 05:35:55 +00:00
|
|
|
}()
|
|
|
|
// stderr is nil for ptys.
|
2022-03-13 20:01:59 +00:00
|
|
|
if ss.stderr != nil {
|
2022-02-23 23:47:57 +00:00
|
|
|
go func() {
|
2022-03-13 20:01:59 +00:00
|
|
|
_, err := io.Copy(ss.Stderr(), ss.stderr)
|
2022-03-09 05:35:55 +00:00
|
|
|
if err != nil {
|
|
|
|
// TODO: don't log in the success case.
|
|
|
|
logf("ssh: stderr copy: %v", err)
|
2022-02-23 23:47:57 +00:00
|
|
|
}
|
|
|
|
}()
|
2022-02-18 22:10:26 +00:00
|
|
|
}
|
2022-03-13 20:01:59 +00:00
|
|
|
err = ss.cmd.Wait()
|
2022-03-09 05:35:55 +00:00
|
|
|
// This will either make the SSH Termination goroutine be a no-op,
|
|
|
|
// or itself will be a no-op because the process was killed by the
|
|
|
|
// aforementioned goroutine.
|
2022-03-13 20:01:59 +00:00
|
|
|
ss.exitOnce.Do(func() {})
|
2022-03-09 05:35:55 +00:00
|
|
|
|
2022-02-19 23:37:13 +00:00
|
|
|
if err == nil {
|
|
|
|
logf("ssh: Wait: ok")
|
2022-03-13 20:01:59 +00:00
|
|
|
ss.Exit(0)
|
2022-02-19 23:37:13 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if ee, ok := err.(*exec.ExitError); ok {
|
|
|
|
code := ee.ProcessState.ExitCode()
|
|
|
|
logf("ssh: Wait: code=%v", code)
|
2022-03-13 20:01:59 +00:00
|
|
|
ss.Exit(code)
|
2022-02-19 23:37:13 +00:00
|
|
|
return
|
2022-02-15 19:59:21 +00:00
|
|
|
}
|
2022-02-19 23:37:13 +00:00
|
|
|
|
|
|
|
logf("ssh: Wait: %v", err)
|
2022-03-13 20:01:59 +00:00
|
|
|
ss.Exit(1)
|
2022-02-15 19:59:21 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-03-13 05:32:17 +00:00
|
|
|
func (ss *sshSession) shouldRecord() bool {
|
|
|
|
// for now only record pty sessions
|
|
|
|
// TODO(bradfitz,maisem): make configurable on SSHPolicy and
|
|
|
|
// support recording non-pty stuff too.
|
|
|
|
_, _, isPtyReq := ss.Pty()
|
|
|
|
return recordSSH && isPtyReq
|
|
|
|
}
|
|
|
|
|
2022-02-24 16:58:53 +00:00
|
|
|
type sshConnInfo struct {
|
2022-02-18 22:10:26 +00:00
|
|
|
// now is the time to consider the present moment for the
|
|
|
|
// purposes of rule evaluation.
|
|
|
|
now time.Time
|
|
|
|
|
|
|
|
// sshUser is the requested local SSH username ("root", "alice", etc).
|
|
|
|
sshUser string
|
|
|
|
|
2022-03-09 05:35:55 +00:00
|
|
|
// src is the Tailscale IP and port that the connection came from.
|
|
|
|
src netaddr.IPPort
|
|
|
|
|
|
|
|
// dst is the Tailscale IP and port that the connection came for.
|
|
|
|
dst netaddr.IPPort
|
2022-02-18 22:10:26 +00:00
|
|
|
|
|
|
|
// node is srcIP's node.
|
|
|
|
node *tailcfg.Node
|
|
|
|
|
|
|
|
// uprof is node's UserProfile.
|
|
|
|
uprof *tailcfg.UserProfile
|
|
|
|
}
|
|
|
|
|
2022-02-24 16:58:53 +00:00
|
|
|
func evalSSHPolicy(pol *tailcfg.SSHPolicy, ci *sshConnInfo) (a *tailcfg.SSHAction, localUser string, ok bool) {
|
2022-02-18 22:10:26 +00:00
|
|
|
for _, r := range pol.Rules {
|
2022-02-24 16:58:53 +00:00
|
|
|
if a, localUser, err := matchRule(r, ci); err == nil {
|
2022-02-18 22:10:26 +00:00
|
|
|
return a, localUser, true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, "", false
|
|
|
|
}
|
|
|
|
|
|
|
|
// internal errors for testing; they don't escape to callers or logs.
|
|
|
|
var (
|
|
|
|
errNilRule = errors.New("nil rule")
|
|
|
|
errNilAction = errors.New("nil action")
|
|
|
|
errRuleExpired = errors.New("rule expired")
|
|
|
|
errPrincipalMatch = errors.New("principal didn't match")
|
|
|
|
errUserMatch = errors.New("user didn't match")
|
|
|
|
)
|
|
|
|
|
2022-02-24 16:58:53 +00:00
|
|
|
func matchRule(r *tailcfg.SSHRule, ci *sshConnInfo) (a *tailcfg.SSHAction, localUser string, err error) {
|
2022-02-18 22:10:26 +00:00
|
|
|
if r == nil {
|
|
|
|
return nil, "", errNilRule
|
|
|
|
}
|
|
|
|
if r.Action == nil {
|
|
|
|
return nil, "", errNilAction
|
|
|
|
}
|
2022-02-24 16:58:53 +00:00
|
|
|
if r.RuleExpires != nil && ci.now.After(*r.RuleExpires) {
|
2022-02-18 22:10:26 +00:00
|
|
|
return nil, "", errRuleExpired
|
|
|
|
}
|
2022-02-24 16:58:53 +00:00
|
|
|
if !matchesPrincipal(r.Principals, ci) {
|
2022-02-18 22:10:26 +00:00
|
|
|
return nil, "", errPrincipalMatch
|
|
|
|
}
|
|
|
|
if !r.Action.Reject || r.SSHUsers != nil {
|
2022-02-24 16:58:53 +00:00
|
|
|
localUser = mapLocalUser(r.SSHUsers, ci.sshUser)
|
2022-02-18 22:10:26 +00:00
|
|
|
if localUser == "" {
|
|
|
|
return nil, "", errUserMatch
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return r.Action, localUser, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func mapLocalUser(ruleSSHUsers map[string]string, reqSSHUser string) (localUser string) {
|
2022-03-21 17:39:54 +00:00
|
|
|
v, ok := ruleSSHUsers[reqSSHUser]
|
|
|
|
if !ok {
|
|
|
|
v = ruleSSHUsers["*"]
|
|
|
|
}
|
|
|
|
if v == "=" {
|
|
|
|
return reqSSHUser
|
2022-02-18 22:10:26 +00:00
|
|
|
}
|
2022-03-21 17:39:54 +00:00
|
|
|
return v
|
2022-02-18 22:10:26 +00:00
|
|
|
}
|
|
|
|
|
2022-02-24 16:58:53 +00:00
|
|
|
func matchesPrincipal(ps []*tailcfg.SSHPrincipal, ci *sshConnInfo) bool {
|
2022-02-18 22:10:26 +00:00
|
|
|
for _, p := range ps {
|
|
|
|
if p == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if p.Any {
|
|
|
|
return true
|
|
|
|
}
|
2022-02-24 16:58:53 +00:00
|
|
|
if !p.Node.IsZero() && ci.node != nil && p.Node == ci.node.StableID {
|
2022-02-18 22:10:26 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
if p.NodeIP != "" {
|
2022-03-09 05:35:55 +00:00
|
|
|
if ip, _ := netaddr.ParseIP(p.NodeIP); ip == ci.src.IP() {
|
2022-02-18 22:10:26 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
2022-02-24 16:58:53 +00:00
|
|
|
if p.UserLogin != "" && ci.uprof != nil && ci.uprof.LoginName == p.UserLogin {
|
2022-02-18 22:10:26 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
2022-03-13 20:01:59 +00:00
|
|
|
|
|
|
|
func randBytes(n int) []byte {
|
|
|
|
b := make([]byte, n)
|
|
|
|
if _, err := rand.Read(b); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return b
|
|
|
|
}
|
2022-03-13 05:32:17 +00:00
|
|
|
|
|
|
|
// startNewRecording starts a new SSH session recording.
|
|
|
|
//
|
|
|
|
// It writes an asciinema file to
|
|
|
|
// $TAILSCALE_VAR_ROOT/ssh-sessions/ssh-session-<unixtime>-*.cast.
|
|
|
|
func (ss *sshSession) startNewRecording() (*recording, error) {
|
|
|
|
var w ssh.Window
|
|
|
|
if ptyReq, _, isPtyReq := ss.Pty(); isPtyReq {
|
|
|
|
w = ptyReq.Window
|
|
|
|
}
|
|
|
|
|
|
|
|
term := envValFromList(ss.Environ(), "TERM")
|
|
|
|
if term == "" {
|
|
|
|
term = "xterm-256color" // something non-empty
|
|
|
|
}
|
|
|
|
|
|
|
|
now := time.Now()
|
|
|
|
rec := &recording{
|
|
|
|
ss: ss,
|
|
|
|
start: now,
|
|
|
|
}
|
|
|
|
varRoot := ss.srv.lb.TailscaleVarRoot()
|
|
|
|
if varRoot == "" {
|
|
|
|
return nil, errors.New("no var root for recording storage")
|
|
|
|
}
|
|
|
|
dir := filepath.Join(varRoot, "ssh-sessions")
|
|
|
|
if err := os.MkdirAll(dir, 0700); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
f, err := ioutil.TempFile(dir, fmt.Sprintf("ssh-session-%v-*.cast", now.UnixNano()))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
rec.out = f
|
|
|
|
|
|
|
|
// {"version": 2, "width": 221, "height": 84, "timestamp": 1647146075, "env": {"SHELL": "/bin/bash", "TERM": "screen"}}
|
|
|
|
type CastHeader struct {
|
|
|
|
Version int `json:"version"`
|
|
|
|
Width int `json:"width"`
|
|
|
|
Height int `json:"height"`
|
|
|
|
Timestamp int64 `json:"timestamp"`
|
|
|
|
Env map[string]string `json:"env"`
|
|
|
|
}
|
|
|
|
j, err := json.Marshal(CastHeader{
|
|
|
|
Version: 2,
|
|
|
|
Width: w.Width,
|
|
|
|
Height: w.Height,
|
|
|
|
Timestamp: now.Unix(),
|
|
|
|
Env: map[string]string{
|
|
|
|
"TERM": term,
|
|
|
|
// TODO(bradiftz): anything else important?
|
|
|
|
// including all seems noisey, but maybe we should
|
|
|
|
// for auditing. But first need to break
|
|
|
|
// launchProcess's startWithStdPipes and
|
|
|
|
// startWithPTY up so that they first return the cmd
|
|
|
|
// without starting it, and then a step that starts
|
|
|
|
// it. Then we can (1) make the cmd, (2) start the
|
|
|
|
// recording, (3) start the process.
|
|
|
|
},
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
f.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
ss.logf("starting asciinema recording to %s", f.Name())
|
|
|
|
j = append(j, '\n')
|
|
|
|
if _, err := f.Write(j); err != nil {
|
|
|
|
f.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return rec, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// recording is the state for an SSH session recording.
|
|
|
|
type recording struct {
|
|
|
|
ss *sshSession
|
|
|
|
start time.Time
|
|
|
|
|
|
|
|
mu sync.Mutex // guards writes to, close of out
|
|
|
|
out *os.File // nil if closed
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *recording) Close() error {
|
|
|
|
r.mu.Lock()
|
|
|
|
defer r.mu.Unlock()
|
|
|
|
if r.out == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
err := r.out.Close()
|
|
|
|
r.out = nil
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// writer returns an io.Writer around w that first records the write.
|
|
|
|
//
|
|
|
|
// The dir should be "i" for input or "o" for output.
|
|
|
|
//
|
|
|
|
// If r is nil, it returns w unchanged.
|
|
|
|
func (r *recording) writer(dir string, w io.Writer) io.Writer {
|
|
|
|
if r == nil {
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
return &loggingWriter{r, dir, w}
|
|
|
|
}
|
|
|
|
|
|
|
|
// loggingWriter is an io.Writer wrapper that writes first an
|
|
|
|
// asciinema JSON cast format recording line, and then writes to w.
|
|
|
|
type loggingWriter struct {
|
|
|
|
r *recording
|
|
|
|
dir string // "i" or "o" (input or output)
|
|
|
|
w io.Writer // underlying Writer, after writing to r.out
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w loggingWriter) Write(p []byte) (n int, err error) {
|
|
|
|
j, err := json.Marshal([]interface{}{
|
|
|
|
time.Since(w.r.start).Seconds(),
|
|
|
|
w.dir,
|
|
|
|
string(p),
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
j = append(j, '\n')
|
|
|
|
if err := w.writeCastLine(j); err != nil {
|
|
|
|
return 0, nil
|
|
|
|
}
|
|
|
|
return w.w.Write(p)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w loggingWriter) writeCastLine(j []byte) error {
|
|
|
|
w.r.mu.Lock()
|
|
|
|
defer w.r.mu.Unlock()
|
|
|
|
if w.r.out == nil {
|
|
|
|
return errors.New("logger closed")
|
|
|
|
}
|
|
|
|
_, err := w.r.out.Write(j)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("logger Write: %w", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func envValFromList(env []string, wantKey string) (v string) {
|
|
|
|
for _, kv := range env {
|
|
|
|
if thisKey, v, ok := strings.Cut(kv, "="); ok && envEq(thisKey, wantKey) {
|
|
|
|
return v
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
// envEq reports whether environment variable a == b for the current
|
|
|
|
// operating system.
|
|
|
|
func envEq(a, b string) bool {
|
|
|
|
if runtime.GOOS == "windows" {
|
|
|
|
return strings.EqualFold(a, b)
|
|
|
|
}
|
|
|
|
return a == b
|
|
|
|
}
|