config.go 73 KB

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