1
0

config.go 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141
  1. // Copyright (C) 2019-2022 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 config manages the configuration
  15. package config
  16. import (
  17. "errors"
  18. "fmt"
  19. "os"
  20. "path/filepath"
  21. "strconv"
  22. "strings"
  23. "github.com/spf13/viper"
  24. "github.com/subosito/gotenv"
  25. "github.com/drakkan/sftpgo/v2/internal/acme"
  26. "github.com/drakkan/sftpgo/v2/internal/command"
  27. "github.com/drakkan/sftpgo/v2/internal/common"
  28. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  29. "github.com/drakkan/sftpgo/v2/internal/ftpd"
  30. "github.com/drakkan/sftpgo/v2/internal/httpclient"
  31. "github.com/drakkan/sftpgo/v2/internal/httpd"
  32. "github.com/drakkan/sftpgo/v2/internal/kms"
  33. "github.com/drakkan/sftpgo/v2/internal/logger"
  34. "github.com/drakkan/sftpgo/v2/internal/mfa"
  35. "github.com/drakkan/sftpgo/v2/internal/plugin"
  36. "github.com/drakkan/sftpgo/v2/internal/sftpd"
  37. "github.com/drakkan/sftpgo/v2/internal/smtp"
  38. "github.com/drakkan/sftpgo/v2/internal/telemetry"
  39. "github.com/drakkan/sftpgo/v2/internal/util"
  40. "github.com/drakkan/sftpgo/v2/internal/version"
  41. "github.com/drakkan/sftpgo/v2/internal/webdavd"
  42. )
  43. const (
  44. logSender = "config"
  45. // configName defines the name for config file.
  46. // This name does not include the extension, viper will search for files
  47. // with supported extensions such as "sftpgo.json", "sftpgo.yaml" and so on
  48. configName = "sftpgo"
  49. // ConfigEnvPrefix defines a prefix that environment variables will use
  50. configEnvPrefix = "sftpgo"
  51. )
  52. var (
  53. globalConf globalConfig
  54. defaultSFTPDBanner = fmt.Sprintf("SFTPGo_%v", version.Get().Version)
  55. defaultFTPDBanner = fmt.Sprintf("SFTPGo %v ready", version.Get().Version)
  56. defaultInstallCodeHint = "Installation code"
  57. defaultSFTPDBinding = sftpd.Binding{
  58. Address: "",
  59. Port: 2022,
  60. ApplyProxyConfig: true,
  61. }
  62. defaultFTPDBinding = ftpd.Binding{
  63. Address: "",
  64. Port: 0,
  65. ApplyProxyConfig: true,
  66. TLSMode: 0,
  67. CertificateFile: "",
  68. CertificateKeyFile: "",
  69. MinTLSVersion: 12,
  70. ForcePassiveIP: "",
  71. PassiveIPOverrides: nil,
  72. ClientAuthType: 0,
  73. TLSCipherSuites: nil,
  74. PassiveConnectionsSecurity: 0,
  75. ActiveConnectionsSecurity: 0,
  76. Debug: false,
  77. }
  78. defaultWebDAVDBinding = webdavd.Binding{
  79. Address: "",
  80. Port: 0,
  81. EnableHTTPS: false,
  82. CertificateFile: "",
  83. CertificateKeyFile: "",
  84. MinTLSVersion: 12,
  85. ClientAuthType: 0,
  86. TLSCipherSuites: nil,
  87. Prefix: "",
  88. ProxyAllowed: nil,
  89. ClientIPProxyHeader: "",
  90. ClientIPHeaderDepth: 0,
  91. DisableWWWAuthHeader: false,
  92. }
  93. defaultHTTPDBinding = httpd.Binding{
  94. Address: "",
  95. Port: 8080,
  96. EnableWebAdmin: true,
  97. EnableWebClient: true,
  98. EnableRESTAPI: true,
  99. EnabledLoginMethods: 0,
  100. EnableHTTPS: false,
  101. CertificateFile: "",
  102. CertificateKeyFile: "",
  103. MinTLSVersion: 12,
  104. ClientAuthType: 0,
  105. TLSCipherSuites: nil,
  106. ProxyAllowed: nil,
  107. ClientIPProxyHeader: "",
  108. ClientIPHeaderDepth: 0,
  109. HideLoginURL: 0,
  110. RenderOpenAPI: true,
  111. WebClientIntegrations: nil,
  112. OIDC: httpd.OIDC{
  113. ClientID: "",
  114. ClientSecret: "",
  115. ConfigURL: "",
  116. RedirectBaseURL: "",
  117. UsernameField: "",
  118. RoleField: "",
  119. ImplicitRoles: false,
  120. Scopes: []string{"openid", "profile", "email"},
  121. CustomFields: []string{},
  122. InsecureSkipSignatureCheck: false,
  123. Debug: false,
  124. },
  125. Security: httpd.SecurityConf{
  126. Enabled: false,
  127. AllowedHosts: nil,
  128. AllowedHostsAreRegex: false,
  129. HostsProxyHeaders: nil,
  130. HTTPSRedirect: false,
  131. HTTPSHost: "",
  132. HTTPSProxyHeaders: nil,
  133. STSSeconds: 0,
  134. STSIncludeSubdomains: false,
  135. STSPreload: false,
  136. ContentTypeNosniff: false,
  137. ContentSecurityPolicy: "",
  138. PermissionsPolicy: "",
  139. CrossOriginOpenerPolicy: "",
  140. ExpectCTHeader: "",
  141. },
  142. Branding: httpd.Branding{},
  143. }
  144. defaultRateLimiter = common.RateLimiterConfig{
  145. Average: 0,
  146. Period: 1000,
  147. Burst: 1,
  148. Type: 2,
  149. Protocols: []string{common.ProtocolSSH, common.ProtocolFTP, common.ProtocolWebDAV, common.ProtocolHTTP},
  150. AllowList: []string{},
  151. GenerateDefenderEvents: false,
  152. EntriesSoftLimit: 100,
  153. EntriesHardLimit: 150,
  154. }
  155. defaultTOTP = mfa.TOTPConfig{
  156. Name: "Default",
  157. Issuer: "SFTPGo",
  158. Algo: mfa.TOTPAlgoSHA1,
  159. }
  160. )
  161. type globalConfig struct {
  162. Common common.Configuration `json:"common" mapstructure:"common"`
  163. ACME acme.Configuration `json:"acme" mapstructure:"acme"`
  164. SFTPD sftpd.Configuration `json:"sftpd" mapstructure:"sftpd"`
  165. FTPD ftpd.Configuration `json:"ftpd" mapstructure:"ftpd"`
  166. WebDAVD webdavd.Configuration `json:"webdavd" mapstructure:"webdavd"`
  167. ProviderConf dataprovider.Config `json:"data_provider" mapstructure:"data_provider"`
  168. HTTPDConfig httpd.Conf `json:"httpd" mapstructure:"httpd"`
  169. HTTPConfig httpclient.Config `json:"http" mapstructure:"http"`
  170. CommandConfig command.Config `json:"command" mapstructure:"command"`
  171. KMSConfig kms.Configuration `json:"kms" mapstructure:"kms"`
  172. MFAConfig mfa.Config `json:"mfa" mapstructure:"mfa"`
  173. TelemetryConfig telemetry.Conf `json:"telemetry" mapstructure:"telemetry"`
  174. PluginsConfig []plugin.Config `json:"plugins" mapstructure:"plugins"`
  175. SMTPConfig smtp.Config `json:"smtp" mapstructure:"smtp"`
  176. }
  177. func init() {
  178. Init()
  179. }
  180. // Init initializes the global configuration.
  181. // It is not supposed to be called outside of this package.
  182. // It is exported to minimize refactoring efforts. Will eventually disappear.
  183. func Init() {
  184. // create a default configuration to use if no config file is provided
  185. globalConf = globalConfig{
  186. Common: common.Configuration{
  187. IdleTimeout: 15,
  188. UploadMode: 0,
  189. Actions: common.ProtocolActions{
  190. ExecuteOn: []string{},
  191. ExecuteSync: []string{},
  192. Hook: "",
  193. },
  194. SetstatMode: 0,
  195. TempPath: "",
  196. ProxyProtocol: 0,
  197. ProxyAllowed: []string{},
  198. PostConnectHook: "",
  199. PostDisconnectHook: "",
  200. DataRetentionHook: "",
  201. MaxTotalConnections: 0,
  202. MaxPerHostConnections: 20,
  203. WhiteListFile: "",
  204. AllowSelfConnections: 0,
  205. DefenderConfig: common.DefenderConfig{
  206. Enabled: false,
  207. Driver: common.DefenderDriverMemory,
  208. BanTime: 30,
  209. BanTimeIncrement: 50,
  210. Threshold: 15,
  211. ScoreInvalid: 2,
  212. ScoreValid: 1,
  213. ScoreLimitExceeded: 3,
  214. ObservationTime: 30,
  215. EntriesSoftLimit: 100,
  216. EntriesHardLimit: 150,
  217. SafeListFile: "",
  218. BlockListFile: "",
  219. SafeList: []string{},
  220. BlockList: []string{},
  221. },
  222. RateLimitersConfig: []common.RateLimiterConfig{defaultRateLimiter},
  223. },
  224. ACME: acme.Configuration{
  225. Email: "",
  226. KeyType: "4096",
  227. CertsPath: "certs",
  228. CAEndpoint: "https://acme-v02.api.letsencrypt.org/directory",
  229. Domains: []string{},
  230. RenewDays: 30,
  231. HTTP01Challenge: acme.HTTP01Challenge{
  232. Port: 80,
  233. WebRoot: "",
  234. ProxyHeader: "",
  235. },
  236. TLSALPN01Challenge: acme.TLSALPN01Challenge{
  237. Port: 0,
  238. },
  239. },
  240. SFTPD: sftpd.Configuration{
  241. Bindings: []sftpd.Binding{defaultSFTPDBinding},
  242. MaxAuthTries: 0,
  243. Banner: defaultSFTPDBanner,
  244. HostKeys: []string{},
  245. HostCertificates: []string{},
  246. HostKeyAlgorithms: []string{},
  247. KexAlgorithms: []string{},
  248. Ciphers: []string{},
  249. MACs: []string{},
  250. TrustedUserCAKeys: []string{},
  251. RevokedUserCertsFile: "",
  252. LoginBannerFile: "",
  253. EnabledSSHCommands: []string{},
  254. KeyboardInteractiveAuthentication: false,
  255. KeyboardInteractiveHook: "",
  256. PasswordAuthentication: true,
  257. FolderPrefix: "",
  258. },
  259. FTPD: ftpd.Configuration{
  260. Bindings: []ftpd.Binding{defaultFTPDBinding},
  261. Banner: defaultFTPDBanner,
  262. BannerFile: "",
  263. ActiveTransfersPortNon20: true,
  264. PassivePortRange: ftpd.PortRange{
  265. Start: 50000,
  266. End: 50100,
  267. },
  268. DisableActiveMode: false,
  269. EnableSite: false,
  270. HASHSupport: 0,
  271. CombineSupport: 0,
  272. CertificateFile: "",
  273. CertificateKeyFile: "",
  274. CACertificates: []string{},
  275. CARevocationLists: []string{},
  276. },
  277. WebDAVD: webdavd.Configuration{
  278. Bindings: []webdavd.Binding{defaultWebDAVDBinding},
  279. CertificateFile: "",
  280. CertificateKeyFile: "",
  281. CACertificates: []string{},
  282. CARevocationLists: []string{},
  283. Cors: webdavd.CorsConfig{
  284. Enabled: false,
  285. AllowedOrigins: []string{},
  286. AllowedMethods: []string{},
  287. AllowedHeaders: []string{},
  288. ExposedHeaders: []string{},
  289. AllowCredentials: false,
  290. MaxAge: 0,
  291. OptionsPassthrough: false,
  292. OptionsSuccessStatus: 0,
  293. AllowPrivateNetwork: false,
  294. },
  295. Cache: webdavd.Cache{
  296. Users: webdavd.UsersCacheConfig{
  297. ExpirationTime: 0,
  298. MaxSize: 50,
  299. },
  300. MimeTypes: webdavd.MimeCacheConfig{
  301. Enabled: true,
  302. MaxSize: 1000,
  303. },
  304. },
  305. },
  306. ProviderConf: dataprovider.Config{
  307. Driver: "sqlite",
  308. Name: "sftpgo.db",
  309. Host: "",
  310. Port: 0,
  311. Username: "",
  312. Password: "",
  313. ConnectionString: "",
  314. SQLTablesPrefix: "",
  315. SSLMode: 0,
  316. DisableSNI: false,
  317. TargetSessionAttrs: "",
  318. RootCert: "",
  319. ClientCert: "",
  320. ClientKey: "",
  321. TrackQuota: 2,
  322. PoolSize: 0,
  323. UsersBaseDir: "",
  324. Actions: dataprovider.ObjectsActions{
  325. ExecuteOn: []string{},
  326. ExecuteFor: []string{},
  327. Hook: "",
  328. },
  329. ExternalAuthHook: "",
  330. ExternalAuthScope: 0,
  331. PreLoginHook: "",
  332. PostLoginHook: "",
  333. PostLoginScope: 0,
  334. CheckPasswordHook: "",
  335. CheckPasswordScope: 0,
  336. PasswordHashing: dataprovider.PasswordHashing{
  337. Argon2Options: dataprovider.Argon2Options{
  338. Memory: 65536,
  339. Iterations: 1,
  340. Parallelism: 2,
  341. },
  342. BcryptOptions: dataprovider.BcryptOptions{
  343. Cost: 10,
  344. },
  345. Algo: dataprovider.HashingAlgoBcrypt,
  346. },
  347. PasswordValidation: dataprovider.PasswordValidation{
  348. Admins: dataprovider.PasswordValidationRules{
  349. MinEntropy: 0,
  350. },
  351. Users: dataprovider.PasswordValidationRules{
  352. MinEntropy: 0,
  353. },
  354. },
  355. PasswordCaching: true,
  356. UpdateMode: 0,
  357. DelayedQuotaUpdate: 0,
  358. CreateDefaultAdmin: false,
  359. NamingRules: 1,
  360. IsShared: 0,
  361. Node: dataprovider.NodeConfig{
  362. Host: "",
  363. Port: 0,
  364. Proto: "http",
  365. },
  366. BackupsPath: "backups",
  367. },
  368. HTTPDConfig: httpd.Conf{
  369. Bindings: []httpd.Binding{defaultHTTPDBinding},
  370. TemplatesPath: "templates",
  371. StaticFilesPath: "static",
  372. OpenAPIPath: "openapi",
  373. WebRoot: "",
  374. CertificateFile: "",
  375. CertificateKeyFile: "",
  376. CACertificates: nil,
  377. CARevocationLists: nil,
  378. SigningPassphrase: "",
  379. TokenValidation: 0,
  380. MaxUploadFileSize: 1048576000,
  381. Cors: httpd.CorsConfig{
  382. Enabled: false,
  383. AllowedOrigins: []string{},
  384. AllowedMethods: []string{},
  385. AllowedHeaders: []string{},
  386. ExposedHeaders: []string{},
  387. AllowCredentials: false,
  388. MaxAge: 0,
  389. OptionsPassthrough: false,
  390. OptionsSuccessStatus: 0,
  391. AllowPrivateNetwork: false,
  392. },
  393. Setup: httpd.SetupConfig{
  394. InstallationCode: "",
  395. InstallationCodeHint: defaultInstallCodeHint,
  396. },
  397. HideSupportLink: false,
  398. },
  399. HTTPConfig: httpclient.Config{
  400. Timeout: 20,
  401. RetryWaitMin: 2,
  402. RetryWaitMax: 30,
  403. RetryMax: 3,
  404. CACertificates: nil,
  405. Certificates: nil,
  406. SkipTLSVerify: false,
  407. Headers: nil,
  408. },
  409. CommandConfig: command.Config{
  410. Timeout: 30,
  411. Env: nil,
  412. Commands: nil,
  413. },
  414. KMSConfig: kms.Configuration{
  415. Secrets: kms.Secrets{
  416. URL: "",
  417. MasterKeyString: "",
  418. MasterKeyPath: "",
  419. },
  420. },
  421. MFAConfig: mfa.Config{
  422. TOTP: []mfa.TOTPConfig{defaultTOTP},
  423. },
  424. TelemetryConfig: telemetry.Conf{
  425. BindPort: 0,
  426. BindAddress: "127.0.0.1",
  427. EnableProfiler: false,
  428. AuthUserFile: "",
  429. CertificateFile: "",
  430. CertificateKeyFile: "",
  431. MinTLSVersion: 12,
  432. TLSCipherSuites: nil,
  433. },
  434. SMTPConfig: smtp.Config{
  435. Host: "",
  436. Port: 25,
  437. From: "",
  438. User: "",
  439. Password: "",
  440. AuthType: 0,
  441. Encryption: 0,
  442. Domain: "",
  443. TemplatesPath: "templates",
  444. },
  445. PluginsConfig: nil,
  446. }
  447. viper.SetEnvPrefix(configEnvPrefix)
  448. replacer := strings.NewReplacer(".", "__")
  449. viper.SetEnvKeyReplacer(replacer)
  450. viper.SetConfigName(configName)
  451. setViperDefaults()
  452. viper.AutomaticEnv()
  453. viper.AllowEmptyEnv(true)
  454. }
  455. // GetCommonConfig returns the common protocols configuration
  456. func GetCommonConfig() common.Configuration {
  457. return globalConf.Common
  458. }
  459. // SetCommonConfig sets the common protocols configuration
  460. func SetCommonConfig(config common.Configuration) {
  461. globalConf.Common = config
  462. }
  463. // GetSFTPDConfig returns the configuration for the SFTP server
  464. func GetSFTPDConfig() sftpd.Configuration {
  465. return globalConf.SFTPD
  466. }
  467. // SetSFTPDConfig sets the configuration for the SFTP server
  468. func SetSFTPDConfig(config sftpd.Configuration) {
  469. globalConf.SFTPD = config
  470. }
  471. // GetFTPDConfig returns the configuration for the FTP server
  472. func GetFTPDConfig() ftpd.Configuration {
  473. return globalConf.FTPD
  474. }
  475. // SetFTPDConfig sets the configuration for the FTP server
  476. func SetFTPDConfig(config ftpd.Configuration) {
  477. globalConf.FTPD = config
  478. }
  479. // GetWebDAVDConfig returns the configuration for the WebDAV server
  480. func GetWebDAVDConfig() webdavd.Configuration {
  481. return globalConf.WebDAVD
  482. }
  483. // SetWebDAVDConfig sets the configuration for the WebDAV server
  484. func SetWebDAVDConfig(config webdavd.Configuration) {
  485. globalConf.WebDAVD = config
  486. }
  487. // GetHTTPDConfig returns the configuration for the HTTP server
  488. func GetHTTPDConfig() httpd.Conf {
  489. return globalConf.HTTPDConfig
  490. }
  491. // SetHTTPDConfig sets the configuration for the HTTP server
  492. func SetHTTPDConfig(config httpd.Conf) {
  493. globalConf.HTTPDConfig = config
  494. }
  495. // GetProviderConf returns the configuration for the data provider
  496. func GetProviderConf() dataprovider.Config {
  497. return globalConf.ProviderConf
  498. }
  499. // SetProviderConf sets the configuration for the data provider
  500. func SetProviderConf(config dataprovider.Config) {
  501. globalConf.ProviderConf = config
  502. }
  503. // GetHTTPConfig returns the configuration for HTTP clients
  504. func GetHTTPConfig() httpclient.Config {
  505. return globalConf.HTTPConfig
  506. }
  507. // GetCommandConfig returns the configuration for external commands
  508. func GetCommandConfig() command.Config {
  509. return globalConf.CommandConfig
  510. }
  511. // GetKMSConfig returns the KMS configuration
  512. func GetKMSConfig() kms.Configuration {
  513. return globalConf.KMSConfig
  514. }
  515. // SetKMSConfig sets the kms configuration
  516. func SetKMSConfig(config kms.Configuration) {
  517. globalConf.KMSConfig = config
  518. }
  519. // GetTelemetryConfig returns the telemetry configuration
  520. func GetTelemetryConfig() telemetry.Conf {
  521. return globalConf.TelemetryConfig
  522. }
  523. // SetTelemetryConfig sets the telemetry configuration
  524. func SetTelemetryConfig(config telemetry.Conf) {
  525. globalConf.TelemetryConfig = config
  526. }
  527. // GetPluginsConfig returns the plugins configuration
  528. func GetPluginsConfig() []plugin.Config {
  529. return globalConf.PluginsConfig
  530. }
  531. // SetPluginsConfig sets the plugin configuration
  532. func SetPluginsConfig(config []plugin.Config) {
  533. globalConf.PluginsConfig = config
  534. }
  535. // GetMFAConfig returns multi-factor authentication config
  536. func GetMFAConfig() mfa.Config {
  537. return globalConf.MFAConfig
  538. }
  539. // GetSMTPConfig returns the SMTP configuration
  540. func GetSMTPConfig() smtp.Config {
  541. return globalConf.SMTPConfig
  542. }
  543. // GetACMEConfig returns the ACME configuration
  544. func GetACMEConfig() acme.Configuration {
  545. return globalConf.ACME
  546. }
  547. // HasServicesToStart returns true if the config defines at least a service to start.
  548. // Supported services are SFTP, FTP and WebDAV
  549. func HasServicesToStart() bool {
  550. if globalConf.SFTPD.ShouldBind() {
  551. return true
  552. }
  553. if globalConf.FTPD.ShouldBind() {
  554. return true
  555. }
  556. if globalConf.WebDAVD.ShouldBind() {
  557. return true
  558. }
  559. return false
  560. }
  561. func getRedactedPassword(value string) string {
  562. if value == "" {
  563. return value
  564. }
  565. return "[redacted]"
  566. }
  567. func getRedactedGlobalConf() globalConfig {
  568. conf := globalConf
  569. conf.Common.Actions.Hook = util.GetRedactedURL(conf.Common.Actions.Hook)
  570. conf.Common.StartupHook = util.GetRedactedURL(conf.Common.StartupHook)
  571. conf.Common.PostConnectHook = util.GetRedactedURL(conf.Common.PostConnectHook)
  572. conf.Common.PostDisconnectHook = util.GetRedactedURL(conf.Common.PostDisconnectHook)
  573. conf.Common.DataRetentionHook = util.GetRedactedURL(conf.Common.DataRetentionHook)
  574. conf.SFTPD.KeyboardInteractiveHook = util.GetRedactedURL(conf.SFTPD.KeyboardInteractiveHook)
  575. conf.HTTPDConfig.SigningPassphrase = getRedactedPassword(conf.HTTPDConfig.SigningPassphrase)
  576. conf.HTTPDConfig.Setup.InstallationCode = getRedactedPassword(conf.HTTPDConfig.Setup.InstallationCode)
  577. conf.ProviderConf.Password = getRedactedPassword(conf.ProviderConf.Password)
  578. conf.ProviderConf.Actions.Hook = util.GetRedactedURL(conf.ProviderConf.Actions.Hook)
  579. conf.ProviderConf.ExternalAuthHook = util.GetRedactedURL(conf.ProviderConf.ExternalAuthHook)
  580. conf.ProviderConf.PreLoginHook = util.GetRedactedURL(conf.ProviderConf.PreLoginHook)
  581. conf.ProviderConf.PostLoginHook = util.GetRedactedURL(conf.ProviderConf.PostLoginHook)
  582. conf.ProviderConf.CheckPasswordHook = util.GetRedactedURL(conf.ProviderConf.CheckPasswordHook)
  583. conf.SMTPConfig.Password = getRedactedPassword(conf.SMTPConfig.Password)
  584. conf.HTTPDConfig.Bindings = nil
  585. for _, binding := range globalConf.HTTPDConfig.Bindings {
  586. binding.OIDC.ClientID = getRedactedPassword(binding.OIDC.ClientID)
  587. binding.OIDC.ClientSecret = getRedactedPassword(binding.OIDC.ClientSecret)
  588. conf.HTTPDConfig.Bindings = append(conf.HTTPDConfig.Bindings, binding)
  589. }
  590. return conf
  591. }
  592. func setConfigFile(configDir, configFile string) {
  593. if configFile == "" {
  594. return
  595. }
  596. if !filepath.IsAbs(configFile) && util.IsFileInputValid(configFile) {
  597. configFile = filepath.Join(configDir, configFile)
  598. }
  599. viper.SetConfigFile(configFile)
  600. }
  601. // readEnvFiles reads files inside the "env.d" directory relative to configDir
  602. // and then export the valid variables into environment variables if they do
  603. // not exist
  604. func readEnvFiles(configDir string) {
  605. envd := filepath.Join(configDir, "env.d")
  606. entries, err := os.ReadDir(envd)
  607. if err != nil {
  608. logger.Info(logSender, "", "unable to read env files from %q: %v", envd, err)
  609. return
  610. }
  611. for _, entry := range entries {
  612. info, err := entry.Info()
  613. if err == nil && info.Mode().IsRegular() {
  614. envFile := filepath.Join(envd, entry.Name())
  615. err = gotenv.Load(envFile)
  616. if err != nil {
  617. logger.Error(logSender, "", "unable to load env vars from file %q, err: %v", envFile, err)
  618. } else {
  619. logger.Info(logSender, "", "set env vars from file %q", envFile)
  620. }
  621. }
  622. }
  623. }
  624. func checkOverrideDefaultSettings() {
  625. // for slices we need to set the defaults to nil if the key is set in the config file,
  626. // otherwise the values are merged and not replaced as expected
  627. rateLimiters := viper.Get("common.rate_limiters")
  628. if val, ok := rateLimiters.([]any); ok {
  629. if len(val) > 0 {
  630. if rl, ok := val[0].(map[string]any); ok {
  631. if _, ok := rl["protocols"]; ok {
  632. globalConf.Common.RateLimitersConfig[0].Protocols = nil
  633. }
  634. }
  635. }
  636. }
  637. httpdBindings := viper.Get("httpd.bindings")
  638. if val, ok := httpdBindings.([]any); ok {
  639. if len(val) > 0 {
  640. if binding, ok := val[0].(map[string]any); ok {
  641. if val, ok := binding["oidc"]; ok {
  642. if oidc, ok := val.(map[string]any); ok {
  643. if _, ok := oidc["scopes"]; ok {
  644. globalConf.HTTPDConfig.Bindings[0].OIDC.Scopes = nil
  645. }
  646. }
  647. }
  648. }
  649. }
  650. }
  651. if util.Contains(viper.AllKeys(), "mfa.totp") {
  652. globalConf.MFAConfig.TOTP = nil
  653. }
  654. }
  655. // LoadConfig loads the configuration
  656. // configDir will be added to the configuration search paths.
  657. // The search path contains by default the current directory and on linux it contains
  658. // $HOME/.config/sftpgo and /etc/sftpgo too.
  659. // configFile is an absolute or relative path (to the config dir) to the configuration file.
  660. func LoadConfig(configDir, configFile string) error {
  661. var err error
  662. readEnvFiles(configDir)
  663. viper.AddConfigPath(configDir)
  664. setViperAdditionalConfigPaths()
  665. viper.AddConfigPath(".")
  666. setConfigFile(configDir, configFile)
  667. if err = viper.ReadInConfig(); err != nil {
  668. // if the user specify a configuration file we get os.ErrNotExist.
  669. // viper.ConfigFileNotFoundError is returned if viper is unable
  670. // to find sftpgo.{json,yaml, etc..} in any of the search paths
  671. if errors.As(err, &viper.ConfigFileNotFoundError{}) {
  672. logger.Debug(logSender, "", "no configuration file found")
  673. } else {
  674. // should we return the error and not start here?
  675. logger.Warn(logSender, "", "error loading configuration file: %v", err)
  676. logger.WarnToConsole("error loading configuration file: %v", err)
  677. }
  678. }
  679. checkOverrideDefaultSettings()
  680. err = viper.Unmarshal(&globalConf)
  681. if err != nil {
  682. logger.Warn(logSender, "", "error parsing configuration file: %v", err)
  683. logger.WarnToConsole("error parsing configuration file: %v", err)
  684. return err
  685. }
  686. // viper only supports slice of strings from env vars, so we use our custom method
  687. loadBindingsFromEnv()
  688. resetInvalidConfigs()
  689. logger.Debug(logSender, "", "config file used: '%#v', config loaded: %+v", viper.ConfigFileUsed(), getRedactedGlobalConf())
  690. return nil
  691. }
  692. func isUploadModeValid() bool {
  693. return globalConf.Common.UploadMode >= 0 && globalConf.Common.UploadMode <= 2
  694. }
  695. func isProxyProtocolValid() bool {
  696. return globalConf.Common.ProxyProtocol >= 0 && globalConf.Common.ProxyProtocol <= 2
  697. }
  698. func isExternalAuthScopeValid() bool {
  699. return globalConf.ProviderConf.ExternalAuthScope >= 0 && globalConf.ProviderConf.ExternalAuthScope <= 15
  700. }
  701. func resetInvalidConfigs() {
  702. if strings.TrimSpace(globalConf.SFTPD.Banner) == "" {
  703. globalConf.SFTPD.Banner = defaultSFTPDBanner
  704. }
  705. if strings.TrimSpace(globalConf.FTPD.Banner) == "" {
  706. globalConf.FTPD.Banner = defaultFTPDBanner
  707. }
  708. if strings.TrimSpace(globalConf.HTTPDConfig.Setup.InstallationCodeHint) == "" {
  709. globalConf.HTTPDConfig.Setup.InstallationCodeHint = defaultInstallCodeHint
  710. }
  711. if globalConf.ProviderConf.UsersBaseDir != "" && !util.IsFileInputValid(globalConf.ProviderConf.UsersBaseDir) {
  712. warn := fmt.Sprintf("invalid users base dir %#v will be ignored", globalConf.ProviderConf.UsersBaseDir)
  713. globalConf.ProviderConf.UsersBaseDir = ""
  714. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  715. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  716. }
  717. if !isUploadModeValid() {
  718. warn := fmt.Sprintf("invalid upload_mode 0, 1 and 2 are supported, configured: %v reset upload_mode to 0",
  719. globalConf.Common.UploadMode)
  720. globalConf.Common.UploadMode = 0
  721. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  722. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  723. }
  724. if !isProxyProtocolValid() {
  725. warn := fmt.Sprintf("invalid proxy_protocol 0, 1 and 2 are supported, configured: %v reset proxy_protocol to 0",
  726. globalConf.Common.ProxyProtocol)
  727. globalConf.Common.ProxyProtocol = 0
  728. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  729. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  730. }
  731. if !isExternalAuthScopeValid() {
  732. warn := fmt.Sprintf("invalid external_auth_scope: %v reset to 0", globalConf.ProviderConf.ExternalAuthScope)
  733. globalConf.ProviderConf.ExternalAuthScope = 0
  734. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  735. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  736. }
  737. if globalConf.Common.DefenderConfig.Enabled && globalConf.Common.DefenderConfig.Driver == common.DefenderDriverProvider {
  738. if !globalConf.ProviderConf.IsDefenderSupported() {
  739. warn := fmt.Sprintf("provider based defender is not supported with data provider %#v, "+
  740. "the memory defender implementation will be used. If you want to use the provider defender "+
  741. "implementation please switch to a shared/distributed data provider",
  742. globalConf.ProviderConf.Driver)
  743. globalConf.Common.DefenderConfig.Driver = common.DefenderDriverMemory
  744. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  745. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  746. }
  747. }
  748. }
  749. func loadBindingsFromEnv() {
  750. for idx := 0; idx < 10; idx++ {
  751. getTOTPFromEnv(idx)
  752. getRateLimitersFromEnv(idx)
  753. getPluginsFromEnv(idx)
  754. getSFTPDBindindFromEnv(idx)
  755. getFTPDBindingFromEnv(idx)
  756. getWebDAVDBindingFromEnv(idx)
  757. getHTTPDBindingFromEnv(idx)
  758. getHTTPClientCertificatesFromEnv(idx)
  759. getHTTPClientHeadersFromEnv(idx)
  760. getCommandConfigsFromEnv(idx)
  761. }
  762. }
  763. func getTOTPFromEnv(idx int) {
  764. totpConfig := defaultTOTP
  765. if len(globalConf.MFAConfig.TOTP) > idx {
  766. totpConfig = globalConf.MFAConfig.TOTP[idx]
  767. }
  768. isSet := false
  769. name, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_MFA__TOTP__%v__NAME", idx))
  770. if ok {
  771. totpConfig.Name = name
  772. isSet = true
  773. }
  774. issuer, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_MFA__TOTP__%v__ISSUER", idx))
  775. if ok {
  776. totpConfig.Issuer = issuer
  777. isSet = true
  778. }
  779. algo, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_MFA__TOTP__%v__ALGO", idx))
  780. if ok {
  781. totpConfig.Algo = algo
  782. isSet = true
  783. }
  784. if isSet {
  785. if len(globalConf.MFAConfig.TOTP) > idx {
  786. globalConf.MFAConfig.TOTP[idx] = totpConfig
  787. } else {
  788. globalConf.MFAConfig.TOTP = append(globalConf.MFAConfig.TOTP, totpConfig)
  789. }
  790. }
  791. }
  792. func getRateLimitersFromEnv(idx int) {
  793. rtlConfig := defaultRateLimiter
  794. if len(globalConf.Common.RateLimitersConfig) > idx {
  795. rtlConfig = globalConf.Common.RateLimitersConfig[idx]
  796. }
  797. isSet := false
  798. average, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__AVERAGE", idx))
  799. if ok {
  800. rtlConfig.Average = average
  801. isSet = true
  802. }
  803. period, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__PERIOD", idx))
  804. if ok {
  805. rtlConfig.Period = period
  806. isSet = true
  807. }
  808. burst, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__BURST", idx))
  809. if ok {
  810. rtlConfig.Burst = int(burst)
  811. isSet = true
  812. }
  813. rtlType, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__TYPE", idx))
  814. if ok {
  815. rtlConfig.Type = int(rtlType)
  816. isSet = true
  817. }
  818. protocols, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__PROTOCOLS", idx))
  819. if ok {
  820. rtlConfig.Protocols = protocols
  821. isSet = true
  822. }
  823. allowList, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__ALLOW_LIST", idx))
  824. if ok {
  825. rtlConfig.AllowList = allowList
  826. isSet = true
  827. }
  828. generateEvents, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__GENERATE_DEFENDER_EVENTS", idx))
  829. if ok {
  830. rtlConfig.GenerateDefenderEvents = generateEvents
  831. isSet = true
  832. }
  833. softLimit, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__ENTRIES_SOFT_LIMIT", idx))
  834. if ok {
  835. rtlConfig.EntriesSoftLimit = int(softLimit)
  836. isSet = true
  837. }
  838. hardLimit, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__ENTRIES_HARD_LIMIT", idx))
  839. if ok {
  840. rtlConfig.EntriesHardLimit = int(hardLimit)
  841. isSet = true
  842. }
  843. if isSet {
  844. if len(globalConf.Common.RateLimitersConfig) > idx {
  845. globalConf.Common.RateLimitersConfig[idx] = rtlConfig
  846. } else {
  847. globalConf.Common.RateLimitersConfig = append(globalConf.Common.RateLimitersConfig, rtlConfig)
  848. }
  849. }
  850. }
  851. func getKMSPluginFromEnv(idx int, pluginConfig *plugin.Config) bool {
  852. isSet := false
  853. kmsScheme, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__KMS_OPTIONS__SCHEME", idx))
  854. if ok {
  855. pluginConfig.KMSOptions.Scheme = kmsScheme
  856. isSet = true
  857. }
  858. kmsEncStatus, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__KMS_OPTIONS__ENCRYPTED_STATUS", idx))
  859. if ok {
  860. pluginConfig.KMSOptions.EncryptedStatus = kmsEncStatus
  861. isSet = true
  862. }
  863. return isSet
  864. }
  865. func getAuthPluginFromEnv(idx int, pluginConfig *plugin.Config) bool {
  866. isSet := false
  867. authScope, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__AUTH_OPTIONS__SCOPE", idx))
  868. if ok {
  869. pluginConfig.AuthOptions.Scope = int(authScope)
  870. isSet = true
  871. }
  872. return isSet
  873. }
  874. func getNotifierPluginFromEnv(idx int, pluginConfig *plugin.Config) bool {
  875. isSet := false
  876. notifierFsEvents, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__FS_EVENTS", idx))
  877. if ok {
  878. pluginConfig.NotifierOptions.FsEvents = notifierFsEvents
  879. isSet = true
  880. }
  881. notifierProviderEvents, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__PROVIDER_EVENTS", idx))
  882. if ok {
  883. pluginConfig.NotifierOptions.ProviderEvents = notifierProviderEvents
  884. isSet = true
  885. }
  886. notifierProviderObjects, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__PROVIDER_OBJECTS", idx))
  887. if ok {
  888. pluginConfig.NotifierOptions.ProviderObjects = notifierProviderObjects
  889. isSet = true
  890. }
  891. notifierRetryMaxTime, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__RETRY_MAX_TIME", idx))
  892. if ok {
  893. pluginConfig.NotifierOptions.RetryMaxTime = int(notifierRetryMaxTime)
  894. isSet = true
  895. }
  896. notifierRetryQueueMaxSize, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__RETRY_QUEUE_MAX_SIZE", idx))
  897. if ok {
  898. pluginConfig.NotifierOptions.RetryQueueMaxSize = int(notifierRetryQueueMaxSize)
  899. isSet = true
  900. }
  901. return isSet
  902. }
  903. func getPluginsFromEnv(idx int) {
  904. pluginConfig := plugin.Config{}
  905. if len(globalConf.PluginsConfig) > idx {
  906. pluginConfig = globalConf.PluginsConfig[idx]
  907. }
  908. isSet := false
  909. pluginType, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__TYPE", idx))
  910. if ok {
  911. pluginConfig.Type = pluginType
  912. isSet = true
  913. }
  914. if getNotifierPluginFromEnv(idx, &pluginConfig) {
  915. isSet = true
  916. }
  917. if getKMSPluginFromEnv(idx, &pluginConfig) {
  918. isSet = true
  919. }
  920. if getAuthPluginFromEnv(idx, &pluginConfig) {
  921. isSet = true
  922. }
  923. cmd, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__CMD", idx))
  924. if ok {
  925. pluginConfig.Cmd = cmd
  926. isSet = true
  927. }
  928. cmdArgs, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__ARGS", idx))
  929. if ok {
  930. pluginConfig.Args = cmdArgs
  931. isSet = true
  932. }
  933. pluginHash, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__SHA256SUM", idx))
  934. if ok {
  935. pluginConfig.SHA256Sum = pluginHash
  936. isSet = true
  937. }
  938. autoMTLS, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__AUTO_MTLS", idx))
  939. if ok {
  940. pluginConfig.AutoMTLS = autoMTLS
  941. isSet = true
  942. }
  943. if isSet {
  944. if len(globalConf.PluginsConfig) > idx {
  945. globalConf.PluginsConfig[idx] = pluginConfig
  946. } else {
  947. globalConf.PluginsConfig = append(globalConf.PluginsConfig, pluginConfig)
  948. }
  949. }
  950. }
  951. func getSFTPDBindindFromEnv(idx int) {
  952. binding := defaultSFTPDBinding
  953. if len(globalConf.SFTPD.Bindings) > idx {
  954. binding = globalConf.SFTPD.Bindings[idx]
  955. }
  956. isSet := false
  957. port, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_SFTPD__BINDINGS__%v__PORT", idx))
  958. if ok {
  959. binding.Port = int(port)
  960. isSet = true
  961. }
  962. address, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_SFTPD__BINDINGS__%v__ADDRESS", idx))
  963. if ok {
  964. binding.Address = address
  965. isSet = true
  966. }
  967. applyProxyConfig, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_SFTPD__BINDINGS__%v__APPLY_PROXY_CONFIG", idx))
  968. if ok {
  969. binding.ApplyProxyConfig = applyProxyConfig
  970. isSet = true
  971. }
  972. if isSet {
  973. if len(globalConf.SFTPD.Bindings) > idx {
  974. globalConf.SFTPD.Bindings[idx] = binding
  975. } else {
  976. globalConf.SFTPD.Bindings = append(globalConf.SFTPD.Bindings, binding)
  977. }
  978. }
  979. }
  980. func getFTPDPassiveIPOverridesFromEnv(idx int) []ftpd.PassiveIPOverride {
  981. var overrides []ftpd.PassiveIPOverride
  982. if len(globalConf.FTPD.Bindings) > idx {
  983. overrides = globalConf.FTPD.Bindings[idx].PassiveIPOverrides
  984. }
  985. for subIdx := 0; subIdx < 10; subIdx++ {
  986. var override ftpd.PassiveIPOverride
  987. var replace bool
  988. if len(globalConf.FTPD.Bindings) > idx && len(globalConf.FTPD.Bindings[idx].PassiveIPOverrides) > subIdx {
  989. override = globalConf.FTPD.Bindings[idx].PassiveIPOverrides[subIdx]
  990. replace = true
  991. }
  992. ip, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__PASSIVE_IP_OVERRIDES__%v__IP", idx, subIdx))
  993. if ok {
  994. override.IP = ip
  995. }
  996. networks, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__PASSIVE_IP_OVERRIDES__%v__NETWORKS",
  997. idx, subIdx))
  998. if ok {
  999. override.Networks = networks
  1000. }
  1001. if len(override.Networks) > 0 {
  1002. if replace {
  1003. overrides[subIdx] = override
  1004. } else {
  1005. overrides = append(overrides, override)
  1006. }
  1007. }
  1008. }
  1009. return overrides
  1010. }
  1011. func getDefaultFTPDBinding(idx int) ftpd.Binding {
  1012. binding := defaultFTPDBinding
  1013. if len(globalConf.FTPD.Bindings) > idx {
  1014. binding = globalConf.FTPD.Bindings[idx]
  1015. }
  1016. return binding
  1017. }
  1018. func getFTPDBindingFromEnv(idx int) {
  1019. binding := getDefaultFTPDBinding(idx)
  1020. isSet := false
  1021. port, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__PORT", idx))
  1022. if ok {
  1023. binding.Port = int(port)
  1024. isSet = true
  1025. }
  1026. address, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__ADDRESS", idx))
  1027. if ok {
  1028. binding.Address = address
  1029. isSet = true
  1030. }
  1031. applyProxyConfig, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__APPLY_PROXY_CONFIG", idx))
  1032. if ok {
  1033. binding.ApplyProxyConfig = applyProxyConfig
  1034. isSet = true
  1035. }
  1036. certificateFile, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__CERTIFICATE_FILE", idx))
  1037. if ok {
  1038. binding.CertificateFile = certificateFile
  1039. isSet = true
  1040. }
  1041. certificateKeyFile, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__CERTIFICATE_KEY_FILE", idx))
  1042. if ok {
  1043. binding.CertificateKeyFile = certificateKeyFile
  1044. isSet = true
  1045. }
  1046. tlsMode, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__TLS_MODE", idx))
  1047. if ok {
  1048. binding.TLSMode = int(tlsMode)
  1049. isSet = true
  1050. }
  1051. tlsVer, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__MIN_TLS_VERSION", idx))
  1052. if ok {
  1053. binding.MinTLSVersion = int(tlsVer)
  1054. isSet = true
  1055. }
  1056. passiveIP, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__FORCE_PASSIVE_IP", idx))
  1057. if ok {
  1058. binding.ForcePassiveIP = passiveIP
  1059. isSet = true
  1060. }
  1061. passiveIPOverrides := getFTPDPassiveIPOverridesFromEnv(idx)
  1062. if len(passiveIPOverrides) > 0 {
  1063. binding.PassiveIPOverrides = passiveIPOverrides
  1064. isSet = true
  1065. }
  1066. clientAuthType, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__CLIENT_AUTH_TYPE", idx))
  1067. if ok {
  1068. binding.ClientAuthType = int(clientAuthType)
  1069. isSet = true
  1070. }
  1071. tlsCiphers, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__TLS_CIPHER_SUITES", idx))
  1072. if ok {
  1073. binding.TLSCipherSuites = tlsCiphers
  1074. isSet = true
  1075. }
  1076. pasvSecurity, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__PASSIVE_CONNECTIONS_SECURITY", idx))
  1077. if ok {
  1078. binding.PassiveConnectionsSecurity = int(pasvSecurity)
  1079. isSet = true
  1080. }
  1081. activeSecurity, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__ACTIVE_CONNECTIONS_SECURITY", idx))
  1082. if ok {
  1083. binding.ActiveConnectionsSecurity = int(activeSecurity)
  1084. isSet = true
  1085. }
  1086. debug, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__DEBUG", idx))
  1087. if ok {
  1088. binding.Debug = debug
  1089. isSet = true
  1090. }
  1091. applyFTPDBindingFromEnv(idx, isSet, binding)
  1092. }
  1093. func applyFTPDBindingFromEnv(idx int, isSet bool, binding ftpd.Binding) {
  1094. if isSet {
  1095. if len(globalConf.FTPD.Bindings) > idx {
  1096. globalConf.FTPD.Bindings[idx] = binding
  1097. } else {
  1098. globalConf.FTPD.Bindings = append(globalConf.FTPD.Bindings, binding)
  1099. }
  1100. }
  1101. }
  1102. func getWebDAVDBindingProxyConfigsFromEnv(idx int, binding *webdavd.Binding) bool {
  1103. isSet := false
  1104. proxyAllowed, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__PROXY_ALLOWED", idx))
  1105. if ok {
  1106. binding.ProxyAllowed = proxyAllowed
  1107. isSet = true
  1108. }
  1109. clientIPProxyHeader, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__CLIENT_IP_PROXY_HEADER", idx))
  1110. if ok {
  1111. binding.ClientIPProxyHeader = clientIPProxyHeader
  1112. isSet = true
  1113. }
  1114. clientIPHeaderDepth, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__CLIENT_IP_HEADER_DEPTH", idx))
  1115. if ok {
  1116. binding.ClientIPHeaderDepth = int(clientIPHeaderDepth)
  1117. isSet = true
  1118. }
  1119. return isSet
  1120. }
  1121. func getWebDAVDBindingFromEnv(idx int) {
  1122. binding := defaultWebDAVDBinding
  1123. if len(globalConf.WebDAVD.Bindings) > idx {
  1124. binding = globalConf.WebDAVD.Bindings[idx]
  1125. }
  1126. isSet := false
  1127. port, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__PORT", idx))
  1128. if ok {
  1129. binding.Port = int(port)
  1130. isSet = true
  1131. }
  1132. address, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__ADDRESS", idx))
  1133. if ok {
  1134. binding.Address = address
  1135. isSet = true
  1136. }
  1137. enableHTTPS, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__ENABLE_HTTPS", idx))
  1138. if ok {
  1139. binding.EnableHTTPS = enableHTTPS
  1140. isSet = true
  1141. }
  1142. certificateFile, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__CERTIFICATE_FILE", idx))
  1143. if ok {
  1144. binding.CertificateFile = certificateFile
  1145. isSet = true
  1146. }
  1147. certificateKeyFile, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__CERTIFICATE_KEY_FILE", idx))
  1148. if ok {
  1149. binding.CertificateKeyFile = certificateKeyFile
  1150. isSet = true
  1151. }
  1152. tlsVer, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__MIN_TLS_VERSION", idx))
  1153. if ok {
  1154. binding.MinTLSVersion = int(tlsVer)
  1155. isSet = true
  1156. }
  1157. clientAuthType, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__CLIENT_AUTH_TYPE", idx))
  1158. if ok {
  1159. binding.ClientAuthType = int(clientAuthType)
  1160. isSet = true
  1161. }
  1162. tlsCiphers, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__TLS_CIPHER_SUITES", idx))
  1163. if ok {
  1164. binding.TLSCipherSuites = tlsCiphers
  1165. isSet = true
  1166. }
  1167. prefix, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__PREFIX", idx))
  1168. if ok {
  1169. binding.Prefix = prefix
  1170. isSet = true
  1171. }
  1172. if getWebDAVDBindingProxyConfigsFromEnv(idx, &binding) {
  1173. isSet = true
  1174. }
  1175. disableWWWAuth, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__DISABLE_WWW_AUTH_HEADER", idx))
  1176. if ok {
  1177. binding.DisableWWWAuthHeader = disableWWWAuth
  1178. isSet = true
  1179. }
  1180. if isSet {
  1181. if len(globalConf.WebDAVD.Bindings) > idx {
  1182. globalConf.WebDAVD.Bindings[idx] = binding
  1183. } else {
  1184. globalConf.WebDAVD.Bindings = append(globalConf.WebDAVD.Bindings, binding)
  1185. }
  1186. }
  1187. }
  1188. func getHTTPDSecurityProxyHeadersFromEnv(idx int) []httpd.HTTPSProxyHeader {
  1189. var httpsProxyHeaders []httpd.HTTPSProxyHeader
  1190. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1191. httpsProxyHeaders = globalConf.HTTPDConfig.Bindings[idx].Security.HTTPSProxyHeaders
  1192. }
  1193. for subIdx := 0; subIdx < 10; subIdx++ {
  1194. var httpsProxyHeader httpd.HTTPSProxyHeader
  1195. var replace bool
  1196. if len(globalConf.HTTPDConfig.Bindings) > idx &&
  1197. len(globalConf.HTTPDConfig.Bindings[idx].Security.HTTPSProxyHeaders) > subIdx {
  1198. httpsProxyHeader = httpsProxyHeaders[subIdx]
  1199. replace = true
  1200. }
  1201. proxyKey, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__HTTPS_PROXY_HEADERS__%v__KEY",
  1202. idx, subIdx))
  1203. if ok {
  1204. httpsProxyHeader.Key = proxyKey
  1205. }
  1206. proxyVal, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__HTTPS_PROXY_HEADERS__%v__VALUE",
  1207. idx, subIdx))
  1208. if ok {
  1209. httpsProxyHeader.Value = proxyVal
  1210. }
  1211. if httpsProxyHeader.Key != "" && httpsProxyHeader.Value != "" {
  1212. if replace {
  1213. httpsProxyHeaders[subIdx] = httpsProxyHeader
  1214. } else {
  1215. httpsProxyHeaders = append(httpsProxyHeaders, httpsProxyHeader)
  1216. }
  1217. }
  1218. }
  1219. return httpsProxyHeaders
  1220. }
  1221. func getHTTPDSecurityConfFromEnv(idx int) (httpd.SecurityConf, bool) { //nolint:gocyclo
  1222. result := defaultHTTPDBinding.Security
  1223. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1224. result = globalConf.HTTPDConfig.Bindings[idx].Security
  1225. }
  1226. isSet := false
  1227. enabled, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__ENABLED", idx))
  1228. if ok {
  1229. result.Enabled = enabled
  1230. isSet = true
  1231. }
  1232. allowedHosts, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__ALLOWED_HOSTS", idx))
  1233. if ok {
  1234. result.AllowedHosts = allowedHosts
  1235. isSet = true
  1236. }
  1237. allowedHostsAreRegex, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__ALLOWED_HOSTS_ARE_REGEX", idx))
  1238. if ok {
  1239. result.AllowedHostsAreRegex = allowedHostsAreRegex
  1240. isSet = true
  1241. }
  1242. hostsProxyHeaders, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__HOSTS_PROXY_HEADERS", idx))
  1243. if ok {
  1244. result.HostsProxyHeaders = hostsProxyHeaders
  1245. isSet = true
  1246. }
  1247. httpsRedirect, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__HTTPS_REDIRECT", idx))
  1248. if ok {
  1249. result.HTTPSRedirect = httpsRedirect
  1250. isSet = true
  1251. }
  1252. httpsHost, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__HTTPS_HOST", idx))
  1253. if ok {
  1254. result.HTTPSHost = httpsHost
  1255. isSet = true
  1256. }
  1257. httpsProxyHeaders := getHTTPDSecurityProxyHeadersFromEnv(idx)
  1258. if len(httpsProxyHeaders) > 0 {
  1259. result.HTTPSProxyHeaders = httpsProxyHeaders
  1260. isSet = true
  1261. }
  1262. stsSeconds, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__STS_SECONDS", idx))
  1263. if ok {
  1264. result.STSSeconds = stsSeconds
  1265. isSet = true
  1266. }
  1267. stsIncludeSubDomains, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__STS_INCLUDE_SUBDOMAINS", idx))
  1268. if ok {
  1269. result.STSIncludeSubdomains = stsIncludeSubDomains
  1270. isSet = true
  1271. }
  1272. stsPreload, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__STS_PRELOAD", idx))
  1273. if ok {
  1274. result.STSPreload = stsPreload
  1275. isSet = true
  1276. }
  1277. contentTypeNosniff, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__CONTENT_TYPE_NOSNIFF", idx))
  1278. if ok {
  1279. result.ContentTypeNosniff = contentTypeNosniff
  1280. isSet = true
  1281. }
  1282. contentSecurityPolicy, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__CONTENT_SECURITY_POLICY", idx))
  1283. if ok {
  1284. result.ContentSecurityPolicy = contentSecurityPolicy
  1285. isSet = true
  1286. }
  1287. permissionsPolicy, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__PERMISSIONS_POLICY", idx))
  1288. if ok {
  1289. result.PermissionsPolicy = permissionsPolicy
  1290. isSet = true
  1291. }
  1292. crossOriginOpenedPolicy, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__CROSS_ORIGIN_OPENER_POLICY", idx))
  1293. if ok {
  1294. result.CrossOriginOpenerPolicy = crossOriginOpenedPolicy
  1295. isSet = true
  1296. }
  1297. expectCTHeader, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__EXPECT_CT_HEADER", idx))
  1298. if ok {
  1299. result.ExpectCTHeader = expectCTHeader
  1300. isSet = true
  1301. }
  1302. return result, isSet
  1303. }
  1304. func getHTTPDOIDCFromEnv(idx int) (httpd.OIDC, bool) {
  1305. result := defaultHTTPDBinding.OIDC
  1306. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1307. result = globalConf.HTTPDConfig.Bindings[idx].OIDC
  1308. }
  1309. isSet := false
  1310. clientID, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__CLIENT_ID", idx))
  1311. if ok {
  1312. result.ClientID = clientID
  1313. isSet = true
  1314. }
  1315. clientSecret, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__CLIENT_SECRET", idx))
  1316. if ok {
  1317. result.ClientSecret = clientSecret
  1318. isSet = true
  1319. }
  1320. configURL, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__CONFIG_URL", idx))
  1321. if ok {
  1322. result.ConfigURL = configURL
  1323. isSet = true
  1324. }
  1325. redirectBaseURL, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__REDIRECT_BASE_URL", idx))
  1326. if ok {
  1327. result.RedirectBaseURL = redirectBaseURL
  1328. isSet = true
  1329. }
  1330. usernameField, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__USERNAME_FIELD", idx))
  1331. if ok {
  1332. result.UsernameField = usernameField
  1333. isSet = true
  1334. }
  1335. scopes, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__SCOPES", idx))
  1336. if ok {
  1337. result.Scopes = scopes
  1338. isSet = true
  1339. }
  1340. roleField, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__ROLE_FIELD", idx))
  1341. if ok {
  1342. result.RoleField = roleField
  1343. isSet = true
  1344. }
  1345. implicitRoles, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__IMPLICIT_ROLES", idx))
  1346. if ok {
  1347. result.ImplicitRoles = implicitRoles
  1348. isSet = true
  1349. }
  1350. customFields, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__CUSTOM_FIELDS", idx))
  1351. if ok {
  1352. result.CustomFields = customFields
  1353. isSet = true
  1354. }
  1355. skipSignatureCheck, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__INSECURE_SKIP_SIGNATURE_CHECK", idx))
  1356. if ok {
  1357. result.InsecureSkipSignatureCheck = skipSignatureCheck
  1358. isSet = true
  1359. }
  1360. debug, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__DEBUG", idx))
  1361. if ok {
  1362. result.Debug = debug
  1363. isSet = true
  1364. }
  1365. return result, isSet
  1366. }
  1367. func getHTTPDUIBrandingFromEnv(prefix string, branding httpd.UIBranding) (httpd.UIBranding, bool) {
  1368. isSet := false
  1369. name, ok := os.LookupEnv(fmt.Sprintf("%s__NAME", prefix))
  1370. if ok {
  1371. branding.Name = name
  1372. isSet = true
  1373. }
  1374. shortName, ok := os.LookupEnv(fmt.Sprintf("%s__SHORT_NAME", prefix))
  1375. if ok {
  1376. branding.ShortName = shortName
  1377. isSet = true
  1378. }
  1379. faviconPath, ok := os.LookupEnv(fmt.Sprintf("%s__FAVICON_PATH", prefix))
  1380. if ok {
  1381. branding.FaviconPath = faviconPath
  1382. isSet = true
  1383. }
  1384. logoPath, ok := os.LookupEnv(fmt.Sprintf("%s__LOGO_PATH", prefix))
  1385. if ok {
  1386. branding.LogoPath = logoPath
  1387. isSet = true
  1388. }
  1389. loginImagePath, ok := os.LookupEnv(fmt.Sprintf("%s__LOGIN_IMAGE_PATH", prefix))
  1390. if ok {
  1391. branding.LoginImagePath = loginImagePath
  1392. isSet = true
  1393. }
  1394. disclaimerName, ok := os.LookupEnv(fmt.Sprintf("%s__DISCLAIMER_NAME", prefix))
  1395. if ok {
  1396. branding.DisclaimerName = disclaimerName
  1397. isSet = true
  1398. }
  1399. disclaimerPath, ok := os.LookupEnv(fmt.Sprintf("%s__DISCLAIMER_PATH", prefix))
  1400. if ok {
  1401. branding.DisclaimerPath = disclaimerPath
  1402. isSet = true
  1403. }
  1404. defaultCSSPath, ok := os.LookupEnv(fmt.Sprintf("%s__DEFAULT_CSS", prefix))
  1405. if ok {
  1406. branding.DefaultCSS = defaultCSSPath
  1407. isSet = true
  1408. }
  1409. extraCSS, ok := lookupStringListFromEnv(fmt.Sprintf("%s__EXTRA_CSS", prefix))
  1410. if ok {
  1411. branding.ExtraCSS = extraCSS
  1412. isSet = true
  1413. }
  1414. return branding, isSet
  1415. }
  1416. func getHTTPDBrandingFromEnv(idx int) (httpd.Branding, bool) {
  1417. result := defaultHTTPDBinding.Branding
  1418. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1419. result = globalConf.HTTPDConfig.Bindings[idx].Branding
  1420. }
  1421. isSet := false
  1422. webAdmin, ok := getHTTPDUIBrandingFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__BRANDING__WEB_ADMIN", idx),
  1423. result.WebAdmin)
  1424. if ok {
  1425. result.WebAdmin = webAdmin
  1426. isSet = true
  1427. }
  1428. webClient, ok := getHTTPDUIBrandingFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__BRANDING__WEB_CLIENT", idx),
  1429. result.WebClient)
  1430. if ok {
  1431. result.WebClient = webClient
  1432. isSet = true
  1433. }
  1434. return result, isSet
  1435. }
  1436. func getHTTPDWebClientIntegrationsFromEnv(idx int) []httpd.WebClientIntegration {
  1437. var integrations []httpd.WebClientIntegration
  1438. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1439. integrations = globalConf.HTTPDConfig.Bindings[idx].WebClientIntegrations
  1440. }
  1441. for subIdx := 0; subIdx < 10; subIdx++ {
  1442. var integration httpd.WebClientIntegration
  1443. var replace bool
  1444. if len(globalConf.HTTPDConfig.Bindings) > idx &&
  1445. len(globalConf.HTTPDConfig.Bindings[idx].WebClientIntegrations) > subIdx {
  1446. integration = integrations[subIdx]
  1447. replace = true
  1448. }
  1449. url, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__WEB_CLIENT_INTEGRATIONS__%v__URL", idx, subIdx))
  1450. if ok {
  1451. integration.URL = url
  1452. }
  1453. extensions, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__WEB_CLIENT_INTEGRATIONS__%v__FILE_EXTENSIONS",
  1454. idx, subIdx))
  1455. if ok {
  1456. integration.FileExtensions = extensions
  1457. }
  1458. if integration.URL != "" && len(integration.FileExtensions) > 0 {
  1459. if replace {
  1460. integrations[subIdx] = integration
  1461. } else {
  1462. integrations = append(integrations, integration)
  1463. }
  1464. }
  1465. }
  1466. return integrations
  1467. }
  1468. func getDefaultHTTPBinding(idx int) httpd.Binding {
  1469. binding := defaultHTTPDBinding
  1470. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1471. binding = globalConf.HTTPDConfig.Bindings[idx]
  1472. }
  1473. return binding
  1474. }
  1475. func getHTTPDNestedObjectsFromEnv(idx int, binding *httpd.Binding) bool {
  1476. isSet := false
  1477. webClientIntegrations := getHTTPDWebClientIntegrationsFromEnv(idx)
  1478. if len(webClientIntegrations) > 0 {
  1479. binding.WebClientIntegrations = webClientIntegrations
  1480. isSet = true
  1481. }
  1482. oidc, ok := getHTTPDOIDCFromEnv(idx)
  1483. if ok {
  1484. binding.OIDC = oidc
  1485. isSet = true
  1486. }
  1487. securityConf, ok := getHTTPDSecurityConfFromEnv(idx)
  1488. if ok {
  1489. binding.Security = securityConf
  1490. isSet = true
  1491. }
  1492. brandingConf, ok := getHTTPDBrandingFromEnv(idx)
  1493. if ok {
  1494. binding.Branding = brandingConf
  1495. isSet = true
  1496. }
  1497. return isSet
  1498. }
  1499. func getHTTPDBindingProxyConfigsFromEnv(idx int, binding *httpd.Binding) bool {
  1500. isSet := false
  1501. proxyAllowed, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__PROXY_ALLOWED", idx))
  1502. if ok {
  1503. binding.ProxyAllowed = proxyAllowed
  1504. isSet = true
  1505. }
  1506. clientIPProxyHeader, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__CLIENT_IP_PROXY_HEADER", idx))
  1507. if ok {
  1508. binding.ClientIPProxyHeader = clientIPProxyHeader
  1509. isSet = true
  1510. }
  1511. clientIPHeaderDepth, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__CLIENT_IP_HEADER_DEPTH", idx))
  1512. if ok {
  1513. binding.ClientIPHeaderDepth = int(clientIPHeaderDepth)
  1514. isSet = true
  1515. }
  1516. return isSet
  1517. }
  1518. func getHTTPDBindingFromEnv(idx int) { //nolint:gocyclo
  1519. binding := getDefaultHTTPBinding(idx)
  1520. isSet := false
  1521. port, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__PORT", idx))
  1522. if ok {
  1523. binding.Port = int(port)
  1524. isSet = true
  1525. }
  1526. address, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ADDRESS", idx))
  1527. if ok {
  1528. binding.Address = address
  1529. isSet = true
  1530. }
  1531. certificateFile, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__CERTIFICATE_FILE", idx))
  1532. if ok {
  1533. binding.CertificateFile = certificateFile
  1534. isSet = true
  1535. }
  1536. certificateKeyFile, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__CERTIFICATE_KEY_FILE", idx))
  1537. if ok {
  1538. binding.CertificateKeyFile = certificateKeyFile
  1539. isSet = true
  1540. }
  1541. enableWebAdmin, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ENABLE_WEB_ADMIN", idx))
  1542. if ok {
  1543. binding.EnableWebAdmin = enableWebAdmin
  1544. isSet = true
  1545. }
  1546. enableWebClient, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ENABLE_WEB_CLIENT", idx))
  1547. if ok {
  1548. binding.EnableWebClient = enableWebClient
  1549. isSet = true
  1550. }
  1551. enableRESTAPI, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ENABLE_REST_API", idx))
  1552. if ok {
  1553. binding.EnableRESTAPI = enableRESTAPI
  1554. isSet = true
  1555. }
  1556. enabledLoginMethods, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ENABLED_LOGIN_METHODS", idx))
  1557. if ok {
  1558. binding.EnabledLoginMethods = int(enabledLoginMethods)
  1559. isSet = true
  1560. }
  1561. renderOpenAPI, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__RENDER_OPENAPI", idx))
  1562. if ok {
  1563. binding.RenderOpenAPI = renderOpenAPI
  1564. isSet = true
  1565. }
  1566. enableHTTPS, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ENABLE_HTTPS", idx))
  1567. if ok {
  1568. binding.EnableHTTPS = enableHTTPS
  1569. isSet = true
  1570. }
  1571. tlsVer, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__MIN_TLS_VERSION", idx))
  1572. if ok {
  1573. binding.MinTLSVersion = int(tlsVer)
  1574. isSet = true
  1575. }
  1576. clientAuthType, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__CLIENT_AUTH_TYPE", idx))
  1577. if ok {
  1578. binding.ClientAuthType = int(clientAuthType)
  1579. isSet = true
  1580. }
  1581. tlsCiphers, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__TLS_CIPHER_SUITES", idx))
  1582. if ok {
  1583. binding.TLSCipherSuites = tlsCiphers
  1584. isSet = true
  1585. }
  1586. if getHTTPDBindingProxyConfigsFromEnv(idx, &binding) {
  1587. isSet = true
  1588. }
  1589. hideLoginURL, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__HIDE_LOGIN_URL", idx))
  1590. if ok {
  1591. binding.HideLoginURL = int(hideLoginURL)
  1592. isSet = true
  1593. }
  1594. if getHTTPDNestedObjectsFromEnv(idx, &binding) {
  1595. isSet = true
  1596. }
  1597. setHTTPDBinding(isSet, binding, idx)
  1598. }
  1599. func setHTTPDBinding(isSet bool, binding httpd.Binding, idx int) {
  1600. if isSet {
  1601. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1602. globalConf.HTTPDConfig.Bindings[idx] = binding
  1603. } else {
  1604. globalConf.HTTPDConfig.Bindings = append(globalConf.HTTPDConfig.Bindings, binding)
  1605. }
  1606. }
  1607. }
  1608. func getHTTPClientCertificatesFromEnv(idx int) {
  1609. tlsCert := httpclient.TLSKeyPair{}
  1610. if len(globalConf.HTTPConfig.Certificates) > idx {
  1611. tlsCert = globalConf.HTTPConfig.Certificates[idx]
  1612. }
  1613. cert, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTP__CERTIFICATES__%v__CERT", idx))
  1614. if ok {
  1615. tlsCert.Cert = cert
  1616. }
  1617. key, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTP__CERTIFICATES__%v__KEY", idx))
  1618. if ok {
  1619. tlsCert.Key = key
  1620. }
  1621. if tlsCert.Cert != "" && tlsCert.Key != "" {
  1622. if len(globalConf.HTTPConfig.Certificates) > idx {
  1623. globalConf.HTTPConfig.Certificates[idx] = tlsCert
  1624. } else {
  1625. globalConf.HTTPConfig.Certificates = append(globalConf.HTTPConfig.Certificates, tlsCert)
  1626. }
  1627. }
  1628. }
  1629. func getHTTPClientHeadersFromEnv(idx int) {
  1630. header := httpclient.Header{}
  1631. if len(globalConf.HTTPConfig.Headers) > idx {
  1632. header = globalConf.HTTPConfig.Headers[idx]
  1633. }
  1634. key, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTP__HEADERS__%v__KEY", idx))
  1635. if ok {
  1636. header.Key = key
  1637. }
  1638. value, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTP__HEADERS__%v__VALUE", idx))
  1639. if ok {
  1640. header.Value = value
  1641. }
  1642. url, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTP__HEADERS__%v__URL", idx))
  1643. if ok {
  1644. header.URL = url
  1645. }
  1646. if header.Key != "" && header.Value != "" {
  1647. if len(globalConf.HTTPConfig.Headers) > idx {
  1648. globalConf.HTTPConfig.Headers[idx] = header
  1649. } else {
  1650. globalConf.HTTPConfig.Headers = append(globalConf.HTTPConfig.Headers, header)
  1651. }
  1652. }
  1653. }
  1654. func getCommandConfigsFromEnv(idx int) {
  1655. cfg := command.Command{}
  1656. if len(globalConf.CommandConfig.Commands) > idx {
  1657. cfg = globalConf.CommandConfig.Commands[idx]
  1658. }
  1659. path, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_COMMAND__COMMANDS__%v__PATH", idx))
  1660. if ok {
  1661. cfg.Path = path
  1662. }
  1663. timeout, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMAND__COMMANDS__%v__TIMEOUT", idx))
  1664. if ok {
  1665. cfg.Timeout = int(timeout)
  1666. }
  1667. env, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_COMMAND__COMMANDS__%v__ENV", idx))
  1668. if ok {
  1669. cfg.Env = env
  1670. }
  1671. if cfg.Path != "" {
  1672. if len(globalConf.CommandConfig.Commands) > idx {
  1673. globalConf.CommandConfig.Commands[idx] = cfg
  1674. } else {
  1675. globalConf.CommandConfig.Commands = append(globalConf.CommandConfig.Commands, cfg)
  1676. }
  1677. }
  1678. }
  1679. func setViperDefaults() {
  1680. viper.SetDefault("common.idle_timeout", globalConf.Common.IdleTimeout)
  1681. viper.SetDefault("common.upload_mode", globalConf.Common.UploadMode)
  1682. viper.SetDefault("common.actions.execute_on", globalConf.Common.Actions.ExecuteOn)
  1683. viper.SetDefault("common.actions.execute_sync", globalConf.Common.Actions.ExecuteSync)
  1684. viper.SetDefault("common.actions.hook", globalConf.Common.Actions.Hook)
  1685. viper.SetDefault("common.setstat_mode", globalConf.Common.SetstatMode)
  1686. viper.SetDefault("common.temp_path", globalConf.Common.TempPath)
  1687. viper.SetDefault("common.proxy_protocol", globalConf.Common.ProxyProtocol)
  1688. viper.SetDefault("common.proxy_allowed", globalConf.Common.ProxyAllowed)
  1689. viper.SetDefault("common.post_connect_hook", globalConf.Common.PostConnectHook)
  1690. viper.SetDefault("common.post_disconnect_hook", globalConf.Common.PostDisconnectHook)
  1691. viper.SetDefault("common.data_retention_hook", globalConf.Common.DataRetentionHook)
  1692. viper.SetDefault("common.max_total_connections", globalConf.Common.MaxTotalConnections)
  1693. viper.SetDefault("common.max_per_host_connections", globalConf.Common.MaxPerHostConnections)
  1694. viper.SetDefault("common.whitelist_file", globalConf.Common.WhiteListFile)
  1695. viper.SetDefault("common.allow_self_connections", globalConf.Common.AllowSelfConnections)
  1696. viper.SetDefault("common.defender.enabled", globalConf.Common.DefenderConfig.Enabled)
  1697. viper.SetDefault("common.defender.driver", globalConf.Common.DefenderConfig.Driver)
  1698. viper.SetDefault("common.defender.ban_time", globalConf.Common.DefenderConfig.BanTime)
  1699. viper.SetDefault("common.defender.ban_time_increment", globalConf.Common.DefenderConfig.BanTimeIncrement)
  1700. viper.SetDefault("common.defender.threshold", globalConf.Common.DefenderConfig.Threshold)
  1701. viper.SetDefault("common.defender.score_invalid", globalConf.Common.DefenderConfig.ScoreInvalid)
  1702. viper.SetDefault("common.defender.score_valid", globalConf.Common.DefenderConfig.ScoreValid)
  1703. viper.SetDefault("common.defender.score_limit_exceeded", globalConf.Common.DefenderConfig.ScoreLimitExceeded)
  1704. viper.SetDefault("common.defender.observation_time", globalConf.Common.DefenderConfig.ObservationTime)
  1705. viper.SetDefault("common.defender.entries_soft_limit", globalConf.Common.DefenderConfig.EntriesSoftLimit)
  1706. viper.SetDefault("common.defender.entries_hard_limit", globalConf.Common.DefenderConfig.EntriesHardLimit)
  1707. viper.SetDefault("common.defender.safelist_file", globalConf.Common.DefenderConfig.SafeListFile)
  1708. viper.SetDefault("common.defender.blocklist_file", globalConf.Common.DefenderConfig.BlockListFile)
  1709. viper.SetDefault("common.defender.safelist", globalConf.Common.DefenderConfig.SafeList)
  1710. viper.SetDefault("common.defender.blocklist", globalConf.Common.DefenderConfig.BlockList)
  1711. viper.SetDefault("acme.email", globalConf.ACME.Email)
  1712. viper.SetDefault("acme.key_type", globalConf.ACME.KeyType)
  1713. viper.SetDefault("acme.certs_path", globalConf.ACME.CertsPath)
  1714. viper.SetDefault("acme.ca_endpoint", globalConf.ACME.CAEndpoint)
  1715. viper.SetDefault("acme.domains", globalConf.ACME.Domains)
  1716. viper.SetDefault("acme.renew_days", globalConf.ACME.RenewDays)
  1717. viper.SetDefault("acme.http01_challenge.port", globalConf.ACME.HTTP01Challenge.Port)
  1718. viper.SetDefault("acme.http01_challenge.webroot", globalConf.ACME.HTTP01Challenge.WebRoot)
  1719. viper.SetDefault("acme.http01_challenge.proxy_header", globalConf.ACME.HTTP01Challenge.ProxyHeader)
  1720. viper.SetDefault("acme.tls_alpn01_challenge.port", globalConf.ACME.TLSALPN01Challenge.Port)
  1721. viper.SetDefault("sftpd.max_auth_tries", globalConf.SFTPD.MaxAuthTries)
  1722. viper.SetDefault("sftpd.banner", globalConf.SFTPD.Banner)
  1723. viper.SetDefault("sftpd.host_keys", globalConf.SFTPD.HostKeys)
  1724. viper.SetDefault("sftpd.host_certificates", globalConf.SFTPD.HostCertificates)
  1725. viper.SetDefault("sftpd.host_key_algorithms", globalConf.SFTPD.HostKeyAlgorithms)
  1726. viper.SetDefault("sftpd.kex_algorithms", globalConf.SFTPD.KexAlgorithms)
  1727. viper.SetDefault("sftpd.ciphers", globalConf.SFTPD.Ciphers)
  1728. viper.SetDefault("sftpd.macs", globalConf.SFTPD.MACs)
  1729. viper.SetDefault("sftpd.trusted_user_ca_keys", globalConf.SFTPD.TrustedUserCAKeys)
  1730. viper.SetDefault("sftpd.revoked_user_certs_file", globalConf.SFTPD.RevokedUserCertsFile)
  1731. viper.SetDefault("sftpd.login_banner_file", globalConf.SFTPD.LoginBannerFile)
  1732. viper.SetDefault("sftpd.enabled_ssh_commands", sftpd.GetDefaultSSHCommands())
  1733. viper.SetDefault("sftpd.keyboard_interactive_authentication", globalConf.SFTPD.KeyboardInteractiveAuthentication)
  1734. viper.SetDefault("sftpd.keyboard_interactive_auth_hook", globalConf.SFTPD.KeyboardInteractiveHook)
  1735. viper.SetDefault("sftpd.password_authentication", globalConf.SFTPD.PasswordAuthentication)
  1736. viper.SetDefault("sftpd.folder_prefix", globalConf.SFTPD.FolderPrefix)
  1737. viper.SetDefault("ftpd.banner", globalConf.FTPD.Banner)
  1738. viper.SetDefault("ftpd.banner_file", globalConf.FTPD.BannerFile)
  1739. viper.SetDefault("ftpd.active_transfers_port_non_20", globalConf.FTPD.ActiveTransfersPortNon20)
  1740. viper.SetDefault("ftpd.passive_port_range.start", globalConf.FTPD.PassivePortRange.Start)
  1741. viper.SetDefault("ftpd.passive_port_range.end", globalConf.FTPD.PassivePortRange.End)
  1742. viper.SetDefault("ftpd.disable_active_mode", globalConf.FTPD.DisableActiveMode)
  1743. viper.SetDefault("ftpd.enable_site", globalConf.FTPD.EnableSite)
  1744. viper.SetDefault("ftpd.hash_support", globalConf.FTPD.HASHSupport)
  1745. viper.SetDefault("ftpd.combine_support", globalConf.FTPD.CombineSupport)
  1746. viper.SetDefault("ftpd.certificate_file", globalConf.FTPD.CertificateFile)
  1747. viper.SetDefault("ftpd.certificate_key_file", globalConf.FTPD.CertificateKeyFile)
  1748. viper.SetDefault("ftpd.ca_certificates", globalConf.FTPD.CACertificates)
  1749. viper.SetDefault("ftpd.ca_revocation_lists", globalConf.FTPD.CARevocationLists)
  1750. viper.SetDefault("webdavd.certificate_file", globalConf.WebDAVD.CertificateFile)
  1751. viper.SetDefault("webdavd.certificate_key_file", globalConf.WebDAVD.CertificateKeyFile)
  1752. viper.SetDefault("webdavd.ca_certificates", globalConf.WebDAVD.CACertificates)
  1753. viper.SetDefault("webdavd.ca_revocation_lists", globalConf.WebDAVD.CARevocationLists)
  1754. viper.SetDefault("webdavd.cors.enabled", globalConf.WebDAVD.Cors.Enabled)
  1755. viper.SetDefault("webdavd.cors.allowed_origins", globalConf.WebDAVD.Cors.AllowedOrigins)
  1756. viper.SetDefault("webdavd.cors.allowed_methods", globalConf.WebDAVD.Cors.AllowedMethods)
  1757. viper.SetDefault("webdavd.cors.allowed_headers", globalConf.WebDAVD.Cors.AllowedHeaders)
  1758. viper.SetDefault("webdavd.cors.exposed_headers", globalConf.WebDAVD.Cors.ExposedHeaders)
  1759. viper.SetDefault("webdavd.cors.allow_credentials", globalConf.WebDAVD.Cors.AllowCredentials)
  1760. viper.SetDefault("webdavd.cors.options_passthrough", globalConf.WebDAVD.Cors.OptionsPassthrough)
  1761. viper.SetDefault("webdavd.cors.options_success_status", globalConf.WebDAVD.Cors.OptionsSuccessStatus)
  1762. viper.SetDefault("webdavd.cors.allow_private_network", globalConf.WebDAVD.Cors.AllowPrivateNetwork)
  1763. viper.SetDefault("webdavd.cors.max_age", globalConf.WebDAVD.Cors.MaxAge)
  1764. viper.SetDefault("webdavd.cache.users.expiration_time", globalConf.WebDAVD.Cache.Users.ExpirationTime)
  1765. viper.SetDefault("webdavd.cache.users.max_size", globalConf.WebDAVD.Cache.Users.MaxSize)
  1766. viper.SetDefault("webdavd.cache.mime_types.enabled", globalConf.WebDAVD.Cache.MimeTypes.Enabled)
  1767. viper.SetDefault("webdavd.cache.mime_types.max_size", globalConf.WebDAVD.Cache.MimeTypes.MaxSize)
  1768. viper.SetDefault("data_provider.driver", globalConf.ProviderConf.Driver)
  1769. viper.SetDefault("data_provider.name", globalConf.ProviderConf.Name)
  1770. viper.SetDefault("data_provider.host", globalConf.ProviderConf.Host)
  1771. viper.SetDefault("data_provider.port", globalConf.ProviderConf.Port)
  1772. viper.SetDefault("data_provider.username", globalConf.ProviderConf.Username)
  1773. viper.SetDefault("data_provider.password", globalConf.ProviderConf.Password)
  1774. viper.SetDefault("data_provider.sslmode", globalConf.ProviderConf.SSLMode)
  1775. viper.SetDefault("data_provider.disable_sni", globalConf.ProviderConf.DisableSNI)
  1776. viper.SetDefault("data_provider.target_session_attrs", globalConf.ProviderConf.TargetSessionAttrs)
  1777. viper.SetDefault("data_provider.root_cert", globalConf.ProviderConf.RootCert)
  1778. viper.SetDefault("data_provider.client_cert", globalConf.ProviderConf.ClientCert)
  1779. viper.SetDefault("data_provider.client_key", globalConf.ProviderConf.ClientKey)
  1780. viper.SetDefault("data_provider.connection_string", globalConf.ProviderConf.ConnectionString)
  1781. viper.SetDefault("data_provider.sql_tables_prefix", globalConf.ProviderConf.SQLTablesPrefix)
  1782. viper.SetDefault("data_provider.track_quota", globalConf.ProviderConf.TrackQuota)
  1783. viper.SetDefault("data_provider.pool_size", globalConf.ProviderConf.PoolSize)
  1784. viper.SetDefault("data_provider.users_base_dir", globalConf.ProviderConf.UsersBaseDir)
  1785. viper.SetDefault("data_provider.actions.execute_on", globalConf.ProviderConf.Actions.ExecuteOn)
  1786. viper.SetDefault("data_provider.actions.execute_for", globalConf.ProviderConf.Actions.ExecuteFor)
  1787. viper.SetDefault("data_provider.actions.hook", globalConf.ProviderConf.Actions.Hook)
  1788. viper.SetDefault("data_provider.external_auth_hook", globalConf.ProviderConf.ExternalAuthHook)
  1789. viper.SetDefault("data_provider.external_auth_scope", globalConf.ProviderConf.ExternalAuthScope)
  1790. viper.SetDefault("data_provider.pre_login_hook", globalConf.ProviderConf.PreLoginHook)
  1791. viper.SetDefault("data_provider.post_login_hook", globalConf.ProviderConf.PostLoginHook)
  1792. viper.SetDefault("data_provider.post_login_scope", globalConf.ProviderConf.PostLoginScope)
  1793. viper.SetDefault("data_provider.check_password_hook", globalConf.ProviderConf.CheckPasswordHook)
  1794. viper.SetDefault("data_provider.check_password_scope", globalConf.ProviderConf.CheckPasswordScope)
  1795. viper.SetDefault("data_provider.password_hashing.bcrypt_options.cost", globalConf.ProviderConf.PasswordHashing.BcryptOptions.Cost)
  1796. viper.SetDefault("data_provider.password_hashing.argon2_options.memory", globalConf.ProviderConf.PasswordHashing.Argon2Options.Memory)
  1797. viper.SetDefault("data_provider.password_hashing.argon2_options.iterations", globalConf.ProviderConf.PasswordHashing.Argon2Options.Iterations)
  1798. viper.SetDefault("data_provider.password_hashing.argon2_options.parallelism", globalConf.ProviderConf.PasswordHashing.Argon2Options.Parallelism)
  1799. viper.SetDefault("data_provider.password_hashing.algo", globalConf.ProviderConf.PasswordHashing.Algo)
  1800. viper.SetDefault("data_provider.password_validation.admins.min_entropy", globalConf.ProviderConf.PasswordValidation.Admins.MinEntropy)
  1801. viper.SetDefault("data_provider.password_validation.users.min_entropy", globalConf.ProviderConf.PasswordValidation.Users.MinEntropy)
  1802. viper.SetDefault("data_provider.password_caching", globalConf.ProviderConf.PasswordCaching)
  1803. viper.SetDefault("data_provider.update_mode", globalConf.ProviderConf.UpdateMode)
  1804. viper.SetDefault("data_provider.delayed_quota_update", globalConf.ProviderConf.DelayedQuotaUpdate)
  1805. viper.SetDefault("data_provider.create_default_admin", globalConf.ProviderConf.CreateDefaultAdmin)
  1806. viper.SetDefault("data_provider.naming_rules", globalConf.ProviderConf.NamingRules)
  1807. viper.SetDefault("data_provider.is_shared", globalConf.ProviderConf.IsShared)
  1808. viper.SetDefault("data_provider.node.host", globalConf.ProviderConf.Node.Host)
  1809. viper.SetDefault("data_provider.node.port", globalConf.ProviderConf.Node.Port)
  1810. viper.SetDefault("data_provider.node.proto", globalConf.ProviderConf.Node.Proto)
  1811. viper.SetDefault("data_provider.backups_path", globalConf.ProviderConf.BackupsPath)
  1812. viper.SetDefault("httpd.templates_path", globalConf.HTTPDConfig.TemplatesPath)
  1813. viper.SetDefault("httpd.static_files_path", globalConf.HTTPDConfig.StaticFilesPath)
  1814. viper.SetDefault("httpd.openapi_path", globalConf.HTTPDConfig.OpenAPIPath)
  1815. viper.SetDefault("httpd.web_root", globalConf.HTTPDConfig.WebRoot)
  1816. viper.SetDefault("httpd.certificate_file", globalConf.HTTPDConfig.CertificateFile)
  1817. viper.SetDefault("httpd.certificate_key_file", globalConf.HTTPDConfig.CertificateKeyFile)
  1818. viper.SetDefault("httpd.ca_certificates", globalConf.HTTPDConfig.CACertificates)
  1819. viper.SetDefault("httpd.ca_revocation_lists", globalConf.HTTPDConfig.CARevocationLists)
  1820. viper.SetDefault("httpd.signing_passphrase", globalConf.HTTPDConfig.SigningPassphrase)
  1821. viper.SetDefault("httpd.token_validation", globalConf.HTTPDConfig.TokenValidation)
  1822. viper.SetDefault("httpd.max_upload_file_size", globalConf.HTTPDConfig.MaxUploadFileSize)
  1823. viper.SetDefault("httpd.cors.enabled", globalConf.HTTPDConfig.Cors.Enabled)
  1824. viper.SetDefault("httpd.cors.allowed_origins", globalConf.HTTPDConfig.Cors.AllowedOrigins)
  1825. viper.SetDefault("httpd.cors.allowed_methods", globalConf.HTTPDConfig.Cors.AllowedMethods)
  1826. viper.SetDefault("httpd.cors.allowed_headers", globalConf.HTTPDConfig.Cors.AllowedHeaders)
  1827. viper.SetDefault("httpd.cors.exposed_headers", globalConf.HTTPDConfig.Cors.ExposedHeaders)
  1828. viper.SetDefault("httpd.cors.allow_credentials", globalConf.HTTPDConfig.Cors.AllowCredentials)
  1829. viper.SetDefault("httpd.cors.max_age", globalConf.HTTPDConfig.Cors.MaxAge)
  1830. viper.SetDefault("httpd.cors.options_passthrough", globalConf.HTTPDConfig.Cors.OptionsPassthrough)
  1831. viper.SetDefault("httpd.cors.options_success_status", globalConf.HTTPDConfig.Cors.OptionsSuccessStatus)
  1832. viper.SetDefault("httpd.cors.allow_private_network", globalConf.HTTPDConfig.Cors.AllowPrivateNetwork)
  1833. viper.SetDefault("httpd.setup.installation_code", globalConf.HTTPDConfig.Setup.InstallationCode)
  1834. viper.SetDefault("httpd.setup.installation_code_hint", globalConf.HTTPDConfig.Setup.InstallationCodeHint)
  1835. viper.SetDefault("httpd.hide_support_link", globalConf.HTTPDConfig.HideSupportLink)
  1836. viper.SetDefault("http.timeout", globalConf.HTTPConfig.Timeout)
  1837. viper.SetDefault("http.retry_wait_min", globalConf.HTTPConfig.RetryWaitMin)
  1838. viper.SetDefault("http.retry_wait_max", globalConf.HTTPConfig.RetryWaitMax)
  1839. viper.SetDefault("http.retry_max", globalConf.HTTPConfig.RetryMax)
  1840. viper.SetDefault("http.ca_certificates", globalConf.HTTPConfig.CACertificates)
  1841. viper.SetDefault("http.skip_tls_verify", globalConf.HTTPConfig.SkipTLSVerify)
  1842. viper.SetDefault("command.timeout", globalConf.CommandConfig.Timeout)
  1843. viper.SetDefault("command.env", globalConf.CommandConfig.Env)
  1844. viper.SetDefault("kms.secrets.url", globalConf.KMSConfig.Secrets.URL)
  1845. viper.SetDefault("kms.secrets.master_key", globalConf.KMSConfig.Secrets.MasterKeyString)
  1846. viper.SetDefault("kms.secrets.master_key_path", globalConf.KMSConfig.Secrets.MasterKeyPath)
  1847. viper.SetDefault("telemetry.bind_port", globalConf.TelemetryConfig.BindPort)
  1848. viper.SetDefault("telemetry.bind_address", globalConf.TelemetryConfig.BindAddress)
  1849. viper.SetDefault("telemetry.enable_profiler", globalConf.TelemetryConfig.EnableProfiler)
  1850. viper.SetDefault("telemetry.auth_user_file", globalConf.TelemetryConfig.AuthUserFile)
  1851. viper.SetDefault("telemetry.certificate_file", globalConf.TelemetryConfig.CertificateFile)
  1852. viper.SetDefault("telemetry.certificate_key_file", globalConf.TelemetryConfig.CertificateKeyFile)
  1853. viper.SetDefault("telemetry.min_tls_version", globalConf.TelemetryConfig.MinTLSVersion)
  1854. viper.SetDefault("telemetry.tls_cipher_suites", globalConf.TelemetryConfig.TLSCipherSuites)
  1855. viper.SetDefault("smtp.host", globalConf.SMTPConfig.Host)
  1856. viper.SetDefault("smtp.port", globalConf.SMTPConfig.Port)
  1857. viper.SetDefault("smtp.from", globalConf.SMTPConfig.From)
  1858. viper.SetDefault("smtp.user", globalConf.SMTPConfig.User)
  1859. viper.SetDefault("smtp.password", globalConf.SMTPConfig.Password)
  1860. viper.SetDefault("smtp.auth_type", globalConf.SMTPConfig.AuthType)
  1861. viper.SetDefault("smtp.encryption", globalConf.SMTPConfig.Encryption)
  1862. viper.SetDefault("smtp.domain", globalConf.SMTPConfig.Domain)
  1863. viper.SetDefault("smtp.templates_path", globalConf.SMTPConfig.TemplatesPath)
  1864. }
  1865. func lookupBoolFromEnv(envName string) (bool, bool) {
  1866. value, ok := os.LookupEnv(envName)
  1867. if ok {
  1868. converted, err := strconv.ParseBool(strings.TrimSpace(value))
  1869. if err == nil {
  1870. return converted, ok
  1871. }
  1872. }
  1873. return false, false
  1874. }
  1875. func lookupIntFromEnv(envName string) (int64, bool) {
  1876. value, ok := os.LookupEnv(envName)
  1877. if ok {
  1878. converted, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64)
  1879. if err == nil {
  1880. return converted, ok
  1881. }
  1882. }
  1883. return 0, false
  1884. }
  1885. func lookupStringListFromEnv(envName string) ([]string, bool) {
  1886. value, ok := os.LookupEnv(envName)
  1887. if ok {
  1888. var result []string
  1889. for _, v := range strings.Split(value, ",") {
  1890. val := strings.TrimSpace(v)
  1891. if val != "" {
  1892. result = append(result, val)
  1893. }
  1894. }
  1895. return result, true
  1896. }
  1897. return nil, false
  1898. }