common.go 13 KB

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