common.go 14 KB

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