httpd.go 44 KB

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