gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package oauth2_provider
  4. import (
  5. "crypto/ecdsa"
  6. "crypto/ed25519"
  7. "crypto/elliptic"
  8. "crypto/rand"
  9. "crypto/rsa"
  10. "crypto/x509"
  11. "encoding/base64"
  12. "encoding/pem"
  13. "fmt"
  14. "math/big"
  15. "os"
  16. "path/filepath"
  17. "strings"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/setting"
  20. "code.gitea.io/gitea/modules/util"
  21. "github.com/golang-jwt/jwt/v5"
  22. )
  23. // ErrInvalidAlgorithmType represents an invalid algorithm error.
  24. type ErrInvalidAlgorithmType struct {
  25. Algorithm string
  26. }
  27. func (err ErrInvalidAlgorithmType) Error() string {
  28. return "JWT signing algorithm is not supported: " + err.Algorithm
  29. }
  30. // JWTSigningKey represents a algorithm/key pair to sign JWTs
  31. type JWTSigningKey interface {
  32. IsSymmetric() bool
  33. SigningMethod() jwt.SigningMethod
  34. SignKey() any
  35. VerifyKey() any
  36. ToJWK() (map[string]string, error)
  37. PreProcessToken(*jwt.Token)
  38. }
  39. type hmacSigningKey struct {
  40. signingMethod jwt.SigningMethod
  41. secret []byte
  42. }
  43. func (key hmacSigningKey) IsSymmetric() bool {
  44. return true
  45. }
  46. func (key hmacSigningKey) SigningMethod() jwt.SigningMethod {
  47. return key.signingMethod
  48. }
  49. func (key hmacSigningKey) SignKey() any {
  50. return key.secret
  51. }
  52. func (key hmacSigningKey) VerifyKey() any {
  53. return key.secret
  54. }
  55. func (key hmacSigningKey) ToJWK() (map[string]string, error) {
  56. return map[string]string{
  57. "kty": "oct",
  58. "alg": key.SigningMethod().Alg(),
  59. }, nil
  60. }
  61. func (key hmacSigningKey) PreProcessToken(*jwt.Token) {}
  62. type rsaSingingKey struct {
  63. signingMethod jwt.SigningMethod
  64. key *rsa.PrivateKey
  65. id string
  66. }
  67. func newRSASingingKey(signingMethod jwt.SigningMethod, key *rsa.PrivateKey) (rsaSingingKey, error) {
  68. kid, err := util.CreatePublicKeyFingerprint(key.Public().(*rsa.PublicKey))
  69. if err != nil {
  70. return rsaSingingKey{}, err
  71. }
  72. return rsaSingingKey{
  73. signingMethod,
  74. key,
  75. base64.RawURLEncoding.EncodeToString(kid),
  76. }, nil
  77. }
  78. func (key rsaSingingKey) IsSymmetric() bool {
  79. return false
  80. }
  81. func (key rsaSingingKey) SigningMethod() jwt.SigningMethod {
  82. return key.signingMethod
  83. }
  84. func (key rsaSingingKey) SignKey() any {
  85. return key.key
  86. }
  87. func (key rsaSingingKey) VerifyKey() any {
  88. return key.key.Public()
  89. }
  90. func (key rsaSingingKey) ToJWK() (map[string]string, error) {
  91. pubKey := key.key.Public().(*rsa.PublicKey)
  92. return map[string]string{
  93. "kty": "RSA",
  94. "alg": key.SigningMethod().Alg(),
  95. "kid": key.id,
  96. "e": base64.RawURLEncoding.EncodeToString(big.NewInt(int64(pubKey.E)).Bytes()),
  97. "n": base64.RawURLEncoding.EncodeToString(pubKey.N.Bytes()),
  98. }, nil
  99. }
  100. func (key rsaSingingKey) PreProcessToken(token *jwt.Token) {
  101. token.Header["kid"] = key.id
  102. }
  103. type eddsaSigningKey struct {
  104. signingMethod jwt.SigningMethod
  105. key ed25519.PrivateKey
  106. id string
  107. }
  108. func newEdDSASingingKey(signingMethod jwt.SigningMethod, key ed25519.PrivateKey) (eddsaSigningKey, error) {
  109. kid, err := util.CreatePublicKeyFingerprint(key.Public().(ed25519.PublicKey))
  110. if err != nil {
  111. return eddsaSigningKey{}, err
  112. }
  113. return eddsaSigningKey{
  114. signingMethod,
  115. key,
  116. base64.RawURLEncoding.EncodeToString(kid),
  117. }, nil
  118. }
  119. func (key eddsaSigningKey) IsSymmetric() bool {
  120. return false
  121. }
  122. func (key eddsaSigningKey) SigningMethod() jwt.SigningMethod {
  123. return key.signingMethod
  124. }
  125. func (key eddsaSigningKey) SignKey() any {
  126. return key.key
  127. }
  128. func (key eddsaSigningKey) VerifyKey() any {
  129. return key.key.Public()
  130. }
  131. func (key eddsaSigningKey) ToJWK() (map[string]string, error) {
  132. pubKey := key.key.Public().(ed25519.PublicKey)
  133. return map[string]string{
  134. "alg": key.SigningMethod().Alg(),
  135. "kid": key.id,
  136. "kty": "OKP",
  137. "crv": "Ed25519",
  138. "x": base64.RawURLEncoding.EncodeToString(pubKey),
  139. }, nil
  140. }
  141. func (key eddsaSigningKey) PreProcessToken(token *jwt.Token) {
  142. token.Header["kid"] = key.id
  143. }
  144. type ecdsaSingingKey struct {
  145. signingMethod jwt.SigningMethod
  146. key *ecdsa.PrivateKey
  147. id string
  148. }
  149. func newECDSASingingKey(signingMethod jwt.SigningMethod, key *ecdsa.PrivateKey) (ecdsaSingingKey, error) {
  150. kid, err := util.CreatePublicKeyFingerprint(key.Public().(*ecdsa.PublicKey))
  151. if err != nil {
  152. return ecdsaSingingKey{}, err
  153. }
  154. return ecdsaSingingKey{
  155. signingMethod,
  156. key,
  157. base64.RawURLEncoding.EncodeToString(kid),
  158. }, nil
  159. }
  160. func (key ecdsaSingingKey) IsSymmetric() bool {
  161. return false
  162. }
  163. func (key ecdsaSingingKey) SigningMethod() jwt.SigningMethod {
  164. return key.signingMethod
  165. }
  166. func (key ecdsaSingingKey) SignKey() any {
  167. return key.key
  168. }
  169. func (key ecdsaSingingKey) VerifyKey() any {
  170. return key.key.Public()
  171. }
  172. func (key ecdsaSingingKey) ToJWK() (map[string]string, error) {
  173. pubKey := key.key.Public().(*ecdsa.PublicKey)
  174. return map[string]string{
  175. "kty": "EC",
  176. "alg": key.SigningMethod().Alg(),
  177. "kid": key.id,
  178. "crv": pubKey.Params().Name,
  179. "x": base64.RawURLEncoding.EncodeToString(pubKey.X.Bytes()),
  180. "y": base64.RawURLEncoding.EncodeToString(pubKey.Y.Bytes()),
  181. }, nil
  182. }
  183. func (key ecdsaSingingKey) PreProcessToken(token *jwt.Token) {
  184. token.Header["kid"] = key.id
  185. }
  186. // CreateJWTSigningKey creates a signing key from an algorithm / key pair.
  187. func CreateJWTSigningKey(algorithm string, key any) (JWTSigningKey, error) {
  188. var signingMethod jwt.SigningMethod
  189. switch algorithm {
  190. case "HS256":
  191. signingMethod = jwt.SigningMethodHS256
  192. case "HS384":
  193. signingMethod = jwt.SigningMethodHS384
  194. case "HS512":
  195. signingMethod = jwt.SigningMethodHS512
  196. case "RS256":
  197. signingMethod = jwt.SigningMethodRS256
  198. case "RS384":
  199. signingMethod = jwt.SigningMethodRS384
  200. case "RS512":
  201. signingMethod = jwt.SigningMethodRS512
  202. case "ES256":
  203. signingMethod = jwt.SigningMethodES256
  204. case "ES384":
  205. signingMethod = jwt.SigningMethodES384
  206. case "ES512":
  207. signingMethod = jwt.SigningMethodES512
  208. case "EdDSA":
  209. signingMethod = jwt.SigningMethodEdDSA
  210. default:
  211. return nil, ErrInvalidAlgorithmType{algorithm}
  212. }
  213. switch signingMethod.(type) {
  214. case *jwt.SigningMethodEd25519:
  215. privateKey, ok := key.(ed25519.PrivateKey)
  216. if !ok {
  217. return nil, jwt.ErrInvalidKeyType
  218. }
  219. return newEdDSASingingKey(signingMethod, privateKey)
  220. case *jwt.SigningMethodECDSA:
  221. privateKey, ok := key.(*ecdsa.PrivateKey)
  222. if !ok {
  223. return nil, jwt.ErrInvalidKeyType
  224. }
  225. return newECDSASingingKey(signingMethod, privateKey)
  226. case *jwt.SigningMethodRSA:
  227. privateKey, ok := key.(*rsa.PrivateKey)
  228. if !ok {
  229. return nil, jwt.ErrInvalidKeyType
  230. }
  231. return newRSASingingKey(signingMethod, privateKey)
  232. default:
  233. secret, ok := key.([]byte)
  234. if !ok {
  235. return nil, jwt.ErrInvalidKeyType
  236. }
  237. return hmacSigningKey{signingMethod, secret}, nil
  238. }
  239. }
  240. // DefaultSigningKey is the default signing key for JWTs.
  241. var DefaultSigningKey JWTSigningKey
  242. // InitSigningKey creates the default signing key from settings or creates a random key.
  243. func InitSigningKey() error {
  244. var err error
  245. var key any
  246. switch setting.OAuth2.JWTSigningAlgorithm {
  247. case "HS256":
  248. fallthrough
  249. case "HS384":
  250. fallthrough
  251. case "HS512":
  252. key = setting.GetGeneralTokenSigningSecret()
  253. case "RS256":
  254. fallthrough
  255. case "RS384":
  256. fallthrough
  257. case "RS512":
  258. fallthrough
  259. case "ES256":
  260. fallthrough
  261. case "ES384":
  262. fallthrough
  263. case "ES512":
  264. fallthrough
  265. case "EdDSA":
  266. key, err = loadOrCreateAsymmetricKey()
  267. default:
  268. return ErrInvalidAlgorithmType{setting.OAuth2.JWTSigningAlgorithm}
  269. }
  270. if err != nil {
  271. return fmt.Errorf("Error while loading or creating JWT key: %w", err)
  272. }
  273. signingKey, err := CreateJWTSigningKey(setting.OAuth2.JWTSigningAlgorithm, key)
  274. if err != nil {
  275. return err
  276. }
  277. DefaultSigningKey = signingKey
  278. return nil
  279. }
  280. // loadOrCreateAsymmetricKey checks if the configured private key exists.
  281. // If it does not exist a new random key gets generated and saved on the configured path.
  282. func loadOrCreateAsymmetricKey() (any, error) {
  283. keyPath := setting.OAuth2.JWTSigningPrivateKeyFile
  284. isExist, err := util.IsExist(keyPath)
  285. if err != nil {
  286. log.Fatal("Unable to check if %s exists. Error: %v", keyPath, err)
  287. }
  288. if !isExist {
  289. err := func() error {
  290. key, err := func() (any, error) {
  291. switch {
  292. case strings.HasPrefix(setting.OAuth2.JWTSigningAlgorithm, "RS"):
  293. return rsa.GenerateKey(rand.Reader, 4096)
  294. case setting.OAuth2.JWTSigningAlgorithm == "EdDSA":
  295. _, pk, err := ed25519.GenerateKey(rand.Reader)
  296. return pk, err
  297. default:
  298. return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  299. }
  300. }()
  301. if err != nil {
  302. return err
  303. }
  304. bytes, err := x509.MarshalPKCS8PrivateKey(key)
  305. if err != nil {
  306. return err
  307. }
  308. privateKeyPEM := &pem.Block{Type: "PRIVATE KEY", Bytes: bytes}
  309. if err := os.MkdirAll(filepath.Dir(keyPath), os.ModePerm); err != nil {
  310. return err
  311. }
  312. f, err := os.OpenFile(keyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
  313. if err != nil {
  314. return err
  315. }
  316. defer func() {
  317. if err = f.Close(); err != nil {
  318. log.Error("Close: %v", err)
  319. }
  320. }()
  321. return pem.Encode(f, privateKeyPEM)
  322. }()
  323. if err != nil {
  324. log.Fatal("Error generating private key: %v", err)
  325. return nil, err
  326. }
  327. }
  328. bytes, err := os.ReadFile(keyPath)
  329. if err != nil {
  330. return nil, err
  331. }
  332. block, _ := pem.Decode(bytes)
  333. if block == nil {
  334. return nil, fmt.Errorf("no valid PEM data found in %s", keyPath)
  335. } else if block.Type != "PRIVATE KEY" {
  336. return nil, fmt.Errorf("expected PRIVATE KEY, got %s in %s", block.Type, keyPath)
  337. }
  338. return x509.ParsePKCS8PrivateKey(block.Bytes)
  339. }