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.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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/models/db"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/process"
  19. "code.gitea.io/gitea/modules/setting"
  20. "code.gitea.io/gitea/modules/util"
  21. "golang.org/x/crypto/ssh"
  22. )
  23. // ____ __. __________
  24. // | |/ _|____ ___.__. \______ \_____ _______ ______ ___________
  25. // | <_/ __ < | | | ___/\__ \\_ __ \/ ___// __ \_ __ \
  26. // | | \ ___/\___ | | | / __ \| | \/\___ \\ ___/| | \/
  27. // |____|__ \___ > ____| |____| (____ /__| /____ >\___ >__|
  28. // \/ \/\/ \/ \/ \/
  29. //
  30. // This file contains functions for parsing ssh-keys
  31. //
  32. // TODO: Consider if these functions belong in models - no other models function call them or are called by them
  33. // They may belong in a service or a module
  34. const ssh2keyStart = "---- BEGIN SSH2 PUBLIC KEY ----"
  35. func extractTypeFromBase64Key(key string) (string, error) {
  36. b, err := base64.StdEncoding.DecodeString(key)
  37. if err != nil || len(b) < 4 {
  38. return "", fmt.Errorf("invalid key format: %w", err)
  39. }
  40. keyLength := int(binary.BigEndian.Uint32(b))
  41. if len(b) < 4+keyLength {
  42. return "", fmt.Errorf("invalid key format: not enough length %d", keyLength)
  43. }
  44. return string(b[4 : 4+keyLength]), nil
  45. }
  46. // parseKeyString parses any key string in OpenSSH or SSH2 format to clean OpenSSH string (RFC4253).
  47. func parseKeyString(content string) (string, error) {
  48. // remove whitespace at start and end
  49. content = strings.TrimSpace(content)
  50. var keyType, keyContent, keyComment string
  51. if strings.HasPrefix(content, ssh2keyStart) {
  52. // Parse SSH2 file format.
  53. // Transform all legal line endings to a single "\n".
  54. content = strings.NewReplacer("\r\n", "\n", "\r", "\n").Replace(content)
  55. lines := strings.Split(content, "\n")
  56. continuationLine := false
  57. for _, line := range lines {
  58. // Skip lines that:
  59. // 1) are a continuation of the previous line,
  60. // 2) contain ":" as that are comment lines
  61. // 3) contain "-" as that are begin and end tags
  62. if continuationLine || strings.ContainsAny(line, ":-") {
  63. continuationLine = strings.HasSuffix(line, "\\")
  64. } else {
  65. keyContent += line
  66. }
  67. }
  68. t, err := extractTypeFromBase64Key(keyContent)
  69. if err != nil {
  70. return "", fmt.Errorf("extractTypeFromBase64Key: %w", err)
  71. }
  72. keyType = t
  73. } else {
  74. if strings.Contains(content, "-----BEGIN") {
  75. // Convert PEM Keys to OpenSSH format
  76. // Transform all legal line endings to a single "\n".
  77. content = strings.NewReplacer("\r\n", "\n", "\r", "\n").Replace(content)
  78. block, _ := pem.Decode([]byte(content))
  79. if block == nil {
  80. return "", fmt.Errorf("failed to parse PEM block containing the public key")
  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. if setting.SSH.Disabled {
  136. return "", db.ErrSSHDisabled{}
  137. }
  138. content, err = parseKeyString(content)
  139. if err != nil {
  140. return "", err
  141. }
  142. content = strings.TrimRight(content, "\n\r")
  143. if strings.ContainsAny(content, "\n\r") {
  144. return "", util.NewInvalidArgumentErrorf("only a single line with a single key please")
  145. }
  146. // remove any unnecessary whitespace now
  147. content = strings.TrimSpace(content)
  148. if !setting.SSH.MinimumKeySizeCheck {
  149. return content, nil
  150. }
  151. var (
  152. fnName string
  153. keyType string
  154. length int
  155. )
  156. if setting.SSH.StartBuiltinServer {
  157. fnName = "SSHNativeParsePublicKey"
  158. keyType, length, err = SSHNativeParsePublicKey(content)
  159. } else {
  160. fnName = "SSHKeyGenParsePublicKey"
  161. keyType, length, err = SSHKeyGenParsePublicKey(content)
  162. }
  163. if err != nil {
  164. return "", fmt.Errorf("%s: %w", fnName, err)
  165. }
  166. log.Trace("Key info [native: %v]: %s-%d", setting.SSH.StartBuiltinServer, keyType, length)
  167. if minLen, found := setting.SSH.MinimumKeySizes[keyType]; found && length >= minLen {
  168. return content, nil
  169. } else if found && length < minLen {
  170. return "", fmt.Errorf("key length is not enough: got %d, needs %d", length, minLen)
  171. }
  172. return "", fmt.Errorf("key type is not allowed: %s", keyType)
  173. }
  174. // SSHNativeParsePublicKey extracts the key type and length using the golang SSH library.
  175. func SSHNativeParsePublicKey(keyLine string) (string, int, error) {
  176. fields := strings.Fields(keyLine)
  177. if len(fields) < 2 {
  178. return "", 0, fmt.Errorf("not enough fields in public key line: %s", keyLine)
  179. }
  180. raw, err := base64.StdEncoding.DecodeString(fields[1])
  181. if err != nil {
  182. return "", 0, err
  183. }
  184. pkey, err := ssh.ParsePublicKey(raw)
  185. if err != nil {
  186. if strings.Contains(err.Error(), "ssh: unknown key algorithm") {
  187. return "", 0, ErrKeyUnableVerify{err.Error()}
  188. }
  189. return "", 0, fmt.Errorf("ParsePublicKey: %w", err)
  190. }
  191. // The ssh library can parse the key, so next we find out what key exactly we have.
  192. switch pkey.Type() {
  193. case ssh.KeyAlgoDSA:
  194. rawPub := struct {
  195. Name string
  196. P, Q, G, Y *big.Int
  197. }{}
  198. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  199. return "", 0, err
  200. }
  201. // as per https://bugzilla.mindrot.org/show_bug.cgi?id=1647 we should never
  202. // see dsa keys != 1024 bit, but as it seems to work, we will not check here
  203. return "dsa", rawPub.P.BitLen(), nil // use P as per crypto/dsa/dsa.go (is L)
  204. case ssh.KeyAlgoRSA:
  205. rawPub := struct {
  206. Name string
  207. E *big.Int
  208. N *big.Int
  209. }{}
  210. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  211. return "", 0, err
  212. }
  213. return "rsa", rawPub.N.BitLen(), nil // use N as per crypto/rsa/rsa.go (is bits)
  214. case ssh.KeyAlgoECDSA256:
  215. return "ecdsa", 256, nil
  216. case ssh.KeyAlgoECDSA384:
  217. return "ecdsa", 384, nil
  218. case ssh.KeyAlgoECDSA521:
  219. return "ecdsa", 521, nil
  220. case ssh.KeyAlgoED25519:
  221. return "ed25519", 256, nil
  222. case ssh.KeyAlgoSKECDSA256:
  223. return "ecdsa-sk", 256, nil
  224. case ssh.KeyAlgoSKED25519:
  225. return "ed25519-sk", 256, nil
  226. }
  227. return "", 0, fmt.Errorf("unsupported key length detection for type: %s", pkey.Type())
  228. }
  229. // writeTmpKeyFile writes key content to a temporary file
  230. // and returns the name of that file, along with any possible errors.
  231. func writeTmpKeyFile(content string) (string, error) {
  232. tmpFile, err := os.CreateTemp(setting.SSH.KeyTestPath, "gitea_keytest")
  233. if err != nil {
  234. return "", fmt.Errorf("TempFile: %w", err)
  235. }
  236. defer tmpFile.Close()
  237. if _, err = tmpFile.WriteString(content); err != nil {
  238. return "", fmt.Errorf("WriteString: %w", err)
  239. }
  240. return tmpFile.Name(), nil
  241. }
  242. // SSHKeyGenParsePublicKey extracts key type and length using ssh-keygen.
  243. func SSHKeyGenParsePublicKey(key string) (string, int, error) {
  244. tmpName, err := writeTmpKeyFile(key)
  245. if err != nil {
  246. return "", 0, fmt.Errorf("writeTmpKeyFile: %w", err)
  247. }
  248. defer func() {
  249. if err := util.Remove(tmpName); err != nil {
  250. log.Warn("Unable to remove temporary key file: %s: Error: %v", tmpName, err)
  251. }
  252. }()
  253. stdout, stderr, err := process.GetManager().Exec("SSHKeyGenParsePublicKey", setting.SSH.KeygenPath, "-lf", tmpName)
  254. if err != nil {
  255. return "", 0, fmt.Errorf("fail to parse public key: %s - %s", err, stderr)
  256. }
  257. if strings.Contains(stdout, "is not a public key file") {
  258. return "", 0, ErrKeyUnableVerify{stdout}
  259. }
  260. fields := strings.Split(stdout, " ")
  261. if len(fields) < 4 {
  262. return "", 0, fmt.Errorf("invalid public key line: %s", stdout)
  263. }
  264. keyType := strings.Trim(fields[len(fields)-1], "()\r\n")
  265. length, err := strconv.ParseInt(fields[0], 10, 32)
  266. if err != nil {
  267. return "", 0, err
  268. }
  269. return strings.ToLower(keyType), int(length), nil
  270. }