webdavd.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. allowHeadersFrom []func(net.IP) bool
  112. }
  113. func (b *Binding) parseAllowedProxy() error {
  114. if filepath.IsAbs(b.Address) && len(b.ProxyAllowed) > 0 {
  115. // unix domain socket
  116. b.allowHeadersFrom = []func(net.IP) bool{func(ip net.IP) bool { return true }}
  117. return nil
  118. }
  119. allowedFuncs, err := util.ParseAllowedIPAndRanges(b.ProxyAllowed)
  120. if err != nil {
  121. return err
  122. }
  123. b.allowHeadersFrom = allowedFuncs
  124. return nil
  125. }
  126. func (b *Binding) isMutualTLSEnabled() bool {
  127. return b.ClientAuthType == 1 || b.ClientAuthType == 2
  128. }
  129. // GetAddress returns the binding address
  130. func (b *Binding) GetAddress() string {
  131. return fmt.Sprintf("%s:%d", b.Address, b.Port)
  132. }
  133. // IsValid returns true if the binding port is > 0
  134. func (b *Binding) IsValid() bool {
  135. return b.Port > 0
  136. }
  137. // Configuration defines the configuration for the WevDAV server
  138. type Configuration struct {
  139. // Addresses and ports to bind to
  140. Bindings []Binding `json:"bindings" mapstructure:"bindings"`
  141. // If files containing a certificate and matching private key for the server are provided you
  142. // can enable HTTPS connections for the configured bindings
  143. // Certificate and key files can be reloaded on demand sending a "SIGHUP" signal on Unix based systems and a
  144. // "paramchange" request to the running service on Windows.
  145. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  146. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  147. // CACertificates defines the set of root certificate authorities to be used to verify client certificates.
  148. CACertificates []string `json:"ca_certificates" mapstructure:"ca_certificates"`
  149. // CARevocationLists defines a set a revocation lists, one for each root CA, to be used to check
  150. // if a client certificate has been revoked
  151. CARevocationLists []string `json:"ca_revocation_lists" mapstructure:"ca_revocation_lists"`
  152. // CORS configuration
  153. Cors CorsConfig `json:"cors" mapstructure:"cors"`
  154. // Cache configuration
  155. Cache Cache `json:"cache" mapstructure:"cache"`
  156. }
  157. // GetStatus returns the server status
  158. func GetStatus() ServiceStatus {
  159. return serviceStatus
  160. }
  161. // ShouldBind returns true if there is at least a valid binding
  162. func (c *Configuration) ShouldBind() bool {
  163. for _, binding := range c.Bindings {
  164. if binding.IsValid() {
  165. return true
  166. }
  167. }
  168. return false
  169. }
  170. func (c *Configuration) getKeyPairs(configDir string) []common.TLSKeyPair {
  171. var keyPairs []common.TLSKeyPair
  172. for _, binding := range c.Bindings {
  173. certificateFile := getConfigPath(binding.CertificateFile, configDir)
  174. certificateKeyFile := getConfigPath(binding.CertificateKeyFile, configDir)
  175. if certificateFile != "" && certificateKeyFile != "" {
  176. keyPairs = append(keyPairs, common.TLSKeyPair{
  177. Cert: certificateFile,
  178. Key: certificateKeyFile,
  179. ID: binding.GetAddress(),
  180. })
  181. }
  182. }
  183. certificateFile := getConfigPath(c.CertificateFile, configDir)
  184. certificateKeyFile := getConfigPath(c.CertificateKeyFile, configDir)
  185. if certificateFile != "" && certificateKeyFile != "" {
  186. keyPairs = append(keyPairs, common.TLSKeyPair{
  187. Cert: certificateFile,
  188. Key: certificateKeyFile,
  189. ID: common.DefaultTLSKeyPaidID,
  190. })
  191. }
  192. return keyPairs
  193. }
  194. // Initialize configures and starts the WebDAV server
  195. func (c *Configuration) Initialize(configDir string) error {
  196. logger.Info(logSender, "", "initializing WebDAV server with config %+v", *c)
  197. mimeTypeCache = mimeCache{
  198. maxSize: c.Cache.MimeTypes.MaxSize,
  199. mimeTypes: make(map[string]string),
  200. }
  201. if !c.Cache.MimeTypes.Enabled {
  202. mimeTypeCache.maxSize = 0
  203. }
  204. if !c.ShouldBind() {
  205. return common.ErrNoBinding
  206. }
  207. keyPairs := c.getKeyPairs(configDir)
  208. if len(keyPairs) > 0 {
  209. mgr, err := common.NewCertManager(keyPairs, configDir, logSender)
  210. if err != nil {
  211. return err
  212. }
  213. mgr.SetCACertificates(c.CACertificates)
  214. if err := mgr.LoadRootCAs(); err != nil {
  215. return err
  216. }
  217. mgr.SetCARevocationLists(c.CARevocationLists)
  218. if err := mgr.LoadCRLs(); err != nil {
  219. return err
  220. }
  221. certMgr = mgr
  222. }
  223. compressor := middleware.NewCompressor(5, "text/*")
  224. dataprovider.InitializeWebDAVUserCache(c.Cache.Users.MaxSize)
  225. serviceStatus = ServiceStatus{
  226. Bindings: nil,
  227. }
  228. exitChannel := make(chan error, 1)
  229. for _, binding := range c.Bindings {
  230. if !binding.IsValid() {
  231. continue
  232. }
  233. if err := binding.parseAllowedProxy(); err != nil {
  234. return err
  235. }
  236. go func(binding Binding) {
  237. server := webDavServer{
  238. config: c,
  239. binding: binding,
  240. }
  241. exitChannel <- server.listenAndServe(compressor)
  242. }(binding)
  243. }
  244. serviceStatus.IsActive = true
  245. return <-exitChannel
  246. }
  247. // ReloadCertificateMgr reloads the certificate manager
  248. func ReloadCertificateMgr() error {
  249. if certMgr != nil {
  250. return certMgr.Reload()
  251. }
  252. return nil
  253. }
  254. func getConfigPath(name, configDir string) string {
  255. if !util.IsFileInputValid(name) {
  256. return ""
  257. }
  258. if name != "" && !filepath.IsAbs(name) {
  259. return filepath.Join(configDir, name)
  260. }
  261. return name
  262. }