config.go 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148
  1. // Copyright (C) 2019-2022 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. // Package config manages the configuration
  15. package config
  16. import (
  17. "errors"
  18. "fmt"
  19. "os"
  20. "path/filepath"
  21. "strconv"
  22. "strings"
  23. "github.com/spf13/viper"
  24. "github.com/subosito/gotenv"
  25. "github.com/drakkan/sftpgo/v2/internal/acme"
  26. "github.com/drakkan/sftpgo/v2/internal/command"
  27. "github.com/drakkan/sftpgo/v2/internal/common"
  28. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  29. "github.com/drakkan/sftpgo/v2/internal/ftpd"
  30. "github.com/drakkan/sftpgo/v2/internal/httpclient"
  31. "github.com/drakkan/sftpgo/v2/internal/httpd"
  32. "github.com/drakkan/sftpgo/v2/internal/kms"
  33. "github.com/drakkan/sftpgo/v2/internal/logger"
  34. "github.com/drakkan/sftpgo/v2/internal/mfa"
  35. "github.com/drakkan/sftpgo/v2/internal/plugin"
  36. "github.com/drakkan/sftpgo/v2/internal/sftpd"
  37. "github.com/drakkan/sftpgo/v2/internal/smtp"
  38. "github.com/drakkan/sftpgo/v2/internal/telemetry"
  39. "github.com/drakkan/sftpgo/v2/internal/util"
  40. "github.com/drakkan/sftpgo/v2/internal/version"
  41. "github.com/drakkan/sftpgo/v2/internal/webdavd"
  42. )
  43. const (
  44. logSender = "config"
  45. // configName defines the name for config file.
  46. // This name does not include the extension, viper will search for files
  47. // with supported extensions such as "sftpgo.json", "sftpgo.yaml" and so on
  48. configName = "sftpgo"
  49. // ConfigEnvPrefix defines a prefix that environment variables will use
  50. configEnvPrefix = "sftpgo"
  51. )
  52. var (
  53. globalConf globalConfig
  54. defaultSFTPDBanner = fmt.Sprintf("SFTPGo_%v", version.Get().Version)
  55. defaultFTPDBanner = fmt.Sprintf("SFTPGo %v ready", version.Get().Version)
  56. defaultInstallCodeHint = "Installation code"
  57. defaultSFTPDBinding = sftpd.Binding{
  58. Address: "",
  59. Port: 2022,
  60. ApplyProxyConfig: true,
  61. }
  62. defaultFTPDBinding = ftpd.Binding{
  63. Address: "",
  64. Port: 0,
  65. ApplyProxyConfig: true,
  66. TLSMode: 0,
  67. CertificateFile: "",
  68. CertificateKeyFile: "",
  69. MinTLSVersion: 12,
  70. ForcePassiveIP: "",
  71. PassiveIPOverrides: nil,
  72. ClientAuthType: 0,
  73. TLSCipherSuites: nil,
  74. PassiveConnectionsSecurity: 0,
  75. ActiveConnectionsSecurity: 0,
  76. Debug: false,
  77. }
  78. defaultWebDAVDBinding = webdavd.Binding{
  79. Address: "",
  80. Port: 0,
  81. EnableHTTPS: false,
  82. CertificateFile: "",
  83. CertificateKeyFile: "",
  84. MinTLSVersion: 12,
  85. ClientAuthType: 0,
  86. TLSCipherSuites: nil,
  87. Prefix: "",
  88. ProxyAllowed: nil,
  89. ClientIPProxyHeader: "",
  90. ClientIPHeaderDepth: 0,
  91. DisableWWWAuthHeader: false,
  92. }
  93. defaultHTTPDBinding = httpd.Binding{
  94. Address: "",
  95. Port: 8080,
  96. EnableWebAdmin: true,
  97. EnableWebClient: true,
  98. EnableRESTAPI: true,
  99. EnabledLoginMethods: 0,
  100. EnableHTTPS: false,
  101. CertificateFile: "",
  102. CertificateKeyFile: "",
  103. MinTLSVersion: 12,
  104. ClientAuthType: 0,
  105. TLSCipherSuites: nil,
  106. ProxyAllowed: nil,
  107. ClientIPProxyHeader: "",
  108. ClientIPHeaderDepth: 0,
  109. HideLoginURL: 0,
  110. RenderOpenAPI: true,
  111. WebClientIntegrations: nil,
  112. OIDC: httpd.OIDC{
  113. ClientID: "",
  114. ClientSecret: "",
  115. ConfigURL: "",
  116. RedirectBaseURL: "",
  117. UsernameField: "",
  118. RoleField: "",
  119. ImplicitRoles: false,
  120. Scopes: []string{"openid", "profile", "email"},
  121. CustomFields: []string{},
  122. InsecureSkipSignatureCheck: false,
  123. Debug: false,
  124. },
  125. Security: httpd.SecurityConf{
  126. Enabled: false,
  127. AllowedHosts: nil,
  128. AllowedHostsAreRegex: false,
  129. HostsProxyHeaders: nil,
  130. HTTPSRedirect: false,
  131. HTTPSHost: "",
  132. HTTPSProxyHeaders: nil,
  133. STSSeconds: 0,
  134. STSIncludeSubdomains: false,
  135. STSPreload: false,
  136. ContentTypeNosniff: false,
  137. ContentSecurityPolicy: "",
  138. PermissionsPolicy: "",
  139. CrossOriginOpenerPolicy: "",
  140. ExpectCTHeader: "",
  141. },
  142. Branding: httpd.Branding{},
  143. }
  144. defaultRateLimiter = common.RateLimiterConfig{
  145. Average: 0,
  146. Period: 1000,
  147. Burst: 1,
  148. Type: 2,
  149. Protocols: []string{common.ProtocolSSH, common.ProtocolFTP, common.ProtocolWebDAV, common.ProtocolHTTP},
  150. AllowList: []string{},
  151. GenerateDefenderEvents: false,
  152. EntriesSoftLimit: 100,
  153. EntriesHardLimit: 150,
  154. }
  155. defaultTOTP = mfa.TOTPConfig{
  156. Name: "Default",
  157. Issuer: "SFTPGo",
  158. Algo: mfa.TOTPAlgoSHA1,
  159. }
  160. )
  161. type globalConfig struct {
  162. Common common.Configuration `json:"common" mapstructure:"common"`
  163. ACME acme.Configuration `json:"acme" mapstructure:"acme"`
  164. SFTPD sftpd.Configuration `json:"sftpd" mapstructure:"sftpd"`
  165. FTPD ftpd.Configuration `json:"ftpd" mapstructure:"ftpd"`
  166. WebDAVD webdavd.Configuration `json:"webdavd" mapstructure:"webdavd"`
  167. ProviderConf dataprovider.Config `json:"data_provider" mapstructure:"data_provider"`
  168. HTTPDConfig httpd.Conf `json:"httpd" mapstructure:"httpd"`
  169. HTTPConfig httpclient.Config `json:"http" mapstructure:"http"`
  170. CommandConfig command.Config `json:"command" mapstructure:"command"`
  171. KMSConfig kms.Configuration `json:"kms" mapstructure:"kms"`
  172. MFAConfig mfa.Config `json:"mfa" mapstructure:"mfa"`
  173. TelemetryConfig telemetry.Conf `json:"telemetry" mapstructure:"telemetry"`
  174. PluginsConfig []plugin.Config `json:"plugins" mapstructure:"plugins"`
  175. SMTPConfig smtp.Config `json:"smtp" mapstructure:"smtp"`
  176. }
  177. func init() {
  178. Init()
  179. }
  180. // Init initializes the global configuration.
  181. // It is not supposed to be called outside of this package.
  182. // It is exported to minimize refactoring efforts. Will eventually disappear.
  183. func Init() {
  184. // create a default configuration to use if no config file is provided
  185. globalConf = globalConfig{
  186. Common: common.Configuration{
  187. IdleTimeout: 15,
  188. UploadMode: 0,
  189. Actions: common.ProtocolActions{
  190. ExecuteOn: []string{},
  191. ExecuteSync: []string{},
  192. Hook: "",
  193. },
  194. SetstatMode: 0,
  195. TempPath: "",
  196. ProxyProtocol: 0,
  197. ProxyAllowed: []string{},
  198. PostConnectHook: "",
  199. PostDisconnectHook: "",
  200. DataRetentionHook: "",
  201. MaxTotalConnections: 0,
  202. MaxPerHostConnections: 20,
  203. WhiteListFile: "",
  204. AllowSelfConnections: 0,
  205. DefenderConfig: common.DefenderConfig{
  206. Enabled: false,
  207. Driver: common.DefenderDriverMemory,
  208. BanTime: 30,
  209. BanTimeIncrement: 50,
  210. Threshold: 15,
  211. ScoreInvalid: 2,
  212. ScoreValid: 1,
  213. ScoreLimitExceeded: 3,
  214. ScoreNoAuth: 2,
  215. ObservationTime: 30,
  216. EntriesSoftLimit: 100,
  217. EntriesHardLimit: 150,
  218. SafeListFile: "",
  219. BlockListFile: "",
  220. SafeList: []string{},
  221. BlockList: []string{},
  222. },
  223. RateLimitersConfig: []common.RateLimiterConfig{defaultRateLimiter},
  224. },
  225. ACME: acme.Configuration{
  226. Email: "",
  227. KeyType: "4096",
  228. CertsPath: "certs",
  229. CAEndpoint: "https://acme-v02.api.letsencrypt.org/directory",
  230. Domains: []string{},
  231. RenewDays: 30,
  232. HTTP01Challenge: acme.HTTP01Challenge{
  233. Port: 80,
  234. WebRoot: "",
  235. ProxyHeader: "",
  236. },
  237. TLSALPN01Challenge: acme.TLSALPN01Challenge{
  238. Port: 0,
  239. },
  240. },
  241. SFTPD: sftpd.Configuration{
  242. Bindings: []sftpd.Binding{defaultSFTPDBinding},
  243. MaxAuthTries: 0,
  244. Banner: defaultSFTPDBanner,
  245. HostKeys: []string{},
  246. HostCertificates: []string{},
  247. HostKeyAlgorithms: []string{},
  248. Moduli: []string{},
  249. KexAlgorithms: []string{},
  250. Ciphers: []string{},
  251. MACs: []string{},
  252. TrustedUserCAKeys: []string{},
  253. RevokedUserCertsFile: "",
  254. LoginBannerFile: "",
  255. EnabledSSHCommands: []string{},
  256. KeyboardInteractiveAuthentication: false,
  257. KeyboardInteractiveHook: "",
  258. PasswordAuthentication: true,
  259. FolderPrefix: "",
  260. },
  261. FTPD: ftpd.Configuration{
  262. Bindings: []ftpd.Binding{defaultFTPDBinding},
  263. Banner: defaultFTPDBanner,
  264. BannerFile: "",
  265. ActiveTransfersPortNon20: true,
  266. PassivePortRange: ftpd.PortRange{
  267. Start: 50000,
  268. End: 50100,
  269. },
  270. DisableActiveMode: false,
  271. EnableSite: false,
  272. HASHSupport: 0,
  273. CombineSupport: 0,
  274. CertificateFile: "",
  275. CertificateKeyFile: "",
  276. CACertificates: []string{},
  277. CARevocationLists: []string{},
  278. },
  279. WebDAVD: webdavd.Configuration{
  280. Bindings: []webdavd.Binding{defaultWebDAVDBinding},
  281. CertificateFile: "",
  282. CertificateKeyFile: "",
  283. CACertificates: []string{},
  284. CARevocationLists: []string{},
  285. Cors: webdavd.CorsConfig{
  286. Enabled: false,
  287. AllowedOrigins: []string{},
  288. AllowedMethods: []string{},
  289. AllowedHeaders: []string{},
  290. ExposedHeaders: []string{},
  291. AllowCredentials: false,
  292. MaxAge: 0,
  293. OptionsPassthrough: false,
  294. OptionsSuccessStatus: 0,
  295. AllowPrivateNetwork: false,
  296. },
  297. Cache: webdavd.Cache{
  298. Users: webdavd.UsersCacheConfig{
  299. ExpirationTime: 0,
  300. MaxSize: 50,
  301. },
  302. MimeTypes: webdavd.MimeCacheConfig{
  303. Enabled: true,
  304. MaxSize: 1000,
  305. },
  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: 1048576000,
  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. err = gotenv.Load(envFile)
  621. if err != nil {
  622. logger.Error(logSender, "", "unable to load env vars from file %q, err: %v", envFile, err)
  623. } else {
  624. logger.Info(logSender, "", "set env vars from file %q", envFile)
  625. }
  626. }
  627. }
  628. }
  629. func checkOverrideDefaultSettings() {
  630. // for slices we need to set the defaults to nil if the key is set in the config file,
  631. // otherwise the values are merged and not replaced as expected
  632. rateLimiters := viper.Get("common.rate_limiters")
  633. if val, ok := rateLimiters.([]any); ok {
  634. if len(val) > 0 {
  635. if rl, ok := val[0].(map[string]any); ok {
  636. if _, ok := rl["protocols"]; ok {
  637. globalConf.Common.RateLimitersConfig[0].Protocols = nil
  638. }
  639. }
  640. }
  641. }
  642. httpdBindings := viper.Get("httpd.bindings")
  643. if val, ok := httpdBindings.([]any); ok {
  644. if len(val) > 0 {
  645. if binding, ok := val[0].(map[string]any); ok {
  646. if val, ok := binding["oidc"]; ok {
  647. if oidc, ok := val.(map[string]any); ok {
  648. if _, ok := oidc["scopes"]; ok {
  649. globalConf.HTTPDConfig.Bindings[0].OIDC.Scopes = nil
  650. }
  651. }
  652. }
  653. }
  654. }
  655. }
  656. if util.Contains(viper.AllKeys(), "mfa.totp") {
  657. globalConf.MFAConfig.TOTP = nil
  658. }
  659. }
  660. // LoadConfig loads the configuration
  661. // configDir will be added to the configuration search paths.
  662. // The search path contains by default the current directory and on linux it contains
  663. // $HOME/.config/sftpgo and /etc/sftpgo too.
  664. // configFile is an absolute or relative path (to the config dir) to the configuration file.
  665. func LoadConfig(configDir, configFile string) error {
  666. var err error
  667. readEnvFiles(configDir)
  668. viper.AddConfigPath(configDir)
  669. setViperAdditionalConfigPaths()
  670. viper.AddConfigPath(".")
  671. setConfigFile(configDir, configFile)
  672. if err = viper.ReadInConfig(); err != nil {
  673. // if the user specify a configuration file we get os.ErrNotExist.
  674. // viper.ConfigFileNotFoundError is returned if viper is unable
  675. // to find sftpgo.{json,yaml, etc..} in any of the search paths
  676. if errors.As(err, &viper.ConfigFileNotFoundError{}) {
  677. logger.Debug(logSender, "", "no configuration file found")
  678. } else {
  679. // should we return the error and not start here?
  680. logger.Warn(logSender, "", "error loading configuration file: %v", err)
  681. logger.WarnToConsole("error loading configuration file: %v", err)
  682. }
  683. }
  684. checkOverrideDefaultSettings()
  685. err = viper.Unmarshal(&globalConf)
  686. if err != nil {
  687. logger.Warn(logSender, "", "error parsing configuration file: %v", err)
  688. logger.WarnToConsole("error parsing configuration file: %v", err)
  689. return err
  690. }
  691. // viper only supports slice of strings from env vars, so we use our custom method
  692. loadBindingsFromEnv()
  693. resetInvalidConfigs()
  694. logger.Debug(logSender, "", "config file used: '%#v', config loaded: %+v", viper.ConfigFileUsed(), getRedactedGlobalConf())
  695. return nil
  696. }
  697. func isUploadModeValid() bool {
  698. return globalConf.Common.UploadMode >= 0 && globalConf.Common.UploadMode <= 2
  699. }
  700. func isProxyProtocolValid() bool {
  701. return globalConf.Common.ProxyProtocol >= 0 && globalConf.Common.ProxyProtocol <= 2
  702. }
  703. func isExternalAuthScopeValid() bool {
  704. return globalConf.ProviderConf.ExternalAuthScope >= 0 && globalConf.ProviderConf.ExternalAuthScope <= 15
  705. }
  706. func resetInvalidConfigs() {
  707. if strings.TrimSpace(globalConf.SFTPD.Banner) == "" {
  708. globalConf.SFTPD.Banner = defaultSFTPDBanner
  709. }
  710. if strings.TrimSpace(globalConf.FTPD.Banner) == "" {
  711. globalConf.FTPD.Banner = defaultFTPDBanner
  712. }
  713. if strings.TrimSpace(globalConf.HTTPDConfig.Setup.InstallationCodeHint) == "" {
  714. globalConf.HTTPDConfig.Setup.InstallationCodeHint = defaultInstallCodeHint
  715. }
  716. if globalConf.ProviderConf.UsersBaseDir != "" && !util.IsFileInputValid(globalConf.ProviderConf.UsersBaseDir) {
  717. warn := fmt.Sprintf("invalid users base dir %#v will be ignored", globalConf.ProviderConf.UsersBaseDir)
  718. globalConf.ProviderConf.UsersBaseDir = ""
  719. logger.Warn(logSender, "", "Non-fatal configuration error: %v", warn)
  720. logger.WarnToConsole("Non-fatal configuration error: %v", warn)
  721. }
  722. if !isUploadModeValid() {
  723. warn := fmt.Sprintf("invalid upload_mode 0, 1 and 2 are supported, configured: %v reset upload_mode to 0",
  724. globalConf.Common.UploadMode)
  725. globalConf.Common.UploadMode = 0
  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 %#v, "+
  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))
  804. if ok {
  805. rtlConfig.Average = average
  806. isSet = true
  807. }
  808. period, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__PERIOD", idx))
  809. if ok {
  810. rtlConfig.Period = period
  811. isSet = true
  812. }
  813. burst, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__BURST", idx))
  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))
  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. allowList, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_COMMON__RATE_LIMITERS__%v__ALLOW_LIST", idx))
  829. if ok {
  830. rtlConfig.AllowList = allowList
  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))
  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))
  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))
  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. notifierRetryMaxTime, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__RETRY_MAX_TIME", idx))
  897. if ok {
  898. pluginConfig.NotifierOptions.RetryMaxTime = int(notifierRetryMaxTime)
  899. isSet = true
  900. }
  901. notifierRetryQueueMaxSize, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__NOTIFIER_OPTIONS__RETRY_QUEUE_MAX_SIZE", idx))
  902. if ok {
  903. pluginConfig.NotifierOptions.RetryQueueMaxSize = int(notifierRetryQueueMaxSize)
  904. isSet = true
  905. }
  906. return isSet
  907. }
  908. func getPluginsFromEnv(idx int) {
  909. pluginConfig := plugin.Config{}
  910. if len(globalConf.PluginsConfig) > idx {
  911. pluginConfig = globalConf.PluginsConfig[idx]
  912. }
  913. isSet := false
  914. pluginType, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__TYPE", idx))
  915. if ok {
  916. pluginConfig.Type = pluginType
  917. isSet = true
  918. }
  919. if getNotifierPluginFromEnv(idx, &pluginConfig) {
  920. isSet = true
  921. }
  922. if getKMSPluginFromEnv(idx, &pluginConfig) {
  923. isSet = true
  924. }
  925. if getAuthPluginFromEnv(idx, &pluginConfig) {
  926. isSet = true
  927. }
  928. cmd, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__CMD", idx))
  929. if ok {
  930. pluginConfig.Cmd = cmd
  931. isSet = true
  932. }
  933. cmdArgs, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__ARGS", idx))
  934. if ok {
  935. pluginConfig.Args = cmdArgs
  936. isSet = true
  937. }
  938. pluginHash, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__SHA256SUM", idx))
  939. if ok {
  940. pluginConfig.SHA256Sum = pluginHash
  941. isSet = true
  942. }
  943. autoMTLS, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_PLUGINS__%v__AUTO_MTLS", idx))
  944. if ok {
  945. pluginConfig.AutoMTLS = autoMTLS
  946. isSet = true
  947. }
  948. if isSet {
  949. if len(globalConf.PluginsConfig) > idx {
  950. globalConf.PluginsConfig[idx] = pluginConfig
  951. } else {
  952. globalConf.PluginsConfig = append(globalConf.PluginsConfig, pluginConfig)
  953. }
  954. }
  955. }
  956. func getSFTPDBindindFromEnv(idx int) {
  957. binding := defaultSFTPDBinding
  958. if len(globalConf.SFTPD.Bindings) > idx {
  959. binding = globalConf.SFTPD.Bindings[idx]
  960. }
  961. isSet := false
  962. port, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_SFTPD__BINDINGS__%v__PORT", idx))
  963. if ok {
  964. binding.Port = int(port)
  965. isSet = true
  966. }
  967. address, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_SFTPD__BINDINGS__%v__ADDRESS", idx))
  968. if ok {
  969. binding.Address = address
  970. isSet = true
  971. }
  972. applyProxyConfig, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_SFTPD__BINDINGS__%v__APPLY_PROXY_CONFIG", idx))
  973. if ok {
  974. binding.ApplyProxyConfig = applyProxyConfig
  975. isSet = true
  976. }
  977. if isSet {
  978. if len(globalConf.SFTPD.Bindings) > idx {
  979. globalConf.SFTPD.Bindings[idx] = binding
  980. } else {
  981. globalConf.SFTPD.Bindings = append(globalConf.SFTPD.Bindings, binding)
  982. }
  983. }
  984. }
  985. func getFTPDPassiveIPOverridesFromEnv(idx int) []ftpd.PassiveIPOverride {
  986. var overrides []ftpd.PassiveIPOverride
  987. if len(globalConf.FTPD.Bindings) > idx {
  988. overrides = globalConf.FTPD.Bindings[idx].PassiveIPOverrides
  989. }
  990. for subIdx := 0; subIdx < 10; subIdx++ {
  991. var override ftpd.PassiveIPOverride
  992. var replace bool
  993. if len(globalConf.FTPD.Bindings) > idx && len(globalConf.FTPD.Bindings[idx].PassiveIPOverrides) > subIdx {
  994. override = globalConf.FTPD.Bindings[idx].PassiveIPOverrides[subIdx]
  995. replace = true
  996. }
  997. ip, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__PASSIVE_IP_OVERRIDES__%v__IP", idx, subIdx))
  998. if ok {
  999. override.IP = ip
  1000. }
  1001. networks, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__PASSIVE_IP_OVERRIDES__%v__NETWORKS",
  1002. idx, subIdx))
  1003. if ok {
  1004. override.Networks = networks
  1005. }
  1006. if len(override.Networks) > 0 {
  1007. if replace {
  1008. overrides[subIdx] = override
  1009. } else {
  1010. overrides = append(overrides, override)
  1011. }
  1012. }
  1013. }
  1014. return overrides
  1015. }
  1016. func getDefaultFTPDBinding(idx int) ftpd.Binding {
  1017. binding := defaultFTPDBinding
  1018. if len(globalConf.FTPD.Bindings) > idx {
  1019. binding = globalConf.FTPD.Bindings[idx]
  1020. }
  1021. return binding
  1022. }
  1023. func getFTPDBindingFromEnv(idx int) {
  1024. binding := getDefaultFTPDBinding(idx)
  1025. isSet := false
  1026. port, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__PORT", idx))
  1027. if ok {
  1028. binding.Port = int(port)
  1029. isSet = true
  1030. }
  1031. address, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__ADDRESS", idx))
  1032. if ok {
  1033. binding.Address = address
  1034. isSet = true
  1035. }
  1036. applyProxyConfig, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__APPLY_PROXY_CONFIG", idx))
  1037. if ok {
  1038. binding.ApplyProxyConfig = applyProxyConfig
  1039. isSet = true
  1040. }
  1041. certificateFile, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__CERTIFICATE_FILE", idx))
  1042. if ok {
  1043. binding.CertificateFile = certificateFile
  1044. isSet = true
  1045. }
  1046. certificateKeyFile, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__CERTIFICATE_KEY_FILE", idx))
  1047. if ok {
  1048. binding.CertificateKeyFile = certificateKeyFile
  1049. isSet = true
  1050. }
  1051. tlsMode, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__TLS_MODE", idx))
  1052. if ok {
  1053. binding.TLSMode = int(tlsMode)
  1054. isSet = true
  1055. }
  1056. tlsVer, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__MIN_TLS_VERSION", idx))
  1057. if ok {
  1058. binding.MinTLSVersion = int(tlsVer)
  1059. isSet = true
  1060. }
  1061. passiveIP, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__FORCE_PASSIVE_IP", idx))
  1062. if ok {
  1063. binding.ForcePassiveIP = passiveIP
  1064. isSet = true
  1065. }
  1066. passiveIPOverrides := getFTPDPassiveIPOverridesFromEnv(idx)
  1067. if len(passiveIPOverrides) > 0 {
  1068. binding.PassiveIPOverrides = passiveIPOverrides
  1069. isSet = true
  1070. }
  1071. clientAuthType, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__CLIENT_AUTH_TYPE", idx))
  1072. if ok {
  1073. binding.ClientAuthType = int(clientAuthType)
  1074. isSet = true
  1075. }
  1076. tlsCiphers, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__TLS_CIPHER_SUITES", idx))
  1077. if ok {
  1078. binding.TLSCipherSuites = tlsCiphers
  1079. isSet = true
  1080. }
  1081. pasvSecurity, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__PASSIVE_CONNECTIONS_SECURITY", idx))
  1082. if ok {
  1083. binding.PassiveConnectionsSecurity = int(pasvSecurity)
  1084. isSet = true
  1085. }
  1086. activeSecurity, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__ACTIVE_CONNECTIONS_SECURITY", idx))
  1087. if ok {
  1088. binding.ActiveConnectionsSecurity = int(activeSecurity)
  1089. isSet = true
  1090. }
  1091. debug, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_FTPD__BINDINGS__%v__DEBUG", idx))
  1092. if ok {
  1093. binding.Debug = debug
  1094. isSet = true
  1095. }
  1096. applyFTPDBindingFromEnv(idx, isSet, binding)
  1097. }
  1098. func applyFTPDBindingFromEnv(idx int, isSet bool, binding ftpd.Binding) {
  1099. if isSet {
  1100. if len(globalConf.FTPD.Bindings) > idx {
  1101. globalConf.FTPD.Bindings[idx] = binding
  1102. } else {
  1103. globalConf.FTPD.Bindings = append(globalConf.FTPD.Bindings, binding)
  1104. }
  1105. }
  1106. }
  1107. func getWebDAVDBindingProxyConfigsFromEnv(idx int, binding *webdavd.Binding) bool {
  1108. isSet := false
  1109. proxyAllowed, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__PROXY_ALLOWED", idx))
  1110. if ok {
  1111. binding.ProxyAllowed = proxyAllowed
  1112. isSet = true
  1113. }
  1114. clientIPProxyHeader, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__CLIENT_IP_PROXY_HEADER", idx))
  1115. if ok {
  1116. binding.ClientIPProxyHeader = clientIPProxyHeader
  1117. isSet = true
  1118. }
  1119. clientIPHeaderDepth, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__CLIENT_IP_HEADER_DEPTH", idx))
  1120. if ok {
  1121. binding.ClientIPHeaderDepth = int(clientIPHeaderDepth)
  1122. isSet = true
  1123. }
  1124. return isSet
  1125. }
  1126. func getWebDAVDBindingFromEnv(idx int) {
  1127. binding := defaultWebDAVDBinding
  1128. if len(globalConf.WebDAVD.Bindings) > idx {
  1129. binding = globalConf.WebDAVD.Bindings[idx]
  1130. }
  1131. isSet := false
  1132. port, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__PORT", idx))
  1133. if ok {
  1134. binding.Port = int(port)
  1135. isSet = true
  1136. }
  1137. address, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__ADDRESS", idx))
  1138. if ok {
  1139. binding.Address = address
  1140. isSet = true
  1141. }
  1142. enableHTTPS, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__ENABLE_HTTPS", idx))
  1143. if ok {
  1144. binding.EnableHTTPS = enableHTTPS
  1145. isSet = true
  1146. }
  1147. certificateFile, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__CERTIFICATE_FILE", idx))
  1148. if ok {
  1149. binding.CertificateFile = certificateFile
  1150. isSet = true
  1151. }
  1152. certificateKeyFile, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__CERTIFICATE_KEY_FILE", idx))
  1153. if ok {
  1154. binding.CertificateKeyFile = certificateKeyFile
  1155. isSet = true
  1156. }
  1157. tlsVer, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__MIN_TLS_VERSION", idx))
  1158. if ok {
  1159. binding.MinTLSVersion = int(tlsVer)
  1160. isSet = true
  1161. }
  1162. clientAuthType, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__CLIENT_AUTH_TYPE", idx))
  1163. if ok {
  1164. binding.ClientAuthType = int(clientAuthType)
  1165. isSet = true
  1166. }
  1167. tlsCiphers, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__TLS_CIPHER_SUITES", idx))
  1168. if ok {
  1169. binding.TLSCipherSuites = tlsCiphers
  1170. isSet = true
  1171. }
  1172. prefix, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__PREFIX", idx))
  1173. if ok {
  1174. binding.Prefix = prefix
  1175. isSet = true
  1176. }
  1177. if getWebDAVDBindingProxyConfigsFromEnv(idx, &binding) {
  1178. isSet = true
  1179. }
  1180. disableWWWAuth, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_WEBDAVD__BINDINGS__%v__DISABLE_WWW_AUTH_HEADER", idx))
  1181. if ok {
  1182. binding.DisableWWWAuthHeader = disableWWWAuth
  1183. isSet = true
  1184. }
  1185. if isSet {
  1186. if len(globalConf.WebDAVD.Bindings) > idx {
  1187. globalConf.WebDAVD.Bindings[idx] = binding
  1188. } else {
  1189. globalConf.WebDAVD.Bindings = append(globalConf.WebDAVD.Bindings, binding)
  1190. }
  1191. }
  1192. }
  1193. func getHTTPDSecurityProxyHeadersFromEnv(idx int) []httpd.HTTPSProxyHeader {
  1194. var httpsProxyHeaders []httpd.HTTPSProxyHeader
  1195. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1196. httpsProxyHeaders = globalConf.HTTPDConfig.Bindings[idx].Security.HTTPSProxyHeaders
  1197. }
  1198. for subIdx := 0; subIdx < 10; subIdx++ {
  1199. var httpsProxyHeader httpd.HTTPSProxyHeader
  1200. var replace bool
  1201. if len(globalConf.HTTPDConfig.Bindings) > idx &&
  1202. len(globalConf.HTTPDConfig.Bindings[idx].Security.HTTPSProxyHeaders) > subIdx {
  1203. httpsProxyHeader = httpsProxyHeaders[subIdx]
  1204. replace = true
  1205. }
  1206. proxyKey, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__HTTPS_PROXY_HEADERS__%v__KEY",
  1207. idx, subIdx))
  1208. if ok {
  1209. httpsProxyHeader.Key = proxyKey
  1210. }
  1211. proxyVal, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__HTTPS_PROXY_HEADERS__%v__VALUE",
  1212. idx, subIdx))
  1213. if ok {
  1214. httpsProxyHeader.Value = proxyVal
  1215. }
  1216. if httpsProxyHeader.Key != "" && httpsProxyHeader.Value != "" {
  1217. if replace {
  1218. httpsProxyHeaders[subIdx] = httpsProxyHeader
  1219. } else {
  1220. httpsProxyHeaders = append(httpsProxyHeaders, httpsProxyHeader)
  1221. }
  1222. }
  1223. }
  1224. return httpsProxyHeaders
  1225. }
  1226. func getHTTPDSecurityConfFromEnv(idx int) (httpd.SecurityConf, bool) { //nolint:gocyclo
  1227. result := defaultHTTPDBinding.Security
  1228. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1229. result = globalConf.HTTPDConfig.Bindings[idx].Security
  1230. }
  1231. isSet := false
  1232. enabled, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__ENABLED", idx))
  1233. if ok {
  1234. result.Enabled = enabled
  1235. isSet = true
  1236. }
  1237. allowedHosts, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__ALLOWED_HOSTS", idx))
  1238. if ok {
  1239. result.AllowedHosts = allowedHosts
  1240. isSet = true
  1241. }
  1242. allowedHostsAreRegex, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__ALLOWED_HOSTS_ARE_REGEX", idx))
  1243. if ok {
  1244. result.AllowedHostsAreRegex = allowedHostsAreRegex
  1245. isSet = true
  1246. }
  1247. hostsProxyHeaders, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__HOSTS_PROXY_HEADERS", idx))
  1248. if ok {
  1249. result.HostsProxyHeaders = hostsProxyHeaders
  1250. isSet = true
  1251. }
  1252. httpsRedirect, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__HTTPS_REDIRECT", idx))
  1253. if ok {
  1254. result.HTTPSRedirect = httpsRedirect
  1255. isSet = true
  1256. }
  1257. httpsHost, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__HTTPS_HOST", idx))
  1258. if ok {
  1259. result.HTTPSHost = httpsHost
  1260. isSet = true
  1261. }
  1262. httpsProxyHeaders := getHTTPDSecurityProxyHeadersFromEnv(idx)
  1263. if len(httpsProxyHeaders) > 0 {
  1264. result.HTTPSProxyHeaders = httpsProxyHeaders
  1265. isSet = true
  1266. }
  1267. stsSeconds, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__STS_SECONDS", idx))
  1268. if ok {
  1269. result.STSSeconds = stsSeconds
  1270. isSet = true
  1271. }
  1272. stsIncludeSubDomains, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__STS_INCLUDE_SUBDOMAINS", idx))
  1273. if ok {
  1274. result.STSIncludeSubdomains = stsIncludeSubDomains
  1275. isSet = true
  1276. }
  1277. stsPreload, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__STS_PRELOAD", idx))
  1278. if ok {
  1279. result.STSPreload = stsPreload
  1280. isSet = true
  1281. }
  1282. contentTypeNosniff, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__CONTENT_TYPE_NOSNIFF", idx))
  1283. if ok {
  1284. result.ContentTypeNosniff = contentTypeNosniff
  1285. isSet = true
  1286. }
  1287. contentSecurityPolicy, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__CONTENT_SECURITY_POLICY", idx))
  1288. if ok {
  1289. result.ContentSecurityPolicy = contentSecurityPolicy
  1290. isSet = true
  1291. }
  1292. permissionsPolicy, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__PERMISSIONS_POLICY", idx))
  1293. if ok {
  1294. result.PermissionsPolicy = permissionsPolicy
  1295. isSet = true
  1296. }
  1297. crossOriginOpenedPolicy, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__CROSS_ORIGIN_OPENER_POLICY", idx))
  1298. if ok {
  1299. result.CrossOriginOpenerPolicy = crossOriginOpenedPolicy
  1300. isSet = true
  1301. }
  1302. expectCTHeader, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__SECURITY__EXPECT_CT_HEADER", idx))
  1303. if ok {
  1304. result.ExpectCTHeader = expectCTHeader
  1305. isSet = true
  1306. }
  1307. return result, isSet
  1308. }
  1309. func getHTTPDOIDCFromEnv(idx int) (httpd.OIDC, bool) {
  1310. result := defaultHTTPDBinding.OIDC
  1311. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1312. result = globalConf.HTTPDConfig.Bindings[idx].OIDC
  1313. }
  1314. isSet := false
  1315. clientID, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__CLIENT_ID", idx))
  1316. if ok {
  1317. result.ClientID = clientID
  1318. isSet = true
  1319. }
  1320. clientSecret, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__CLIENT_SECRET", idx))
  1321. if ok {
  1322. result.ClientSecret = clientSecret
  1323. isSet = true
  1324. }
  1325. configURL, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__CONFIG_URL", idx))
  1326. if ok {
  1327. result.ConfigURL = configURL
  1328. isSet = true
  1329. }
  1330. redirectBaseURL, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__REDIRECT_BASE_URL", idx))
  1331. if ok {
  1332. result.RedirectBaseURL = redirectBaseURL
  1333. isSet = true
  1334. }
  1335. usernameField, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__USERNAME_FIELD", idx))
  1336. if ok {
  1337. result.UsernameField = usernameField
  1338. isSet = true
  1339. }
  1340. scopes, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__SCOPES", idx))
  1341. if ok {
  1342. result.Scopes = scopes
  1343. isSet = true
  1344. }
  1345. roleField, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__ROLE_FIELD", idx))
  1346. if ok {
  1347. result.RoleField = roleField
  1348. isSet = true
  1349. }
  1350. implicitRoles, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__IMPLICIT_ROLES", idx))
  1351. if ok {
  1352. result.ImplicitRoles = implicitRoles
  1353. isSet = true
  1354. }
  1355. customFields, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__CUSTOM_FIELDS", idx))
  1356. if ok {
  1357. result.CustomFields = customFields
  1358. isSet = true
  1359. }
  1360. skipSignatureCheck, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__INSECURE_SKIP_SIGNATURE_CHECK", idx))
  1361. if ok {
  1362. result.InsecureSkipSignatureCheck = skipSignatureCheck
  1363. isSet = true
  1364. }
  1365. debug, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__OIDC__DEBUG", idx))
  1366. if ok {
  1367. result.Debug = debug
  1368. isSet = true
  1369. }
  1370. return result, isSet
  1371. }
  1372. func getHTTPDUIBrandingFromEnv(prefix string, branding httpd.UIBranding) (httpd.UIBranding, bool) {
  1373. isSet := false
  1374. name, ok := os.LookupEnv(fmt.Sprintf("%s__NAME", prefix))
  1375. if ok {
  1376. branding.Name = name
  1377. isSet = true
  1378. }
  1379. shortName, ok := os.LookupEnv(fmt.Sprintf("%s__SHORT_NAME", prefix))
  1380. if ok {
  1381. branding.ShortName = shortName
  1382. isSet = true
  1383. }
  1384. faviconPath, ok := os.LookupEnv(fmt.Sprintf("%s__FAVICON_PATH", prefix))
  1385. if ok {
  1386. branding.FaviconPath = faviconPath
  1387. isSet = true
  1388. }
  1389. logoPath, ok := os.LookupEnv(fmt.Sprintf("%s__LOGO_PATH", prefix))
  1390. if ok {
  1391. branding.LogoPath = logoPath
  1392. isSet = true
  1393. }
  1394. loginImagePath, ok := os.LookupEnv(fmt.Sprintf("%s__LOGIN_IMAGE_PATH", prefix))
  1395. if ok {
  1396. branding.LoginImagePath = loginImagePath
  1397. isSet = true
  1398. }
  1399. disclaimerName, ok := os.LookupEnv(fmt.Sprintf("%s__DISCLAIMER_NAME", prefix))
  1400. if ok {
  1401. branding.DisclaimerName = disclaimerName
  1402. isSet = true
  1403. }
  1404. disclaimerPath, ok := os.LookupEnv(fmt.Sprintf("%s__DISCLAIMER_PATH", prefix))
  1405. if ok {
  1406. branding.DisclaimerPath = disclaimerPath
  1407. isSet = true
  1408. }
  1409. defaultCSSPath, ok := os.LookupEnv(fmt.Sprintf("%s__DEFAULT_CSS", prefix))
  1410. if ok {
  1411. branding.DefaultCSS = defaultCSSPath
  1412. isSet = true
  1413. }
  1414. extraCSS, ok := lookupStringListFromEnv(fmt.Sprintf("%s__EXTRA_CSS", prefix))
  1415. if ok {
  1416. branding.ExtraCSS = extraCSS
  1417. isSet = true
  1418. }
  1419. return branding, isSet
  1420. }
  1421. func getHTTPDBrandingFromEnv(idx int) (httpd.Branding, bool) {
  1422. result := defaultHTTPDBinding.Branding
  1423. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1424. result = globalConf.HTTPDConfig.Bindings[idx].Branding
  1425. }
  1426. isSet := false
  1427. webAdmin, ok := getHTTPDUIBrandingFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__BRANDING__WEB_ADMIN", idx),
  1428. result.WebAdmin)
  1429. if ok {
  1430. result.WebAdmin = webAdmin
  1431. isSet = true
  1432. }
  1433. webClient, ok := getHTTPDUIBrandingFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__BRANDING__WEB_CLIENT", idx),
  1434. result.WebClient)
  1435. if ok {
  1436. result.WebClient = webClient
  1437. isSet = true
  1438. }
  1439. return result, isSet
  1440. }
  1441. func getHTTPDWebClientIntegrationsFromEnv(idx int) []httpd.WebClientIntegration {
  1442. var integrations []httpd.WebClientIntegration
  1443. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1444. integrations = globalConf.HTTPDConfig.Bindings[idx].WebClientIntegrations
  1445. }
  1446. for subIdx := 0; subIdx < 10; subIdx++ {
  1447. var integration httpd.WebClientIntegration
  1448. var replace bool
  1449. if len(globalConf.HTTPDConfig.Bindings) > idx &&
  1450. len(globalConf.HTTPDConfig.Bindings[idx].WebClientIntegrations) > subIdx {
  1451. integration = integrations[subIdx]
  1452. replace = true
  1453. }
  1454. url, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__WEB_CLIENT_INTEGRATIONS__%v__URL", idx, subIdx))
  1455. if ok {
  1456. integration.URL = url
  1457. }
  1458. extensions, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__WEB_CLIENT_INTEGRATIONS__%v__FILE_EXTENSIONS",
  1459. idx, subIdx))
  1460. if ok {
  1461. integration.FileExtensions = extensions
  1462. }
  1463. if integration.URL != "" && len(integration.FileExtensions) > 0 {
  1464. if replace {
  1465. integrations[subIdx] = integration
  1466. } else {
  1467. integrations = append(integrations, integration)
  1468. }
  1469. }
  1470. }
  1471. return integrations
  1472. }
  1473. func getDefaultHTTPBinding(idx int) httpd.Binding {
  1474. binding := defaultHTTPDBinding
  1475. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1476. binding = globalConf.HTTPDConfig.Bindings[idx]
  1477. }
  1478. return binding
  1479. }
  1480. func getHTTPDNestedObjectsFromEnv(idx int, binding *httpd.Binding) bool {
  1481. isSet := false
  1482. webClientIntegrations := getHTTPDWebClientIntegrationsFromEnv(idx)
  1483. if len(webClientIntegrations) > 0 {
  1484. binding.WebClientIntegrations = webClientIntegrations
  1485. isSet = true
  1486. }
  1487. oidc, ok := getHTTPDOIDCFromEnv(idx)
  1488. if ok {
  1489. binding.OIDC = oidc
  1490. isSet = true
  1491. }
  1492. securityConf, ok := getHTTPDSecurityConfFromEnv(idx)
  1493. if ok {
  1494. binding.Security = securityConf
  1495. isSet = true
  1496. }
  1497. brandingConf, ok := getHTTPDBrandingFromEnv(idx)
  1498. if ok {
  1499. binding.Branding = brandingConf
  1500. isSet = true
  1501. }
  1502. return isSet
  1503. }
  1504. func getHTTPDBindingProxyConfigsFromEnv(idx int, binding *httpd.Binding) bool {
  1505. isSet := false
  1506. proxyAllowed, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__PROXY_ALLOWED", idx))
  1507. if ok {
  1508. binding.ProxyAllowed = proxyAllowed
  1509. isSet = true
  1510. }
  1511. clientIPProxyHeader, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__CLIENT_IP_PROXY_HEADER", idx))
  1512. if ok {
  1513. binding.ClientIPProxyHeader = clientIPProxyHeader
  1514. isSet = true
  1515. }
  1516. clientIPHeaderDepth, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__CLIENT_IP_HEADER_DEPTH", idx))
  1517. if ok {
  1518. binding.ClientIPHeaderDepth = int(clientIPHeaderDepth)
  1519. isSet = true
  1520. }
  1521. return isSet
  1522. }
  1523. func getHTTPDBindingFromEnv(idx int) { //nolint:gocyclo
  1524. binding := getDefaultHTTPBinding(idx)
  1525. isSet := false
  1526. port, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__PORT", idx))
  1527. if ok {
  1528. binding.Port = int(port)
  1529. isSet = true
  1530. }
  1531. address, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ADDRESS", idx))
  1532. if ok {
  1533. binding.Address = address
  1534. isSet = true
  1535. }
  1536. certificateFile, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__CERTIFICATE_FILE", idx))
  1537. if ok {
  1538. binding.CertificateFile = certificateFile
  1539. isSet = true
  1540. }
  1541. certificateKeyFile, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__CERTIFICATE_KEY_FILE", idx))
  1542. if ok {
  1543. binding.CertificateKeyFile = certificateKeyFile
  1544. isSet = true
  1545. }
  1546. enableWebAdmin, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ENABLE_WEB_ADMIN", idx))
  1547. if ok {
  1548. binding.EnableWebAdmin = enableWebAdmin
  1549. isSet = true
  1550. }
  1551. enableWebClient, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ENABLE_WEB_CLIENT", idx))
  1552. if ok {
  1553. binding.EnableWebClient = enableWebClient
  1554. isSet = true
  1555. }
  1556. enableRESTAPI, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ENABLE_REST_API", idx))
  1557. if ok {
  1558. binding.EnableRESTAPI = enableRESTAPI
  1559. isSet = true
  1560. }
  1561. enabledLoginMethods, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ENABLED_LOGIN_METHODS", idx))
  1562. if ok {
  1563. binding.EnabledLoginMethods = int(enabledLoginMethods)
  1564. isSet = true
  1565. }
  1566. renderOpenAPI, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__RENDER_OPENAPI", idx))
  1567. if ok {
  1568. binding.RenderOpenAPI = renderOpenAPI
  1569. isSet = true
  1570. }
  1571. enableHTTPS, ok := lookupBoolFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__ENABLE_HTTPS", idx))
  1572. if ok {
  1573. binding.EnableHTTPS = enableHTTPS
  1574. isSet = true
  1575. }
  1576. tlsVer, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__MIN_TLS_VERSION", idx))
  1577. if ok {
  1578. binding.MinTLSVersion = int(tlsVer)
  1579. isSet = true
  1580. }
  1581. clientAuthType, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__CLIENT_AUTH_TYPE", idx))
  1582. if ok {
  1583. binding.ClientAuthType = int(clientAuthType)
  1584. isSet = true
  1585. }
  1586. tlsCiphers, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__TLS_CIPHER_SUITES", idx))
  1587. if ok {
  1588. binding.TLSCipherSuites = tlsCiphers
  1589. isSet = true
  1590. }
  1591. if getHTTPDBindingProxyConfigsFromEnv(idx, &binding) {
  1592. isSet = true
  1593. }
  1594. hideLoginURL, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_HTTPD__BINDINGS__%v__HIDE_LOGIN_URL", idx))
  1595. if ok {
  1596. binding.HideLoginURL = int(hideLoginURL)
  1597. isSet = true
  1598. }
  1599. if getHTTPDNestedObjectsFromEnv(idx, &binding) {
  1600. isSet = true
  1601. }
  1602. setHTTPDBinding(isSet, binding, idx)
  1603. }
  1604. func setHTTPDBinding(isSet bool, binding httpd.Binding, idx int) {
  1605. if isSet {
  1606. if len(globalConf.HTTPDConfig.Bindings) > idx {
  1607. globalConf.HTTPDConfig.Bindings[idx] = binding
  1608. } else {
  1609. globalConf.HTTPDConfig.Bindings = append(globalConf.HTTPDConfig.Bindings, binding)
  1610. }
  1611. }
  1612. }
  1613. func getHTTPClientCertificatesFromEnv(idx int) {
  1614. tlsCert := httpclient.TLSKeyPair{}
  1615. if len(globalConf.HTTPConfig.Certificates) > idx {
  1616. tlsCert = globalConf.HTTPConfig.Certificates[idx]
  1617. }
  1618. cert, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTP__CERTIFICATES__%v__CERT", idx))
  1619. if ok {
  1620. tlsCert.Cert = cert
  1621. }
  1622. key, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTP__CERTIFICATES__%v__KEY", idx))
  1623. if ok {
  1624. tlsCert.Key = key
  1625. }
  1626. if tlsCert.Cert != "" && tlsCert.Key != "" {
  1627. if len(globalConf.HTTPConfig.Certificates) > idx {
  1628. globalConf.HTTPConfig.Certificates[idx] = tlsCert
  1629. } else {
  1630. globalConf.HTTPConfig.Certificates = append(globalConf.HTTPConfig.Certificates, tlsCert)
  1631. }
  1632. }
  1633. }
  1634. func getHTTPClientHeadersFromEnv(idx int) {
  1635. header := httpclient.Header{}
  1636. if len(globalConf.HTTPConfig.Headers) > idx {
  1637. header = globalConf.HTTPConfig.Headers[idx]
  1638. }
  1639. key, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTP__HEADERS__%v__KEY", idx))
  1640. if ok {
  1641. header.Key = key
  1642. }
  1643. value, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTP__HEADERS__%v__VALUE", idx))
  1644. if ok {
  1645. header.Value = value
  1646. }
  1647. url, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_HTTP__HEADERS__%v__URL", idx))
  1648. if ok {
  1649. header.URL = url
  1650. }
  1651. if header.Key != "" && header.Value != "" {
  1652. if len(globalConf.HTTPConfig.Headers) > idx {
  1653. globalConf.HTTPConfig.Headers[idx] = header
  1654. } else {
  1655. globalConf.HTTPConfig.Headers = append(globalConf.HTTPConfig.Headers, header)
  1656. }
  1657. }
  1658. }
  1659. func getCommandConfigsFromEnv(idx int) {
  1660. cfg := command.Command{}
  1661. if len(globalConf.CommandConfig.Commands) > idx {
  1662. cfg = globalConf.CommandConfig.Commands[idx]
  1663. }
  1664. path, ok := os.LookupEnv(fmt.Sprintf("SFTPGO_COMMAND__COMMANDS__%v__PATH", idx))
  1665. if ok {
  1666. cfg.Path = path
  1667. }
  1668. timeout, ok := lookupIntFromEnv(fmt.Sprintf("SFTPGO_COMMAND__COMMANDS__%v__TIMEOUT", idx))
  1669. if ok {
  1670. cfg.Timeout = int(timeout)
  1671. }
  1672. env, ok := lookupStringListFromEnv(fmt.Sprintf("SFTPGO_COMMAND__COMMANDS__%v__ENV", idx))
  1673. if ok {
  1674. cfg.Env = env
  1675. }
  1676. if cfg.Path != "" {
  1677. if len(globalConf.CommandConfig.Commands) > idx {
  1678. globalConf.CommandConfig.Commands[idx] = cfg
  1679. } else {
  1680. globalConf.CommandConfig.Commands = append(globalConf.CommandConfig.Commands, cfg)
  1681. }
  1682. }
  1683. }
  1684. func setViperDefaults() {
  1685. viper.SetDefault("common.idle_timeout", globalConf.Common.IdleTimeout)
  1686. viper.SetDefault("common.upload_mode", globalConf.Common.UploadMode)
  1687. viper.SetDefault("common.actions.execute_on", globalConf.Common.Actions.ExecuteOn)
  1688. viper.SetDefault("common.actions.execute_sync", globalConf.Common.Actions.ExecuteSync)
  1689. viper.SetDefault("common.actions.hook", globalConf.Common.Actions.Hook)
  1690. viper.SetDefault("common.setstat_mode", globalConf.Common.SetstatMode)
  1691. viper.SetDefault("common.temp_path", globalConf.Common.TempPath)
  1692. viper.SetDefault("common.proxy_protocol", globalConf.Common.ProxyProtocol)
  1693. viper.SetDefault("common.proxy_allowed", globalConf.Common.ProxyAllowed)
  1694. viper.SetDefault("common.post_connect_hook", globalConf.Common.PostConnectHook)
  1695. viper.SetDefault("common.post_disconnect_hook", globalConf.Common.PostDisconnectHook)
  1696. viper.SetDefault("common.data_retention_hook", globalConf.Common.DataRetentionHook)
  1697. viper.SetDefault("common.max_total_connections", globalConf.Common.MaxTotalConnections)
  1698. viper.SetDefault("common.max_per_host_connections", globalConf.Common.MaxPerHostConnections)
  1699. viper.SetDefault("common.whitelist_file", globalConf.Common.WhiteListFile)
  1700. viper.SetDefault("common.allow_self_connections", globalConf.Common.AllowSelfConnections)
  1701. viper.SetDefault("common.defender.enabled", globalConf.Common.DefenderConfig.Enabled)
  1702. viper.SetDefault("common.defender.driver", globalConf.Common.DefenderConfig.Driver)
  1703. viper.SetDefault("common.defender.ban_time", globalConf.Common.DefenderConfig.BanTime)
  1704. viper.SetDefault("common.defender.ban_time_increment", globalConf.Common.DefenderConfig.BanTimeIncrement)
  1705. viper.SetDefault("common.defender.threshold", globalConf.Common.DefenderConfig.Threshold)
  1706. viper.SetDefault("common.defender.score_invalid", globalConf.Common.DefenderConfig.ScoreInvalid)
  1707. viper.SetDefault("common.defender.score_valid", globalConf.Common.DefenderConfig.ScoreValid)
  1708. viper.SetDefault("common.defender.score_limit_exceeded", globalConf.Common.DefenderConfig.ScoreLimitExceeded)
  1709. viper.SetDefault("common.defender.score_no_auth", globalConf.Common.DefenderConfig.ScoreNoAuth)
  1710. viper.SetDefault("common.defender.observation_time", globalConf.Common.DefenderConfig.ObservationTime)
  1711. viper.SetDefault("common.defender.entries_soft_limit", globalConf.Common.DefenderConfig.EntriesSoftLimit)
  1712. viper.SetDefault("common.defender.entries_hard_limit", globalConf.Common.DefenderConfig.EntriesHardLimit)
  1713. viper.SetDefault("common.defender.safelist_file", globalConf.Common.DefenderConfig.SafeListFile)
  1714. viper.SetDefault("common.defender.blocklist_file", globalConf.Common.DefenderConfig.BlockListFile)
  1715. viper.SetDefault("common.defender.safelist", globalConf.Common.DefenderConfig.SafeList)
  1716. viper.SetDefault("common.defender.blocklist", globalConf.Common.DefenderConfig.BlockList)
  1717. viper.SetDefault("acme.email", globalConf.ACME.Email)
  1718. viper.SetDefault("acme.key_type", globalConf.ACME.KeyType)
  1719. viper.SetDefault("acme.certs_path", globalConf.ACME.CertsPath)
  1720. viper.SetDefault("acme.ca_endpoint", globalConf.ACME.CAEndpoint)
  1721. viper.SetDefault("acme.domains", globalConf.ACME.Domains)
  1722. viper.SetDefault("acme.renew_days", globalConf.ACME.RenewDays)
  1723. viper.SetDefault("acme.http01_challenge.port", globalConf.ACME.HTTP01Challenge.Port)
  1724. viper.SetDefault("acme.http01_challenge.webroot", globalConf.ACME.HTTP01Challenge.WebRoot)
  1725. viper.SetDefault("acme.http01_challenge.proxy_header", globalConf.ACME.HTTP01Challenge.ProxyHeader)
  1726. viper.SetDefault("acme.tls_alpn01_challenge.port", globalConf.ACME.TLSALPN01Challenge.Port)
  1727. viper.SetDefault("sftpd.max_auth_tries", globalConf.SFTPD.MaxAuthTries)
  1728. viper.SetDefault("sftpd.banner", globalConf.SFTPD.Banner)
  1729. viper.SetDefault("sftpd.host_keys", globalConf.SFTPD.HostKeys)
  1730. viper.SetDefault("sftpd.host_certificates", globalConf.SFTPD.HostCertificates)
  1731. viper.SetDefault("sftpd.host_key_algorithms", globalConf.SFTPD.HostKeyAlgorithms)
  1732. viper.SetDefault("sftpd.moduli", globalConf.SFTPD.Moduli)
  1733. viper.SetDefault("sftpd.kex_algorithms", globalConf.SFTPD.KexAlgorithms)
  1734. viper.SetDefault("sftpd.ciphers", globalConf.SFTPD.Ciphers)
  1735. viper.SetDefault("sftpd.macs", globalConf.SFTPD.MACs)
  1736. viper.SetDefault("sftpd.trusted_user_ca_keys", globalConf.SFTPD.TrustedUserCAKeys)
  1737. viper.SetDefault("sftpd.revoked_user_certs_file", globalConf.SFTPD.RevokedUserCertsFile)
  1738. viper.SetDefault("sftpd.login_banner_file", globalConf.SFTPD.LoginBannerFile)
  1739. viper.SetDefault("sftpd.enabled_ssh_commands", sftpd.GetDefaultSSHCommands())
  1740. viper.SetDefault("sftpd.keyboard_interactive_authentication", globalConf.SFTPD.KeyboardInteractiveAuthentication)
  1741. viper.SetDefault("sftpd.keyboard_interactive_auth_hook", globalConf.SFTPD.KeyboardInteractiveHook)
  1742. viper.SetDefault("sftpd.password_authentication", globalConf.SFTPD.PasswordAuthentication)
  1743. viper.SetDefault("sftpd.folder_prefix", globalConf.SFTPD.FolderPrefix)
  1744. viper.SetDefault("ftpd.banner", globalConf.FTPD.Banner)
  1745. viper.SetDefault("ftpd.banner_file", globalConf.FTPD.BannerFile)
  1746. viper.SetDefault("ftpd.active_transfers_port_non_20", globalConf.FTPD.ActiveTransfersPortNon20)
  1747. viper.SetDefault("ftpd.passive_port_range.start", globalConf.FTPD.PassivePortRange.Start)
  1748. viper.SetDefault("ftpd.passive_port_range.end", globalConf.FTPD.PassivePortRange.End)
  1749. viper.SetDefault("ftpd.disable_active_mode", globalConf.FTPD.DisableActiveMode)
  1750. viper.SetDefault("ftpd.enable_site", globalConf.FTPD.EnableSite)
  1751. viper.SetDefault("ftpd.hash_support", globalConf.FTPD.HASHSupport)
  1752. viper.SetDefault("ftpd.combine_support", globalConf.FTPD.CombineSupport)
  1753. viper.SetDefault("ftpd.certificate_file", globalConf.FTPD.CertificateFile)
  1754. viper.SetDefault("ftpd.certificate_key_file", globalConf.FTPD.CertificateKeyFile)
  1755. viper.SetDefault("ftpd.ca_certificates", globalConf.FTPD.CACertificates)
  1756. viper.SetDefault("ftpd.ca_revocation_lists", globalConf.FTPD.CARevocationLists)
  1757. viper.SetDefault("webdavd.certificate_file", globalConf.WebDAVD.CertificateFile)
  1758. viper.SetDefault("webdavd.certificate_key_file", globalConf.WebDAVD.CertificateKeyFile)
  1759. viper.SetDefault("webdavd.ca_certificates", globalConf.WebDAVD.CACertificates)
  1760. viper.SetDefault("webdavd.ca_revocation_lists", globalConf.WebDAVD.CARevocationLists)
  1761. viper.SetDefault("webdavd.cors.enabled", globalConf.WebDAVD.Cors.Enabled)
  1762. viper.SetDefault("webdavd.cors.allowed_origins", globalConf.WebDAVD.Cors.AllowedOrigins)
  1763. viper.SetDefault("webdavd.cors.allowed_methods", globalConf.WebDAVD.Cors.AllowedMethods)
  1764. viper.SetDefault("webdavd.cors.allowed_headers", globalConf.WebDAVD.Cors.AllowedHeaders)
  1765. viper.SetDefault("webdavd.cors.exposed_headers", globalConf.WebDAVD.Cors.ExposedHeaders)
  1766. viper.SetDefault("webdavd.cors.allow_credentials", globalConf.WebDAVD.Cors.AllowCredentials)
  1767. viper.SetDefault("webdavd.cors.options_passthrough", globalConf.WebDAVD.Cors.OptionsPassthrough)
  1768. viper.SetDefault("webdavd.cors.options_success_status", globalConf.WebDAVD.Cors.OptionsSuccessStatus)
  1769. viper.SetDefault("webdavd.cors.allow_private_network", globalConf.WebDAVD.Cors.AllowPrivateNetwork)
  1770. viper.SetDefault("webdavd.cors.max_age", globalConf.WebDAVD.Cors.MaxAge)
  1771. viper.SetDefault("webdavd.cache.users.expiration_time", globalConf.WebDAVD.Cache.Users.ExpirationTime)
  1772. viper.SetDefault("webdavd.cache.users.max_size", globalConf.WebDAVD.Cache.Users.MaxSize)
  1773. viper.SetDefault("webdavd.cache.mime_types.enabled", globalConf.WebDAVD.Cache.MimeTypes.Enabled)
  1774. viper.SetDefault("webdavd.cache.mime_types.max_size", globalConf.WebDAVD.Cache.MimeTypes.MaxSize)
  1775. viper.SetDefault("data_provider.driver", globalConf.ProviderConf.Driver)
  1776. viper.SetDefault("data_provider.name", globalConf.ProviderConf.Name)
  1777. viper.SetDefault("data_provider.host", globalConf.ProviderConf.Host)
  1778. viper.SetDefault("data_provider.port", globalConf.ProviderConf.Port)
  1779. viper.SetDefault("data_provider.username", globalConf.ProviderConf.Username)
  1780. viper.SetDefault("data_provider.password", globalConf.ProviderConf.Password)
  1781. viper.SetDefault("data_provider.sslmode", globalConf.ProviderConf.SSLMode)
  1782. viper.SetDefault("data_provider.disable_sni", globalConf.ProviderConf.DisableSNI)
  1783. viper.SetDefault("data_provider.target_session_attrs", globalConf.ProviderConf.TargetSessionAttrs)
  1784. viper.SetDefault("data_provider.root_cert", globalConf.ProviderConf.RootCert)
  1785. viper.SetDefault("data_provider.client_cert", globalConf.ProviderConf.ClientCert)
  1786. viper.SetDefault("data_provider.client_key", globalConf.ProviderConf.ClientKey)
  1787. viper.SetDefault("data_provider.connection_string", globalConf.ProviderConf.ConnectionString)
  1788. viper.SetDefault("data_provider.sql_tables_prefix", globalConf.ProviderConf.SQLTablesPrefix)
  1789. viper.SetDefault("data_provider.track_quota", globalConf.ProviderConf.TrackQuota)
  1790. viper.SetDefault("data_provider.pool_size", globalConf.ProviderConf.PoolSize)
  1791. viper.SetDefault("data_provider.users_base_dir", globalConf.ProviderConf.UsersBaseDir)
  1792. viper.SetDefault("data_provider.actions.execute_on", globalConf.ProviderConf.Actions.ExecuteOn)
  1793. viper.SetDefault("data_provider.actions.execute_for", globalConf.ProviderConf.Actions.ExecuteFor)
  1794. viper.SetDefault("data_provider.actions.hook", globalConf.ProviderConf.Actions.Hook)
  1795. viper.SetDefault("data_provider.external_auth_hook", globalConf.ProviderConf.ExternalAuthHook)
  1796. viper.SetDefault("data_provider.external_auth_scope", globalConf.ProviderConf.ExternalAuthScope)
  1797. viper.SetDefault("data_provider.pre_login_hook", globalConf.ProviderConf.PreLoginHook)
  1798. viper.SetDefault("data_provider.post_login_hook", globalConf.ProviderConf.PostLoginHook)
  1799. viper.SetDefault("data_provider.post_login_scope", globalConf.ProviderConf.PostLoginScope)
  1800. viper.SetDefault("data_provider.check_password_hook", globalConf.ProviderConf.CheckPasswordHook)
  1801. viper.SetDefault("data_provider.check_password_scope", globalConf.ProviderConf.CheckPasswordScope)
  1802. viper.SetDefault("data_provider.password_hashing.bcrypt_options.cost", globalConf.ProviderConf.PasswordHashing.BcryptOptions.Cost)
  1803. viper.SetDefault("data_provider.password_hashing.argon2_options.memory", globalConf.ProviderConf.PasswordHashing.Argon2Options.Memory)
  1804. viper.SetDefault("data_provider.password_hashing.argon2_options.iterations", globalConf.ProviderConf.PasswordHashing.Argon2Options.Iterations)
  1805. viper.SetDefault("data_provider.password_hashing.argon2_options.parallelism", globalConf.ProviderConf.PasswordHashing.Argon2Options.Parallelism)
  1806. viper.SetDefault("data_provider.password_hashing.algo", globalConf.ProviderConf.PasswordHashing.Algo)
  1807. viper.SetDefault("data_provider.password_validation.admins.min_entropy", globalConf.ProviderConf.PasswordValidation.Admins.MinEntropy)
  1808. viper.SetDefault("data_provider.password_validation.users.min_entropy", globalConf.ProviderConf.PasswordValidation.Users.MinEntropy)
  1809. viper.SetDefault("data_provider.password_caching", globalConf.ProviderConf.PasswordCaching)
  1810. viper.SetDefault("data_provider.update_mode", globalConf.ProviderConf.UpdateMode)
  1811. viper.SetDefault("data_provider.delayed_quota_update", globalConf.ProviderConf.DelayedQuotaUpdate)
  1812. viper.SetDefault("data_provider.create_default_admin", globalConf.ProviderConf.CreateDefaultAdmin)
  1813. viper.SetDefault("data_provider.naming_rules", globalConf.ProviderConf.NamingRules)
  1814. viper.SetDefault("data_provider.is_shared", globalConf.ProviderConf.IsShared)
  1815. viper.SetDefault("data_provider.node.host", globalConf.ProviderConf.Node.Host)
  1816. viper.SetDefault("data_provider.node.port", globalConf.ProviderConf.Node.Port)
  1817. viper.SetDefault("data_provider.node.proto", globalConf.ProviderConf.Node.Proto)
  1818. viper.SetDefault("data_provider.backups_path", globalConf.ProviderConf.BackupsPath)
  1819. viper.SetDefault("httpd.templates_path", globalConf.HTTPDConfig.TemplatesPath)
  1820. viper.SetDefault("httpd.static_files_path", globalConf.HTTPDConfig.StaticFilesPath)
  1821. viper.SetDefault("httpd.openapi_path", globalConf.HTTPDConfig.OpenAPIPath)
  1822. viper.SetDefault("httpd.web_root", globalConf.HTTPDConfig.WebRoot)
  1823. viper.SetDefault("httpd.certificate_file", globalConf.HTTPDConfig.CertificateFile)
  1824. viper.SetDefault("httpd.certificate_key_file", globalConf.HTTPDConfig.CertificateKeyFile)
  1825. viper.SetDefault("httpd.ca_certificates", globalConf.HTTPDConfig.CACertificates)
  1826. viper.SetDefault("httpd.ca_revocation_lists", globalConf.HTTPDConfig.CARevocationLists)
  1827. viper.SetDefault("httpd.signing_passphrase", globalConf.HTTPDConfig.SigningPassphrase)
  1828. viper.SetDefault("httpd.token_validation", globalConf.HTTPDConfig.TokenValidation)
  1829. viper.SetDefault("httpd.max_upload_file_size", globalConf.HTTPDConfig.MaxUploadFileSize)
  1830. viper.SetDefault("httpd.cors.enabled", globalConf.HTTPDConfig.Cors.Enabled)
  1831. viper.SetDefault("httpd.cors.allowed_origins", globalConf.HTTPDConfig.Cors.AllowedOrigins)
  1832. viper.SetDefault("httpd.cors.allowed_methods", globalConf.HTTPDConfig.Cors.AllowedMethods)
  1833. viper.SetDefault("httpd.cors.allowed_headers", globalConf.HTTPDConfig.Cors.AllowedHeaders)
  1834. viper.SetDefault("httpd.cors.exposed_headers", globalConf.HTTPDConfig.Cors.ExposedHeaders)
  1835. viper.SetDefault("httpd.cors.allow_credentials", globalConf.HTTPDConfig.Cors.AllowCredentials)
  1836. viper.SetDefault("httpd.cors.max_age", globalConf.HTTPDConfig.Cors.MaxAge)
  1837. viper.SetDefault("httpd.cors.options_passthrough", globalConf.HTTPDConfig.Cors.OptionsPassthrough)
  1838. viper.SetDefault("httpd.cors.options_success_status", globalConf.HTTPDConfig.Cors.OptionsSuccessStatus)
  1839. viper.SetDefault("httpd.cors.allow_private_network", globalConf.HTTPDConfig.Cors.AllowPrivateNetwork)
  1840. viper.SetDefault("httpd.setup.installation_code", globalConf.HTTPDConfig.Setup.InstallationCode)
  1841. viper.SetDefault("httpd.setup.installation_code_hint", globalConf.HTTPDConfig.Setup.InstallationCodeHint)
  1842. viper.SetDefault("httpd.hide_support_link", globalConf.HTTPDConfig.HideSupportLink)
  1843. viper.SetDefault("http.timeout", globalConf.HTTPConfig.Timeout)
  1844. viper.SetDefault("http.retry_wait_min", globalConf.HTTPConfig.RetryWaitMin)
  1845. viper.SetDefault("http.retry_wait_max", globalConf.HTTPConfig.RetryWaitMax)
  1846. viper.SetDefault("http.retry_max", globalConf.HTTPConfig.RetryMax)
  1847. viper.SetDefault("http.ca_certificates", globalConf.HTTPConfig.CACertificates)
  1848. viper.SetDefault("http.skip_tls_verify", globalConf.HTTPConfig.SkipTLSVerify)
  1849. viper.SetDefault("command.timeout", globalConf.CommandConfig.Timeout)
  1850. viper.SetDefault("command.env", globalConf.CommandConfig.Env)
  1851. viper.SetDefault("kms.secrets.url", globalConf.KMSConfig.Secrets.URL)
  1852. viper.SetDefault("kms.secrets.master_key", globalConf.KMSConfig.Secrets.MasterKeyString)
  1853. viper.SetDefault("kms.secrets.master_key_path", globalConf.KMSConfig.Secrets.MasterKeyPath)
  1854. viper.SetDefault("telemetry.bind_port", globalConf.TelemetryConfig.BindPort)
  1855. viper.SetDefault("telemetry.bind_address", globalConf.TelemetryConfig.BindAddress)
  1856. viper.SetDefault("telemetry.enable_profiler", globalConf.TelemetryConfig.EnableProfiler)
  1857. viper.SetDefault("telemetry.auth_user_file", globalConf.TelemetryConfig.AuthUserFile)
  1858. viper.SetDefault("telemetry.certificate_file", globalConf.TelemetryConfig.CertificateFile)
  1859. viper.SetDefault("telemetry.certificate_key_file", globalConf.TelemetryConfig.CertificateKeyFile)
  1860. viper.SetDefault("telemetry.min_tls_version", globalConf.TelemetryConfig.MinTLSVersion)
  1861. viper.SetDefault("telemetry.tls_cipher_suites", globalConf.TelemetryConfig.TLSCipherSuites)
  1862. viper.SetDefault("smtp.host", globalConf.SMTPConfig.Host)
  1863. viper.SetDefault("smtp.port", globalConf.SMTPConfig.Port)
  1864. viper.SetDefault("smtp.from", globalConf.SMTPConfig.From)
  1865. viper.SetDefault("smtp.user", globalConf.SMTPConfig.User)
  1866. viper.SetDefault("smtp.password", globalConf.SMTPConfig.Password)
  1867. viper.SetDefault("smtp.auth_type", globalConf.SMTPConfig.AuthType)
  1868. viper.SetDefault("smtp.encryption", globalConf.SMTPConfig.Encryption)
  1869. viper.SetDefault("smtp.domain", globalConf.SMTPConfig.Domain)
  1870. viper.SetDefault("smtp.templates_path", globalConf.SMTPConfig.TemplatesPath)
  1871. }
  1872. func lookupBoolFromEnv(envName string) (bool, bool) {
  1873. value, ok := os.LookupEnv(envName)
  1874. if ok {
  1875. converted, err := strconv.ParseBool(strings.TrimSpace(value))
  1876. if err == nil {
  1877. return converted, ok
  1878. }
  1879. }
  1880. return false, false
  1881. }
  1882. func lookupIntFromEnv(envName string) (int64, bool) {
  1883. value, ok := os.LookupEnv(envName)
  1884. if ok {
  1885. converted, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64)
  1886. if err == nil {
  1887. return converted, ok
  1888. }
  1889. }
  1890. return 0, false
  1891. }
  1892. func lookupStringListFromEnv(envName string) ([]string, bool) {
  1893. value, ok := os.LookupEnv(envName)
  1894. if ok {
  1895. var result []string
  1896. for _, v := range strings.Split(value, ",") {
  1897. val := strings.TrimSpace(v)
  1898. if val != "" {
  1899. result = append(result, val)
  1900. }
  1901. }
  1902. return result, true
  1903. }
  1904. return nil, false
  1905. }