common.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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",
  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",
  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-256-etm@openssh.com", "hmac-sha2-256", "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", gcmCipherID, 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. gcmCipherID: true,
  156. chacha20Poly1305ID: true,
  157. }
  158. type algorithms struct {
  159. kex string
  160. hostKey string
  161. w directionAlgorithms
  162. r directionAlgorithms
  163. }
  164. func findAgreedAlgorithms(isClient bool, clientKexInit, serverKexInit *kexInitMsg) (algs *algorithms, err error) {
  165. result := &algorithms{}
  166. result.kex, err = findCommon("key exchange", clientKexInit.KexAlgos, serverKexInit.KexAlgos)
  167. if err != nil {
  168. return
  169. }
  170. result.hostKey, err = findCommon("host key", clientKexInit.ServerHostKeyAlgos, serverKexInit.ServerHostKeyAlgos)
  171. if err != nil {
  172. return
  173. }
  174. stoc, ctos := &result.w, &result.r
  175. if isClient {
  176. ctos, stoc = stoc, ctos
  177. }
  178. ctos.Cipher, err = findCommon("client to server cipher", clientKexInit.CiphersClientServer, serverKexInit.CiphersClientServer)
  179. if err != nil {
  180. return
  181. }
  182. stoc.Cipher, err = findCommon("server to client cipher", clientKexInit.CiphersServerClient, serverKexInit.CiphersServerClient)
  183. if err != nil {
  184. return
  185. }
  186. if !aeadCiphers[ctos.Cipher] {
  187. ctos.MAC, err = findCommon("client to server MAC", clientKexInit.MACsClientServer, serverKexInit.MACsClientServer)
  188. if err != nil {
  189. return
  190. }
  191. }
  192. if !aeadCiphers[stoc.Cipher] {
  193. stoc.MAC, err = findCommon("server to client MAC", clientKexInit.MACsServerClient, serverKexInit.MACsServerClient)
  194. if err != nil {
  195. return
  196. }
  197. }
  198. ctos.Compression, err = findCommon("client to server compression", clientKexInit.CompressionClientServer, serverKexInit.CompressionClientServer)
  199. if err != nil {
  200. return
  201. }
  202. stoc.Compression, err = findCommon("server to client compression", clientKexInit.CompressionServerClient, serverKexInit.CompressionServerClient)
  203. if err != nil {
  204. return
  205. }
  206. return result, nil
  207. }
  208. // If rekeythreshold is too small, we can't make any progress sending
  209. // stuff.
  210. const minRekeyThreshold uint64 = 256
  211. // Config contains configuration data common to both ServerConfig and
  212. // ClientConfig.
  213. type Config struct {
  214. // Rand provides the source of entropy for cryptographic
  215. // primitives. If Rand is nil, the cryptographic random reader
  216. // in package crypto/rand will be used.
  217. Rand io.Reader
  218. // The maximum number of bytes sent or received after which a
  219. // new key is negotiated. It must be at least 256. If
  220. // unspecified, a size suitable for the chosen cipher is used.
  221. RekeyThreshold uint64
  222. // The allowed key exchanges algorithms. If unspecified then a
  223. // default set of algorithms is used.
  224. KeyExchanges []string
  225. // The allowed cipher algorithms. If unspecified then a sensible
  226. // default is used.
  227. Ciphers []string
  228. // The allowed MAC algorithms. If unspecified then a sensible default
  229. // is used.
  230. MACs []string
  231. }
  232. // SetDefaults sets sensible values for unset fields in config. This is
  233. // exported for testing: Configs passed to SSH functions are copied and have
  234. // default values set automatically.
  235. func (c *Config) SetDefaults() {
  236. if c.Rand == nil {
  237. c.Rand = rand.Reader
  238. }
  239. if c.Ciphers == nil {
  240. c.Ciphers = preferredCiphers
  241. }
  242. var ciphers []string
  243. for _, c := range c.Ciphers {
  244. if cipherModes[c] != nil {
  245. // reject the cipher if we have no cipherModes definition
  246. ciphers = append(ciphers, c)
  247. }
  248. }
  249. c.Ciphers = ciphers
  250. if c.KeyExchanges == nil {
  251. c.KeyExchanges = preferredKexAlgos
  252. }
  253. if c.MACs == nil {
  254. c.MACs = supportedMACs
  255. }
  256. if c.RekeyThreshold == 0 {
  257. // cipher specific default
  258. } else if c.RekeyThreshold < minRekeyThreshold {
  259. c.RekeyThreshold = minRekeyThreshold
  260. } else if c.RekeyThreshold >= math.MaxInt64 {
  261. // Avoid weirdness if somebody uses -1 as a threshold.
  262. c.RekeyThreshold = math.MaxInt64
  263. }
  264. }
  265. // buildDataSignedForAuth returns the data that is signed in order to prove
  266. // possession of a private key. See RFC 4252, section 7. algo is the advertised
  267. // algorithm, and may be a certificate type.
  268. func buildDataSignedForAuth(sessionID []byte, req userAuthRequestMsg, algo string, pubKey []byte) []byte {
  269. data := struct {
  270. Session []byte
  271. Type byte
  272. User string
  273. Service string
  274. Method string
  275. Sign bool
  276. Algo string
  277. PubKey []byte
  278. }{
  279. sessionID,
  280. msgUserAuthRequest,
  281. req.User,
  282. req.Service,
  283. req.Method,
  284. true,
  285. algo,
  286. pubKey,
  287. }
  288. return Marshal(data)
  289. }
  290. func appendU16(buf []byte, n uint16) []byte {
  291. return append(buf, byte(n>>8), byte(n))
  292. }
  293. func appendU32(buf []byte, n uint32) []byte {
  294. return append(buf, byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  295. }
  296. func appendU64(buf []byte, n uint64) []byte {
  297. return append(buf,
  298. byte(n>>56), byte(n>>48), byte(n>>40), byte(n>>32),
  299. byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  300. }
  301. func appendInt(buf []byte, n int) []byte {
  302. return appendU32(buf, uint32(n))
  303. }
  304. func appendString(buf []byte, s string) []byte {
  305. buf = appendU32(buf, uint32(len(s)))
  306. buf = append(buf, s...)
  307. return buf
  308. }
  309. func appendBool(buf []byte, b bool) []byte {
  310. if b {
  311. return append(buf, 1)
  312. }
  313. return append(buf, 0)
  314. }
  315. // newCond is a helper to hide the fact that there is no usable zero
  316. // value for sync.Cond.
  317. func newCond() *sync.Cond { return sync.NewCond(new(sync.Mutex)) }
  318. // window represents the buffer available to clients
  319. // wishing to write to a channel.
  320. type window struct {
  321. *sync.Cond
  322. win uint32 // RFC 4254 5.2 says the window size can grow to 2^32-1
  323. writeWaiters int
  324. closed bool
  325. }
  326. // add adds win to the amount of window available
  327. // for consumers.
  328. func (w *window) add(win uint32) bool {
  329. // a zero sized window adjust is a noop.
  330. if win == 0 {
  331. return true
  332. }
  333. w.L.Lock()
  334. if w.win+win < win {
  335. w.L.Unlock()
  336. return false
  337. }
  338. w.win += win
  339. // It is unusual that multiple goroutines would be attempting to reserve
  340. // window space, but not guaranteed. Use broadcast to notify all waiters
  341. // that additional window is available.
  342. w.Broadcast()
  343. w.L.Unlock()
  344. return true
  345. }
  346. // close sets the window to closed, so all reservations fail
  347. // immediately.
  348. func (w *window) close() {
  349. w.L.Lock()
  350. w.closed = true
  351. w.Broadcast()
  352. w.L.Unlock()
  353. }
  354. // reserve reserves win from the available window capacity.
  355. // If no capacity remains, reserve will block. reserve may
  356. // return less than requested.
  357. func (w *window) reserve(win uint32) (uint32, error) {
  358. var err error
  359. w.L.Lock()
  360. w.writeWaiters++
  361. w.Broadcast()
  362. for w.win == 0 && !w.closed {
  363. w.Wait()
  364. }
  365. w.writeWaiters--
  366. if w.win < win {
  367. win = w.win
  368. }
  369. w.win -= win
  370. if w.closed {
  371. err = io.EOF
  372. }
  373. w.L.Unlock()
  374. return win, err
  375. }
  376. // waitWriterBlocked waits until some goroutine is blocked for further
  377. // writes. It is used in tests only.
  378. func (w *window) waitWriterBlocked() {
  379. w.Cond.L.Lock()
  380. for w.writeWaiters == 0 {
  381. w.Cond.Wait()
  382. }
  383. w.Cond.L.Unlock()
  384. }