keys.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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"
  8. "crypto/dsa"
  9. "crypto/ecdsa"
  10. "crypto/elliptic"
  11. "crypto/rsa"
  12. "encoding/base64"
  13. "math/big"
  14. )
  15. // These constants represent the algorithm names for key types supported by this
  16. // package.
  17. const (
  18. KeyAlgoRSA = "ssh-rsa"
  19. KeyAlgoDSA = "ssh-dss"
  20. KeyAlgoECDSA256 = "ecdsa-sha2-nistp256"
  21. KeyAlgoECDSA384 = "ecdsa-sha2-nistp384"
  22. KeyAlgoECDSA521 = "ecdsa-sha2-nistp521"
  23. )
  24. // parsePubKey parses a public key according to RFC 4253, section 6.6.
  25. func parsePubKey(in []byte) (pubKey PublicKey, rest []byte, ok bool) {
  26. algo, in, ok := parseString(in)
  27. if !ok {
  28. return
  29. }
  30. switch string(algo) {
  31. case KeyAlgoRSA:
  32. return parseRSA(in)
  33. case KeyAlgoDSA:
  34. return parseDSA(in)
  35. case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
  36. return parseECDSA(in)
  37. case CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01:
  38. return parseOpenSSHCertV01(in, string(algo))
  39. }
  40. return nil, nil, false
  41. }
  42. // parseAuthorizedKey parses a public key in OpenSSH authorized_keys format
  43. // (see sshd(8) manual page) once the options and key type fields have been
  44. // removed.
  45. func parseAuthorizedKey(in []byte) (out interface{}, comment string, ok bool) {
  46. in = bytes.TrimSpace(in)
  47. i := bytes.IndexAny(in, " \t")
  48. if i == -1 {
  49. i = len(in)
  50. }
  51. base64Key := in[:i]
  52. key := make([]byte, base64.StdEncoding.DecodedLen(len(base64Key)))
  53. n, err := base64.StdEncoding.Decode(key, base64Key)
  54. if err != nil {
  55. return
  56. }
  57. key = key[:n]
  58. out, _, ok = parsePubKey(key)
  59. if !ok {
  60. return nil, "", false
  61. }
  62. comment = string(bytes.TrimSpace(in[i:]))
  63. return
  64. }
  65. // ParseAuthorizedKeys parses a public key from an authorized_keys
  66. // file used in OpenSSH according to the sshd(8) manual page.
  67. func ParseAuthorizedKey(in []byte) (out interface{}, comment string, options []string, rest []byte, ok bool) {
  68. for len(in) > 0 {
  69. end := bytes.IndexByte(in, '\n')
  70. if end != -1 {
  71. rest = in[end+1:]
  72. in = in[:end]
  73. } else {
  74. rest = nil
  75. }
  76. end = bytes.IndexByte(in, '\r')
  77. if end != -1 {
  78. in = in[:end]
  79. }
  80. in = bytes.TrimSpace(in)
  81. if len(in) == 0 || in[0] == '#' {
  82. in = rest
  83. continue
  84. }
  85. i := bytes.IndexAny(in, " \t")
  86. if i == -1 {
  87. in = rest
  88. continue
  89. }
  90. field := string(in[:i])
  91. switch field {
  92. case KeyAlgoRSA, KeyAlgoDSA:
  93. out, comment, ok = parseAuthorizedKey(in[i:])
  94. if ok {
  95. return
  96. }
  97. case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
  98. // We don't support these keys.
  99. in = rest
  100. continue
  101. case CertAlgoRSAv01, CertAlgoDSAv01,
  102. CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01:
  103. // We don't support these certificates.
  104. in = rest
  105. continue
  106. }
  107. // No key type recognised. Maybe there's an options field at
  108. // the beginning.
  109. var b byte
  110. inQuote := false
  111. var candidateOptions []string
  112. optionStart := 0
  113. for i, b = range in {
  114. isEnd := !inQuote && (b == ' ' || b == '\t')
  115. if (b == ',' && !inQuote) || isEnd {
  116. if i-optionStart > 0 {
  117. candidateOptions = append(candidateOptions, string(in[optionStart:i]))
  118. }
  119. optionStart = i + 1
  120. }
  121. if isEnd {
  122. break
  123. }
  124. if b == '"' && (i == 0 || (i > 0 && in[i-1] != '\\')) {
  125. inQuote = !inQuote
  126. }
  127. }
  128. for i < len(in) && (in[i] == ' ' || in[i] == '\t') {
  129. i++
  130. }
  131. if i == len(in) {
  132. // Invalid line: unmatched quote
  133. in = rest
  134. continue
  135. }
  136. in = in[i:]
  137. i = bytes.IndexAny(in, " \t")
  138. if i == -1 {
  139. in = rest
  140. continue
  141. }
  142. field = string(in[:i])
  143. switch field {
  144. case KeyAlgoRSA, KeyAlgoDSA:
  145. out, comment, ok = parseAuthorizedKey(in[i:])
  146. if ok {
  147. options = candidateOptions
  148. return
  149. }
  150. }
  151. in = rest
  152. continue
  153. }
  154. return
  155. }
  156. // ParsePublicKey parses an SSH public key formatted for use in
  157. // the SSH wire protocol.
  158. func ParsePublicKey(in []byte) (out PublicKey, rest []byte, ok bool) {
  159. return parsePubKey(in)
  160. }
  161. // MarshalAuthorizedKey returns a byte stream suitable for inclusion
  162. // in an OpenSSH authorized_keys file following the format specified
  163. // in the sshd(8) manual page.
  164. func MarshalAuthorizedKey(key PublicKey) []byte {
  165. b := &bytes.Buffer{}
  166. b.WriteString(key.PublicKeyAlgo())
  167. b.WriteByte(' ')
  168. e := base64.NewEncoder(base64.StdEncoding, b)
  169. e.Write(MarshalPublicKey(key))
  170. e.Close()
  171. b.WriteByte('\n')
  172. return b.Bytes()
  173. }
  174. // PublicKey is an abstraction of different types of public keys.
  175. type PublicKey interface {
  176. // PrivateKeyAlgo returns the name of the encryption system.
  177. PrivateKeyAlgo() string
  178. // PublicKeyAlgo returns the algorithm for the public key,
  179. // which may be different from PrivateKeyAlgo for certificates.
  180. PublicKeyAlgo() string
  181. // Marshal returns the serialized key data in SSH wire format,
  182. // without the name prefix. Callers should typically use
  183. // MarshalPublicKey().
  184. Marshal() []byte
  185. // Verify that sig is a signature on the given data using this
  186. // key. This function will hash the data appropriately first.
  187. Verify(data []byte, sigBlob []byte) bool
  188. // RawKey returns the underlying object, eg. *rsa.PublicKey.
  189. RawKey() interface{}
  190. }
  191. // TODO(hanwen): define PrivateKey too.
  192. type rsaPublicKey rsa.PublicKey
  193. func (r *rsaPublicKey) PrivateKeyAlgo() string {
  194. return "ssh-rsa"
  195. }
  196. func (r *rsaPublicKey) PublicKeyAlgo() string {
  197. return "ssh-rsa"
  198. }
  199. func (r *rsaPublicKey) RawKey() interface{} {
  200. return (*rsa.PublicKey)(r)
  201. }
  202. // parseRSA parses an RSA key according to RFC 4253, section 6.6.
  203. func parseRSA(in []byte) (out PublicKey, rest []byte, ok bool) {
  204. key := new(rsa.PublicKey)
  205. bigE, in, ok := parseInt(in)
  206. if !ok || bigE.BitLen() > 24 {
  207. return
  208. }
  209. e := bigE.Int64()
  210. if e < 3 || e&1 == 0 {
  211. ok = false
  212. return
  213. }
  214. key.E = int(e)
  215. if key.N, in, ok = parseInt(in); !ok {
  216. return
  217. }
  218. ok = true
  219. return NewRSAPublicKey(key), in, ok
  220. }
  221. func (r *rsaPublicKey) Marshal() []byte {
  222. // See RFC 4253, section 6.6.
  223. e := new(big.Int).SetInt64(int64(r.E))
  224. length := intLength(e)
  225. length += intLength(r.N)
  226. ret := make([]byte, length)
  227. rest := marshalInt(ret, e)
  228. marshalInt(rest, r.N)
  229. return ret
  230. }
  231. func (r *rsaPublicKey) Verify(data []byte, sig []byte) bool {
  232. h := crypto.SHA1.New()
  233. h.Write(data)
  234. digest := h.Sum(nil)
  235. return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), crypto.SHA1, digest, sig) == nil
  236. }
  237. func NewRSAPublicKey(k *rsa.PublicKey) PublicKey {
  238. return (*rsaPublicKey)(k)
  239. }
  240. type dsaPublicKey dsa.PublicKey
  241. func (r *dsaPublicKey) PrivateKeyAlgo() string {
  242. return "ssh-dss"
  243. }
  244. func (r *dsaPublicKey) PublicKeyAlgo() string {
  245. return "ssh-dss"
  246. }
  247. func (r *dsaPublicKey) RawKey() interface{} {
  248. return (*dsa.PublicKey)(r)
  249. }
  250. // parseDSA parses an DSA key according to RFC 4253, section 6.6.
  251. func parseDSA(in []byte) (out PublicKey, rest []byte, ok bool) {
  252. key := new(dsa.PublicKey)
  253. if key.P, in, ok = parseInt(in); !ok {
  254. return
  255. }
  256. if key.Q, in, ok = parseInt(in); !ok {
  257. return
  258. }
  259. if key.G, in, ok = parseInt(in); !ok {
  260. return
  261. }
  262. if key.Y, in, ok = parseInt(in); !ok {
  263. return
  264. }
  265. ok = true
  266. return NewDSAPublicKey(key), in, ok
  267. }
  268. func (r *dsaPublicKey) Marshal() []byte {
  269. // See RFC 4253, section 6.6.
  270. length := intLength(r.P)
  271. length += intLength(r.Q)
  272. length += intLength(r.G)
  273. length += intLength(r.Y)
  274. ret := make([]byte, length)
  275. rest := marshalInt(ret, r.P)
  276. rest = marshalInt(rest, r.Q)
  277. rest = marshalInt(rest, r.G)
  278. marshalInt(rest, r.Y)
  279. return ret
  280. }
  281. func (k *dsaPublicKey) Verify(data []byte, sigBlob []byte) bool {
  282. h := crypto.SHA1.New()
  283. h.Write(data)
  284. digest := h.Sum(nil)
  285. // Per RFC 4253, section 6.6,
  286. // The value for 'dss_signature_blob' is encoded as a string containing
  287. // r, followed by s (which are 160-bit integers, without lengths or
  288. // padding, unsigned, and in network byte order).
  289. // For DSS purposes, sig.Blob should be exactly 40 bytes in length.
  290. if len(sigBlob) != 40 {
  291. return false
  292. }
  293. r := new(big.Int).SetBytes(sigBlob[:20])
  294. s := new(big.Int).SetBytes(sigBlob[20:])
  295. return dsa.Verify((*dsa.PublicKey)(k), digest, r, s)
  296. }
  297. func NewDSAPublicKey(k *dsa.PublicKey) PublicKey {
  298. return (*dsaPublicKey)(k)
  299. }
  300. type ecdsaPublicKey ecdsa.PublicKey
  301. func NewECDSAPublicKey(k *ecdsa.PublicKey) PublicKey {
  302. return (*ecdsaPublicKey)(k)
  303. }
  304. func (r *ecdsaPublicKey) RawKey() interface{} {
  305. return (*ecdsa.PublicKey)(r)
  306. }
  307. func (key *ecdsaPublicKey) PrivateKeyAlgo() string {
  308. return "ecdh-sha2-" + key.nistID()
  309. }
  310. func (key *ecdsaPublicKey) nistID() string {
  311. switch key.Params().BitSize {
  312. case 256:
  313. return "nistp256"
  314. case 384:
  315. return "nistp384"
  316. case 521:
  317. return "nistp521"
  318. }
  319. panic("ssh: unsupported ecdsa key size")
  320. }
  321. // RFC 5656, section 6.2.1 (for ECDSA).
  322. func (key *ecdsaPublicKey) hash() crypto.Hash {
  323. switch key.Params().BitSize {
  324. case 256:
  325. return crypto.SHA256
  326. case 384:
  327. return crypto.SHA384
  328. case 521:
  329. return crypto.SHA512
  330. }
  331. panic("ssh: unsupported ecdsa key size")
  332. }
  333. func (key *ecdsaPublicKey) PublicKeyAlgo() string {
  334. switch key.Params().BitSize {
  335. case 256:
  336. return KeyAlgoECDSA256
  337. case 384:
  338. return KeyAlgoECDSA384
  339. case 521:
  340. return KeyAlgoECDSA521
  341. }
  342. panic("ssh: unsupported ecdsa key size")
  343. }
  344. // parseECDSA parses an ECDSA key according to RFC 5656, section 3.1.
  345. func parseECDSA(in []byte) (out PublicKey, rest []byte, ok bool) {
  346. var identifier []byte
  347. if identifier, in, ok = parseString(in); !ok {
  348. return
  349. }
  350. key := new(ecdsa.PublicKey)
  351. switch string(identifier) {
  352. case "nistp256":
  353. key.Curve = elliptic.P256()
  354. case "nistp384":
  355. key.Curve = elliptic.P384()
  356. case "nistp521":
  357. key.Curve = elliptic.P521()
  358. default:
  359. ok = false
  360. return
  361. }
  362. var keyBytes []byte
  363. if keyBytes, in, ok = parseString(in); !ok {
  364. return
  365. }
  366. key.X, key.Y = elliptic.Unmarshal(key.Curve, keyBytes)
  367. if key.X == nil || key.Y == nil {
  368. ok = false
  369. return
  370. }
  371. return NewECDSAPublicKey(key), in, ok
  372. }
  373. func (key *ecdsaPublicKey) Marshal() []byte {
  374. // See RFC 5656, section 3.1.
  375. keyBytes := elliptic.Marshal(key.Curve, key.X, key.Y)
  376. ID := key.nistID()
  377. length := stringLength(len(ID))
  378. length += stringLength(len(keyBytes))
  379. ret := make([]byte, length)
  380. r := marshalString(ret, []byte(ID))
  381. r = marshalString(r, keyBytes)
  382. return ret
  383. }
  384. func (key *ecdsaPublicKey) Verify(data []byte, sigBlob []byte) bool {
  385. h := key.hash().New()
  386. h.Write(data)
  387. digest := h.Sum(nil)
  388. // Per RFC 5656, section 3.1.2,
  389. // The ecdsa_signature_blob value has the following specific encoding:
  390. // mpint r
  391. // mpint s
  392. r, rest, ok := parseInt(sigBlob)
  393. if !ok {
  394. return false
  395. }
  396. s, rest, ok := parseInt(rest)
  397. if !ok || len(rest) > 0 {
  398. return false
  399. }
  400. return ecdsa.Verify((*ecdsa.PublicKey)(key), digest, r, s)
  401. }