webdavd.go 11 KB

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