github.com/coreos/mantle@v0.13.0/network/mockssh/mockssh.go (about)

     1  // Copyright 2017 CoreOS, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // mockssh implements a basic ssh server for use in unit tests.
    16  //
    17  // Command execution in the server is implemented by a user provided handler
    18  // function rather than executing a real shell.
    19  //
    20  // Some inspiration is taken from but not based on:
    21  // https://godoc.org/github.com/gliderlabs/ssh
    22  package mockssh
    23  
    24  import (
    25  	"fmt"
    26  	"io"
    27  	"log"
    28  	"net"
    29  
    30  	"golang.org/x/crypto/ssh"
    31  
    32  	"github.com/coreos/mantle/network/bufnet"
    33  )
    34  
    35  const (
    36  	pipeBufferSize = 8192
    37  )
    38  
    39  var (
    40  	mockServerPrivateKey ssh.Signer
    41  )
    42  
    43  func init() {
    44  	var err error
    45  	mockServerPrivateKey, err = ssh.ParsePrivateKey([]byte(`
    46  -----BEGIN RSA PRIVATE KEY-----
    47  MIICXgIBAAKBgQC+6EsrBSr0Ik+ADcR17zjYK9+RcO+AYFA6IN/wYl0lV8Os/Md8
    48  amVUnC3FGhvK4hQwvQVEQpoxcT4DoHZh6Fs4uStixFZSCWLGbYwb8qsRkMJl/ZkZ
    49  kgY/ZUOQSHqoNsIkVajoVPOK8gb9pFcDW0WHcIDHa6L+IoZH7nfUmG5/9QIDAQAB
    50  AoGBALxhwPr8qHwr90MnUrwFiZRXBtAgH1YQtFoH4rL0fXHB/wcOkVMGMmOhkdCz
    51  iMVU/hNyEmZfSoSLeGRfzTGj9Y541nfcbFcCwpen8mfLk4JyVsHr1J9T/c0i9yot
    52  NtZFU6Imsw6judu4ohzLrI6hYdvSTUzJvrUe4jKQ8uv/O4JBAkEA6ON3ZnxlwtvC
    53  rcTBes/8bHLjrvQk371HraRH9xN29XSII11igPYDGRsrO8+5fTcVi/gYI6GIo/pU
    54  amRoMgwm7QJBANHaS9VJwSWHyfO5AjNHzOQM7M5SUf9KVTUdgCXi+H0cBPZdlZaF
    55  FviXHnH114tiSlKDmwJicrmWW0Pk0c1A1CkCQGoWZGe9NyXisfYycOifIh/M3kbu
    56  VHXPZX2GHnpA1anOoc1qVtrkNlkTdUhTwe12UExogaaJiRMZj6a/gm959akCQQCo
    57  KXsdRsYNMhwmPzpBJ6dLlAPrbdIhdkqDjslTEue3Mc3UMrgdbzcyK78M6Uk5e6E9
    58  MBL2PTfb+l3WMTXiebHJAkEApUjV9xL1i+7EidI3hOgTZxk5Ti6eXpZdjQIN3OGn
    59  uCeD0x31tIEl6p5wYaspSAOZJh8/jz4qMbLOUjmhRUzIJg==
    60  -----END RSA PRIVATE KEY-----
    61  `))
    62  	if err != nil {
    63  		panic(err)
    64  	}
    65  }
    66  
    67  // SessionHandler is a user provided function that processes/executes
    68  // the command given to it in the given Session. Before finishing the
    69  // handler must call session.Close or session.Exit.
    70  type SessionHandler func(session *Session)
    71  
    72  // Session represents the server side execution of the client's ssh.Session.
    73  type Session struct {
    74  	Exec   string   // Command to execute.
    75  	Env    []string // Environment values provided by the client.
    76  	Stdin  io.Reader
    77  	Stdout io.Writer
    78  	Stderr io.Writer
    79  
    80  	channel ssh.Channel
    81  }
    82  
    83  // Exit sends the given command exit status and closes the session.
    84  func (s *Session) Exit(code int) error {
    85  	status := struct{ Status uint32 }{uint32(code)}
    86  	payload := ssh.Marshal(&status)
    87  
    88  	_, err := s.channel.SendRequest("exit-status", false, payload)
    89  	if err != nil {
    90  		return err
    91  	}
    92  
    93  	return s.channel.Close()
    94  }
    95  
    96  // Close ends the session without sending an exit status.
    97  func (s *Session) Close() error {
    98  	return s.channel.Close()
    99  }
   100  
   101  // NewMockClient starts a ssh server backed by the given handler and
   102  // returns a client that is connected to it.
   103  func NewMockClient(handler SessionHandler) *ssh.Client {
   104  	config := ssh.ClientConfig{
   105  		User: "mock",
   106  		Auth: []ssh.AuthMethod{
   107  			ssh.Password(""),
   108  		},
   109  	}
   110  
   111  	pipe := startMockServer(handler)
   112  	conn, chans, reqs, err := ssh.NewClientConn(pipe, "mock", &config)
   113  	if err != nil {
   114  		panic(err)
   115  	}
   116  
   117  	return ssh.NewClient(conn, chans, reqs)
   118  }
   119  
   120  type mockServer struct {
   121  	config  ssh.ServerConfig
   122  	handler SessionHandler
   123  	server  *ssh.ServerConn
   124  }
   125  
   126  func startMockServer(handler SessionHandler) net.Conn {
   127  	m := mockServer{
   128  		config: ssh.ServerConfig{
   129  			PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
   130  				return nil, nil
   131  			},
   132  		},
   133  		handler: handler,
   134  	}
   135  	m.config.AddHostKey(mockServerPrivateKey)
   136  
   137  	sPipe, cPipe := bufnet.FixedPipe(pipeBufferSize)
   138  	go m.handleServerConn(sPipe)
   139  	return cPipe
   140  }
   141  
   142  func (m *mockServer) handleServerConn(conn net.Conn) {
   143  	serverConn, chans, reqs, err := ssh.NewServerConn(conn, &m.config)
   144  	if err != nil {
   145  		log.Printf("mockssh: server handshake failed: %v", err)
   146  		return
   147  	}
   148  	m.server = serverConn
   149  
   150  	// reqs must be serviced but are not important to us.
   151  	go ssh.DiscardRequests(reqs)
   152  
   153  	for newChannel := range chans {
   154  		go m.handleServerChannel(newChannel)
   155  	}
   156  }
   157  
   158  func (m *mockServer) handleServerChannel(newChannel ssh.NewChannel) {
   159  	if newChannel.ChannelType() != "session" {
   160  		newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
   161  		return
   162  	}
   163  
   164  	channel, requests, err := newChannel.Accept()
   165  	if err != nil {
   166  		log.Printf("mockssh: accepting channel failed: %v", err)
   167  		return
   168  	}
   169  
   170  	session := &Session{
   171  		Stdin:   channel,
   172  		Stdout:  channel,
   173  		Stderr:  channel.Stderr(),
   174  		channel: channel,
   175  	}
   176  
   177  	// shell and pty requests are not implemented.
   178  	for req := range requests {
   179  		if session == nil {
   180  			req.Reply(false, nil)
   181  		}
   182  		switch req.Type {
   183  		case "exec":
   184  			v := struct{ Value string }{}
   185  			if err := ssh.Unmarshal(req.Payload, &v); err != nil {
   186  				req.Reply(false, nil)
   187  			} else {
   188  				session.Exec = v.Value
   189  				req.Reply(true, nil)
   190  				go m.handler(session)
   191  			}
   192  			session = nil
   193  		case "env":
   194  			kv := struct{ Key, Value string }{}
   195  			if err := ssh.Unmarshal(req.Payload, &kv); err != nil {
   196  				req.Reply(false, nil)
   197  			} else {
   198  				env := fmt.Sprintf("%s=%s", kv.Key, kv.Value)
   199  				session.Env = append(session.Env, env)
   200  				req.Reply(true, nil)
   201  			}
   202  		default:
   203  			req.Reply(false, nil)
   204  		}
   205  	}
   206  }