本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

405 lines
11KB

  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. "math"
  11. "sync"
  12. _ "crypto/sha1"
  13. _ "crypto/sha256"
  14. _ "crypto/sha512"
  15. )
  16. // These are string constants in the SSH protocol.
  17. const (
  18. compressionNone = "none"
  19. serviceUserAuth = "ssh-userauth"
  20. serviceSSH = "ssh-connection"
  21. )
  22. // supportedCiphers lists ciphers we support but might not recommend.
  23. var supportedCiphers = []string{
  24. "aes128-ctr", "aes192-ctr", "aes256-ctr",
  25. "aes128-gcm@openssh.com",
  26. chacha20Poly1305ID,
  27. "arcfour256", "arcfour128", "arcfour",
  28. aes128cbcID,
  29. tripledescbcID,
  30. }
  31. // preferredCiphers specifies the default preference for ciphers.
  32. var preferredCiphers = []string{
  33. "aes128-gcm@openssh.com",
  34. chacha20Poly1305ID,
  35. "aes128-ctr", "aes192-ctr", "aes256-ctr",
  36. }
  37. // supportedKexAlgos specifies the supported key-exchange algorithms in
  38. // preference order.
  39. var supportedKexAlgos = []string{
  40. kexAlgoCurve25519SHA256,
  41. // P384 and P521 are not constant-time yet, but since we don't
  42. // reuse ephemeral keys, using them for ECDH should be OK.
  43. kexAlgoECDH256, kexAlgoECDH384, kexAlgoECDH521,
  44. kexAlgoDH14SHA1, kexAlgoDH1SHA1,
  45. }
  46. // serverForbiddenKexAlgos contains key exchange algorithms, that are forbidden
  47. // for the server half.
  48. var serverForbiddenKexAlgos = map[string]struct{}{
  49. kexAlgoDHGEXSHA1: {}, // server half implementation is only minimal to satisfy the automated tests
  50. kexAlgoDHGEXSHA256: {}, // server half implementation is only minimal to satisfy the automated tests
  51. }
  52. // preferredKexAlgos specifies the default preference for key-exchange algorithms
  53. // in preference order.
  54. var preferredKexAlgos = []string{
  55. kexAlgoCurve25519SHA256,
  56. kexAlgoECDH256, kexAlgoECDH384, kexAlgoECDH521,
  57. kexAlgoDH14SHA1,
  58. }
  59. // supportedHostKeyAlgos specifies the supported host-key algorithms (i.e. methods
  60. // of authenticating servers) in preference order.
  61. var supportedHostKeyAlgos = []string{
  62. CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01,
  63. CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01,
  64. KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521,
  65. KeyAlgoRSA, KeyAlgoDSA,
  66. KeyAlgoED25519,
  67. }
  68. // supportedMACs specifies a default set of MAC algorithms in preference order.
  69. // This is based on RFC 4253, section 6.4, but with hmac-md5 variants removed
  70. // because they have reached the end of their useful life.
  71. var supportedMACs = []string{
  72. "hmac-sha2-256-etm@openssh.com", "hmac-sha2-256", "hmac-sha1", "hmac-sha1-96",
  73. }
  74. var supportedCompressions = []string{compressionNone}
  75. // hashFuncs keeps the mapping of supported algorithms to their respective
  76. // hashes needed for signature verification.
  77. var hashFuncs = map[string]crypto.Hash{
  78. KeyAlgoRSA: crypto.SHA1,
  79. KeyAlgoDSA: crypto.SHA1,
  80. KeyAlgoECDSA256: crypto.SHA256,
  81. KeyAlgoECDSA384: crypto.SHA384,
  82. KeyAlgoECDSA521: crypto.SHA512,
  83. CertAlgoRSAv01: crypto.SHA1,
  84. CertAlgoDSAv01: crypto.SHA1,
  85. CertAlgoECDSA256v01: crypto.SHA256,
  86. CertAlgoECDSA384v01: crypto.SHA384,
  87. CertAlgoECDSA521v01: crypto.SHA512,
  88. }
  89. // unexpectedMessageError results when the SSH message that we received didn't
  90. // match what we wanted.
  91. func unexpectedMessageError(expected, got uint8) error {
  92. return fmt.Errorf("ssh: unexpected message type %d (expected %d)", got, expected)
  93. }
  94. // parseError results from a malformed SSH message.
  95. func parseError(tag uint8) error {
  96. return fmt.Errorf("ssh: parse error in message type %d", tag)
  97. }
  98. func findCommon(what string, client []string, server []string) (common string, err error) {
  99. for _, c := range client {
  100. for _, s := range server {
  101. if c == s {
  102. return c, nil
  103. }
  104. }
  105. }
  106. return "", fmt.Errorf("ssh: no common algorithm for %s; client offered: %v, server offered: %v", what, client, server)
  107. }
  108. // directionAlgorithms records algorithm choices in one direction (either read or write)
  109. type directionAlgorithms struct {
  110. Cipher string
  111. MAC string
  112. Compression string
  113. }
  114. // rekeyBytes returns a rekeying intervals in bytes.
  115. func (a *directionAlgorithms) rekeyBytes() int64 {
  116. // According to RFC4344 block ciphers should rekey after
  117. // 2^(BLOCKSIZE/4) blocks. For all AES flavors BLOCKSIZE is
  118. // 128.
  119. switch a.Cipher {
  120. case "aes128-ctr", "aes192-ctr", "aes256-ctr", gcmCipherID, aes128cbcID:
  121. return 16 * (1 << 32)
  122. }
  123. // For others, stick with RFC4253 recommendation to rekey after 1 Gb of data.
  124. return 1 << 30
  125. }
  126. type algorithms struct {
  127. kex string
  128. hostKey string
  129. w directionAlgorithms
  130. r directionAlgorithms
  131. }
  132. func findAgreedAlgorithms(isClient bool, clientKexInit, serverKexInit *kexInitMsg) (algs *algorithms, err error) {
  133. result := &algorithms{}
  134. result.kex, err = findCommon("key exchange", clientKexInit.KexAlgos, serverKexInit.KexAlgos)
  135. if err != nil {
  136. return
  137. }
  138. result.hostKey, err = findCommon("host key", clientKexInit.ServerHostKeyAlgos, serverKexInit.ServerHostKeyAlgos)
  139. if err != nil {
  140. return
  141. }
  142. stoc, ctos := &result.w, &result.r
  143. if isClient {
  144. ctos, stoc = stoc, ctos
  145. }
  146. ctos.Cipher, err = findCommon("client to server cipher", clientKexInit.CiphersClientServer, serverKexInit.CiphersClientServer)
  147. if err != nil {
  148. return
  149. }
  150. stoc.Cipher, err = findCommon("server to client cipher", clientKexInit.CiphersServerClient, serverKexInit.CiphersServerClient)
  151. if err != nil {
  152. return
  153. }
  154. ctos.MAC, err = findCommon("client to server MAC", clientKexInit.MACsClientServer, serverKexInit.MACsClientServer)
  155. if err != nil {
  156. return
  157. }
  158. stoc.MAC, err = findCommon("server to client MAC", clientKexInit.MACsServerClient, serverKexInit.MACsServerClient)
  159. if err != nil {
  160. return
  161. }
  162. ctos.Compression, err = findCommon("client to server compression", clientKexInit.CompressionClientServer, serverKexInit.CompressionClientServer)
  163. if err != nil {
  164. return
  165. }
  166. stoc.Compression, err = findCommon("server to client compression", clientKexInit.CompressionServerClient, serverKexInit.CompressionServerClient)
  167. if err != nil {
  168. return
  169. }
  170. return result, nil
  171. }
  172. // If rekeythreshold is too small, we can't make any progress sending
  173. // stuff.
  174. const minRekeyThreshold uint64 = 256
  175. // Config contains configuration data common to both ServerConfig and
  176. // ClientConfig.
  177. type Config struct {
  178. // Rand provides the source of entropy for cryptographic
  179. // primitives. If Rand is nil, the cryptographic random reader
  180. // in package crypto/rand will be used.
  181. Rand io.Reader
  182. // The maximum number of bytes sent or received after which a
  183. // new key is negotiated. It must be at least 256. If
  184. // unspecified, a size suitable for the chosen cipher is used.
  185. RekeyThreshold uint64
  186. // The allowed key exchanges algorithms. If unspecified then a
  187. // default set of algorithms is used.
  188. KeyExchanges []string
  189. // The allowed cipher algorithms. If unspecified then a sensible
  190. // default is used.
  191. Ciphers []string
  192. // The allowed MAC algorithms. If unspecified then a sensible default
  193. // is used.
  194. MACs []string
  195. }
  196. // SetDefaults sets sensible values for unset fields in config. This is
  197. // exported for testing: Configs passed to SSH functions are copied and have
  198. // default values set automatically.
  199. func (c *Config) SetDefaults() {
  200. if c.Rand == nil {
  201. c.Rand = rand.Reader
  202. }
  203. if c.Ciphers == nil {
  204. c.Ciphers = preferredCiphers
  205. }
  206. var ciphers []string
  207. for _, c := range c.Ciphers {
  208. if cipherModes[c] != nil {
  209. // reject the cipher if we have no cipherModes definition
  210. ciphers = append(ciphers, c)
  211. }
  212. }
  213. c.Ciphers = ciphers
  214. if c.KeyExchanges == nil {
  215. c.KeyExchanges = preferredKexAlgos
  216. }
  217. if c.MACs == nil {
  218. c.MACs = supportedMACs
  219. }
  220. if c.RekeyThreshold == 0 {
  221. // cipher specific default
  222. } else if c.RekeyThreshold < minRekeyThreshold {
  223. c.RekeyThreshold = minRekeyThreshold
  224. } else if c.RekeyThreshold >= math.MaxInt64 {
  225. // Avoid weirdness if somebody uses -1 as a threshold.
  226. c.RekeyThreshold = math.MaxInt64
  227. }
  228. }
  229. // buildDataSignedForAuth returns the data that is signed in order to prove
  230. // possession of a private key. See RFC 4252, section 7.
  231. func buildDataSignedForAuth(sessionID []byte, req userAuthRequestMsg, algo, pubKey []byte) []byte {
  232. data := struct {
  233. Session []byte
  234. Type byte
  235. User string
  236. Service string
  237. Method string
  238. Sign bool
  239. Algo []byte
  240. PubKey []byte
  241. }{
  242. sessionID,
  243. msgUserAuthRequest,
  244. req.User,
  245. req.Service,
  246. req.Method,
  247. true,
  248. algo,
  249. pubKey,
  250. }
  251. return Marshal(data)
  252. }
  253. func appendU16(buf []byte, n uint16) []byte {
  254. return append(buf, byte(n>>8), byte(n))
  255. }
  256. func appendU32(buf []byte, n uint32) []byte {
  257. return append(buf, byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  258. }
  259. func appendU64(buf []byte, n uint64) []byte {
  260. return append(buf,
  261. byte(n>>56), byte(n>>48), byte(n>>40), byte(n>>32),
  262. byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  263. }
  264. func appendInt(buf []byte, n int) []byte {
  265. return appendU32(buf, uint32(n))
  266. }
  267. func appendString(buf []byte, s string) []byte {
  268. buf = appendU32(buf, uint32(len(s)))
  269. buf = append(buf, s...)
  270. return buf
  271. }
  272. func appendBool(buf []byte, b bool) []byte {
  273. if b {
  274. return append(buf, 1)
  275. }
  276. return append(buf, 0)
  277. }
  278. // newCond is a helper to hide the fact that there is no usable zero
  279. // value for sync.Cond.
  280. func newCond() *sync.Cond { return sync.NewCond(new(sync.Mutex)) }
  281. // window represents the buffer available to clients
  282. // wishing to write to a channel.
  283. type window struct {
  284. *sync.Cond
  285. win uint32 // RFC 4254 5.2 says the window size can grow to 2^32-1
  286. writeWaiters int
  287. closed bool
  288. }
  289. // add adds win to the amount of window available
  290. // for consumers.
  291. func (w *window) add(win uint32) bool {
  292. // a zero sized window adjust is a noop.
  293. if win == 0 {
  294. return true
  295. }
  296. w.L.Lock()
  297. if w.win+win < win {
  298. w.L.Unlock()
  299. return false
  300. }
  301. w.win += win
  302. // It is unusual that multiple goroutines would be attempting to reserve
  303. // window space, but not guaranteed. Use broadcast to notify all waiters
  304. // that additional window is available.
  305. w.Broadcast()
  306. w.L.Unlock()
  307. return true
  308. }
  309. // close sets the window to closed, so all reservations fail
  310. // immediately.
  311. func (w *window) close() {
  312. w.L.Lock()
  313. w.closed = true
  314. w.Broadcast()
  315. w.L.Unlock()
  316. }
  317. // reserve reserves win from the available window capacity.
  318. // If no capacity remains, reserve will block. reserve may
  319. // return less than requested.
  320. func (w *window) reserve(win uint32) (uint32, error) {
  321. var err error
  322. w.L.Lock()
  323. w.writeWaiters++
  324. w.Broadcast()
  325. for w.win == 0 && !w.closed {
  326. w.Wait()
  327. }
  328. w.writeWaiters--
  329. if w.win < win {
  330. win = w.win
  331. }
  332. w.win -= win
  333. if w.closed {
  334. err = io.EOF
  335. }
  336. w.L.Unlock()
  337. return win, err
  338. }
  339. // waitWriterBlocked waits until some goroutine is blocked for further
  340. // writes. It is used in tests only.
  341. func (w *window) waitWriterBlocked() {
  342. w.Cond.L.Lock()
  343. for w.writeWaiters == 0 {
  344. w.Cond.Wait()
  345. }
  346. w.Cond.L.Unlock()
  347. }
上海开阖软件有限公司 沪ICP备12045867号-1