gitea源码

ssh_key_parse.go 7.5KB

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