common.go 9.1 KB

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