config.go 71 KB

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