httpd.go 46 KB

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