httpd.go 51 KB

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