// 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"
)

// The ciphers currently or previously implemented by this library, to use in
// [Config.Ciphers]. For a list, see the [Algorithms.Ciphers] returned by
// [SupportedAlgorithms] or [InsecureAlgorithms].
const (
	CipherAES128GCM            = "aes128-gcm@openssh.com"
	CipherAES256GCM            = "aes256-gcm@openssh.com"
	CipherChaCha20Poly1305     = "chacha20-poly1305@openssh.com"
	CipherAES128CTR            = "aes128-ctr"
	CipherAES192CTR            = "aes192-ctr"
	CipherAES256CTR            = "aes256-ctr"
	InsecureCipherAES128CBC    = "aes128-cbc"
	InsecureCipherTripleDESCBC = "3des-cbc"
	InsecureCipherRC4          = "arcfour"
	InsecureCipherRC4128       = "arcfour128"
	InsecureCipherRC4256       = "arcfour256"
)

// The key exchanges currently or previously implemented by this library, to use
// in [Config.KeyExchanges]. For a list, see the
// [Algorithms.KeyExchanges] returned by [SupportedAlgorithms] or
// [InsecureAlgorithms].
const (
	InsecureKeyExchangeDH1SHA1   = "diffie-hellman-group1-sha1"
	InsecureKeyExchangeDH14SHA1  = "diffie-hellman-group14-sha1"
	KeyExchangeDH14SHA256        = "diffie-hellman-group14-sha256"
	KeyExchangeDH16SHA512        = "diffie-hellman-group16-sha512"
	KeyExchangeECDHP256          = "ecdh-sha2-nistp256"
	KeyExchangeECDHP384          = "ecdh-sha2-nistp384"
	KeyExchangeECDHP521          = "ecdh-sha2-nistp521"
	KeyExchangeCurve25519        = "curve25519-sha256"
	InsecureKeyExchangeDHGEXSHA1 = "diffie-hellman-group-exchange-sha1"
	KeyExchangeDHGEXSHA256       = "diffie-hellman-group-exchange-sha256"
	// KeyExchangeMLKEM768X25519 is supported from Go 1.24.
	KeyExchangeMLKEM768X25519 = "mlkem768x25519-sha256"

	// An alias for KeyExchangeCurve25519SHA256. This kex ID will be added if
	// KeyExchangeCurve25519SHA256 is requested for backward compatibility with
	// OpenSSH versions up to 7.2.
	keyExchangeCurve25519LibSSH = "curve25519-sha256@libssh.org"
)

// The message authentication code (MAC) currently or previously implemented by
// this library, to use in [Config.MACs]. For a list, see the
// [Algorithms.MACs] returned by [SupportedAlgorithms] or
// [InsecureAlgorithms].
const (
	HMACSHA256ETM      = "hmac-sha2-256-etm@openssh.com"
	HMACSHA512ETM      = "hmac-sha2-512-etm@openssh.com"
	HMACSHA256         = "hmac-sha2-256"
	HMACSHA512         = "hmac-sha2-512"
	HMACSHA1           = "hmac-sha1"
	InsecureHMACSHA196 = "hmac-sha1-96"
)

var (
	// supportedKexAlgos specifies key-exchange algorithms implemented by this
	// package in preference order, excluding those with security issues.
	supportedKexAlgos = []string{
		KeyExchangeMLKEM768X25519,
		KeyExchangeCurve25519,
		KeyExchangeECDHP256,
		KeyExchangeECDHP384,
		KeyExchangeECDHP521,
		KeyExchangeDH14SHA256,
		KeyExchangeDH16SHA512,
		KeyExchangeDHGEXSHA256,
	}
	// defaultKexAlgos specifies the default preference for key-exchange
	// algorithms in preference order.
	defaultKexAlgos = []string{
		KeyExchangeMLKEM768X25519,
		KeyExchangeCurve25519,
		KeyExchangeECDHP256,
		KeyExchangeECDHP384,
		KeyExchangeECDHP521,
		KeyExchangeDH14SHA256,
		InsecureKeyExchangeDH14SHA1,
	}
	// insecureKexAlgos specifies key-exchange algorithms implemented by this
	// package and which have security issues.
	insecureKexAlgos = []string{
		InsecureKeyExchangeDH14SHA1,
		InsecureKeyExchangeDH1SHA1,
		InsecureKeyExchangeDHGEXSHA1,
	}
	// supportedCiphers specifies cipher algorithms implemented by this package
	// in preference order, excluding those with security issues.
	supportedCiphers = []string{
		CipherAES128GCM,
		CipherAES256GCM,
		CipherChaCha20Poly1305,
		CipherAES128CTR,
		CipherAES192CTR,
		CipherAES256CTR,
	}
	// defaultCiphers specifies the default preference for ciphers algorithms
	// in preference order.
	defaultCiphers = supportedCiphers
	// insecureCiphers specifies cipher algorithms implemented by this
	// package and which have security issues.
	insecureCiphers = []string{
		InsecureCipherAES128CBC,
		InsecureCipherTripleDESCBC,
		InsecureCipherRC4256,
		InsecureCipherRC4128,
		InsecureCipherRC4,
	}
	// supportedMACs specifies MAC algorithms implemented by this package in
	// preference order, excluding those with security issues.
	supportedMACs = []string{
		HMACSHA256ETM,
		HMACSHA512ETM,
		HMACSHA256,
		HMACSHA512,
		HMACSHA1,
	}
	// defaultMACs specifies the default preference for MAC algorithms in
	// preference order.
	defaultMACs = []string{
		HMACSHA256ETM,
		HMACSHA512ETM,
		HMACSHA256,
		HMACSHA512,
		HMACSHA1,
		InsecureHMACSHA196,
	}
	// insecureMACs specifies MAC algorithms implemented by this
	// package and which have security issues.
	insecureMACs = []string{
		InsecureHMACSHA196,
	}
	// supportedHostKeyAlgos specifies the supported host-key algorithms (i.e.
	// methods of authenticating servers) implemented by this package in
	// preference order, excluding those with security issues.
	supportedHostKeyAlgos = []string{
		CertAlgoRSASHA256v01,
		CertAlgoRSASHA512v01,
		CertAlgoECDSA256v01,
		CertAlgoECDSA384v01,
		CertAlgoECDSA521v01,
		CertAlgoED25519v01,
		KeyAlgoRSASHA256,
		KeyAlgoRSASHA512,
		KeyAlgoECDSA256,
		KeyAlgoECDSA384,
		KeyAlgoECDSA521,
		KeyAlgoED25519,
	}
	// defaultHostKeyAlgos specifies the default preference for host-key
	// algorithms in preference order.
	defaultHostKeyAlgos = []string{
		CertAlgoRSASHA256v01,
		CertAlgoRSASHA512v01,
		CertAlgoRSAv01,
		InsecureCertAlgoDSAv01,
		CertAlgoECDSA256v01,
		CertAlgoECDSA384v01,
		CertAlgoECDSA521v01,
		CertAlgoED25519v01,
		KeyAlgoECDSA256,
		KeyAlgoECDSA384,
		KeyAlgoECDSA521,
		KeyAlgoRSASHA256,
		KeyAlgoRSASHA512,
		KeyAlgoRSA,
		InsecureKeyAlgoDSA,
		KeyAlgoED25519,
	}
	// insecureHostKeyAlgos specifies host-key algorithms implemented by this
	// package and which have security issues.
	insecureHostKeyAlgos = []string{
		KeyAlgoRSA,
		InsecureKeyAlgoDSA,
		CertAlgoRSAv01,
		InsecureCertAlgoDSAv01,
	}
	// supportedPubKeyAuthAlgos specifies the supported client public key
	// authentication algorithms. Note that this doesn't include certificate
	// types since those use the underlying algorithm. Order is irrelevant.
	supportedPubKeyAuthAlgos = []string{
		KeyAlgoED25519,
		KeyAlgoSKED25519,
		KeyAlgoSKECDSA256,
		KeyAlgoECDSA256,
		KeyAlgoECDSA384,
		KeyAlgoECDSA521,
		KeyAlgoRSASHA256,
		KeyAlgoRSASHA512,
	}

	// defaultPubKeyAuthAlgos specifies the preferred client public key
	// authentication algorithms. This list is sent to the client if it supports
	// the server-sig-algs extension. Order is irrelevant.
	defaultPubKeyAuthAlgos = []string{
		KeyAlgoED25519,
		KeyAlgoSKED25519,
		KeyAlgoSKECDSA256,
		KeyAlgoECDSA256,
		KeyAlgoECDSA384,
		KeyAlgoECDSA521,
		KeyAlgoRSASHA256,
		KeyAlgoRSASHA512,
		KeyAlgoRSA,
		InsecureKeyAlgoDSA,
	}
	// insecurePubKeyAuthAlgos specifies client public key authentication
	// algorithms implemented by this package and which have security issues.
	insecurePubKeyAuthAlgos = []string{
		KeyAlgoRSA,
		InsecureKeyAlgoDSA,
	}
)

// NegotiatedAlgorithms defines algorithms negotiated between client and server.
type NegotiatedAlgorithms struct {
	KeyExchange string
	HostKey     string
	Read        DirectionAlgorithms
	Write       DirectionAlgorithms
}

// Algorithms defines a set of algorithms that can be configured in the client
// or server config for negotiation during a handshake.
type Algorithms struct {
	KeyExchanges   []string
	Ciphers        []string
	MACs           []string
	HostKeys       []string
	PublicKeyAuths []string
}

func init() {
	if fips140.Enabled() {
		defaultHostKeyAlgos = slices.DeleteFunc(defaultHostKeyAlgos, func( string) bool {
			,  := hashFunc(underlyingAlgo())
			return  != nil
		})
		defaultPubKeyAuthAlgos = slices.DeleteFunc(defaultPubKeyAuthAlgos, func( string) bool {
			,  := hashFunc(underlyingAlgo())
			return  != nil
		})
	}
}

func hashFunc( string) (crypto.Hash, error) {
	switch  {
	case KeyAlgoRSASHA256, KeyAlgoECDSA256, KeyAlgoSKED25519, KeyAlgoSKECDSA256:
		return crypto.SHA256, nil
	case KeyAlgoECDSA384:
		return crypto.SHA384, nil
	case KeyAlgoRSASHA512, KeyAlgoECDSA521:
		return crypto.SHA512, nil
	case KeyAlgoED25519:
		// KeyAlgoED25519 doesn't pre-hash.
		return 0, nil
	case KeyAlgoRSA, InsecureKeyAlgoDSA:
		if fips140.Enabled() {
			return 0, fmt.Errorf("ssh: hash algorithm for format %q not allowed in FIPS 140 mode", )
		}
		return crypto.SHA1, nil
	default:
		return 0, fmt.Errorf("ssh: hash algorithm for format %q not mapped", )
	}
}

// SupportedAlgorithms returns algorithms currently implemented by this package,
// excluding those with security issues, which are returned by
// InsecureAlgorithms. The algorithms listed here are in preference order.
func () Algorithms {
	return Algorithms{
		Ciphers:        slices.Clone(supportedCiphers),
		MACs:           slices.Clone(supportedMACs),
		KeyExchanges:   slices.Clone(supportedKexAlgos),
		HostKeys:       slices.Clone(supportedHostKeyAlgos),
		PublicKeyAuths: slices.Clone(supportedPubKeyAuthAlgos),
	}
}

// InsecureAlgorithms returns algorithms currently implemented by this package
// and which have security issues.
func () Algorithms {
	return Algorithms{
		KeyExchanges:   slices.Clone(insecureKexAlgos),
		Ciphers:        slices.Clone(insecureCiphers),
		MACs:           slices.Clone(insecureMACs),
		HostKeys:       slices.Clone(insecureHostKeyAlgos),
		PublicKeyAuths: slices.Clone(insecurePubKeyAuthAlgos),
	}
}

var supportedCompressions = []string{compressionNone}

// 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{}
	}
}

// keyFormatForAlgorithm returns the key format corresponding to the given
// signature algorithm. It returns an empty string if the signature algorithm is
// invalid or unsupported.
func keyFormatForAlgorithm( string) string {
	switch  {
	case KeyAlgoRSA, KeyAlgoRSASHA256, KeyAlgoRSASHA512:
		return KeyAlgoRSA
	case CertAlgoRSAv01, CertAlgoRSASHA256v01, CertAlgoRSASHA512v01:
		return CertAlgoRSAv01
	case KeyAlgoED25519,
		KeyAlgoSKED25519,
		KeyAlgoSKECDSA256,
		KeyAlgoECDSA256,
		KeyAlgoECDSA384,
		KeyAlgoECDSA521,
		InsecureKeyAlgoDSA,
		InsecureCertAlgoDSAv01,
		CertAlgoECDSA256v01,
		CertAlgoECDSA384v01,
		CertAlgoECDSA521v01,
		CertAlgoSKECDSA256v01,
		CertAlgoED25519v01,
		CertAlgoSKED25519v01:
		return 
	default:
		return ""
	}
}

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

func isRSACert( string) bool {
	,  := certKeyAlgoNames[]
	if ! {
		return false
	}
	return isRSA()
}

// 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,  bool) (string, error) {
	for ,  := range  {
		for ,  := range  {
			if  ==  {
				return , nil
			}
		}
	}
	 := &AlgorithmNegotiationError{
		What: ,
	}
	if  {
		.SupportedAlgorithms = 
		.RequestedAlgorithms = 
	} else {
		.SupportedAlgorithms = 
		.RequestedAlgorithms = 
	}
	return "", 
}

// AlgorithmNegotiationError defines the error returned if the client and the
// server cannot agree on an algorithm for key exchange, host key, cipher, MAC.
type AlgorithmNegotiationError struct {
	What string
	// RequestedAlgorithms lists the algorithms supported by the peer.
	RequestedAlgorithms []string
	// SupportedAlgorithms lists the algorithms supported on our side.
	SupportedAlgorithms []string
}

func ( *AlgorithmNegotiationError) () string {
	return fmt.Sprintf("ssh: no common algorithm for %s; we offered: %v, peer offered: %v",
		.What, .SupportedAlgorithms, .RequestedAlgorithms)
}

// DirectionAlgorithms defines the algorithms negotiated 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 CipherAES128CTR, CipherAES192CTR, CipherAES256CTR, CipherAES128GCM, CipherAES256GCM, InsecureCipherAES128CBC:
		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{
	CipherAES128GCM:        true,
	CipherAES256GCM:        true,
	CipherChaCha20Poly1305: true,
}

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

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

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

	,  := &.Write, &.Read
	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 = defaultCiphers
	}
	var  []string
	for ,  := range .Ciphers {
		if cipherModes[] != nil {
			// Ignore the cipher if we have no cipherModes definition.
			 = append(, )
		}
	}
	.Ciphers = 

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

	if .MACs == nil {
		.MACs = defaultMACs
	}
	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()
}