httpd.go 50 KB

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