common.go 11 KB

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