config.go 73 KB

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