common.go 11 KB

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