webdavd.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 webdavd implements the WebDAV protocol
  15. package webdavd
  16. import (
  17. "fmt"
  18. "net"
  19. "os"
  20. "path/filepath"
  21. "github.com/go-chi/chi/v5/middleware"
  22. "github.com/drakkan/sftpgo/v2/internal/common"
  23. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  24. "github.com/drakkan/sftpgo/v2/internal/logger"
  25. "github.com/drakkan/sftpgo/v2/internal/util"
  26. )
  27. type ctxReqParams int
  28. const (
  29. requestIDKey ctxReqParams = iota
  30. requestStartKey
  31. )
  32. const (
  33. logSender = "webdavd"
  34. )
  35. var (
  36. certMgr *common.CertManager
  37. serviceStatus ServiceStatus
  38. )
  39. // ServiceStatus defines the service status
  40. type ServiceStatus struct {
  41. IsActive bool `json:"is_active"`
  42. Bindings []Binding `json:"bindings"`
  43. }
  44. // CorsConfig defines the CORS configuration
  45. type CorsConfig struct {
  46. AllowedOrigins []string `json:"allowed_origins" mapstructure:"allowed_origins"`
  47. AllowedMethods []string `json:"allowed_methods" mapstructure:"allowed_methods"`
  48. AllowedHeaders []string `json:"allowed_headers" mapstructure:"allowed_headers"`
  49. ExposedHeaders []string `json:"exposed_headers" mapstructure:"exposed_headers"`
  50. AllowCredentials bool `json:"allow_credentials" mapstructure:"allow_credentials"`
  51. Enabled bool `json:"enabled" mapstructure:"enabled"`
  52. MaxAge int `json:"max_age" mapstructure:"max_age"`
  53. OptionsPassthrough bool `json:"options_passthrough" mapstructure:"options_passthrough"`
  54. OptionsSuccessStatus int `json:"options_success_status" mapstructure:"options_success_status"`
  55. AllowPrivateNetwork bool `json:"allow_private_network" mapstructure:"allow_private_network"`
  56. }
  57. // CustomMimeMapping defines additional, user defined mime mappings
  58. type CustomMimeMapping struct {
  59. Ext string `json:"ext" mapstructure:"ext"`
  60. Mime string `json:"mime" mapstructure:"mime"`
  61. }
  62. // UsersCacheConfig defines the cache configuration for users
  63. type UsersCacheConfig struct {
  64. ExpirationTime int `json:"expiration_time" mapstructure:"expiration_time"`
  65. MaxSize int `json:"max_size" mapstructure:"max_size"`
  66. }
  67. // MimeCacheConfig defines the cache configuration for mime types
  68. type MimeCacheConfig struct {
  69. Enabled bool `json:"enabled" mapstructure:"enabled"`
  70. MaxSize int `json:"max_size" mapstructure:"max_size"`
  71. CustomMappings []CustomMimeMapping `json:"custom_mappings" mapstructure:"custom_mappings"`
  72. }
  73. // Cache configuration
  74. type Cache struct {
  75. Users UsersCacheConfig `json:"users" mapstructure:"users"`
  76. MimeTypes MimeCacheConfig `json:"mime_types" mapstructure:"mime_types"`
  77. }
  78. // Binding defines the configuration for a network listener
  79. type Binding struct {
  80. // The address to listen on. A blank value means listen on all available network interfaces.
  81. Address string `json:"address" mapstructure:"address"`
  82. // The port used for serving requests
  83. Port int `json:"port" mapstructure:"port"`
  84. // you also need to provide a certificate for enabling HTTPS
  85. EnableHTTPS bool `json:"enable_https" mapstructure:"enable_https"`
  86. // Certificate and matching private key for this specific binding, if empty the global
  87. // ones will be used, if any
  88. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  89. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  90. // Defines the minimum TLS version. 13 means TLS 1.3, default is TLS 1.2
  91. MinTLSVersion int `json:"min_tls_version" mapstructure:"min_tls_version"`
  92. // set to 1 to require client certificate authentication in addition to basic auth.
  93. // You need to define at least a certificate authority for this to work
  94. ClientAuthType int `json:"client_auth_type" mapstructure:"client_auth_type"`
  95. // TLSCipherSuites is a list of supported cipher suites for TLS version 1.2.
  96. // If CipherSuites is nil/empty, a default list of secure cipher suites
  97. // is used, with a preference order based on hardware performance.
  98. // Note that TLS 1.3 ciphersuites are not configurable.
  99. // The supported ciphersuites names are defined here:
  100. //
  101. // https://github.com/golang/go/blob/master/src/crypto/tls/cipher_suites.go#L52
  102. //
  103. // any invalid name will be silently ignored.
  104. // The order matters, the ciphers listed first will be the preferred ones.
  105. TLSCipherSuites []string `json:"tls_cipher_suites" mapstructure:"tls_cipher_suites"`
  106. // Prefix for WebDAV resources, if empty WebDAV resources will be available at the
  107. // root ("/") URI. If defined it must be an absolute URI.
  108. Prefix string `json:"prefix" mapstructure:"prefix"`
  109. // List of IP addresses and IP ranges allowed to set client IP proxy headers
  110. ProxyAllowed []string `json:"proxy_allowed" mapstructure:"proxy_allowed"`
  111. // Allowed client IP proxy header such as "X-Forwarded-For", "X-Real-IP"
  112. ClientIPProxyHeader string `json:"client_ip_proxy_header" mapstructure:"client_ip_proxy_header"`
  113. // Some client IP headers such as "X-Forwarded-For" can contain multiple IP address, this setting
  114. // define the position to trust starting from the right. For example if we have:
  115. // "10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1" and the depth is 0, SFTPGo will use "13.0.0.1"
  116. // as client IP, if depth is 1, "12.0.0.1" will be used and so on
  117. ClientIPHeaderDepth int `json:"client_ip_header_depth" mapstructure:"client_ip_header_depth"`
  118. // Do not add the WWW-Authenticate header after an authentication error,
  119. // only the 401 status code will be sent
  120. DisableWWWAuthHeader bool `json:"disable_www_auth_header" mapstructure:"disable_www_auth_header"`
  121. allowHeadersFrom []func(net.IP) bool
  122. }
  123. func (b *Binding) parseAllowedProxy() error {
  124. if filepath.IsAbs(b.Address) && len(b.ProxyAllowed) > 0 {
  125. // unix domain socket
  126. b.allowHeadersFrom = []func(net.IP) bool{func(ip net.IP) bool { return true }}
  127. return nil
  128. }
  129. allowedFuncs, err := util.ParseAllowedIPAndRanges(b.ProxyAllowed)
  130. if err != nil {
  131. return err
  132. }
  133. b.allowHeadersFrom = allowedFuncs
  134. return nil
  135. }
  136. func (b *Binding) isMutualTLSEnabled() bool {
  137. return b.ClientAuthType == 1 || b.ClientAuthType == 2
  138. }
  139. // GetAddress returns the binding address
  140. func (b *Binding) GetAddress() string {
  141. return fmt.Sprintf("%s:%d", b.Address, b.Port)
  142. }
  143. // IsValid returns true if the binding port is > 0
  144. func (b *Binding) IsValid() bool {
  145. return b.Port > 0
  146. }
  147. // Configuration defines the configuration for the WevDAV server
  148. type Configuration struct {
  149. // Addresses and ports to bind to
  150. Bindings []Binding `json:"bindings" mapstructure:"bindings"`
  151. // If files containing a certificate and matching private key for the server are provided you
  152. // can enable HTTPS connections for the configured bindings
  153. // Certificate and key files can be reloaded on demand sending a "SIGHUP" signal on Unix based systems and a
  154. // "paramchange" request to the running service on Windows.
  155. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  156. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  157. // CACertificates defines the set of root certificate authorities to be used to verify client certificates.
  158. CACertificates []string `json:"ca_certificates" mapstructure:"ca_certificates"`
  159. // CARevocationLists defines a set a revocation lists, one for each root CA, to be used to check
  160. // if a client certificate has been revoked
  161. CARevocationLists []string `json:"ca_revocation_lists" mapstructure:"ca_revocation_lists"`
  162. // CORS configuration
  163. Cors CorsConfig `json:"cors" mapstructure:"cors"`
  164. // Cache configuration
  165. Cache Cache `json:"cache" mapstructure:"cache"`
  166. acmeDomain string
  167. }
  168. // GetStatus returns the server status
  169. func GetStatus() ServiceStatus {
  170. return serviceStatus
  171. }
  172. // ShouldBind returns true if there is at least a valid binding
  173. func (c *Configuration) ShouldBind() bool {
  174. for _, binding := range c.Bindings {
  175. if binding.IsValid() {
  176. return true
  177. }
  178. }
  179. return false
  180. }
  181. func (c *Configuration) getKeyPairs(configDir string) []common.TLSKeyPair {
  182. var keyPairs []common.TLSKeyPair
  183. for _, binding := range c.Bindings {
  184. certificateFile := getConfigPath(binding.CertificateFile, configDir)
  185. certificateKeyFile := getConfigPath(binding.CertificateKeyFile, configDir)
  186. if certificateFile != "" && certificateKeyFile != "" {
  187. keyPairs = append(keyPairs, common.TLSKeyPair{
  188. Cert: certificateFile,
  189. Key: certificateKeyFile,
  190. ID: binding.GetAddress(),
  191. })
  192. }
  193. }
  194. var certificateFile, certificateKeyFile string
  195. if c.acmeDomain != "" {
  196. certificateFile, certificateKeyFile = util.GetACMECertificateKeyPair(c.acmeDomain)
  197. } else {
  198. certificateFile = getConfigPath(c.CertificateFile, configDir)
  199. certificateKeyFile = getConfigPath(c.CertificateKeyFile, configDir)
  200. }
  201. if certificateFile != "" && certificateKeyFile != "" {
  202. keyPairs = append(keyPairs, common.TLSKeyPair{
  203. Cert: certificateFile,
  204. Key: certificateKeyFile,
  205. ID: common.DefaultTLSKeyPaidID,
  206. })
  207. }
  208. return keyPairs
  209. }
  210. func (c *Configuration) loadFromProvider() error {
  211. configs, err := dataprovider.GetConfigs()
  212. if err != nil {
  213. return fmt.Errorf("unable to load config from provider: %w", err)
  214. }
  215. configs.SetNilsToEmpty()
  216. if configs.ACME.Domain == "" || !configs.ACME.HasProtocol(common.ProtocolWebDAV) {
  217. return nil
  218. }
  219. crt, key := util.GetACMECertificateKeyPair(configs.ACME.Domain)
  220. if crt != "" && key != "" {
  221. if _, err := os.Stat(crt); err != nil {
  222. logger.Error(logSender, "", "unable to load acme cert file %q: %v", crt, err)
  223. return nil
  224. }
  225. if _, err := os.Stat(key); err != nil {
  226. logger.Error(logSender, "", "unable to load acme key file %q: %v", key, err)
  227. return nil
  228. }
  229. for idx := range c.Bindings {
  230. c.Bindings[idx].EnableHTTPS = true
  231. }
  232. c.acmeDomain = configs.ACME.Domain
  233. logger.Info(logSender, "", "acme domain set to %q", c.acmeDomain)
  234. return nil
  235. }
  236. return nil
  237. }
  238. // Initialize configures and starts the WebDAV server
  239. func (c *Configuration) Initialize(configDir string) error {
  240. if err := c.loadFromProvider(); err != nil {
  241. return err
  242. }
  243. logger.Info(logSender, "", "initializing WebDAV server with config %+v", *c)
  244. mimeTypeCache = mimeCache{
  245. maxSize: c.Cache.MimeTypes.MaxSize,
  246. mimeTypes: make(map[string]string),
  247. }
  248. if !c.Cache.MimeTypes.Enabled {
  249. mimeTypeCache.maxSize = 0
  250. } else {
  251. customMimeTypeMapping = make(map[string]string)
  252. for _, m := range c.Cache.MimeTypes.CustomMappings {
  253. if m.Mime != "" {
  254. logger.Debug(logSender, "", "adding custom mime mapping for extension %q, mime type %q", m.Ext, m.Mime)
  255. customMimeTypeMapping[m.Ext] = m.Mime
  256. }
  257. }
  258. }
  259. if !c.ShouldBind() {
  260. return common.ErrNoBinding
  261. }
  262. keyPairs := c.getKeyPairs(configDir)
  263. if len(keyPairs) > 0 {
  264. mgr, err := common.NewCertManager(keyPairs, configDir, logSender)
  265. if err != nil {
  266. return err
  267. }
  268. mgr.SetCACertificates(c.CACertificates)
  269. if err := mgr.LoadRootCAs(); err != nil {
  270. return err
  271. }
  272. mgr.SetCARevocationLists(c.CARevocationLists)
  273. if err := mgr.LoadCRLs(); err != nil {
  274. return err
  275. }
  276. certMgr = mgr
  277. }
  278. compressor := middleware.NewCompressor(5, "text/*")
  279. dataprovider.InitializeWebDAVUserCache(c.Cache.Users.MaxSize)
  280. serviceStatus = ServiceStatus{
  281. Bindings: nil,
  282. }
  283. exitChannel := make(chan error, 1)
  284. for _, binding := range c.Bindings {
  285. if !binding.IsValid() {
  286. continue
  287. }
  288. if err := binding.parseAllowedProxy(); err != nil {
  289. return err
  290. }
  291. go func(binding Binding) {
  292. server := webDavServer{
  293. config: c,
  294. binding: binding,
  295. }
  296. exitChannel <- server.listenAndServe(compressor)
  297. }(binding)
  298. }
  299. serviceStatus.IsActive = true
  300. return <-exitChannel
  301. }
  302. // ReloadCertificateMgr reloads the certificate manager
  303. func ReloadCertificateMgr() error {
  304. if certMgr != nil {
  305. return certMgr.Reload()
  306. }
  307. return nil
  308. }
  309. func getConfigPath(name, configDir string) string {
  310. if !util.IsFileInputValid(name) {
  311. return ""
  312. }
  313. if name != "" && !filepath.IsAbs(name) {
  314. return filepath.Join(configDir, name)
  315. }
  316. return name
  317. }