webdavd.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. // Package webdavd implements the WebDAV protocol
  2. package webdavd
  3. import (
  4. "fmt"
  5. "net"
  6. "path/filepath"
  7. "github.com/go-chi/chi/v5/middleware"
  8. "github.com/drakkan/sftpgo/v2/common"
  9. "github.com/drakkan/sftpgo/v2/dataprovider"
  10. "github.com/drakkan/sftpgo/v2/logger"
  11. "github.com/drakkan/sftpgo/v2/util"
  12. )
  13. type ctxReqParams int
  14. const (
  15. requestIDKey ctxReqParams = iota
  16. requestStartKey
  17. )
  18. const (
  19. logSender = "webdavd"
  20. )
  21. var (
  22. certMgr *common.CertManager
  23. serviceStatus ServiceStatus
  24. )
  25. // ServiceStatus defines the service status
  26. type ServiceStatus struct {
  27. IsActive bool `json:"is_active"`
  28. Bindings []Binding `json:"bindings"`
  29. }
  30. // CorsConfig defines the CORS configuration
  31. type CorsConfig struct {
  32. AllowedOrigins []string `json:"allowed_origins" mapstructure:"allowed_origins"`
  33. AllowedMethods []string `json:"allowed_methods" mapstructure:"allowed_methods"`
  34. AllowedHeaders []string `json:"allowed_headers" mapstructure:"allowed_headers"`
  35. ExposedHeaders []string `json:"exposed_headers" mapstructure:"exposed_headers"`
  36. AllowCredentials bool `json:"allow_credentials" mapstructure:"allow_credentials"`
  37. Enabled bool `json:"enabled" mapstructure:"enabled"`
  38. MaxAge int `json:"max_age" mapstructure:"max_age"`
  39. }
  40. // UsersCacheConfig defines the cache configuration for users
  41. type UsersCacheConfig struct {
  42. ExpirationTime int `json:"expiration_time" mapstructure:"expiration_time"`
  43. MaxSize int `json:"max_size" mapstructure:"max_size"`
  44. }
  45. // MimeCacheConfig defines the cache configuration for mime types
  46. type MimeCacheConfig struct {
  47. Enabled bool `json:"enabled" mapstructure:"enabled"`
  48. MaxSize int `json:"max_size" mapstructure:"max_size"`
  49. }
  50. // Cache configuration
  51. type Cache struct {
  52. Users UsersCacheConfig `json:"users" mapstructure:"users"`
  53. MimeTypes MimeCacheConfig `json:"mime_types" mapstructure:"mime_types"`
  54. }
  55. // Binding defines the configuration for a network listener
  56. type Binding struct {
  57. // The address to listen on. A blank value means listen on all available network interfaces.
  58. Address string `json:"address" mapstructure:"address"`
  59. // The port used for serving requests
  60. Port int `json:"port" mapstructure:"port"`
  61. // you also need to provide a certificate for enabling HTTPS
  62. EnableHTTPS bool `json:"enable_https" mapstructure:"enable_https"`
  63. // Certificate and matching private key for this specific binding, if empty the global
  64. // ones will be used, if any
  65. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  66. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  67. // Defines the minimum TLS version. 13 means TLS 1.3, default is TLS 1.2
  68. MinTLSVersion int `json:"min_tls_version" mapstructure:"min_tls_version"`
  69. // set to 1 to require client certificate authentication in addition to basic auth.
  70. // You need to define at least a certificate authority for this to work
  71. ClientAuthType int `json:"client_auth_type" mapstructure:"client_auth_type"`
  72. // TLSCipherSuites is a list of supported cipher suites for TLS version 1.2.
  73. // If CipherSuites is nil/empty, a default list of secure cipher suites
  74. // is used, with a preference order based on hardware performance.
  75. // Note that TLS 1.3 ciphersuites are not configurable.
  76. // The supported ciphersuites names are defined here:
  77. //
  78. // https://github.com/golang/go/blob/master/src/crypto/tls/cipher_suites.go#L52
  79. //
  80. // any invalid name will be silently ignored.
  81. // The order matters, the ciphers listed first will be the preferred ones.
  82. TLSCipherSuites []string `json:"tls_cipher_suites" mapstructure:"tls_cipher_suites"`
  83. // Prefix for WebDAV resources, if empty WebDAV resources will be available at the
  84. // root ("/") URI. If defined it must be an absolute URI.
  85. Prefix string `json:"prefix" mapstructure:"prefix"`
  86. // List of IP addresses and IP ranges allowed to set client IP proxy headers
  87. ProxyAllowed []string `json:"proxy_allowed" mapstructure:"proxy_allowed"`
  88. // Allowed client IP proxy header such as "X-Forwarded-For", "X-Real-IP"
  89. ClientIPProxyHeader string `json:"client_ip_proxy_header" mapstructure:"client_ip_proxy_header"`
  90. // Some client IP headers such as "X-Forwarded-For" can contain multiple IP address, this setting
  91. // define the position to trust starting from the right. For example if we have:
  92. // "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"
  93. // as client IP, if depth is 1, "12.0.0.1" will be used and so on
  94. ClientIPHeaderDepth int `json:"client_ip_header_depth" mapstructure:"client_ip_header_depth"`
  95. allowHeadersFrom []func(net.IP) bool
  96. }
  97. func (b *Binding) parseAllowedProxy() error {
  98. allowedFuncs, err := util.ParseAllowedIPAndRanges(b.ProxyAllowed)
  99. if err != nil {
  100. return err
  101. }
  102. b.allowHeadersFrom = allowedFuncs
  103. return nil
  104. }
  105. func (b *Binding) isMutualTLSEnabled() bool {
  106. return b.ClientAuthType == 1 || b.ClientAuthType == 2
  107. }
  108. // GetAddress returns the binding address
  109. func (b *Binding) GetAddress() string {
  110. return fmt.Sprintf("%s:%d", b.Address, b.Port)
  111. }
  112. // IsValid returns true if the binding port is > 0
  113. func (b *Binding) IsValid() bool {
  114. return b.Port > 0
  115. }
  116. // Configuration defines the configuration for the WevDAV server
  117. type Configuration struct {
  118. // Addresses and ports to bind to
  119. Bindings []Binding `json:"bindings" mapstructure:"bindings"`
  120. // If files containing a certificate and matching private key for the server are provided you
  121. // can enable HTTPS connections for the configured bindings
  122. // Certificate and key files can be reloaded on demand sending a "SIGHUP" signal on Unix based systems and a
  123. // "paramchange" request to the running service on Windows.
  124. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  125. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  126. // CACertificates defines the set of root certificate authorities to be used to verify client certificates.
  127. CACertificates []string `json:"ca_certificates" mapstructure:"ca_certificates"`
  128. // CARevocationLists defines a set a revocation lists, one for each root CA, to be used to check
  129. // if a client certificate has been revoked
  130. CARevocationLists []string `json:"ca_revocation_lists" mapstructure:"ca_revocation_lists"`
  131. // CORS configuration
  132. Cors CorsConfig `json:"cors" mapstructure:"cors"`
  133. // Cache configuration
  134. Cache Cache `json:"cache" mapstructure:"cache"`
  135. }
  136. // GetStatus returns the server status
  137. func GetStatus() ServiceStatus {
  138. return serviceStatus
  139. }
  140. // ShouldBind returns true if there is at least a valid binding
  141. func (c *Configuration) ShouldBind() bool {
  142. for _, binding := range c.Bindings {
  143. if binding.IsValid() {
  144. return true
  145. }
  146. }
  147. return false
  148. }
  149. func (c *Configuration) getKeyPairs(configDir string) []common.TLSKeyPair {
  150. var keyPairs []common.TLSKeyPair
  151. for _, binding := range c.Bindings {
  152. certificateFile := getConfigPath(binding.CertificateFile, configDir)
  153. certificateKeyFile := getConfigPath(binding.CertificateKeyFile, configDir)
  154. if certificateFile != "" && certificateKeyFile != "" {
  155. keyPairs = append(keyPairs, common.TLSKeyPair{
  156. Cert: certificateFile,
  157. Key: certificateKeyFile,
  158. ID: binding.GetAddress(),
  159. })
  160. }
  161. }
  162. certificateFile := getConfigPath(c.CertificateFile, configDir)
  163. certificateKeyFile := getConfigPath(c.CertificateKeyFile, configDir)
  164. if certificateFile != "" && certificateKeyFile != "" {
  165. keyPairs = append(keyPairs, common.TLSKeyPair{
  166. Cert: certificateFile,
  167. Key: certificateKeyFile,
  168. ID: common.DefaultTLSKeyPaidID,
  169. })
  170. }
  171. return keyPairs
  172. }
  173. // Initialize configures and starts the WebDAV server
  174. func (c *Configuration) Initialize(configDir string) error {
  175. logger.Info(logSender, "", "initializing WebDAV server with config %+v", *c)
  176. mimeTypeCache = mimeCache{
  177. maxSize: c.Cache.MimeTypes.MaxSize,
  178. mimeTypes: make(map[string]string),
  179. }
  180. if !c.Cache.MimeTypes.Enabled {
  181. mimeTypeCache.maxSize = 0
  182. }
  183. if !c.ShouldBind() {
  184. return common.ErrNoBinding
  185. }
  186. keyPairs := c.getKeyPairs(configDir)
  187. if len(keyPairs) > 0 {
  188. mgr, err := common.NewCertManager(keyPairs, configDir, logSender)
  189. if err != nil {
  190. return err
  191. }
  192. mgr.SetCACertificates(c.CACertificates)
  193. if err := mgr.LoadRootCAs(); err != nil {
  194. return err
  195. }
  196. mgr.SetCARevocationLists(c.CARevocationLists)
  197. if err := mgr.LoadCRLs(); err != nil {
  198. return err
  199. }
  200. certMgr = mgr
  201. }
  202. compressor := middleware.NewCompressor(5, "text/*")
  203. dataprovider.InitializeWebDAVUserCache(c.Cache.Users.MaxSize)
  204. serviceStatus = ServiceStatus{
  205. Bindings: nil,
  206. }
  207. exitChannel := make(chan error, 1)
  208. for _, binding := range c.Bindings {
  209. if !binding.IsValid() {
  210. continue
  211. }
  212. if err := binding.parseAllowedProxy(); err != nil {
  213. return err
  214. }
  215. go func(binding Binding) {
  216. server := webDavServer{
  217. config: c,
  218. binding: binding,
  219. }
  220. exitChannel <- server.listenAndServe(compressor)
  221. }(binding)
  222. }
  223. serviceStatus.IsActive = true
  224. return <-exitChannel
  225. }
  226. // ReloadCertificateMgr reloads the certificate manager
  227. func ReloadCertificateMgr() error {
  228. if certMgr != nil {
  229. return certMgr.Reload()
  230. }
  231. return nil
  232. }
  233. func getConfigPath(name, configDir string) string {
  234. if !util.IsFileInputValid(name) {
  235. return ""
  236. }
  237. if name != "" && !filepath.IsAbs(name) {
  238. return filepath.Join(configDir, name)
  239. }
  240. return name
  241. }