keys.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. // Copyright 2012 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. "bytes"
  7. "crypto/dsa"
  8. "crypto/ecdsa"
  9. "crypto/elliptic"
  10. "crypto/rsa"
  11. "encoding/base64"
  12. "math/big"
  13. )
  14. // These constants represent the algorithm names for key types supported by this
  15. // package.
  16. const (
  17. KeyAlgoRSA = "ssh-rsa"
  18. KeyAlgoDSA = "ssh-dss"
  19. KeyAlgoECDSA256 = "ecdsa-sha2-nistp256"
  20. KeyAlgoECDSA384 = "ecdsa-sha2-nistp384"
  21. KeyAlgoECDSA521 = "ecdsa-sha2-nistp521"
  22. )
  23. // parsePubKey parses a public key according to RFC 4253, section 6.6.
  24. func parsePubKey(in []byte) (out interface{}, rest []byte, ok bool) {
  25. algo, in, ok := parseString(in)
  26. if !ok {
  27. return
  28. }
  29. switch string(algo) {
  30. case KeyAlgoRSA:
  31. return parseRSA(in)
  32. case KeyAlgoDSA:
  33. return parseDSA(in)
  34. case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
  35. return parseECDSA(in)
  36. case CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01:
  37. return parseOpenSSHCertV01(in, string(algo))
  38. }
  39. panic("ssh: unknown public key type")
  40. }
  41. // parseRSA parses an RSA key according to RFC 4253, section 6.6.
  42. func parseRSA(in []byte) (out *rsa.PublicKey, rest []byte, ok bool) {
  43. key := new(rsa.PublicKey)
  44. bigE, in, ok := parseInt(in)
  45. if !ok || bigE.BitLen() > 24 {
  46. return
  47. }
  48. e := bigE.Int64()
  49. if e < 3 || e&1 == 0 {
  50. ok = false
  51. return
  52. }
  53. key.E = int(e)
  54. if key.N, in, ok = parseInt(in); !ok {
  55. return
  56. }
  57. ok = true
  58. return key, in, ok
  59. }
  60. // parseDSA parses an DSA key according to RFC 4253, section 6.6.
  61. func parseDSA(in []byte) (out *dsa.PublicKey, rest []byte, ok bool) {
  62. key := new(dsa.PublicKey)
  63. if key.P, in, ok = parseInt(in); !ok {
  64. return
  65. }
  66. if key.Q, in, ok = parseInt(in); !ok {
  67. return
  68. }
  69. if key.G, in, ok = parseInt(in); !ok {
  70. return
  71. }
  72. if key.Y, in, ok = parseInt(in); !ok {
  73. return
  74. }
  75. ok = true
  76. return key, in, ok
  77. }
  78. // parseECDSA parses an ECDSA key according to RFC 5656, section 3.1.
  79. func parseECDSA(in []byte) (out *ecdsa.PublicKey, rest []byte, ok bool) {
  80. var identifier []byte
  81. if identifier, in, ok = parseString(in); !ok {
  82. return
  83. }
  84. key := new(ecdsa.PublicKey)
  85. switch string(identifier) {
  86. case "nistp256":
  87. key.Curve = elliptic.P256()
  88. case "nistp384":
  89. key.Curve = elliptic.P384()
  90. case "nistp521":
  91. key.Curve = elliptic.P521()
  92. default:
  93. ok = false
  94. return
  95. }
  96. var keyBytes []byte
  97. if keyBytes, in, ok = parseString(in); !ok {
  98. return
  99. }
  100. key.X, key.Y = elliptic.Unmarshal(key.Curve, keyBytes)
  101. if key.X == nil || key.Y == nil {
  102. ok = false
  103. return
  104. }
  105. return key, in, ok
  106. }
  107. // marshalPrivRSA serializes an RSA private key according to RFC 4253, section 6.6.
  108. func marshalPrivRSA(priv *rsa.PrivateKey) []byte {
  109. e := new(big.Int).SetInt64(int64(priv.E))
  110. length := stringLength(len(KeyAlgoRSA))
  111. length += intLength(e)
  112. length += intLength(priv.N)
  113. ret := make([]byte, length)
  114. r := marshalString(ret, []byte(KeyAlgoRSA))
  115. r = marshalInt(r, e)
  116. r = marshalInt(r, priv.N)
  117. return ret
  118. }
  119. // marshalPubRSA serializes an RSA public key according to RFC 4253, section 6.6.
  120. func marshalPubRSA(key *rsa.PublicKey) []byte {
  121. e := new(big.Int).SetInt64(int64(key.E))
  122. length := intLength(e)
  123. length += intLength(key.N)
  124. ret := make([]byte, length)
  125. r := marshalInt(ret, e)
  126. r = marshalInt(r, key.N)
  127. return ret
  128. }
  129. // marshalPubDSA serializes an DSA public key according to RFC 4253, section 6.6.
  130. func marshalPubDSA(key *dsa.PublicKey) []byte {
  131. length := intLength(key.P)
  132. length += intLength(key.Q)
  133. length += intLength(key.G)
  134. length += intLength(key.Y)
  135. ret := make([]byte, length)
  136. r := marshalInt(ret, key.P)
  137. r = marshalInt(r, key.Q)
  138. r = marshalInt(r, key.G)
  139. r = marshalInt(r, key.Y)
  140. return ret
  141. }
  142. // marshalPubECDSA serializes an ECDSA public key according to RFC 5656, section 3.1.
  143. func marshalPubECDSA(key *ecdsa.PublicKey) []byte {
  144. var identifier []byte
  145. switch key.Params().BitSize {
  146. case 256:
  147. identifier = []byte("nistp256")
  148. case 384:
  149. identifier = []byte("nistp384")
  150. case 521:
  151. identifier = []byte("nistp521")
  152. default:
  153. panic("ssh: unsupported ecdsa key size")
  154. }
  155. keyBytes := elliptic.Marshal(key.Curve, key.X, key.Y)
  156. length := stringLength(len(identifier))
  157. length += stringLength(len(keyBytes))
  158. ret := make([]byte, length)
  159. r := marshalString(ret, identifier)
  160. r = marshalString(r, keyBytes)
  161. return ret
  162. }
  163. // parseAuthorizedKey parses a public key in OpenSSH authorized_keys format
  164. // (see sshd(8) manual page) once the options and key type fields have been
  165. // removed.
  166. func parseAuthorizedKey(in []byte) (out interface{}, comment string, ok bool) {
  167. in = bytes.TrimSpace(in)
  168. i := bytes.IndexAny(in, " \t")
  169. if i == -1 {
  170. i = len(in)
  171. }
  172. base64Key := in[:i]
  173. key := make([]byte, base64.StdEncoding.DecodedLen(len(base64Key)))
  174. n, err := base64.StdEncoding.Decode(key, base64Key)
  175. if err != nil {
  176. return
  177. }
  178. key = key[:n]
  179. out, _, ok = parsePubKey(key)
  180. if !ok {
  181. return nil, "", false
  182. }
  183. comment = string(bytes.TrimSpace(in[i:]))
  184. return
  185. }
  186. // ParseAuthorizedKeys parses a public key from an authorized_keys
  187. // file used in OpenSSH according to the sshd(8) manual page.
  188. func ParseAuthorizedKey(in []byte) (out interface{}, comment string, options []string, rest []byte, ok bool) {
  189. for len(in) > 0 {
  190. end := bytes.IndexByte(in, '\n')
  191. if end != -1 {
  192. rest = in[end+1:]
  193. in = in[:end]
  194. } else {
  195. rest = nil
  196. }
  197. end = bytes.IndexByte(in, '\r')
  198. if end != -1 {
  199. in = in[:end]
  200. }
  201. in = bytes.TrimSpace(in)
  202. if len(in) == 0 || in[0] == '#' {
  203. in = rest
  204. continue
  205. }
  206. i := bytes.IndexAny(in, " \t")
  207. if i == -1 {
  208. in = rest
  209. continue
  210. }
  211. field := string(in[:i])
  212. switch field {
  213. case KeyAlgoRSA, KeyAlgoDSA:
  214. out, comment, ok = parseAuthorizedKey(in[i:])
  215. if ok {
  216. return
  217. }
  218. case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
  219. // We don't support these keys.
  220. in = rest
  221. continue
  222. case CertAlgoRSAv01, CertAlgoDSAv01,
  223. CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01:
  224. // We don't support these certificates.
  225. in = rest
  226. continue
  227. }
  228. // No key type recognised. Maybe there's an options field at
  229. // the beginning.
  230. var b byte
  231. inQuote := false
  232. var candidateOptions []string
  233. optionStart := 0
  234. for i, b = range in {
  235. isEnd := !inQuote && (b == ' ' || b == '\t')
  236. if (b == ',' && !inQuote) || isEnd {
  237. if i-optionStart > 0 {
  238. candidateOptions = append(candidateOptions, string(in[optionStart:i]))
  239. }
  240. optionStart = i + 1
  241. }
  242. if isEnd {
  243. break
  244. }
  245. if b == '"' && (i == 0 || (i > 0 && in[i-1] != '\\')) {
  246. inQuote = !inQuote
  247. }
  248. }
  249. for i < len(in) && (in[i] == ' ' || in[i] == '\t') {
  250. i++
  251. }
  252. if i == len(in) {
  253. // Invalid line: unmatched quote
  254. in = rest
  255. continue
  256. }
  257. in = in[i:]
  258. i = bytes.IndexAny(in, " \t")
  259. if i == -1 {
  260. in = rest
  261. continue
  262. }
  263. field = string(in[:i])
  264. switch field {
  265. case KeyAlgoRSA, KeyAlgoDSA:
  266. out, comment, ok = parseAuthorizedKey(in[i:])
  267. if ok {
  268. options = candidateOptions
  269. return
  270. }
  271. }
  272. in = rest
  273. continue
  274. }
  275. return
  276. }
  277. // ParsePublicKey parses an SSH public key formatted for use in
  278. // the SSH wire protocol.
  279. func ParsePublicKey(in []byte) (out interface{}, rest []byte, ok bool) {
  280. return parsePubKey(in)
  281. }
  282. // MarshalAuthorizedKey returns a byte stream suitable for inclusion
  283. // in an OpenSSH authorized_keys file following the format specified
  284. // in the sshd(8) manual page.
  285. func MarshalAuthorizedKey(key interface{}) []byte {
  286. b := &bytes.Buffer{}
  287. b.WriteString(algoName(key))
  288. b.WriteByte(' ')
  289. e := base64.NewEncoder(base64.StdEncoding, b)
  290. e.Write(serializePublickey(key))
  291. e.Close()
  292. b.WriteByte('\n')
  293. return b.Bytes()
  294. }
  295. // MarshalPublicKey serializes a supported key or certificate for use by the
  296. // SSH wire protocol. It can be used for comparison with the pubkey argument
  297. // of ServerConfig's PublicKeyCallback as well as for generating an
  298. // authorized_keys or host_keys file.
  299. func MarshalPublicKey(key interface{}) []byte {
  300. return serializePublickey(key)
  301. }