common.go 9.2 KB

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