webdavd.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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#L53
  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. // HTTP protocols to enable in preference order. Supported values: http/1.1, h2
  121. Protocols []string `json:"protocols" mapstructure:"protocols"`
  122. // Prefix for WebDAV resources, if empty WebDAV resources will be available at the
  123. // root ("/") URI. If defined it must be an absolute URI.
  124. Prefix string `json:"prefix" mapstructure:"prefix"`
  125. // List of IP addresses and IP ranges allowed to set client IP proxy headers
  126. ProxyAllowed []string `json:"proxy_allowed" mapstructure:"proxy_allowed"`
  127. // Allowed client IP proxy header such as "X-Forwarded-For", "X-Real-IP"
  128. ClientIPProxyHeader string `json:"client_ip_proxy_header" mapstructure:"client_ip_proxy_header"`
  129. // Some client IP headers such as "X-Forwarded-For" can contain multiple IP address, this setting
  130. // define the position to trust starting from the right. For example if we have:
  131. // "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"
  132. // as client IP, if depth is 1, "12.0.0.1" will be used and so on
  133. ClientIPHeaderDepth int `json:"client_ip_header_depth" mapstructure:"client_ip_header_depth"`
  134. // Do not add the WWW-Authenticate header after an authentication error,
  135. // only the 401 status code will be sent
  136. DisableWWWAuthHeader bool `json:"disable_www_auth_header" mapstructure:"disable_www_auth_header"`
  137. allowHeadersFrom []func(net.IP) bool
  138. }
  139. func (b *Binding) parseAllowedProxy() error {
  140. if filepath.IsAbs(b.Address) && len(b.ProxyAllowed) > 0 {
  141. // unix domain socket
  142. b.allowHeadersFrom = []func(net.IP) bool{func(ip net.IP) bool { return true }}
  143. return nil
  144. }
  145. allowedFuncs, err := util.ParseAllowedIPAndRanges(b.ProxyAllowed)
  146. if err != nil {
  147. return err
  148. }
  149. b.allowHeadersFrom = allowedFuncs
  150. return nil
  151. }
  152. func (b *Binding) isMutualTLSEnabled() bool {
  153. return b.ClientAuthType == 1 || b.ClientAuthType == 2
  154. }
  155. // GetAddress returns the binding address
  156. func (b *Binding) GetAddress() string {
  157. return fmt.Sprintf("%s:%d", b.Address, b.Port)
  158. }
  159. // IsValid returns true if the binding port is > 0
  160. func (b *Binding) IsValid() bool {
  161. return b.Port > 0
  162. }
  163. // Configuration defines the configuration for the WevDAV server
  164. type Configuration struct {
  165. // Addresses and ports to bind to
  166. Bindings []Binding `json:"bindings" mapstructure:"bindings"`
  167. // If files containing a certificate and matching private key for the server are provided you
  168. // can enable HTTPS connections for the configured bindings
  169. // Certificate and key files can be reloaded on demand sending a "SIGHUP" signal on Unix based systems and a
  170. // "paramchange" request to the running service on Windows.
  171. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  172. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  173. // CACertificates defines the set of root certificate authorities to be used to verify client certificates.
  174. CACertificates []string `json:"ca_certificates" mapstructure:"ca_certificates"`
  175. // CARevocationLists defines a set a revocation lists, one for each root CA, to be used to check
  176. // if a client certificate has been revoked
  177. CARevocationLists []string `json:"ca_revocation_lists" mapstructure:"ca_revocation_lists"`
  178. // CORS configuration
  179. Cors CorsConfig `json:"cors" mapstructure:"cors"`
  180. // Cache configuration
  181. Cache Cache `json:"cache" mapstructure:"cache"`
  182. acmeDomain string
  183. }
  184. // GetStatus returns the server status
  185. func GetStatus() ServiceStatus {
  186. return serviceStatus
  187. }
  188. // ShouldBind returns true if there is at least a valid binding
  189. func (c *Configuration) ShouldBind() bool {
  190. for _, binding := range c.Bindings {
  191. if binding.IsValid() {
  192. return true
  193. }
  194. }
  195. return false
  196. }
  197. func (c *Configuration) getKeyPairs(configDir string) []common.TLSKeyPair {
  198. var keyPairs []common.TLSKeyPair
  199. for _, binding := range c.Bindings {
  200. certificateFile := getConfigPath(binding.CertificateFile, configDir)
  201. certificateKeyFile := getConfigPath(binding.CertificateKeyFile, configDir)
  202. if certificateFile != "" && certificateKeyFile != "" {
  203. keyPairs = append(keyPairs, common.TLSKeyPair{
  204. Cert: certificateFile,
  205. Key: certificateKeyFile,
  206. ID: binding.GetAddress(),
  207. })
  208. }
  209. }
  210. var certificateFile, certificateKeyFile string
  211. if c.acmeDomain != "" {
  212. certificateFile, certificateKeyFile = util.GetACMECertificateKeyPair(c.acmeDomain)
  213. } else {
  214. certificateFile = getConfigPath(c.CertificateFile, configDir)
  215. certificateKeyFile = getConfigPath(c.CertificateKeyFile, configDir)
  216. }
  217. if certificateFile != "" && certificateKeyFile != "" {
  218. keyPairs = append(keyPairs, common.TLSKeyPair{
  219. Cert: certificateFile,
  220. Key: certificateKeyFile,
  221. ID: common.DefaultTLSKeyPaidID,
  222. })
  223. }
  224. return keyPairs
  225. }
  226. func (c *Configuration) loadFromProvider() error {
  227. configs, err := dataprovider.GetConfigs()
  228. if err != nil {
  229. return fmt.Errorf("unable to load config from provider: %w", err)
  230. }
  231. configs.SetNilsToEmpty()
  232. if configs.ACME.Domain == "" || !configs.ACME.HasProtocol(common.ProtocolWebDAV) {
  233. return nil
  234. }
  235. crt, key := util.GetACMECertificateKeyPair(configs.ACME.Domain)
  236. if crt != "" && key != "" {
  237. if _, err := os.Stat(crt); err != nil {
  238. logger.Error(logSender, "", "unable to load acme cert file %q: %v", crt, err)
  239. return nil
  240. }
  241. if _, err := os.Stat(key); err != nil {
  242. logger.Error(logSender, "", "unable to load acme key file %q: %v", key, err)
  243. return nil
  244. }
  245. for idx := range c.Bindings {
  246. c.Bindings[idx].EnableHTTPS = true
  247. }
  248. c.acmeDomain = configs.ACME.Domain
  249. logger.Info(logSender, "", "acme domain set to %q", c.acmeDomain)
  250. return nil
  251. }
  252. return nil
  253. }
  254. // Initialize configures and starts the WebDAV server
  255. func (c *Configuration) Initialize(configDir string) error {
  256. if err := c.loadFromProvider(); err != nil {
  257. return err
  258. }
  259. logger.Info(logSender, "", "initializing WebDAV server with config %+v", *c)
  260. mimeTypeCache = mimeCache{
  261. maxSize: c.Cache.MimeTypes.MaxSize,
  262. mimeTypes: make(map[string]string),
  263. }
  264. if !c.Cache.MimeTypes.Enabled {
  265. mimeTypeCache.maxSize = 0
  266. } else {
  267. customMimeTypeMapping = make(map[string]string)
  268. for _, m := range c.Cache.MimeTypes.CustomMappings {
  269. if m.Mime != "" {
  270. logger.Debug(logSender, "", "adding custom mime mapping for extension %q, mime type %q", m.Ext, m.Mime)
  271. customMimeTypeMapping[m.Ext] = m.Mime
  272. }
  273. }
  274. }
  275. if !c.ShouldBind() {
  276. return common.ErrNoBinding
  277. }
  278. keyPairs := c.getKeyPairs(configDir)
  279. if len(keyPairs) > 0 {
  280. mgr, err := common.NewCertManager(keyPairs, configDir, logSender)
  281. if err != nil {
  282. return err
  283. }
  284. mgr.SetCACertificates(c.CACertificates)
  285. if err := mgr.LoadRootCAs(); err != nil {
  286. return err
  287. }
  288. mgr.SetCARevocationLists(c.CARevocationLists)
  289. if err := mgr.LoadCRLs(); err != nil {
  290. return err
  291. }
  292. certMgr = mgr
  293. }
  294. compressor := middleware.NewCompressor(5, "text/*")
  295. dataprovider.InitializeWebDAVUserCache(c.Cache.Users.MaxSize)
  296. serviceStatus = ServiceStatus{
  297. Bindings: nil,
  298. }
  299. exitChannel := make(chan error, 1)
  300. for _, binding := range c.Bindings {
  301. if !binding.IsValid() {
  302. continue
  303. }
  304. if err := binding.parseAllowedProxy(); err != nil {
  305. return err
  306. }
  307. go func(binding Binding) {
  308. server := webDavServer{
  309. config: c,
  310. binding: binding,
  311. }
  312. exitChannel <- server.listenAndServe(compressor)
  313. }(binding)
  314. }
  315. serviceStatus.IsActive = true
  316. return <-exitChannel
  317. }
  318. // ReloadCertificateMgr reloads the certificate manager
  319. func ReloadCertificateMgr() error {
  320. if certMgr != nil {
  321. return certMgr.Reload()
  322. }
  323. return nil
  324. }
  325. func getConfigPath(name, configDir string) string {
  326. if !util.IsFileInputValid(name) {
  327. return ""
  328. }
  329. if name != "" && !filepath.IsAbs(name) {
  330. return filepath.Join(configDir, name)
  331. }
  332. return name
  333. }
  334. func parseTime(text string) (t time.Time, err error) {
  335. for _, layout := range timeFormats {
  336. t, err = time.Parse(layout, text)
  337. if err == nil {
  338. return
  339. }
  340. }
  341. return
  342. }