common.go 14 KB

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