Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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