config.go 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206
  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. ResumeMaxSize: 0,
  198. TempPath: "",
  199. ProxyProtocol: 0,
  200. ProxyAllowed: []string{},
  201. ProxySkipped: []string{},
  202. PostConnectHook: "",
  203. PostDisconnectHook: "",
  204. DataRetentionHook: "",
  205. MaxTotalConnections: 0,
  206. MaxPerHostConnections: 20,
  207. AllowListStatus: 0,
  208. AllowSelfConnections: 0,
  209. DefenderConfig: common.DefenderConfig{
  210. Enabled: false,
  211. Driver: common.DefenderDriverMemory,
  212. BanTime: 30,
  213. BanTimeIncrement: 50,
  214. Threshold: 15,
  215. ScoreInvalid: 2,
  216. ScoreValid: 1,
  217. ScoreLimitExceeded: 3,
  218. ScoreNoAuth: 0,
  219. ObservationTime: 30,
  220. EntriesSoftLimit: 100,
  221. EntriesHardLimit: 150,
  222. },
  223. RateLimitersConfig: []common.RateLimiterConfig{defaultRateLimiter},
  224. Umask: "",
  225. Metadata: common.MetadataConfig{
  226. Read: 0,
  227. },
  228. },
  229. ACME: acme.Configuration{
  230. Email: "",
  231. KeyType: "4096",
  232. CertsPath: "certs",
  233. CAEndpoint: "https://acme-v02.api.letsencrypt.org/directory",
  234. Domains: []string{},
  235. RenewDays: 30,
  236. HTTP01Challenge: acme.HTTP01Challenge{
  237. Port: 80,
  238. WebRoot: "",
  239. ProxyHeader: "",
  240. },
  241. TLSALPN01Challenge: acme.TLSALPN01Challenge{
  242. Port: 0,
  243. },
  244. },
  245. SFTPD: sftpd.Configuration{
  246. Bindings: []sftpd.Binding{defaultSFTPDBinding},
  247. MaxAuthTries: 0,
  248. Banner: defaultSFTPDBanner,
  249. HostKeys: []string{},
  250. HostCertificates: []string{},
  251. HostKeyAlgorithms: []string{},
  252. Moduli: []string{},
  253. KexAlgorithms: []string{},
  254. Ciphers: []string{},
  255. MACs: []string{},
  256. TrustedUserCAKeys: []string{},
  257. RevokedUserCertsFile: "",
  258. LoginBannerFile: "",
  259. EnabledSSHCommands: []string{},
  260. KeyboardInteractiveAuthentication: true,
  261. KeyboardInteractiveHook: "",
  262. PasswordAuthentication: true,
  263. FolderPrefix: "",
  264. },
  265. FTPD: ftpd.Configuration{
  266. Bindings: []ftpd.Binding{defaultFTPDBinding},
  267. Banner: defaultFTPDBanner,
  268. BannerFile: "",
  269. ActiveTransfersPortNon20: true,
  270. PassivePortRange: ftpd.PortRange{
  271. Start: 50000,
  272. End: 50100,
  273. },
  274. DisableActiveMode: false,
  275. EnableSite: false,
  276. HASHSupport: 0,
  277. CombineSupport: 0,
  278. CertificateFile: "",
  279. CertificateKeyFile: "",
  280. CACertificates: []string{},
  281. CARevocationLists: []string{},
  282. },
  283. WebDAVD: webdavd.Configuration{
  284. Bindings: []webdavd.Binding{defaultWebDAVDBinding},
  285. CertificateFile: "",
  286. CertificateKeyFile: "",
  287. CACertificates: []string{},
  288. CARevocationLists: []string{},
  289. Cors: webdavd.CorsConfig{
  290. Enabled: false,
  291. AllowedOrigins: []string{},
  292. AllowedMethods: []string{},
  293. AllowedHeaders: []string{},
  294. ExposedHeaders: []string{},
  295. AllowCredentials: false,
  296. MaxAge: 0,
  297. OptionsPassthrough: false,
  298. OptionsSuccessStatus: 0,
  299. AllowPrivateNetwork: false,
  300. },
  301. Cache: webdavd.Cache{
  302. Users: webdavd.UsersCacheConfig{
  303. ExpirationTime: 0,
  304. MaxSize: 50,
  305. },
  306. MimeTypes: webdavd.MimeCacheConfig{
  307. Enabled: true,
  308. MaxSize: 1000,
  309. CustomMappings: nil,
  310. },
  311. },
  312. },
  313. ProviderConf: dataprovider.Config{
  314. Driver: "sqlite",
  315. Name: "sftpgo.db",
  316. Host: "",
  317. Port: 0,
  318. Username: "",
  319. Password: "",
  320. ConnectionString: "",
  321. SQLTablesPrefix: "",
  322. SSLMode: 0,
  323. DisableSNI: false,
  324. TargetSessionAttrs: "",
  325. RootCert: "",
  326. ClientCert: "",
  327. ClientKey: "",
  328. TrackQuota: 2,
  329. PoolSize: 0,
  330. UsersBaseDir: "",
  331. Actions: dataprovider.ObjectsActions{
  332. ExecuteOn: []string{},
  333. ExecuteFor: []string{},
  334. Hook: "",
  335. },
  336. ExternalAuthHook: "",
  337. ExternalAuthScope: 0,
  338. PreLoginHook: "",
  339. PostLoginHook: "",
  340. PostLoginScope: 0,
  341. CheckPasswordHook: "",
  342. CheckPasswordScope: 0,
  343. PasswordHashing: dataprovider.PasswordHashing{
  344. Argon2Options: dataprovider.Argon2Options{
  345. Memory: 65536,
  346. Iterations: 1,
  347. Parallelism: 2,
  348. },
  349. BcryptOptions: dataprovider.BcryptOptions{
  350. Cost: 10,
  351. },
  352. Algo: dataprovider.HashingAlgoBcrypt,
  353. },
  354. PasswordValidation: dataprovider.PasswordValidation{
  355. Admins: dataprovider.PasswordValidationRules{
  356. MinEntropy: 0,
  357. },
  358. Users: dataprovider.PasswordValidationRules{
  359. MinEntropy: 0,
  360. },
  361. },
  362. PasswordCaching: true,
  363. UpdateMode: 0,
  364. DelayedQuotaUpdate: 0,
  365. CreateDefaultAdmin: false,
  366. NamingRules: 1,
  367. IsShared: 0,
  368. Node: dataprovider.NodeConfig{
  369. Host: "",
  370. Port: 0,
  371. Proto: "http",
  372. },
  373. BackupsPath: "backups",
  374. },
  375. HTTPDConfig: httpd.Conf{
  376. Bindings: []httpd.Binding{defaultHTTPDBinding},
  377. TemplatesPath: "templates",
  378. StaticFilesPath: "static",
  379. OpenAPIPath: "openapi",
  380. WebRoot: "",
  381. CertificateFile: "",
  382. CertificateKeyFile: "",
  383. CACertificates: nil,
  384. CARevocationLists: nil,
  385. SigningPassphrase: "",
  386. TokenValidation: 0,
  387. MaxUploadFileSize: 0,
  388. Cors: httpd.CorsConfig{
  389. Enabled: false,
  390. AllowedOrigins: []string{},
  391. AllowedMethods: []string{},
  392. AllowedHeaders: []string{},
  393. ExposedHeaders: []string{},
  394. AllowCredentials: false,
  395. MaxAge: 0,
  396. OptionsPassthrough: false,
  397. OptionsSuccessStatus: 0,
  398. AllowPrivateNetwork: false,
  399. },
  400. Setup: httpd.SetupConfig{
  401. InstallationCode: "",
  402. InstallationCodeHint: defaultInstallCodeHint,
  403. },
  404. HideSupportLink: false,
  405. },
  406. HTTPConfig: httpclient.Config{
  407. Timeout: 20,
  408. RetryWaitMin: 2,
  409. RetryWaitMax: 30,
  410. RetryMax: 3,
  411. CACertificates: nil,
  412. Certificates: nil,
  413. SkipTLSVerify: false,
  414. Headers: nil,
  415. },
  416. CommandConfig: command.Config{
  417. Timeout: 30,
  418. Env: nil,
  419. Commands: nil,
  420. },
  421. KMSConfig: kms.Configuration{
  422. Secrets: kms.Secrets{
  423. URL: "",
  424. MasterKeyString: "",
  425. MasterKeyPath: "",
  426. },
  427. },
  428. MFAConfig: mfa.Config{
  429. TOTP: []mfa.TOTPConfig{defaultTOTP},
  430. },
  431. TelemetryConfig: telemetry.Conf{
  432. BindPort: 0,
  433. BindAddress: "127.0.0.1",
  434. EnableProfiler: false,
  435. AuthUserFile: "",
  436. CertificateFile: "",
  437. CertificateKeyFile: "",
  438. MinTLSVersion: 12,
  439. TLSCipherSuites: nil,
  440. },
  441. SMTPConfig: smtp.Config{
  442. Host: "",
  443. Port: 587,
  444. From: "",
  445. User: "",
  446. Password: "",
  447. AuthType: 0,
  448. Encryption: 0,
  449. Domain: "",
  450. TemplatesPath: "templates",
  451. },
  452. PluginsConfig: nil,
  453. }
  454. viper.SetEnvPrefix(configEnvPrefix)
  455. replacer := strings.NewReplacer(".", "__")
  456. viper.SetEnvKeyReplacer(replacer)
  457. viper.SetConfigName(configName)
  458. setViperDefaults()
  459. viper.AutomaticEnv()
  460. viper.AllowEmptyEnv(true)
  461. }
  462. // GetCommonConfig returns the common protocols configuration
  463. func GetCommonConfig() common.Configuration {
  464. return globalConf.Common
  465. }
  466. // SetCommonConfig sets the common protocols configuration
  467. func SetCommonConfig(config common.Configuration) {
  468. globalConf.Common = config
  469. }
  470. // GetSFTPDConfig returns the configuration for the SFTP server
  471. func GetSFTPDConfig() sftpd.Configuration {
  472. return globalConf.SFTPD
  473. }
  474. // SetSFTPDConfig sets the configuration for the SFTP server
  475. func SetSFTPDConfig(config sftpd.Configuration) {
  476. globalConf.SFTPD = config
  477. }
  478. // GetFTPDConfig returns the configuration for the FTP server
  479. func GetFTPDConfig() ftpd.Configuration {
  480. return globalConf.FTPD
  481. }
  482. // SetFTPDConfig sets the configuration for the FTP server
  483. func SetFTPDConfig(config ftpd.Configuration) {
  484. globalConf.FTPD = config
  485. }
  486. // GetWebDAVDConfig returns the configuration for the WebDAV server
  487. func GetWebDAVDConfig() webdavd.Configuration {
  488. return globalConf.WebDAVD
  489. }
  490. // SetWebDAVDConfig sets the configuration for the WebDAV server
  491. func SetWebDAVDConfig(config webdavd.Configuration) {
  492. globalConf.WebDAVD = config
  493. }
  494. // GetHTTPDConfig returns the configuration for the HTTP server
  495. func GetHTTPDConfig() httpd.Conf {
  496. return globalConf.HTTPDConfig
  497. }
  498. // SetHTTPDConfig sets the configuration for the HTTP server
  499. func SetHTTPDConfig(config httpd.Conf) {
  500. globalConf.HTTPDConfig = config
  501. }
  502. // GetProviderConf returns the configuration for the data provider
  503. func GetProviderConf() dataprovider.Config {
  504. return globalConf.ProviderConf
  505. }
  506. // SetProviderConf sets the configuration for the data provider
  507. func SetProviderConf(config dataprovider.Config) {
  508. globalConf.ProviderConf = config
  509. }
  510. // GetHTTPConfig returns the configuration for HTTP clients
  511. func GetHTTPConfig() httpclient.Config {
  512. return globalConf.HTTPConfig
  513. }
  514. // GetCommandConfig returns the configuration for external commands
  515. func GetCommandConfig() command.Config {
  516. return globalConf.CommandConfig
  517. }
  518. // GetKMSConfig returns the KMS configuration
  519. func GetKMSConfig() kms.Configuration {
  520. return globalConf.KMSConfig
  521. }
  522. // SetKMSConfig sets the kms configuration
  523. func SetKMSConfig(config kms.Configuration) {
  524. globalConf.KMSConfig = config
  525. }
  526. // GetTelemetryConfig returns the telemetry configuration
  527. func GetTelemetryConfig() telemetry.Conf {
  528. return globalConf.TelemetryConfig
  529. }
  530. // SetTelemetryConfig sets the telemetry configuration
  531. func SetTelemetryConfig(config telemetry.Conf) {
  532. globalConf.TelemetryConfig = config
  533. }
  534. // GetPluginsConfig returns the plugins configuration
  535. func GetPluginsConfig() []plugin.Config {
  536. return globalConf.PluginsConfig
  537. }
  538. // SetPluginsConfig sets the plugin configuration
  539. func SetPluginsConfig(config []plugin.Config) {
  540. globalConf.PluginsConfig = config
  541. }
  542. // GetMFAConfig returns multi-factor authentication config
  543. func GetMFAConfig() mfa.Config {
  544. return globalConf.MFAConfig
  545. }
  546. // GetSMTPConfig returns the SMTP configuration
  547. func GetSMTPConfig() smtp.Config {
  548. return globalConf.SMTPConfig
  549. }
  550. // GetACMEConfig returns the ACME configuration
  551. func GetACMEConfig() acme.Configuration {
  552. return globalConf.ACME
  553. }
  554. // HasServicesToStart returns true if the config defines at least a service to start.
  555. // Supported services are SFTP, FTP and WebDAV
  556. func HasServicesToStart() bool {
  557. if globalConf.SFTPD.ShouldBind() {
  558. return true
  559. }
  560. if globalConf.FTPD.ShouldBind() {
  561. return true
  562. }
  563. if globalConf.WebDAVD.ShouldBind() {
  564. return true
  565. }
  566. if globalConf.HTTPDConfig.ShouldBind() {
  567. return true
  568. }
  569. return false
  570. }
  571. func getRedactedPassword(value string) string {
  572. if value == "" {
  573. return value
  574. }
  575. return "[redacted]"
  576. }
  577. func getRedactedGlobalConf() globalConfig {
  578. conf := globalConf
  579. conf.Common.Actions.Hook = util.GetRedactedURL(conf.Common.Actions.Hook)
  580. conf.Common.StartupHook = util.GetRedactedURL(conf.Common.StartupHook)
  581. conf.Common.PostConnectHook = util.GetRedactedURL(conf.Common.PostConnectHook)
  582. conf.Common.PostDisconnectHook = util.GetRedactedURL(conf.Common.PostDisconnectHook)
  583. conf.Common.DataRetentionHook = util.GetRedactedURL(conf.Common.DataRetentionHook)
  584. conf.SFTPD.KeyboardInteractiveHook = util.GetRedactedURL(conf.SFTPD.KeyboardInteractiveHook)
  585. conf.HTTPDConfig.SigningPassphrase = getRedactedPassword(conf.HTTPDConfig.SigningPassphrase)
  586. conf.HTTPDConfig.Setup.InstallationCode = getRedactedPassword(conf.HTTPDConfig.Setup.InstallationCode)
  587. conf.ProviderConf.Password = getRedactedPassword(conf.ProviderConf.Password)
  588. conf.ProviderConf.Actions.Hook = util.GetRedactedURL(conf.ProviderConf.Actions.Hook)
  589. conf.ProviderConf.ExternalAuthHook = util.GetRedactedURL(conf.ProviderConf.ExternalAuthHook)
  590. conf.ProviderConf.PreLoginHook = util.GetRedactedURL(conf.ProviderConf.PreLoginHook)
  591. conf.ProviderConf.PostLoginHook = util.GetRedactedURL(conf.ProviderConf.PostLoginHook)
  592. conf.ProviderConf.CheckPasswordHook = util.GetRedactedURL(conf.ProviderConf.CheckPasswordHook)
  593. conf.SMTPConfig.Password = getRedactedPassword(conf.SMTPConfig.Password)
  594. conf.HTTPDConfig.Bindings = nil
  595. for _, binding := range globalConf.HTTPDConfig.Bindings {
  596. binding.OIDC.ClientID = getRedactedPassword(binding.OIDC.ClientID)
  597. binding.OIDC.ClientSecret = getRedactedPassword(binding.OIDC.ClientSecret)
  598. conf.HTTPDConfig.Bindings = append(conf.HTTPDConfig.Bindings, binding)
  599. }
  600. return conf
  601. }
  602. func setConfigFile(configDir, configFile string) {
  603. if configFile == "" {
  604. return
  605. }
  606. if !filepath.IsAbs(configFile) && util.IsFileInputValid(configFile) {
  607. configFile = filepath.Join(configDir, configFile)
  608. }
  609. viper.SetConfigFile(configFile)
  610. }
  611. // readEnvFiles reads files inside the "env.d" directory relative to configDir
  612. // and then export the valid variables into environment variables if they do
  613. // not exist
  614. func readEnvFiles(configDir string) {
  615. envd := filepath.Join(configDir, "env.d")
  616. entries, err := os.ReadDir(envd)
  617. if err != nil {
  618. logger.Info(logSender, "", "unable to read env files from %q: %v", envd, err)
  619. return
  620. }
  621. for _, entry := range entries {
  622. info, err := entry.Info()
  623. if err == nil && info.Mode().IsRegular() {
  624. envFile := filepath.Join(envd, entry.Name())
  625. if info.Size() > envFileMaxSize {
  626. logger.Info(logSender, "", "env file %q too big: %s, skipping", entry.Name(), util.ByteCountIEC(info.Size()))
  627. continue
  628. }
  629. err = gotenv.Load(envFile)
  630. if err != nil {
  631. logger.Error(logSender, "", "unable to load env vars from file %q, err: %v", envFile, err)
  632. } else {
  633. logger.Info(logSender, "", "set env vars from file %q", envFile)
  634. }
  635. }
  636. }
  637. }
  638. func checkOverrideDefaultSettings() {
  639. // for slices we need to set the defaults to nil if the key is set in the config file,
  640. // otherwise the values are merged and not replaced as expected
  641. rateLimiters := viper.Get("common.rate_limiters")
  642. if val, ok := rateLimiters.([]any); ok {
  643. if len(val) > 0 {
  644. if rl, ok := val[0].(map[string]any); ok {
  645. if _, ok := rl["protocols"]; ok {
  646. globalConf.Common.RateLimitersConfig[0].Protocols = nil
  647. }
  648. }
  649. }
  650. }
  651. httpdBindings := viper.Get("httpd.bindings")
  652. if val, ok := httpdBindings.([]any); ok {
  653. if len(val) > 0 {
  654. if binding, ok := val[0].(map[string]any); ok {
  655. if val, ok := binding["oidc"]; ok {
  656. if oidc, ok := val.(map[string]any); ok {
  657. if _, ok := oidc["scopes"]; ok {
  658. globalConf.HTTPDConfig.Bindings[0].OIDC.Scopes = nil
  659. }
  660. }
  661. }
  662. }
  663. }
  664. }
  665. if util.Contains(viper.AllKeys(), "mfa.totp") {
  666. globalConf.MFAConfig.TOTP = nil
  667. }
  668. }
  669. // LoadConfig loads the configuration
  670. // configDir will be added to the configuration search paths.
  671. // The search path contains by default the current directory and on linux it contains
  672. // $HOME/.config/sftpgo and /etc/sftpgo too.
  673. // configFile is an absolute or relative path (to the config dir) to the configuration file.
  674. func LoadConfig(configDir, configFile string) error {
  675. var err error
  676. readEnvFiles(configDir)
  677. viper.AddConfigPath(configDir)
  678. setViperAdditionalConfigPaths()
  679. viper.AddConfigPath(".")
  680. setConfigFile(configDir, configFile)
  681. if err = viper.ReadInConfig(); err != nil {
  682. // if the user specify a configuration file we get os.ErrNotExist.
  683. // viper.ConfigFileNotFoundError is returned if viper is unable
  684. // to find sftpgo.{json,yaml, etc..} in any of the search paths
  685. if errors.As(err, &viper.ConfigFileNotFoundError{}) {
  686. logger.Debug(logSender, "", "no configuration file found")
  687. } else {
  688. // should we return the error and not start here?
  689. logger.Warn(logSender, "", "error loading configuration file: %v", err)
  690. logger.WarnToConsole("error loading configuration file: %v", err)
  691. }
  692. }
  693. checkOverrideDefaultSettings()
  694. err = viper.Unmarshal(&globalConf)
  695. if err != nil {
  696. logger.Warn(logSender, "", "error parsing configuration file: %v", err)
  697. logger.WarnToConsole("error parsing configuration file: %v", err)
  698. return err
  699. }
  700. // viper only supports slice of strings from env vars, so we use our custom method
  701. loadBindingsFromEnv()
  702. loadWebDAVCacheMappingsFromEnv()
  703. resetInvalidConfigs()
  704. logger.Debug(logSender, "", "config file used: '%q', config loaded: %+v", viper.ConfigFileUsed(), getRedactedGlobalConf())
  705. return nil
  706. }
  707. func isProxyProtocolValid() bool {
  708. return globalConf.Common.ProxyProtocol >= 0 && globalConf.Common.ProxyProtocol <= 2
  709. }
  710. func isExternalAuthScopeValid() bool {
  711. return globalConf.ProviderConf.ExternalAuthScope >= 0 && globalConf.ProviderConf.ExternalAuthScope <= 15
  712. }
  713. func resetInvalidConfigs() {
  714. if strings.TrimSpace(globalConf.SFTPD.Banner) == "" {
  715. globalConf.SFTPD.Banner = defaultSFTPDBanner
  716. }
  717. if strings.TrimSpace(globalConf.FTPD.Banner) == "" {
  718. globalConf.FTPD.Banner = defaultFTPDBanner
  719. }
  720. if strings.TrimSpace(globalConf.HTTPDConfig.Setup.InstallationCodeHint) == "" {
  721. globalConf.HTTPDConfig.Setup.InstallationCodeHint = defaultInstallCodeHint
  722. }
  723. if globalConf.ProviderConf.UsersBaseDir != "" && !util.IsFileInputValid(globalConf.ProviderConf.UsersBaseDir) {
  724. warn := fmt.Sprintf("invalid users base dir %q will be ignored", globalConf.ProviderConf.UsersBaseDir)
  725. globalConf.ProviderConf.UsersBaseDir = ""
  726. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  727. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  728. }
  729. if !isProxyProtocolValid() {
  730. warn := fmt.Sprintf("invalid proxy_protocol 0, 1 and 2 are supported, configured: %v reset proxy_protocol to 0",
  731. globalConf.Common.ProxyProtocol)
  732. globalConf.Common.ProxyProtocol = 0
  733. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  734. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  735. }
  736. if !isExternalAuthScopeValid() {
  737. warn := fmt.Sprintf("invalid external_auth_scope: %v reset to 0", globalConf.ProviderConf.ExternalAuthScope)
  738. globalConf.ProviderConf.ExternalAuthScope = 0
  739. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  740. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  741. }
  742. if globalConf.Common.DefenderConfig.Enabled && globalConf.Common.DefenderConfig.Driver == common.DefenderDriverProvider {
  743. if !globalConf.ProviderConf.IsDefenderSupported() {
  744. warn := fmt.Sprintf("provider based defender is not supported with data provider %q, "+
  745. "the memory defender implementation will be used. If you want to use the provider defender "+
  746. "implementation please switch to a shared/distributed data provider",
  747. globalConf.ProviderConf.Driver)
  748. globalConf.Common.DefenderConfig.Driver = common.DefenderDriverMemory
  749. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  750. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  751. }
  752. }
  753. }
  754. func loadBindingsFromEnv() {
  755. for idx := 0; idx < 10; idx++ {
  756. getTOTPFromEnv(idx)
  757. getRateLimitersFromEnv(idx)
  758. getPluginsFromEnv(idx)
  759. getSFTPDBindindFromEnv(idx)
  760. getFTPDBindingFromEnv(idx)
  761. getWebDAVDBindingFromEnv(idx)
  762. getHTTPDBindingFromEnv(idx)
  763. getHTTPClientCertificatesFromEnv(idx)
  764. getHTTPClientHeadersFromEnv(idx)
  765. getCommandConfigsFromEnv(idx)
  766. }
  767. }
  768. func getTOTPFromEnv(idx int) {
  769. totpConfig := defaultTOTP
  770. if len(globalConf.MFAConfig.TOTP) > idx {
  771. totpConfig = globalConf.MFAConfig.TOTP[idx]
  772. }
  773. isSet := false
  774. name, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_MFA__TOTP__%v__NAME", idx))
  775. if ok {
  776. totpConfig.Name = name
  777. isSet = true
  778. }
  779. issuer, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_MFA__TOTP__%v__ISSUER", idx))
  780. if ok {
  781. totpConfig.Issuer = issuer
  782. isSet = true
  783. }
  784. algo, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_MFA__TOTP__%v__ALGO", idx))
  785. if ok {
  786. totpConfig.Algo = algo
  787. isSet = true
  788. }
  789. if isSet {
  790. if len(globalConf.MFAConfig.TOTP) > idx {
  791. globalConf.MFAConfig.TOTP[idx] = totpConfig
  792. } else {
  793. globalConf.MFAConfig.TOTP = append(globalConf.MFAConfig.TOTP, totpConfig)
  794. }
  795. }
  796. }
  797. func getRateLimitersFromEnv(idx int) {
  798. rtlConfig := defaultRateLimiter
  799. if len(globalConf.Common.RateLimitersConfig) > idx {
  800. rtlConfig = globalConf.Common.RateLimitersConfig[idx]
  801. }
  802. isSet := false
  803. average, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__AVERAGE", idx), 64)
  804. if ok {
  805. rtlConfig.Average = average
  806. isSet = true
  807. }
  808. period, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__PERIOD", idx), 64)
  809. if ok {
  810. rtlConfig.Period = period
  811. isSet = true
  812. }
  813. burst, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__BURST", idx), 0)
  814. if ok {
  815. rtlConfig.Burst = int(burst)
  816. isSet = true
  817. }
  818. rtlType, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__TYPE", idx), 0)
  819. if ok {
  820. rtlConfig.Type = int(rtlType)
  821. isSet = true
  822. }
  823. protocols, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__PROTOCOLS", idx))
  824. if ok {
  825. rtlConfig.Protocols = protocols
  826. isSet = true
  827. }
  828. generateEvents, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__GENERATE_DEFENDER_EVENTS", idx))
  829. if ok {
  830. rtlConfig.GenerateDefenderEvents = generateEvents
  831. isSet = true
  832. }
  833. softLimit, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__ENTRIES_SOFT_LIMIT", idx), 0)
  834. if ok {
  835. rtlConfig.EntriesSoftLimit = int(softLimit)
  836. isSet = true
  837. }
  838. hardLimit, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__ENTRIES_HARD_LIMIT", idx), 0)
  839. if ok {
  840. rtlConfig.EntriesHardLimit = int(hardLimit)
  841. isSet = true
  842. }
  843. if isSet {
  844. if len(globalConf.Common.RateLimitersConfig) > idx {
  845. globalConf.Common.RateLimitersConfig[idx] = rtlConfig
  846. } else {
  847. globalConf.Common.RateLimitersConfig = append(globalConf.Common.RateLimitersConfig, rtlConfig)
  848. }
  849. }
  850. }
  851. func getKMSPluginFromEnv(idx int, pluginConfig *plugin.Config) bool {
  852. isSet := false
  853. kmsScheme, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__KMS_OPTIONS__SCHEME", idx))
  854. if ok {
  855. pluginConfig.KMSOptions.Scheme = kmsScheme
  856. isSet = true
  857. }
  858. kmsEncStatus, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__KMS_OPTIONS__ENCRYPTED_STATUS", idx))
  859. if ok {
  860. pluginConfig.KMSOptions.EncryptedStatus = kmsEncStatus
  861. isSet = true
  862. }
  863. return isSet
  864. }
  865. func getAuthPluginFromEnv(idx int, pluginConfig *plugin.Config) bool {
  866. isSet := false
  867. authScope, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__AUTH_OPTIONS__SCOPE", idx), 0)
  868. if ok {
  869. pluginConfig.AuthOptions.Scope = int(authScope)
  870. isSet = true
  871. }
  872. return isSet
  873. }
  874. func getNotifierPluginFromEnv(idx int, pluginConfig *plugin.Config) bool {
  875. isSet := false
  876. notifierFsEvents, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__FS_EVENTS", idx))
  877. if ok {
  878. pluginConfig.NotifierOptions.FsEvents = notifierFsEvents
  879. isSet = true
  880. }
  881. notifierProviderEvents, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__PROVIDER_EVENTS", idx))
  882. if ok {
  883. pluginConfig.NotifierOptions.ProviderEvents = notifierProviderEvents
  884. isSet = true
  885. }
  886. notifierProviderObjects, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__PROVIDER_OBJECTS", idx))
  887. if ok {
  888. pluginConfig.NotifierOptions.ProviderObjects = notifierProviderObjects
  889. isSet = true
  890. }
  891. notifierLogEventsString, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__LOG_EVENTS", idx))
  892. if ok {
  893. var notifierLogEvents []int
  894. for _, e := range notifierLogEventsString {
  895. ev, err := strconv.Atoi(e)
  896. if err == nil {
  897. notifierLogEvents = append(notifierLogEvents, ev)
  898. }
  899. }
  900. if len(notifierLogEvents) > 0 {
  901. pluginConfig.NotifierOptions.LogEvents = notifierLogEvents
  902. isSet = true
  903. }
  904. }
  905. notifierRetryMaxTime, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__RETRY_MAX_TIME", idx), 0)
  906. if ok {
  907. pluginConfig.NotifierOptions.RetryMaxTime = int(notifierRetryMaxTime)
  908. isSet = true
  909. }
  910. notifierRetryQueueMaxSize, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__RETRY_QUEUE_MAX_SIZE", idx), 0)
  911. if ok {
  912. pluginConfig.NotifierOptions.RetryQueueMaxSize = int(notifierRetryQueueMaxSize)
  913. isSet = true
  914. }
  915. return isSet
  916. }
  917. func getPluginsFromEnv(idx int) {
  918. pluginConfig := plugin.Config{}
  919. if len(globalConf.PluginsConfig) > idx {
  920. pluginConfig = globalConf.PluginsConfig[idx]
  921. }
  922. isSet := false
  923. pluginType, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__TYPE", idx))
  924. if ok {
  925. pluginConfig.Type = pluginType
  926. isSet = true
  927. }
  928. if getNotifierPluginFromEnv(idx, &pluginConfig) {
  929. isSet = true
  930. }
  931. if getKMSPluginFromEnv(idx, &pluginConfig) {
  932. isSet = true
  933. }
  934. if getAuthPluginFromEnv(idx, &pluginConfig) {
  935. isSet = true
  936. }
  937. cmd, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__CMD", idx))
  938. if ok {
  939. pluginConfig.Cmd = cmd
  940. isSet = true
  941. }
  942. cmdArgs, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__ARGS", idx))
  943. if ok {
  944. pluginConfig.Args = cmdArgs
  945. isSet = true
  946. }
  947. pluginHash, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__SHA256SUM", idx))
  948. if ok {
  949. pluginConfig.SHA256Sum = pluginHash
  950. isSet = true
  951. }
  952. autoMTLS, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__AUTO_MTLS", idx))
  953. if ok {
  954. pluginConfig.AutoMTLS = autoMTLS
  955. isSet = true
  956. }
  957. if isSet {
  958. if len(globalConf.PluginsConfig) > idx {
  959. globalConf.PluginsConfig[idx] = pluginConfig
  960. } else {
  961. globalConf.PluginsConfig = append(globalConf.PluginsConfig, pluginConfig)
  962. }
  963. }
  964. }
  965. func getSFTPDBindindFromEnv(idx int) {
  966. binding := defaultSFTPDBinding
  967. if len(globalConf.SFTPD.Bindings) > idx {
  968. binding = globalConf.SFTPD.Bindings[idx]
  969. }
  970. isSet := false
  971. port, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_SFTPD__BINDINGS__%v__PORT", idx), 0)
  972. if ok {
  973. binding.Port = int(port)
  974. isSet = true
  975. }
  976. address, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_SFTPD__BINDINGS__%v__ADDRESS", idx))
  977. if ok {
  978. binding.Address = address
  979. isSet = true
  980. }
  981. applyProxyConfig, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_SFTPD__BINDINGS__%v__APPLY_PROXY_CONFIG", idx))
  982. if ok {
  983. binding.ApplyProxyConfig = applyProxyConfig
  984. isSet = true
  985. }
  986. if isSet {
  987. if len(globalConf.SFTPD.Bindings) > idx {
  988. globalConf.SFTPD.Bindings[idx] = binding
  989. } else {
  990. globalConf.SFTPD.Bindings = append(globalConf.SFTPD.Bindings, binding)
  991. }
  992. }
  993. }
  994. func getFTPDPassiveIPOverridesFromEnv(idx int) []ftpd.PassiveIPOverride {
  995. var overrides []ftpd.PassiveIPOverride
  996. if len(globalConf.FTPD.Bindings) > idx {
  997. overrides = globalConf.FTPD.Bindings[idx].PassiveIPOverrides
  998. }
  999. for subIdx := 0; subIdx < 10; subIdx++ {
  1000. var override ftpd.PassiveIPOverride
  1001. var replace bool
  1002. if len(globalConf.FTPD.Bindings) > idx && len(globalConf.FTPD.Bindings[idx].PassiveIPOverrides) > subIdx {
  1003. override = globalConf.FTPD.Bindings[idx].PassiveIPOverrides[subIdx]
  1004. replace = true
  1005. }
  1006. ip, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__PASSIVE_IP_OVERRIDES__%v__IP", idx, subIdx))
  1007. if ok {
  1008. override.IP = ip
  1009. }
  1010. networks, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__PASSIVE_IP_OVERRIDES__%v__NETWORKS",
  1011. idx, subIdx))
  1012. if ok {
  1013. override.Networks = networks
  1014. }
  1015. if len(override.Networks) > 0 {
  1016. if replace {
  1017. overrides[subIdx] = override
  1018. } else {
  1019. overrides = append(overrides, override)
  1020. }
  1021. }
  1022. }
  1023. return overrides
  1024. }
  1025. func getDefaultFTPDBinding(idx int) ftpd.Binding {
  1026. binding := defaultFTPDBinding
  1027. if len(globalConf.FTPD.Bindings) > idx {
  1028. binding = globalConf.FTPD.Bindings[idx]
  1029. }
  1030. return binding
  1031. }
  1032. func getFTPDBindingSecurityFromEnv(idx int, binding *ftpd.Binding) bool {
  1033. isSet := false
  1034. certificateFile, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__CERTIFICATE_FILE", idx))
  1035. if ok {
  1036. binding.CertificateFile = certificateFile
  1037. isSet = true
  1038. }
  1039. certificateKeyFile, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__CERTIFICATE_KEY_FILE", idx))
  1040. if ok {
  1041. binding.CertificateKeyFile = certificateKeyFile
  1042. isSet = true
  1043. }
  1044. tlsMode, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__TLS_MODE", idx), 0)
  1045. if ok {
  1046. binding.TLSMode = int(tlsMode)
  1047. isSet = true
  1048. }
  1049. tlsSessionReuse, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__TLS_SESSION_REUSE", idx), 0)
  1050. if ok {
  1051. binding.TLSSessionReuse = int(tlsSessionReuse)
  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.resume_max_size", globalConf.Common.ResumeMaxSize)
  1742. viper.SetDefault("common.temp_path", globalConf.Common.TempPath)
  1743. viper.SetDefault("common.proxy_protocol", globalConf.Common.ProxyProtocol)
  1744. viper.SetDefault("common.proxy_allowed", globalConf.Common.ProxyAllowed)
  1745. viper.SetDefault("common.proxy_skipped", globalConf.Common.ProxySkipped)
  1746. viper.SetDefault("common.post_connect_hook", globalConf.Common.PostConnectHook)
  1747. viper.SetDefault("common.post_disconnect_hook", globalConf.Common.PostDisconnectHook)
  1748. viper.SetDefault("common.data_retention_hook", globalConf.Common.DataRetentionHook)
  1749. viper.SetDefault("common.max_total_connections", globalConf.Common.MaxTotalConnections)
  1750. viper.SetDefault("common.max_per_host_connections", globalConf.Common.MaxPerHostConnections)
  1751. viper.SetDefault("common.allowlist_status", globalConf.Common.AllowListStatus)
  1752. viper.SetDefault("common.allow_self_connections", globalConf.Common.AllowSelfConnections)
  1753. viper.SetDefault("common.defender.enabled", globalConf.Common.DefenderConfig.Enabled)
  1754. viper.SetDefault("common.defender.driver", globalConf.Common.DefenderConfig.Driver)
  1755. viper.SetDefault("common.defender.ban_time", globalConf.Common.DefenderConfig.BanTime)
  1756. viper.SetDefault("common.defender.ban_time_increment", globalConf.Common.DefenderConfig.BanTimeIncrement)
  1757. viper.SetDefault("common.defender.threshold", globalConf.Common.DefenderConfig.Threshold)
  1758. viper.SetDefault("common.defender.score_invalid", globalConf.Common.DefenderConfig.ScoreInvalid)
  1759. viper.SetDefault("common.defender.score_valid", globalConf.Common.DefenderConfig.ScoreValid)
  1760. viper.SetDefault("common.defender.score_limit_exceeded", globalConf.Common.DefenderConfig.ScoreLimitExceeded)
  1761. viper.SetDefault("common.defender.score_no_auth", globalConf.Common.DefenderConfig.ScoreNoAuth)
  1762. viper.SetDefault("common.defender.observation_time", globalConf.Common.DefenderConfig.ObservationTime)
  1763. viper.SetDefault("common.defender.entries_soft_limit", globalConf.Common.DefenderConfig.EntriesSoftLimit)
  1764. viper.SetDefault("common.defender.entries_hard_limit", globalConf.Common.DefenderConfig.EntriesHardLimit)
  1765. viper.SetDefault("common.umask", globalConf.Common.Umask)
  1766. viper.SetDefault("common.metadata.read", globalConf.Common.Metadata.Read)
  1767. viper.SetDefault("acme.email", globalConf.ACME.Email)
  1768. viper.SetDefault("acme.key_type", globalConf.ACME.KeyType)
  1769. viper.SetDefault("acme.certs_path", globalConf.ACME.CertsPath)
  1770. viper.SetDefault("acme.ca_endpoint", globalConf.ACME.CAEndpoint)
  1771. viper.SetDefault("acme.domains", globalConf.ACME.Domains)
  1772. viper.SetDefault("acme.renew_days", globalConf.ACME.RenewDays)
  1773. viper.SetDefault("acme.http01_challenge.port", globalConf.ACME.HTTP01Challenge.Port)
  1774. viper.SetDefault("acme.http01_challenge.webroot", globalConf.ACME.HTTP01Challenge.WebRoot)
  1775. viper.SetDefault("acme.http01_challenge.proxy_header", globalConf.ACME.HTTP01Challenge.ProxyHeader)
  1776. viper.SetDefault("acme.tls_alpn01_challenge.port", globalConf.ACME.TLSALPN01Challenge.Port)
  1777. viper.SetDefault("sftpd.max_auth_tries", globalConf.SFTPD.MaxAuthTries)
  1778. viper.SetDefault("sftpd.banner", globalConf.SFTPD.Banner)
  1779. viper.SetDefault("sftpd.host_keys", globalConf.SFTPD.HostKeys)
  1780. viper.SetDefault("sftpd.host_certificates", globalConf.SFTPD.HostCertificates)
  1781. viper.SetDefault("sftpd.host_key_algorithms", globalConf.SFTPD.HostKeyAlgorithms)
  1782. viper.SetDefault("sftpd.moduli", globalConf.SFTPD.Moduli)
  1783. viper.SetDefault("sftpd.kex_algorithms", globalConf.SFTPD.KexAlgorithms)
  1784. viper.SetDefault("sftpd.ciphers", globalConf.SFTPD.Ciphers)
  1785. viper.SetDefault("sftpd.macs", globalConf.SFTPD.MACs)
  1786. viper.SetDefault("sftpd.trusted_user_ca_keys", globalConf.SFTPD.TrustedUserCAKeys)
  1787. viper.SetDefault("sftpd.revoked_user_certs_file", globalConf.SFTPD.RevokedUserCertsFile)
  1788. viper.SetDefault("sftpd.login_banner_file", globalConf.SFTPD.LoginBannerFile)
  1789. viper.SetDefault("sftpd.enabled_ssh_commands", sftpd.GetDefaultSSHCommands())
  1790. viper.SetDefault("sftpd.keyboard_interactive_authentication", globalConf.SFTPD.KeyboardInteractiveAuthentication)
  1791. viper.SetDefault("sftpd.keyboard_interactive_auth_hook", globalConf.SFTPD.KeyboardInteractiveHook)
  1792. viper.SetDefault("sftpd.password_authentication", globalConf.SFTPD.PasswordAuthentication)
  1793. viper.SetDefault("sftpd.folder_prefix", globalConf.SFTPD.FolderPrefix)
  1794. viper.SetDefault("ftpd.banner", globalConf.FTPD.Banner)
  1795. viper.SetDefault("ftpd.banner_file", globalConf.FTPD.BannerFile)
  1796. viper.SetDefault("ftpd.active_transfers_port_non_20", globalConf.FTPD.ActiveTransfersPortNon20)
  1797. viper.SetDefault("ftpd.passive_port_range.start", globalConf.FTPD.PassivePortRange.Start)
  1798. viper.SetDefault("ftpd.passive_port_range.end", globalConf.FTPD.PassivePortRange.End)
  1799. viper.SetDefault("ftpd.disable_active_mode", globalConf.FTPD.DisableActiveMode)
  1800. viper.SetDefault("ftpd.enable_site", globalConf.FTPD.EnableSite)
  1801. viper.SetDefault("ftpd.hash_support", globalConf.FTPD.HASHSupport)
  1802. viper.SetDefault("ftpd.combine_support", globalConf.FTPD.CombineSupport)
  1803. viper.SetDefault("ftpd.certificate_file", globalConf.FTPD.CertificateFile)
  1804. viper.SetDefault("ftpd.certificate_key_file", globalConf.FTPD.CertificateKeyFile)
  1805. viper.SetDefault("ftpd.ca_certificates", globalConf.FTPD.CACertificates)
  1806. viper.SetDefault("ftpd.ca_revocation_lists", globalConf.FTPD.CARevocationLists)
  1807. viper.SetDefault("webdavd.certificate_file", globalConf.WebDAVD.CertificateFile)
  1808. viper.SetDefault("webdavd.certificate_key_file", globalConf.WebDAVD.CertificateKeyFile)
  1809. viper.SetDefault("webdavd.ca_certificates", globalConf.WebDAVD.CACertificates)
  1810. viper.SetDefault("webdavd.ca_revocation_lists", globalConf.WebDAVD.CARevocationLists)
  1811. viper.SetDefault("webdavd.cors.enabled", globalConf.WebDAVD.Cors.Enabled)
  1812. viper.SetDefault("webdavd.cors.allowed_origins", globalConf.WebDAVD.Cors.AllowedOrigins)
  1813. viper.SetDefault("webdavd.cors.allowed_methods", globalConf.WebDAVD.Cors.AllowedMethods)
  1814. viper.SetDefault("webdavd.cors.allowed_headers", globalConf.WebDAVD.Cors.AllowedHeaders)
  1815. viper.SetDefault("webdavd.cors.exposed_headers", globalConf.WebDAVD.Cors.ExposedHeaders)
  1816. viper.SetDefault("webdavd.cors.allow_credentials", globalConf.WebDAVD.Cors.AllowCredentials)
  1817. viper.SetDefault("webdavd.cors.options_passthrough", globalConf.WebDAVD.Cors.OptionsPassthrough)
  1818. viper.SetDefault("webdavd.cors.options_success_status", globalConf.WebDAVD.Cors.OptionsSuccessStatus)
  1819. viper.SetDefault("webdavd.cors.allow_private_network", globalConf.WebDAVD.Cors.AllowPrivateNetwork)
  1820. viper.SetDefault("webdavd.cors.max_age", globalConf.WebDAVD.Cors.MaxAge)
  1821. viper.SetDefault("webdavd.cache.users.expiration_time", globalConf.WebDAVD.Cache.Users.ExpirationTime)
  1822. viper.SetDefault("webdavd.cache.users.max_size", globalConf.WebDAVD.Cache.Users.MaxSize)
  1823. viper.SetDefault("webdavd.cache.mime_types.enabled", globalConf.WebDAVD.Cache.MimeTypes.Enabled)
  1824. viper.SetDefault("webdavd.cache.mime_types.max_size", globalConf.WebDAVD.Cache.MimeTypes.MaxSize)
  1825. viper.SetDefault("webdavd.cache.mime_types.custom_mappings", globalConf.WebDAVD.Cache.MimeTypes.CustomMappings)
  1826. viper.SetDefault("data_provider.driver", globalConf.ProviderConf.Driver)
  1827. viper.SetDefault("data_provider.name", globalConf.ProviderConf.Name)
  1828. viper.SetDefault("data_provider.host", globalConf.ProviderConf.Host)
  1829. viper.SetDefault("data_provider.port", globalConf.ProviderConf.Port)
  1830. viper.SetDefault("data_provider.username", globalConf.ProviderConf.Username)
  1831. viper.SetDefault("data_provider.password", globalConf.ProviderConf.Password)
  1832. viper.SetDefault("data_provider.sslmode", globalConf.ProviderConf.SSLMode)
  1833. viper.SetDefault("data_provider.disable_sni", globalConf.ProviderConf.DisableSNI)
  1834. viper.SetDefault("data_provider.target_session_attrs", globalConf.ProviderConf.TargetSessionAttrs)
  1835. viper.SetDefault("data_provider.root_cert", globalConf.ProviderConf.RootCert)
  1836. viper.SetDefault("data_provider.client_cert", globalConf.ProviderConf.ClientCert)
  1837. viper.SetDefault("data_provider.client_key", globalConf.ProviderConf.ClientKey)
  1838. viper.SetDefault("data_provider.connection_string", globalConf.ProviderConf.ConnectionString)
  1839. viper.SetDefault("data_provider.sql_tables_prefix", globalConf.ProviderConf.SQLTablesPrefix)
  1840. viper.SetDefault("data_provider.track_quota", globalConf.ProviderConf.TrackQuota)
  1841. viper.SetDefault("data_provider.pool_size", globalConf.ProviderConf.PoolSize)
  1842. viper.SetDefault("data_provider.users_base_dir", globalConf.ProviderConf.UsersBaseDir)
  1843. viper.SetDefault("data_provider.actions.execute_on", globalConf.ProviderConf.Actions.ExecuteOn)
  1844. viper.SetDefault("data_provider.actions.execute_for", globalConf.ProviderConf.Actions.ExecuteFor)
  1845. viper.SetDefault("data_provider.actions.hook", globalConf.ProviderConf.Actions.Hook)
  1846. viper.SetDefault("data_provider.external_auth_hook", globalConf.ProviderConf.ExternalAuthHook)
  1847. viper.SetDefault("data_provider.external_auth_scope", globalConf.ProviderConf.ExternalAuthScope)
  1848. viper.SetDefault("data_provider.pre_login_hook", globalConf.ProviderConf.PreLoginHook)
  1849. viper.SetDefault("data_provider.post_login_hook", globalConf.ProviderConf.PostLoginHook)
  1850. viper.SetDefault("data_provider.post_login_scope", globalConf.ProviderConf.PostLoginScope)
  1851. viper.SetDefault("data_provider.check_password_hook", globalConf.ProviderConf.CheckPasswordHook)
  1852. viper.SetDefault("data_provider.check_password_scope", globalConf.ProviderConf.CheckPasswordScope)
  1853. viper.SetDefault("data_provider.password_hashing.bcrypt_options.cost", globalConf.ProviderConf.PasswordHashing.BcryptOptions.Cost)
  1854. viper.SetDefault("data_provider.password_hashing.argon2_options.memory", globalConf.ProviderConf.PasswordHashing.Argon2Options.Memory)
  1855. viper.SetDefault("data_provider.password_hashing.argon2_options.iterations", globalConf.ProviderConf.PasswordHashing.Argon2Options.Iterations)
  1856. viper.SetDefault("data_provider.password_hashing.argon2_options.parallelism", globalConf.ProviderConf.PasswordHashing.Argon2Options.Parallelism)
  1857. viper.SetDefault("data_provider.password_hashing.algo", globalConf.ProviderConf.PasswordHashing.Algo)
  1858. viper.SetDefault("data_provider.password_validation.admins.min_entropy", globalConf.ProviderConf.PasswordValidation.Admins.MinEntropy)
  1859. viper.SetDefault("data_provider.password_validation.users.min_entropy", globalConf.ProviderConf.PasswordValidation.Users.MinEntropy)
  1860. viper.SetDefault("data_provider.password_caching", globalConf.ProviderConf.PasswordCaching)
  1861. viper.SetDefault("data_provider.update_mode", globalConf.ProviderConf.UpdateMode)
  1862. viper.SetDefault("data_provider.delayed_quota_update", globalConf.ProviderConf.DelayedQuotaUpdate)
  1863. viper.SetDefault("data_provider.create_default_admin", globalConf.ProviderConf.CreateDefaultAdmin)
  1864. viper.SetDefault("data_provider.naming_rules", globalConf.ProviderConf.NamingRules)
  1865. viper.SetDefault("data_provider.is_shared", globalConf.ProviderConf.IsShared)
  1866. viper.SetDefault("data_provider.node.host", globalConf.ProviderConf.Node.Host)
  1867. viper.SetDefault("data_provider.node.port", globalConf.ProviderConf.Node.Port)
  1868. viper.SetDefault("data_provider.node.proto", globalConf.ProviderConf.Node.Proto)
  1869. viper.SetDefault("data_provider.backups_path", globalConf.ProviderConf.BackupsPath)
  1870. viper.SetDefault("httpd.templates_path", globalConf.HTTPDConfig.TemplatesPath)
  1871. viper.SetDefault("httpd.static_files_path", globalConf.HTTPDConfig.StaticFilesPath)
  1872. viper.SetDefault("httpd.openapi_path", globalConf.HTTPDConfig.OpenAPIPath)
  1873. viper.SetDefault("httpd.web_root", globalConf.HTTPDConfig.WebRoot)
  1874. viper.SetDefault("httpd.certificate_file", globalConf.HTTPDConfig.CertificateFile)
  1875. viper.SetDefault("httpd.certificate_key_file", globalConf.HTTPDConfig.CertificateKeyFile)
  1876. viper.SetDefault("httpd.ca_certificates", globalConf.HTTPDConfig.CACertificates)
  1877. viper.SetDefault("httpd.ca_revocation_lists", globalConf.HTTPDConfig.CARevocationLists)
  1878. viper.SetDefault("httpd.signing_passphrase", globalConf.HTTPDConfig.SigningPassphrase)
  1879. viper.SetDefault("httpd.token_validation", globalConf.HTTPDConfig.TokenValidation)
  1880. viper.SetDefault("httpd.max_upload_file_size", globalConf.HTTPDConfig.MaxUploadFileSize)
  1881. viper.SetDefault("httpd.cors.enabled", globalConf.HTTPDConfig.Cors.Enabled)
  1882. viper.SetDefault("httpd.cors.allowed_origins", globalConf.HTTPDConfig.Cors.AllowedOrigins)
  1883. viper.SetDefault("httpd.cors.allowed_methods", globalConf.HTTPDConfig.Cors.AllowedMethods)
  1884. viper.SetDefault("httpd.cors.allowed_headers", globalConf.HTTPDConfig.Cors.AllowedHeaders)
  1885. viper.SetDefault("httpd.cors.exposed_headers", globalConf.HTTPDConfig.Cors.ExposedHeaders)
  1886. viper.SetDefault("httpd.cors.allow_credentials", globalConf.HTTPDConfig.Cors.AllowCredentials)
  1887. viper.SetDefault("httpd.cors.max_age", globalConf.HTTPDConfig.Cors.MaxAge)
  1888. viper.SetDefault("httpd.cors.options_passthrough", globalConf.HTTPDConfig.Cors.OptionsPassthrough)
  1889. viper.SetDefault("httpd.cors.options_success_status", globalConf.HTTPDConfig.Cors.OptionsSuccessStatus)
  1890. viper.SetDefault("httpd.cors.allow_private_network", globalConf.HTTPDConfig.Cors.AllowPrivateNetwork)
  1891. viper.SetDefault("httpd.setup.installation_code", globalConf.HTTPDConfig.Setup.InstallationCode)
  1892. viper.SetDefault("httpd.setup.installation_code_hint", globalConf.HTTPDConfig.Setup.InstallationCodeHint)
  1893. viper.SetDefault("httpd.hide_support_link", globalConf.HTTPDConfig.HideSupportLink)
  1894. viper.SetDefault("http.timeout", globalConf.HTTPConfig.Timeout)
  1895. viper.SetDefault("http.retry_wait_min", globalConf.HTTPConfig.RetryWaitMin)
  1896. viper.SetDefault("http.retry_wait_max", globalConf.HTTPConfig.RetryWaitMax)
  1897. viper.SetDefault("http.retry_max", globalConf.HTTPConfig.RetryMax)
  1898. viper.SetDefault("http.ca_certificates", globalConf.HTTPConfig.CACertificates)
  1899. viper.SetDefault("http.skip_tls_verify", globalConf.HTTPConfig.SkipTLSVerify)
  1900. viper.SetDefault("command.timeout", globalConf.CommandConfig.Timeout)
  1901. viper.SetDefault("command.env", globalConf.CommandConfig.Env)
  1902. viper.SetDefault("kms.secrets.url", globalConf.KMSConfig.Secrets.URL)
  1903. viper.SetDefault("kms.secrets.master_key", globalConf.KMSConfig.Secrets.MasterKeyString)
  1904. viper.SetDefault("kms.secrets.master_key_path", globalConf.KMSConfig.Secrets.MasterKeyPath)
  1905. viper.SetDefault("telemetry.bind_port", globalConf.TelemetryConfig.BindPort)
  1906. viper.SetDefault("telemetry.bind_address", globalConf.TelemetryConfig.BindAddress)
  1907. viper.SetDefault("telemetry.enable_profiler", globalConf.TelemetryConfig.EnableProfiler)
  1908. viper.SetDefault("telemetry.auth_user_file", globalConf.TelemetryConfig.AuthUserFile)
  1909. viper.SetDefault("telemetry.certificate_file", globalConf.TelemetryConfig.CertificateFile)
  1910. viper.SetDefault("telemetry.certificate_key_file", globalConf.TelemetryConfig.CertificateKeyFile)
  1911. viper.SetDefault("telemetry.min_tls_version", globalConf.TelemetryConfig.MinTLSVersion)
  1912. viper.SetDefault("telemetry.tls_cipher_suites", globalConf.TelemetryConfig.TLSCipherSuites)
  1913. viper.SetDefault("smtp.host", globalConf.SMTPConfig.Host)
  1914. viper.SetDefault("smtp.port", globalConf.SMTPConfig.Port)
  1915. viper.SetDefault("smtp.from", globalConf.SMTPConfig.From)
  1916. viper.SetDefault("smtp.user", globalConf.SMTPConfig.User)
  1917. viper.SetDefault("smtp.password", globalConf.SMTPConfig.Password)
  1918. viper.SetDefault("smtp.auth_type", globalConf.SMTPConfig.AuthType)
  1919. viper.SetDefault("smtp.encryption", globalConf.SMTPConfig.Encryption)
  1920. viper.SetDefault("smtp.domain", globalConf.SMTPConfig.Domain)
  1921. viper.SetDefault("smtp.templates_path", globalConf.SMTPConfig.TemplatesPath)
  1922. }
  1923. func lookupBoolFromEnv(envName string) (bool, bool) {
  1924. value, ok := os.LookupEnv(envName)
  1925. if ok {
  1926. converted, err := strconv.ParseBool(strings.TrimSpace(value))
  1927. if err == nil {
  1928. return converted, ok
  1929. }
  1930. }
  1931. return false, false
  1932. }
  1933. func lookupIntFromEnv(envName string, bitSize int) (int64, bool) {
  1934. value, ok := os.LookupEnv(envName)
  1935. if ok {
  1936. converted, err := strconv.ParseInt(strings.TrimSpace(value), 10, bitSize)
  1937. if err == nil {
  1938. return converted, ok
  1939. }
  1940. }
  1941. return 0, false
  1942. }
  1943. func lookupStringListFromEnv(envName string) ([]string, bool) {
  1944. value, ok := os.LookupEnv(envName)
  1945. if ok {
  1946. var result []string
  1947. for _, v := range strings.Split(value, ",") {
  1948. val := strings.TrimSpace(v)
  1949. if val != "" {
  1950. result = append(result, val)
  1951. }
  1952. }
  1953. return result, true
  1954. }
  1955. return nil, false
  1956. }