common.go 9.5 KB

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