您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

372 行
9.6 KiB

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