common.go 12 KB

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