httpd.go 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  1. // Copyright (C) 2019 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 httpd implements REST API and Web interface for SFTPGo.
  15. // The OpenAPI 3 schema for the supported API can be found inside the source tree:
  16. // https://github.com/drakkan/sftpgo/blob/main/openapi/openapi.yaml
  17. package httpd
  18. import (
  19. "crypto/sha256"
  20. "errors"
  21. "fmt"
  22. "net"
  23. "net/http"
  24. "os"
  25. "path"
  26. "path/filepath"
  27. "runtime"
  28. "strings"
  29. "sync"
  30. "time"
  31. "github.com/go-chi/chi/v5"
  32. "github.com/drakkan/sftpgo/v2/internal/acme"
  33. "github.com/drakkan/sftpgo/v2/internal/common"
  34. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  35. "github.com/drakkan/sftpgo/v2/internal/ftpd"
  36. "github.com/drakkan/sftpgo/v2/internal/logger"
  37. "github.com/drakkan/sftpgo/v2/internal/mfa"
  38. "github.com/drakkan/sftpgo/v2/internal/sftpd"
  39. "github.com/drakkan/sftpgo/v2/internal/util"
  40. "github.com/drakkan/sftpgo/v2/internal/webdavd"
  41. )
  42. const (
  43. logSender = "httpd"
  44. tokenPath = "/api/v2/token"
  45. logoutPath = "/api/v2/logout"
  46. userTokenPath = "/api/v2/user/token"
  47. userLogoutPath = "/api/v2/user/logout"
  48. activeConnectionsPath = "/api/v2/connections"
  49. quotasBasePath = "/api/v2/quotas"
  50. userPath = "/api/v2/users"
  51. versionPath = "/api/v2/version"
  52. folderPath = "/api/v2/folders"
  53. groupPath = "/api/v2/groups"
  54. serverStatusPath = "/api/v2/status"
  55. dumpDataPath = "/api/v2/dumpdata"
  56. loadDataPath = "/api/v2/loaddata"
  57. defenderHosts = "/api/v2/defender/hosts"
  58. adminPath = "/api/v2/admins"
  59. adminPwdPath = "/api/v2/admin/changepwd"
  60. adminProfilePath = "/api/v2/admin/profile"
  61. userPwdPath = "/api/v2/user/changepwd"
  62. userDirsPath = "/api/v2/user/dirs"
  63. userFilesPath = "/api/v2/user/files"
  64. userFileActionsPath = "/api/v2/user/file-actions"
  65. userStreamZipPath = "/api/v2/user/streamzip"
  66. userUploadFilePath = "/api/v2/user/files/upload"
  67. userFilesDirsMetadataPath = "/api/v2/user/files/metadata"
  68. apiKeysPath = "/api/v2/apikeys"
  69. adminTOTPConfigsPath = "/api/v2/admin/totp/configs"
  70. adminTOTPGeneratePath = "/api/v2/admin/totp/generate"
  71. adminTOTPValidatePath = "/api/v2/admin/totp/validate"
  72. adminTOTPSavePath = "/api/v2/admin/totp/save"
  73. admin2FARecoveryCodesPath = "/api/v2/admin/2fa/recoverycodes"
  74. userTOTPConfigsPath = "/api/v2/user/totp/configs"
  75. userTOTPGeneratePath = "/api/v2/user/totp/generate"
  76. userTOTPValidatePath = "/api/v2/user/totp/validate"
  77. userTOTPSavePath = "/api/v2/user/totp/save"
  78. user2FARecoveryCodesPath = "/api/v2/user/2fa/recoverycodes"
  79. userProfilePath = "/api/v2/user/profile"
  80. userSharesPath = "/api/v2/user/shares"
  81. retentionBasePath = "/api/v2/retention/users"
  82. retentionChecksPath = "/api/v2/retention/users/checks"
  83. fsEventsPath = "/api/v2/events/fs"
  84. providerEventsPath = "/api/v2/events/provider"
  85. logEventsPath = "/api/v2/events/logs"
  86. sharesPath = "/api/v2/shares"
  87. eventActionsPath = "/api/v2/eventactions"
  88. eventRulesPath = "/api/v2/eventrules"
  89. rolesPath = "/api/v2/roles"
  90. ipListsPath = "/api/v2/iplists"
  91. healthzPath = "/healthz"
  92. webRootPathDefault = "/"
  93. webBasePathDefault = "/web"
  94. webBasePathAdminDefault = "/web/admin"
  95. webBasePathClientDefault = "/web/client"
  96. webAdminSetupPathDefault = "/web/admin/setup"
  97. webAdminLoginPathDefault = "/web/admin/login"
  98. webAdminOIDCLoginPathDefault = "/web/admin/oidclogin"
  99. webOIDCRedirectPathDefault = "/web/oidc/redirect"
  100. webOAuth2RedirectPathDefault = "/web/oauth2/redirect"
  101. webOAuth2TokenPathDefault = "/web/admin/oauth2/token"
  102. webAdminTwoFactorPathDefault = "/web/admin/twofactor"
  103. webAdminTwoFactorRecoveryPathDefault = "/web/admin/twofactor-recovery"
  104. webLogoutPathDefault = "/web/admin/logout"
  105. webUsersPathDefault = "/web/admin/users"
  106. webUserPathDefault = "/web/admin/user"
  107. webConnectionsPathDefault = "/web/admin/connections"
  108. webFoldersPathDefault = "/web/admin/folders"
  109. webFolderPathDefault = "/web/admin/folder"
  110. webGroupsPathDefault = "/web/admin/groups"
  111. webGroupPathDefault = "/web/admin/group"
  112. webStatusPathDefault = "/web/admin/status"
  113. webAdminsPathDefault = "/web/admin/managers"
  114. webAdminPathDefault = "/web/admin/manager"
  115. webMaintenancePathDefault = "/web/admin/maintenance"
  116. webBackupPathDefault = "/web/admin/backup"
  117. webRestorePathDefault = "/web/admin/restore"
  118. webScanVFolderPathDefault = "/web/admin/quotas/scanfolder"
  119. webQuotaScanPathDefault = "/web/admin/quotas/scanuser"
  120. webChangeAdminPwdPathDefault = "/web/admin/changepwd"
  121. webAdminForgotPwdPathDefault = "/web/admin/forgot-password"
  122. webAdminResetPwdPathDefault = "/web/admin/reset-password"
  123. webAdminProfilePathDefault = "/web/admin/profile"
  124. webAdminMFAPathDefault = "/web/admin/mfa"
  125. webAdminEventRulesPathDefault = "/web/admin/eventrules"
  126. webAdminEventRulePathDefault = "/web/admin/eventrule"
  127. webAdminEventActionsPathDefault = "/web/admin/eventactions"
  128. webAdminEventActionPathDefault = "/web/admin/eventaction"
  129. webAdminRolesPathDefault = "/web/admin/roles"
  130. webAdminRolePathDefault = "/web/admin/role"
  131. webAdminTOTPGeneratePathDefault = "/web/admin/totp/generate"
  132. webAdminTOTPValidatePathDefault = "/web/admin/totp/validate"
  133. webAdminTOTPSavePathDefault = "/web/admin/totp/save"
  134. webAdminRecoveryCodesPathDefault = "/web/admin/recoverycodes"
  135. webTemplateUserDefault = "/web/admin/template/user"
  136. webTemplateFolderDefault = "/web/admin/template/folder"
  137. webDefenderPathDefault = "/web/admin/defender"
  138. webIPListsPathDefault = "/web/admin/ip-lists"
  139. webIPListPathDefault = "/web/admin/ip-list"
  140. webDefenderHostsPathDefault = "/web/admin/defender/hosts"
  141. webEventsPathDefault = "/web/admin/events"
  142. webEventsFsSearchPathDefault = "/web/admin/events/fs"
  143. webEventsProviderSearchPathDefault = "/web/admin/events/provider"
  144. webEventsLogSearchPathDefault = "/web/admin/events/logs"
  145. webConfigsPathDefault = "/web/admin/configs"
  146. webClientLoginPathDefault = "/web/client/login"
  147. webClientOIDCLoginPathDefault = "/web/client/oidclogin"
  148. webClientTwoFactorPathDefault = "/web/client/twofactor"
  149. webClientTwoFactorRecoveryPathDefault = "/web/client/twofactor-recovery"
  150. webClientFilesPathDefault = "/web/client/files"
  151. webClientFilePathDefault = "/web/client/file"
  152. webClientFileActionsPathDefault = "/web/client/file-actions"
  153. webClientSharesPathDefault = "/web/client/shares"
  154. webClientSharePathDefault = "/web/client/share"
  155. webClientEditFilePathDefault = "/web/client/editfile"
  156. webClientDirsPathDefault = "/web/client/dirs"
  157. webClientDownloadZipPathDefault = "/web/client/downloadzip"
  158. webClientProfilePathDefault = "/web/client/profile"
  159. webClientPingPathDefault = "/web/client/ping"
  160. webClientMFAPathDefault = "/web/client/mfa"
  161. webClientTOTPGeneratePathDefault = "/web/client/totp/generate"
  162. webClientTOTPValidatePathDefault = "/web/client/totp/validate"
  163. webClientTOTPSavePathDefault = "/web/client/totp/save"
  164. webClientRecoveryCodesPathDefault = "/web/client/recoverycodes"
  165. webChangeClientPwdPathDefault = "/web/client/changepwd"
  166. webClientLogoutPathDefault = "/web/client/logout"
  167. webClientPubSharesPathDefault = "/web/client/pubshares"
  168. webClientForgotPwdPathDefault = "/web/client/forgot-password"
  169. webClientResetPwdPathDefault = "/web/client/reset-password"
  170. webClientViewPDFPathDefault = "/web/client/viewpdf"
  171. webClientGetPDFPathDefault = "/web/client/getpdf"
  172. webClientExistPathDefault = "/web/client/exist"
  173. webClientTasksPathDefault = "/web/client/tasks"
  174. webStaticFilesPathDefault = "/static"
  175. webOpenAPIPathDefault = "/openapi"
  176. // MaxRestoreSize defines the max size for the loaddata input file
  177. MaxRestoreSize = 20 * 1048576 // 20 MB
  178. maxRequestSize = 1048576 // 1MB
  179. maxLoginBodySize = 262144 // 256 KB
  180. httpdMaxEditFileSize = 2 * 1048576 // 2 MB
  181. maxMultipartMem = 10 * 1048576 // 10 MB
  182. osWindows = "windows"
  183. otpHeaderCode = "X-SFTPGO-OTP"
  184. mTimeHeader = "X-SFTPGO-MTIME"
  185. acmeChallengeURI = "/.well-known/acme-challenge/"
  186. )
  187. var (
  188. certMgr *common.CertManager
  189. cleanupTicker *time.Ticker
  190. cleanupDone chan bool
  191. invalidatedJWTTokens tokenManager
  192. webRootPath string
  193. webBasePath string
  194. webBaseAdminPath string
  195. webBaseClientPath string
  196. webOIDCRedirectPath string
  197. webOAuth2RedirectPath string
  198. webOAuth2TokenPath string
  199. webAdminSetupPath string
  200. webAdminOIDCLoginPath string
  201. webAdminLoginPath string
  202. webAdminTwoFactorPath string
  203. webAdminTwoFactorRecoveryPath string
  204. webLogoutPath string
  205. webUsersPath string
  206. webUserPath string
  207. webConnectionsPath string
  208. webFoldersPath string
  209. webFolderPath string
  210. webGroupsPath string
  211. webGroupPath string
  212. webStatusPath string
  213. webAdminsPath string
  214. webAdminPath string
  215. webMaintenancePath string
  216. webBackupPath string
  217. webRestorePath string
  218. webScanVFolderPath string
  219. webQuotaScanPath string
  220. webAdminProfilePath string
  221. webAdminMFAPath string
  222. webAdminEventRulesPath string
  223. webAdminEventRulePath string
  224. webAdminEventActionsPath string
  225. webAdminEventActionPath string
  226. webAdminRolesPath string
  227. webAdminRolePath string
  228. webAdminTOTPGeneratePath string
  229. webAdminTOTPValidatePath string
  230. webAdminTOTPSavePath string
  231. webAdminRecoveryCodesPath string
  232. webChangeAdminPwdPath string
  233. webAdminForgotPwdPath string
  234. webAdminResetPwdPath string
  235. webTemplateUser string
  236. webTemplateFolder string
  237. webDefenderPath string
  238. webIPListPath string
  239. webIPListsPath string
  240. webEventsPath string
  241. webEventsFsSearchPath string
  242. webEventsProviderSearchPath string
  243. webEventsLogSearchPath string
  244. webConfigsPath string
  245. webDefenderHostsPath string
  246. webClientLoginPath string
  247. webClientOIDCLoginPath string
  248. webClientTwoFactorPath string
  249. webClientTwoFactorRecoveryPath string
  250. webClientFilesPath string
  251. webClientFilePath string
  252. webClientFileActionsPath string
  253. webClientSharesPath string
  254. webClientSharePath string
  255. webClientEditFilePath string
  256. webClientDirsPath string
  257. webClientDownloadZipPath string
  258. webClientProfilePath string
  259. webClientPingPath string
  260. webChangeClientPwdPath string
  261. webClientMFAPath string
  262. webClientTOTPGeneratePath string
  263. webClientTOTPValidatePath string
  264. webClientTOTPSavePath string
  265. webClientRecoveryCodesPath string
  266. webClientPubSharesPath string
  267. webClientLogoutPath string
  268. webClientForgotPwdPath string
  269. webClientResetPwdPath string
  270. webClientViewPDFPath string
  271. webClientGetPDFPath string
  272. webClientExistPath string
  273. webClientTasksPath string
  274. webStaticFilesPath string
  275. webOpenAPIPath string
  276. // max upload size for http clients, 1GB by default
  277. maxUploadFileSize = int64(1048576000)
  278. hideSupportLink bool
  279. installationCode string
  280. installationCodeHint string
  281. fnInstallationCodeResolver FnInstallationCodeResolver
  282. configurationDir string
  283. dbBrandingConfig brandingCache
  284. )
  285. func init() {
  286. updateWebAdminURLs("")
  287. updateWebClientURLs("")
  288. acme.SetReloadHTTPDCertsFn(ReloadCertificateMgr)
  289. common.SetUpdateBrandingFn(dbBrandingConfig.Set)
  290. }
  291. type brandingCache struct {
  292. mu sync.RWMutex
  293. configs *dataprovider.BrandingConfigs
  294. }
  295. func (b *brandingCache) Set(configs *dataprovider.BrandingConfigs) {
  296. b.mu.Lock()
  297. defer b.mu.Unlock()
  298. b.configs = configs
  299. }
  300. func (b *brandingCache) getWebAdminLogo() []byte {
  301. b.mu.RLock()
  302. defer b.mu.RUnlock()
  303. return b.configs.WebAdmin.Logo
  304. }
  305. func (b *brandingCache) getWebAdminFavicon() []byte {
  306. b.mu.RLock()
  307. defer b.mu.RUnlock()
  308. return b.configs.WebAdmin.Favicon
  309. }
  310. func (b *brandingCache) getWebClientLogo() []byte {
  311. b.mu.RLock()
  312. defer b.mu.RUnlock()
  313. return b.configs.WebClient.Logo
  314. }
  315. func (b *brandingCache) getWebClientFavicon() []byte {
  316. b.mu.RLock()
  317. defer b.mu.RUnlock()
  318. return b.configs.WebClient.Favicon
  319. }
  320. func (b *brandingCache) mergeBrandingConfig(branding UIBranding, isWebClient bool) UIBranding {
  321. b.mu.RLock()
  322. defer b.mu.RUnlock()
  323. var urlPrefix string
  324. var cfg dataprovider.BrandingConfig
  325. if isWebClient {
  326. cfg = b.configs.WebClient
  327. urlPrefix = "webclient"
  328. } else {
  329. cfg = b.configs.WebAdmin
  330. urlPrefix = "webadmin"
  331. }
  332. if cfg.Name != "" {
  333. branding.Name = cfg.Name
  334. }
  335. if cfg.ShortName != "" {
  336. branding.ShortName = cfg.ShortName
  337. }
  338. if cfg.DisclaimerName != "" {
  339. branding.DisclaimerName = cfg.DisclaimerName
  340. }
  341. if cfg.DisclaimerURL != "" {
  342. branding.DisclaimerPath = cfg.DisclaimerURL
  343. }
  344. if len(cfg.Logo) > 0 {
  345. branding.LogoPath = path.Join("/", "branding", urlPrefix, "logo.png")
  346. }
  347. if len(cfg.Favicon) > 0 {
  348. branding.FaviconPath = path.Join("/", "branding", urlPrefix, "favicon.png")
  349. }
  350. return branding
  351. }
  352. // FnInstallationCodeResolver defines a method to get the installation code.
  353. // If the installation code cannot be resolved the provided default must be returned
  354. type FnInstallationCodeResolver func(defaultInstallationCode string) string
  355. // HTTPSProxyHeader defines an HTTPS proxy header as key/value.
  356. // For example Key could be "X-Forwarded-Proto" and Value "https"
  357. type HTTPSProxyHeader struct {
  358. Key string
  359. Value string
  360. }
  361. // SecurityConf allows to add some security related headers to HTTP responses and to restrict allowed hosts
  362. type SecurityConf struct {
  363. // Set to true to enable the security configurations
  364. Enabled bool `json:"enabled" mapstructure:"enabled"`
  365. // AllowedHosts is a list of fully qualified domain names that are allowed.
  366. // Default is empty list, which allows any and all host names.
  367. AllowedHosts []string `json:"allowed_hosts" mapstructure:"allowed_hosts"`
  368. // AllowedHostsAreRegex determines if the provided allowed hosts contains valid regular expressions
  369. AllowedHostsAreRegex bool `json:"allowed_hosts_are_regex" mapstructure:"allowed_hosts_are_regex"`
  370. // HostsProxyHeaders is a set of header keys that may hold a proxied hostname value for the request.
  371. HostsProxyHeaders []string `json:"hosts_proxy_headers" mapstructure:"hosts_proxy_headers"`
  372. // Set to true to redirect HTTP requests to HTTPS
  373. HTTPSRedirect bool `json:"https_redirect" mapstructure:"https_redirect"`
  374. // HTTPSHost defines the host name that is used to redirect HTTP requests to HTTPS.
  375. // Default is "", which indicates to use the same host.
  376. HTTPSHost string `json:"https_host" mapstructure:"https_host"`
  377. // HTTPSProxyHeaders is a list of header keys with associated values that would indicate a valid https request.
  378. HTTPSProxyHeaders []HTTPSProxyHeader `json:"https_proxy_headers" mapstructure:"https_proxy_headers"`
  379. // STSSeconds is the max-age of the Strict-Transport-Security header.
  380. // Default is 0, which would NOT include the header.
  381. STSSeconds int64 `json:"sts_seconds" mapstructure:"sts_seconds"`
  382. // If STSIncludeSubdomains is set to true, the "includeSubdomains" will be appended to the
  383. // Strict-Transport-Security header. Default is false.
  384. STSIncludeSubdomains bool `json:"sts_include_subdomains" mapstructure:"sts_include_subdomains"`
  385. // If STSPreload is set to true, the `preload` flag will be appended to the
  386. // Strict-Transport-Security header. Default is false.
  387. STSPreload bool `json:"sts_preload" mapstructure:"sts_preload"`
  388. // If ContentTypeNosniff is true, adds the X-Content-Type-Options header with the value "nosniff". Default is false.
  389. ContentTypeNosniff bool `json:"content_type_nosniff" mapstructure:"content_type_nosniff"`
  390. // ContentSecurityPolicy allows to set the Content-Security-Policy header value. Default is "".
  391. ContentSecurityPolicy string `json:"content_security_policy" mapstructure:"content_security_policy"`
  392. // PermissionsPolicy allows to set the Permissions-Policy header value. Default is "".
  393. PermissionsPolicy string `json:"permissions_policy" mapstructure:"permissions_policy"`
  394. // CrossOriginOpenerPolicy allows to set the `Cross-Origin-Opener-Policy` header value. Default is "".
  395. CrossOriginOpenerPolicy string `json:"cross_origin_opener_policy" mapstructure:"cross_origin_opener_policy"`
  396. proxyHeaders []string
  397. }
  398. func (s *SecurityConf) updateProxyHeaders() {
  399. if !s.Enabled {
  400. s.proxyHeaders = nil
  401. return
  402. }
  403. s.proxyHeaders = s.HostsProxyHeaders
  404. for _, httpsProxyHeader := range s.HTTPSProxyHeaders {
  405. s.proxyHeaders = append(s.proxyHeaders, httpsProxyHeader.Key)
  406. }
  407. }
  408. func (s *SecurityConf) getHTTPSProxyHeaders() map[string]string {
  409. headers := make(map[string]string)
  410. for _, httpsProxyHeader := range s.HTTPSProxyHeaders {
  411. headers[httpsProxyHeader.Key] = httpsProxyHeader.Value
  412. }
  413. return headers
  414. }
  415. func (s *SecurityConf) redirectHandler(next http.Handler) http.Handler {
  416. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  417. if !isTLS(r) && !strings.HasPrefix(r.RequestURI, acmeChallengeURI) {
  418. url := r.URL
  419. url.Scheme = "https"
  420. if s.HTTPSHost != "" {
  421. url.Host = s.HTTPSHost
  422. } else {
  423. host := r.Host
  424. for _, header := range s.HostsProxyHeaders {
  425. if h := r.Header.Get(header); h != "" {
  426. host = h
  427. break
  428. }
  429. }
  430. url.Host = host
  431. }
  432. http.Redirect(w, r, url.String(), http.StatusTemporaryRedirect)
  433. return
  434. }
  435. next.ServeHTTP(w, r)
  436. })
  437. }
  438. // UIBranding defines the supported customizations for the web UIs
  439. type UIBranding struct {
  440. // Name defines the text to show at the login page and as HTML title
  441. Name string `json:"name" mapstructure:"name"`
  442. // ShortName defines the name to show next to the logo image
  443. ShortName string `json:"short_name" mapstructure:"short_name"`
  444. // Path to your logo relative to "static_files_path".
  445. // For example, if you create a directory named "branding" inside the static dir and
  446. // put the "mylogo.png" file in it, you must set "/branding/mylogo.png" as logo path.
  447. LogoPath string `json:"logo_path" mapstructure:"logo_path"`
  448. // Path to your favicon relative to "static_files_path"
  449. FaviconPath string `json:"favicon_path" mapstructure:"favicon_path"`
  450. // DisclaimerName defines the name for the link to your optional disclaimer
  451. DisclaimerName string `json:"disclaimer_name" mapstructure:"disclaimer_name"`
  452. // Path to the HTML page for your disclaimer relative to "static_files_path"
  453. // or an absolute http/https URL.
  454. DisclaimerPath string `json:"disclaimer_path" mapstructure:"disclaimer_path"`
  455. // Path to custom CSS files, relative to "static_files_path", which replaces
  456. // the default CSS files
  457. DefaultCSS []string `json:"default_css" mapstructure:"default_css"`
  458. // Additional CSS file paths, relative to "static_files_path", to include
  459. ExtraCSS []string `json:"extra_css" mapstructure:"extra_css"`
  460. DefaultLogoPath string `json:"-" mapstructure:"-"`
  461. DefaultFaviconPath string `json:"-" mapstructure:"-"`
  462. }
  463. func (b *UIBranding) check() {
  464. b.DefaultLogoPath = "/img/logo.png"
  465. b.DefaultFaviconPath = "/favicon.png"
  466. if b.LogoPath != "" {
  467. b.LogoPath = util.CleanPath(b.LogoPath)
  468. } else {
  469. b.LogoPath = b.DefaultLogoPath
  470. }
  471. if b.FaviconPath != "" {
  472. b.FaviconPath = util.CleanPath(b.FaviconPath)
  473. } else {
  474. b.FaviconPath = b.DefaultFaviconPath
  475. }
  476. if b.DisclaimerPath != "" {
  477. if !strings.HasPrefix(b.DisclaimerPath, "https://") && !strings.HasPrefix(b.DisclaimerPath, "http://") {
  478. b.DisclaimerPath = path.Join(webStaticFilesPath, util.CleanPath(b.DisclaimerPath))
  479. }
  480. }
  481. if len(b.DefaultCSS) > 0 {
  482. for idx := range b.DefaultCSS {
  483. b.DefaultCSS[idx] = util.CleanPath(b.DefaultCSS[idx])
  484. }
  485. } else {
  486. b.DefaultCSS = []string{
  487. "/assets/plugins/global/plugins.bundle.css",
  488. "/assets/css/style.bundle.css",
  489. }
  490. }
  491. for idx := range b.ExtraCSS {
  492. b.ExtraCSS[idx] = util.CleanPath(b.ExtraCSS[idx])
  493. }
  494. }
  495. // Branding defines the branding-related customizations supported
  496. type Branding struct {
  497. WebAdmin UIBranding `json:"web_admin" mapstructure:"web_admin"`
  498. WebClient UIBranding `json:"web_client" mapstructure:"web_client"`
  499. }
  500. // WebClientIntegration defines the configuration for an external Web Client integration
  501. type WebClientIntegration struct {
  502. // Files with these extensions can be sent to the configured URL
  503. FileExtensions []string `json:"file_extensions" mapstructure:"file_extensions"`
  504. // URL that will receive the files
  505. URL string `json:"url" mapstructure:"url"`
  506. }
  507. // Binding defines the configuration for a network listener
  508. type Binding struct {
  509. // The address to listen on. A blank value means listen on all available network interfaces.
  510. Address string `json:"address" mapstructure:"address"`
  511. // The port used for serving requests
  512. Port int `json:"port" mapstructure:"port"`
  513. // Enable the built-in admin interface.
  514. // You have to define TemplatesPath and StaticFilesPath for this to work
  515. EnableWebAdmin bool `json:"enable_web_admin" mapstructure:"enable_web_admin"`
  516. // Enable the built-in client interface.
  517. // You have to define TemplatesPath and StaticFilesPath for this to work
  518. EnableWebClient bool `json:"enable_web_client" mapstructure:"enable_web_client"`
  519. // Enable REST API
  520. EnableRESTAPI bool `json:"enable_rest_api" mapstructure:"enable_rest_api"`
  521. // Defines the login methods available for the WebAdmin and WebClient UIs:
  522. //
  523. // - 0 means any configured method: username/password login form and OIDC, if enabled
  524. // - 1 means OIDC for the WebAdmin UI
  525. // - 2 means OIDC for the WebClient UI
  526. // - 4 means login form for the WebAdmin UI
  527. // - 8 means login form for the WebClient UI
  528. //
  529. // You can combine the values. For example 3 means that you can only login using OIDC on
  530. // both WebClient and WebAdmin UI.
  531. EnabledLoginMethods int `json:"enabled_login_methods" mapstructure:"enabled_login_methods"`
  532. // you also need to provide a certificate for enabling HTTPS
  533. EnableHTTPS bool `json:"enable_https" mapstructure:"enable_https"`
  534. // Certificate and matching private key for this specific binding, if empty the global
  535. // ones will be used, if any
  536. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  537. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  538. // Defines the minimum TLS version. 13 means TLS 1.3, default is TLS 1.2
  539. MinTLSVersion int `json:"min_tls_version" mapstructure:"min_tls_version"`
  540. // set to 1 to require client certificate authentication in addition to basic auth.
  541. // You need to define at least a certificate authority for this to work
  542. ClientAuthType int `json:"client_auth_type" mapstructure:"client_auth_type"`
  543. // TLSCipherSuites is a list of supported cipher suites for TLS version 1.2.
  544. // If CipherSuites is nil/empty, a default list of secure cipher suites
  545. // is used, with a preference order based on hardware performance.
  546. // Note that TLS 1.3 ciphersuites are not configurable.
  547. // The supported ciphersuites names are defined here:
  548. //
  549. // https://github.com/golang/go/blob/master/src/crypto/tls/cipher_suites.go#L53
  550. //
  551. // any invalid name will be silently ignored.
  552. // The order matters, the ciphers listed first will be the preferred ones.
  553. TLSCipherSuites []string `json:"tls_cipher_suites" mapstructure:"tls_cipher_suites"`
  554. // HTTP protocols in preference order. Supported values: http/1.1, h2
  555. Protocols []string `json:"tls_protocols" mapstructure:"tls_protocols"`
  556. // List of IP addresses and IP ranges allowed to set client IP proxy headers and
  557. // X-Forwarded-Proto header.
  558. ProxyAllowed []string `json:"proxy_allowed" mapstructure:"proxy_allowed"`
  559. // Allowed client IP proxy header such as "X-Forwarded-For", "X-Real-IP"
  560. ClientIPProxyHeader string `json:"client_ip_proxy_header" mapstructure:"client_ip_proxy_header"`
  561. // Some client IP headers such as "X-Forwarded-For" can contain multiple IP address, this setting
  562. // define the position to trust starting from the right. For example if we have:
  563. // "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"
  564. // as client IP, if depth is 1, "12.0.0.1" will be used and so on
  565. ClientIPHeaderDepth int `json:"client_ip_header_depth" mapstructure:"client_ip_header_depth"`
  566. // If both web admin and web client are enabled each login page will show a link
  567. // to the other one. This setting allows to hide this link:
  568. // - 0 login links are displayed on both admin and client login page. This is the default
  569. // - 1 the login link to the web client login page is hidden on admin login page
  570. // - 2 the login link to the web admin login page is hidden on client login page
  571. // The flags can be combined, for example 3 will disable both login links.
  572. HideLoginURL int `json:"hide_login_url" mapstructure:"hide_login_url"`
  573. // Enable the built-in OpenAPI renderer
  574. RenderOpenAPI bool `json:"render_openapi" mapstructure:"render_openapi"`
  575. // Defining an OIDC configuration the web admin and web client UI will use OpenID to authenticate users.
  576. OIDC OIDC `json:"oidc" mapstructure:"oidc"`
  577. // Security defines security headers to add to HTTP responses and allows to restrict allowed hosts
  578. Security SecurityConf `json:"security" mapstructure:"security"`
  579. // Branding defines customizations to suit your brand
  580. Branding Branding `json:"branding" mapstructure:"branding"`
  581. allowHeadersFrom []func(net.IP) bool
  582. }
  583. func (b *Binding) checkBranding() {
  584. b.Branding.WebAdmin.check()
  585. b.Branding.WebClient.check()
  586. if b.Branding.WebAdmin.Name == "" {
  587. b.Branding.WebAdmin.Name = "SFTPGo WebAdmin"
  588. }
  589. if b.Branding.WebAdmin.ShortName == "" {
  590. b.Branding.WebAdmin.ShortName = "WebAdmin"
  591. }
  592. if b.Branding.WebClient.Name == "" {
  593. b.Branding.WebClient.Name = "SFTPGo WebClient"
  594. }
  595. if b.Branding.WebClient.ShortName == "" {
  596. b.Branding.WebClient.ShortName = "WebClient"
  597. }
  598. }
  599. func (b *Binding) webAdminBranding() UIBranding {
  600. return dbBrandingConfig.mergeBrandingConfig(b.Branding.WebAdmin, false)
  601. }
  602. func (b *Binding) webClientBranding() UIBranding {
  603. return dbBrandingConfig.mergeBrandingConfig(b.Branding.WebClient, true)
  604. }
  605. func (b *Binding) parseAllowedProxy() error {
  606. if filepath.IsAbs(b.Address) && len(b.ProxyAllowed) > 0 {
  607. // unix domain socket
  608. b.allowHeadersFrom = []func(net.IP) bool{func(_ net.IP) bool { return true }}
  609. return nil
  610. }
  611. allowedFuncs, err := util.ParseAllowedIPAndRanges(b.ProxyAllowed)
  612. if err != nil {
  613. return err
  614. }
  615. b.allowHeadersFrom = allowedFuncs
  616. return nil
  617. }
  618. // GetAddress returns the binding address
  619. func (b *Binding) GetAddress() string {
  620. return fmt.Sprintf("%s:%d", b.Address, b.Port)
  621. }
  622. // IsValid returns true if the binding is valid
  623. func (b *Binding) IsValid() bool {
  624. if !b.EnableRESTAPI && !b.EnableWebAdmin && !b.EnableWebClient {
  625. return false
  626. }
  627. if b.Port > 0 {
  628. return true
  629. }
  630. if filepath.IsAbs(b.Address) && runtime.GOOS != osWindows {
  631. return true
  632. }
  633. return false
  634. }
  635. func (b *Binding) isWebAdminOIDCLoginDisabled() bool {
  636. if b.EnableWebAdmin {
  637. if b.EnabledLoginMethods == 0 {
  638. return false
  639. }
  640. return b.EnabledLoginMethods&1 == 0
  641. }
  642. return false
  643. }
  644. func (b *Binding) isWebClientOIDCLoginDisabled() bool {
  645. if b.EnableWebClient {
  646. if b.EnabledLoginMethods == 0 {
  647. return false
  648. }
  649. return b.EnabledLoginMethods&2 == 0
  650. }
  651. return false
  652. }
  653. func (b *Binding) isWebAdminLoginFormDisabled() bool {
  654. if b.EnableWebAdmin {
  655. if b.EnabledLoginMethods == 0 {
  656. return false
  657. }
  658. return b.EnabledLoginMethods&4 == 0
  659. }
  660. return false
  661. }
  662. func (b *Binding) isWebClientLoginFormDisabled() bool {
  663. if b.EnableWebClient {
  664. if b.EnabledLoginMethods == 0 {
  665. return false
  666. }
  667. return b.EnabledLoginMethods&8 == 0
  668. }
  669. return false
  670. }
  671. func (b *Binding) checkLoginMethods() error {
  672. if b.isWebAdminLoginFormDisabled() && b.isWebAdminOIDCLoginDisabled() {
  673. return errors.New("no login method available for WebAdmin UI")
  674. }
  675. if !b.isWebAdminOIDCLoginDisabled() {
  676. if b.isWebAdminLoginFormDisabled() && !b.OIDC.hasRoles() {
  677. return errors.New("no login method available for WebAdmin UI")
  678. }
  679. }
  680. if b.isWebClientLoginFormDisabled() && b.isWebClientOIDCLoginDisabled() {
  681. return errors.New("no login method available for WebClient UI")
  682. }
  683. if !b.isWebClientOIDCLoginDisabled() {
  684. if b.isWebClientLoginFormDisabled() && !b.OIDC.isEnabled() {
  685. return errors.New("no login method available for WebClient UI")
  686. }
  687. }
  688. return nil
  689. }
  690. func (b *Binding) showAdminLoginURL() bool {
  691. if !b.EnableWebAdmin {
  692. return false
  693. }
  694. if b.HideLoginURL&2 != 0 {
  695. return false
  696. }
  697. return true
  698. }
  699. func (b *Binding) showClientLoginURL() bool {
  700. if !b.EnableWebClient {
  701. return false
  702. }
  703. if b.HideLoginURL&1 != 0 {
  704. return false
  705. }
  706. return true
  707. }
  708. func (b *Binding) isMutualTLSEnabled() bool {
  709. return b.ClientAuthType == 1
  710. }
  711. type defenderStatus struct {
  712. IsActive bool `json:"is_active"`
  713. }
  714. type allowListStatus struct {
  715. IsActive bool `json:"is_active"`
  716. }
  717. type rateLimiters struct {
  718. IsActive bool `json:"is_active"`
  719. Protocols []string `json:"protocols"`
  720. }
  721. // GetProtocolsAsString returns the enabled protocols as comma separated string
  722. func (r *rateLimiters) GetProtocolsAsString() string {
  723. return strings.Join(r.Protocols, ", ")
  724. }
  725. // ServicesStatus keep the state of the running services
  726. type ServicesStatus struct {
  727. SSH sftpd.ServiceStatus `json:"ssh"`
  728. FTP ftpd.ServiceStatus `json:"ftp"`
  729. WebDAV webdavd.ServiceStatus `json:"webdav"`
  730. DataProvider dataprovider.ProviderStatus `json:"data_provider"`
  731. Defender defenderStatus `json:"defender"`
  732. MFA mfa.ServiceStatus `json:"mfa"`
  733. AllowList allowListStatus `json:"allow_list"`
  734. RateLimiters rateLimiters `json:"rate_limiters"`
  735. }
  736. // SetupConfig defines the configuration parameters for the initial web admin setup
  737. type SetupConfig struct {
  738. // Installation code to require when creating the first admin account.
  739. // As for the other configurations, this value is read at SFTPGo startup and not at runtime
  740. // even if set using an environment variable.
  741. // This is not a license key or similar, the purpose here is to prevent anyone who can access
  742. // to the initial setup screen from creating an admin user
  743. InstallationCode string `json:"installation_code" mapstructure:"installation_code"`
  744. // Description for the installation code input field
  745. InstallationCodeHint string `json:"installation_code_hint" mapstructure:"installation_code_hint"`
  746. }
  747. // CorsConfig defines the CORS configuration
  748. type CorsConfig struct {
  749. AllowedOrigins []string `json:"allowed_origins" mapstructure:"allowed_origins"`
  750. AllowedMethods []string `json:"allowed_methods" mapstructure:"allowed_methods"`
  751. AllowedHeaders []string `json:"allowed_headers" mapstructure:"allowed_headers"`
  752. ExposedHeaders []string `json:"exposed_headers" mapstructure:"exposed_headers"`
  753. AllowCredentials bool `json:"allow_credentials" mapstructure:"allow_credentials"`
  754. Enabled bool `json:"enabled" mapstructure:"enabled"`
  755. MaxAge int `json:"max_age" mapstructure:"max_age"`
  756. OptionsPassthrough bool `json:"options_passthrough" mapstructure:"options_passthrough"`
  757. OptionsSuccessStatus int `json:"options_success_status" mapstructure:"options_success_status"`
  758. AllowPrivateNetwork bool `json:"allow_private_network" mapstructure:"allow_private_network"`
  759. }
  760. // Conf httpd daemon configuration
  761. type Conf struct {
  762. // Addresses and ports to bind to
  763. Bindings []Binding `json:"bindings" mapstructure:"bindings"`
  764. // Path to the HTML web templates. This can be an absolute path or a path relative to the config dir
  765. TemplatesPath string `json:"templates_path" mapstructure:"templates_path"`
  766. // Path to the static files for the web interface. This can be an absolute path or a path relative to the config dir.
  767. // If both TemplatesPath and StaticFilesPath are empty the built-in web interface will be disabled
  768. StaticFilesPath string `json:"static_files_path" mapstructure:"static_files_path"`
  769. // Path to the backup directory. This can be an absolute path or a path relative to the config dir
  770. //BackupsPath string `json:"backups_path" mapstructure:"backups_path"`
  771. // Path to the directory that contains the OpenAPI schema and the default renderer.
  772. // This can be an absolute path or a path relative to the config dir
  773. OpenAPIPath string `json:"openapi_path" mapstructure:"openapi_path"`
  774. // Defines a base URL for the web admin and client interfaces. If empty web admin and client resources will
  775. // be available at the root ("/") URI. If defined it must be an absolute URI or it will be ignored.
  776. WebRoot string `json:"web_root" mapstructure:"web_root"`
  777. // If files containing a certificate and matching private key for the server are provided you can enable
  778. // HTTPS connections for the configured bindings.
  779. // Certificate and key files can be reloaded on demand sending a "SIGHUP" signal on Unix based systems and a
  780. // "paramchange" request to the running service on Windows.
  781. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  782. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  783. // CACertificates defines the set of root certificate authorities to be used to verify client certificates.
  784. CACertificates []string `json:"ca_certificates" mapstructure:"ca_certificates"`
  785. // CARevocationLists defines a set a revocation lists, one for each root CA, to be used to check
  786. // if a client certificate has been revoked
  787. CARevocationLists []string `json:"ca_revocation_lists" mapstructure:"ca_revocation_lists"`
  788. // SigningPassphrase defines the passphrase to use to derive the signing key for JWT and CSRF tokens.
  789. // If empty a random signing key will be generated each time SFTPGo starts. If you set a
  790. // signing passphrase you should consider rotating it periodically for added security
  791. SigningPassphrase string `json:"signing_passphrase" mapstructure:"signing_passphrase"`
  792. SigningPassphraseFile string `json:"signing_passphrase_file" mapstructure:"signing_passphrase_file"`
  793. // TokenValidation allows to define how to validate JWT tokens, cookies and CSRF tokens.
  794. // By default all the available security checks are enabled. Set to 1 to disable the requirement
  795. // that a token must be used by the same IP for which it was issued.
  796. TokenValidation int `json:"token_validation" mapstructure:"token_validation"`
  797. // MaxUploadFileSize Defines the maximum request body size, in bytes, for Web Client/API HTTP upload requests.
  798. // 0 means no limit
  799. MaxUploadFileSize int64 `json:"max_upload_file_size" mapstructure:"max_upload_file_size"`
  800. // CORS configuration
  801. Cors CorsConfig `json:"cors" mapstructure:"cors"`
  802. // Initial setup configuration
  803. Setup SetupConfig `json:"setup" mapstructure:"setup"`
  804. // If enabled, the link to the sponsors section will not appear on the setup screen page
  805. HideSupportLink bool `json:"hide_support_link" mapstructure:"hide_support_link"`
  806. acmeDomain string
  807. }
  808. type apiResponse struct {
  809. Error string `json:"error,omitempty"`
  810. Message string `json:"message"`
  811. }
  812. // ShouldBind returns true if there is at least a valid binding
  813. func (c *Conf) ShouldBind() bool {
  814. for _, binding := range c.Bindings {
  815. if binding.IsValid() {
  816. return true
  817. }
  818. }
  819. return false
  820. }
  821. func (c *Conf) isWebAdminEnabled() bool {
  822. for _, binding := range c.Bindings {
  823. if binding.EnableWebAdmin {
  824. return true
  825. }
  826. }
  827. return false
  828. }
  829. func (c *Conf) isWebClientEnabled() bool {
  830. for _, binding := range c.Bindings {
  831. if binding.EnableWebClient {
  832. return true
  833. }
  834. }
  835. return false
  836. }
  837. func (c *Conf) checkRequiredDirs(staticFilesPath, templatesPath string) error {
  838. if (c.isWebAdminEnabled() || c.isWebClientEnabled()) && (staticFilesPath == "" || templatesPath == "") {
  839. return fmt.Errorf("required directory is invalid, static file path: %q template path: %q",
  840. staticFilesPath, templatesPath)
  841. }
  842. return nil
  843. }
  844. func (c *Conf) getRedacted() Conf {
  845. redacted := "[redacted]"
  846. conf := *c
  847. if conf.SigningPassphrase != "" {
  848. conf.SigningPassphrase = redacted
  849. }
  850. if conf.Setup.InstallationCode != "" {
  851. conf.Setup.InstallationCode = redacted
  852. }
  853. conf.Bindings = nil
  854. for _, binding := range c.Bindings {
  855. if binding.OIDC.ClientID != "" {
  856. binding.OIDC.ClientID = redacted
  857. }
  858. if binding.OIDC.ClientSecret != "" {
  859. binding.OIDC.ClientSecret = redacted
  860. }
  861. conf.Bindings = append(conf.Bindings, binding)
  862. }
  863. return conf
  864. }
  865. func (c *Conf) getKeyPairs(configDir string) []common.TLSKeyPair {
  866. var keyPairs []common.TLSKeyPair
  867. for _, binding := range c.Bindings {
  868. certificateFile := getConfigPath(binding.CertificateFile, configDir)
  869. certificateKeyFile := getConfigPath(binding.CertificateKeyFile, configDir)
  870. if certificateFile != "" && certificateKeyFile != "" {
  871. keyPairs = append(keyPairs, common.TLSKeyPair{
  872. Cert: certificateFile,
  873. Key: certificateKeyFile,
  874. ID: binding.GetAddress(),
  875. })
  876. }
  877. }
  878. var certificateFile, certificateKeyFile string
  879. if c.acmeDomain != "" {
  880. certificateFile, certificateKeyFile = util.GetACMECertificateKeyPair(c.acmeDomain)
  881. } else {
  882. certificateFile = getConfigPath(c.CertificateFile, configDir)
  883. certificateKeyFile = getConfigPath(c.CertificateKeyFile, configDir)
  884. }
  885. if certificateFile != "" && certificateKeyFile != "" {
  886. keyPairs = append(keyPairs, common.TLSKeyPair{
  887. Cert: certificateFile,
  888. Key: certificateKeyFile,
  889. ID: common.DefaultTLSKeyPaidID,
  890. })
  891. }
  892. return keyPairs
  893. }
  894. func (c *Conf) setTokenValidationMode() {
  895. if c.TokenValidation == 1 {
  896. tokenValidationMode = tokenValidationNoIPMatch
  897. } else {
  898. tokenValidationMode = tokenValidationFull
  899. }
  900. }
  901. func (c *Conf) loadFromProvider() error {
  902. configs, err := dataprovider.GetConfigs()
  903. if err != nil {
  904. return fmt.Errorf("unable to load config from provider: %w", err)
  905. }
  906. configs.SetNilsToEmpty()
  907. dbBrandingConfig.Set(configs.Branding)
  908. if configs.ACME.Domain == "" || !configs.ACME.HasProtocol(common.ProtocolHTTP) {
  909. return nil
  910. }
  911. crt, key := util.GetACMECertificateKeyPair(configs.ACME.Domain)
  912. if crt != "" && key != "" {
  913. if _, err := os.Stat(crt); err != nil {
  914. logger.Error(logSender, "", "unable to load acme cert file %q: %v", crt, err)
  915. return nil
  916. }
  917. if _, err := os.Stat(key); err != nil {
  918. logger.Error(logSender, "", "unable to load acme key file %q: %v", key, err)
  919. return nil
  920. }
  921. for idx := range c.Bindings {
  922. if c.Bindings[idx].Security.Enabled && c.Bindings[idx].Security.HTTPSRedirect {
  923. continue
  924. }
  925. c.Bindings[idx].EnableHTTPS = true
  926. }
  927. c.acmeDomain = configs.ACME.Domain
  928. logger.Info(logSender, "", "acme domain set to %q", c.acmeDomain)
  929. return nil
  930. }
  931. return nil
  932. }
  933. func (c *Conf) loadTemplates(templatesPath string) {
  934. if c.isWebAdminEnabled() {
  935. updateWebAdminURLs(c.WebRoot)
  936. loadAdminTemplates(templatesPath)
  937. } else {
  938. logger.Info(logSender, "", "built-in web admin interface disabled")
  939. }
  940. if c.isWebClientEnabled() {
  941. updateWebClientURLs(c.WebRoot)
  942. loadClientTemplates(templatesPath)
  943. } else {
  944. logger.Info(logSender, "", "built-in web client interface disabled")
  945. }
  946. }
  947. // Initialize configures and starts the HTTP server
  948. func (c *Conf) Initialize(configDir string, isShared int) error {
  949. if err := c.loadFromProvider(); err != nil {
  950. return err
  951. }
  952. logger.Info(logSender, "", "initializing HTTP server with config %+v", c.getRedacted())
  953. configurationDir = configDir
  954. invalidatedJWTTokens = newTokenManager(isShared)
  955. resetCodesMgr = newResetCodeManager(isShared)
  956. oidcMgr = newOIDCManager(isShared)
  957. oauth2Mgr = newOAuth2Manager(isShared)
  958. webTaskMgr = newWebTaskManager(isShared)
  959. staticFilesPath := util.FindSharedDataPath(c.StaticFilesPath, configDir)
  960. templatesPath := util.FindSharedDataPath(c.TemplatesPath, configDir)
  961. openAPIPath := util.FindSharedDataPath(c.OpenAPIPath, configDir)
  962. if err := c.checkRequiredDirs(staticFilesPath, templatesPath); err != nil {
  963. return err
  964. }
  965. c.loadTemplates(templatesPath)
  966. keyPairs := c.getKeyPairs(configDir)
  967. if len(keyPairs) > 0 {
  968. mgr, err := common.NewCertManager(keyPairs, configDir, logSender)
  969. if err != nil {
  970. return err
  971. }
  972. mgr.SetCACertificates(c.CACertificates)
  973. if err := mgr.LoadRootCAs(); err != nil {
  974. return err
  975. }
  976. mgr.SetCARevocationLists(c.CARevocationLists)
  977. if err := mgr.LoadCRLs(); err != nil {
  978. return err
  979. }
  980. certMgr = mgr
  981. }
  982. if c.SigningPassphraseFile != "" {
  983. passphrase, err := util.ReadConfigFromFile(c.SigningPassphraseFile, configDir)
  984. if err != nil {
  985. return err
  986. }
  987. c.SigningPassphrase = passphrase
  988. }
  989. hideSupportLink = c.HideSupportLink
  990. exitChannel := make(chan error, 1)
  991. for _, binding := range c.Bindings {
  992. if !binding.IsValid() {
  993. continue
  994. }
  995. if err := binding.parseAllowedProxy(); err != nil {
  996. return err
  997. }
  998. binding.checkBranding()
  999. binding.Security.updateProxyHeaders()
  1000. go func(b Binding) {
  1001. if err := b.OIDC.initialize(); err != nil {
  1002. exitChannel <- err
  1003. return
  1004. }
  1005. if err := b.checkLoginMethods(); err != nil {
  1006. exitChannel <- err
  1007. return
  1008. }
  1009. server := newHttpdServer(b, staticFilesPath, c.SigningPassphrase, c.Cors, openAPIPath)
  1010. server.setShared(isShared)
  1011. exitChannel <- server.listenAndServe()
  1012. }(binding)
  1013. }
  1014. maxUploadFileSize = c.MaxUploadFileSize
  1015. installationCode = c.Setup.InstallationCode
  1016. installationCodeHint = c.Setup.InstallationCodeHint
  1017. startCleanupTicker(tokenDuration / 2)
  1018. c.setTokenValidationMode()
  1019. return <-exitChannel
  1020. }
  1021. func isWebRequest(r *http.Request) bool {
  1022. return strings.HasPrefix(r.RequestURI, webBasePath+"/")
  1023. }
  1024. func isWebClientRequest(r *http.Request) bool {
  1025. return strings.HasPrefix(r.RequestURI, webBaseClientPath+"/")
  1026. }
  1027. // ReloadCertificateMgr reloads the certificate manager
  1028. func ReloadCertificateMgr() error {
  1029. if certMgr != nil {
  1030. return certMgr.Reload()
  1031. }
  1032. return nil
  1033. }
  1034. func getConfigPath(name, configDir string) string {
  1035. if !util.IsFileInputValid(name) {
  1036. return ""
  1037. }
  1038. if name != "" && !filepath.IsAbs(name) {
  1039. return filepath.Join(configDir, name)
  1040. }
  1041. return name
  1042. }
  1043. func getServicesStatus() *ServicesStatus {
  1044. rtlEnabled, rtlProtocols := common.Config.GetRateLimitersStatus()
  1045. status := &ServicesStatus{
  1046. SSH: sftpd.GetStatus(),
  1047. FTP: ftpd.GetStatus(),
  1048. WebDAV: webdavd.GetStatus(),
  1049. DataProvider: dataprovider.GetProviderStatus(),
  1050. Defender: defenderStatus{
  1051. IsActive: common.Config.DefenderConfig.Enabled,
  1052. },
  1053. MFA: mfa.GetStatus(),
  1054. AllowList: allowListStatus{
  1055. IsActive: common.Config.IsAllowListEnabled(),
  1056. },
  1057. RateLimiters: rateLimiters{
  1058. IsActive: rtlEnabled,
  1059. Protocols: rtlProtocols,
  1060. },
  1061. }
  1062. return status
  1063. }
  1064. func fileServer(r chi.Router, path string, root http.FileSystem, disableDirectoryIndex bool) {
  1065. if path != "/" && path[len(path)-1] != '/' {
  1066. r.Get(path, http.RedirectHandler(path+"/", http.StatusMovedPermanently).ServeHTTP)
  1067. path += "/"
  1068. }
  1069. path += "*"
  1070. r.Get(path, func(w http.ResponseWriter, r *http.Request) {
  1071. rctx := chi.RouteContext(r.Context())
  1072. pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*")
  1073. if disableDirectoryIndex {
  1074. root = neuteredFileSystem{root}
  1075. }
  1076. fs := http.StripPrefix(pathPrefix, http.FileServer(root))
  1077. fs.ServeHTTP(w, r)
  1078. })
  1079. }
  1080. func updateWebClientURLs(baseURL string) {
  1081. if !path.IsAbs(baseURL) {
  1082. baseURL = "/"
  1083. }
  1084. webRootPath = path.Join(baseURL, webRootPathDefault)
  1085. webBasePath = path.Join(baseURL, webBasePathDefault)
  1086. webBaseClientPath = path.Join(baseURL, webBasePathClientDefault)
  1087. webOIDCRedirectPath = path.Join(baseURL, webOIDCRedirectPathDefault)
  1088. webClientLoginPath = path.Join(baseURL, webClientLoginPathDefault)
  1089. webClientOIDCLoginPath = path.Join(baseURL, webClientOIDCLoginPathDefault)
  1090. webClientTwoFactorPath = path.Join(baseURL, webClientTwoFactorPathDefault)
  1091. webClientTwoFactorRecoveryPath = path.Join(baseURL, webClientTwoFactorRecoveryPathDefault)
  1092. webClientFilesPath = path.Join(baseURL, webClientFilesPathDefault)
  1093. webClientFilePath = path.Join(baseURL, webClientFilePathDefault)
  1094. webClientFileActionsPath = path.Join(baseURL, webClientFileActionsPathDefault)
  1095. webClientSharesPath = path.Join(baseURL, webClientSharesPathDefault)
  1096. webClientPubSharesPath = path.Join(baseURL, webClientPubSharesPathDefault)
  1097. webClientSharePath = path.Join(baseURL, webClientSharePathDefault)
  1098. webClientEditFilePath = path.Join(baseURL, webClientEditFilePathDefault)
  1099. webClientDirsPath = path.Join(baseURL, webClientDirsPathDefault)
  1100. webClientDownloadZipPath = path.Join(baseURL, webClientDownloadZipPathDefault)
  1101. webClientProfilePath = path.Join(baseURL, webClientProfilePathDefault)
  1102. webClientPingPath = path.Join(baseURL, webClientPingPathDefault)
  1103. webChangeClientPwdPath = path.Join(baseURL, webChangeClientPwdPathDefault)
  1104. webClientLogoutPath = path.Join(baseURL, webClientLogoutPathDefault)
  1105. webClientMFAPath = path.Join(baseURL, webClientMFAPathDefault)
  1106. webClientTOTPGeneratePath = path.Join(baseURL, webClientTOTPGeneratePathDefault)
  1107. webClientTOTPValidatePath = path.Join(baseURL, webClientTOTPValidatePathDefault)
  1108. webClientTOTPSavePath = path.Join(baseURL, webClientTOTPSavePathDefault)
  1109. webClientRecoveryCodesPath = path.Join(baseURL, webClientRecoveryCodesPathDefault)
  1110. webClientForgotPwdPath = path.Join(baseURL, webClientForgotPwdPathDefault)
  1111. webClientResetPwdPath = path.Join(baseURL, webClientResetPwdPathDefault)
  1112. webClientViewPDFPath = path.Join(baseURL, webClientViewPDFPathDefault)
  1113. webClientGetPDFPath = path.Join(baseURL, webClientGetPDFPathDefault)
  1114. webClientExistPath = path.Join(baseURL, webClientExistPathDefault)
  1115. webClientTasksPath = path.Join(baseURL, webClientTasksPathDefault)
  1116. webStaticFilesPath = path.Join(baseURL, webStaticFilesPathDefault)
  1117. webOpenAPIPath = path.Join(baseURL, webOpenAPIPathDefault)
  1118. }
  1119. func updateWebAdminURLs(baseURL string) {
  1120. if !path.IsAbs(baseURL) {
  1121. baseURL = "/"
  1122. }
  1123. webRootPath = path.Join(baseURL, webRootPathDefault)
  1124. webBasePath = path.Join(baseURL, webBasePathDefault)
  1125. webBaseAdminPath = path.Join(baseURL, webBasePathAdminDefault)
  1126. webOIDCRedirectPath = path.Join(baseURL, webOIDCRedirectPathDefault)
  1127. webOAuth2RedirectPath = path.Join(baseURL, webOAuth2RedirectPathDefault)
  1128. webOAuth2TokenPath = path.Join(baseURL, webOAuth2TokenPathDefault)
  1129. webAdminSetupPath = path.Join(baseURL, webAdminSetupPathDefault)
  1130. webAdminLoginPath = path.Join(baseURL, webAdminLoginPathDefault)
  1131. webAdminOIDCLoginPath = path.Join(baseURL, webAdminOIDCLoginPathDefault)
  1132. webAdminTwoFactorPath = path.Join(baseURL, webAdminTwoFactorPathDefault)
  1133. webAdminTwoFactorRecoveryPath = path.Join(baseURL, webAdminTwoFactorRecoveryPathDefault)
  1134. webLogoutPath = path.Join(baseURL, webLogoutPathDefault)
  1135. webUsersPath = path.Join(baseURL, webUsersPathDefault)
  1136. webUserPath = path.Join(baseURL, webUserPathDefault)
  1137. webConnectionsPath = path.Join(baseURL, webConnectionsPathDefault)
  1138. webFoldersPath = path.Join(baseURL, webFoldersPathDefault)
  1139. webFolderPath = path.Join(baseURL, webFolderPathDefault)
  1140. webGroupsPath = path.Join(baseURL, webGroupsPathDefault)
  1141. webGroupPath = path.Join(baseURL, webGroupPathDefault)
  1142. webStatusPath = path.Join(baseURL, webStatusPathDefault)
  1143. webAdminsPath = path.Join(baseURL, webAdminsPathDefault)
  1144. webAdminPath = path.Join(baseURL, webAdminPathDefault)
  1145. webMaintenancePath = path.Join(baseURL, webMaintenancePathDefault)
  1146. webBackupPath = path.Join(baseURL, webBackupPathDefault)
  1147. webRestorePath = path.Join(baseURL, webRestorePathDefault)
  1148. webScanVFolderPath = path.Join(baseURL, webScanVFolderPathDefault)
  1149. webQuotaScanPath = path.Join(baseURL, webQuotaScanPathDefault)
  1150. webChangeAdminPwdPath = path.Join(baseURL, webChangeAdminPwdPathDefault)
  1151. webAdminForgotPwdPath = path.Join(baseURL, webAdminForgotPwdPathDefault)
  1152. webAdminResetPwdPath = path.Join(baseURL, webAdminResetPwdPathDefault)
  1153. webAdminProfilePath = path.Join(baseURL, webAdminProfilePathDefault)
  1154. webAdminMFAPath = path.Join(baseURL, webAdminMFAPathDefault)
  1155. webAdminEventRulesPath = path.Join(baseURL, webAdminEventRulesPathDefault)
  1156. webAdminEventRulePath = path.Join(baseURL, webAdminEventRulePathDefault)
  1157. webAdminEventActionsPath = path.Join(baseURL, webAdminEventActionsPathDefault)
  1158. webAdminEventActionPath = path.Join(baseURL, webAdminEventActionPathDefault)
  1159. webAdminRolesPath = path.Join(baseURL, webAdminRolesPathDefault)
  1160. webAdminRolePath = path.Join(baseURL, webAdminRolePathDefault)
  1161. webAdminTOTPGeneratePath = path.Join(baseURL, webAdminTOTPGeneratePathDefault)
  1162. webAdminTOTPValidatePath = path.Join(baseURL, webAdminTOTPValidatePathDefault)
  1163. webAdminTOTPSavePath = path.Join(baseURL, webAdminTOTPSavePathDefault)
  1164. webAdminRecoveryCodesPath = path.Join(baseURL, webAdminRecoveryCodesPathDefault)
  1165. webTemplateUser = path.Join(baseURL, webTemplateUserDefault)
  1166. webTemplateFolder = path.Join(baseURL, webTemplateFolderDefault)
  1167. webDefenderHostsPath = path.Join(baseURL, webDefenderHostsPathDefault)
  1168. webDefenderPath = path.Join(baseURL, webDefenderPathDefault)
  1169. webIPListPath = path.Join(baseURL, webIPListPathDefault)
  1170. webIPListsPath = path.Join(baseURL, webIPListsPathDefault)
  1171. webEventsPath = path.Join(baseURL, webEventsPathDefault)
  1172. webEventsFsSearchPath = path.Join(baseURL, webEventsFsSearchPathDefault)
  1173. webEventsProviderSearchPath = path.Join(baseURL, webEventsProviderSearchPathDefault)
  1174. webEventsLogSearchPath = path.Join(baseURL, webEventsLogSearchPathDefault)
  1175. webConfigsPath = path.Join(baseURL, webConfigsPathDefault)
  1176. webStaticFilesPath = path.Join(baseURL, webStaticFilesPathDefault)
  1177. webOpenAPIPath = path.Join(baseURL, webOpenAPIPathDefault)
  1178. }
  1179. // GetHTTPRouter returns an HTTP handler suitable to use for test cases
  1180. func GetHTTPRouter(b Binding) http.Handler {
  1181. server := newHttpdServer(b, filepath.Join("..", "..", "static"), "", CorsConfig{}, filepath.Join("..", "..", "openapi"))
  1182. server.initializeRouter()
  1183. return server.router
  1184. }
  1185. // the ticker cannot be started/stopped from multiple goroutines
  1186. func startCleanupTicker(duration time.Duration) {
  1187. stopCleanupTicker()
  1188. cleanupTicker = time.NewTicker(duration)
  1189. cleanupDone = make(chan bool)
  1190. go func() {
  1191. counter := int64(0)
  1192. for {
  1193. select {
  1194. case <-cleanupDone:
  1195. return
  1196. case <-cleanupTicker.C:
  1197. counter++
  1198. invalidatedJWTTokens.Cleanup()
  1199. resetCodesMgr.Cleanup()
  1200. webTaskMgr.Cleanup()
  1201. if counter%2 == 0 {
  1202. oidcMgr.cleanup()
  1203. oauth2Mgr.cleanup()
  1204. }
  1205. }
  1206. }
  1207. }()
  1208. }
  1209. func stopCleanupTicker() {
  1210. if cleanupTicker != nil {
  1211. cleanupTicker.Stop()
  1212. cleanupDone <- true
  1213. cleanupTicker = nil
  1214. }
  1215. }
  1216. func getSigningKey(signingPassphrase string) []byte {
  1217. if signingPassphrase != "" {
  1218. sk := sha256.Sum256([]byte(signingPassphrase))
  1219. return sk[:]
  1220. }
  1221. return util.GenerateRandomBytes(32)
  1222. }
  1223. // SetInstallationCodeResolver sets a function to call to resolve the installation code
  1224. func SetInstallationCodeResolver(fn FnInstallationCodeResolver) {
  1225. fnInstallationCodeResolver = fn
  1226. }
  1227. func resolveInstallationCode() string {
  1228. if fnInstallationCodeResolver != nil {
  1229. return fnInstallationCodeResolver(installationCode)
  1230. }
  1231. return installationCode
  1232. }
  1233. type neuteredFileSystem struct {
  1234. fs http.FileSystem
  1235. }
  1236. func (nfs neuteredFileSystem) Open(name string) (http.File, error) {
  1237. f, err := nfs.fs.Open(name)
  1238. if err != nil {
  1239. return nil, err
  1240. }
  1241. s, err := f.Stat()
  1242. if err != nil {
  1243. return nil, err
  1244. }
  1245. if s.IsDir() {
  1246. index := path.Join(name, "index.html")
  1247. if _, err := nfs.fs.Open(index); err != nil {
  1248. defer f.Close()
  1249. return nil, err
  1250. }
  1251. }
  1252. return f, nil
  1253. }