config.go 76 KB

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