config.go 74 KB

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