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.

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