common.go 11 KB

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