httpd.go 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. // Copyright (C) 2019-2022 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. // Package httpd implements REST API and Web interface for SFTPGo.
  15. // The OpenAPI 3 schema for the exposed 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. "path"
  25. "path/filepath"
  26. "runtime"
  27. "strings"
  28. "sync"
  29. "time"
  30. "github.com/go-chi/chi/v5"
  31. "github.com/go-chi/jwtauth/v5"
  32. "github.com/lestrrat-go/jwx/v2/jwa"
  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. userStreamZipPath = "/api/v2/user/streamzip"
  65. userUploadFilePath = "/api/v2/user/files/upload"
  66. userFilesDirsMetadataPath = "/api/v2/user/files/metadata"
  67. apiKeysPath = "/api/v2/apikeys"
  68. adminTOTPConfigsPath = "/api/v2/admin/totp/configs"
  69. adminTOTPGeneratePath = "/api/v2/admin/totp/generate"
  70. adminTOTPValidatePath = "/api/v2/admin/totp/validate"
  71. adminTOTPSavePath = "/api/v2/admin/totp/save"
  72. admin2FARecoveryCodesPath = "/api/v2/admin/2fa/recoverycodes"
  73. userTOTPConfigsPath = "/api/v2/user/totp/configs"
  74. userTOTPGeneratePath = "/api/v2/user/totp/generate"
  75. userTOTPValidatePath = "/api/v2/user/totp/validate"
  76. userTOTPSavePath = "/api/v2/user/totp/save"
  77. user2FARecoveryCodesPath = "/api/v2/user/2fa/recoverycodes"
  78. userProfilePath = "/api/v2/user/profile"
  79. userSharesPath = "/api/v2/user/shares"
  80. retentionBasePath = "/api/v2/retention/users"
  81. retentionChecksPath = "/api/v2/retention/users/checks"
  82. metadataBasePath = "/api/v2/metadata/users"
  83. metadataChecksPath = "/api/v2/metadata/users/checks"
  84. fsEventsPath = "/api/v2/events/fs"
  85. providerEventsPath = "/api/v2/events/provider"
  86. sharesPath = "/api/v2/shares"
  87. eventActionsPath = "/api/v2/eventactions"
  88. eventRulesPath = "/api/v2/eventrules"
  89. rolesPath = "/api/v2/roles"
  90. healthzPath = "/healthz"
  91. robotsTxtPath = "/robots.txt"
  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. webAdminTwoFactorPathDefault = "/web/admin/twofactor"
  101. webAdminTwoFactorRecoveryPathDefault = "/web/admin/twofactor-recovery"
  102. webLogoutPathDefault = "/web/admin/logout"
  103. webUsersPathDefault = "/web/admin/users"
  104. webUserPathDefault = "/web/admin/user"
  105. webConnectionsPathDefault = "/web/admin/connections"
  106. webFoldersPathDefault = "/web/admin/folders"
  107. webFolderPathDefault = "/web/admin/folder"
  108. webGroupsPathDefault = "/web/admin/groups"
  109. webGroupPathDefault = "/web/admin/group"
  110. webStatusPathDefault = "/web/admin/status"
  111. webAdminsPathDefault = "/web/admin/managers"
  112. webAdminPathDefault = "/web/admin/manager"
  113. webMaintenancePathDefault = "/web/admin/maintenance"
  114. webBackupPathDefault = "/web/admin/backup"
  115. webRestorePathDefault = "/web/admin/restore"
  116. webScanVFolderPathDefault = "/web/admin/quotas/scanfolder"
  117. webQuotaScanPathDefault = "/web/admin/quotas/scanuser"
  118. webChangeAdminPwdPathDefault = "/web/admin/changepwd"
  119. webAdminForgotPwdPathDefault = "/web/admin/forgot-password"
  120. webAdminResetPwdPathDefault = "/web/admin/reset-password"
  121. webAdminProfilePathDefault = "/web/admin/profile"
  122. webAdminMFAPathDefault = "/web/admin/mfa"
  123. webAdminEventRulesPathDefault = "/web/admin/eventrules"
  124. webAdminEventRulePathDefault = "/web/admin/eventrule"
  125. webAdminEventActionsPathDefault = "/web/admin/eventactions"
  126. webAdminEventActionPathDefault = "/web/admin/eventaction"
  127. webAdminRolesPathDefault = "/web/admin/roles"
  128. webAdminRolePathDefault = "/web/admin/role"
  129. webAdminTOTPGeneratePathDefault = "/web/admin/totp/generate"
  130. webAdminTOTPValidatePathDefault = "/web/admin/totp/validate"
  131. webAdminTOTPSavePathDefault = "/web/admin/totp/save"
  132. webAdminRecoveryCodesPathDefault = "/web/admin/recoverycodes"
  133. webTemplateUserDefault = "/web/admin/template/user"
  134. webTemplateFolderDefault = "/web/admin/template/folder"
  135. webDefenderPathDefault = "/web/admin/defender"
  136. webDefenderHostsPathDefault = "/web/admin/defender/hosts"
  137. webEventsPathDefault = "/web/admin/events"
  138. webEventsFsSearchPathDefault = "/web/admin/events/fs"
  139. webEventsProviderSearchPathDefault = "/web/admin/events/provider"
  140. webClientLoginPathDefault = "/web/client/login"
  141. webClientOIDCLoginPathDefault = "/web/client/oidclogin"
  142. webClientTwoFactorPathDefault = "/web/client/twofactor"
  143. webClientTwoFactorRecoveryPathDefault = "/web/client/twofactor-recovery"
  144. webClientFilesPathDefault = "/web/client/files"
  145. webClientFilePathDefault = "/web/client/file"
  146. webClientSharesPathDefault = "/web/client/shares"
  147. webClientSharePathDefault = "/web/client/share"
  148. webClientEditFilePathDefault = "/web/client/editfile"
  149. webClientDirsPathDefault = "/web/client/dirs"
  150. webClientDownloadZipPathDefault = "/web/client/downloadzip"
  151. webClientProfilePathDefault = "/web/client/profile"
  152. webClientMFAPathDefault = "/web/client/mfa"
  153. webClientTOTPGeneratePathDefault = "/web/client/totp/generate"
  154. webClientTOTPValidatePathDefault = "/web/client/totp/validate"
  155. webClientTOTPSavePathDefault = "/web/client/totp/save"
  156. webClientRecoveryCodesPathDefault = "/web/client/recoverycodes"
  157. webChangeClientPwdPathDefault = "/web/client/changepwd"
  158. webClientLogoutPathDefault = "/web/client/logout"
  159. webClientPubSharesPathDefault = "/web/client/pubshares"
  160. webClientForgotPwdPathDefault = "/web/client/forgot-password"
  161. webClientResetPwdPathDefault = "/web/client/reset-password"
  162. webClientViewPDFPathDefault = "/web/client/viewpdf"
  163. webClientGetPDFPathDefault = "/web/client/getpdf"
  164. webStaticFilesPathDefault = "/static"
  165. webOpenAPIPathDefault = "/openapi"
  166. // MaxRestoreSize defines the max size for the loaddata input file
  167. MaxRestoreSize = 10485760 // 10 MB
  168. maxRequestSize = 1048576 // 1MB
  169. maxLoginBodySize = 262144 // 256 KB
  170. httpdMaxEditFileSize = 1048576 // 1 MB
  171. maxMultipartMem = 10485760 // 10 MB
  172. osWindows = "windows"
  173. otpHeaderCode = "X-SFTPGO-OTP"
  174. mTimeHeader = "X-SFTPGO-MTIME"
  175. )
  176. var (
  177. certMgr *common.CertManager
  178. cleanupTicker *time.Ticker
  179. cleanupDone chan bool
  180. invalidatedJWTTokens sync.Map
  181. csrfTokenAuth *jwtauth.JWTAuth
  182. webRootPath string
  183. webBasePath string
  184. webBaseAdminPath string
  185. webBaseClientPath string
  186. webOIDCRedirectPath string
  187. webAdminSetupPath string
  188. webAdminOIDCLoginPath string
  189. webAdminLoginPath string
  190. webAdminTwoFactorPath string
  191. webAdminTwoFactorRecoveryPath string
  192. webLogoutPath string
  193. webUsersPath string
  194. webUserPath string
  195. webConnectionsPath string
  196. webFoldersPath string
  197. webFolderPath string
  198. webGroupsPath string
  199. webGroupPath string
  200. webStatusPath string
  201. webAdminsPath string
  202. webAdminPath string
  203. webMaintenancePath string
  204. webBackupPath string
  205. webRestorePath string
  206. webScanVFolderPath string
  207. webQuotaScanPath string
  208. webAdminProfilePath string
  209. webAdminMFAPath string
  210. webAdminEventRulesPath string
  211. webAdminEventRulePath string
  212. webAdminEventActionsPath string
  213. webAdminEventActionPath string
  214. webAdminRolesPath string
  215. webAdminRolePath string
  216. webAdminTOTPGeneratePath string
  217. webAdminTOTPValidatePath string
  218. webAdminTOTPSavePath string
  219. webAdminRecoveryCodesPath string
  220. webChangeAdminPwdPath string
  221. webAdminForgotPwdPath string
  222. webAdminResetPwdPath string
  223. webTemplateUser string
  224. webTemplateFolder string
  225. webDefenderPath string
  226. webEventsPath string
  227. webEventsFsSearchPath string
  228. webEventsProviderSearchPath string
  229. webDefenderHostsPath string
  230. webClientLoginPath string
  231. webClientOIDCLoginPath string
  232. webClientTwoFactorPath string
  233. webClientTwoFactorRecoveryPath string
  234. webClientFilesPath string
  235. webClientFilePath string
  236. webClientSharesPath string
  237. webClientSharePath string
  238. webClientEditFilePath string
  239. webClientDirsPath string
  240. webClientDownloadZipPath string
  241. webClientProfilePath string
  242. webChangeClientPwdPath string
  243. webClientMFAPath string
  244. webClientTOTPGeneratePath string
  245. webClientTOTPValidatePath string
  246. webClientTOTPSavePath string
  247. webClientRecoveryCodesPath string
  248. webClientPubSharesPath string
  249. webClientLogoutPath string
  250. webClientForgotPwdPath string
  251. webClientResetPwdPath string
  252. webClientViewPDFPath string
  253. webClientGetPDFPath string
  254. webStaticFilesPath string
  255. webOpenAPIPath string
  256. // max upload size for http clients, 1GB by default
  257. maxUploadFileSize = int64(1048576000)
  258. hideSupportLink bool
  259. installationCode string
  260. installationCodeHint string
  261. fnInstallationCodeResolver FnInstallationCodeResolver
  262. )
  263. func init() {
  264. updateWebAdminURLs("")
  265. updateWebClientURLs("")
  266. }
  267. // FnInstallationCodeResolver defines a method to get the installation code.
  268. // If the installation code cannot be resolved the provided default must be returned
  269. type FnInstallationCodeResolver func(defaultInstallationCode string) string
  270. // HTTPSProxyHeader defines an HTTPS proxy header as key/value.
  271. // For example Key could be "X-Forwarded-Proto" and Value "https"
  272. type HTTPSProxyHeader struct {
  273. Key string
  274. Value string
  275. }
  276. // SecurityConf allows to add some security related headers to HTTP responses and to restrict allowed hosts
  277. type SecurityConf struct {
  278. // Set to true to enable the security configurations
  279. Enabled bool `json:"enabled" mapstructure:"enabled"`
  280. // AllowedHosts is a list of fully qualified domain names that are allowed.
  281. // Default is empty list, which allows any and all host names.
  282. AllowedHosts []string `json:"allowed_hosts" mapstructure:"allowed_hosts"`
  283. // AllowedHostsAreRegex determines if the provided allowed hosts contains valid regular expressions
  284. AllowedHostsAreRegex bool `json:"allowed_hosts_are_regex" mapstructure:"allowed_hosts_are_regex"`
  285. // HostsProxyHeaders is a set of header keys that may hold a proxied hostname value for the request.
  286. HostsProxyHeaders []string `json:"hosts_proxy_headers" mapstructure:"hosts_proxy_headers"`
  287. // Set to true to redirect HTTP requests to HTTPS
  288. HTTPSRedirect bool `json:"https_redirect" mapstructure:"https_redirect"`
  289. // HTTPSHost defines the host name that is used to redirect HTTP requests to HTTPS.
  290. // Default is "", which indicates to use the same host.
  291. HTTPSHost string `json:"https_host" mapstructure:"https_host"`
  292. // HTTPSProxyHeaders is a list of header keys with associated values that would indicate a valid https request.
  293. HTTPSProxyHeaders []HTTPSProxyHeader `json:"https_proxy_headers" mapstructure:"https_proxy_headers"`
  294. // STSSeconds is the max-age of the Strict-Transport-Security header.
  295. // Default is 0, which would NOT include the header.
  296. STSSeconds int64 `json:"sts_seconds" mapstructure:"sts_seconds"`
  297. // If STSIncludeSubdomains is set to true, the "includeSubdomains" will be appended to the
  298. // Strict-Transport-Security header. Default is false.
  299. STSIncludeSubdomains bool `json:"sts_include_subdomains" mapstructure:"sts_include_subdomains"`
  300. // If STSPreload is set to true, the `preload` flag will be appended to the
  301. // Strict-Transport-Security header. Default is false.
  302. STSPreload bool `json:"sts_preload" mapstructure:"sts_preload"`
  303. // If ContentTypeNosniff is true, adds the X-Content-Type-Options header with the value "nosniff". Default is false.
  304. ContentTypeNosniff bool `json:"content_type_nosniff" mapstructure:"content_type_nosniff"`
  305. // ContentSecurityPolicy allows to set the Content-Security-Policy header value. Default is "".
  306. ContentSecurityPolicy string `json:"content_security_policy" mapstructure:"content_security_policy"`
  307. // PermissionsPolicy allows to set the Permissions-Policy header value. Default is "".
  308. PermissionsPolicy string `json:"permissions_policy" mapstructure:"permissions_policy"`
  309. // CrossOriginOpenerPolicy allows to set the `Cross-Origin-Opener-Policy` header value. Default is "".
  310. CrossOriginOpenerPolicy string `json:"cross_origin_opener_policy" mapstructure:"cross_origin_opener_policy"`
  311. // ExpectCTHeader allows to set the Expect-CT header value. Default is "".
  312. ExpectCTHeader string `json:"expect_ct_header" mapstructure:"expect_ct_header"`
  313. proxyHeaders []string
  314. }
  315. func (s *SecurityConf) updateProxyHeaders() {
  316. if !s.Enabled {
  317. s.proxyHeaders = nil
  318. return
  319. }
  320. s.proxyHeaders = s.HostsProxyHeaders
  321. for _, httpsProxyHeader := range s.HTTPSProxyHeaders {
  322. s.proxyHeaders = append(s.proxyHeaders, httpsProxyHeader.Key)
  323. }
  324. }
  325. func (s *SecurityConf) getHTTPSProxyHeaders() map[string]string {
  326. headers := make(map[string]string)
  327. for _, httpsProxyHeader := range s.HTTPSProxyHeaders {
  328. headers[httpsProxyHeader.Key] = httpsProxyHeader.Value
  329. }
  330. return headers
  331. }
  332. // UIBranding defines the supported customizations for the web UIs
  333. type UIBranding struct {
  334. // Name defines the text to show at the login page and as HTML title
  335. Name string `json:"name" mapstructure:"name"`
  336. // ShortName defines the name to show next to the logo image
  337. ShortName string `json:"short_name" mapstructure:"short_name"`
  338. // Path to your logo relative to "static_files_path".
  339. // For example, if you create a directory named "branding" inside the static dir and
  340. // put the "mylogo.png" file in it, you must set "/branding/mylogo.png" as logo path.
  341. LogoPath string `json:"logo_path" mapstructure:"logo_path"`
  342. // Path to the image to show on the login screen relative to "static_files_path"
  343. LoginImagePath string `json:"login_image_path" mapstructure:"login_image_path"`
  344. // Path to your favicon relative to "static_files_path"
  345. FaviconPath string `json:"favicon_path" mapstructure:"favicon_path"`
  346. // DisclaimerName defines the name for the link to your optional disclaimer
  347. DisclaimerName string `json:"disclaimer_name" mapstructure:"disclaimer_name"`
  348. // Path to the HTML page for your disclaimer relative to "static_files_path".
  349. DisclaimerPath string `json:"disclaimer_path" mapstructure:"disclaimer_path"`
  350. // Path to a custom CSS file, relative to "static_files_path", which replaces
  351. // the SB Admin2 default CSS. This is useful, for example, if you rebuild
  352. // SB Admin2 CSS to use custom colors
  353. DefaultCSS string `json:"default_css" mapstructure:"default_css"`
  354. // Additional CSS file paths, relative to "static_files_path", to include
  355. ExtraCSS []string `json:"extra_css" mapstructure:"extra_css"`
  356. }
  357. func (b *UIBranding) check() {
  358. if b.LogoPath != "" {
  359. b.LogoPath = util.CleanPath(b.LogoPath)
  360. } else {
  361. b.LogoPath = "/img/logo.png"
  362. }
  363. if b.LoginImagePath != "" {
  364. b.LoginImagePath = util.CleanPath(b.LoginImagePath)
  365. } else {
  366. b.LoginImagePath = "/img/login_image.png"
  367. }
  368. if b.FaviconPath != "" {
  369. b.FaviconPath = util.CleanPath(b.FaviconPath)
  370. } else {
  371. b.FaviconPath = "/favicon.ico"
  372. }
  373. if b.DisclaimerPath != "" {
  374. b.DisclaimerPath = util.CleanPath(b.DisclaimerPath)
  375. }
  376. if b.DefaultCSS != "" {
  377. b.DefaultCSS = util.CleanPath(b.DefaultCSS)
  378. } else {
  379. b.DefaultCSS = "/css/sb-admin-2.min.css"
  380. }
  381. for idx := range b.ExtraCSS {
  382. b.ExtraCSS[idx] = util.CleanPath(b.ExtraCSS[idx])
  383. }
  384. }
  385. // Branding defines the branding-related customizations supported
  386. type Branding struct {
  387. WebAdmin UIBranding `json:"web_admin" mapstructure:"web_admin"`
  388. WebClient UIBranding `json:"web_client" mapstructure:"web_client"`
  389. }
  390. // WebClientIntegration defines the configuration for an external Web Client integration
  391. type WebClientIntegration struct {
  392. // Files with these extensions can be sent to the configured URL
  393. FileExtensions []string `json:"file_extensions" mapstructure:"file_extensions"`
  394. // URL that will receive the files
  395. URL string `json:"url" mapstructure:"url"`
  396. }
  397. // Binding defines the configuration for a network listener
  398. type Binding struct {
  399. // The address to listen on. A blank value means listen on all available network interfaces.
  400. Address string `json:"address" mapstructure:"address"`
  401. // The port used for serving requests
  402. Port int `json:"port" mapstructure:"port"`
  403. // Enable the built-in admin interface.
  404. // You have to define TemplatesPath and StaticFilesPath for this to work
  405. EnableWebAdmin bool `json:"enable_web_admin" mapstructure:"enable_web_admin"`
  406. // Enable the built-in client interface.
  407. // You have to define TemplatesPath and StaticFilesPath for this to work
  408. EnableWebClient bool `json:"enable_web_client" mapstructure:"enable_web_client"`
  409. // Enable REST API
  410. EnableRESTAPI bool `json:"enable_rest_api" mapstructure:"enable_rest_api"`
  411. // Defines the login methods available for the WebAdmin and WebClient UIs:
  412. //
  413. // - 0 means any configured method: username/password login form and OIDC, if enabled
  414. // - 1 means OIDC for the WebAdmin UI
  415. // - 2 means OIDC for the WebClient UI
  416. // - 4 means login form for the WebAdmin UI
  417. // - 8 means login form for the WebClient UI
  418. //
  419. // You can combine the values. For example 3 means that you can only login using OIDC on
  420. // both WebClient and WebAdmin UI.
  421. EnabledLoginMethods int `json:"enabled_login_methods" mapstructure:"enabled_login_methods"`
  422. // you also need to provide a certificate for enabling HTTPS
  423. EnableHTTPS bool `json:"enable_https" mapstructure:"enable_https"`
  424. // Certificate and matching private key for this specific binding, if empty the global
  425. // ones will be used, if any
  426. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  427. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  428. // Defines the minimum TLS version. 13 means TLS 1.3, default is TLS 1.2
  429. MinTLSVersion int `json:"min_tls_version" mapstructure:"min_tls_version"`
  430. // set to 1 to require client certificate authentication in addition to basic auth.
  431. // You need to define at least a certificate authority for this to work
  432. ClientAuthType int `json:"client_auth_type" mapstructure:"client_auth_type"`
  433. // TLSCipherSuites is a list of supported cipher suites for TLS version 1.2.
  434. // If CipherSuites is nil/empty, a default list of secure cipher suites
  435. // is used, with a preference order based on hardware performance.
  436. // Note that TLS 1.3 ciphersuites are not configurable.
  437. // The supported ciphersuites names are defined here:
  438. //
  439. // https://github.com/golang/go/blob/master/src/crypto/tls/cipher_suites.go#L52
  440. //
  441. // any invalid name will be silently ignored.
  442. // The order matters, the ciphers listed first will be the preferred ones.
  443. TLSCipherSuites []string `json:"tls_cipher_suites" mapstructure:"tls_cipher_suites"`
  444. // List of IP addresses and IP ranges allowed to set client IP proxy headers and
  445. // X-Forwarded-Proto header.
  446. ProxyAllowed []string `json:"proxy_allowed" mapstructure:"proxy_allowed"`
  447. // Allowed client IP proxy header such as "X-Forwarded-For", "X-Real-IP"
  448. ClientIPProxyHeader string `json:"client_ip_proxy_header" mapstructure:"client_ip_proxy_header"`
  449. // Some client IP headers such as "X-Forwarded-For" can contain multiple IP address, this setting
  450. // define the position to trust starting from the right. For example if we have:
  451. // "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"
  452. // as client IP, if depth is 1, "12.0.0.1" will be used and so on
  453. ClientIPHeaderDepth int `json:"client_ip_header_depth" mapstructure:"client_ip_header_depth"`
  454. // If both web admin and web client are enabled each login page will show a link
  455. // to the other one. This setting allows to hide this link:
  456. // - 0 login links are displayed on both admin and client login page. This is the default
  457. // - 1 the login link to the web client login page is hidden on admin login page
  458. // - 2 the login link to the web admin login page is hidden on client login page
  459. // The flags can be combined, for example 3 will disable both login links.
  460. HideLoginURL int `json:"hide_login_url" mapstructure:"hide_login_url"`
  461. // Enable the built-in OpenAPI renderer
  462. RenderOpenAPI bool `json:"render_openapi" mapstructure:"render_openapi"`
  463. // Enabling web client integrations you can render or modify the files with the specified
  464. // extensions using an external tool.
  465. WebClientIntegrations []WebClientIntegration `json:"web_client_integrations" mapstructure:"web_client_integrations"`
  466. // Defining an OIDC configuration the web admin and web client UI will use OpenID to authenticate users.
  467. OIDC OIDC `json:"oidc" mapstructure:"oidc"`
  468. // Security defines security headers to add to HTTP responses and allows to restrict allowed hosts
  469. Security SecurityConf `json:"security" mapstructure:"security"`
  470. // Branding defines customizations to suit your brand
  471. Branding Branding `json:"branding" mapstructure:"branding"`
  472. allowHeadersFrom []func(net.IP) bool
  473. }
  474. func (b *Binding) checkWebClientIntegrations() {
  475. var integrations []WebClientIntegration
  476. for _, integration := range b.WebClientIntegrations {
  477. if integration.URL != "" && len(integration.FileExtensions) > 0 {
  478. integrations = append(integrations, integration)
  479. }
  480. }
  481. b.WebClientIntegrations = integrations
  482. }
  483. func (b *Binding) checkBranding() {
  484. b.Branding.WebAdmin.check()
  485. b.Branding.WebClient.check()
  486. if b.Branding.WebAdmin.Name == "" {
  487. b.Branding.WebAdmin.Name = "SFTPGo WebAdmin"
  488. }
  489. if b.Branding.WebAdmin.ShortName == "" {
  490. b.Branding.WebAdmin.ShortName = "WebAdmin"
  491. }
  492. if b.Branding.WebClient.Name == "" {
  493. b.Branding.WebClient.Name = "SFTPGo WebClient"
  494. }
  495. if b.Branding.WebClient.ShortName == "" {
  496. b.Branding.WebClient.ShortName = "WebClient"
  497. }
  498. }
  499. func (b *Binding) parseAllowedProxy() error {
  500. if filepath.IsAbs(b.Address) && len(b.ProxyAllowed) > 0 {
  501. // unix domain socket
  502. b.allowHeadersFrom = []func(net.IP) bool{func(ip net.IP) bool { return true }}
  503. return nil
  504. }
  505. allowedFuncs, err := util.ParseAllowedIPAndRanges(b.ProxyAllowed)
  506. if err != nil {
  507. return err
  508. }
  509. b.allowHeadersFrom = allowedFuncs
  510. return nil
  511. }
  512. // GetAddress returns the binding address
  513. func (b *Binding) GetAddress() string {
  514. return fmt.Sprintf("%s:%d", b.Address, b.Port)
  515. }
  516. // IsValid returns true if the binding is valid
  517. func (b *Binding) IsValid() bool {
  518. if !b.EnableRESTAPI && !b.EnableWebAdmin && !b.EnableWebClient {
  519. return false
  520. }
  521. if b.Port > 0 {
  522. return true
  523. }
  524. if filepath.IsAbs(b.Address) && runtime.GOOS != osWindows {
  525. return true
  526. }
  527. return false
  528. }
  529. func (b *Binding) isWebAdminOIDCLoginDisabled() bool {
  530. if b.EnableWebAdmin {
  531. if b.EnabledLoginMethods == 0 {
  532. return false
  533. }
  534. return b.EnabledLoginMethods&1 == 0
  535. }
  536. return false
  537. }
  538. func (b *Binding) isWebClientOIDCLoginDisabled() bool {
  539. if b.EnableWebClient {
  540. if b.EnabledLoginMethods == 0 {
  541. return false
  542. }
  543. return b.EnabledLoginMethods&2 == 0
  544. }
  545. return false
  546. }
  547. func (b *Binding) isWebAdminLoginFormDisabled() bool {
  548. if b.EnableWebAdmin {
  549. if b.EnabledLoginMethods == 0 {
  550. return false
  551. }
  552. return b.EnabledLoginMethods&4 == 0
  553. }
  554. return false
  555. }
  556. func (b *Binding) isWebClientLoginFormDisabled() bool {
  557. if b.EnableWebClient {
  558. if b.EnabledLoginMethods == 0 {
  559. return false
  560. }
  561. return b.EnabledLoginMethods&8 == 0
  562. }
  563. return false
  564. }
  565. func (b *Binding) checkLoginMethods() error {
  566. if b.isWebAdminLoginFormDisabled() && b.isWebAdminOIDCLoginDisabled() {
  567. return errors.New("no login method available for WebAdmin UI")
  568. }
  569. if !b.isWebAdminOIDCLoginDisabled() {
  570. if b.isWebAdminLoginFormDisabled() && !b.OIDC.hasRoles() {
  571. return errors.New("no login method available for WebAdmin UI")
  572. }
  573. }
  574. if b.isWebClientLoginFormDisabled() && b.isWebClientOIDCLoginDisabled() {
  575. return errors.New("no login method available for WebClient UI")
  576. }
  577. if !b.isWebClientOIDCLoginDisabled() {
  578. if b.isWebClientLoginFormDisabled() && !b.OIDC.isEnabled() {
  579. return errors.New("no login method available for WebClient UI")
  580. }
  581. }
  582. return nil
  583. }
  584. func (b *Binding) showAdminLoginURL() bool {
  585. if !b.EnableWebAdmin {
  586. return false
  587. }
  588. if b.HideLoginURL&2 != 0 {
  589. return false
  590. }
  591. return true
  592. }
  593. func (b *Binding) showClientLoginURL() bool {
  594. if !b.EnableWebClient {
  595. return false
  596. }
  597. if b.HideLoginURL&1 != 0 {
  598. return false
  599. }
  600. return true
  601. }
  602. type defenderStatus struct {
  603. IsActive bool `json:"is_active"`
  604. }
  605. // ServicesStatus keep the state of the running services
  606. type ServicesStatus struct {
  607. SSH sftpd.ServiceStatus `json:"ssh"`
  608. FTP ftpd.ServiceStatus `json:"ftp"`
  609. WebDAV webdavd.ServiceStatus `json:"webdav"`
  610. DataProvider dataprovider.ProviderStatus `json:"data_provider"`
  611. Defender defenderStatus `json:"defender"`
  612. MFA mfa.ServiceStatus `json:"mfa"`
  613. }
  614. // SetupConfig defines the configuration parameters for the initial web admin setup
  615. type SetupConfig struct {
  616. // Installation code to require when creating the first admin account.
  617. // As for the other configurations, this value is read at SFTPGo startup and not at runtime
  618. // even if set using an environment variable.
  619. // This is not a license key or similar, the purpose here is to prevent anyone who can access
  620. // to the initial setup screen from creating an admin user
  621. InstallationCode string `json:"installation_code" mapstructure:"installation_code"`
  622. // Description for the installation code input field
  623. InstallationCodeHint string `json:"installation_code_hint" mapstructure:"installation_code_hint"`
  624. }
  625. // CorsConfig defines the CORS configuration
  626. type CorsConfig struct {
  627. AllowedOrigins []string `json:"allowed_origins" mapstructure:"allowed_origins"`
  628. AllowedMethods []string `json:"allowed_methods" mapstructure:"allowed_methods"`
  629. AllowedHeaders []string `json:"allowed_headers" mapstructure:"allowed_headers"`
  630. ExposedHeaders []string `json:"exposed_headers" mapstructure:"exposed_headers"`
  631. AllowCredentials bool `json:"allow_credentials" mapstructure:"allow_credentials"`
  632. Enabled bool `json:"enabled" mapstructure:"enabled"`
  633. MaxAge int `json:"max_age" mapstructure:"max_age"`
  634. OptionsPassthrough bool `json:"options_passthrough" mapstructure:"options_passthrough"`
  635. OptionsSuccessStatus int `json:"options_success_status" mapstructure:"options_success_status"`
  636. AllowPrivateNetwork bool `json:"allow_private_network" mapstructure:"allow_private_network"`
  637. }
  638. // Conf httpd daemon configuration
  639. type Conf struct {
  640. // Addresses and ports to bind to
  641. Bindings []Binding `json:"bindings" mapstructure:"bindings"`
  642. // Path to the HTML web templates. This can be an absolute path or a path relative to the config dir
  643. TemplatesPath string `json:"templates_path" mapstructure:"templates_path"`
  644. // Path to the static files for the web interface. This can be an absolute path or a path relative to the config dir.
  645. // If both TemplatesPath and StaticFilesPath are empty the built-in web interface will be disabled
  646. StaticFilesPath string `json:"static_files_path" mapstructure:"static_files_path"`
  647. // Path to the backup directory. This can be an absolute path or a path relative to the config dir
  648. //BackupsPath string `json:"backups_path" mapstructure:"backups_path"`
  649. // Path to the directory that contains the OpenAPI schema and the default renderer.
  650. // This can be an absolute path or a path relative to the config dir
  651. OpenAPIPath string `json:"openapi_path" mapstructure:"openapi_path"`
  652. // Defines a base URL for the web admin and client interfaces. If empty web admin and client resources will
  653. // be available at the root ("/") URI. If defined it must be an absolute URI or it will be ignored.
  654. WebRoot string `json:"web_root" mapstructure:"web_root"`
  655. // If files containing a certificate and matching private key for the server are provided you can enable
  656. // HTTPS connections for the configured bindings.
  657. // Certificate and key files can be reloaded on demand sending a "SIGHUP" signal on Unix based systems and a
  658. // "paramchange" request to the running service on Windows.
  659. CertificateFile string `json:"certificate_file" mapstructure:"certificate_file"`
  660. CertificateKeyFile string `json:"certificate_key_file" mapstructure:"certificate_key_file"`
  661. // CACertificates defines the set of root certificate authorities to be used to verify client certificates.
  662. CACertificates []string `json:"ca_certificates" mapstructure:"ca_certificates"`
  663. // CARevocationLists defines a set a revocation lists, one for each root CA, to be used to check
  664. // if a client certificate has been revoked
  665. CARevocationLists []string `json:"ca_revocation_lists" mapstructure:"ca_revocation_lists"`
  666. // SigningPassphrase defines the passphrase to use to derive the signing key for JWT and CSRF tokens.
  667. // If empty a random signing key will be generated each time SFTPGo starts. If you set a
  668. // signing passphrase you should consider rotating it periodically for added security
  669. SigningPassphrase string `json:"signing_passphrase" mapstructure:"signing_passphrase"`
  670. // TokenValidation allows to define how to validate JWT tokens, cookies and CSRF tokens.
  671. // By default all the available security checks are enabled. Set to 1 to disable the requirement
  672. // that a token must be used by the same IP for which it was issued.
  673. TokenValidation int `json:"token_validation" mapstructure:"token_validation"`
  674. // MaxUploadFileSize Defines the maximum request body size, in bytes, for Web Client/API HTTP upload requests.
  675. // 0 means no limit
  676. MaxUploadFileSize int64 `json:"max_upload_file_size" mapstructure:"max_upload_file_size"`
  677. // CORS configuration
  678. Cors CorsConfig `json:"cors" mapstructure:"cors"`
  679. // Initial setup configuration
  680. Setup SetupConfig `json:"setup" mapstructure:"setup"`
  681. // If enabled, the link to the sponsors section will not appear on the setup screen page
  682. HideSupportLink bool `json:"hide_support_link" mapstructure:"hide_support_link"`
  683. }
  684. type apiResponse struct {
  685. Error string `json:"error,omitempty"`
  686. Message string `json:"message"`
  687. }
  688. // ShouldBind returns true if there is at least a valid binding
  689. func (c *Conf) ShouldBind() bool {
  690. for _, binding := range c.Bindings {
  691. if binding.IsValid() {
  692. return true
  693. }
  694. }
  695. return false
  696. }
  697. func (c *Conf) isWebAdminEnabled() bool {
  698. for _, binding := range c.Bindings {
  699. if binding.EnableWebAdmin {
  700. return true
  701. }
  702. }
  703. return false
  704. }
  705. func (c *Conf) isWebClientEnabled() bool {
  706. for _, binding := range c.Bindings {
  707. if binding.EnableWebClient {
  708. return true
  709. }
  710. }
  711. return false
  712. }
  713. func (c *Conf) checkRequiredDirs(staticFilesPath, templatesPath string) error {
  714. if (c.isWebAdminEnabled() || c.isWebClientEnabled()) && (staticFilesPath == "" || templatesPath == "") {
  715. return fmt.Errorf("required directory is invalid, static file path: %#v template path: %#v",
  716. staticFilesPath, templatesPath)
  717. }
  718. return nil
  719. }
  720. func (c *Conf) getRedacted() Conf {
  721. redacted := "[redacted]"
  722. conf := *c
  723. if conf.SigningPassphrase != "" {
  724. conf.SigningPassphrase = redacted
  725. }
  726. if conf.Setup.InstallationCode != "" {
  727. conf.Setup.InstallationCode = redacted
  728. }
  729. conf.Bindings = nil
  730. for _, binding := range c.Bindings {
  731. if binding.OIDC.ClientID != "" {
  732. binding.OIDC.ClientID = redacted
  733. }
  734. if binding.OIDC.ClientSecret != "" {
  735. binding.OIDC.ClientSecret = redacted
  736. }
  737. conf.Bindings = append(conf.Bindings, binding)
  738. }
  739. return conf
  740. }
  741. func (c *Conf) getKeyPairs(configDir string) []common.TLSKeyPair {
  742. var keyPairs []common.TLSKeyPair
  743. for _, binding := range c.Bindings {
  744. certificateFile := getConfigPath(binding.CertificateFile, configDir)
  745. certificateKeyFile := getConfigPath(binding.CertificateKeyFile, configDir)
  746. if certificateFile != "" && certificateKeyFile != "" {
  747. keyPairs = append(keyPairs, common.TLSKeyPair{
  748. Cert: certificateFile,
  749. Key: certificateKeyFile,
  750. ID: binding.GetAddress(),
  751. })
  752. }
  753. }
  754. certificateFile := getConfigPath(c.CertificateFile, configDir)
  755. certificateKeyFile := getConfigPath(c.CertificateKeyFile, configDir)
  756. if certificateFile != "" && certificateKeyFile != "" {
  757. keyPairs = append(keyPairs, common.TLSKeyPair{
  758. Cert: certificateFile,
  759. Key: certificateKeyFile,
  760. ID: common.DefaultTLSKeyPaidID,
  761. })
  762. }
  763. return keyPairs
  764. }
  765. func (c *Conf) setTokenValidationMode() {
  766. if c.TokenValidation == 1 {
  767. tokenValidationMode = tokenValidationNoIPMatch
  768. } else {
  769. tokenValidationMode = tokenValidationFull
  770. }
  771. }
  772. // Initialize configures and starts the HTTP server
  773. func (c *Conf) Initialize(configDir string, isShared int) error {
  774. logger.Info(logSender, "", "initializing HTTP server with config %+v", c.getRedacted())
  775. resetCodesMgr = newResetCodeManager(isShared)
  776. oidcMgr = newOIDCManager(isShared)
  777. staticFilesPath := util.FindSharedDataPath(c.StaticFilesPath, configDir)
  778. templatesPath := util.FindSharedDataPath(c.TemplatesPath, configDir)
  779. openAPIPath := util.FindSharedDataPath(c.OpenAPIPath, configDir)
  780. if err := c.checkRequiredDirs(staticFilesPath, templatesPath); err != nil {
  781. return err
  782. }
  783. if c.isWebAdminEnabled() {
  784. updateWebAdminURLs(c.WebRoot)
  785. loadAdminTemplates(templatesPath)
  786. } else {
  787. logger.Info(logSender, "", "built-in web admin interface disabled")
  788. }
  789. if c.isWebClientEnabled() {
  790. updateWebClientURLs(c.WebRoot)
  791. loadClientTemplates(templatesPath)
  792. } else {
  793. logger.Info(logSender, "", "built-in web client interface disabled")
  794. }
  795. keyPairs := c.getKeyPairs(configDir)
  796. if len(keyPairs) > 0 {
  797. mgr, err := common.NewCertManager(keyPairs, configDir, logSender)
  798. if err != nil {
  799. return err
  800. }
  801. mgr.SetCACertificates(c.CACertificates)
  802. if err := mgr.LoadRootCAs(); err != nil {
  803. return err
  804. }
  805. mgr.SetCARevocationLists(c.CARevocationLists)
  806. if err := mgr.LoadCRLs(); err != nil {
  807. return err
  808. }
  809. certMgr = mgr
  810. }
  811. csrfTokenAuth = jwtauth.New(jwa.HS256.String(), getSigningKey(c.SigningPassphrase), nil)
  812. hideSupportLink = c.HideSupportLink
  813. exitChannel := make(chan error, 1)
  814. for _, binding := range c.Bindings {
  815. if !binding.IsValid() {
  816. continue
  817. }
  818. if err := binding.parseAllowedProxy(); err != nil {
  819. return err
  820. }
  821. binding.checkWebClientIntegrations()
  822. binding.checkBranding()
  823. binding.Security.updateProxyHeaders()
  824. go func(b Binding) {
  825. if err := b.OIDC.initialize(); err != nil {
  826. exitChannel <- err
  827. return
  828. }
  829. if err := b.checkLoginMethods(); err != nil {
  830. exitChannel <- err
  831. return
  832. }
  833. server := newHttpdServer(b, staticFilesPath, c.SigningPassphrase, c.Cors, openAPIPath)
  834. server.setShared(isShared)
  835. exitChannel <- server.listenAndServe()
  836. }(binding)
  837. }
  838. maxUploadFileSize = c.MaxUploadFileSize
  839. installationCode = c.Setup.InstallationCode
  840. installationCodeHint = c.Setup.InstallationCodeHint
  841. startCleanupTicker(tokenDuration / 2)
  842. c.setTokenValidationMode()
  843. return <-exitChannel
  844. }
  845. func isWebRequest(r *http.Request) bool {
  846. return strings.HasPrefix(r.RequestURI, webBasePath+"/")
  847. }
  848. func isWebClientRequest(r *http.Request) bool {
  849. return strings.HasPrefix(r.RequestURI, webBaseClientPath+"/")
  850. }
  851. // ReloadCertificateMgr reloads the certificate manager
  852. func ReloadCertificateMgr() error {
  853. if certMgr != nil {
  854. return certMgr.Reload()
  855. }
  856. return nil
  857. }
  858. func getConfigPath(name, configDir string) string {
  859. if !util.IsFileInputValid(name) {
  860. return ""
  861. }
  862. if name != "" && !filepath.IsAbs(name) {
  863. return filepath.Join(configDir, name)
  864. }
  865. return name
  866. }
  867. func getServicesStatus() *ServicesStatus {
  868. status := &ServicesStatus{
  869. SSH: sftpd.GetStatus(),
  870. FTP: ftpd.GetStatus(),
  871. WebDAV: webdavd.GetStatus(),
  872. DataProvider: dataprovider.GetProviderStatus(),
  873. Defender: defenderStatus{
  874. IsActive: common.Config.DefenderConfig.Enabled,
  875. },
  876. MFA: mfa.GetStatus(),
  877. }
  878. return status
  879. }
  880. func fileServer(r chi.Router, path string, root http.FileSystem) {
  881. if path != "/" && path[len(path)-1] != '/' {
  882. r.Get(path, http.RedirectHandler(path+"/", http.StatusMovedPermanently).ServeHTTP)
  883. path += "/"
  884. }
  885. path += "*"
  886. r.Get(path, func(w http.ResponseWriter, r *http.Request) {
  887. rctx := chi.RouteContext(r.Context())
  888. pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*")
  889. fs := http.StripPrefix(pathPrefix, http.FileServer(root))
  890. fs.ServeHTTP(w, r)
  891. })
  892. }
  893. func updateWebClientURLs(baseURL string) {
  894. if !path.IsAbs(baseURL) {
  895. baseURL = "/"
  896. }
  897. webRootPath = path.Join(baseURL, webRootPathDefault)
  898. webBasePath = path.Join(baseURL, webBasePathDefault)
  899. webBaseClientPath = path.Join(baseURL, webBasePathClientDefault)
  900. webOIDCRedirectPath = path.Join(baseURL, webOIDCRedirectPathDefault)
  901. webClientLoginPath = path.Join(baseURL, webClientLoginPathDefault)
  902. webClientOIDCLoginPath = path.Join(baseURL, webClientOIDCLoginPathDefault)
  903. webClientTwoFactorPath = path.Join(baseURL, webClientTwoFactorPathDefault)
  904. webClientTwoFactorRecoveryPath = path.Join(baseURL, webClientTwoFactorRecoveryPathDefault)
  905. webClientFilesPath = path.Join(baseURL, webClientFilesPathDefault)
  906. webClientFilePath = path.Join(baseURL, webClientFilePathDefault)
  907. webClientSharesPath = path.Join(baseURL, webClientSharesPathDefault)
  908. webClientPubSharesPath = path.Join(baseURL, webClientPubSharesPathDefault)
  909. webClientSharePath = path.Join(baseURL, webClientSharePathDefault)
  910. webClientEditFilePath = path.Join(baseURL, webClientEditFilePathDefault)
  911. webClientDirsPath = path.Join(baseURL, webClientDirsPathDefault)
  912. webClientDownloadZipPath = path.Join(baseURL, webClientDownloadZipPathDefault)
  913. webClientProfilePath = path.Join(baseURL, webClientProfilePathDefault)
  914. webChangeClientPwdPath = path.Join(baseURL, webChangeClientPwdPathDefault)
  915. webClientLogoutPath = path.Join(baseURL, webClientLogoutPathDefault)
  916. webClientMFAPath = path.Join(baseURL, webClientMFAPathDefault)
  917. webClientTOTPGeneratePath = path.Join(baseURL, webClientTOTPGeneratePathDefault)
  918. webClientTOTPValidatePath = path.Join(baseURL, webClientTOTPValidatePathDefault)
  919. webClientTOTPSavePath = path.Join(baseURL, webClientTOTPSavePathDefault)
  920. webClientRecoveryCodesPath = path.Join(baseURL, webClientRecoveryCodesPathDefault)
  921. webClientForgotPwdPath = path.Join(baseURL, webClientForgotPwdPathDefault)
  922. webClientResetPwdPath = path.Join(baseURL, webClientResetPwdPathDefault)
  923. webClientViewPDFPath = path.Join(baseURL, webClientViewPDFPathDefault)
  924. webClientGetPDFPath = path.Join(baseURL, webClientGetPDFPathDefault)
  925. }
  926. func updateWebAdminURLs(baseURL string) {
  927. if !path.IsAbs(baseURL) {
  928. baseURL = "/"
  929. }
  930. webRootPath = path.Join(baseURL, webRootPathDefault)
  931. webBasePath = path.Join(baseURL, webBasePathDefault)
  932. webBaseAdminPath = path.Join(baseURL, webBasePathAdminDefault)
  933. webOIDCRedirectPath = path.Join(baseURL, webOIDCRedirectPathDefault)
  934. webAdminSetupPath = path.Join(baseURL, webAdminSetupPathDefault)
  935. webAdminLoginPath = path.Join(baseURL, webAdminLoginPathDefault)
  936. webAdminOIDCLoginPath = path.Join(baseURL, webAdminOIDCLoginPathDefault)
  937. webAdminTwoFactorPath = path.Join(baseURL, webAdminTwoFactorPathDefault)
  938. webAdminTwoFactorRecoveryPath = path.Join(baseURL, webAdminTwoFactorRecoveryPathDefault)
  939. webLogoutPath = path.Join(baseURL, webLogoutPathDefault)
  940. webUsersPath = path.Join(baseURL, webUsersPathDefault)
  941. webUserPath = path.Join(baseURL, webUserPathDefault)
  942. webConnectionsPath = path.Join(baseURL, webConnectionsPathDefault)
  943. webFoldersPath = path.Join(baseURL, webFoldersPathDefault)
  944. webFolderPath = path.Join(baseURL, webFolderPathDefault)
  945. webGroupsPath = path.Join(baseURL, webGroupsPathDefault)
  946. webGroupPath = path.Join(baseURL, webGroupPathDefault)
  947. webStatusPath = path.Join(baseURL, webStatusPathDefault)
  948. webAdminsPath = path.Join(baseURL, webAdminsPathDefault)
  949. webAdminPath = path.Join(baseURL, webAdminPathDefault)
  950. webMaintenancePath = path.Join(baseURL, webMaintenancePathDefault)
  951. webBackupPath = path.Join(baseURL, webBackupPathDefault)
  952. webRestorePath = path.Join(baseURL, webRestorePathDefault)
  953. webScanVFolderPath = path.Join(baseURL, webScanVFolderPathDefault)
  954. webQuotaScanPath = path.Join(baseURL, webQuotaScanPathDefault)
  955. webChangeAdminPwdPath = path.Join(baseURL, webChangeAdminPwdPathDefault)
  956. webAdminForgotPwdPath = path.Join(baseURL, webAdminForgotPwdPathDefault)
  957. webAdminResetPwdPath = path.Join(baseURL, webAdminResetPwdPathDefault)
  958. webAdminProfilePath = path.Join(baseURL, webAdminProfilePathDefault)
  959. webAdminMFAPath = path.Join(baseURL, webAdminMFAPathDefault)
  960. webAdminEventRulesPath = path.Join(baseURL, webAdminEventRulesPathDefault)
  961. webAdminEventRulePath = path.Join(baseURL, webAdminEventRulePathDefault)
  962. webAdminEventActionsPath = path.Join(baseURL, webAdminEventActionsPathDefault)
  963. webAdminEventActionPath = path.Join(baseURL, webAdminEventActionPathDefault)
  964. webAdminRolesPath = path.Join(baseURL, webAdminRolesPathDefault)
  965. webAdminRolePath = path.Join(baseURL, webAdminRolePathDefault)
  966. webAdminTOTPGeneratePath = path.Join(baseURL, webAdminTOTPGeneratePathDefault)
  967. webAdminTOTPValidatePath = path.Join(baseURL, webAdminTOTPValidatePathDefault)
  968. webAdminTOTPSavePath = path.Join(baseURL, webAdminTOTPSavePathDefault)
  969. webAdminRecoveryCodesPath = path.Join(baseURL, webAdminRecoveryCodesPathDefault)
  970. webTemplateUser = path.Join(baseURL, webTemplateUserDefault)
  971. webTemplateFolder = path.Join(baseURL, webTemplateFolderDefault)
  972. webDefenderHostsPath = path.Join(baseURL, webDefenderHostsPathDefault)
  973. webDefenderPath = path.Join(baseURL, webDefenderPathDefault)
  974. webEventsPath = path.Join(baseURL, webEventsPathDefault)
  975. webEventsFsSearchPath = path.Join(baseURL, webEventsFsSearchPathDefault)
  976. webEventsProviderSearchPath = path.Join(baseURL, webEventsProviderSearchPathDefault)
  977. webStaticFilesPath = path.Join(baseURL, webStaticFilesPathDefault)
  978. webOpenAPIPath = path.Join(baseURL, webOpenAPIPathDefault)
  979. }
  980. // GetHTTPRouter returns an HTTP handler suitable to use for test cases
  981. func GetHTTPRouter(b Binding) http.Handler {
  982. server := newHttpdServer(b, filepath.Join("..", "..", "static"), "", CorsConfig{}, filepath.Join("..", "..", "openapi"))
  983. server.initializeRouter()
  984. return server.router
  985. }
  986. // the ticker cannot be started/stopped from multiple goroutines
  987. func startCleanupTicker(duration time.Duration) {
  988. stopCleanupTicker()
  989. cleanupTicker = time.NewTicker(duration)
  990. cleanupDone = make(chan bool)
  991. go func() {
  992. counter := int64(0)
  993. for {
  994. select {
  995. case <-cleanupDone:
  996. return
  997. case <-cleanupTicker.C:
  998. counter++
  999. cleanupExpiredJWTTokens()
  1000. resetCodesMgr.Cleanup()
  1001. if counter%2 == 0 {
  1002. oidcMgr.cleanup()
  1003. }
  1004. }
  1005. }
  1006. }()
  1007. }
  1008. func stopCleanupTicker() {
  1009. if cleanupTicker != nil {
  1010. cleanupTicker.Stop()
  1011. cleanupDone <- true
  1012. cleanupTicker = nil
  1013. }
  1014. }
  1015. func cleanupExpiredJWTTokens() {
  1016. invalidatedJWTTokens.Range(func(key, value any) bool {
  1017. exp, ok := value.(time.Time)
  1018. if !ok || exp.Before(time.Now().UTC()) {
  1019. invalidatedJWTTokens.Delete(key)
  1020. }
  1021. return true
  1022. })
  1023. }
  1024. func getSigningKey(signingPassphrase string) []byte {
  1025. if signingPassphrase != "" {
  1026. sk := sha256.Sum256([]byte(signingPassphrase))
  1027. return sk[:]
  1028. }
  1029. return util.GenerateRandomBytes(32)
  1030. }
  1031. // SetInstallationCodeResolver sets a function to call to resolve the installation code
  1032. func SetInstallationCodeResolver(fn FnInstallationCodeResolver) {
  1033. fnInstallationCodeResolver = fn
  1034. }
  1035. func resolveInstallationCode() string {
  1036. if fnInstallationCodeResolver != nil {
  1037. return fnInstallationCodeResolver(installationCode)
  1038. }
  1039. return installationCode
  1040. }