common.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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-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. if c.KeyExchanges == nil {
  177. c.KeyExchanges = supportedKexAlgos
  178. }
  179. if c.MACs == nil {
  180. c.MACs = supportedMACs
  181. }
  182. if c.RekeyThreshold == 0 {
  183. // RFC 4253, section 9 suggests rekeying after 1G.
  184. c.RekeyThreshold = 1 << 30
  185. }
  186. if c.RekeyThreshold < minRekeyThreshold {
  187. c.RekeyThreshold = minRekeyThreshold
  188. }
  189. }
  190. // buildDataSignedForAuth returns the data that is signed in order to prove
  191. // possession of a private key. See RFC 4252, section 7.
  192. func buildDataSignedForAuth(sessionId []byte, req userAuthRequestMsg, algo, pubKey []byte) []byte {
  193. data := struct {
  194. Session []byte
  195. Type byte
  196. User string
  197. Service string
  198. Method string
  199. Sign bool
  200. Algo []byte
  201. PubKey []byte
  202. }{
  203. sessionId,
  204. msgUserAuthRequest,
  205. req.User,
  206. req.Service,
  207. req.Method,
  208. true,
  209. algo,
  210. pubKey,
  211. }
  212. return Marshal(data)
  213. }
  214. func appendU16(buf []byte, n uint16) []byte {
  215. return append(buf, byte(n>>8), byte(n))
  216. }
  217. func appendU32(buf []byte, n uint32) []byte {
  218. return append(buf, byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  219. }
  220. func appendU64(buf []byte, n uint64) []byte {
  221. return append(buf,
  222. byte(n>>56), byte(n>>48), byte(n>>40), byte(n>>32),
  223. byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  224. }
  225. func appendInt(buf []byte, n int) []byte {
  226. return appendU32(buf, uint32(n))
  227. }
  228. func appendString(buf []byte, s string) []byte {
  229. buf = appendU32(buf, uint32(len(s)))
  230. buf = append(buf, s...)
  231. return buf
  232. }
  233. func appendBool(buf []byte, b bool) []byte {
  234. if b {
  235. return append(buf, 1)
  236. }
  237. return append(buf, 0)
  238. }
  239. // newCond is a helper to hide the fact that there is no usable zero
  240. // value for sync.Cond.
  241. func newCond() *sync.Cond { return sync.NewCond(new(sync.Mutex)) }
  242. // window represents the buffer available to clients
  243. // wishing to write to a channel.
  244. type window struct {
  245. *sync.Cond
  246. win uint32 // RFC 4254 5.2 says the window size can grow to 2^32-1
  247. writeWaiters int
  248. closed bool
  249. }
  250. // add adds win to the amount of window available
  251. // for consumers.
  252. func (w *window) add(win uint32) bool {
  253. // a zero sized window adjust is a noop.
  254. if win == 0 {
  255. return true
  256. }
  257. w.L.Lock()
  258. if w.win+win < win {
  259. w.L.Unlock()
  260. return false
  261. }
  262. w.win += win
  263. // It is unusual that multiple goroutines would be attempting to reserve
  264. // window space, but not guaranteed. Use broadcast to notify all waiters
  265. // that additional window is available.
  266. w.Broadcast()
  267. w.L.Unlock()
  268. return true
  269. }
  270. // close sets the window to closed, so all reservations fail
  271. // immediately.
  272. func (w *window) close() {
  273. w.L.Lock()
  274. w.closed = true
  275. w.Broadcast()
  276. w.L.Unlock()
  277. }
  278. // reserve reserves win from the available window capacity.
  279. // If no capacity remains, reserve will block. reserve may
  280. // return less than requested.
  281. func (w *window) reserve(win uint32) (uint32, error) {
  282. var err error
  283. w.L.Lock()
  284. w.writeWaiters++
  285. w.Broadcast()
  286. for w.win == 0 && !w.closed {
  287. w.Wait()
  288. }
  289. w.writeWaiters--
  290. if w.win < win {
  291. win = w.win
  292. }
  293. w.win -= win
  294. if w.closed {
  295. err = io.EOF
  296. }
  297. w.L.Unlock()
  298. return win, err
  299. }
  300. // waitWriterBlocked waits until some goroutine is blocked for further
  301. // writes. It is used in tests only.
  302. func (w *window) waitWriterBlocked() {
  303. w.Cond.L.Lock()
  304. for w.writeWaiters == 0 {
  305. w.Cond.Wait()
  306. }
  307. w.Cond.L.Unlock()
  308. }