common.go 12 KB

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