common.go 9.1 KB

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