keys.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. // marshalPubRSA serializes an RSA public key according to RFC 4253, section 6.6.
  108. func marshalPubRSA(key *rsa.PublicKey) []byte {
  109. e := new(big.Int).SetInt64(int64(key.E))
  110. length := intLength(e)
  111. length += intLength(key.N)
  112. ret := make([]byte, length)
  113. r := marshalInt(ret, e)
  114. r = marshalInt(r, key.N)
  115. return ret
  116. }
  117. // marshalPubDSA serializes an DSA public key according to RFC 4253, section 6.6.
  118. func marshalPubDSA(key *dsa.PublicKey) []byte {
  119. length := intLength(key.P)
  120. length += intLength(key.Q)
  121. length += intLength(key.G)
  122. length += intLength(key.Y)
  123. ret := make([]byte, length)
  124. r := marshalInt(ret, key.P)
  125. r = marshalInt(r, key.Q)
  126. r = marshalInt(r, key.G)
  127. r = marshalInt(r, key.Y)
  128. return ret
  129. }
  130. // marshalPubECDSA serializes an ECDSA public key according to RFC 5656, section 3.1.
  131. func marshalPubECDSA(key *ecdsa.PublicKey) []byte {
  132. var identifier []byte
  133. switch key.Params().BitSize {
  134. case 256:
  135. identifier = []byte("nistp256")
  136. case 384:
  137. identifier = []byte("nistp384")
  138. case 521:
  139. identifier = []byte("nistp521")
  140. default:
  141. panic("ssh: unsupported ecdsa key size")
  142. }
  143. keyBytes := elliptic.Marshal(key.Curve, key.X, key.Y)
  144. length := stringLength(len(identifier))
  145. length += stringLength(len(keyBytes))
  146. ret := make([]byte, length)
  147. r := marshalString(ret, identifier)
  148. r = marshalString(r, keyBytes)
  149. return ret
  150. }
  151. // parseAuthorizedKey parses a public key in OpenSSH authorized_keys format
  152. // (see sshd(8) manual page) once the options and key type fields have been
  153. // removed.
  154. func parseAuthorizedKey(in []byte) (out interface{}, comment string, ok bool) {
  155. in = bytes.TrimSpace(in)
  156. i := bytes.IndexAny(in, " \t")
  157. if i == -1 {
  158. i = len(in)
  159. }
  160. base64Key := in[:i]
  161. key := make([]byte, base64.StdEncoding.DecodedLen(len(base64Key)))
  162. n, err := base64.StdEncoding.Decode(key, base64Key)
  163. if err != nil {
  164. return
  165. }
  166. key = key[:n]
  167. out, _, ok = parsePubKey(key)
  168. if !ok {
  169. return nil, "", false
  170. }
  171. comment = string(bytes.TrimSpace(in[i:]))
  172. return
  173. }
  174. // ParseAuthorizedKeys parses a public key from an authorized_keys
  175. // file used in OpenSSH according to the sshd(8) manual page.
  176. func ParseAuthorizedKey(in []byte) (out interface{}, comment string, options []string, rest []byte, ok bool) {
  177. for len(in) > 0 {
  178. end := bytes.IndexByte(in, '\n')
  179. if end != -1 {
  180. rest = in[end+1:]
  181. in = in[:end]
  182. } else {
  183. rest = nil
  184. }
  185. end = bytes.IndexByte(in, '\r')
  186. if end != -1 {
  187. in = in[:end]
  188. }
  189. in = bytes.TrimSpace(in)
  190. if len(in) == 0 || in[0] == '#' {
  191. in = rest
  192. continue
  193. }
  194. i := bytes.IndexAny(in, " \t")
  195. if i == -1 {
  196. in = rest
  197. continue
  198. }
  199. field := string(in[:i])
  200. switch field {
  201. case KeyAlgoRSA, KeyAlgoDSA:
  202. out, comment, ok = parseAuthorizedKey(in[i:])
  203. if ok {
  204. return
  205. }
  206. case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
  207. // We don't support these keys.
  208. in = rest
  209. continue
  210. case CertAlgoRSAv01, CertAlgoDSAv01,
  211. CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01:
  212. // We don't support these certificates.
  213. in = rest
  214. continue
  215. }
  216. // No key type recognised. Maybe there's an options field at
  217. // the beginning.
  218. var b byte
  219. inQuote := false
  220. var candidateOptions []string
  221. optionStart := 0
  222. for i, b = range in {
  223. isEnd := !inQuote && (b == ' ' || b == '\t')
  224. if (b == ',' && !inQuote) || isEnd {
  225. if i-optionStart > 0 {
  226. candidateOptions = append(candidateOptions, string(in[optionStart:i]))
  227. }
  228. optionStart = i + 1
  229. }
  230. if isEnd {
  231. break
  232. }
  233. if b == '"' && (i == 0 || (i > 0 && in[i-1] != '\\')) {
  234. inQuote = !inQuote
  235. }
  236. }
  237. for i < len(in) && (in[i] == ' ' || in[i] == '\t') {
  238. i++
  239. }
  240. if i == len(in) {
  241. // Invalid line: unmatched quote
  242. in = rest
  243. continue
  244. }
  245. in = in[i:]
  246. i = bytes.IndexAny(in, " \t")
  247. if i == -1 {
  248. in = rest
  249. continue
  250. }
  251. field = string(in[:i])
  252. switch field {
  253. case KeyAlgoRSA, KeyAlgoDSA:
  254. out, comment, ok = parseAuthorizedKey(in[i:])
  255. if ok {
  256. options = candidateOptions
  257. return
  258. }
  259. }
  260. in = rest
  261. continue
  262. }
  263. return
  264. }
  265. // ParsePublicKey parses an SSH public key formatted for use in
  266. // the SSH wire protocol.
  267. func ParsePublicKey(in []byte) (out interface{}, rest []byte, ok bool) {
  268. return parsePubKey(in)
  269. }
  270. // MarshalAuthorizedKey returns a byte stream suitable for inclusion
  271. // in an OpenSSH authorized_keys file following the format specified
  272. // in the sshd(8) manual page.
  273. func MarshalAuthorizedKey(key interface{}) []byte {
  274. b := &bytes.Buffer{}
  275. b.WriteString(algoName(key))
  276. b.WriteByte(' ')
  277. e := base64.NewEncoder(base64.StdEncoding, b)
  278. e.Write(serializePublicKey(key))
  279. e.Close()
  280. b.WriteByte('\n')
  281. return b.Bytes()
  282. }
  283. // MarshalPublicKey serializes a supported key or certificate for use by the
  284. // SSH wire protocol. It can be used for comparison with the pubkey argument
  285. // of ServerConfig's PublicKeyCallback as well as for generating an
  286. // authorized_keys or host_keys file.
  287. func MarshalPublicKey(key interface{}) []byte {
  288. return serializePublicKey(key)
  289. }