common.go 9.2 KB

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