config.go 71 KB

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