├── .gitignore ├── jumpgate ├── schema.db ├── jumpgate.schema ├── jumpgate.go ├── channel.go ├── README.md └── sconn.go ├── README.md ├── sslclient └── sslclient.go ├── listener └── listener.go ├── handshakekey └── handshakekey.go ├── handshakekbi └── kbi.go ├── sslserver └── sslserver.go ├── main └── sshproxy_main.go ├── sshproxy.go └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | -------------------------------------------------------------------------------- /jumpgate/schema.db: -------------------------------------------------------------------------------- 1 | CREATE TABLE host_keys( 2 | target STRING NOT NULL, 3 | pubkey STRING NOT NULL, 4 | PRIMARY KEY(target) 5 | ); 6 | CREATE TABLE passwords( 7 | target STRING NOT NULL, 8 | password STRING NOT NULL, 9 | PRIMARY KEY(target) 10 | ); 11 | CREATE TABLE acl( 12 | pubkey TEXT NOT NULL, 13 | target TEXT NOT NULL 14 | ); 15 | -------------------------------------------------------------------------------- /jumpgate/jumpgate.schema: -------------------------------------------------------------------------------- 1 | CREATE TABLE host_keys( 2 | host STRING NOT NULL, 3 | type STRING NOT NULL, 4 | pubkey STRING NOT NULL, 5 | PRIMARY KEY(host, type) 6 | ); 7 | CREATE TABLE passwords( 8 | target STRING NOT NULL, 9 | password STRING NOT NULL, 10 | PRIMARY KEY(target) 11 | ); 12 | CREATE TABLE acl( 13 | pubkey TEXT NOT NULL, 14 | target TEXT NOT NULL 15 | ); 16 | CREATE TABLE cas( 17 | pubkey TEXT NOT NULL, 18 | target TEXT NOT NULL 19 | ); 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sshproxy 2 | SSH Proxy / Load balancer 3 | 4 | Copyright (C) 2014 Thomas Habets 5 | 6 | ## Description 7 | 8 | SSHProxy proxies an SSH connection over SSL, to allow: 9 | * A client to use an SSH key they don't have access to. Therefore 10 | they can't go around the proxy, or lose the key. 11 | * Logging of everything typed and received through the proxy (optional). 12 | 13 | For setup instructions, see 14 | [this blog post](https://blog.habets.se/2014/06/Another-way-to-protect-your-SSH-keys). 15 | 16 | ## -auth=key 17 | 18 | With `-auth=key` the client will use `PubkeyAuthentication` to authenticate to `SSHProxy`, 19 | and SSHProxy will use the key specified in `-client_keyfile` to log in to the server. 20 | 21 | ## -auth=kbi 22 | 23 | With `-auth=kbi` SSHProxy will forward the password from the client on to the server. 24 | -------------------------------------------------------------------------------- /sslclient/sslclient.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | * Copyright (C) 2014 Thomas Habets 5 | * 6 | * This program is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along 17 | * with this program; if not, write to the Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 19 | * 20 | * 21 | **/ 22 | import ( 23 | "crypto/tls" 24 | "flag" 25 | "fmt" 26 | "io" 27 | "log" 28 | "os" 29 | ) 30 | 31 | var ( 32 | proxy = flag.String("proxy", "", "SSHProxy host:port.") 33 | target = flag.String("target", "", "Target to connect to.") 34 | ) 35 | 36 | func mandatoryFlag(name string) { 37 | f := flag.Lookup(name) 38 | if f.Value.String() == f.DefValue { 39 | log.Fatalf("-%s is mandatory", name) 40 | } 41 | } 42 | 43 | func main() { 44 | flag.Parse() 45 | mandatoryFlag("proxy") 46 | mandatoryFlag("target") 47 | 48 | conf := tls.Config{ 49 | // TODO: Secure settings. 50 | InsecureSkipVerify: true, 51 | } 52 | 53 | c, err := tls.Dial("tcp", *proxy, &conf) 54 | if err != nil { 55 | log.Fatalf("tls Dial: %v", err) 56 | } 57 | if _, err := c.Write([]byte(fmt.Sprintf("%s\n", *target))); err != nil { 58 | log.Fatalf("Write: %v", err) 59 | } 60 | go io.Copy(os.Stdout, c) 61 | io.Copy(c, os.Stdin) 62 | } 63 | -------------------------------------------------------------------------------- /jumpgate/jumpgate.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "database/sql" 6 | "flag" 7 | "io/ioutil" 8 | "net" 9 | 10 | _ "github.com/mattn/go-sqlite3" 11 | log "github.com/sirupsen/logrus" 12 | "golang.org/x/crypto/ssh" 13 | ) 14 | 15 | var ( 16 | addr = flag.String("addr", ":2022", "Address to listen to.") 17 | serverKey = flag.String("server_key", "jumpgate-key", "Server key.") 18 | dbType = flag.String("db_type", "sqlite3", "Database type.") 19 | dbConn = flag.String("db", "", "Database connect string.") 20 | 21 | db *sql.DB 22 | ) 23 | 24 | func main() { 25 | flag.Parse() 26 | 27 | if flag.NArg() > 0 { 28 | log.Fatalf("Trailing cmdline args: %q", flag.Args()) 29 | } 30 | 31 | var err error 32 | db, err = sql.Open(*dbType, *dbConn) 33 | if err != nil { 34 | log.Fatalf("Failed to connect to DB %q %q: %v", *dbType, *dbConn) 35 | } 36 | if err := db.Ping(); err != nil { 37 | log.Fatalf("Failed to ping DB %q %q: %v", *dbType, *dbConn) 38 | } 39 | defer db.Close() 40 | 41 | l, err := net.Listen("tcp", *addr) 42 | if err != nil { 43 | log.Fatalf("Listening to %q: %v", *addr, err) 44 | } 45 | 46 | log.Infof("Ready on %q", *addr) 47 | cfg := ssh.ServerConfig{} 48 | { 49 | b, err := ioutil.ReadFile(*serverKey) 50 | if err != nil { 51 | log.Fatalf("Can't read private key file %q (-server_key): %v", *serverKey, err) 52 | } 53 | sk, err := ssh.ParsePrivateKey(b) 54 | if err != nil { 55 | log.Fatalf("Can't parse private key file %q (-server_key): %v", *serverKey, err) 56 | } 57 | cfg.AddHostKey(sk) 58 | } 59 | ctx := context.Background() 60 | for { 61 | conn, err := l.Accept() 62 | if err != nil { 63 | log.Errorf("accept(): %v", err) 64 | } 65 | t := sconn{ 66 | conn: conn, 67 | cfg: cfg, 68 | } 69 | go func() { 70 | if err := t.handleConnection(ctx); err != nil { 71 | log.Errorf("Handling connection: %v", err) 72 | } 73 | }() 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /listener/listener.go: -------------------------------------------------------------------------------- 1 | // ./listener -listen 0.0.0.0:2022 ./next-program -conn_fd '{}' 2 | // 3 | // The point of listener is so that `next-program` doesn't have to 4 | // handle multiple connections, and can exit on errors. 5 | // Go doesn't "do" fork within a binary for these purposes. 6 | package main 7 | 8 | /* 9 | * Copyright (C) 2014 Thomas Habets 10 | * 11 | * This program is free software; you can redistribute it and/or modify 12 | * it under the terms of the GNU General Public License as published by 13 | * the Free Software Foundation; either version 2 of the License, or 14 | * (at your option) any later version. 15 | * 16 | * This program is distributed in the hope that it will be useful, 17 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | * GNU General Public License for more details. 20 | * 21 | * You should have received a copy of the GNU General Public License along 22 | * with this program; if not, write to the Free Software Foundation, Inc., 23 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 24 | * 25 | */ 26 | import ( 27 | "flag" 28 | "log" 29 | "net" 30 | "os" 31 | "os/exec" 32 | ) 33 | 34 | var ( 35 | listen = flag.String("listen", "", "Listen address.") 36 | ) 37 | 38 | func handleConnection(conn *net.TCPConn) { 39 | defer conn.Close() 40 | args := flag.Args()[1:] 41 | for n := range args { 42 | if args[n] == "{}" { 43 | args[n] = "3" 44 | } 45 | } 46 | cmd := exec.Command(flag.Args()[0], args...) 47 | cmd.Stdout = os.Stdout 48 | cmd.Stderr = os.Stderr 49 | func() { 50 | if f, err := conn.File(); err != nil { 51 | log.Printf("Command start failed: %v", err) 52 | } else { 53 | defer conn.Close() 54 | defer f.Close() 55 | cmd.ExtraFiles = []*os.File{f} 56 | } 57 | if err := cmd.Start(); err != nil { 58 | log.Printf("Command start failed: %v", err) 59 | } 60 | }() 61 | if err := cmd.Wait(); err != nil { 62 | log.Printf("Command wait failed: %v", err) 63 | } 64 | } 65 | 66 | func main() { 67 | flag.Parse() 68 | listener, err := net.Listen("tcp", *listen) 69 | if err != nil { 70 | log.Fatalf("Failed to listen to %q: %v", *listen, err) 71 | } 72 | log.Printf("Ready") 73 | for { 74 | conn, err := listener.Accept() 75 | if err != nil { 76 | log.Printf("accept(): %v", err) 77 | continue 78 | } 79 | go handleConnection(conn.(*net.TCPConn)) 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /handshakekey/handshakekey.go: -------------------------------------------------------------------------------- 1 | package handshakekey 2 | 3 | /* 4 | * Copyright (C) 2014 Thomas Habets 5 | * 6 | * This program is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along 17 | * with this program; if not, write to the Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 19 | * 20 | */ 21 | import ( 22 | "fmt" 23 | "io/ioutil" 24 | "log" 25 | "strings" 26 | 27 | "code.google.com/p/go.crypto/ssh" 28 | ) 29 | 30 | // HandshakeKey implements SSH key auth to proxy, and then uses a differnt local key against the target. 31 | type HandshakeKey struct { 32 | AuthorizedKeys string 33 | ClientPrivateKey ssh.Signer 34 | } 35 | 36 | // Handshake performs the handshake. 37 | func (h *HandshakeKey) Handshake(downstreamConf *ssh.ServerConfig, target string) <-chan *ssh.Client { 38 | var user string 39 | upstreamConnected := make(chan error, 10) 40 | userChan := make(chan string, 10) 41 | downstreamConf.PublicKeyCallback = func(c ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { 42 | thisKey := strings.SplitN(strings.Trim(string(ssh.MarshalAuthorizedKey(key)), "\n"), " ", 3) 43 | log.Printf("Public key callback: %q", thisKey) 44 | // TODO: certs. 45 | d, err := ioutil.ReadFile(h.AuthorizedKeys) 46 | if err != nil { 47 | log.Fatal(err) 48 | } 49 | authOk := false 50 | for _, line := range strings.Split(string(d), "\n") { 51 | parts := strings.SplitN(line, " ", 3) 52 | if parts[0] == thisKey[0] && parts[1] == thisKey[1] { 53 | authOk = true 54 | break 55 | } 56 | } 57 | if authOk { 58 | userChan <- c.User() 59 | return nil, nil 60 | } 61 | return nil, fmt.Errorf("no I don't think so") 62 | } 63 | 64 | upstreamConf := &ssh.ClientConfig{ 65 | ClientVersion: "SSH-2.0-SSHProxy", 66 | Auth: []ssh.AuthMethod{ 67 | ssh.PublicKeys(h.ClientPrivateKey), 68 | }, 69 | } 70 | upstreamChannel := make(chan *ssh.Client) 71 | go func() { 72 | upstreamConf.User = <-userChan 73 | user = upstreamConf.User 74 | defer close(upstreamChannel) 75 | upstream, err := ssh.Dial("tcp", target, upstreamConf) 76 | if err != nil { 77 | upstreamConnected <- err 78 | log.Fatalf("upstream dial: %v", err) 79 | } 80 | log.Printf("upstream is connected") 81 | upstreamChannel <- upstream 82 | }() 83 | return upstreamChannel 84 | } 85 | -------------------------------------------------------------------------------- /jumpgate/channel.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "fmt" 7 | "io" 8 | "strings" 9 | "sync" 10 | 11 | log "github.com/sirupsen/logrus" 12 | "golang.org/x/crypto/ssh" 13 | "golang.org/x/sync/semaphore" 14 | ) 15 | 16 | const ( 17 | semAll int64 = 100 18 | ) 19 | 20 | type channel struct { 21 | channel ssh.Channel 22 | clientChannel ssh.Channel 23 | req <-chan *ssh.Request 24 | clientReq <-chan *ssh.Request 25 | } 26 | 27 | // TODO: time out with ctx. 28 | func (c *channel) run(ctx context.Context) error { 29 | defer c.channel.Close() 30 | sem := semaphore.NewWeighted(semAll) 31 | 32 | var mu sync.Mutex 33 | var errs []error 34 | 35 | sem.Acquire(ctx, 1) 36 | go func() { 37 | defer sem.Release(1) 38 | if _, err := io.Copy(c.channel, c.clientChannel); err != nil { 39 | mu.Lock() 40 | defer mu.Unlock() 41 | errs = append(errs, fmt.Errorf("client->server streaming: %v", err)) 42 | return 43 | } 44 | log.Debugf("... Channel client->server done") 45 | if err := c.channel.Close(); err != nil { 46 | mu.Lock() 47 | defer mu.Unlock() 48 | errs = append(errs, fmt.Errorf("closing server channel: %v", err)) 49 | return 50 | } 51 | }() 52 | 53 | sem.Acquire(ctx, 1) 54 | go func() { 55 | defer sem.Release(1) 56 | if _, err := io.Copy(c.clientChannel, c.channel); err != nil { 57 | mu.Lock() 58 | defer mu.Unlock() 59 | errs = append(errs, fmt.Errorf("server->client streaming: %v", err)) 60 | return 61 | } 62 | log.Debugf("... Channel server->client done") 63 | }() 64 | 65 | var cDone, sDone bool 66 | for !cDone && !sDone { 67 | select { 68 | case r := <-c.req: 69 | if r == nil { 70 | sDone = true 71 | c.req = nil 72 | continue 73 | } 74 | log.Debugf("Server request: %v", r) 75 | b, err := c.clientChannel.SendRequest(r.Type, r.WantReply, r.Payload) 76 | if err != nil { 77 | mu.Lock() 78 | errs = append(errs, fmt.Errorf("client SendRequest failed: %v", err)) 79 | mu.Unlock() 80 | } else { 81 | if r.WantReply { 82 | if err := r.Reply(b, r.Payload); err != nil { 83 | mu.Lock() 84 | errs = append(errs, fmt.Errorf("server Reply failed: %v", err)) 85 | mu.Unlock() 86 | } 87 | } 88 | } 89 | case r := <-c.clientReq: 90 | if r == nil { 91 | cDone = true 92 | c.clientReq = nil 93 | continue 94 | } 95 | log.Debugf("Client request: %v", r) 96 | b, err := c.channel.SendRequest(r.Type, r.WantReply, r.Payload) 97 | if err != nil { 98 | mu.Lock() 99 | errs = append(errs, fmt.Errorf("server SendRequest failed: %v", err)) 100 | mu.Unlock() 101 | } else { 102 | if r.WantReply { 103 | if err := r.Reply(b, r.Payload); err != nil { 104 | mu.Lock() 105 | errs = append(errs, fmt.Errorf("client Reply failed: %v", err)) 106 | mu.Unlock() 107 | } 108 | } 109 | } 110 | } 111 | } 112 | log.Debugf("... Channel closing") 113 | sem.Acquire(ctx, semAll) 114 | var ss []string 115 | for _, e := range errs { 116 | ss = append(ss, e.Error()) 117 | } 118 | if len(ss) > 0 { 119 | return errors.New(strings.Join(ss, ";")) 120 | } 121 | return nil 122 | } 123 | -------------------------------------------------------------------------------- /handshakekbi/kbi.go: -------------------------------------------------------------------------------- 1 | package handshakekbi 2 | 3 | /* 4 | * Copyright (C) 2014 Thomas Habets 5 | * 6 | * This program is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along 17 | * with this program; if not, write to the Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 19 | * 20 | */ 21 | import ( 22 | "log" 23 | 24 | "code.google.com/p/go.crypto/ssh" 25 | ) 26 | 27 | type keyboardInteractive struct { 28 | user, instruction string 29 | questions []string 30 | echos []bool 31 | reply chan []string 32 | } 33 | 34 | // HandshakeKBI implements straight forwarding of KeyboardInteractive auth. 35 | type HandshakeKBI struct{} 36 | 37 | // Handshake performs KeyboardInteractive proxy handshake. 38 | func (k *HandshakeKBI) Handshake(downstreamConf *ssh.ServerConfig, target string) <-chan *ssh.Client { 39 | authKBI := make(chan keyboardInteractive, 10) 40 | userChan := make(chan string, 10) 41 | upstreamConnected := make(chan error, 10) 42 | ua := ssh.KeyboardInteractive(func(user, instruction string, questions []string, echos []bool) (answers []string, err error) { 43 | log.Printf("upstream auth: %q %q %v", user, instruction, questions) 44 | q := keyboardInteractive{ 45 | user: user, 46 | instruction: instruction, 47 | questions: questions, 48 | echos: echos, 49 | reply: make(chan []string, 10), 50 | } 51 | authKBI <- q 52 | ans := <-q.reply 53 | log.Printf("answering upstream") 54 | return ans, nil 55 | }) 56 | 57 | upstreamConf := &ssh.ClientConfig{ 58 | ClientVersion: "SSH-2.0-SSHProxy", 59 | Auth: []ssh.AuthMethod{ 60 | ua, 61 | }, 62 | } 63 | 64 | downstreamConf.KeyboardInteractiveCallback = func(c ssh.ConnMetadata, chal ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) { 65 | userChan <- c.User() 66 | for try := range authKBI { 67 | log.Printf("downstream auth: %+v", try) 68 | defer close(try.reply) 69 | reply, err := chal(try.user, try.instruction, try.questions, try.echos) 70 | if err != nil { 71 | log.Printf("server chal: %v", err) 72 | } 73 | log.Printf("got reply from downstream: %v", reply) 74 | try.reply <- reply 75 | } 76 | if err := <-upstreamConnected; err != nil { 77 | log.Fatalf("upstream not connected: %v", err) 78 | } 79 | return nil, nil 80 | } 81 | upstreamChannel := make(chan *ssh.Client) 82 | go func() { 83 | upstreamConf.User = <-userChan 84 | defer close(upstreamChannel) 85 | defer close(authKBI) 86 | upstream, err := ssh.Dial("tcp", target, upstreamConf) 87 | if err != nil { 88 | upstreamConnected <- err 89 | log.Fatalf("upstream dial: %v", err) 90 | } 91 | log.Printf("upstream is connected") 92 | upstreamChannel <- upstream 93 | }() 94 | 95 | return upstreamChannel 96 | } 97 | -------------------------------------------------------------------------------- /jumpgate/README.md: -------------------------------------------------------------------------------- 1 | # Jumpgate 2 | 3 | ## Purpose 4 | 5 | [SSH Certificates](https://blog.habets.se/2011/07/OpenSSH-certificates.html) are 6 | great, but are not supported by all SSH implementations, nor where they are 7 | supported are they always configurable. E.g. many IoT devices don't support 8 | them. Even public key logins are not always supported. 9 | 10 | Jumpgate will allow you to set a unique password on all devices, and have a 11 | jumpgate where you SSH with a certificate or pubkey, and the jumpgate logs in 12 | for you, using the password it stores. 13 | 14 | So you can have good and unique passwords, but with all the benefits of pubkeys 15 | and CAs, even when the devices themselves don't support them. 16 | 17 | Taking all connections through a set of proxies helps auditing and enables 18 | cutting all new and existing connections instantly. 19 | 20 | ## Setup 21 | 22 | ### Create CA and a user key 23 | 24 | ``` 25 | $ ssh-keygen -t ed25519 -N "secret CA password" -f ca 26 | $ ssh-keygen -t ed25519 -f user_key 27 | $ ssh-keygen -s ca -I thomas-key1 -n thomas,username2 user_key.pub 28 | $ ssh-keygen -l -f user_key.pub | awk '{print $2 ""}' 29 | SHA256:abcabc___user_key_here___abcabc 30 | ``` 31 | 32 | ### Create SSH proxy host key 33 | 34 | ``` 35 | $ ssh-keygen -t ed25519 -N '' -f jumpgate-key 36 | ``` 37 | 38 | ### Set up login database 39 | 40 | ``` 41 | $ sqlite3 jumpgate.sqlite3 < jumpgate.schema 42 | ``` 43 | 44 | #### Add host keys 45 | 46 | Host keys can be printed from a `known_hosts` with: 47 | 48 | ``` 49 | $ ssh-keygen -F router.example.com -l | grep -v ^# | awk '{print $3 "\n" $2}' 50 | SHA256:abcabc___HOST_key_here___abcabc 51 | ssh-rsa 52 | ``` 53 | 54 | Or on the server with something like: 55 | 56 | ``` 57 | $ ssh-keygen -l -f /etc/ssh/ssh_host_ecdsa_key.pub | awk '{print $2}' 58 | SHA256:abcabc___HOST_key_here___abcabc 59 | $ awk '{print $1}' /etc/ssh/ssh_host_ecdsa_key.pub 60 | ecdsa-sha2-nistp256 61 | ``` 62 | 63 | ``` 64 | $ sqlite3 jumpgate.sqlite3 65 | > INSERT INTO host_keys(host, type, pubkey) VALUES('router.example.com:22', 'ssh-rsa', 'SHA256:abcabc___HOST_key_here___abcabc'); 66 | > INSERT INTO host_keys(host, type, pubkey) VALUES('router2.example.com:22', 'ssh-rsa', 'SHA256:abcabc___HOST_key2_here___abcabc'); 67 | ``` 68 | 69 | #### Add user keys, client CAs, and account passwords 70 | 71 | CA fingerprint can be extracted like the host key: 72 | 73 | ``` 74 | $ ssh-keygen -l -f ca.pub | awk '{print $2}' 75 | SHA256:abcabc___CA_key_here___abcabc 76 | $ awk '{print $1}' ca.pub 77 | ssh-ed25519 78 | ``` 79 | 80 | ``` 81 | $ sqlite3 jumpgate.sqlite3 82 | > INSERT INTO acl(pubkey, target) VALUES('SHA256:abcabc___user_key_here___abcabc', 'admin@router.example.com:22'); 83 | > INSERT INTO cas(pubkey, target) VALUES('SHA256:abcabc___CA_key_here___abcabc', 'admin@router.example.com:22'); 84 | > INSERT INTO cas(pubkey, target) VALUES('SHA256:abcabc___CA_key_here___abcabc', 'admin@router2.example.com:22'); 85 | > INSERT INTO passwords VALUES('admin@router.example.com:22', 'password here'); 86 | > INSERT INTO passwords VALUES('admin@router2.example.com:22', 'password here'); 87 | ^D 88 | $ ./jumpgate -db jumpgate.sqlite3 89 | ``` 90 | 91 | ### Start jumpgate 92 | 93 | ``` 94 | ./jumpgate -db=jumpgate.sqlite3 95 | ``` 96 | 97 | ### Log in to host 98 | 99 | ``` 100 | ssh -p 2022 admin%router.example.com:22@localhost 101 | ``` 102 | -------------------------------------------------------------------------------- /sslserver/sslserver.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | * Copyright (C) 2014 Thomas Habets 5 | * 6 | * This program is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along 17 | * with this program; if not, write to the Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 19 | * 20 | * 21 | **/ 22 | import ( 23 | "bytes" 24 | "crypto/tls" 25 | "flag" 26 | "fmt" 27 | "io" 28 | "log" 29 | "net" 30 | "os" 31 | "os/exec" 32 | "syscall" 33 | ) 34 | 35 | var ( 36 | keyfile = flag.String("key", "", "SSL server key file.") 37 | certfile = flag.String("cert", "", "SSL server CRT file.") 38 | listen = flag.String("listen", "", "Listen address.") 39 | ) 40 | 41 | func mandatoryFlag(name string) { 42 | f := flag.Lookup(name) 43 | if f.Value.String() == f.DefValue { 44 | log.Fatalf("-%s is mandatory", name) 45 | } 46 | } 47 | 48 | func readLine(r io.Reader) (string, error) { 49 | var b bytes.Buffer 50 | for { 51 | ch := make([]byte, 1) 52 | if n, err := r.Read(ch); n != 1 || err != nil { 53 | return "", nil 54 | } 55 | if ch[0] == '\n' { 56 | break 57 | } 58 | if n, err := b.Write(ch); n != 1 || err != nil { 59 | return "", nil 60 | } 61 | if b.Len() > 256 { 62 | return "", fmt.Errorf("Target line too long.") 63 | } 64 | } 65 | return b.String(), nil 66 | } 67 | 68 | func handle(c net.Conn) { 69 | defer c.Close() 70 | l, err := readLine(c) 71 | if err != nil { 72 | log.Print(err) 73 | return 74 | } 75 | log.Printf("Connecting to %s...", l) 76 | args := flag.Args() 77 | args = append(args, "-conn_fd=3") 78 | args = append(args, "-forwarded="+c.RemoteAddr().String()) 79 | args = append(args, "-target="+l) 80 | cmd := exec.Command(args[0], args[1:]...) 81 | cmd.Stdout = os.Stdout 82 | cmd.Stderr = os.Stderr 83 | 84 | fds, err := syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_STREAM, 0) 85 | if err != nil { 86 | } 87 | mine := os.NewFile(uintptr(fds[0]), "connection") 88 | theirs := os.NewFile(uintptr(fds[1]), "connection") 89 | cmd.ExtraFiles = []*os.File{theirs} 90 | if err := cmd.Start(); err != nil { 91 | log.Printf("cmd.Start(): %v", err) 92 | return 93 | } 94 | theirs.Close() 95 | go io.Copy(c, mine) 96 | _, err = io.Copy(mine, c) 97 | if err != nil { 98 | log.Printf("Copying from network to socketpair(): %v", err) 99 | } 100 | mine.Close() 101 | if err := cmd.Wait(); err != nil { 102 | log.Printf("cmd.Wait(): %v", err) 103 | } 104 | log.Printf("Done.") 105 | } 106 | 107 | func main() { 108 | flag.Parse() 109 | mandatoryFlag("key") 110 | mandatoryFlag("cert") 111 | mandatoryFlag("listen") 112 | 113 | cert, err := tls.LoadX509KeyPair(*certfile, *keyfile) 114 | if err != nil { 115 | log.Fatalf("server: loadkeys(%s, %s): %s", *certfile, *keyfile, err) 116 | } 117 | conf := tls.Config{ 118 | Certificates: []tls.Certificate{cert}, 119 | } 120 | 121 | l, err := tls.Listen("tcp", *listen, &conf) 122 | if err != nil { 123 | log.Fatalf("tls Listen: %v", err) 124 | } 125 | log.Printf("Ready...") 126 | for { 127 | c, err := l.Accept() 128 | if err != nil { 129 | log.Printf("accept(): %v", err) 130 | continue 131 | } 132 | go handle(c) 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /main/sshproxy_main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | * Copyright (C) 2014 Thomas Habets 5 | * 6 | * This program is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along 17 | * with this program; if not, write to the Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 19 | * 20 | ssh-keygen -N "" -f id_rsa 21 | ./listener -listen 127.0.0.1:2022 \ 22 | ./sshproxy \ 23 | -conn_fd '{}' \ 24 | -keyfile id_rsa \ 25 | -target 127.0.0.1:22 \ 26 | -logdir sshlogdir \ 27 | -log_upstream \ 28 | -log_downstream \ 29 | -auth=kbi 30 | * 31 | **/ 32 | import ( 33 | "flag" 34 | "fmt" 35 | "io/ioutil" 36 | "log" 37 | "net" 38 | "os" 39 | "strconv" 40 | 41 | "code.google.com/p/go.crypto/ssh" 42 | "github.com/ThomasHabets/sshproxy" 43 | "github.com/ThomasHabets/sshproxy/handshakekbi" 44 | "github.com/ThomasHabets/sshproxy/handshakekey" 45 | ) 46 | 47 | var ( 48 | target = flag.String("target", "", "SSH server to connect to.") 49 | connFD = flag.String("conn_fd", "", "File descriptor to work with.") 50 | keyfile = flag.String("keyfile", "", "SSH server key file.") 51 | forwarded = flag.String("forwarded", "", "Forwarded for. Used by sslserver.") 52 | logdir = flag.String("logdir", "", "Directory in which to create logs.") 53 | logUpstream = flag.Bool("log_upstream", false, "Log data from upstream (server).") 54 | logDownstream = flag.Bool("log_downstream", false, "Log data from downstream (client).") 55 | 56 | auth = flag.String("auth", "", "Auth mode (key, kbi).") 57 | 58 | // For -auth=key 59 | clientKeyfile = flag.String("client_keyfile", "", "auth=key: SSH client key file.") 60 | authorizedKeys = flag.String("authorized_keys", "", "auth=key: Authorized keys for clients.") 61 | 62 | privateKey ssh.Signer 63 | 64 | user string 65 | ) 66 | 67 | func mandatoryFlag(name string) { 68 | f := flag.Lookup(name) 69 | if f.Value.String() == f.DefValue { 70 | log.Fatalf("-%s is mandatory", name) 71 | } 72 | } 73 | 74 | func main() { 75 | flag.Parse() 76 | mandatoryFlag("conn_fd") 77 | mandatoryFlag("target") 78 | mandatoryFlag("keyfile") 79 | mandatoryFlag("logdir") 80 | 81 | var auther sshproxy.Handshake 82 | if *auth == "key" { 83 | mandatoryFlag("authorized_keys") 84 | mandatoryFlag("client_keyfile") 85 | // Load SSH client key. 86 | privBytes, err := ioutil.ReadFile(*clientKeyfile) 87 | if err != nil { 88 | log.Fatalf("Can't read client private key file %q (-client_keyfile).", *clientKeyfile) 89 | } 90 | priv, err := ssh.ParsePrivateKey(privBytes) 91 | if err != nil { 92 | log.Fatalf("Parse error client reading private key %q: %v", *clientKeyfile, err) 93 | } 94 | 95 | auther = &handshakekey.HandshakeKey{ 96 | AuthorizedKeys: *authorizedKeys, 97 | ClientPrivateKey: priv, 98 | } 99 | } else if *auth == "kbi" { 100 | auther = &handshakekbi.HandshakeKBI{} 101 | } else { 102 | fmt.Fprintf(os.Stderr, "Unknown auth mode %q.", *auth) 103 | os.Exit(1) 104 | } 105 | 106 | // Load SSH server key. 107 | privateBytes, err := ioutil.ReadFile(*keyfile) 108 | if err != nil { 109 | log.Fatalf("Can't read private key file %q (-keyfile).", *keyfile) 110 | } 111 | privateKey, err = ssh.ParsePrivateKey(privateBytes) 112 | if err != nil { 113 | log.Fatalf("Parse error reading private key %q: %v", *keyfile, err) 114 | } 115 | 116 | connFDInt, err := strconv.Atoi(*connFD) 117 | if err != nil { 118 | log.Fatalf("-conn_fd %q is not int: %v", *connFD, err) 119 | } 120 | f := os.NewFile(uintptr(connFDInt), "connection") 121 | conn, err := net.FileConn(f) 122 | if err != nil { 123 | log.Fatalf("Broken FD passed in: %v", err) 124 | } 125 | f.Close() 126 | p := sshproxy.SSHProxy{ 127 | Target: *target, 128 | Conn: conn, 129 | Auther: auther, 130 | PrivateKey: privateKey, 131 | Forwarded: *forwarded, 132 | LogDir: *logdir, 133 | LogUpstream: *logUpstream, 134 | LogDownstream: *logDownstream, 135 | } 136 | log.Printf("sshproxy: running...") 137 | p.Run() 138 | } 139 | -------------------------------------------------------------------------------- /jumpgate/sconn.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "net" 7 | "strings" 8 | 9 | log "github.com/sirupsen/logrus" 10 | "golang.org/x/crypto/ssh" 11 | ) 12 | 13 | type sconn struct { 14 | conn net.Conn 15 | cfg ssh.ServerConfig 16 | 17 | // Filled in after handshake. 18 | password string 19 | target string 20 | host string 21 | meta ssh.ConnMetadata 22 | key ssh.PublicKey 23 | user string 24 | client ssh.Conn 25 | } 26 | 27 | func user2Target(in string) (string, string, error) { 28 | t := strings.SplitN(in, "%", 2) 29 | if len(t) < 2 { 30 | return "", "", fmt.Errorf("username has wrong format: %q", in) 31 | } 32 | return t[0], t[1], nil 33 | } 34 | 35 | func (sc *sconn) pubkeyCallback(inmeta ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { 36 | meta := inmeta.(*decodedConnMetadata) 37 | fprint := ssh.FingerprintSHA256(key) 38 | log.Infof("Pubkey attempt by %s to %s from %s: %v", meta.User(), meta.host, meta.RemoteAddr().String(), fprint) 39 | 40 | var n int 41 | if err := db.QueryRowContext( 42 | context.TODO(), 43 | `SELECT 1 FROM acl WHERE pubkey=$1 AND target=$2`, 44 | fprint, 45 | meta.target).Scan(&n); err != nil { 46 | return nil, fmt.Errorf("acl rejects key %q from connecting to %q", fprint, meta.target) 47 | } 48 | 49 | sc.meta = meta 50 | sc.key = key 51 | sc.user = meta.User() 52 | sc.target = meta.target 53 | sc.host = meta.host 54 | if err := db.QueryRowContext( 55 | context.TODO(), 56 | `SELECT password FROM passwords WHERE target=$1`, 57 | sc.target).Scan(&sc.password); err != nil { 58 | return nil, fmt.Errorf("getting password for %q: %v", sc.target, err) 59 | } 60 | log.Infof("... Accepted pubkey %q for user %q target %q", fprint, meta.User(), sc.target) 61 | return nil, nil 62 | } 63 | 64 | func (sc *sconn) keyboardInteractive(user, instruction string, questions []string, echos []bool) (answers []string, err error) { 65 | log.Debugf("... keyboardinteractive: %q %q %q %v", user, instruction, questions, echos) 66 | var ans []string 67 | for _ = range questions { 68 | ans = append(ans, sc.password) 69 | } 70 | return ans, nil 71 | } 72 | 73 | func (sc *sconn) hostKeyCallback(hostname string, remote net.Addr, key ssh.PublicKey) error { 74 | // TODO: check host cert, if present. 75 | log.Debugf("... Host key %q: %v", hostname, ssh.FingerprintSHA256(key)) 76 | var k string 77 | if err := db.QueryRowContext( 78 | context.TODO(), 79 | `SELECT pubkey FROM host_keys WHERE host=$1`, 80 | sc.host).Scan(&k); err != nil { 81 | return fmt.Errorf("getting host key %q: %v", sc.target, err) 82 | } 83 | if got, want := ssh.FingerprintSHA256(key), k; got != want { 84 | return fmt.Errorf("wrong host key. got %q, want %q", got, want) 85 | } 86 | return nil 87 | } 88 | 89 | func (sc *sconn) getAlgos(ctx context.Context) ([]string, error) { 90 | rows, err := db.QueryContext(ctx, `SELECT type FROM host_keys WHERE host=$1`, sc.host) 91 | if err != nil { 92 | return nil, fmt.Errorf("failed to query for host keys: %v", err) 93 | } 94 | defer rows.Close() 95 | var algos []string 96 | 97 | for rows.Next() { 98 | var a string 99 | if err := rows.Scan(&a); err != nil { 100 | return nil, err 101 | } 102 | algos = append(algos, a) 103 | } 104 | if err := rows.Err(); err != nil { 105 | return nil, err 106 | } 107 | return algos, nil 108 | } 109 | 110 | type decodedConnMetadata struct { 111 | user string 112 | host string 113 | target string 114 | meta ssh.ConnMetadata 115 | } 116 | 117 | func (m *decodedConnMetadata) User() string { 118 | return m.user 119 | } 120 | 121 | // SessionID returns the session hash, also denoted by H. 122 | func (m *decodedConnMetadata) SessionID() []byte { 123 | return m.meta.SessionID() 124 | } 125 | 126 | func (m *decodedConnMetadata) ClientVersion() []byte { 127 | return m.meta.ClientVersion() 128 | } 129 | 130 | func (m *decodedConnMetadata) ServerVersion() []byte { 131 | return m.meta.ServerVersion() 132 | } 133 | 134 | // RemoteAddr returns the remote address for this connection. 135 | func (m *decodedConnMetadata) RemoteAddr() net.Addr { 136 | return m.meta.RemoteAddr() 137 | } 138 | 139 | // LocalAddr returns the local address for this connection. 140 | func (m *decodedConnMetadata) LocalAddr() net.Addr { 141 | return m.meta.LocalAddr() 142 | } 143 | 144 | func (sc *sconn) certCallback(meta ssh.ConnMetadata, pub ssh.PublicKey) (*ssh.Permissions, error) { 145 | user, host, err := user2Target(meta.User()) 146 | if err != nil { 147 | // TODO: show error message to user 148 | log.Errorf("bad username %q", meta.User()) 149 | return nil, err 150 | } 151 | target := fmt.Sprintf("%s@%s", user, host) 152 | checker := ssh.CertChecker{ 153 | UserKeyFallback: sc.pubkeyCallback, 154 | // IsRevoked: TODO, 155 | IsUserAuthority: func(ca ssh.PublicKey) bool { 156 | cafpr := ssh.FingerprintSHA256(ca) 157 | var n int 158 | if err := db.QueryRowContext( 159 | context.TODO(), 160 | `SELECT 1 FROM cas WHERE pubkey=$1 AND target=$2`, 161 | cafpr, 162 | host).Scan(&n); err != nil { 163 | log.Errorf("Unknown CA %q for %q provided", cafpr, host) 164 | return false 165 | } 166 | sc.meta = meta 167 | sc.key = pub 168 | sc.user = user 169 | sc.target = target 170 | sc.host = host 171 | if err := db.QueryRowContext( 172 | context.TODO(), 173 | `SELECT password FROM passwords WHERE target=$1`, 174 | target).Scan(&sc.password); err != nil { 175 | log.Errorf("getting password for %q: %v", target, err) 176 | // TODO: show error to user. 177 | return false 178 | } 179 | log.Infof("... Accepted certificate %q using CA %q", ssh.FingerprintSHA256(pub), cafpr) 180 | return true 181 | }, 182 | } 183 | t := decodedConnMetadata{ 184 | user: user, 185 | host: host, 186 | meta: meta, 187 | target: target, 188 | } 189 | return checker.Authenticate(&t, pub) 190 | } 191 | 192 | // TODO: time out with ctx. 193 | func (sc *sconn) handleConnection(ctx context.Context) error { 194 | sc.cfg.PublicKeyCallback = sc.certCallback 195 | conn, chch, requestch, err := ssh.NewServerConn(sc.conn, &sc.cfg) 196 | if err != nil { 197 | return err 198 | } 199 | defer conn.Close() 200 | log.Infof("... Server connected!") 201 | 202 | var n int 203 | if err := db.QueryRowContext( 204 | ctx, 205 | `SELECT 1 FROM acl WHERE pubkey=$1 AND target=$2`, 206 | ssh.FingerprintSHA256(sc.key), 207 | sc.target).Scan(&n); err != nil { 208 | return fmt.Errorf("acl rejects key %q from connecting to %q", ssh.FingerprintSHA256(sc.key), sc.target) 209 | } 210 | 211 | algos, err := sc.getAlgos(ctx) 212 | if err != nil { 213 | return err 214 | } 215 | 216 | log.Infof("... dialing %q as user %q", sc.target, sc.user) 217 | sc.client, err = ssh.Dial("tcp", sc.host, &ssh.ClientConfig{ 218 | User: sc.user, 219 | // Timeout: TODO, 220 | BannerCallback: ssh.BannerDisplayStderr(), 221 | HostKeyAlgorithms: algos, 222 | HostKeyCallback: sc.hostKeyCallback, 223 | Auth: []ssh.AuthMethod{ 224 | ssh.Password(sc.password), 225 | ssh.KeyboardInteractive(sc.keyboardInteractive), 226 | }, 227 | }) 228 | if err != nil { 229 | return err 230 | } 231 | 232 | var chchDone, rchDone bool 233 | for !chchDone && !rchDone { 234 | select { 235 | case nch := <-chch: 236 | if nch == nil { 237 | log.Debugf("... No more channels") 238 | chch = nil 239 | chchDone = true 240 | continue 241 | } 242 | log.Debugf("... New channel type %q extradata %v", nch.ChannelType(), nch.ExtraData()) 243 | ch, req, err := nch.Accept() 244 | if err != nil { 245 | log.Errorf("Failed to accept channel: %v", err) 246 | } 247 | clientChannel, clientReq, err := sc.client.OpenChannel(nch.ChannelType(), nch.ExtraData()) 248 | c := &channel{ 249 | channel: ch, 250 | clientChannel: clientChannel, 251 | clientReq: clientReq, 252 | req: req, 253 | } 254 | go func() { 255 | if err := c.run(ctx); err != nil { 256 | log.Errorf("Channel failed: %v", err) 257 | } 258 | }() 259 | case req := <-requestch: 260 | if req == nil { 261 | log.Debugf("... No more requests") 262 | requestch = nil 263 | rchDone = true 264 | continue 265 | } 266 | log.Debugf("... New connection req: %v", req) 267 | } 268 | } 269 | log.Infof("... Server connection closing") 270 | return nil 271 | } 272 | -------------------------------------------------------------------------------- /sshproxy.go: -------------------------------------------------------------------------------- 1 | package sshproxy 2 | 3 | /* 4 | * Copyright (C) 2014 Thomas Habets 5 | * 6 | * This program is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along 17 | * with this program; if not, write to the Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 19 | */ 20 | import ( 21 | "fmt" 22 | "io" 23 | "log" 24 | "net" 25 | "os" 26 | "path" 27 | "sync" 28 | "time" 29 | 30 | "code.google.com/p/go-uuid/uuid" 31 | "code.google.com/p/go.crypto/ssh" 32 | ) 33 | 34 | // SSHProxy proxies a connection to a target. 35 | type SSHProxy struct { 36 | // Conn is the connection to downstream client. 37 | Conn net.Conn 38 | 39 | // Forwarded-for address. 40 | Forwarded string 41 | 42 | // Target is the name of the upstream server. 43 | Target string 44 | 45 | // Auther is the handshake implementation. 46 | Auther Handshake 47 | 48 | // PrivateKey is the private key of the SSHProxy server. 49 | PrivateKey ssh.Signer 50 | 51 | // Logging settings. 52 | LogUpstream, LogDownstream bool 53 | LogDir string 54 | 55 | user string 56 | } 57 | 58 | // Handshake is the auth type proxied. 59 | type Handshake interface { 60 | // Handshake handshakes downstream client, and returns a channel where the client object is then sent. 61 | // Because this function has to be run *concurrently* with ssh.NewServerConn(), it's never right to 62 | // call this synchronously, and the API makes that clear. 63 | Handshake(conf *ssh.ServerConfig, target string) <-chan *ssh.Client 64 | } 65 | 66 | func (p *SSHProxy) makeConfig() *ssh.ServerConfig { 67 | config := &ssh.ServerConfig{} 68 | config.AuthLogCallback = func(conn ssh.ConnMetadata, method string, err error) { 69 | log.Printf("(%s) Attempt method %s: %v", conn.RemoteAddr(), method, err) 70 | log.Printf("... user: %s", conn.User()) 71 | log.Printf("... session: %v", conn.SessionID()) 72 | log.Printf("... clientVersion: %s", conn.ClientVersion()) 73 | log.Printf("... serverVersion: %s", conn.ServerVersion()) 74 | log.Printf("... localAddr: %v", conn.LocalAddr()) 75 | p.user = conn.User() 76 | } 77 | config.AddHostKey(p.PrivateKey) 78 | return config 79 | } 80 | 81 | func (p *SSHProxy) handshake(wg *sync.WaitGroup) (<-chan ssh.NewChannel, *ssh.Client, error) { 82 | downstreamConf := p.makeConfig() 83 | upstreamChannel := p.Auther.Handshake(downstreamConf, p.Target) 84 | 85 | var err error 86 | 87 | _, channels, reqs, err := ssh.NewServerConn(p.Conn, downstreamConf) 88 | if err != nil { 89 | log.Fatalf("Handshake failed: %v", err) 90 | } 91 | upstream := <-upstreamChannel 92 | 93 | wg.Add(1) 94 | go func() { 95 | defer wg.Done() 96 | for req := range reqs { 97 | log.Printf("downstream->upstream req: %+v", req) 98 | ok, payload, err := upstream.Conn.SendRequest(req.Type, req.WantReply, req.Payload) 99 | if err != nil { 100 | log.Fatalf("request: %v", err) 101 | } 102 | req.Reply(ok, payload) 103 | } 104 | }() 105 | return channels, upstream, nil 106 | } 107 | 108 | // Run handshakes and handles the connection. 109 | func (p *SSHProxy) Run() { 110 | var wg sync.WaitGroup 111 | defer func() { 112 | wg.Wait() 113 | log.Printf("Connection closed.") 114 | p.Conn.Close() 115 | }() 116 | 117 | channels, upstream, err := p.handshake(&wg) 118 | if err != nil { 119 | log.Fatal(err) 120 | } 121 | for newChannel := range channels { 122 | wg.Add(1) 123 | go func(newChannel ssh.NewChannel) { 124 | defer wg.Done() 125 | if err := p.handleChannel(p.Conn, upstream, newChannel); err != nil { 126 | log.Printf("handleChannel: %v", err) 127 | } 128 | }(newChannel) 129 | } 130 | } 131 | 132 | type source string 133 | 134 | const ( 135 | sourceUpstream source = "upstream" 136 | sourceDownstream source = "downstream" 137 | ) 138 | 139 | func reverseDirection(s source) source { 140 | if s == sourceUpstream { 141 | return sourceDownstream 142 | } 143 | return sourceUpstream 144 | } 145 | 146 | func reader(from source, src ssh.Channel) <-chan []byte { 147 | ch := make(chan []byte) 148 | go func() { 149 | defer close(ch) 150 | for { 151 | data := make([]byte, 16) 152 | n, err := src.Read(data) 153 | if err == io.EOF { 154 | break 155 | } 156 | if n == 0 { 157 | continue 158 | } 159 | if err != nil { 160 | log.Fatalf("read from %s: %v", from, err) 161 | } 162 | ch <- data[:n] 163 | } 164 | }() 165 | return ch 166 | } 167 | 168 | func writer(from source, dst ssh.Channel, ch <-chan []byte) { 169 | for data := range ch { 170 | n := len(data) 171 | if nw, err := dst.Write(data[:n]); err != nil { 172 | log.Fatalf("write(%d) of data from %s: %v", n, from, err) 173 | } else if nw != n { 174 | log.Fatalf("short write %d < %d from %s", nw, n, from) 175 | } 176 | } 177 | } 178 | 179 | func (p *SSHProxy) dataForward(channelID string, from source, wg *sync.WaitGroup, src, dst ssh.Channel) { 180 | defer wg.Done() 181 | defer dst.Close() 182 | ch := reader(from, src) 183 | if (from == sourceUpstream && p.LogUpstream) || (from == sourceDownstream && p.LogDownstream) { 184 | ch = p.dataLogger(fmt.Sprintf("%s.%s", channelID, from), ch) 185 | } 186 | writer(from, dst, ch) 187 | log.Printf("closing %s", reverseDirection(from)) 188 | } 189 | 190 | func requestForward(from source, wg *sync.WaitGroup, in <-chan *ssh.Request, fwd ssh.Channel) { 191 | defer wg.Done() 192 | for req := range in { 193 | log.Printf("req from %s of type %s", from, req.Type) 194 | ok, err := fwd.SendRequest(req.Type, req.WantReply, req.Payload) 195 | if err == io.EOF { 196 | continue 197 | } else if err != nil { 198 | log.Fatalf("%s fwd.SendRequest(): %v", from, err) 199 | } 200 | log.Printf("... req ok: %v", ok) 201 | req.Reply(ok, nil) 202 | } 203 | } 204 | 205 | func (p *SSHProxy) dataLogger(fn string, ch <-chan []byte) <-chan []byte { 206 | newCh := make(chan []byte) 207 | f, err := os.Create(path.Join(p.LogDir, fn)) 208 | if err != nil { 209 | log.Fatal(err) 210 | } 211 | go func() { 212 | defer close(newCh) 213 | defer f.Close() 214 | for data := range ch { 215 | newCh <- data 216 | f.Write(data) 217 | } 218 | }() 219 | return newCh 220 | } 221 | 222 | // handleChannel forwards data and requests between upstream and downstream. 223 | // It blocks until until channel is closed. 224 | func (p *SSHProxy) handleChannel(conn net.Conn, upstreamClient *ssh.Client, newChannel ssh.NewChannel) error { 225 | channelID := uuid.New() 226 | startTime := time.Now() 227 | f, err := os.Create(path.Join(p.LogDir, fmt.Sprintf("%s.meta", channelID))) 228 | if err != nil { 229 | log.Fatal(err) 230 | } 231 | defer func() { 232 | n := time.Now() 233 | if _, err := f.WriteString(fmt.Sprintf("EndTime: %s\nDuration: %s\n", n, n.Sub(startTime))); err != nil { 234 | log.Fatal(err) 235 | } 236 | f.Close() 237 | }() 238 | if _, err := f.WriteString(fmt.Sprintf(`User: %s 239 | Target: %s 240 | StartTime: %s 241 | Client: %s 242 | Forwarded-For: %s 243 | `, p.user, p.Target, startTime, conn.RemoteAddr(), p.Forwarded)); err != nil { 244 | log.Fatal(err) 245 | } 246 | log.Printf("Downstream requested new channel of type %s", newChannel.ChannelType()) 247 | 248 | var wg sync.WaitGroup 249 | okReturn := make(chan bool) 250 | okWait := make(chan bool) 251 | go func() { 252 | <-okWait 253 | wg.Wait() 254 | okReturn <- true 255 | }() 256 | 257 | // Open channel with server. 258 | upstream, upstreamRequests, err := upstreamClient.Conn.OpenChannel(newChannel.ChannelType(), nil) 259 | if err != nil { 260 | newChannel.Reject(ssh.UnknownChannelType, "failed") 261 | return fmt.Errorf("upstream chan create failed: %v", err) 262 | } 263 | defer upstream.Close() 264 | 265 | downstream, downstreamRequests, err := newChannel.Accept() 266 | if err != nil { 267 | return fmt.Errorf("downstream: could not accept channel: %v", err) 268 | } 269 | defer downstream.Close() 270 | 271 | // Discard all requests from server. 272 | wg.Add(2) 273 | go requestForward(sourceUpstream, &wg, upstreamRequests, downstream) 274 | go requestForward(sourceDownstream, &wg, downstreamRequests, upstream) 275 | 276 | // downstream -> upstream. 277 | wg.Add(2) 278 | go p.dataForward(channelID, sourceDownstream, &wg, downstream, upstream) 279 | go p.dataForward(channelID, sourceUpstream, &wg, upstream, downstream) 280 | okWait <- true 281 | <-okReturn 282 | return nil 283 | } 284 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | --------------------------------------------------------------------------------