config.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. },
  69. FTPD: ftpd.Configuration{
  70. BindPort: 0,
  71. BindAddress: "",
  72. Banner: defaultFTPDBanner,
  73. BannerFile: "",
  74. ActiveTransfersPortNon20: false,
  75. ForcePassiveIP: "",
  76. PassivePortRange: ftpd.PortRange{
  77. Start: 50000,
  78. End: 50100,
  79. },
  80. CertificateFile: "",
  81. CertificateKeyFile: "",
  82. },
  83. WebDAVD: webdavd.Configuration{
  84. BindPort: 0,
  85. BindAddress: "",
  86. CertificateFile: "",
  87. CertificateKeyFile: "",
  88. Cors: webdavd.Cors{
  89. Enabled: false,
  90. AllowedOrigins: []string{},
  91. AllowedMethods: []string{},
  92. AllowedHeaders: []string{},
  93. ExposedHeaders: []string{},
  94. AllowCredentials: false,
  95. MaxAge: 0,
  96. },
  97. },
  98. ProviderConf: dataprovider.Config{
  99. Driver: "sqlite",
  100. Name: "sftpgo.db",
  101. Host: "",
  102. Port: 5432,
  103. Username: "",
  104. Password: "",
  105. ConnectionString: "",
  106. SQLTablesPrefix: "",
  107. ManageUsers: 1,
  108. SSLMode: 0,
  109. TrackQuota: 1,
  110. PoolSize: 0,
  111. UsersBaseDir: "",
  112. Actions: dataprovider.UserActions{
  113. ExecuteOn: []string{},
  114. Hook: "",
  115. },
  116. ExternalAuthHook: "",
  117. ExternalAuthScope: 0,
  118. CredentialsPath: "credentials",
  119. PreLoginHook: "",
  120. PostLoginHook: "",
  121. PostLoginScope: 0,
  122. },
  123. HTTPDConfig: httpd.Conf{
  124. BindPort: 8080,
  125. BindAddress: "127.0.0.1",
  126. TemplatesPath: "templates",
  127. StaticFilesPath: "static",
  128. BackupsPath: "backups",
  129. AuthUserFile: "",
  130. CertificateFile: "",
  131. CertificateKeyFile: "",
  132. },
  133. HTTPConfig: httpclient.Config{
  134. Timeout: 20,
  135. CACertificates: nil,
  136. SkipTLSVerify: false,
  137. },
  138. }
  139. viper.SetEnvPrefix(configEnvPrefix)
  140. replacer := strings.NewReplacer(".", "__")
  141. viper.SetEnvKeyReplacer(replacer)
  142. viper.SetConfigName(DefaultConfigName)
  143. viper.AutomaticEnv()
  144. viper.AllowEmptyEnv(true)
  145. }
  146. // GetCommonConfig returns the common protocols configuration
  147. func GetCommonConfig() common.Configuration {
  148. return globalConf.Common
  149. }
  150. // SetCommonConfig sets the common protocols configuration
  151. func SetCommonConfig(config common.Configuration) {
  152. globalConf.Common = config
  153. }
  154. // GetSFTPDConfig returns the configuration for the SFTP server
  155. func GetSFTPDConfig() sftpd.Configuration {
  156. return globalConf.SFTPD
  157. }
  158. // SetSFTPDConfig sets the configuration for the SFTP server
  159. func SetSFTPDConfig(config sftpd.Configuration) {
  160. globalConf.SFTPD = config
  161. }
  162. // GetFTPDConfig returns the configuration for the FTP server
  163. func GetFTPDConfig() ftpd.Configuration {
  164. return globalConf.FTPD
  165. }
  166. // SetFTPDConfig sets the configuration for the FTP server
  167. func SetFTPDConfig(config ftpd.Configuration) {
  168. globalConf.FTPD = config
  169. }
  170. // GetWebDAVDConfig returns the configuration for the WebDAV server
  171. func GetWebDAVDConfig() webdavd.Configuration {
  172. return globalConf.WebDAVD
  173. }
  174. // SetWebDAVDConfig sets the configuration for the WebDAV server
  175. func SetWebDAVDConfig(config webdavd.Configuration) {
  176. globalConf.WebDAVD = config
  177. }
  178. // GetHTTPDConfig returns the configuration for the HTTP server
  179. func GetHTTPDConfig() httpd.Conf {
  180. return globalConf.HTTPDConfig
  181. }
  182. // SetHTTPDConfig sets the configuration for the HTTP server
  183. func SetHTTPDConfig(config httpd.Conf) {
  184. globalConf.HTTPDConfig = config
  185. }
  186. //GetProviderConf returns the configuration for the data provider
  187. func GetProviderConf() dataprovider.Config {
  188. return globalConf.ProviderConf
  189. }
  190. //SetProviderConf sets the configuration for the data provider
  191. func SetProviderConf(config dataprovider.Config) {
  192. globalConf.ProviderConf = config
  193. }
  194. // GetHTTPConfig returns the configuration for HTTP clients
  195. func GetHTTPConfig() httpclient.Config {
  196. return globalConf.HTTPConfig
  197. }
  198. func getRedactedGlobalConf() globalConfig {
  199. conf := globalConf
  200. conf.ProviderConf.Password = "[redacted]"
  201. return conf
  202. }
  203. // LoadConfig loads the configuration
  204. // configDir will be added to the configuration search paths.
  205. // The search path contains by default the current directory and on linux it contains
  206. // $HOME/.config/sftpgo and /etc/sftpgo too.
  207. // configName is the name of the configuration to search without extension
  208. func LoadConfig(configDir, configName string) error {
  209. var err error
  210. viper.AddConfigPath(configDir)
  211. setViperAdditionalConfigPaths()
  212. viper.AddConfigPath(".")
  213. viper.SetConfigName(configName)
  214. if err = viper.ReadInConfig(); err != nil {
  215. logger.Warn(logSender, "", "error loading configuration file: %v. Default configuration will be used: %+v",
  216. err, getRedactedGlobalConf())
  217. logger.WarnToConsole("error loading configuration file: %v. Default configuration will be used.", err)
  218. return err
  219. }
  220. err = viper.Unmarshal(&globalConf)
  221. if err != nil {
  222. logger.Warn(logSender, "", "error parsing configuration file: %v. Default configuration will be used: %+v",
  223. err, getRedactedGlobalConf())
  224. logger.WarnToConsole("error parsing configuration file: %v. Default configuration will be used.", err)
  225. return err
  226. }
  227. checkCommonParamsCompatibility()
  228. if strings.TrimSpace(globalConf.SFTPD.Banner) == "" {
  229. globalConf.SFTPD.Banner = defaultSFTPDBanner
  230. }
  231. if strings.TrimSpace(globalConf.FTPD.Banner) == "" {
  232. globalConf.FTPD.Banner = defaultFTPDBanner
  233. }
  234. if len(globalConf.ProviderConf.UsersBaseDir) > 0 && !utils.IsFileInputValid(globalConf.ProviderConf.UsersBaseDir) {
  235. err = fmt.Errorf("invalid users base dir %#v will be ignored", globalConf.ProviderConf.UsersBaseDir)
  236. globalConf.ProviderConf.UsersBaseDir = ""
  237. logger.Warn(logSender, "", "Configuration error: %v", err)
  238. logger.WarnToConsole("Configuration error: %v", err)
  239. }
  240. if globalConf.Common.UploadMode < 0 || globalConf.Common.UploadMode > 2 {
  241. err = fmt.Errorf("invalid upload_mode 0, 1 and 2 are supported, configured: %v reset upload_mode to 0",
  242. globalConf.Common.UploadMode)
  243. globalConf.Common.UploadMode = 0
  244. logger.Warn(logSender, "", "Configuration error: %v", err)
  245. logger.WarnToConsole("Configuration error: %v", err)
  246. }
  247. if globalConf.Common.ProxyProtocol < 0 || globalConf.Common.ProxyProtocol > 2 {
  248. err = fmt.Errorf("invalid proxy_protocol 0, 1 and 2 are supported, configured: %v reset proxy_protocol to 0",
  249. globalConf.Common.ProxyProtocol)
  250. globalConf.Common.ProxyProtocol = 0
  251. logger.Warn(logSender, "", "Configuration error: %v", err)
  252. logger.WarnToConsole("Configuration error: %v", err)
  253. }
  254. if globalConf.ProviderConf.ExternalAuthScope < 0 || globalConf.ProviderConf.ExternalAuthScope > 7 {
  255. err = fmt.Errorf("invalid external_auth_scope: %v reset to 0", globalConf.ProviderConf.ExternalAuthScope)
  256. globalConf.ProviderConf.ExternalAuthScope = 0
  257. logger.Warn(logSender, "", "Configuration error: %v", err)
  258. logger.WarnToConsole("Configuration error: %v", err)
  259. }
  260. if len(globalConf.ProviderConf.CredentialsPath) == 0 {
  261. err = fmt.Errorf("invalid credentials path, reset to \"credentials\"")
  262. globalConf.ProviderConf.CredentialsPath = "credentials"
  263. logger.Warn(logSender, "", "Configuration error: %v", err)
  264. logger.WarnToConsole("Configuration error: %v", err)
  265. }
  266. checkHostKeyCompatibility()
  267. logger.Debug(logSender, "", "config file used: '%#v', config loaded: %+v", viper.ConfigFileUsed(), getRedactedGlobalConf())
  268. return err
  269. }
  270. func checkHostKeyCompatibility() {
  271. // we copy deprecated fields to new ones to keep backward compatibility so lint is disabled
  272. if len(globalConf.SFTPD.Keys) > 0 && len(globalConf.SFTPD.HostKeys) == 0 { //nolint:staticcheck
  273. logger.Warn(logSender, "", "keys is deprecated, please use host_keys")
  274. logger.WarnToConsole("keys is deprecated, please use host_keys")
  275. for _, k := range globalConf.SFTPD.Keys { //nolint:staticcheck
  276. globalConf.SFTPD.HostKeys = append(globalConf.SFTPD.HostKeys, k.PrivateKey)
  277. }
  278. }
  279. }
  280. func checkCommonParamsCompatibility() {
  281. // we copy deprecated fields to new ones to keep backward compatibility so lint is disabled
  282. if globalConf.SFTPD.IdleTimeout > 0 { //nolint:staticcheck
  283. logger.Warn(logSender, "", "sftpd.idle_timeout is deprecated, please use common.idle_timeout")
  284. logger.WarnToConsole("sftpd.idle_timeout is deprecated, please use common.idle_timeout")
  285. globalConf.Common.IdleTimeout = globalConf.SFTPD.IdleTimeout //nolint:staticcheck
  286. }
  287. if len(globalConf.SFTPD.Actions.Hook) > 0 && len(globalConf.Common.Actions.Hook) == 0 { //nolint:staticcheck
  288. logger.Warn(logSender, "", "sftpd.actions is deprecated, please use common.actions")
  289. logger.WarnToConsole("sftpd.actions is deprecated, please use common.actions")
  290. globalConf.Common.Actions.ExecuteOn = globalConf.SFTPD.Actions.ExecuteOn //nolint:staticcheck
  291. globalConf.Common.Actions.Hook = globalConf.SFTPD.Actions.Hook //nolint:staticcheck
  292. }
  293. if globalConf.SFTPD.SetstatMode > 0 && globalConf.Common.SetstatMode == 0 { //nolint:staticcheck
  294. logger.Warn(logSender, "", "sftpd.setstat_mode is deprecated, please use common.setstat_mode")
  295. logger.WarnToConsole("sftpd.setstat_mode is deprecated, please use common.setstat_mode")
  296. globalConf.Common.SetstatMode = globalConf.SFTPD.SetstatMode //nolint:staticcheck
  297. }
  298. if globalConf.SFTPD.UploadMode > 0 && globalConf.Common.UploadMode == 0 { //nolint:staticcheck
  299. logger.Warn(logSender, "", "sftpd.upload_mode is deprecated, please use common.upload_mode")
  300. logger.WarnToConsole("sftpd.upload_mode is deprecated, please use common.upload_mode")
  301. globalConf.Common.UploadMode = globalConf.SFTPD.UploadMode //nolint:staticcheck
  302. }
  303. if globalConf.SFTPD.ProxyProtocol > 0 && globalConf.Common.ProxyProtocol == 0 { //nolint:staticcheck
  304. logger.Warn(logSender, "", "sftpd.proxy_protocol is deprecated, please use common.proxy_protocol")
  305. logger.WarnToConsole("sftpd.proxy_protocol is deprecated, please use common.proxy_protocol")
  306. globalConf.Common.ProxyProtocol = globalConf.SFTPD.ProxyProtocol //nolint:staticcheck
  307. globalConf.Common.ProxyAllowed = globalConf.SFTPD.ProxyAllowed //nolint:staticcheck
  308. }
  309. }