httpd.go 45 KB

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