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