config.go 73 KB

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