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(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 {
42 AuthorizedKeys []ssh.PublicKey
53 // Address returns the host:port where the SSH server is listening. It
54 // returns "" if called before the server is ready to accept
56 func (ss *SSHService) Address() string {
64 return ln.Addr().String()
67 // Close shuts down the server and releases resources. Established
68 // connections are unaffected.
69 func (ss *SSHService) Close() {
80 // Start returns when the server is ready to accept connections.
81 func (ss *SSHService) Start() error {
87 func (ss *SSHService) start() {
88 ss.started = make(chan bool)
92 func (ss *SSHService) run() {
93 defer close(ss.started)
94 config := &ssh.ServerConfig{
95 PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
96 for _, ak := range ss.AuthorizedKeys {
97 if bytes.Equal(ak.Marshal(), pubKey.Marshal()) {
98 return &ssh.Permissions{}, nil
101 return nil, fmt.Errorf("unknown public key for %q", c.User())
104 config.AddHostKey(ss.HostKey)
106 listener, err := net.Listen("tcp", ":")
113 ss.listener = listener
118 nConn, err := listener.Accept()
119 if err != nil && strings.Contains(err.Error(), "use of closed network connection") && ss.closed {
121 } else if err != nil {
122 log.Printf("accept: %s", err)
125 go ss.serveConn(nConn, config)
130 func (ss *SSHService) serveConn(nConn net.Conn, config *ssh.ServerConfig) {
132 conn, newchans, reqs, err := ssh.NewServerConn(nConn, config)
134 log.Printf("ssh.NewServerConn: %s", err)
138 go ssh.DiscardRequests(reqs)
139 for newch := range newchans {
140 if newch.ChannelType() != "session" {
141 newch.Reject(ssh.UnknownChannelType, "unknown channel type")
144 ch, reqs, err := newch.Accept()
146 log.Printf("accept channel: %s", err)
153 for req := range reqs {
154 if req.Type == "exec" && execReq.Command == "" {
156 ssh.Unmarshal(req.Payload, &execReq)
161 resp.Status = ss.Exec(execReq.Command, ch, ch, ch.Stderr())
162 ch.SendRequest("exit-status", false, ssh.Marshal(&resp))