config.go 74 KB

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