config.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. // Package config manages the configuration
  2. package config
  3. import (
  4. "fmt"
  5. "strings"
  6. "github.com/spf13/viper"
  7. "github.com/drakkan/sftpgo/common"
  8. "github.com/drakkan/sftpgo/dataprovider"
  9. "github.com/drakkan/sftpgo/ftpd"
  10. "github.com/drakkan/sftpgo/httpclient"
  11. "github.com/drakkan/sftpgo/httpd"
  12. "github.com/drakkan/sftpgo/logger"
  13. "github.com/drakkan/sftpgo/sftpd"
  14. "github.com/drakkan/sftpgo/utils"
  15. "github.com/drakkan/sftpgo/version"
  16. "github.com/drakkan/sftpgo/webdavd"
  17. )
  18. const (
  19. logSender = "config"
  20. // DefaultConfigName defines the name for the default config file.
  21. // This is the file name without extension, we use viper and so we
  22. // support all the config files format supported by viper
  23. DefaultConfigName = "sftpgo"
  24. // ConfigEnvPrefix defines a prefix that ENVIRONMENT variables will use
  25. configEnvPrefix = "sftpgo"
  26. )
  27. var (
  28. globalConf globalConfig
  29. defaultSFTPDBanner = fmt.Sprintf("SFTPGo_%v", version.Get().Version)
  30. defaultFTPDBanner = fmt.Sprintf("SFTPGo %v ready", version.Get().Version)
  31. )
  32. type globalConfig struct {
  33. Common common.Configuration `json:"common" mapstructure:"common"`
  34. SFTPD sftpd.Configuration `json:"sftpd" mapstructure:"sftpd"`
  35. FTPD ftpd.Configuration `json:"ftpd" mapstructure:"ftpd"`
  36. WebDAVD webdavd.Configuration `json:"webdavd" mapstructure:"webdavd"`
  37. ProviderConf dataprovider.Config `json:"data_provider" mapstructure:"data_provider"`
  38. HTTPDConfig httpd.Conf `json:"httpd" mapstructure:"httpd"`
  39. HTTPConfig httpclient.Config `json:"http" mapstructure:"http"`
  40. }
  41. func init() {
  42. // create a default configuration to use if no config file is provided
  43. globalConf = globalConfig{
  44. Common: common.Configuration{
  45. IdleTimeout: 15,
  46. UploadMode: 0,
  47. Actions: common.ProtocolActions{
  48. ExecuteOn: []string{},
  49. Hook: "",
  50. },
  51. SetstatMode: 0,
  52. ProxyProtocol: 0,
  53. ProxyAllowed: []string{},
  54. },
  55. SFTPD: sftpd.Configuration{
  56. Banner: defaultSFTPDBanner,
  57. BindPort: 2022,
  58. BindAddress: "",
  59. MaxAuthTries: 0,
  60. HostKeys: []string{},
  61. KexAlgorithms: []string{},
  62. Ciphers: []string{},
  63. MACs: []string{},
  64. TrustedUserCAKeys: []string{},
  65. LoginBannerFile: "",
  66. EnabledSSHCommands: sftpd.GetDefaultSSHCommands(),
  67. KeyboardInteractiveHook: "",
  68. PasswordAuthentication: true,
  69. },
  70. FTPD: ftpd.Configuration{
  71. BindPort: 0,
  72. BindAddress: "",
  73. Banner: defaultFTPDBanner,
  74. BannerFile: "",
  75. ActiveTransfersPortNon20: false,
  76. ForcePassiveIP: "",
  77. PassivePortRange: ftpd.PortRange{
  78. Start: 50000,
  79. End: 50100,
  80. },
  81. CertificateFile: "",
  82. CertificateKeyFile: "",
  83. },
  84. WebDAVD: webdavd.Configuration{
  85. BindPort: 0,
  86. BindAddress: "",
  87. CertificateFile: "",
  88. CertificateKeyFile: "",
  89. Cors: webdavd.Cors{
  90. Enabled: false,
  91. AllowedOrigins: []string{},
  92. AllowedMethods: []string{},
  93. AllowedHeaders: []string{},
  94. ExposedHeaders: []string{},
  95. AllowCredentials: false,
  96. MaxAge: 0,
  97. },
  98. Cache: webdavd.Cache{
  99. Enabled: true,
  100. ExpirationTime: 0,
  101. MaxSize: 50,
  102. },
  103. },
  104. ProviderConf: dataprovider.Config{
  105. Driver: "sqlite",
  106. Name: "sftpgo.db",
  107. Host: "",
  108. Port: 5432,
  109. Username: "",
  110. Password: "",
  111. ConnectionString: "",
  112. SQLTablesPrefix: "",
  113. ManageUsers: 1,
  114. SSLMode: 0,
  115. TrackQuota: 1,
  116. PoolSize: 0,
  117. UsersBaseDir: "",
  118. Actions: dataprovider.UserActions{
  119. ExecuteOn: []string{},
  120. Hook: "",
  121. },
  122. ExternalAuthHook: "",
  123. ExternalAuthScope: 0,
  124. CredentialsPath: "credentials",
  125. PreLoginHook: "",
  126. PostLoginHook: "",
  127. PostLoginScope: 0,
  128. CheckPasswordHook: "",
  129. CheckPasswordScope: 0,
  130. PasswordHashing: dataprovider.PasswordHashing{
  131. Argon2Options: dataprovider.Argon2Options{
  132. Memory: 65536,
  133. Iterations: 1,
  134. Parallelism: 2,
  135. },
  136. },
  137. UpdateMode: 0,
  138. PreferDatabaseCredentials: false,
  139. },
  140. HTTPDConfig: httpd.Conf{
  141. BindPort: 8080,
  142. BindAddress: "127.0.0.1",
  143. TemplatesPath: "templates",
  144. StaticFilesPath: "static",
  145. BackupsPath: "backups",
  146. AuthUserFile: "",
  147. CertificateFile: "",
  148. CertificateKeyFile: "",
  149. },
  150. HTTPConfig: httpclient.Config{
  151. Timeout: 20,
  152. CACertificates: nil,
  153. SkipTLSVerify: false,
  154. },
  155. }
  156. viper.SetEnvPrefix(configEnvPrefix)
  157. replacer := strings.NewReplacer(".", "__")
  158. viper.SetEnvKeyReplacer(replacer)
  159. viper.SetConfigName(DefaultConfigName)
  160. viper.AutomaticEnv()
  161. viper.AllowEmptyEnv(true)
  162. }
  163. // GetCommonConfig returns the common protocols configuration
  164. func GetCommonConfig() common.Configuration {
  165. return globalConf.Common
  166. }
  167. // SetCommonConfig sets the common protocols configuration
  168. func SetCommonConfig(config common.Configuration) {
  169. globalConf.Common = config
  170. }
  171. // GetSFTPDConfig returns the configuration for the SFTP server
  172. func GetSFTPDConfig() sftpd.Configuration {
  173. return globalConf.SFTPD
  174. }
  175. // SetSFTPDConfig sets the configuration for the SFTP server
  176. func SetSFTPDConfig(config sftpd.Configuration) {
  177. globalConf.SFTPD = config
  178. }
  179. // GetFTPDConfig returns the configuration for the FTP server
  180. func GetFTPDConfig() ftpd.Configuration {
  181. return globalConf.FTPD
  182. }
  183. // SetFTPDConfig sets the configuration for the FTP server
  184. func SetFTPDConfig(config ftpd.Configuration) {
  185. globalConf.FTPD = config
  186. }
  187. // GetWebDAVDConfig returns the configuration for the WebDAV server
  188. func GetWebDAVDConfig() webdavd.Configuration {
  189. return globalConf.WebDAVD
  190. }
  191. // SetWebDAVDConfig sets the configuration for the WebDAV server
  192. func SetWebDAVDConfig(config webdavd.Configuration) {
  193. globalConf.WebDAVD = config
  194. }
  195. // GetHTTPDConfig returns the configuration for the HTTP server
  196. func GetHTTPDConfig() httpd.Conf {
  197. return globalConf.HTTPDConfig
  198. }
  199. // SetHTTPDConfig sets the configuration for the HTTP server
  200. func SetHTTPDConfig(config httpd.Conf) {
  201. globalConf.HTTPDConfig = config
  202. }
  203. //GetProviderConf returns the configuration for the data provider
  204. func GetProviderConf() dataprovider.Config {
  205. return globalConf.ProviderConf
  206. }
  207. //SetProviderConf sets the configuration for the data provider
  208. func SetProviderConf(config dataprovider.Config) {
  209. globalConf.ProviderConf = config
  210. }
  211. // GetHTTPConfig returns the configuration for HTTP clients
  212. func GetHTTPConfig() httpclient.Config {
  213. return globalConf.HTTPConfig
  214. }
  215. func getRedactedGlobalConf() globalConfig {
  216. conf := globalConf
  217. conf.ProviderConf.Password = "[redacted]"
  218. return conf
  219. }
  220. // LoadConfig loads the configuration
  221. // configDir will be added to the configuration search paths.
  222. // The search path contains by default the current directory and on linux it contains
  223. // $HOME/.config/sftpgo and /etc/sftpgo too.
  224. // configName is the name of the configuration to search without extension
  225. func LoadConfig(configDir, configName string) error {
  226. var err error
  227. viper.AddConfigPath(configDir)
  228. setViperAdditionalConfigPaths()
  229. viper.AddConfigPath(".")
  230. viper.SetConfigName(configName)
  231. if err = viper.ReadInConfig(); err != nil {
  232. logger.Warn(logSender, "", "error loading configuration file: %v. Default configuration will be used: %+v",
  233. err, getRedactedGlobalConf())
  234. logger.WarnToConsole("error loading configuration file: %v. Default configuration will be used.", err)
  235. return err
  236. }
  237. err = viper.Unmarshal(&globalConf)
  238. if err != nil {
  239. logger.Warn(logSender, "", "error parsing configuration file: %v. Default configuration will be used: %+v",
  240. err, getRedactedGlobalConf())
  241. logger.WarnToConsole("error parsing configuration file: %v. Default configuration will be used.", err)
  242. return err
  243. }
  244. checkCommonParamsCompatibility()
  245. if strings.TrimSpace(globalConf.SFTPD.Banner) == "" {
  246. globalConf.SFTPD.Banner = defaultSFTPDBanner
  247. }
  248. if strings.TrimSpace(globalConf.FTPD.Banner) == "" {
  249. globalConf.FTPD.Banner = defaultFTPDBanner
  250. }
  251. if len(globalConf.ProviderConf.UsersBaseDir) > 0 && !utils.IsFileInputValid(globalConf.ProviderConf.UsersBaseDir) {
  252. err = fmt.Errorf("invalid users base dir %#v will be ignored", globalConf.ProviderConf.UsersBaseDir)
  253. globalConf.ProviderConf.UsersBaseDir = ""
  254. logger.Warn(logSender, "", "Configuration error: %v", err)
  255. logger.WarnToConsole("Configuration error: %v", err)
  256. }
  257. if globalConf.Common.UploadMode < 0 || globalConf.Common.UploadMode > 2 {
  258. err = fmt.Errorf("invalid upload_mode 0, 1 and 2 are supported, configured: %v reset upload_mode to 0",
  259. globalConf.Common.UploadMode)
  260. globalConf.Common.UploadMode = 0
  261. logger.Warn(logSender, "", "Configuration error: %v", err)
  262. logger.WarnToConsole("Configuration error: %v", err)
  263. }
  264. if globalConf.Common.ProxyProtocol < 0 || globalConf.Common.ProxyProtocol > 2 {
  265. err = fmt.Errorf("invalid proxy_protocol 0, 1 and 2 are supported, configured: %v reset proxy_protocol to 0",
  266. globalConf.Common.ProxyProtocol)
  267. globalConf.Common.ProxyProtocol = 0
  268. logger.Warn(logSender, "", "Configuration error: %v", err)
  269. logger.WarnToConsole("Configuration error: %v", err)
  270. }
  271. if globalConf.ProviderConf.ExternalAuthScope < 0 || globalConf.ProviderConf.ExternalAuthScope > 7 {
  272. err = fmt.Errorf("invalid external_auth_scope: %v reset to 0", globalConf.ProviderConf.ExternalAuthScope)
  273. globalConf.ProviderConf.ExternalAuthScope = 0
  274. logger.Warn(logSender, "", "Configuration error: %v", err)
  275. logger.WarnToConsole("Configuration error: %v", err)
  276. }
  277. if len(globalConf.ProviderConf.CredentialsPath) == 0 {
  278. err = fmt.Errorf("invalid credentials path, reset to \"credentials\"")
  279. globalConf.ProviderConf.CredentialsPath = "credentials"
  280. logger.Warn(logSender, "", "Configuration error: %v", err)
  281. logger.WarnToConsole("Configuration error: %v", err)
  282. }
  283. checkHostKeyCompatibility()
  284. logger.Debug(logSender, "", "config file used: '%#v', config loaded: %+v", viper.ConfigFileUsed(), getRedactedGlobalConf())
  285. return err
  286. }
  287. func checkHostKeyCompatibility() {
  288. // we copy deprecated fields to new ones to keep backward compatibility so lint is disabled
  289. if len(globalConf.SFTPD.Keys) > 0 && len(globalConf.SFTPD.HostKeys) == 0 { //nolint:staticcheck
  290. logger.Warn(logSender, "", "keys is deprecated, please use host_keys")
  291. logger.WarnToConsole("keys is deprecated, please use host_keys")
  292. for _, k := range globalConf.SFTPD.Keys { //nolint:staticcheck
  293. globalConf.SFTPD.HostKeys = append(globalConf.SFTPD.HostKeys, k.PrivateKey)
  294. }
  295. }
  296. }
  297. func checkCommonParamsCompatibility() {
  298. // we copy deprecated fields to new ones to keep backward compatibility so lint is disabled
  299. if globalConf.SFTPD.IdleTimeout > 0 { //nolint:staticcheck
  300. logger.Warn(logSender, "", "sftpd.idle_timeout is deprecated, please use common.idle_timeout")
  301. logger.WarnToConsole("sftpd.idle_timeout is deprecated, please use common.idle_timeout")
  302. globalConf.Common.IdleTimeout = globalConf.SFTPD.IdleTimeout //nolint:staticcheck
  303. }
  304. if len(globalConf.SFTPD.Actions.Hook) > 0 && len(globalConf.Common.Actions.Hook) == 0 { //nolint:staticcheck
  305. logger.Warn(logSender, "", "sftpd.actions is deprecated, please use common.actions")
  306. logger.WarnToConsole("sftpd.actions is deprecated, please use common.actions")
  307. globalConf.Common.Actions.ExecuteOn = globalConf.SFTPD.Actions.ExecuteOn //nolint:staticcheck
  308. globalConf.Common.Actions.Hook = globalConf.SFTPD.Actions.Hook //nolint:staticcheck
  309. }
  310. if globalConf.SFTPD.SetstatMode > 0 && globalConf.Common.SetstatMode == 0 { //nolint:staticcheck
  311. logger.Warn(logSender, "", "sftpd.setstat_mode is deprecated, please use common.setstat_mode")
  312. logger.WarnToConsole("sftpd.setstat_mode is deprecated, please use common.setstat_mode")
  313. globalConf.Common.SetstatMode = globalConf.SFTPD.SetstatMode //nolint:staticcheck
  314. }
  315. if globalConf.SFTPD.UploadMode > 0 && globalConf.Common.UploadMode == 0 { //nolint:staticcheck
  316. logger.Warn(logSender, "", "sftpd.upload_mode is deprecated, please use common.upload_mode")
  317. logger.WarnToConsole("sftpd.upload_mode is deprecated, please use common.upload_mode")
  318. globalConf.Common.UploadMode = globalConf.SFTPD.UploadMode //nolint:staticcheck
  319. }
  320. if globalConf.SFTPD.ProxyProtocol > 0 && globalConf.Common.ProxyProtocol == 0 { //nolint:staticcheck
  321. logger.Warn(logSender, "", "sftpd.proxy_protocol is deprecated, please use common.proxy_protocol")
  322. logger.WarnToConsole("sftpd.proxy_protocol is deprecated, please use common.proxy_protocol")
  323. globalConf.Common.ProxyProtocol = globalConf.SFTPD.ProxyProtocol //nolint:staticcheck
  324. globalConf.Common.ProxyAllowed = globalConf.SFTPD.ProxyAllowed //nolint:staticcheck
  325. }
  326. }