webdavd.go 13 KB

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