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

common.go 11 kB

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