common.go 9.7 KB

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