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

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