You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ssh_key_parse.go 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package asymkey
  4. import (
  5. "crypto/rsa"
  6. "crypto/x509"
  7. "encoding/asn1"
  8. "encoding/base64"
  9. "encoding/binary"
  10. "encoding/pem"
  11. "fmt"
  12. "math/big"
  13. "os"
  14. "strconv"
  15. "strings"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/process"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/util"
  20. "golang.org/x/crypto/ssh"
  21. )
  22. // ____ __. __________
  23. // | |/ _|____ ___.__. \______ \_____ _______ ______ ___________
  24. // | <_/ __ < | | | ___/\__ \\_ __ \/ ___// __ \_ __ \
  25. // | | \ ___/\___ | | | / __ \| | \/\___ \\ ___/| | \/
  26. // |____|__ \___ > ____| |____| (____ /__| /____ >\___ >__|
  27. // \/ \/\/ \/ \/ \/
  28. //
  29. // This file contains functions for parsing ssh-keys
  30. //
  31. // TODO: Consider if these functions belong in models - no other models function call them or are called by them
  32. // They may belong in a service or a module
  33. const ssh2keyStart = "---- BEGIN SSH2 PUBLIC KEY ----"
  34. func extractTypeFromBase64Key(key string) (string, error) {
  35. b, err := base64.StdEncoding.DecodeString(key)
  36. if err != nil || len(b) < 4 {
  37. return "", fmt.Errorf("invalid key format: %w", err)
  38. }
  39. keyLength := int(binary.BigEndian.Uint32(b))
  40. if len(b) < 4+keyLength {
  41. return "", fmt.Errorf("invalid key format: not enough length %d", keyLength)
  42. }
  43. return string(b[4 : 4+keyLength]), nil
  44. }
  45. // parseKeyString parses any key string in OpenSSH or SSH2 format to clean OpenSSH string (RFC4253).
  46. func parseKeyString(content string) (string, error) {
  47. // remove whitespace at start and end
  48. content = strings.TrimSpace(content)
  49. var keyType, keyContent, keyComment string
  50. if strings.HasPrefix(content, ssh2keyStart) {
  51. // Parse SSH2 file format.
  52. // Transform all legal line endings to a single "\n".
  53. content = strings.NewReplacer("\r\n", "\n", "\r", "\n").Replace(content)
  54. lines := strings.Split(content, "\n")
  55. continuationLine := false
  56. for _, line := range lines {
  57. // Skip lines that:
  58. // 1) are a continuation of the previous line,
  59. // 2) contain ":" as that are comment lines
  60. // 3) contain "-" as that are begin and end tags
  61. if continuationLine || strings.ContainsAny(line, ":-") {
  62. continuationLine = strings.HasSuffix(line, "\\")
  63. } else {
  64. keyContent += line
  65. }
  66. }
  67. t, err := extractTypeFromBase64Key(keyContent)
  68. if err != nil {
  69. return "", fmt.Errorf("extractTypeFromBase64Key: %w", err)
  70. }
  71. keyType = t
  72. } else {
  73. if strings.Contains(content, "-----BEGIN") {
  74. // Convert PEM Keys to OpenSSH format
  75. // Transform all legal line endings to a single "\n".
  76. content = strings.NewReplacer("\r\n", "\n", "\r", "\n").Replace(content)
  77. block, _ := pem.Decode([]byte(content))
  78. if block == nil {
  79. return "", fmt.Errorf("failed to parse PEM block containing the public key")
  80. }
  81. if strings.Contains(block.Type, "PRIVATE") {
  82. return "", ErrKeyIsPrivate
  83. }
  84. pub, err := x509.ParsePKIXPublicKey(block.Bytes)
  85. if err != nil {
  86. var pk rsa.PublicKey
  87. _, err2 := asn1.Unmarshal(block.Bytes, &pk)
  88. if err2 != nil {
  89. return "", fmt.Errorf("failed to parse DER encoded public key as either PKIX or PEM RSA Key: %v %w", err, err2)
  90. }
  91. pub = &pk
  92. }
  93. sshKey, err := ssh.NewPublicKey(pub)
  94. if err != nil {
  95. return "", fmt.Errorf("unable to convert to ssh public key: %w", err)
  96. }
  97. content = string(ssh.MarshalAuthorizedKey(sshKey))
  98. }
  99. // Parse OpenSSH format.
  100. // Remove all newlines
  101. content = strings.NewReplacer("\r\n", "", "\n", "").Replace(content)
  102. parts := strings.SplitN(content, " ", 3)
  103. switch len(parts) {
  104. case 0:
  105. return "", util.NewInvalidArgumentErrorf("empty key")
  106. case 1:
  107. keyContent = parts[0]
  108. case 2:
  109. keyType = parts[0]
  110. keyContent = parts[1]
  111. default:
  112. keyType = parts[0]
  113. keyContent = parts[1]
  114. keyComment = parts[2]
  115. }
  116. // If keyType is not given, extract it from content. If given, validate it.
  117. t, err := extractTypeFromBase64Key(keyContent)
  118. if err != nil {
  119. return "", fmt.Errorf("extractTypeFromBase64Key: %w", err)
  120. }
  121. if len(keyType) == 0 {
  122. keyType = t
  123. } else if keyType != t {
  124. return "", fmt.Errorf("key type and content does not match: %s - %s", keyType, t)
  125. }
  126. }
  127. // Finally we need to check whether we can actually read the proposed key:
  128. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(keyType + " " + keyContent + " " + keyComment))
  129. if err != nil {
  130. return "", fmt.Errorf("invalid ssh public key: %w", err)
  131. }
  132. return keyType + " " + keyContent + " " + keyComment, nil
  133. }
  134. // CheckPublicKeyString checks if the given public key string is recognized by SSH.
  135. // It returns the actual public key line on success.
  136. func CheckPublicKeyString(content string) (_ string, err error) {
  137. content, err = parseKeyString(content)
  138. if err != nil {
  139. return "", err
  140. }
  141. content = strings.TrimRight(content, "\n\r")
  142. if strings.ContainsAny(content, "\n\r") {
  143. return "", util.NewInvalidArgumentErrorf("only a single line with a single key please")
  144. }
  145. // remove any unnecessary whitespace now
  146. content = strings.TrimSpace(content)
  147. if !setting.SSH.MinimumKeySizeCheck {
  148. return content, nil
  149. }
  150. var (
  151. fnName string
  152. keyType string
  153. length int
  154. )
  155. if len(setting.SSH.KeygenPath) == 0 {
  156. fnName = "SSHNativeParsePublicKey"
  157. keyType, length, err = SSHNativeParsePublicKey(content)
  158. } else {
  159. fnName = "SSHKeyGenParsePublicKey"
  160. keyType, length, err = SSHKeyGenParsePublicKey(content)
  161. }
  162. if err != nil {
  163. return "", fmt.Errorf("%s: %w", fnName, err)
  164. }
  165. log.Trace("Key info [native: %v]: %s-%d", setting.SSH.StartBuiltinServer, keyType, length)
  166. if minLen, found := setting.SSH.MinimumKeySizes[keyType]; found && length >= minLen {
  167. return content, nil
  168. } else if found && length < minLen {
  169. return "", fmt.Errorf("key length is not enough: got %d, needs %d", length, minLen)
  170. }
  171. return "", fmt.Errorf("key type is not allowed: %s", keyType)
  172. }
  173. // SSHNativeParsePublicKey extracts the key type and length using the golang SSH library.
  174. func SSHNativeParsePublicKey(keyLine string) (string, int, error) {
  175. fields := strings.Fields(keyLine)
  176. if len(fields) < 2 {
  177. return "", 0, fmt.Errorf("not enough fields in public key line: %s", keyLine)
  178. }
  179. raw, err := base64.StdEncoding.DecodeString(fields[1])
  180. if err != nil {
  181. return "", 0, err
  182. }
  183. pkey, err := ssh.ParsePublicKey(raw)
  184. if err != nil {
  185. if strings.Contains(err.Error(), "ssh: unknown key algorithm") {
  186. return "", 0, ErrKeyUnableVerify{err.Error()}
  187. }
  188. return "", 0, fmt.Errorf("ParsePublicKey: %w", err)
  189. }
  190. // The ssh library can parse the key, so next we find out what key exactly we have.
  191. switch pkey.Type() {
  192. case ssh.KeyAlgoDSA:
  193. rawPub := struct {
  194. Name string
  195. P, Q, G, Y *big.Int
  196. }{}
  197. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  198. return "", 0, err
  199. }
  200. // as per https://bugzilla.mindrot.org/show_bug.cgi?id=1647 we should never
  201. // see dsa keys != 1024 bit, but as it seems to work, we will not check here
  202. return "dsa", rawPub.P.BitLen(), nil // use P as per crypto/dsa/dsa.go (is L)
  203. case ssh.KeyAlgoRSA:
  204. rawPub := struct {
  205. Name string
  206. E *big.Int
  207. N *big.Int
  208. }{}
  209. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  210. return "", 0, err
  211. }
  212. return "rsa", rawPub.N.BitLen(), nil // use N as per crypto/rsa/rsa.go (is bits)
  213. case ssh.KeyAlgoECDSA256:
  214. return "ecdsa", 256, nil
  215. case ssh.KeyAlgoECDSA384:
  216. return "ecdsa", 384, nil
  217. case ssh.KeyAlgoECDSA521:
  218. return "ecdsa", 521, nil
  219. case ssh.KeyAlgoED25519:
  220. return "ed25519", 256, nil
  221. case ssh.KeyAlgoSKECDSA256:
  222. return "ecdsa-sk", 256, nil
  223. case ssh.KeyAlgoSKED25519:
  224. return "ed25519-sk", 256, nil
  225. }
  226. return "", 0, fmt.Errorf("unsupported key length detection for type: %s", pkey.Type())
  227. }
  228. // writeTmpKeyFile writes key content to a temporary file
  229. // and returns the name of that file, along with any possible errors.
  230. func writeTmpKeyFile(content string) (string, error) {
  231. tmpFile, err := os.CreateTemp(setting.SSH.KeyTestPath, "gitea_keytest")
  232. if err != nil {
  233. return "", fmt.Errorf("TempFile: %w", err)
  234. }
  235. defer tmpFile.Close()
  236. if _, err = tmpFile.WriteString(content); err != nil {
  237. return "", fmt.Errorf("WriteString: %w", err)
  238. }
  239. return tmpFile.Name(), nil
  240. }
  241. // SSHKeyGenParsePublicKey extracts key type and length using ssh-keygen.
  242. func SSHKeyGenParsePublicKey(key string) (string, int, error) {
  243. tmpName, err := writeTmpKeyFile(key)
  244. if err != nil {
  245. return "", 0, fmt.Errorf("writeTmpKeyFile: %w", err)
  246. }
  247. defer func() {
  248. if err := util.Remove(tmpName); err != nil {
  249. log.Warn("Unable to remove temporary key file: %s: Error: %v", tmpName, err)
  250. }
  251. }()
  252. keygenPath := setting.SSH.KeygenPath
  253. if len(keygenPath) == 0 {
  254. keygenPath = "ssh-keygen"
  255. }
  256. stdout, stderr, err := process.GetManager().Exec("SSHKeyGenParsePublicKey", keygenPath, "-lf", tmpName)
  257. if err != nil {
  258. return "", 0, fmt.Errorf("fail to parse public key: %s - %s", err, stderr)
  259. }
  260. if strings.Contains(stdout, "is not a public key file") {
  261. return "", 0, ErrKeyUnableVerify{stdout}
  262. }
  263. fields := strings.Split(stdout, " ")
  264. if len(fields) < 4 {
  265. return "", 0, fmt.Errorf("invalid public key line: %s", stdout)
  266. }
  267. keyType := strings.Trim(fields[len(fields)-1], "()\r\n")
  268. length, err := strconv.ParseInt(fields[0], 10, 32)
  269. if err != nil {
  270. return "", 0, err
  271. }
  272. return strings.ToLower(keyType), int(length), nil
  273. }