config.go 73 KB

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