gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package cmd
  4. import (
  5. "crypto/x509"
  6. "encoding/pem"
  7. "fmt"
  8. "net/http"
  9. "os"
  10. "strconv"
  11. "strings"
  12. "code.gitea.io/gitea/modules/graceful"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/process"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/util"
  17. "github.com/caddyserver/certmagic"
  18. )
  19. func getCARoot(path string) (*x509.CertPool, error) {
  20. r, err := os.ReadFile(path)
  21. if err != nil {
  22. return nil, err
  23. }
  24. block, _ := pem.Decode(r)
  25. if block == nil {
  26. return nil, fmt.Errorf("no PEM found in the file %s", path)
  27. }
  28. caRoot, err := x509.ParseCertificate(block.Bytes)
  29. if err != nil {
  30. return nil, err
  31. }
  32. certPool := x509.NewCertPool()
  33. certPool.AddCert(caRoot)
  34. return certPool, nil
  35. }
  36. func runACME(listenAddr string, m http.Handler) error {
  37. // If HTTP Challenge enabled, needs to be serving on port 80. For TLSALPN needs 443.
  38. // Due to docker port mapping this can't be checked programmatically
  39. // TODO: these are placeholders until we add options for each in settings with appropriate warning
  40. enableHTTPChallenge := true
  41. enableTLSALPNChallenge := true
  42. altHTTPPort := 0
  43. altTLSALPNPort := 0
  44. if p, err := strconv.Atoi(setting.PortToRedirect); err == nil {
  45. altHTTPPort = p
  46. }
  47. if p, err := strconv.Atoi(setting.HTTPPort); err == nil {
  48. altTLSALPNPort = p
  49. }
  50. // Try to use private CA root if provided, otherwise defaults to system's trust
  51. var certPool *x509.CertPool
  52. if setting.AcmeCARoot != "" {
  53. var err error
  54. certPool, err = getCARoot(setting.AcmeCARoot)
  55. if err != nil {
  56. log.Warn("Failed to parse CA Root certificate, using default CA trust: %v", err)
  57. }
  58. }
  59. // FIXME: this path is not right, it uses "AppWorkPath" incorrectly, and writes the data into "AppWorkPath/https"
  60. // Ideally it should migrate to AppDataPath write to "AppDataPath/https"
  61. // And one more thing, no idea why we should set the global default variables here
  62. // But it seems that the current ACME code needs these global variables to make renew work.
  63. // Otherwise, "renew" will use incorrect storage path
  64. oldDefaultACME := certmagic.DefaultACME
  65. certmagic.Default.Storage = &certmagic.FileStorage{Path: setting.AcmeLiveDirectory}
  66. certmagic.DefaultACME = certmagic.ACMEIssuer{
  67. // try to use the default values provided by DefaultACME
  68. CA: util.IfZero(setting.AcmeURL, oldDefaultACME.CA),
  69. TestCA: oldDefaultACME.TestCA,
  70. Logger: oldDefaultACME.Logger,
  71. HTTPProxy: oldDefaultACME.HTTPProxy,
  72. TrustedRoots: certPool,
  73. Email: setting.AcmeEmail,
  74. Agreed: setting.AcmeTOS,
  75. DisableHTTPChallenge: !enableHTTPChallenge,
  76. DisableTLSALPNChallenge: !enableTLSALPNChallenge,
  77. ListenHost: setting.HTTPAddr,
  78. AltTLSALPNPort: altTLSALPNPort,
  79. AltHTTPPort: altHTTPPort,
  80. }
  81. magic := certmagic.NewDefault()
  82. myACME := certmagic.NewACMEIssuer(magic, certmagic.DefaultACME)
  83. magic.Issuers = []certmagic.Issuer{myACME}
  84. // this obtains certificates or renews them if necessary
  85. err := magic.ManageSync(graceful.GetManager().HammerContext(), []string{setting.Domain})
  86. if err != nil {
  87. return err
  88. }
  89. tlsConfig := magic.TLSConfig()
  90. tlsConfig.NextProtos = append(tlsConfig.NextProtos, "h2")
  91. if version := toTLSVersion(setting.SSLMinimumVersion); version != 0 {
  92. tlsConfig.MinVersion = version
  93. }
  94. if version := toTLSVersion(setting.SSLMaximumVersion); version != 0 {
  95. tlsConfig.MaxVersion = version
  96. }
  97. // Set curve preferences
  98. if curves := toCurvePreferences(setting.SSLCurvePreferences); len(curves) > 0 {
  99. tlsConfig.CurvePreferences = curves
  100. }
  101. // Set cipher suites
  102. if ciphers := toTLSCiphers(setting.SSLCipherSuites); len(ciphers) > 0 {
  103. tlsConfig.CipherSuites = ciphers
  104. }
  105. if enableHTTPChallenge {
  106. go func() {
  107. _, _, finished := process.GetManager().AddTypedContext(graceful.GetManager().HammerContext(), "Web: ACME HTTP challenge server", process.SystemProcessType, true)
  108. defer finished()
  109. log.Info("Running Let's Encrypt handler on %s", setting.HTTPAddr+":"+setting.PortToRedirect)
  110. // all traffic coming into HTTP will be redirect to HTTPS automatically (LE HTTP-01 validation happens here)
  111. err := runHTTP("tcp", setting.HTTPAddr+":"+setting.PortToRedirect, "Let's Encrypt HTTP Challenge", myACME.HTTPChallengeHandler(http.HandlerFunc(runLetsEncryptFallbackHandler)), setting.RedirectorUseProxyProtocol)
  112. if err != nil {
  113. log.Fatal("Failed to start the Let's Encrypt handler on port %s: %v", setting.PortToRedirect, err)
  114. }
  115. }()
  116. }
  117. return runHTTPSWithTLSConfig("tcp", listenAddr, "Web", tlsConfig, m, setting.UseProxyProtocol, setting.ProxyProtocolTLSBridging)
  118. }
  119. func runLetsEncryptFallbackHandler(w http.ResponseWriter, r *http.Request) {
  120. if r.Method != http.MethodGet && r.Method != http.MethodHead {
  121. http.Error(w, "Use HTTPS", http.StatusBadRequest)
  122. return
  123. }
  124. // Remove the trailing slash at the end of setting.AppURL, the request
  125. // URI always contains a leading slash, which would result in a double
  126. // slash
  127. target := strings.TrimSuffix(setting.AppURL, "/") + r.URL.RequestURI()
  128. http.Redirect(w, r, target, http.StatusTemporaryRedirect)
  129. }