common.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. "math/big"
  10. "strconv"
  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 "ssh: unexpected message type " + strconv.Itoa(int(u.got)) + " (expected " + strconv.Itoa(int(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 "ssh: parse error in message type " + strconv.Itoa(int(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 findAgreedAlgorithms(transport *transport, clientKexInit, serverKexInit *kexInitMsg) (kexAlgo, hostKeyAlgo string, ok bool) {
  88. kexAlgo, ok = findCommonAlgorithm(clientKexInit.KexAlgos, serverKexInit.KexAlgos)
  89. if !ok {
  90. return
  91. }
  92. hostKeyAlgo, ok = findCommonAlgorithm(clientKexInit.ServerHostKeyAlgos, serverKexInit.ServerHostKeyAlgos)
  93. if !ok {
  94. return
  95. }
  96. transport.writer.cipherAlgo, ok = findCommonAlgorithm(clientKexInit.CiphersClientServer, serverKexInit.CiphersClientServer)
  97. if !ok {
  98. return
  99. }
  100. transport.reader.cipherAlgo, ok = findCommonAlgorithm(clientKexInit.CiphersServerClient, serverKexInit.CiphersServerClient)
  101. if !ok {
  102. return
  103. }
  104. transport.writer.macAlgo, ok = findCommonAlgorithm(clientKexInit.MACsClientServer, serverKexInit.MACsClientServer)
  105. if !ok {
  106. return
  107. }
  108. transport.reader.macAlgo, ok = findCommonAlgorithm(clientKexInit.MACsServerClient, serverKexInit.MACsServerClient)
  109. if !ok {
  110. return
  111. }
  112. transport.writer.compressionAlgo, ok = findCommonAlgorithm(clientKexInit.CompressionClientServer, serverKexInit.CompressionClientServer)
  113. if !ok {
  114. return
  115. }
  116. transport.reader.compressionAlgo, ok = findCommonAlgorithm(clientKexInit.CompressionServerClient, serverKexInit.CompressionServerClient)
  117. if !ok {
  118. return
  119. }
  120. ok = true
  121. return
  122. }
  123. // Cryptographic configuration common to both ServerConfig and ClientConfig.
  124. type CryptoConfig struct {
  125. // The allowed cipher algorithms. If unspecified then DefaultCipherOrder is
  126. // used.
  127. Ciphers []string
  128. // The allowed MAC algorithms. If unspecified then DefaultMACOrder is used.
  129. MACs []string
  130. }
  131. func (c *CryptoConfig) ciphers() []string {
  132. if c.Ciphers == nil {
  133. return DefaultCipherOrder
  134. }
  135. return c.Ciphers
  136. }
  137. func (c *CryptoConfig) macs() []string {
  138. if c.MACs == nil {
  139. return DefaultMACOrder
  140. }
  141. return c.MACs
  142. }
  143. // serialize a signed slice according to RFC 4254 6.6.
  144. func serializeSignature(algoname string, sig []byte) []byte {
  145. switch algoname {
  146. // The corresponding private key to a public certificate is always a normal
  147. // private key. For signature serialization purposes, ensure we use the
  148. // proper ssh-rsa or ssh-dss algo name in case the public cert algo name is passed.
  149. case hostAlgoRSACertV01:
  150. algoname = "ssh-rsa"
  151. case hostAlgoDSACertV01:
  152. algoname = "ssh-dss"
  153. }
  154. length := stringLength(len(algoname))
  155. length += stringLength(len(sig))
  156. ret := make([]byte, length)
  157. r := marshalString(ret, []byte(algoname))
  158. r = marshalString(r, sig)
  159. return ret
  160. }
  161. // serialize a *rsa.PublicKey or *dsa.PublicKey according to RFC 4253 6.6.
  162. func serializePublickey(key interface{}) []byte {
  163. var pubKeyBytes []byte
  164. algoname := algoName(key)
  165. switch key := key.(type) {
  166. case *rsa.PublicKey:
  167. pubKeyBytes = marshalPubRSA(key)
  168. case *dsa.PublicKey:
  169. pubKeyBytes = marshalPubDSA(key)
  170. case *OpenSSHCertV01:
  171. pubKeyBytes = marshalOpenSSHCertV01(key)
  172. default:
  173. panic("unexpected key type")
  174. }
  175. length := stringLength(len(algoname))
  176. length += len(pubKeyBytes)
  177. ret := make([]byte, length)
  178. r := marshalString(ret, []byte(algoname))
  179. copy(r, pubKeyBytes)
  180. return ret
  181. }
  182. func algoName(key interface{}) string {
  183. switch key.(type) {
  184. case *rsa.PublicKey:
  185. return "ssh-rsa"
  186. case *dsa.PublicKey:
  187. return "ssh-dss"
  188. case *OpenSSHCertV01:
  189. return algoName(key.(*OpenSSHCertV01).Key) + "-cert-v01@openssh.com"
  190. }
  191. panic("unexpected key type")
  192. }
  193. // buildDataSignedForAuth returns the data that is signed in order to prove
  194. // posession of a private key. See RFC 4252, section 7.
  195. func buildDataSignedForAuth(sessionId []byte, req userAuthRequestMsg, algo, pubKey []byte) []byte {
  196. user := []byte(req.User)
  197. service := []byte(req.Service)
  198. method := []byte(req.Method)
  199. length := stringLength(len(sessionId))
  200. length += 1
  201. length += stringLength(len(user))
  202. length += stringLength(len(service))
  203. length += stringLength(len(method))
  204. length += 1
  205. length += stringLength(len(algo))
  206. length += stringLength(len(pubKey))
  207. ret := make([]byte, length)
  208. r := marshalString(ret, sessionId)
  209. r[0] = msgUserAuthRequest
  210. r = r[1:]
  211. r = marshalString(r, user)
  212. r = marshalString(r, service)
  213. r = marshalString(r, method)
  214. r[0] = 1
  215. r = r[1:]
  216. r = marshalString(r, algo)
  217. r = marshalString(r, pubKey)
  218. return ret
  219. }
  220. // safeString sanitises s according to RFC 4251, section 9.2.
  221. // All control characters except tab, carriage return and newline are
  222. // replaced by 0x20.
  223. func safeString(s string) string {
  224. out := []byte(s)
  225. for i, c := range out {
  226. if c < 0x20 && c != 0xd && c != 0xa && c != 0x9 {
  227. out[i] = 0x20
  228. }
  229. }
  230. return string(out)
  231. }
  232. func appendU16(buf []byte, n uint16) []byte {
  233. return append(buf, byte(n>>8), byte(n))
  234. }
  235. func appendU32(buf []byte, n uint32) []byte {
  236. return append(buf, byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  237. }
  238. func appendInt(buf []byte, n int) []byte {
  239. return appendU32(buf, uint32(n))
  240. }