httpclient.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // Copyright (C) 2019-2023 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. // Package httpclient provides HTTP client configuration for SFTPGo hooks
  15. package httpclient
  16. import (
  17. "crypto/tls"
  18. "crypto/x509"
  19. "fmt"
  20. "io"
  21. "net/http"
  22. "os"
  23. "path/filepath"
  24. "strings"
  25. "time"
  26. "github.com/hashicorp/go-retryablehttp"
  27. "github.com/drakkan/sftpgo/v2/internal/logger"
  28. "github.com/drakkan/sftpgo/v2/internal/util"
  29. )
  30. // TLSKeyPair defines the paths for a TLS key pair
  31. type TLSKeyPair struct {
  32. Cert string `json:"cert" mapstructure:"cert"`
  33. Key string `json:"key" mapstructure:"key"`
  34. }
  35. // Header defines an HTTP header.
  36. // If the URL is not empty, the header is added only if the
  37. // requested URL starts with the one specified
  38. type Header struct {
  39. Key string `json:"key" mapstructure:"key"`
  40. Value string `json:"value" mapstructure:"value"`
  41. URL string `json:"url" mapstructure:"url"`
  42. }
  43. // Config defines the configuration for HTTP clients.
  44. // HTTP clients are used for executing hooks such as the ones used for
  45. // custom actions, external authentication and pre-login user modifications
  46. type Config struct {
  47. // Timeout specifies a time limit, in seconds, for a request
  48. Timeout float64 `json:"timeout" mapstructure:"timeout"`
  49. // RetryWaitMin defines the minimum waiting time between attempts in seconds
  50. RetryWaitMin int `json:"retry_wait_min" mapstructure:"retry_wait_min"`
  51. // RetryWaitMax defines the minimum waiting time between attempts in seconds
  52. RetryWaitMax int `json:"retry_wait_max" mapstructure:"retry_wait_max"`
  53. // RetryMax defines the maximum number of attempts
  54. RetryMax int `json:"retry_max" mapstructure:"retry_max"`
  55. // CACertificates defines extra CA certificates to trust.
  56. // The paths can be absolute or relative to the config dir.
  57. // Adding trusted CA certificates is a convenient way to use self-signed
  58. // certificates without defeating the purpose of using TLS
  59. CACertificates []string `json:"ca_certificates" mapstructure:"ca_certificates"`
  60. // Certificates defines the certificates to use for mutual TLS
  61. Certificates []TLSKeyPair `json:"certificates" mapstructure:"certificates"`
  62. // if enabled the HTTP client accepts any TLS certificate presented by
  63. // the server and any host name in that certificate.
  64. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  65. // This should be used only for testing.
  66. SkipTLSVerify bool `json:"skip_tls_verify" mapstructure:"skip_tls_verify"`
  67. // Headers defines a list of http headers to add to each request
  68. Headers []Header `json:"headers" mapstructure:"headers"`
  69. customTransport *http.Transport
  70. }
  71. const logSender = "httpclient"
  72. var httpConfig Config
  73. // Initialize configures HTTP clients
  74. func (c *Config) Initialize(configDir string) error {
  75. if c.Timeout <= 0 {
  76. return fmt.Errorf("invalid timeout: %v", c.Timeout)
  77. }
  78. rootCAs, err := c.loadCACerts(configDir)
  79. if err != nil {
  80. return err
  81. }
  82. customTransport := http.DefaultTransport.(*http.Transport).Clone()
  83. if customTransport.TLSClientConfig != nil {
  84. customTransport.TLSClientConfig.RootCAs = rootCAs
  85. } else {
  86. customTransport.TLSClientConfig = &tls.Config{
  87. RootCAs: rootCAs,
  88. }
  89. }
  90. customTransport.TLSClientConfig.InsecureSkipVerify = c.SkipTLSVerify
  91. c.customTransport = customTransport
  92. err = c.loadCertificates(configDir)
  93. if err != nil {
  94. return err
  95. }
  96. var headers []Header
  97. for _, h := range c.Headers {
  98. if h.Key != "" && h.Value != "" {
  99. headers = append(headers, h)
  100. }
  101. }
  102. c.Headers = headers
  103. httpConfig = *c
  104. return nil
  105. }
  106. // loadCACerts returns system cert pools and try to add the configured
  107. // CA certificates to it
  108. func (c *Config) loadCACerts(configDir string) (*x509.CertPool, error) {
  109. if len(c.CACertificates) == 0 {
  110. return nil, nil
  111. }
  112. rootCAs, err := x509.SystemCertPool()
  113. if err != nil {
  114. rootCAs = x509.NewCertPool()
  115. }
  116. for _, ca := range c.CACertificates {
  117. if !util.IsFileInputValid(ca) {
  118. return nil, fmt.Errorf("unable to load invalid CA certificate: %q", ca)
  119. }
  120. if !filepath.IsAbs(ca) {
  121. ca = filepath.Join(configDir, ca)
  122. }
  123. certs, err := os.ReadFile(ca)
  124. if err != nil {
  125. return nil, fmt.Errorf("unable to load CA certificate: %v", err)
  126. }
  127. if rootCAs.AppendCertsFromPEM(certs) {
  128. logger.Debug(logSender, "", "CA certificate %q added to the trusted certificates", ca)
  129. } else {
  130. return nil, fmt.Errorf("unable to add CA certificate %q to the trusted cetificates", ca)
  131. }
  132. }
  133. return rootCAs, nil
  134. }
  135. func (c *Config) loadCertificates(configDir string) error {
  136. if len(c.Certificates) == 0 {
  137. return nil
  138. }
  139. for _, keyPair := range c.Certificates {
  140. cert := keyPair.Cert
  141. key := keyPair.Key
  142. if !util.IsFileInputValid(cert) {
  143. return fmt.Errorf("unable to load invalid certificate: %q", cert)
  144. }
  145. if !util.IsFileInputValid(key) {
  146. return fmt.Errorf("unable to load invalid key: %q", key)
  147. }
  148. if !filepath.IsAbs(cert) {
  149. cert = filepath.Join(configDir, cert)
  150. }
  151. if !filepath.IsAbs(key) {
  152. key = filepath.Join(configDir, key)
  153. }
  154. tlsCert, err := tls.LoadX509KeyPair(cert, key)
  155. if err != nil {
  156. return fmt.Errorf("unable to load key pair %q, %q: %v", cert, key, err)
  157. }
  158. x509Cert, err := x509.ParseCertificate(tlsCert.Certificate[0])
  159. if err == nil {
  160. logger.Debug(logSender, "", "adding leaf certificate for key pair %q, %q", cert, key)
  161. tlsCert.Leaf = x509Cert
  162. }
  163. logger.Debug(logSender, "", "client certificate %q and key %q successfully loaded", cert, key)
  164. c.customTransport.TLSClientConfig.Certificates = append(c.customTransport.TLSClientConfig.Certificates, tlsCert)
  165. }
  166. return nil
  167. }
  168. // GetHTTPClient returns a new HTTP client with the configured parameters
  169. func GetHTTPClient() *http.Client {
  170. return &http.Client{
  171. Timeout: time.Duration(httpConfig.Timeout * float64(time.Second)),
  172. Transport: httpConfig.customTransport,
  173. }
  174. }
  175. // GetRetraybleHTTPClient returns an HTTP client that retry a request on error.
  176. // It uses the configured retry parameters
  177. func GetRetraybleHTTPClient() *retryablehttp.Client {
  178. client := retryablehttp.NewClient()
  179. client.HTTPClient.Timeout = time.Duration(httpConfig.Timeout * float64(time.Second))
  180. client.HTTPClient.Transport.(*http.Transport).TLSClientConfig = httpConfig.customTransport.TLSClientConfig
  181. client.Logger = &logger.LeveledLogger{Sender: "RetryableHTTPClient"}
  182. client.RetryWaitMin = time.Duration(httpConfig.RetryWaitMin) * time.Second
  183. client.RetryWaitMax = time.Duration(httpConfig.RetryWaitMax) * time.Second
  184. client.RetryMax = httpConfig.RetryMax
  185. return client
  186. }
  187. // Get issues a GET to the specified URL
  188. func Get(url string) (*http.Response, error) {
  189. req, err := http.NewRequest(http.MethodGet, url, nil)
  190. if err != nil {
  191. return nil, err
  192. }
  193. addHeaders(req, url)
  194. client := GetHTTPClient()
  195. defer client.CloseIdleConnections()
  196. return client.Do(req)
  197. }
  198. // Post issues a POST to the specified URL
  199. func Post(url string, contentType string, body io.Reader) (*http.Response, error) {
  200. req, err := http.NewRequest(http.MethodPost, url, body)
  201. if err != nil {
  202. return nil, err
  203. }
  204. req.Header.Set("Content-Type", contentType)
  205. addHeaders(req, url)
  206. client := GetHTTPClient()
  207. defer client.CloseIdleConnections()
  208. return client.Do(req)
  209. }
  210. // RetryableGet issues a GET to the specified URL using the retryable client
  211. func RetryableGet(url string) (*http.Response, error) {
  212. req, err := retryablehttp.NewRequest(http.MethodGet, url, nil)
  213. if err != nil {
  214. return nil, err
  215. }
  216. addHeadersToRetryableReq(req, url)
  217. client := GetRetraybleHTTPClient()
  218. defer client.HTTPClient.CloseIdleConnections()
  219. return client.Do(req)
  220. }
  221. // RetryablePost issues a POST to the specified URL using the retryable client
  222. func RetryablePost(url string, contentType string, body io.Reader) (*http.Response, error) {
  223. req, err := retryablehttp.NewRequest(http.MethodPost, url, body)
  224. if err != nil {
  225. return nil, err
  226. }
  227. req.Header.Set("Content-Type", contentType)
  228. addHeadersToRetryableReq(req, url)
  229. client := GetRetraybleHTTPClient()
  230. defer client.HTTPClient.CloseIdleConnections()
  231. return client.Do(req)
  232. }
  233. func addHeaders(req *http.Request, url string) {
  234. for idx := range httpConfig.Headers {
  235. h := &httpConfig.Headers[idx]
  236. if h.URL == "" || strings.HasPrefix(url, h.URL) {
  237. req.Header.Set(h.Key, h.Value)
  238. }
  239. }
  240. }
  241. func addHeadersToRetryableReq(req *retryablehttp.Request, url string) {
  242. for idx := range httpConfig.Headers {
  243. h := &httpConfig.Headers[idx]
  244. if h.URL == "" || strings.HasPrefix(url, h.URL) {
  245. req.Header.Set(h.Key, h.Value)
  246. }
  247. }
  248. }