common.go 10 KB

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