httpd.go 50 KB

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