httpd.go 50 KB

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