httpd.go 45 KB

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