// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ssh

import (
	
	
	
	
	
	
	

	_ 
	_ 
	_ 
)

// These are string constants in the SSH protocol.
const (
	compressionNone = "none"
	serviceUserAuth = "ssh-userauth"
	serviceSSH      = "ssh-connection"
)

// supportedCiphers lists ciphers we support but might not recommend.
var supportedCiphers = []string{
	"aes128-ctr", "aes192-ctr", "aes256-ctr",
	"aes128-gcm@openssh.com", gcm256CipherID,
	chacha20Poly1305ID,
	"arcfour256", "arcfour128", "arcfour",
	aes128cbcID,
	tripledescbcID,
}

// preferredCiphers specifies the default preference for ciphers.
var preferredCiphers = []string{
	"aes128-gcm@openssh.com", gcm256CipherID,
	chacha20Poly1305ID,
	"aes128-ctr", "aes192-ctr", "aes256-ctr",
}

// supportedKexAlgos specifies the supported key-exchange algorithms in
// preference order.
var supportedKexAlgos = []string{
	kexAlgoCurve25519SHA256, kexAlgoCurve25519SHA256LibSSH,
	// P384 and P521 are not constant-time yet, but since we don't
	// reuse ephemeral keys, using them for ECDH should be OK.
	kexAlgoECDH256, kexAlgoECDH384, kexAlgoECDH521,
	kexAlgoDH14SHA256, kexAlgoDH16SHA512, kexAlgoDH14SHA1,
	kexAlgoDH1SHA1,
}

// serverForbiddenKexAlgos contains key exchange algorithms, that are forbidden
// for the server half.
var serverForbiddenKexAlgos = map[string]struct{}{
	kexAlgoDHGEXSHA1:   {}, // server half implementation is only minimal to satisfy the automated tests
	kexAlgoDHGEXSHA256: {}, // server half implementation is only minimal to satisfy the automated tests
}

// preferredKexAlgos specifies the default preference for key-exchange
// algorithms in preference order. The diffie-hellman-group16-sha512 algorithm
// is disabled by default because it is a bit slower than the others.
var preferredKexAlgos = []string{
	kexAlgoCurve25519SHA256, kexAlgoCurve25519SHA256LibSSH,
	kexAlgoECDH256, kexAlgoECDH384, kexAlgoECDH521,
	kexAlgoDH14SHA256, kexAlgoDH14SHA1,
}

// supportedHostKeyAlgos specifies the supported host-key algorithms (i.e. methods
// of authenticating servers) in preference order.
var supportedHostKeyAlgos = []string{
	CertAlgoRSASHA256v01, CertAlgoRSASHA512v01,
	CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01,
	CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01,

	KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521,
	KeyAlgoRSASHA256, KeyAlgoRSASHA512,
	KeyAlgoRSA, KeyAlgoDSA,

	KeyAlgoED25519,
}

// supportedMACs specifies a default set of MAC algorithms in preference order.
// This is based on RFC 4253, section 6.4, but with hmac-md5 variants removed
// because they have reached the end of their useful life.
var supportedMACs = []string{
	"hmac-sha2-256-etm@openssh.com", "hmac-sha2-512-etm@openssh.com", "hmac-sha2-256", "hmac-sha2-512", "hmac-sha1", "hmac-sha1-96",
}

var supportedCompressions = []string{compressionNone}

// hashFuncs keeps the mapping of supported signature algorithms to their
// respective hashes needed for signing and verification.
var hashFuncs = map[string]crypto.Hash{
	KeyAlgoRSA:       crypto.SHA1,
	KeyAlgoRSASHA256: crypto.SHA256,
	KeyAlgoRSASHA512: crypto.SHA512,
	KeyAlgoDSA:       crypto.SHA1,
	KeyAlgoECDSA256:  crypto.SHA256,
	KeyAlgoECDSA384:  crypto.SHA384,
	KeyAlgoECDSA521:  crypto.SHA512,
	// KeyAlgoED25519 doesn't pre-hash.
	KeyAlgoSKECDSA256: crypto.SHA256,
	KeyAlgoSKED25519:  crypto.SHA256,
}

// algorithmsForKeyFormat returns the supported signature algorithms for a given
// public key format (PublicKey.Type), in order of preference. See RFC 8332,
// Section 2. See also the note in sendKexInit on backwards compatibility.
func algorithmsForKeyFormat( string) []string {
	switch  {
	case KeyAlgoRSA:
		return []string{KeyAlgoRSASHA256, KeyAlgoRSASHA512, KeyAlgoRSA}
	case CertAlgoRSAv01:
		return []string{CertAlgoRSASHA256v01, CertAlgoRSASHA512v01, CertAlgoRSAv01}
	default:
		return []string{}
	}
}

// isRSA returns whether algo is a supported RSA algorithm, including certificate
// algorithms.
func isRSA( string) bool {
	 := algorithmsForKeyFormat(KeyAlgoRSA)
	return contains(, underlyingAlgo())
}

// supportedPubKeyAuthAlgos specifies the supported client public key
// authentication algorithms. Note that this doesn't include certificate types
// since those use the underlying algorithm. This list is sent to the client if
// it supports the server-sig-algs extension. Order is irrelevant.
var supportedPubKeyAuthAlgos = []string{
	KeyAlgoED25519,
	KeyAlgoSKED25519, KeyAlgoSKECDSA256,
	KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521,
	KeyAlgoRSASHA256, KeyAlgoRSASHA512, KeyAlgoRSA,
	KeyAlgoDSA,
}

var supportedPubKeyAuthAlgosList = strings.Join(supportedPubKeyAuthAlgos, ",")

// unexpectedMessageError results when the SSH message that we received didn't
// match what we wanted.
func unexpectedMessageError(,  uint8) error {
	return fmt.Errorf("ssh: unexpected message type %d (expected %d)", , )
}

// parseError results from a malformed SSH message.
func parseError( uint8) error {
	return fmt.Errorf("ssh: parse error in message type %d", )
}

func findCommon( string,  []string,  []string) ( string,  error) {
	for ,  := range  {
		for ,  := range  {
			if  ==  {
				return , nil
			}
		}
	}
	return "", fmt.Errorf("ssh: no common algorithm for %s; client offered: %v, server offered: %v", , , )
}

// directionAlgorithms records algorithm choices in one direction (either read or write)
type directionAlgorithms struct {
	Cipher      string
	MAC         string
	Compression string
}

// rekeyBytes returns a rekeying intervals in bytes.
func ( *directionAlgorithms) () int64 {
	// According to RFC 4344 block ciphers should rekey after
	// 2^(BLOCKSIZE/4) blocks. For all AES flavors BLOCKSIZE is
	// 128.
	switch .Cipher {
	case "aes128-ctr", "aes192-ctr", "aes256-ctr", gcm128CipherID, gcm256CipherID, aes128cbcID:
		return 16 * (1 << 32)

	}

	// For others, stick with RFC 4253 recommendation to rekey after 1 Gb of data.
	return 1 << 30
}

var aeadCiphers = map[string]bool{
	gcm128CipherID:     true,
	gcm256CipherID:     true,
	chacha20Poly1305ID: true,
}

type algorithms struct {
	kex     string
	hostKey string
	w       directionAlgorithms
	r       directionAlgorithms
}

func findAgreedAlgorithms( bool, ,  *kexInitMsg) ( *algorithms,  error) {
	 := &algorithms{}

	.kex,  = findCommon("key exchange", .KexAlgos, .KexAlgos)
	if  != nil {
		return
	}

	.hostKey,  = findCommon("host key", .ServerHostKeyAlgos, .ServerHostKeyAlgos)
	if  != nil {
		return
	}

	,  := &.w, &.r
	if  {
		,  = , 
	}

	.Cipher,  = findCommon("client to server cipher", .CiphersClientServer, .CiphersClientServer)
	if  != nil {
		return
	}

	.Cipher,  = findCommon("server to client cipher", .CiphersServerClient, .CiphersServerClient)
	if  != nil {
		return
	}

	if !aeadCiphers[.Cipher] {
		.MAC,  = findCommon("client to server MAC", .MACsClientServer, .MACsClientServer)
		if  != nil {
			return
		}
	}

	if !aeadCiphers[.Cipher] {
		.MAC,  = findCommon("server to client MAC", .MACsServerClient, .MACsServerClient)
		if  != nil {
			return
		}
	}

	.Compression,  = findCommon("client to server compression", .CompressionClientServer, .CompressionClientServer)
	if  != nil {
		return
	}

	.Compression,  = findCommon("server to client compression", .CompressionServerClient, .CompressionServerClient)
	if  != nil {
		return
	}

	return , nil
}

// If rekeythreshold is too small, we can't make any progress sending
// stuff.
const minRekeyThreshold uint64 = 256

// Config contains configuration data common to both ServerConfig and
// ClientConfig.
type Config struct {
	// Rand provides the source of entropy for cryptographic
	// primitives. If Rand is nil, the cryptographic random reader
	// in package crypto/rand will be used.
	Rand io.Reader

	// The maximum number of bytes sent or received after which a
	// new key is negotiated. It must be at least 256. If
	// unspecified, a size suitable for the chosen cipher is used.
	RekeyThreshold uint64

	// The allowed key exchanges algorithms. If unspecified then a default set
	// of algorithms is used. Unsupported values are silently ignored.
	KeyExchanges []string

	// The allowed cipher algorithms. If unspecified then a sensible default is
	// used. Unsupported values are silently ignored.
	Ciphers []string

	// The allowed MAC algorithms. If unspecified then a sensible default is
	// used. Unsupported values are silently ignored.
	MACs []string
}

// SetDefaults sets sensible values for unset fields in config. This is
// exported for testing: Configs passed to SSH functions are copied and have
// default values set automatically.
func ( *Config) () {
	if .Rand == nil {
		.Rand = rand.Reader
	}
	if .Ciphers == nil {
		.Ciphers = preferredCiphers
	}
	var  []string
	for ,  := range .Ciphers {
		if cipherModes[] != nil {
			// Ignore the cipher if we have no cipherModes definition.
			 = append(, )
		}
	}
	.Ciphers = 

	if .KeyExchanges == nil {
		.KeyExchanges = preferredKexAlgos
	}
	var  []string
	for ,  := range .KeyExchanges {
		if kexAlgoMap[] != nil {
			// Ignore the KEX if we have no kexAlgoMap definition.
			 = append(, )
		}
	}
	.KeyExchanges = 

	if .MACs == nil {
		.MACs = supportedMACs
	}
	var  []string
	for ,  := range .MACs {
		if macModes[] != nil {
			// Ignore the MAC if we have no macModes definition.
			 = append(, )
		}
	}
	.MACs = 

	if .RekeyThreshold == 0 {
		// cipher specific default
	} else if .RekeyThreshold < minRekeyThreshold {
		.RekeyThreshold = minRekeyThreshold
	} else if .RekeyThreshold >= math.MaxInt64 {
		// Avoid weirdness if somebody uses -1 as a threshold.
		.RekeyThreshold = math.MaxInt64
	}
}

// buildDataSignedForAuth returns the data that is signed in order to prove
// possession of a private key. See RFC 4252, section 7. algo is the advertised
// algorithm, and may be a certificate type.
func buildDataSignedForAuth( []byte,  userAuthRequestMsg,  string,  []byte) []byte {
	 := struct {
		 []byte
		    byte
		    string
		 string
		  string
		    bool
		    string
		  []byte
	}{
		,
		msgUserAuthRequest,
		.User,
		.Service,
		.Method,
		true,
		,
		,
	}
	return Marshal()
}

func appendU16( []byte,  uint16) []byte {
	return append(, byte(>>8), byte())
}

func appendU32( []byte,  uint32) []byte {
	return append(, byte(>>24), byte(>>16), byte(>>8), byte())
}

func appendU64( []byte,  uint64) []byte {
	return append(,
		byte(>>56), byte(>>48), byte(>>40), byte(>>32),
		byte(>>24), byte(>>16), byte(>>8), byte())
}

func appendInt( []byte,  int) []byte {
	return appendU32(, uint32())
}

func appendString( []byte,  string) []byte {
	 = appendU32(, uint32(len()))
	 = append(, ...)
	return 
}

func appendBool( []byte,  bool) []byte {
	if  {
		return append(, 1)
	}
	return append(, 0)
}

// newCond is a helper to hide the fact that there is no usable zero
// value for sync.Cond.
func newCond() *sync.Cond { return sync.NewCond(new(sync.Mutex)) }

// window represents the buffer available to clients
// wishing to write to a channel.
type window struct {
	*sync.Cond
	win          uint32 // RFC 4254 5.2 says the window size can grow to 2^32-1
	writeWaiters int
	closed       bool
}

// add adds win to the amount of window available
// for consumers.
func ( *window) ( uint32) bool {
	// a zero sized window adjust is a noop.
	if  == 0 {
		return true
	}
	.L.Lock()
	if .win+ <  {
		.L.Unlock()
		return false
	}
	.win += 
	// It is unusual that multiple goroutines would be attempting to reserve
	// window space, but not guaranteed. Use broadcast to notify all waiters
	// that additional window is available.
	.Broadcast()
	.L.Unlock()
	return true
}

// close sets the window to closed, so all reservations fail
// immediately.
func ( *window) () {
	.L.Lock()
	.closed = true
	.Broadcast()
	.L.Unlock()
}

// reserve reserves win from the available window capacity.
// If no capacity remains, reserve will block. reserve may
// return less than requested.
func ( *window) ( uint32) (uint32, error) {
	var  error
	.L.Lock()
	.writeWaiters++
	.Broadcast()
	for .win == 0 && !.closed {
		.Wait()
	}
	.writeWaiters--
	if .win <  {
		 = .win
	}
	.win -= 
	if .closed {
		 = io.EOF
	}
	.L.Unlock()
	return , 
}

// waitWriterBlocked waits until some goroutine is blocked for further
// writes. It is used in tests only.
func ( *window) () {
	.Cond.L.Lock()
	for .writeWaiters == 0 {
		.Cond.Wait()
	}
	.Cond.L.Unlock()
}