config.go 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646
  1. // Package config manages the configuration
  2. package config
  3. import (
  4. "errors"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. "github.com/spf13/viper"
  11. "github.com/drakkan/sftpgo/v2/common"
  12. "github.com/drakkan/sftpgo/v2/dataprovider"
  13. "github.com/drakkan/sftpgo/v2/ftpd"
  14. "github.com/drakkan/sftpgo/v2/httpclient"
  15. "github.com/drakkan/sftpgo/v2/httpd"
  16. "github.com/drakkan/sftpgo/v2/kms"
  17. "github.com/drakkan/sftpgo/v2/logger"
  18. "github.com/drakkan/sftpgo/v2/mfa"
  19. "github.com/drakkan/sftpgo/v2/plugin"
  20. "github.com/drakkan/sftpgo/v2/sftpd"
  21. "github.com/drakkan/sftpgo/v2/smtp"
  22. "github.com/drakkan/sftpgo/v2/telemetry"
  23. "github.com/drakkan/sftpgo/v2/util"
  24. "github.com/drakkan/sftpgo/v2/version"
  25. "github.com/drakkan/sftpgo/v2/webdavd"
  26. )
  27. const (
  28. logSender = "config"
  29. // configName defines the name for config file.
  30. // This name does not include the extension, viper will search for files
  31. // with supported extensions such as "sftpgo.json", "sftpgo.yaml" and so on
  32. configName = "sftpgo"
  33. // ConfigEnvPrefix defines a prefix that environment variables will use
  34. configEnvPrefix = "sftpgo"
  35. )
  36. var (
  37. globalConf globalConfig
  38. defaultSFTPDBanner = fmt.Sprintf("SFTPGo_%v", version.Get().Version)
  39. defaultFTPDBanner = fmt.Sprintf("SFTPGo %v ready", version.Get().Version)
  40. defaultInstallCodeHint = "Installation code"
  41. defaultSFTPDBinding = sftpd.Binding{
  42. Address: "",
  43. Port: 2022,
  44. ApplyProxyConfig: true,
  45. }
  46. defaultFTPDBinding = ftpd.Binding{
  47. Address: "",
  48. Port: 0,
  49. ApplyProxyConfig: true,
  50. TLSMode: 0,
  51. MinTLSVersion: 12,
  52. ForcePassiveIP: "",
  53. PassiveIPOverrides: nil,
  54. ClientAuthType: 0,
  55. TLSCipherSuites: nil,
  56. PassiveConnectionsSecurity: 0,
  57. ActiveConnectionsSecurity: 0,
  58. Debug: false,
  59. }
  60. defaultWebDAVDBinding = webdavd.Binding{
  61. Address: "",
  62. Port: 0,
  63. EnableHTTPS: false,
  64. MinTLSVersion: 12,
  65. ClientAuthType: 0,
  66. TLSCipherSuites: nil,
  67. Prefix: "",
  68. ProxyAllowed: nil,
  69. }
  70. defaultHTTPDBinding = httpd.Binding{
  71. Address: "",
  72. Port: 8080,
  73. EnableWebAdmin: true,
  74. EnableWebClient: true,
  75. EnableHTTPS: false,
  76. MinTLSVersion: 12,
  77. ClientAuthType: 0,
  78. TLSCipherSuites: nil,
  79. ProxyAllowed: nil,
  80. HideLoginURL: 0,
  81. RenderOpenAPI: true,
  82. WebClientIntegrations: nil,
  83. OIDC: httpd.OIDC{
  84. ClientID: "",
  85. ClientSecret: "",
  86. ConfigURL: "",
  87. RedirectBaseURL: "",
  88. UsernameField: "",
  89. RoleField: "",
  90. },
  91. Security: httpd.SecurityConf{
  92. Enabled: false,
  93. AllowedHosts: nil,
  94. AllowedHostsAreRegex: false,
  95. HostsProxyHeaders: nil,
  96. HTTPSProxyHeaders: nil,
  97. STSSeconds: 0,
  98. STSIncludeSubdomains: false,
  99. STSPreload: false,
  100. ContentTypeNosniff: false,
  101. ContentSecurityPolicy: "",
  102. PermissionsPolicy: "",
  103. CrossOriginOpenerPolicy: "",
  104. ExpectCTHeader: "",
  105. },
  106. }
  107. defaultRateLimiter = common.RateLimiterConfig{
  108. Average: 0,
  109. Period: 1000,
  110. Burst: 1,
  111. Type: 2,
  112. Protocols: []string{common.ProtocolSSH, common.ProtocolFTP, common.ProtocolWebDAV, common.ProtocolHTTP},
  113. AllowList: []string{},
  114. GenerateDefenderEvents: false,
  115. EntriesSoftLimit: 100,
  116. EntriesHardLimit: 150,
  117. }
  118. defaultTOTP = mfa.TOTPConfig{
  119. Name: "Default",
  120. Issuer: "SFTPGo",
  121. Algo: mfa.TOTPAlgoSHA1,
  122. }
  123. )
  124. type globalConfig struct {
  125. Common common.Configuration `json:"common" mapstructure:"common"`
  126. SFTPD sftpd.Configuration `json:"sftpd" mapstructure:"sftpd"`
  127. FTPD ftpd.Configuration `json:"ftpd" mapstructure:"ftpd"`
  128. WebDAVD webdavd.Configuration `json:"webdavd" mapstructure:"webdavd"`
  129. ProviderConf dataprovider.Config `json:"data_provider" mapstructure:"data_provider"`
  130. HTTPDConfig httpd.Conf `json:"httpd" mapstructure:"httpd"`
  131. HTTPConfig httpclient.Config `json:"http" mapstructure:"http"`
  132. KMSConfig kms.Configuration `json:"kms" mapstructure:"kms"`
  133. MFAConfig mfa.Config `json:"mfa" mapstructure:"mfa"`
  134. TelemetryConfig telemetry.Conf `json:"telemetry" mapstructure:"telemetry"`
  135. PluginsConfig []plugin.Config `json:"plugins" mapstructure:"plugins"`
  136. SMTPConfig smtp.Config `json:"smtp" mapstructure:"smtp"`
  137. }
  138. func init() {
  139. Init()
  140. }
  141. // Init initializes the global configuration.
  142. // It is not supposed to be called outside of this package.
  143. // It is exported to minimize refactoring efforts. Will eventually disappear.
  144. func Init() {
  145. // create a default configuration to use if no config file is provided
  146. globalConf = globalConfig{
  147. Common: common.Configuration{
  148. IdleTimeout: 15,
  149. UploadMode: 0,
  150. Actions: common.ProtocolActions{
  151. ExecuteOn: []string{},
  152. ExecuteSync: []string{},
  153. Hook: "",
  154. },
  155. SetstatMode: 0,
  156. TempPath: "",
  157. ProxyProtocol: 0,
  158. ProxyAllowed: []string{},
  159. PostConnectHook: "",
  160. PostDisconnectHook: "",
  161. DataRetentionHook: "",
  162. MaxTotalConnections: 0,
  163. MaxPerHostConnections: 20,
  164. DefenderConfig: common.DefenderConfig{
  165. Enabled: false,
  166. Driver: common.DefenderDriverMemory,
  167. BanTime: 30,
  168. BanTimeIncrement: 50,
  169. Threshold: 15,
  170. ScoreInvalid: 2,
  171. ScoreValid: 1,
  172. ScoreLimitExceeded: 3,
  173. ObservationTime: 30,
  174. EntriesSoftLimit: 100,
  175. EntriesHardLimit: 150,
  176. SafeListFile: "",
  177. BlockListFile: "",
  178. },
  179. RateLimitersConfig: []common.RateLimiterConfig{defaultRateLimiter},
  180. },
  181. SFTPD: sftpd.Configuration{
  182. Banner: defaultSFTPDBanner,
  183. Bindings: []sftpd.Binding{defaultSFTPDBinding},
  184. MaxAuthTries: 0,
  185. HostKeys: []string{},
  186. KexAlgorithms: []string{},
  187. Ciphers: []string{},
  188. MACs: []string{},
  189. TrustedUserCAKeys: []string{},
  190. LoginBannerFile: "",
  191. EnabledSSHCommands: []string{},
  192. KeyboardInteractiveAuthentication: false,
  193. KeyboardInteractiveHook: "",
  194. PasswordAuthentication: true,
  195. FolderPrefix: "",
  196. },
  197. FTPD: ftpd.Configuration{
  198. Bindings: []ftpd.Binding{defaultFTPDBinding},
  199. Banner: defaultFTPDBanner,
  200. BannerFile: "",
  201. ActiveTransfersPortNon20: true,
  202. PassivePortRange: ftpd.PortRange{
  203. Start: 50000,
  204. End: 50100,
  205. },
  206. DisableActiveMode: false,
  207. EnableSite: false,
  208. HASHSupport: 0,
  209. CombineSupport: 0,
  210. CertificateFile: "",
  211. CertificateKeyFile: "",
  212. CACertificates: []string{},
  213. CARevocationLists: []string{},
  214. },
  215. WebDAVD: webdavd.Configuration{
  216. Bindings: []webdavd.Binding{defaultWebDAVDBinding},
  217. CertificateFile: "",
  218. CertificateKeyFile: "",
  219. CACertificates: []string{},
  220. CARevocationLists: []string{},
  221. Cors: webdavd.CorsConfig{
  222. Enabled: false,
  223. AllowedOrigins: []string{},
  224. AllowedMethods: []string{},
  225. AllowedHeaders: []string{},
  226. ExposedHeaders: []string{},
  227. AllowCredentials: false,
  228. MaxAge: 0,
  229. },
  230. Cache: webdavd.Cache{
  231. Users: webdavd.UsersCacheConfig{
  232. ExpirationTime: 0,
  233. MaxSize: 50,
  234. },
  235. MimeTypes: webdavd.MimeCacheConfig{
  236. Enabled: true,
  237. MaxSize: 1000,
  238. },
  239. },
  240. },
  241. ProviderConf: dataprovider.Config{
  242. Driver: "sqlite",
  243. Name: "sftpgo.db",
  244. Host: "",
  245. Port: 0,
  246. Username: "",
  247. Password: "",
  248. ConnectionString: "",
  249. SQLTablesPrefix: "",
  250. SSLMode: 0,
  251. RootCert: "",
  252. ClientCert: "",
  253. ClientKey: "",
  254. TrackQuota: 1,
  255. PoolSize: 0,
  256. UsersBaseDir: "",
  257. Actions: dataprovider.ObjectsActions{
  258. ExecuteOn: []string{},
  259. ExecuteFor: []string{},
  260. Hook: "",
  261. },
  262. ExternalAuthHook: "",
  263. ExternalAuthScope: 0,
  264. CredentialsPath: "credentials",
  265. PreLoginHook: "",
  266. PostLoginHook: "",
  267. PostLoginScope: 0,
  268. CheckPasswordHook: "",
  269. CheckPasswordScope: 0,
  270. PasswordHashing: dataprovider.PasswordHashing{
  271. Argon2Options: dataprovider.Argon2Options{
  272. Memory: 65536,
  273. Iterations: 1,
  274. Parallelism: 2,
  275. },
  276. BcryptOptions: dataprovider.BcryptOptions{
  277. Cost: 10,
  278. },
  279. Algo: dataprovider.HashingAlgoBcrypt,
  280. },
  281. PasswordValidation: dataprovider.PasswordValidation{
  282. Admins: dataprovider.PasswordValidationRules{
  283. MinEntropy: 0,
  284. },
  285. Users: dataprovider.PasswordValidationRules{
  286. MinEntropy: 0,
  287. },
  288. },
  289. PasswordCaching: true,
  290. UpdateMode: 0,
  291. PreferDatabaseCredentials: false,
  292. DelayedQuotaUpdate: 0,
  293. CreateDefaultAdmin: false,
  294. NamingRules: 0,
  295. IsShared: 0,
  296. },
  297. HTTPDConfig: httpd.Conf{
  298. Bindings: []httpd.Binding{defaultHTTPDBinding},
  299. TemplatesPath: "templates",
  300. StaticFilesPath: "static",
  301. BackupsPath: "backups",
  302. OpenAPIPath: "openapi",
  303. WebRoot: "",
  304. CertificateFile: "",
  305. CertificateKeyFile: "",
  306. CACertificates: nil,
  307. CARevocationLists: nil,
  308. SigningPassphrase: "",
  309. MaxUploadFileSize: 1048576000,
  310. Cors: httpd.CorsConfig{
  311. Enabled: false,
  312. AllowedOrigins: []string{},
  313. AllowedMethods: []string{},
  314. AllowedHeaders: []string{},
  315. ExposedHeaders: []string{},
  316. AllowCredentials: false,
  317. MaxAge: 0,
  318. },
  319. Setup: httpd.SetupConfig{
  320. InstallationCode: "",
  321. InstallationCodeHint: defaultInstallCodeHint,
  322. },
  323. },
  324. HTTPConfig: httpclient.Config{
  325. Timeout: 20,
  326. RetryWaitMin: 2,
  327. RetryWaitMax: 30,
  328. RetryMax: 3,
  329. CACertificates: nil,
  330. Certificates: nil,
  331. SkipTLSVerify: false,
  332. Headers: nil,
  333. },
  334. KMSConfig: kms.Configuration{
  335. Secrets: kms.Secrets{
  336. URL: "",
  337. MasterKeyString: "",
  338. MasterKeyPath: "",
  339. },
  340. },
  341. MFAConfig: mfa.Config{
  342. TOTP: nil,
  343. },
  344. TelemetryConfig: telemetry.Conf{
  345. BindPort: 10000,
  346. BindAddress: "127.0.0.1",
  347. EnableProfiler: false,
  348. AuthUserFile: "",
  349. CertificateFile: "",
  350. CertificateKeyFile: "",
  351. MinTLSVersion: 12,
  352. TLSCipherSuites: nil,
  353. },
  354. SMTPConfig: smtp.Config{
  355. Host: "",
  356. Port: 25,
  357. From: "",
  358. User: "",
  359. Password: "",
  360. AuthType: 0,
  361. Encryption: 0,
  362. Domain: "",
  363. TemplatesPath: "templates",
  364. },
  365. PluginsConfig: nil,
  366. }
  367. viper.SetEnvPrefix(configEnvPrefix)
  368. replacer := strings.NewReplacer(".", "__")
  369. viper.SetEnvKeyReplacer(replacer)
  370. viper.SetConfigName(configName)
  371. setViperDefaults()
  372. viper.AutomaticEnv()
  373. viper.AllowEmptyEnv(true)
  374. }
  375. // GetCommonConfig returns the common protocols configuration
  376. func GetCommonConfig() common.Configuration {
  377. return globalConf.Common
  378. }
  379. // SetCommonConfig sets the common protocols configuration
  380. func SetCommonConfig(config common.Configuration) {
  381. globalConf.Common = config
  382. }
  383. // GetSFTPDConfig returns the configuration for the SFTP server
  384. func GetSFTPDConfig() sftpd.Configuration {
  385. return globalConf.SFTPD
  386. }
  387. // SetSFTPDConfig sets the configuration for the SFTP server
  388. func SetSFTPDConfig(config sftpd.Configuration) {
  389. globalConf.SFTPD = config
  390. }
  391. // GetFTPDConfig returns the configuration for the FTP server
  392. func GetFTPDConfig() ftpd.Configuration {
  393. return globalConf.FTPD
  394. }
  395. // SetFTPDConfig sets the configuration for the FTP server
  396. func SetFTPDConfig(config ftpd.Configuration) {
  397. globalConf.FTPD = config
  398. }
  399. // GetWebDAVDConfig returns the configuration for the WebDAV server
  400. func GetWebDAVDConfig() webdavd.Configuration {
  401. return globalConf.WebDAVD
  402. }
  403. // SetWebDAVDConfig sets the configuration for the WebDAV server
  404. func SetWebDAVDConfig(config webdavd.Configuration) {
  405. globalConf.WebDAVD = config
  406. }
  407. // GetHTTPDConfig returns the configuration for the HTTP server
  408. func GetHTTPDConfig() httpd.Conf {
  409. return globalConf.HTTPDConfig
  410. }
  411. // SetHTTPDConfig sets the configuration for the HTTP server
  412. func SetHTTPDConfig(config httpd.Conf) {
  413. globalConf.HTTPDConfig = config
  414. }
  415. // GetProviderConf returns the configuration for the data provider
  416. func GetProviderConf() dataprovider.Config {
  417. return globalConf.ProviderConf
  418. }
  419. // SetProviderConf sets the configuration for the data provider
  420. func SetProviderConf(config dataprovider.Config) {
  421. globalConf.ProviderConf = config
  422. }
  423. // GetHTTPConfig returns the configuration for HTTP clients
  424. func GetHTTPConfig() httpclient.Config {
  425. return globalConf.HTTPConfig
  426. }
  427. // GetKMSConfig returns the KMS configuration
  428. func GetKMSConfig() kms.Configuration {
  429. return globalConf.KMSConfig
  430. }
  431. // SetKMSConfig sets the kms configuration
  432. func SetKMSConfig(config kms.Configuration) {
  433. globalConf.KMSConfig = config
  434. }
  435. // GetTelemetryConfig returns the telemetry configuration
  436. func GetTelemetryConfig() telemetry.Conf {
  437. return globalConf.TelemetryConfig
  438. }
  439. // SetTelemetryConfig sets the telemetry configuration
  440. func SetTelemetryConfig(config telemetry.Conf) {
  441. globalConf.TelemetryConfig = config
  442. }
  443. // GetPluginsConfig returns the plugins configuration
  444. func GetPluginsConfig() []plugin.Config {
  445. return globalConf.PluginsConfig
  446. }
  447. // SetPluginsConfig sets the plugin configuration
  448. func SetPluginsConfig(config []plugin.Config) {
  449. globalConf.PluginsConfig = config
  450. }
  451. // GetMFAConfig returns multi-factor authentication config
  452. func GetMFAConfig() mfa.Config {
  453. return globalConf.MFAConfig
  454. }
  455. // GetSMTPConfig returns the SMTP configuration
  456. func GetSMTPConfig() smtp.Config {
  457. return globalConf.SMTPConfig
  458. }
  459. // HasServicesToStart returns true if the config defines at least a service to start.
  460. // Supported services are SFTP, FTP and WebDAV
  461. func HasServicesToStart() bool {
  462. if globalConf.SFTPD.ShouldBind() {
  463. return true
  464. }
  465. if globalConf.FTPD.ShouldBind() {
  466. return true
  467. }
  468. if globalConf.WebDAVD.ShouldBind() {
  469. return true
  470. }
  471. return false
  472. }
  473. func getRedactedPassword(value string) string {
  474. if value == "" {
  475. return value
  476. }
  477. return "[redacted]"
  478. }
  479. func getRedactedGlobalConf() globalConfig {
  480. conf := globalConf
  481. conf.Common.Actions.Hook = util.GetRedactedURL(conf.Common.Actions.Hook)
  482. conf.Common.StartupHook = util.GetRedactedURL(conf.Common.StartupHook)
  483. conf.Common.PostConnectHook = util.GetRedactedURL(conf.Common.PostConnectHook)
  484. conf.Common.PostDisconnectHook = util.GetRedactedURL(conf.Common.PostDisconnectHook)
  485. conf.Common.DataRetentionHook = util.GetRedactedURL(conf.Common.DataRetentionHook)
  486. conf.SFTPD.KeyboardInteractiveHook = util.GetRedactedURL(conf.SFTPD.KeyboardInteractiveHook)
  487. conf.HTTPDConfig.SigningPassphrase = getRedactedPassword(conf.HTTPDConfig.SigningPassphrase)
  488. conf.HTTPDConfig.Setup.InstallationCode = getRedactedPassword(conf.HTTPDConfig.Setup.InstallationCode)
  489. conf.ProviderConf.Password = getRedactedPassword(conf.ProviderConf.Password)
  490. conf.ProviderConf.Actions.Hook = util.GetRedactedURL(conf.ProviderConf.Actions.Hook)
  491. conf.ProviderConf.ExternalAuthHook = util.GetRedactedURL(conf.ProviderConf.ExternalAuthHook)
  492. conf.ProviderConf.PreLoginHook = util.GetRedactedURL(conf.ProviderConf.PreLoginHook)
  493. conf.ProviderConf.PostLoginHook = util.GetRedactedURL(conf.ProviderConf.PostLoginHook)
  494. conf.ProviderConf.CheckPasswordHook = util.GetRedactedURL(conf.ProviderConf.CheckPasswordHook)
  495. conf.SMTPConfig.Password = getRedactedPassword(conf.SMTPConfig.Password)
  496. conf.HTTPDConfig.Bindings = nil
  497. for _, binding := range globalConf.HTTPDConfig.Bindings {
  498. binding.OIDC.ClientID = getRedactedPassword(binding.OIDC.ClientID)
  499. binding.OIDC.ClientSecret = getRedactedPassword(binding.OIDC.ClientSecret)
  500. conf.HTTPDConfig.Bindings = append(conf.HTTPDConfig.Bindings, binding)
  501. }
  502. return conf
  503. }
  504. func setConfigFile(configDir, configFile string) {
  505. if configFile == "" {
  506. return
  507. }
  508. if !filepath.IsAbs(configFile) && util.IsFileInputValid(configFile) {
  509. configFile = filepath.Join(configDir, configFile)
  510. }
  511. viper.SetConfigFile(configFile)
  512. }
  513. // LoadConfig loads the configuration
  514. // configDir will be added to the configuration search paths.
  515. // The search path contains by default the current directory and on linux it contains
  516. // $HOME/.config/sftpgo and /etc/sftpgo too.
  517. // configFile is an absolute or relative path (to the config dir) to the configuration file.
  518. func LoadConfig(configDir, configFile string) error {
  519. var err error
  520. viper.AddConfigPath(configDir)
  521. setViperAdditionalConfigPaths()
  522. viper.AddConfigPath(".")
  523. setConfigFile(configDir, configFile)
  524. if err = viper.ReadInConfig(); err != nil {
  525. // if the user specify a configuration file we get os.ErrNotExist.
  526. // viper.ConfigFileNotFoundError is returned if viper is unable
  527. // to find sftpgo.{json,yaml, etc..} in any of the search paths
  528. if errors.As(err, &viper.ConfigFileNotFoundError{}) {
  529. logger.Debug(logSender, "", "no configuration file found")
  530. } else {
  531. // should we return the error and not start here?
  532. logger.Warn(logSender, "", "error loading configuration file: %v", err)
  533. logger.WarnToConsole("error loading configuration file: %v", err)
  534. }
  535. }
  536. err = viper.Unmarshal(&globalConf)
  537. if err != nil {
  538. logger.Warn(logSender, "", "error parsing configuration file: %v", err)
  539. logger.WarnToConsole("error parsing configuration file: %v", err)
  540. return err
  541. }
  542. // viper only supports slice of strings from env vars, so we use our custom method
  543. loadBindingsFromEnv()
  544. resetInvalidConfigs()
  545. logger.Debug(logSender, "", "config file used: '%#v', config loaded: %+v", viper.ConfigFileUsed(), getRedactedGlobalConf())
  546. return nil
  547. }
  548. func isUploadModeValid() bool {
  549. return globalConf.Common.UploadMode >= 0 && globalConf.Common.UploadMode <= 2
  550. }
  551. func isProxyProtocolValid() bool {
  552. return globalConf.Common.ProxyProtocol >= 0 && globalConf.Common.ProxyProtocol <= 2
  553. }
  554. func isExternalAuthScopeValid() bool {
  555. return globalConf.ProviderConf.ExternalAuthScope >= 0 && globalConf.ProviderConf.ExternalAuthScope <= 15
  556. }
  557. func resetInvalidConfigs() {
  558. if strings.TrimSpace(globalConf.SFTPD.Banner) == "" {
  559. globalConf.SFTPD.Banner = defaultSFTPDBanner
  560. }
  561. if strings.TrimSpace(globalConf.FTPD.Banner) == "" {
  562. globalConf.FTPD.Banner = defaultFTPDBanner
  563. }
  564. if strings.TrimSpace(globalConf.HTTPDConfig.Setup.InstallationCodeHint) == "" {
  565. globalConf.HTTPDConfig.Setup.InstallationCodeHint = defaultInstallCodeHint
  566. }
  567. if globalConf.ProviderConf.UsersBaseDir != "" && !util.IsFileInputValid(globalConf.ProviderConf.UsersBaseDir) {
  568. warn := fmt.Sprintf("invalid users base dir %#v will be ignored", globalConf.ProviderConf.UsersBaseDir)
  569. globalConf.ProviderConf.UsersBaseDir = ""
  570. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  571. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  572. }
  573. if !isUploadModeValid() {
  574. warn := fmt.Sprintf("invalid upload_mode 0, 1 and 2 are supported, configured: %v reset upload_mode to 0",
  575. globalConf.Common.UploadMode)
  576. globalConf.Common.UploadMode = 0
  577. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  578. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  579. }
  580. if !isProxyProtocolValid() {
  581. warn := fmt.Sprintf("invalid proxy_protocol 0, 1 and 2 are supported, configured: %v reset proxy_protocol to 0",
  582. globalConf.Common.ProxyProtocol)
  583. globalConf.Common.ProxyProtocol = 0
  584. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  585. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  586. }
  587. if !isExternalAuthScopeValid() {
  588. warn := fmt.Sprintf("invalid external_auth_scope: %v reset to 0", globalConf.ProviderConf.ExternalAuthScope)
  589. globalConf.ProviderConf.ExternalAuthScope = 0
  590. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  591. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  592. }
  593. if globalConf.ProviderConf.CredentialsPath == "" {
  594. warn := "invalid credentials path, reset to \"credentials\""
  595. globalConf.ProviderConf.CredentialsPath = "credentials"
  596. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  597. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  598. }
  599. if globalConf.Common.DefenderConfig.Enabled && globalConf.Common.DefenderConfig.Driver == common.DefenderDriverProvider {
  600. if !globalConf.ProviderConf.IsDefenderSupported() {
  601. warn := fmt.Sprintf("provider based defender is not supported with data provider %#v, "+
  602. "the memory defender implementation will be used. If you want to use the provider defender "+
  603. "implementation please switch to a shared/distributed data provider",
  604. globalConf.ProviderConf.Driver)
  605. globalConf.Common.DefenderConfig.Driver = common.DefenderDriverMemory
  606. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  607. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  608. }
  609. }
  610. }
  611. func loadBindingsFromEnv() {
  612. for idx := 0; idx < 10; idx++ {
  613. getTOTPFromEnv(idx)
  614. getRateLimitersFromEnv(idx)
  615. getPluginsFromEnv(idx)
  616. getSFTPDBindindFromEnv(idx)
  617. getFTPDBindingFromEnv(idx)
  618. getWebDAVDBindingFromEnv(idx)
  619. getHTTPDBindingFromEnv(idx)
  620. getHTTPClientCertificatesFromEnv(idx)
  621. getHTTPClientHeadersFromEnv(idx)
  622. }
  623. }
  624. func getTOTPFromEnv(idx int) {
  625. totpConfig := defaultTOTP
  626. if len(globalConf.MFAConfig.TOTP) > idx {
  627. totpConfig = globalConf.MFAConfig.TOTP[idx]
  628. }
  629. isSet := false
  630. name, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_MFA__TOTP__%v__NAME", idx))
  631. if ok {
  632. totpConfig.Name = name
  633. isSet = true
  634. }
  635. issuer, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_MFA__TOTP__%v__ISSUER", idx))
  636. if ok {
  637. totpConfig.Issuer = issuer
  638. isSet = true
  639. }
  640. algo, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_MFA__TOTP__%v__ALGO", idx))
  641. if ok {
  642. totpConfig.Algo = algo
  643. isSet = true
  644. }
  645. if isSet {
  646. if len(globalConf.MFAConfig.TOTP) > idx {
  647. globalConf.MFAConfig.TOTP[idx] = totpConfig
  648. } else {
  649. globalConf.MFAConfig.TOTP = append(globalConf.MFAConfig.TOTP, totpConfig)
  650. }
  651. }
  652. }
  653. func getRateLimitersFromEnv(idx int) {
  654. rtlConfig := defaultRateLimiter
  655. if len(globalConf.Common.RateLimitersConfig) > idx {
  656. rtlConfig = globalConf.Common.RateLimitersConfig[idx]
  657. }
  658. isSet := false
  659. average, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__AVERAGE", idx))
  660. if ok {
  661. rtlConfig.Average = average
  662. isSet = true
  663. }
  664. period, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__PERIOD", idx))
  665. if ok {
  666. rtlConfig.Period = period
  667. isSet = true
  668. }
  669. burst, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__BURST", idx))
  670. if ok {
  671. rtlConfig.Burst = int(burst)
  672. isSet = true
  673. }
  674. rtlType, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__TYPE", idx))
  675. if ok {
  676. rtlConfig.Type = int(rtlType)
  677. isSet = true
  678. }
  679. protocols, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__PROTOCOLS", idx))
  680. if ok {
  681. rtlConfig.Protocols = protocols
  682. isSet = true
  683. }
  684. allowList, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__ALLOW_LIST", idx))
  685. if ok {
  686. rtlConfig.AllowList = allowList
  687. isSet = true
  688. }
  689. generateEvents, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__GENERATE_DEFENDER_EVENTS", idx))
  690. if ok {
  691. rtlConfig.GenerateDefenderEvents = generateEvents
  692. isSet = true
  693. }
  694. softLimit, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__ENTRIES_SOFT_LIMIT", idx))
  695. if ok {
  696. rtlConfig.EntriesSoftLimit = int(softLimit)
  697. isSet = true
  698. }
  699. hardLimit, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__ENTRIES_HARD_LIMIT", idx))
  700. if ok {
  701. rtlConfig.EntriesHardLimit = int(hardLimit)
  702. isSet = true
  703. }
  704. if isSet {
  705. if len(globalConf.Common.RateLimitersConfig) > idx {
  706. globalConf.Common.RateLimitersConfig[idx] = rtlConfig
  707. } else {
  708. globalConf.Common.RateLimitersConfig = append(globalConf.Common.RateLimitersConfig, rtlConfig)
  709. }
  710. }
  711. }
  712. func getKMSPluginFromEnv(idx int, pluginConfig *plugin.Config) bool {
  713. isSet := false
  714. kmsScheme, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__KMS_OPTIONS__SCHEME", idx))
  715. if ok {
  716. pluginConfig.KMSOptions.Scheme = kmsScheme
  717. isSet = true
  718. }
  719. kmsEncStatus, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__KMS_OPTIONS__ENCRYPTED_STATUS", idx))
  720. if ok {
  721. pluginConfig.KMSOptions.EncryptedStatus = kmsEncStatus
  722. isSet = true
  723. }
  724. return isSet
  725. }
  726. func getAuthPluginFromEnv(idx int, pluginConfig *plugin.Config) bool {
  727. isSet := false
  728. authScope, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__AUTH_OPTIONS__SCOPE", idx))
  729. if ok {
  730. pluginConfig.AuthOptions.Scope = int(authScope)
  731. isSet = true
  732. }
  733. return isSet
  734. }
  735. func getNotifierPluginFromEnv(idx int, pluginConfig *plugin.Config) bool {
  736. isSet := false
  737. notifierFsEvents, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__FS_EVENTS", idx))
  738. if ok {
  739. pluginConfig.NotifierOptions.FsEvents = notifierFsEvents
  740. isSet = true
  741. }
  742. notifierProviderEvents, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__PROVIDER_EVENTS", idx))
  743. if ok {
  744. pluginConfig.NotifierOptions.ProviderEvents = notifierProviderEvents
  745. isSet = true
  746. }
  747. notifierProviderObjects, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__PROVIDER_OBJECTS", idx))
  748. if ok {
  749. pluginConfig.NotifierOptions.ProviderObjects = notifierProviderObjects
  750. isSet = true
  751. }
  752. notifierRetryMaxTime, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__RETRY_MAX_TIME", idx))
  753. if ok {
  754. pluginConfig.NotifierOptions.RetryMaxTime = int(notifierRetryMaxTime)
  755. isSet = true
  756. }
  757. notifierRetryQueueMaxSize, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__RETRY_QUEUE_MAX_SIZE", idx))
  758. if ok {
  759. pluginConfig.NotifierOptions.RetryQueueMaxSize = int(notifierRetryQueueMaxSize)
  760. isSet = true
  761. }
  762. return isSet
  763. }
  764. func getPluginsFromEnv(idx int) {
  765. pluginConfig := plugin.Config{}
  766. if len(globalConf.PluginsConfig) > idx {
  767. pluginConfig = globalConf.PluginsConfig[idx]
  768. }
  769. isSet := false
  770. pluginType, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__TYPE", idx))
  771. if ok {
  772. pluginConfig.Type = pluginType
  773. isSet = true
  774. }
  775. if getNotifierPluginFromEnv(idx, &pluginConfig) {
  776. isSet = true
  777. }
  778. if getKMSPluginFromEnv(idx, &pluginConfig) {
  779. isSet = true
  780. }
  781. if getAuthPluginFromEnv(idx, &pluginConfig) {
  782. isSet = true
  783. }
  784. cmd, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__CMD", idx))
  785. if ok {
  786. pluginConfig.Cmd = cmd
  787. isSet = true
  788. }
  789. cmdArgs, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__ARGS", idx))
  790. if ok {
  791. pluginConfig.Args = cmdArgs
  792. isSet = true
  793. }
  794. pluginHash, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__SHA256SUM", idx))
  795. if ok {
  796. pluginConfig.SHA256Sum = pluginHash
  797. isSet = true
  798. }
  799. autoMTLS, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__AUTO_MTLS", idx))
  800. if ok {
  801. pluginConfig.AutoMTLS = autoMTLS
  802. isSet = true
  803. }
  804. if isSet {
  805. if len(globalConf.PluginsConfig) > idx {
  806. globalConf.PluginsConfig[idx] = pluginConfig
  807. } else {
  808. globalConf.PluginsConfig = append(globalConf.PluginsConfig, pluginConfig)
  809. }
  810. }
  811. }
  812. func getSFTPDBindindFromEnv(idx int) {
  813. binding := sftpd.Binding{
  814. ApplyProxyConfig: true,
  815. }
  816. if len(globalConf.SFTPD.Bindings) > idx {
  817. binding = globalConf.SFTPD.Bindings[idx]
  818. }
  819. isSet := false
  820. port, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_SFTPD__BINDINGS__%v__PORT", idx))
  821. if ok {
  822. binding.Port = int(port)
  823. isSet = true
  824. }
  825. address, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_SFTPD__BINDINGS__%v__ADDRESS", idx))
  826. if ok {
  827. binding.Address = address
  828. isSet = true
  829. }
  830. applyProxyConfig, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_SFTPD__BINDINGS__%v__APPLY_PROXY_CONFIG", idx))
  831. if ok {
  832. binding.ApplyProxyConfig = applyProxyConfig
  833. isSet = true
  834. }
  835. if isSet {
  836. if len(globalConf.SFTPD.Bindings) > idx {
  837. globalConf.SFTPD.Bindings[idx] = binding
  838. } else {
  839. globalConf.SFTPD.Bindings = append(globalConf.SFTPD.Bindings, binding)
  840. }
  841. }
  842. }
  843. func getFTPDPassiveIPOverridesFromEnv(idx int) []ftpd.PassiveIPOverride {
  844. var overrides []ftpd.PassiveIPOverride
  845. for subIdx := 0; subIdx < 10; subIdx++ {
  846. var override ftpd.PassiveIPOverride
  847. ip, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__PASSIVE_IP_OVERRIDES__%v__IP", idx, subIdx))
  848. if ok {
  849. override.IP = ip
  850. }
  851. networks, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__PASSIVE_IP_OVERRIDES__%v__NETWORKS",
  852. idx, subIdx))
  853. if ok {
  854. override.Networks = networks
  855. }
  856. if len(override.Networks) > 0 {
  857. overrides = append(overrides, override)
  858. }
  859. }
  860. return overrides
  861. }
  862. func getDefaultFTPDBinding(idx int) ftpd.Binding {
  863. binding := ftpd.Binding{
  864. ApplyProxyConfig: true,
  865. MinTLSVersion: 12,
  866. }
  867. if len(globalConf.FTPD.Bindings) > idx {
  868. binding = globalConf.FTPD.Bindings[idx]
  869. }
  870. return binding
  871. }
  872. func getFTPDBindingFromEnv(idx int) {
  873. binding := getDefaultFTPDBinding(idx)
  874. isSet := false
  875. port, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__PORT", idx))
  876. if ok {
  877. binding.Port = int(port)
  878. isSet = true
  879. }
  880. address, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__ADDRESS", idx))
  881. if ok {
  882. binding.Address = address
  883. isSet = true
  884. }
  885. applyProxyConfig, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__APPLY_PROXY_CONFIG", idx))
  886. if ok {
  887. binding.ApplyProxyConfig = applyProxyConfig
  888. isSet = true
  889. }
  890. tlsMode, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__TLS_MODE", idx))
  891. if ok {
  892. binding.TLSMode = int(tlsMode)
  893. isSet = true
  894. }
  895. tlsVer, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__MIN_TLS_VERSION", idx))
  896. if ok {
  897. binding.MinTLSVersion = int(tlsVer)
  898. isSet = true
  899. }
  900. passiveIP, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__FORCE_PASSIVE_IP", idx))
  901. if ok {
  902. binding.ForcePassiveIP = passiveIP
  903. isSet = true
  904. }
  905. passiveIPOverrides := getFTPDPassiveIPOverridesFromEnv(idx)
  906. if len(passiveIPOverrides) > 0 {
  907. binding.PassiveIPOverrides = passiveIPOverrides
  908. isSet = true
  909. }
  910. clientAuthType, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__CLIENT_AUTH_TYPE", idx))
  911. if ok {
  912. binding.ClientAuthType = int(clientAuthType)
  913. isSet = true
  914. }
  915. tlsCiphers, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__TLS_CIPHER_SUITES", idx))
  916. if ok {
  917. binding.TLSCipherSuites = tlsCiphers
  918. isSet = true
  919. }
  920. pasvSecurity, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__PASSIVE_CONNECTIONS_SECURITY", idx))
  921. if ok {
  922. binding.PassiveConnectionsSecurity = int(pasvSecurity)
  923. isSet = true
  924. }
  925. activeSecurity, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__ACTIVE_CONNECTIONS_SECURITY", idx))
  926. if ok {
  927. binding.ActiveConnectionsSecurity = int(activeSecurity)
  928. isSet = true
  929. }
  930. debug, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__DEBUG", idx))
  931. if ok {
  932. binding.Debug = debug
  933. isSet = true
  934. }
  935. if isSet {
  936. if len(globalConf.FTPD.Bindings) > idx {
  937. globalConf.FTPD.Bindings[idx] = binding
  938. } else {
  939. globalConf.FTPD.Bindings = append(globalConf.FTPD.Bindings, binding)
  940. }
  941. }
  942. }
  943. func getWebDAVDBindingFromEnv(idx int) {
  944. binding := webdavd.Binding{
  945. MinTLSVersion: 12,
  946. }
  947. if len(globalConf.WebDAVD.Bindings) > idx {
  948. binding = globalConf.WebDAVD.Bindings[idx]
  949. }
  950. isSet := false
  951. port, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__PORT", idx))
  952. if ok {
  953. binding.Port = int(port)
  954. isSet = true
  955. }
  956. address, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__ADDRESS", idx))
  957. if ok {
  958. binding.Address = address
  959. isSet = true
  960. }
  961. enableHTTPS, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__ENABLE_HTTPS", idx))
  962. if ok {
  963. binding.EnableHTTPS = enableHTTPS
  964. isSet = true
  965. }
  966. tlsVer, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__MIN_TLS_VERSION", idx))
  967. if ok {
  968. binding.MinTLSVersion = int(tlsVer)
  969. isSet = true
  970. }
  971. clientAuthType, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__CLIENT_AUTH_TYPE", idx))
  972. if ok {
  973. binding.ClientAuthType = int(clientAuthType)
  974. isSet = true
  975. }
  976. tlsCiphers, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__TLS_CIPHER_SUITES", idx))
  977. if ok {
  978. binding.TLSCipherSuites = tlsCiphers
  979. isSet = true
  980. }
  981. proxyAllowed, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__PROXY_ALLOWED", idx))
  982. if ok {
  983. binding.ProxyAllowed = proxyAllowed
  984. isSet = true
  985. }
  986. prefix, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__PREFIX", idx))
  987. if ok {
  988. binding.Prefix = prefix
  989. isSet = true
  990. }
  991. if isSet {
  992. if len(globalConf.WebDAVD.Bindings) > idx {
  993. globalConf.WebDAVD.Bindings[idx] = binding
  994. } else {
  995. globalConf.WebDAVD.Bindings = append(globalConf.WebDAVD.Bindings, binding)
  996. }
  997. }
  998. }
  999. func getHTTPDSecurityProxyHeadersFromEnv(idx int) []httpd.HTTPSProxyHeader {
  1000. var httpsProxyHeaders []httpd.HTTPSProxyHeader
  1001. for subIdx := 0; subIdx < 10; subIdx++ {
  1002. proxyKey, _ := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__HTTPS_PROXY_HEADERS__%v__KEY", idx, subIdx))
  1003. proxyVal, _ := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__HTTPS_PROXY_HEADERS__%v__VALUE", idx, subIdx))
  1004. if proxyKey != "" && proxyVal != "" {
  1005. httpsProxyHeaders = append(httpsProxyHeaders, httpd.HTTPSProxyHeader{
  1006. Key: proxyKey,
  1007. Value: proxyVal,
  1008. })
  1009. }
  1010. }
  1011. return httpsProxyHeaders
  1012. }
  1013. func getHTTPDSecurityConfFromEnv(idx int) (httpd.SecurityConf, bool) {
  1014. var result httpd.SecurityConf
  1015. isSet := false
  1016. enabled, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__ENABLED", idx))
  1017. if ok {
  1018. result.Enabled = enabled
  1019. isSet = true
  1020. }
  1021. allowedHosts, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__ALLOWED_HOSTS", idx))
  1022. if ok {
  1023. result.AllowedHosts = allowedHosts
  1024. isSet = true
  1025. }
  1026. allowedHostsAreRegex, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__ALLOWED_HOSTS_ARE_REGEX", idx))
  1027. if ok {
  1028. result.AllowedHostsAreRegex = allowedHostsAreRegex
  1029. isSet = true
  1030. }
  1031. hostsProxyHeaders, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__HOSTS_PROXY_HEADERS", idx))
  1032. if ok {
  1033. result.HostsProxyHeaders = hostsProxyHeaders
  1034. isSet = true
  1035. }
  1036. httpsProxyHeaders := getHTTPDSecurityProxyHeadersFromEnv(idx)
  1037. if len(httpsProxyHeaders) > 0 {
  1038. result.HTTPSProxyHeaders = httpsProxyHeaders
  1039. isSet = true
  1040. }
  1041. stsSeconds, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__STS_SECONDS", idx))
  1042. if ok {
  1043. result.STSSeconds = stsSeconds
  1044. }
  1045. stsIncludeSubDomains, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__STS_INCLUDE_SUBDOMAINS", idx))
  1046. if ok {
  1047. result.STSIncludeSubdomains = stsIncludeSubDomains
  1048. isSet = true
  1049. }
  1050. stsPreload, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__STS_PRELOAD", idx))
  1051. if ok {
  1052. result.STSPreload = stsPreload
  1053. isSet = true
  1054. }
  1055. contentTypeNosniff, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__CONTENT_TYPE_NOSNIFF", idx))
  1056. if ok {
  1057. result.ContentTypeNosniff = contentTypeNosniff
  1058. isSet = true
  1059. }
  1060. contentSecurityPolicy, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__CONTENT_SECURITY_POLICY", idx))
  1061. if ok {
  1062. result.ContentSecurityPolicy = contentSecurityPolicy
  1063. isSet = true
  1064. }
  1065. permissionsPolicy, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__PERMISSIONS_POLICY", idx))
  1066. if ok {
  1067. result.PermissionsPolicy = permissionsPolicy
  1068. isSet = true
  1069. }
  1070. crossOriginOpenedPolicy, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__CROSS_ORIGIN_OPENER_POLICY", idx))
  1071. if ok {
  1072. result.CrossOriginOpenerPolicy = crossOriginOpenedPolicy
  1073. isSet = true
  1074. }
  1075. expectCTHeader, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__EXPECT_CT_HEADER", idx))
  1076. if ok {
  1077. result.ExpectCTHeader = expectCTHeader
  1078. isSet = true
  1079. }
  1080. return result, isSet
  1081. }
  1082. func getHTTPDOIDCFromEnv(idx int) (httpd.OIDC, bool) {
  1083. var result httpd.OIDC
  1084. isSet := false
  1085. clientID, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__CLIENT_ID", idx))
  1086. if ok {
  1087. result.ClientID = clientID
  1088. isSet = true
  1089. }
  1090. clientSecret, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__CLIENT_SECRET", idx))
  1091. if ok {
  1092. result.ClientSecret = clientSecret
  1093. isSet = true
  1094. }
  1095. configURL, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__CONFIG_URL", idx))
  1096. if ok {
  1097. result.ConfigURL = configURL
  1098. isSet = true
  1099. }
  1100. redirectBaseURL, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__REDIRECT_BASE_URL", idx))
  1101. if ok {
  1102. result.RedirectBaseURL = redirectBaseURL
  1103. isSet = true
  1104. }
  1105. usernameField, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__USERNAME_FIELD", idx))
  1106. if ok {
  1107. result.UsernameField = usernameField
  1108. isSet = true
  1109. }
  1110. roleField, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__ROLE_FIELD", idx))
  1111. if ok {
  1112. result.RoleField = roleField
  1113. isSet = true
  1114. }
  1115. return result, isSet
  1116. }
  1117. func getHTTPDWebClientIntegrationsFromEnv(idx int) []httpd.WebClientIntegration {
  1118. var integrations []httpd.WebClientIntegration
  1119. for subIdx := 0; subIdx < 10; subIdx++ {
  1120. var integration httpd.WebClientIntegration
  1121. url, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__WEB_CLIENT_INTEGRATIONS__%v__URL", idx, subIdx))
  1122. if ok {
  1123. integration.URL = url
  1124. }
  1125. extensions, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__WEB_CLIENT_INTEGRATIONS__%v__FILE_EXTENSIONS",
  1126. idx, subIdx))
  1127. if ok {
  1128. integration.FileExtensions = extensions
  1129. }
  1130. if url != "" && len(extensions) > 0 {
  1131. integrations = append(integrations, integration)
  1132. }
  1133. }
  1134. return integrations
  1135. }
  1136. func getDefaultHTTPBinding(idx int) httpd.Binding {
  1137. binding := httpd.Binding{
  1138. EnableWebAdmin: true,
  1139. EnableWebClient: true,
  1140. RenderOpenAPI: true,
  1141. MinTLSVersion: 12,
  1142. }
  1143. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1144. binding = globalConf.HTTPDConfig.Bindings[idx]
  1145. }
  1146. return binding
  1147. }
  1148. func getHTTPDBindingFromEnv(idx int) {
  1149. binding := getDefaultHTTPBinding(idx)
  1150. isSet := false
  1151. port, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__PORT", idx))
  1152. if ok {
  1153. binding.Port = int(port)
  1154. isSet = true
  1155. }
  1156. address, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ADDRESS", idx))
  1157. if ok {
  1158. binding.Address = address
  1159. isSet = true
  1160. }
  1161. enableWebAdmin, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ENABLE_WEB_ADMIN", idx))
  1162. if ok {
  1163. binding.EnableWebAdmin = enableWebAdmin
  1164. isSet = true
  1165. }
  1166. enableWebClient, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ENABLE_WEB_CLIENT", idx))
  1167. if ok {
  1168. binding.EnableWebClient = enableWebClient
  1169. isSet = true
  1170. }
  1171. renderOpenAPI, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__RENDER_OPENAPI", idx))
  1172. if ok {
  1173. binding.RenderOpenAPI = renderOpenAPI
  1174. isSet = true
  1175. }
  1176. webClientIntegrations := getHTTPDWebClientIntegrationsFromEnv(idx)
  1177. if len(webClientIntegrations) > 0 {
  1178. binding.WebClientIntegrations = webClientIntegrations
  1179. isSet = true
  1180. }
  1181. enableHTTPS, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ENABLE_HTTPS", idx))
  1182. if ok {
  1183. binding.EnableHTTPS = enableHTTPS
  1184. isSet = true
  1185. }
  1186. tlsVer, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__MIN_TLS_VERSION", idx))
  1187. if ok {
  1188. binding.MinTLSVersion = int(tlsVer)
  1189. isSet = true
  1190. }
  1191. clientAuthType, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__CLIENT_AUTH_TYPE", idx))
  1192. if ok {
  1193. binding.ClientAuthType = int(clientAuthType)
  1194. isSet = true
  1195. }
  1196. tlsCiphers, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__TLS_CIPHER_SUITES", idx))
  1197. if ok {
  1198. binding.TLSCipherSuites = tlsCiphers
  1199. isSet = true
  1200. }
  1201. proxyAllowed, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__PROXY_ALLOWED", idx))
  1202. if ok {
  1203. binding.ProxyAllowed = proxyAllowed
  1204. isSet = true
  1205. }
  1206. hideLoginURL, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__HIDE_LOGIN_URL", idx))
  1207. if ok {
  1208. binding.HideLoginURL = int(hideLoginURL)
  1209. isSet = true
  1210. }
  1211. oidc, ok := getHTTPDOIDCFromEnv(idx)
  1212. if ok {
  1213. binding.OIDC = oidc
  1214. isSet = true
  1215. }
  1216. securityConf, ok := getHTTPDSecurityConfFromEnv(idx)
  1217. if ok {
  1218. binding.Security = securityConf
  1219. isSet = true
  1220. }
  1221. setHTTPDBinding(isSet, binding, idx)
  1222. }
  1223. func setHTTPDBinding(isSet bool, binding httpd.Binding, idx int) {
  1224. if isSet {
  1225. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1226. globalConf.HTTPDConfig.Bindings[idx] = binding
  1227. } else {
  1228. globalConf.HTTPDConfig.Bindings = append(globalConf.HTTPDConfig.Bindings, binding)
  1229. }
  1230. }
  1231. }
  1232. func getHTTPClientCertificatesFromEnv(idx int) {
  1233. tlsCert := httpclient.TLSKeyPair{}
  1234. cert, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTP__CERTIFICATES__%v__CERT", idx))
  1235. if ok {
  1236. tlsCert.Cert = cert
  1237. }
  1238. key, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTP__CERTIFICATES__%v__KEY", idx))
  1239. if ok {
  1240. tlsCert.Key = key
  1241. }
  1242. if tlsCert.Cert != "" && tlsCert.Key != "" {
  1243. if len(globalConf.HTTPConfig.Certificates) > idx {
  1244. globalConf.HTTPConfig.Certificates[idx] = tlsCert
  1245. } else {
  1246. globalConf.HTTPConfig.Certificates = append(globalConf.HTTPConfig.Certificates, tlsCert)
  1247. }
  1248. }
  1249. }
  1250. func getHTTPClientHeadersFromEnv(idx int) {
  1251. header := httpclient.Header{}
  1252. key, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTP__HEADERS__%v__KEY", idx))
  1253. if ok {
  1254. header.Key = key
  1255. }
  1256. value, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTP__HEADERS__%v__VALUE", idx))
  1257. if ok {
  1258. header.Value = value
  1259. }
  1260. url, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTP__HEADERS__%v__URL", idx))
  1261. if ok {
  1262. header.URL = url
  1263. }
  1264. if header.Key != "" && header.Value != "" {
  1265. if len(globalConf.HTTPConfig.Headers) > idx {
  1266. globalConf.HTTPConfig.Headers[idx] = header
  1267. } else {
  1268. globalConf.HTTPConfig.Headers = append(globalConf.HTTPConfig.Headers, header)
  1269. }
  1270. }
  1271. }
  1272. func setViperDefaults() {
  1273. viper.SetDefault("common.idle_timeout", globalConf.Common.IdleTimeout)
  1274. viper.SetDefault("common.upload_mode", globalConf.Common.UploadMode)
  1275. viper.SetDefault("common.actions.execute_on", globalConf.Common.Actions.ExecuteOn)
  1276. viper.SetDefault("common.actions.execute_sync", globalConf.Common.Actions.ExecuteSync)
  1277. viper.SetDefault("common.actions.hook", globalConf.Common.Actions.Hook)
  1278. viper.SetDefault("common.setstat_mode", globalConf.Common.SetstatMode)
  1279. viper.SetDefault("common.temp_path", globalConf.Common.TempPath)
  1280. viper.SetDefault("common.proxy_protocol", globalConf.Common.ProxyProtocol)
  1281. viper.SetDefault("common.proxy_allowed", globalConf.Common.ProxyAllowed)
  1282. viper.SetDefault("common.post_connect_hook", globalConf.Common.PostConnectHook)
  1283. viper.SetDefault("common.post_disconnect_hook", globalConf.Common.PostDisconnectHook)
  1284. viper.SetDefault("common.data_retention_hook", globalConf.Common.DataRetentionHook)
  1285. viper.SetDefault("common.max_total_connections", globalConf.Common.MaxTotalConnections)
  1286. viper.SetDefault("common.max_per_host_connections", globalConf.Common.MaxPerHostConnections)
  1287. viper.SetDefault("common.defender.enabled", globalConf.Common.DefenderConfig.Enabled)
  1288. viper.SetDefault("common.defender.driver", globalConf.Common.DefenderConfig.Driver)
  1289. viper.SetDefault("common.defender.ban_time", globalConf.Common.DefenderConfig.BanTime)
  1290. viper.SetDefault("common.defender.ban_time_increment", globalConf.Common.DefenderConfig.BanTimeIncrement)
  1291. viper.SetDefault("common.defender.threshold", globalConf.Common.DefenderConfig.Threshold)
  1292. viper.SetDefault("common.defender.score_invalid", globalConf.Common.DefenderConfig.ScoreInvalid)
  1293. viper.SetDefault("common.defender.score_valid", globalConf.Common.DefenderConfig.ScoreValid)
  1294. viper.SetDefault("common.defender.score_limit_exceeded", globalConf.Common.DefenderConfig.ScoreLimitExceeded)
  1295. viper.SetDefault("common.defender.observation_time", globalConf.Common.DefenderConfig.ObservationTime)
  1296. viper.SetDefault("common.defender.entries_soft_limit", globalConf.Common.DefenderConfig.EntriesSoftLimit)
  1297. viper.SetDefault("common.defender.entries_hard_limit", globalConf.Common.DefenderConfig.EntriesHardLimit)
  1298. viper.SetDefault("common.defender.safelist_file", globalConf.Common.DefenderConfig.SafeListFile)
  1299. viper.SetDefault("common.defender.blocklist_file", globalConf.Common.DefenderConfig.BlockListFile)
  1300. viper.SetDefault("sftpd.max_auth_tries", globalConf.SFTPD.MaxAuthTries)
  1301. viper.SetDefault("sftpd.banner", globalConf.SFTPD.Banner)
  1302. viper.SetDefault("sftpd.host_keys", globalConf.SFTPD.HostKeys)
  1303. viper.SetDefault("sftpd.kex_algorithms", globalConf.SFTPD.KexAlgorithms)
  1304. viper.SetDefault("sftpd.ciphers", globalConf.SFTPD.Ciphers)
  1305. viper.SetDefault("sftpd.macs", globalConf.SFTPD.MACs)
  1306. viper.SetDefault("sftpd.trusted_user_ca_keys", globalConf.SFTPD.TrustedUserCAKeys)
  1307. viper.SetDefault("sftpd.login_banner_file", globalConf.SFTPD.LoginBannerFile)
  1308. viper.SetDefault("sftpd.enabled_ssh_commands", sftpd.GetDefaultSSHCommands())
  1309. viper.SetDefault("sftpd.keyboard_interactive_authentication", globalConf.SFTPD.KeyboardInteractiveAuthentication)
  1310. viper.SetDefault("sftpd.keyboard_interactive_auth_hook", globalConf.SFTPD.KeyboardInteractiveHook)
  1311. viper.SetDefault("sftpd.password_authentication", globalConf.SFTPD.PasswordAuthentication)
  1312. viper.SetDefault("sftpd.folder_prefix", globalConf.SFTPD.FolderPrefix)
  1313. viper.SetDefault("ftpd.banner", globalConf.FTPD.Banner)
  1314. viper.SetDefault("ftpd.banner_file", globalConf.FTPD.BannerFile)
  1315. viper.SetDefault("ftpd.active_transfers_port_non_20", globalConf.FTPD.ActiveTransfersPortNon20)
  1316. viper.SetDefault("ftpd.passive_port_range.start", globalConf.FTPD.PassivePortRange.Start)
  1317. viper.SetDefault("ftpd.passive_port_range.end", globalConf.FTPD.PassivePortRange.End)
  1318. viper.SetDefault("ftpd.disable_active_mode", globalConf.FTPD.DisableActiveMode)
  1319. viper.SetDefault("ftpd.enable_site", globalConf.FTPD.EnableSite)
  1320. viper.SetDefault("ftpd.hash_support", globalConf.FTPD.HASHSupport)
  1321. viper.SetDefault("ftpd.combine_support", globalConf.FTPD.CombineSupport)
  1322. viper.SetDefault("ftpd.certificate_file", globalConf.FTPD.CertificateFile)
  1323. viper.SetDefault("ftpd.certificate_key_file", globalConf.FTPD.CertificateKeyFile)
  1324. viper.SetDefault("ftpd.ca_certificates", globalConf.FTPD.CACertificates)
  1325. viper.SetDefault("ftpd.ca_revocation_lists", globalConf.FTPD.CARevocationLists)
  1326. viper.SetDefault("webdavd.certificate_file", globalConf.WebDAVD.CertificateFile)
  1327. viper.SetDefault("webdavd.certificate_key_file", globalConf.WebDAVD.CertificateKeyFile)
  1328. viper.SetDefault("webdavd.ca_certificates", globalConf.WebDAVD.CACertificates)
  1329. viper.SetDefault("webdavd.ca_revocation_lists", globalConf.WebDAVD.CARevocationLists)
  1330. viper.SetDefault("webdavd.cors.enabled", globalConf.WebDAVD.Cors.Enabled)
  1331. viper.SetDefault("webdavd.cors.allowed_origins", globalConf.WebDAVD.Cors.AllowedOrigins)
  1332. viper.SetDefault("webdavd.cors.allowed_methods", globalConf.WebDAVD.Cors.AllowedMethods)
  1333. viper.SetDefault("webdavd.cors.allowed_headers", globalConf.WebDAVD.Cors.AllowedHeaders)
  1334. viper.SetDefault("webdavd.cors.exposed_headers", globalConf.WebDAVD.Cors.ExposedHeaders)
  1335. viper.SetDefault("webdavd.cors.allow_credentials", globalConf.WebDAVD.Cors.AllowCredentials)
  1336. viper.SetDefault("webdavd.cors.max_age", globalConf.WebDAVD.Cors.MaxAge)
  1337. viper.SetDefault("webdavd.cache.users.expiration_time", globalConf.WebDAVD.Cache.Users.ExpirationTime)
  1338. viper.SetDefault("webdavd.cache.users.max_size", globalConf.WebDAVD.Cache.Users.MaxSize)
  1339. viper.SetDefault("webdavd.cache.mime_types.enabled", globalConf.WebDAVD.Cache.MimeTypes.Enabled)
  1340. viper.SetDefault("webdavd.cache.mime_types.max_size", globalConf.WebDAVD.Cache.MimeTypes.MaxSize)
  1341. viper.SetDefault("data_provider.driver", globalConf.ProviderConf.Driver)
  1342. viper.SetDefault("data_provider.name", globalConf.ProviderConf.Name)
  1343. viper.SetDefault("data_provider.host", globalConf.ProviderConf.Host)
  1344. viper.SetDefault("data_provider.port", globalConf.ProviderConf.Port)
  1345. viper.SetDefault("data_provider.username", globalConf.ProviderConf.Username)
  1346. viper.SetDefault("data_provider.password", globalConf.ProviderConf.Password)
  1347. viper.SetDefault("data_provider.sslmode", globalConf.ProviderConf.SSLMode)
  1348. viper.SetDefault("data_provider.root_cert", globalConf.ProviderConf.RootCert)
  1349. viper.SetDefault("data_provider.client_cert", globalConf.ProviderConf.ClientCert)
  1350. viper.SetDefault("data_provider.client_key", globalConf.ProviderConf.ClientKey)
  1351. viper.SetDefault("data_provider.connection_string", globalConf.ProviderConf.ConnectionString)
  1352. viper.SetDefault("data_provider.sql_tables_prefix", globalConf.ProviderConf.SQLTablesPrefix)
  1353. viper.SetDefault("data_provider.track_quota", globalConf.ProviderConf.TrackQuota)
  1354. viper.SetDefault("data_provider.pool_size", globalConf.ProviderConf.PoolSize)
  1355. viper.SetDefault("data_provider.users_base_dir", globalConf.ProviderConf.UsersBaseDir)
  1356. viper.SetDefault("data_provider.actions.execute_on", globalConf.ProviderConf.Actions.ExecuteOn)
  1357. viper.SetDefault("data_provider.actions.execute_for", globalConf.ProviderConf.Actions.ExecuteFor)
  1358. viper.SetDefault("data_provider.actions.hook", globalConf.ProviderConf.Actions.Hook)
  1359. viper.SetDefault("data_provider.external_auth_hook", globalConf.ProviderConf.ExternalAuthHook)
  1360. viper.SetDefault("data_provider.external_auth_scope", globalConf.ProviderConf.ExternalAuthScope)
  1361. viper.SetDefault("data_provider.credentials_path", globalConf.ProviderConf.CredentialsPath)
  1362. viper.SetDefault("data_provider.prefer_database_credentials", globalConf.ProviderConf.PreferDatabaseCredentials)
  1363. viper.SetDefault("data_provider.pre_login_hook", globalConf.ProviderConf.PreLoginHook)
  1364. viper.SetDefault("data_provider.post_login_hook", globalConf.ProviderConf.PostLoginHook)
  1365. viper.SetDefault("data_provider.post_login_scope", globalConf.ProviderConf.PostLoginScope)
  1366. viper.SetDefault("data_provider.check_password_hook", globalConf.ProviderConf.CheckPasswordHook)
  1367. viper.SetDefault("data_provider.check_password_scope", globalConf.ProviderConf.CheckPasswordScope)
  1368. viper.SetDefault("data_provider.password_hashing.bcrypt_options.cost", globalConf.ProviderConf.PasswordHashing.BcryptOptions.Cost)
  1369. viper.SetDefault("data_provider.password_hashing.argon2_options.memory", globalConf.ProviderConf.PasswordHashing.Argon2Options.Memory)
  1370. viper.SetDefault("data_provider.password_hashing.argon2_options.iterations", globalConf.ProviderConf.PasswordHashing.Argon2Options.Iterations)
  1371. viper.SetDefault("data_provider.password_hashing.argon2_options.parallelism", globalConf.ProviderConf.PasswordHashing.Argon2Options.Parallelism)
  1372. viper.SetDefault("data_provider.password_hashing.algo", globalConf.ProviderConf.PasswordHashing.Algo)
  1373. viper.SetDefault("data_provider.password_validation.admins.min_entropy", globalConf.ProviderConf.PasswordValidation.Admins.MinEntropy)
  1374. viper.SetDefault("data_provider.password_validation.users.min_entropy", globalConf.ProviderConf.PasswordValidation.Users.MinEntropy)
  1375. viper.SetDefault("data_provider.password_caching", globalConf.ProviderConf.PasswordCaching)
  1376. viper.SetDefault("data_provider.update_mode", globalConf.ProviderConf.UpdateMode)
  1377. viper.SetDefault("data_provider.delayed_quota_update", globalConf.ProviderConf.DelayedQuotaUpdate)
  1378. viper.SetDefault("data_provider.create_default_admin", globalConf.ProviderConf.CreateDefaultAdmin)
  1379. viper.SetDefault("data_provider.naming_rules", globalConf.ProviderConf.NamingRules)
  1380. viper.SetDefault("data_provider.is_shared", globalConf.ProviderConf.IsShared)
  1381. viper.SetDefault("httpd.templates_path", globalConf.HTTPDConfig.TemplatesPath)
  1382. viper.SetDefault("httpd.static_files_path", globalConf.HTTPDConfig.StaticFilesPath)
  1383. viper.SetDefault("httpd.backups_path", globalConf.HTTPDConfig.BackupsPath)
  1384. viper.SetDefault("httpd.openapi_path", globalConf.HTTPDConfig.OpenAPIPath)
  1385. viper.SetDefault("httpd.web_root", globalConf.HTTPDConfig.WebRoot)
  1386. viper.SetDefault("httpd.certificate_file", globalConf.HTTPDConfig.CertificateFile)
  1387. viper.SetDefault("httpd.certificate_key_file", globalConf.HTTPDConfig.CertificateKeyFile)
  1388. viper.SetDefault("httpd.ca_certificates", globalConf.HTTPDConfig.CACertificates)
  1389. viper.SetDefault("httpd.ca_revocation_lists", globalConf.HTTPDConfig.CARevocationLists)
  1390. viper.SetDefault("httpd.signing_passphrase", globalConf.HTTPDConfig.SigningPassphrase)
  1391. viper.SetDefault("httpd.max_upload_file_size", globalConf.HTTPDConfig.MaxUploadFileSize)
  1392. viper.SetDefault("httpd.cors.enabled", globalConf.HTTPDConfig.Cors.Enabled)
  1393. viper.SetDefault("httpd.cors.allowed_origins", globalConf.HTTPDConfig.Cors.AllowedOrigins)
  1394. viper.SetDefault("httpd.cors.allowed_methods", globalConf.HTTPDConfig.Cors.AllowedMethods)
  1395. viper.SetDefault("httpd.cors.allowed_headers", globalConf.HTTPDConfig.Cors.AllowedHeaders)
  1396. viper.SetDefault("httpd.cors.exposed_headers", globalConf.HTTPDConfig.Cors.ExposedHeaders)
  1397. viper.SetDefault("httpd.cors.allow_credentials", globalConf.HTTPDConfig.Cors.AllowCredentials)
  1398. viper.SetDefault("httpd.setup.installation_code", globalConf.HTTPDConfig.Setup.InstallationCode)
  1399. viper.SetDefault("httpd.setup.installation_code_hint", globalConf.HTTPDConfig.Setup.InstallationCodeHint)
  1400. viper.SetDefault("httpd.cors.max_age", globalConf.HTTPDConfig.Cors.MaxAge)
  1401. viper.SetDefault("http.timeout", globalConf.HTTPConfig.Timeout)
  1402. viper.SetDefault("http.retry_wait_min", globalConf.HTTPConfig.RetryWaitMin)
  1403. viper.SetDefault("http.retry_wait_max", globalConf.HTTPConfig.RetryWaitMax)
  1404. viper.SetDefault("http.retry_max", globalConf.HTTPConfig.RetryMax)
  1405. viper.SetDefault("http.ca_certificates", globalConf.HTTPConfig.CACertificates)
  1406. viper.SetDefault("http.skip_tls_verify", globalConf.HTTPConfig.SkipTLSVerify)
  1407. viper.SetDefault("kms.secrets.url", globalConf.KMSConfig.Secrets.URL)
  1408. viper.SetDefault("kms.secrets.master_key", globalConf.KMSConfig.Secrets.MasterKeyString)
  1409. viper.SetDefault("kms.secrets.master_key_path", globalConf.KMSConfig.Secrets.MasterKeyPath)
  1410. viper.SetDefault("telemetry.bind_port", globalConf.TelemetryConfig.BindPort)
  1411. viper.SetDefault("telemetry.bind_address", globalConf.TelemetryConfig.BindAddress)
  1412. viper.SetDefault("telemetry.enable_profiler", globalConf.TelemetryConfig.EnableProfiler)
  1413. viper.SetDefault("telemetry.auth_user_file", globalConf.TelemetryConfig.AuthUserFile)
  1414. viper.SetDefault("telemetry.certificate_file", globalConf.TelemetryConfig.CertificateFile)
  1415. viper.SetDefault("telemetry.certificate_key_file", globalConf.TelemetryConfig.CertificateKeyFile)
  1416. viper.SetDefault("telemetry.min_tls_version", globalConf.TelemetryConfig.MinTLSVersion)
  1417. viper.SetDefault("telemetry.tls_cipher_suites", globalConf.TelemetryConfig.TLSCipherSuites)
  1418. viper.SetDefault("smtp.host", globalConf.SMTPConfig.Host)
  1419. viper.SetDefault("smtp.port", globalConf.SMTPConfig.Port)
  1420. viper.SetDefault("smtp.from", globalConf.SMTPConfig.From)
  1421. viper.SetDefault("smtp.user", globalConf.SMTPConfig.User)
  1422. viper.SetDefault("smtp.password", globalConf.SMTPConfig.Password)
  1423. viper.SetDefault("smtp.auth_type", globalConf.SMTPConfig.AuthType)
  1424. viper.SetDefault("smtp.encryption", globalConf.SMTPConfig.Encryption)
  1425. viper.SetDefault("smtp.domain", globalConf.SMTPConfig.Domain)
  1426. viper.SetDefault("smtp.templates_path", globalConf.SMTPConfig.TemplatesPath)
  1427. }
  1428. func lookupBoolFromEnv(envName string) (bool, bool) {
  1429. value, ok := os.LookupEnv(envName)
  1430. if ok {
  1431. converted, err := strconv.ParseBool(strings.TrimSpace(value))
  1432. if err == nil {
  1433. return converted, ok
  1434. }
  1435. }
  1436. return false, false
  1437. }
  1438. func lookupIntFromEnv(envName string) (int64, bool) {
  1439. value, ok := os.LookupEnv(envName)
  1440. if ok {
  1441. converted, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64)
  1442. if err == nil {
  1443. return converted, ok
  1444. }
  1445. }
  1446. return 0, false
  1447. }
  1448. func lookupStringListFromEnv(envName string) ([]string, bool) {
  1449. value, ok := os.LookupEnv(envName)
  1450. if ok {
  1451. var result []string
  1452. for _, v := range strings.Split(value, ",") {
  1453. val := strings.TrimSpace(v)
  1454. if val != "" {
  1455. result = append(result, val)
  1456. }
  1457. }
  1458. return result, true
  1459. }
  1460. return nil, false
  1461. }