webdavd.go 11 KB

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