1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
17 "golang.org/x/crypto/ssh"
18 check "gopkg.in/check.v1"
21 func LoadTestKey(c *check.C, fnm string) (ssh.PublicKey, ssh.Signer) {
22 rawpubkey, err := ioutil.ReadFile(fnm + ".pub")
23 c.Assert(err, check.IsNil)
24 pubkey, _, _, _, err := ssh.ParseAuthorizedKey(rawpubkey)
25 c.Assert(err, check.IsNil)
26 rawprivkey, err := ioutil.ReadFile(fnm)
27 c.Assert(err, check.IsNil)
28 privkey, err := ssh.ParsePrivateKey(rawprivkey)
29 c.Assert(err, check.IsNil)
30 return pubkey, privkey
33 // An SSHExecFunc handles an "exec" session on a multiplexed SSH
35 type SSHExecFunc func(env map[string]string, command string, stdin io.Reader, stdout, stderr io.Writer) uint32
37 // An SSHService accepts SSH connections on an available TCP port and
38 // passes clients' "exec" sessions to the provided SSHExecFunc.
39 type SSHService struct {
43 AuthorizedKeys []ssh.PublicKey
54 // Address returns the host:port where the SSH server is listening. It
55 // returns "" if called before the server is ready to accept
57 func (ss *SSHService) Address() string {
65 return ln.Addr().String()
68 // RemoteUser returns the username that will be accepted.
69 func (ss *SSHService) RemoteUser() string {
70 return ss.AuthorizedUser
73 // Close shuts down the server and releases resources. Established
74 // connections are unaffected.
75 func (ss *SSHService) Close() {
86 // Start returns when the server is ready to accept connections.
87 func (ss *SSHService) Start() error {
93 func (ss *SSHService) start() {
94 ss.started = make(chan bool)
98 func (ss *SSHService) run() {
99 defer close(ss.started)
100 config := &ssh.ServerConfig{
101 PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
102 for _, ak := range ss.AuthorizedKeys {
103 if bytes.Equal(ak.Marshal(), pubKey.Marshal()) {
104 return &ssh.Permissions{}, nil
107 return nil, fmt.Errorf("unknown public key for %q", c.User())
110 config.AddHostKey(ss.HostKey)
112 listener, err := net.Listen("tcp", "127.0.0.1:")
119 ss.listener = listener
124 nConn, err := listener.Accept()
125 if err != nil && strings.Contains(err.Error(), "use of closed network connection") && ss.closed {
127 } else if err != nil {
128 log.Printf("accept: %s", err)
131 go ss.serveConn(nConn, config)
136 func (ss *SSHService) serveConn(nConn net.Conn, config *ssh.ServerConfig) {
138 conn, newchans, reqs, err := ssh.NewServerConn(nConn, config)
140 log.Printf("ssh.NewServerConn: %s", err)
144 go ssh.DiscardRequests(reqs)
145 for newch := range newchans {
146 if newch.ChannelType() != "session" {
147 newch.Reject(ssh.UnknownChannelType, "unknown channel type")
150 ch, reqs, err := newch.Accept()
152 log.Printf("accept channel: %s", err)
156 sessionEnv := map[string]string{}
158 for req := range reqs {
161 // Reject anything after exec
162 req.Reply(false, nil)
163 case req.Type == "exec":
168 ssh.Unmarshal(req.Payload, &execReq)
173 resp.Status = ss.Exec(sessionEnv, execReq.Command, ch, ch, ch.Stderr())
174 ch.SendRequest("exit-status", false, ssh.Marshal(&resp))
178 case req.Type == "env":
184 ssh.Unmarshal(req.Payload, &envReq)
185 sessionEnv[envReq.Name] = envReq.Value