common.go 13 KB

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