common.go 12 KB

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