keys.go 6.8 KB

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