github.com/devops-filetransfer/sshego@v7.0.4+incompatible/_vendor/golang.org/x/crypto/ssh/common.go (about)

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package ssh
     6  
     7  import (
     8  	"crypto"
     9  	"crypto/rand"
    10  	"fmt"
    11  	"io"
    12  	"math"
    13  	"sync"
    14  
    15  	_ "crypto/sha1"
    16  	_ "crypto/sha256"
    17  	_ "crypto/sha512"
    18  )
    19  
    20  // These are string constants in the SSH protocol.
    21  const (
    22  	compressionNone = "none"
    23  	serviceUserAuth = "ssh-userauth"
    24  	serviceSSH      = "ssh-connection"
    25  )
    26  
    27  // supportedCiphers specifies the supported ciphers in preference order.
    28  var supportedCiphers = []string{
    29  	"aes128-ctr", "aes192-ctr", "aes256-ctr",
    30  	"aes128-gcm@openssh.com",
    31  	"arcfour256", "arcfour128",
    32  }
    33  
    34  // supportedKexAlgos specifies the supported key-exchange algorithms in
    35  // preference order.
    36  var supportedKexAlgos = []string{
    37  	kexAlgoCurve25519SHA256,
    38  	// P384 and P521 are not constant-time yet, but since we don't
    39  	// reuse ephemeral keys, using them for ECDH should be OK.
    40  	kexAlgoECDH256, kexAlgoECDH384, kexAlgoECDH521,
    41  	kexAlgoDH14SHA1, kexAlgoDH1SHA1,
    42  }
    43  
    44  // supportedHostKeyAlgos specifies the supported host-key algorithms (i.e. methods
    45  // of authenticating servers) in preference order.
    46  var supportedHostKeyAlgos = []string{
    47  	CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01,
    48  	CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01,
    49  
    50  	KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521,
    51  	KeyAlgoRSA, KeyAlgoDSA,
    52  
    53  	KeyAlgoED25519,
    54  }
    55  
    56  // supportedMACs specifies a default set of MAC algorithms in preference order.
    57  // This is based on RFC 4253, section 6.4, but with hmac-md5 variants removed
    58  // because they have reached the end of their useful life.
    59  var supportedMACs = []string{
    60  	"hmac-sha2-256-etm@openssh.com", "hmac-sha2-256", "hmac-sha1", "hmac-sha1-96",
    61  }
    62  
    63  var supportedCompressions = []string{compressionNone}
    64  
    65  // hashFuncs keeps the mapping of supported algorithms to their respective
    66  // hashes needed for signature verification.
    67  var hashFuncs = map[string]crypto.Hash{
    68  	KeyAlgoRSA:          crypto.SHA1,
    69  	KeyAlgoDSA:          crypto.SHA1,
    70  	KeyAlgoECDSA256:     crypto.SHA256,
    71  	KeyAlgoECDSA384:     crypto.SHA384,
    72  	KeyAlgoECDSA521:     crypto.SHA512,
    73  	CertAlgoRSAv01:      crypto.SHA1,
    74  	CertAlgoDSAv01:      crypto.SHA1,
    75  	CertAlgoECDSA256v01: crypto.SHA256,
    76  	CertAlgoECDSA384v01: crypto.SHA384,
    77  	CertAlgoECDSA521v01: crypto.SHA512,
    78  }
    79  
    80  // unexpectedMessageError results when the SSH message that we received didn't
    81  // match what we wanted.
    82  func unexpectedMessageError(expected, got uint8) error {
    83  	return fmt.Errorf("ssh: unexpected message type %d (expected %d)", got, expected)
    84  }
    85  
    86  // parseError results from a malformed SSH message.
    87  func parseError(tag uint8) error {
    88  	return fmt.Errorf("ssh: parse error in message type %d", tag)
    89  }
    90  
    91  func findCommon(what string, client []string, server []string) (common string, err error) {
    92  	for _, c := range client {
    93  		for _, s := range server {
    94  			if c == s {
    95  				return c, nil
    96  			}
    97  		}
    98  	}
    99  	return "", fmt.Errorf("ssh: no common algorithm for %s; client offered: %v, server offered: %v", what, client, server)
   100  }
   101  
   102  type directionAlgorithms struct {
   103  	Cipher      string
   104  	MAC         string
   105  	Compression string
   106  }
   107  
   108  // rekeyBytes returns a rekeying intervals in bytes.
   109  func (a *directionAlgorithms) rekeyBytes() int64 {
   110  	// According to RFC4344 block ciphers should rekey after
   111  	// 2^(BLOCKSIZE/4) blocks. For all AES flavors BLOCKSIZE is
   112  	// 128.
   113  	switch a.Cipher {
   114  	case "aes128-ctr", "aes192-ctr", "aes256-ctr", gcmCipherID, aes128cbcID:
   115  		return 16 * (1 << 32)
   116  
   117  	}
   118  
   119  	// For others, stick with RFC4253 recommendation to rekey after 1 Gb of data.
   120  	return 1 << 30
   121  }
   122  
   123  type algorithms struct {
   124  	kex     string
   125  	hostKey string
   126  	w       directionAlgorithms
   127  	r       directionAlgorithms
   128  }
   129  
   130  func findAgreedAlgorithms(clientKexInit, serverKexInit *kexInitMsg) (algs *algorithms, err error) {
   131  	result := &algorithms{}
   132  
   133  	result.kex, err = findCommon("key exchange", clientKexInit.KexAlgos, serverKexInit.KexAlgos)
   134  	if err != nil {
   135  		return
   136  	}
   137  
   138  	result.hostKey, err = findCommon("host key", clientKexInit.ServerHostKeyAlgos, serverKexInit.ServerHostKeyAlgos)
   139  	if err != nil {
   140  		return
   141  	}
   142  
   143  	result.w.Cipher, err = findCommon("client to server cipher", clientKexInit.CiphersClientServer, serverKexInit.CiphersClientServer)
   144  	if err != nil {
   145  		return
   146  	}
   147  
   148  	result.r.Cipher, err = findCommon("server to client cipher", clientKexInit.CiphersServerClient, serverKexInit.CiphersServerClient)
   149  	if err != nil {
   150  		return
   151  	}
   152  
   153  	result.w.MAC, err = findCommon("client to server MAC", clientKexInit.MACsClientServer, serverKexInit.MACsClientServer)
   154  	if err != nil {
   155  		return
   156  	}
   157  
   158  	result.r.MAC, err = findCommon("server to client MAC", clientKexInit.MACsServerClient, serverKexInit.MACsServerClient)
   159  	if err != nil {
   160  		return
   161  	}
   162  
   163  	result.w.Compression, err = findCommon("client to server compression", clientKexInit.CompressionClientServer, serverKexInit.CompressionClientServer)
   164  	if err != nil {
   165  		return
   166  	}
   167  
   168  	result.r.Compression, err = findCommon("server to client compression", clientKexInit.CompressionServerClient, serverKexInit.CompressionServerClient)
   169  	if err != nil {
   170  		return
   171  	}
   172  
   173  	return result, nil
   174  }
   175  
   176  // If rekeythreshold is too small, we can't make any progress sending
   177  // stuff.
   178  const minRekeyThreshold uint64 = 256
   179  
   180  // Config contains configuration data common to both ServerConfig and
   181  // ClientConfig.
   182  type Config struct {
   183  	// Rand provides the source of entropy for cryptographic
   184  	// primitives. If Rand is nil, the cryptographic random reader
   185  	// in package crypto/rand will be used.
   186  	Rand io.Reader
   187  
   188  	// The maximum number of bytes sent or received after which a
   189  	// new key is negotiated. It must be at least 256. If
   190  	// unspecified, a size suitable for the chosen cipher is used.
   191  	RekeyThreshold uint64
   192  
   193  	// The allowed key exchanges algorithms. If unspecified then a
   194  	// default set of algorithms is used.
   195  	KeyExchanges []string
   196  
   197  	// The allowed cipher algorithms. If unspecified then a sensible
   198  	// default is used.
   199  	Ciphers []string
   200  
   201  	// The allowed MAC algorithms. If unspecified then a sensible default
   202  	// is used.
   203  	MACs []string
   204  }
   205  
   206  // SetDefaults sets sensible values for unset fields in config. This is
   207  // exported for testing: Configs passed to SSH functions are copied and have
   208  // default values set automatically.
   209  func (c *Config) SetDefaults() {
   210  	if c.Rand == nil {
   211  		c.Rand = rand.Reader
   212  	}
   213  	if c.Ciphers == nil {
   214  		c.Ciphers = supportedCiphers
   215  	}
   216  	var ciphers []string
   217  	for _, c := range c.Ciphers {
   218  		if cipherModes[c] != nil {
   219  			// reject the cipher if we have no cipherModes definition
   220  			ciphers = append(ciphers, c)
   221  		}
   222  	}
   223  	c.Ciphers = ciphers
   224  
   225  	if c.KeyExchanges == nil {
   226  		c.KeyExchanges = supportedKexAlgos
   227  	}
   228  
   229  	if c.MACs == nil {
   230  		c.MACs = supportedMACs
   231  	}
   232  
   233  	if c.RekeyThreshold == 0 {
   234  		// cipher specific default
   235  	} else if c.RekeyThreshold < minRekeyThreshold {
   236  		c.RekeyThreshold = minRekeyThreshold
   237  	} else if c.RekeyThreshold >= math.MaxInt64 {
   238  		// Avoid weirdness if somebody uses -1 as a threshold.
   239  		c.RekeyThreshold = math.MaxInt64
   240  	}
   241  }
   242  
   243  // buildDataSignedForAuth returns the data that is signed in order to prove
   244  // possession of a private key. See RFC 4252, section 7.
   245  func buildDataSignedForAuth(sessionId []byte, req userAuthRequestMsg, algo, pubKey []byte) []byte {
   246  	data := struct {
   247  		Session []byte
   248  		Type    byte
   249  		User    string
   250  		Service string
   251  		Method  string
   252  		Sign    bool
   253  		Algo    []byte
   254  		PubKey  []byte
   255  	}{
   256  		sessionId,
   257  		msgUserAuthRequest,
   258  		req.User,
   259  		req.Service,
   260  		req.Method,
   261  		true,
   262  		algo,
   263  		pubKey,
   264  	}
   265  	return Marshal(data)
   266  }
   267  
   268  func appendU16(buf []byte, n uint16) []byte {
   269  	return append(buf, byte(n>>8), byte(n))
   270  }
   271  
   272  func appendU32(buf []byte, n uint32) []byte {
   273  	return append(buf, byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
   274  }
   275  
   276  func appendU64(buf []byte, n uint64) []byte {
   277  	return append(buf,
   278  		byte(n>>56), byte(n>>48), byte(n>>40), byte(n>>32),
   279  		byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
   280  }
   281  
   282  func appendInt(buf []byte, n int) []byte {
   283  	return appendU32(buf, uint32(n))
   284  }
   285  
   286  func appendString(buf []byte, s string) []byte {
   287  	buf = appendU32(buf, uint32(len(s)))
   288  	buf = append(buf, s...)
   289  	return buf
   290  }
   291  
   292  func appendBool(buf []byte, b bool) []byte {
   293  	if b {
   294  		return append(buf, 1)
   295  	}
   296  	return append(buf, 0)
   297  }
   298  
   299  // newCond is a helper to hide the fact that there is no usable zero
   300  // value for sync.Cond.
   301  func newCond() *sync.Cond { return sync.NewCond(new(sync.Mutex)) }
   302  
   303  // window represents the buffer available to clients
   304  // wishing to write to a channel.
   305  type window struct {
   306  	*sync.Cond
   307  	win          uint32 // RFC 4254 5.2 says the window size can grow to 2^32-1
   308  	writeWaiters int
   309  	closed       bool
   310  }
   311  
   312  // add adds win to the amount of window available
   313  // for consumers.
   314  func (w *window) add(win uint32) bool {
   315  	// a zero sized window adjust is a noop.
   316  	if win == 0 {
   317  		return true
   318  	}
   319  	w.L.Lock()
   320  	if w.win+win < win {
   321  		w.L.Unlock()
   322  		return false
   323  	}
   324  	w.win += win
   325  	// It is unusual that multiple goroutines would be attempting to reserve
   326  	// window space, but not guaranteed. Use broadcast to notify all waiters
   327  	// that additional window is available.
   328  	w.Broadcast()
   329  	w.L.Unlock()
   330  	return true
   331  }
   332  
   333  // close sets the window to closed, so all reservations fail
   334  // immediately.
   335  func (w *window) close() {
   336  	w.L.Lock()
   337  	w.closed = true
   338  	w.Broadcast()
   339  	w.L.Unlock()
   340  }
   341  
   342  // reserve reserves win from the available window capacity.
   343  // If no capacity remains, reserve will block. reserve may
   344  // return less than requested.
   345  func (w *window) reserve(win uint32) (uint32, error) {
   346  	var err error
   347  	w.L.Lock()
   348  	w.writeWaiters++
   349  	w.Broadcast()
   350  	for w.win == 0 && !w.closed {
   351  		w.Wait()
   352  	}
   353  	w.writeWaiters--
   354  	if w.win < win {
   355  		win = w.win
   356  	}
   357  	w.win -= win
   358  	if w.closed {
   359  		err = io.EOF
   360  	}
   361  	w.L.Unlock()
   362  	return win, err
   363  }
   364  
   365  // waitWriterBlocked waits until some goroutine is blocked for further
   366  // writes. It is used in tests only.
   367  func (w *window) waitWriterBlocked() {
   368  	w.Cond.L.Lock()
   369  	for w.writeWaiters == 0 {
   370  		w.Cond.Wait()
   371  	}
   372  	w.Cond.L.Unlock()
   373  }