common.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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/dsa"
  8. "crypto/ecdsa"
  9. "crypto/elliptic"
  10. "crypto/rsa"
  11. "errors"
  12. "fmt"
  13. "math/big"
  14. "sync"
  15. )
  16. // These are string constants in the SSH protocol.
  17. const (
  18. kexAlgoDH1SHA1 = "diffie-hellman-group1-sha1"
  19. kexAlgoDH14SHA1 = "diffie-hellman-group14-sha1"
  20. kexAlgoECDH256 = "ecdh-sha2-nistp256"
  21. kexAlgoECDH384 = "ecdh-sha2-nistp384"
  22. kexAlgoECDH521 = "ecdh-sha2-nistp521"
  23. hostAlgoRSA = "ssh-rsa"
  24. hostAlgoDSA = "ssh-dss"
  25. compressionNone = "none"
  26. serviceUserAuth = "ssh-userauth"
  27. serviceSSH = "ssh-connection"
  28. )
  29. var supportedKexAlgos = []string{
  30. kexAlgoECDH256, kexAlgoECDH384, kexAlgoECDH521,
  31. kexAlgoDH14SHA1, kexAlgoDH1SHA1,
  32. }
  33. var supportedHostKeyAlgos = []string{hostAlgoRSA}
  34. var supportedCompressions = []string{compressionNone}
  35. // dhGroup is a multiplicative group suitable for implementing Diffie-Hellman key agreement.
  36. type dhGroup struct {
  37. g, p *big.Int
  38. }
  39. func (group *dhGroup) diffieHellman(theirPublic, myPrivate *big.Int) (*big.Int, error) {
  40. if theirPublic.Sign() <= 0 || theirPublic.Cmp(group.p) >= 0 {
  41. return nil, errors.New("ssh: DH parameter out of bounds")
  42. }
  43. return new(big.Int).Exp(theirPublic, myPrivate, group.p), nil
  44. }
  45. // dhGroup1 is the group called diffie-hellman-group1-sha1 in RFC 4253 and
  46. // Oakley Group 2 in RFC 2409.
  47. var dhGroup1 *dhGroup
  48. var dhGroup1Once sync.Once
  49. func initDHGroup1() {
  50. p, _ := new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF", 16)
  51. dhGroup1 = &dhGroup{
  52. g: new(big.Int).SetInt64(2),
  53. p: p,
  54. }
  55. }
  56. // dhGroup14 is the group called diffie-hellman-group14-sha1 in RFC 4253 and
  57. // Oakley Group 14 in RFC 3526.
  58. var dhGroup14 *dhGroup
  59. var dhGroup14Once sync.Once
  60. func initDHGroup14() {
  61. p, _ := new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF", 16)
  62. dhGroup14 = &dhGroup{
  63. g: new(big.Int).SetInt64(2),
  64. p: p,
  65. }
  66. }
  67. // UnexpectedMessageError results when the SSH message that we received didn't
  68. // match what we wanted.
  69. type UnexpectedMessageError struct {
  70. expected, got uint8
  71. }
  72. func (u UnexpectedMessageError) Error() string {
  73. return fmt.Sprintf("ssh: unexpected message type %d (expected %d)", u.got, u.expected)
  74. }
  75. // ParseError results from a malformed SSH message.
  76. type ParseError struct {
  77. msgType uint8
  78. }
  79. func (p ParseError) Error() string {
  80. return fmt.Sprintf("ssh: parse error in message type %d", p.msgType)
  81. }
  82. type handshakeMagics struct {
  83. clientVersion, serverVersion []byte
  84. clientKexInit, serverKexInit []byte
  85. }
  86. func findCommonAlgorithm(clientAlgos []string, serverAlgos []string) (commonAlgo string, ok bool) {
  87. for _, clientAlgo := range clientAlgos {
  88. for _, serverAlgo := range serverAlgos {
  89. if clientAlgo == serverAlgo {
  90. return clientAlgo, true
  91. }
  92. }
  93. }
  94. return
  95. }
  96. func findCommonCipher(clientCiphers []string, serverCiphers []string) (commonCipher string, ok bool) {
  97. for _, clientCipher := range clientCiphers {
  98. for _, serverCipher := range serverCiphers {
  99. // reject the cipher if we have no cipherModes definition
  100. if clientCipher == serverCipher && cipherModes[clientCipher] != nil {
  101. return clientCipher, true
  102. }
  103. }
  104. }
  105. return
  106. }
  107. func findAgreedAlgorithms(transport *transport, clientKexInit, serverKexInit *kexInitMsg) (kexAlgo, hostKeyAlgo string, ok bool) {
  108. kexAlgo, ok = findCommonAlgorithm(clientKexInit.KexAlgos, serverKexInit.KexAlgos)
  109. if !ok {
  110. return
  111. }
  112. hostKeyAlgo, ok = findCommonAlgorithm(clientKexInit.ServerHostKeyAlgos, serverKexInit.ServerHostKeyAlgos)
  113. if !ok {
  114. return
  115. }
  116. transport.writer.cipherAlgo, ok = findCommonCipher(clientKexInit.CiphersClientServer, serverKexInit.CiphersClientServer)
  117. if !ok {
  118. return
  119. }
  120. transport.reader.cipherAlgo, ok = findCommonCipher(clientKexInit.CiphersServerClient, serverKexInit.CiphersServerClient)
  121. if !ok {
  122. return
  123. }
  124. transport.writer.macAlgo, ok = findCommonAlgorithm(clientKexInit.MACsClientServer, serverKexInit.MACsClientServer)
  125. if !ok {
  126. return
  127. }
  128. transport.reader.macAlgo, ok = findCommonAlgorithm(clientKexInit.MACsServerClient, serverKexInit.MACsServerClient)
  129. if !ok {
  130. return
  131. }
  132. transport.writer.compressionAlgo, ok = findCommonAlgorithm(clientKexInit.CompressionClientServer, serverKexInit.CompressionClientServer)
  133. if !ok {
  134. return
  135. }
  136. transport.reader.compressionAlgo, ok = findCommonAlgorithm(clientKexInit.CompressionServerClient, serverKexInit.CompressionServerClient)
  137. if !ok {
  138. return
  139. }
  140. ok = true
  141. return
  142. }
  143. // Cryptographic configuration common to both ServerConfig and ClientConfig.
  144. type CryptoConfig struct {
  145. // The allowed key exchanges algorithms. If unspecified then a
  146. // default set of algorithms is used.
  147. KeyExchanges []string
  148. // The allowed cipher algorithms. If unspecified then DefaultCipherOrder is
  149. // used.
  150. Ciphers []string
  151. // The allowed MAC algorithms. If unspecified then DefaultMACOrder is used.
  152. MACs []string
  153. }
  154. func (c *CryptoConfig) ciphers() []string {
  155. if c.Ciphers == nil {
  156. return DefaultCipherOrder
  157. }
  158. return c.Ciphers
  159. }
  160. func (c *CryptoConfig) kexes() []string {
  161. if c.KeyExchanges == nil {
  162. return defaultKeyExchangeOrder
  163. }
  164. return c.KeyExchanges
  165. }
  166. func (c *CryptoConfig) macs() []string {
  167. if c.MACs == nil {
  168. return DefaultMACOrder
  169. }
  170. return c.MACs
  171. }
  172. // ecHash returns the hash to match the given elliptic curve, see RFC
  173. // 5656, section 6.2.1
  174. func ecHash(curve elliptic.Curve) crypto.Hash {
  175. bitSize := curve.Params().BitSize
  176. switch {
  177. case bitSize <= 256:
  178. return crypto.SHA256
  179. case bitSize <= 384:
  180. return crypto.SHA384
  181. }
  182. return crypto.SHA512
  183. }
  184. // serialize a signed slice according to RFC 4254 6.6.
  185. func serializeSignature(algoname string, sig []byte) []byte {
  186. switch algoname {
  187. // The corresponding private key to a public certificate is always a normal
  188. // private key. For signature serialization purposes, ensure we use the
  189. // proper key algorithm name in case the public cert algorithm name is passed.
  190. case CertAlgoRSAv01:
  191. algoname = KeyAlgoRSA
  192. case CertAlgoDSAv01:
  193. algoname = KeyAlgoDSA
  194. case CertAlgoECDSA256v01:
  195. algoname = KeyAlgoECDSA256
  196. case CertAlgoECDSA384v01:
  197. algoname = KeyAlgoECDSA384
  198. case CertAlgoECDSA521v01:
  199. algoname = KeyAlgoECDSA521
  200. }
  201. length := stringLength(len(algoname))
  202. length += stringLength(len(sig))
  203. ret := make([]byte, length)
  204. r := marshalString(ret, []byte(algoname))
  205. r = marshalString(r, sig)
  206. return ret
  207. }
  208. // serialize a *rsa.PublicKey or *dsa.PublicKey according to RFC 4253 6.6.
  209. func serializePublicKey(key interface{}) []byte {
  210. var pubKeyBytes []byte
  211. algoname := algoName(key)
  212. switch key := key.(type) {
  213. case *rsa.PublicKey:
  214. pubKeyBytes = marshalPubRSA(key)
  215. case *dsa.PublicKey:
  216. pubKeyBytes = marshalPubDSA(key)
  217. case *ecdsa.PublicKey:
  218. pubKeyBytes = marshalPubECDSA(key)
  219. case *OpenSSHCertV01:
  220. pubKeyBytes = marshalOpenSSHCertV01(key)
  221. default:
  222. panic("unexpected key type")
  223. }
  224. length := stringLength(len(algoname))
  225. length += len(pubKeyBytes)
  226. ret := make([]byte, length)
  227. r := marshalString(ret, []byte(algoname))
  228. copy(r, pubKeyBytes)
  229. return ret
  230. }
  231. func algoName(key interface{}) string {
  232. switch key.(type) {
  233. case *rsa.PublicKey:
  234. return KeyAlgoRSA
  235. case *dsa.PublicKey:
  236. return KeyAlgoDSA
  237. case *ecdsa.PublicKey:
  238. switch key.(*ecdsa.PublicKey).Params().BitSize {
  239. case 256:
  240. return KeyAlgoECDSA256
  241. case 384:
  242. return KeyAlgoECDSA384
  243. case 521:
  244. return KeyAlgoECDSA521
  245. }
  246. case *OpenSSHCertV01:
  247. switch key.(*OpenSSHCertV01).Key.(type) {
  248. case *rsa.PublicKey:
  249. return CertAlgoRSAv01
  250. case *dsa.PublicKey:
  251. return CertAlgoDSAv01
  252. case *ecdsa.PublicKey:
  253. switch key.(*OpenSSHCertV01).Key.(*ecdsa.PublicKey).Params().BitSize {
  254. case 256:
  255. return CertAlgoECDSA256v01
  256. case 384:
  257. return CertAlgoECDSA384v01
  258. case 521:
  259. return CertAlgoECDSA521v01
  260. }
  261. }
  262. }
  263. panic(fmt.Sprintf("unexpected key type %T", key))
  264. }
  265. // buildDataSignedForAuth returns the data that is signed in order to prove
  266. // posession of a private key. See RFC 4252, section 7.
  267. func buildDataSignedForAuth(sessionId []byte, req userAuthRequestMsg, algo, pubKey []byte) []byte {
  268. user := []byte(req.User)
  269. service := []byte(req.Service)
  270. method := []byte(req.Method)
  271. length := stringLength(len(sessionId))
  272. length += 1
  273. length += stringLength(len(user))
  274. length += stringLength(len(service))
  275. length += stringLength(len(method))
  276. length += 1
  277. length += stringLength(len(algo))
  278. length += stringLength(len(pubKey))
  279. ret := make([]byte, length)
  280. r := marshalString(ret, sessionId)
  281. r[0] = msgUserAuthRequest
  282. r = r[1:]
  283. r = marshalString(r, user)
  284. r = marshalString(r, service)
  285. r = marshalString(r, method)
  286. r[0] = 1
  287. r = r[1:]
  288. r = marshalString(r, algo)
  289. r = marshalString(r, pubKey)
  290. return ret
  291. }
  292. // safeString sanitises s according to RFC 4251, section 9.2.
  293. // All control characters except tab, carriage return and newline are
  294. // replaced by 0x20.
  295. func safeString(s string) string {
  296. out := []byte(s)
  297. for i, c := range out {
  298. if c < 0x20 && c != 0xd && c != 0xa && c != 0x9 {
  299. out[i] = 0x20
  300. }
  301. }
  302. return string(out)
  303. }
  304. func appendU16(buf []byte, n uint16) []byte {
  305. return append(buf, byte(n>>8), byte(n))
  306. }
  307. func appendU32(buf []byte, n uint32) []byte {
  308. return append(buf, byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  309. }
  310. func appendInt(buf []byte, n int) []byte {
  311. return appendU32(buf, uint32(n))
  312. }
  313. func appendString(buf []byte, s string) []byte {
  314. buf = appendU32(buf, uint32(len(s)))
  315. buf = append(buf, s...)
  316. return buf
  317. }
  318. func appendBool(buf []byte, b bool) []byte {
  319. if b {
  320. buf = append(buf, 1)
  321. } else {
  322. buf = append(buf, 0)
  323. }
  324. return buf
  325. }
  326. // newCond is a helper to hide the fact that there is no usable zero
  327. // value for sync.Cond.
  328. func newCond() *sync.Cond { return sync.NewCond(new(sync.Mutex)) }
  329. // window represents the buffer available to clients
  330. // wishing to write to a channel.
  331. type window struct {
  332. *sync.Cond
  333. win uint32 // RFC 4254 5.2 says the window size can grow to 2^32-1
  334. }
  335. // add adds win to the amount of window available
  336. // for consumers.
  337. func (w *window) add(win uint32) bool {
  338. // a zero sized window adjust is a noop.
  339. if win == 0 {
  340. return true
  341. }
  342. w.L.Lock()
  343. if w.win+win < win {
  344. w.L.Unlock()
  345. return false
  346. }
  347. w.win += win
  348. // It is unusual that multiple goroutines would be attempting to reserve
  349. // window space, but not guaranteed. Use broadcast to notify all waiters
  350. // that additional window is available.
  351. w.Broadcast()
  352. w.L.Unlock()
  353. return true
  354. }
  355. // reserve reserves win from the available window capacity.
  356. // If no capacity remains, reserve will block. reserve may
  357. // return less than requested.
  358. func (w *window) reserve(win uint32) uint32 {
  359. w.L.Lock()
  360. for w.win == 0 {
  361. w.Wait()
  362. }
  363. if w.win < win {
  364. win = w.win
  365. }
  366. w.win -= win
  367. w.L.Unlock()
  368. return win
  369. }