config.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. package guerrilla
  2. import (
  3. "crypto/tls"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/flashmob/go-guerrilla/backends"
  8. "github.com/flashmob/go-guerrilla/log"
  9. "os"
  10. "reflect"
  11. "strings"
  12. "time"
  13. )
  14. // AppConfig is the holder of the configuration of the app
  15. type AppConfig struct {
  16. // Servers can have one or more items.
  17. /// Defaults to 1 server listening on 127.0.0.1:2525
  18. Servers []ServerConfig `json:"servers"`
  19. // AllowedHosts lists which hosts to accept email for. Defaults to os.Hostname
  20. AllowedHosts []string `json:"allowed_hosts"`
  21. // PidFile is the path for writing out the process id. No output if empty
  22. PidFile string `json:"pid_file"`
  23. // LogFile is where the logs go. Use path to file, or "stderr", "stdout"
  24. // or "off". Default "stderr"
  25. LogFile string `json:"log_file,omitempty"`
  26. // LogLevel controls the lowest level we log.
  27. // "info", "debug", "error", "panic". Default "info"
  28. LogLevel string `json:"log_level,omitempty"`
  29. // BackendConfig configures the email envelope processing backend
  30. BackendConfig backends.BackendConfig `json:"backend_config"`
  31. }
  32. // ServerConfig specifies config options for a single server
  33. type ServerConfig struct {
  34. // IsEnabled set to true to start the server, false will ignore it
  35. IsEnabled bool `json:"is_enabled"`
  36. // Hostname will be used in the server's reply to HELO/EHLO. If TLS enabled
  37. // make sure that the Hostname matches the cert. Defaults to os.Hostname()
  38. Hostname string `json:"host_name"`
  39. // MaxSize is the maximum size of an email that will be accepted for delivery.
  40. // Defaults to 10 Mebibytes
  41. MaxSize int64 `json:"max_size"`
  42. // TLS Configuration
  43. TLS ServerTLSConfig `json:"tls,omitempty"`
  44. // Timeout specifies the connection timeout in seconds. Defaults to 30
  45. Timeout int `json:"timeout"`
  46. // Listen interface specified in <ip>:<port> - defaults to 127.0.0.1:2525
  47. ListenInterface string `json:"listen_interface"`
  48. // MaxClients controls how many maximum clients we can handle at once.
  49. // Defaults to defaultMaxClients
  50. MaxClients int `json:"max_clients"`
  51. // LogFile is where the logs go. Use path to file, or "stderr", "stdout" or "off".
  52. // defaults to AppConfig.Log file setting
  53. LogFile string `json:"log_file,omitempty"`
  54. // XClientOn when using a proxy such as Nginx, XCLIENT command is used to pass the
  55. // original client's IP address & client's HELO
  56. XClientOn bool `json:"xclient_on,omitempty"`
  57. }
  58. type ServerTLSConfig struct {
  59. // StartTLSOn should we offer STARTTLS command. Cert must be valid.
  60. // False by default
  61. StartTLSOn bool `json:"start_tls_on,omitempty"`
  62. // AlwaysOn run this server as a pure TLS server, i.e. SMTPS
  63. AlwaysOn bool `json:"tls_always_on,omitempty"`
  64. // PrivateKeyFile path to cert private key in PEM format.
  65. PrivateKeyFile string `json:"private_key_file"`
  66. // PublicKeyFile path to cert (public key) chain in PEM format.
  67. PublicKeyFile string `json:"public_key_file"`
  68. // TLS Protocols to use. [0] = min, [1]max
  69. // Use Go's default if empty
  70. Protocols []string `json:"protocols,omitempty"`
  71. // TLS Ciphers to use.
  72. // Use Go's default if empty
  73. Ciphers []string `json:"ciphers,omitempty"`
  74. // TLS Curves to use.
  75. // Use Go's default if empty
  76. Curves []string `json:"curves,omitempty"`
  77. // TLS Root cert authorities to use. "A PEM encoded CA's certificate file.
  78. // Defaults to system's root CA file if empty
  79. RootCAs string `json:"root_cas_file,omitempty"`
  80. // declares the policy the server will follow for TLS Client Authentication.
  81. // Use Go's default if empty
  82. ClientAuthType string `json:"client_auth_type,omitempty"`
  83. // controls whether the server selects the
  84. // client's most preferred cipher suite
  85. PreferServerCipherSuites bool `json:"prefer_server_cipher_suites,omitempty"`
  86. // The following used to watch certificate changes so that the TLS can be reloaded
  87. _privateKeyFileMtime int64
  88. _publicKeyFileMtime int64
  89. }
  90. // https://golang.org/pkg/crypto/tls/#pkg-constants
  91. // Ciphers introduced before Go 1.7 are listed here,
  92. // ciphers since Go 1.8, see tls_go1.8.go
  93. var TLSCiphers = map[string]uint16{
  94. // // Note: Generally avoid using CBC unless for compatibility
  95. "TLS_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  96. "TLS_RSA_WITH_AES_128_CBC_SHA": tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  97. "TLS_RSA_WITH_AES_256_CBC_SHA": tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  98. "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  99. "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  100. "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  101. "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  102. "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA": tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  103. "TLS_RSA_WITH_RC4_128_SHA": tls.TLS_RSA_WITH_RC4_128_SHA,
  104. "TLS_RSA_WITH_AES_128_GCM_SHA256": tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
  105. "TLS_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
  106. "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  107. "TLS_ECDHE_RSA_WITH_RC4_128_SHA": tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
  108. "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  109. "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  110. "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  111. // Include to prevent downgrade attacks
  112. "TLS_FALLBACK_SCSV": tls.TLS_FALLBACK_SCSV,
  113. }
  114. // https://golang.org/pkg/crypto/tls/#pkg-constants
  115. var TLSProtocols = map[string]uint16{
  116. "ssl3.0": tls.VersionSSL30,
  117. "tls1.0": tls.VersionTLS10,
  118. "tls1.1": tls.VersionTLS11,
  119. "tls1.2": tls.VersionTLS12,
  120. }
  121. // https://golang.org/pkg/crypto/tls/#CurveID
  122. var TLSCurves = map[string]tls.CurveID{
  123. "P256": tls.CurveP256,
  124. "P384": tls.CurveP384,
  125. "P521": tls.CurveP521,
  126. }
  127. // https://golang.org/pkg/crypto/tls/#ClientAuthType
  128. var TLSClientAuthTypes = map[string]tls.ClientAuthType{
  129. "NoClientCert": tls.NoClientCert,
  130. "RequestClientCert": tls.RequestClientCert,
  131. "RequireAnyClientCert": tls.RequireAnyClientCert,
  132. "VerifyClientCertIfGiven": tls.VerifyClientCertIfGiven,
  133. "RequireAndVerifyClientCert": tls.RequireAndVerifyClientCert,
  134. }
  135. const defaultMaxClients = 100
  136. const defaultTimeout = 30
  137. const defaultInterface = "127.0.0.1:2525"
  138. const defaultMaxSize = int64(10 << 20) // 10 Mebibytes
  139. // Unmarshalls json data into AppConfig struct and any other initialization of the struct
  140. // also does validation, returns error if validation failed or something went wrong
  141. func (c *AppConfig) Load(jsonBytes []byte) error {
  142. err := json.Unmarshal(jsonBytes, c)
  143. if err != nil {
  144. return fmt.Errorf("could not parse config file: %s", err)
  145. }
  146. if err = c.setDefaults(); err != nil {
  147. return err
  148. }
  149. if err = c.setBackendDefaults(); err != nil {
  150. return err
  151. }
  152. // all servers must be valid in order to continue
  153. for _, server := range c.Servers {
  154. if errs := server.Validate(); errs != nil {
  155. return errs
  156. }
  157. }
  158. // read the timestamps for the ssl keys, to determine if they need to be reloaded
  159. for i := 0; i < len(c.Servers); i++ {
  160. if err := c.Servers[i].loadTlsKeyTimestamps(); err != nil {
  161. return err
  162. }
  163. }
  164. return nil
  165. }
  166. // Emits any configuration change events onto the event bus.
  167. func (c *AppConfig) EmitChangeEvents(oldConfig *AppConfig, app Guerrilla) {
  168. // has backend changed?
  169. if !reflect.DeepEqual((*c).BackendConfig, (*oldConfig).BackendConfig) {
  170. app.Publish(EventConfigBackendConfig, c)
  171. }
  172. // has config changed, general check
  173. if !reflect.DeepEqual(oldConfig, c) {
  174. app.Publish(EventConfigNewConfig, c)
  175. }
  176. // has 'allowed hosts' changed?
  177. if !reflect.DeepEqual(oldConfig.AllowedHosts, c.AllowedHosts) {
  178. app.Publish(EventConfigAllowedHosts, c)
  179. }
  180. // has pid file changed?
  181. if strings.Compare(oldConfig.PidFile, c.PidFile) != 0 {
  182. app.Publish(EventConfigPidFile, c)
  183. }
  184. // has mainlog log changed?
  185. if strings.Compare(oldConfig.LogFile, c.LogFile) != 0 {
  186. app.Publish(EventConfigLogFile, c)
  187. }
  188. // has log level changed?
  189. if strings.Compare(oldConfig.LogLevel, c.LogLevel) != 0 {
  190. app.Publish(EventConfigLogLevel, c)
  191. }
  192. // server config changes
  193. oldServers := oldConfig.getServers()
  194. for iface, newServer := range c.getServers() {
  195. // is server is in both configs?
  196. if oldServer, ok := oldServers[iface]; ok {
  197. // since old server exists in the new config, we do not track it anymore
  198. delete(oldServers, iface)
  199. // so we know the server exists in both old & new configs
  200. newServer.emitChangeEvents(oldServer, app)
  201. } else {
  202. // start new server
  203. app.Publish(EventConfigServerNew, newServer)
  204. }
  205. }
  206. // remove any servers that don't exist anymore
  207. for _, oldServer := range oldServers {
  208. app.Publish(EventConfigServerRemove, oldServer)
  209. }
  210. }
  211. // EmitLogReopen emits log reopen events using existing config
  212. func (c *AppConfig) EmitLogReopenEvents(app Guerrilla) {
  213. app.Publish(EventConfigLogReopen, c)
  214. for _, sc := range c.getServers() {
  215. app.Publish(EventConfigServerLogReopen, sc)
  216. }
  217. }
  218. // gets the servers in a map (key by interface) for easy lookup
  219. func (c *AppConfig) getServers() map[string]*ServerConfig {
  220. servers := make(map[string]*ServerConfig, len(c.Servers))
  221. for i := 0; i < len(c.Servers); i++ {
  222. servers[c.Servers[i].ListenInterface] = &c.Servers[i]
  223. }
  224. return servers
  225. }
  226. // setDefaults fills in default server settings for values that were not configured
  227. // The defaults are:
  228. // * Server listening to 127.0.0.1:2525
  229. // * use your hostname to determine your which hosts to accept email for
  230. // * 100 maximum clients
  231. // * 10MB max message size
  232. // * log to Stderr,
  233. // * log level set to "`debug`"
  234. // * timeout to 30 sec
  235. // * Backend configured with the following processors: `HeadersParser|Header|Debugger`
  236. // where it will log the received emails.
  237. func (c *AppConfig) setDefaults() error {
  238. if c.LogFile == "" {
  239. c.LogFile = log.OutputStderr.String()
  240. }
  241. if c.LogLevel == "" {
  242. c.LogLevel = "debug"
  243. }
  244. if len(c.AllowedHosts) == 0 {
  245. if h, err := os.Hostname(); err != nil {
  246. return err
  247. } else {
  248. c.AllowedHosts = append(c.AllowedHosts, h)
  249. }
  250. }
  251. h, err := os.Hostname()
  252. if err != nil {
  253. return err
  254. }
  255. if len(c.Servers) == 0 {
  256. sc := ServerConfig{}
  257. sc.LogFile = c.LogFile
  258. sc.ListenInterface = defaultInterface
  259. sc.IsEnabled = true
  260. sc.Hostname = h
  261. sc.MaxClients = defaultMaxClients
  262. sc.Timeout = defaultTimeout
  263. sc.MaxSize = defaultMaxSize
  264. c.Servers = append(c.Servers, sc)
  265. } else {
  266. // make sure each server has defaults correctly configured
  267. for i := range c.Servers {
  268. if c.Servers[i].Hostname == "" {
  269. c.Servers[i].Hostname = h
  270. }
  271. if c.Servers[i].MaxClients == 0 {
  272. c.Servers[i].MaxClients = defaultMaxClients
  273. }
  274. if c.Servers[i].Timeout == 0 {
  275. c.Servers[i].Timeout = defaultTimeout
  276. }
  277. if c.Servers[i].MaxSize == 0 {
  278. c.Servers[i].MaxSize = defaultMaxSize // 10 Mebibytes
  279. }
  280. if c.Servers[i].ListenInterface == "" {
  281. return errors.New(fmt.Sprintf("Listen interface not specified for server at index %d", i))
  282. }
  283. if c.Servers[i].LogFile == "" {
  284. c.Servers[i].LogFile = c.LogFile
  285. }
  286. // validate the server config
  287. err = c.Servers[i].Validate()
  288. if err != nil {
  289. return err
  290. }
  291. }
  292. }
  293. return nil
  294. }
  295. // setBackendDefaults sets default values for the backend config,
  296. // if no backend config was added before starting, then use a default config
  297. // otherwise, see what required values were missed in the config and add any missing with defaults
  298. func (c *AppConfig) setBackendDefaults() error {
  299. if len(c.BackendConfig) == 0 {
  300. h, err := os.Hostname()
  301. if err != nil {
  302. return err
  303. }
  304. c.BackendConfig = backends.BackendConfig{
  305. "log_received_mails": true,
  306. "save_workers_size": 1,
  307. "save_process": "HeadersParser|Header|Debugger",
  308. "primary_mail_host": h,
  309. }
  310. } else {
  311. if _, ok := c.BackendConfig["save_process"]; !ok {
  312. c.BackendConfig["save_process"] = "HeadersParser|Header|Debugger"
  313. }
  314. if _, ok := c.BackendConfig["primary_mail_host"]; !ok {
  315. h, err := os.Hostname()
  316. if err != nil {
  317. return err
  318. }
  319. c.BackendConfig["primary_mail_host"] = h
  320. }
  321. if _, ok := c.BackendConfig["save_workers_size"]; !ok {
  322. c.BackendConfig["save_workers_size"] = 1
  323. }
  324. if _, ok := c.BackendConfig["log_received_mails"]; !ok {
  325. c.BackendConfig["log_received_mails"] = false
  326. }
  327. }
  328. return nil
  329. }
  330. // Emits any configuration change events on the server.
  331. // All events are fired and run synchronously
  332. func (sc *ServerConfig) emitChangeEvents(oldServer *ServerConfig, app Guerrilla) {
  333. // get a list of changes
  334. changes := getChanges(
  335. *oldServer,
  336. *sc,
  337. )
  338. tlsChanges := getChanges(
  339. (*oldServer).TLS,
  340. (*sc).TLS,
  341. )
  342. if len(changes) > 0 || len(tlsChanges) > 0 {
  343. // something changed in the server config
  344. app.Publish(EventConfigServerConfig, sc)
  345. }
  346. // enable or disable?
  347. if _, ok := changes["IsEnabled"]; ok {
  348. if sc.IsEnabled {
  349. app.Publish(EventConfigServerStart, sc)
  350. } else {
  351. app.Publish(EventConfigServerStop, sc)
  352. }
  353. // do not emit any more events when IsEnabled changed
  354. return
  355. }
  356. // log file change?
  357. if _, ok := changes["LogFile"]; ok {
  358. app.Publish(EventConfigServerLogFile, sc)
  359. } else {
  360. // since config file has not changed, we reload it
  361. app.Publish(EventConfigServerLogReopen, sc)
  362. }
  363. // timeout changed
  364. if _, ok := changes["Timeout"]; ok {
  365. app.Publish(EventConfigServerTimeout, sc)
  366. }
  367. // max_clients changed
  368. if _, ok := changes["MaxClients"]; ok {
  369. app.Publish(EventConfigServerMaxClients, sc)
  370. }
  371. if len(tlsChanges) > 0 {
  372. app.Publish(EventConfigServerTLSConfig, sc)
  373. }
  374. }
  375. // Loads in timestamps for the ssl keys
  376. func (sc *ServerConfig) loadTlsKeyTimestamps() error {
  377. var statErr = func(iface string, err error) error {
  378. return errors.New(
  379. fmt.Sprintf(
  380. "could not stat key for server [%s], %s",
  381. iface,
  382. err.Error()))
  383. }
  384. if sc.TLS.PrivateKeyFile == "" {
  385. sc.TLS._privateKeyFileMtime = time.Now().Unix()
  386. return nil
  387. }
  388. if sc.TLS.PublicKeyFile == "" {
  389. sc.TLS._publicKeyFileMtime = time.Now().Unix()
  390. return nil
  391. }
  392. if info, err := os.Stat(sc.TLS.PrivateKeyFile); err == nil {
  393. sc.TLS._privateKeyFileMtime = info.ModTime().Unix()
  394. } else {
  395. return statErr(sc.ListenInterface, err)
  396. }
  397. if info, err := os.Stat(sc.TLS.PublicKeyFile); err == nil {
  398. sc.TLS._publicKeyFileMtime = info.ModTime().Unix()
  399. } else {
  400. return statErr(sc.ListenInterface, err)
  401. }
  402. return nil
  403. }
  404. // Validate validates the server's configuration.
  405. func (sc *ServerConfig) Validate() error {
  406. var errs Errors
  407. if sc.TLS.StartTLSOn || sc.TLS.AlwaysOn {
  408. if sc.TLS.PublicKeyFile == "" {
  409. errs = append(errs, errors.New("PublicKeyFile is empty"))
  410. }
  411. if sc.TLS.PrivateKeyFile == "" {
  412. errs = append(errs, errors.New("PrivateKeyFile is empty"))
  413. }
  414. if _, err := tls.LoadX509KeyPair(sc.TLS.PublicKeyFile, sc.TLS.PrivateKeyFile); err != nil {
  415. errs = append(errs,
  416. errors.New(fmt.Sprintf("cannot use TLS config for [%s], %v", sc.ListenInterface, err)))
  417. }
  418. }
  419. if len(errs) > 0 {
  420. return errs
  421. }
  422. return nil
  423. }
  424. // Gets the timestamp of the TLS certificates. Returns a unix time of when they were last modified
  425. // when the config was read. We use this info to determine if TLS needs to be re-loaded.
  426. func (stc *ServerTLSConfig) getTlsKeyTimestamps() (int64, int64) {
  427. return stc._privateKeyFileMtime, stc._publicKeyFileMtime
  428. }
  429. // Returns value changes between struct a & struct b.
  430. // Results are returned in a map, where each key is the name of the field that was different.
  431. // a and b are struct values, must not be pointer
  432. // and of the same struct type
  433. func getChanges(a interface{}, b interface{}) map[string]interface{} {
  434. ret := make(map[string]interface{}, 5)
  435. compareWith := structtomap(b)
  436. for key, val := range structtomap(a) {
  437. if sliceOfStr, ok := val.([]string); ok {
  438. val, _ = json.Marshal(sliceOfStr)
  439. val = string(val.([]uint8))
  440. }
  441. if sliceOfStr, ok := compareWith[key].([]string); ok {
  442. compareWith[key], _ = json.Marshal(sliceOfStr)
  443. compareWith[key] = string(compareWith[key].([]uint8))
  444. }
  445. if val != compareWith[key] {
  446. ret[key] = compareWith[key]
  447. }
  448. }
  449. // detect changes to TLS keys (have the key files been modified?)
  450. if oldTLS, ok := a.(ServerTLSConfig); ok {
  451. t1, t2 := oldTLS.getTlsKeyTimestamps()
  452. if newTLS, ok := b.(ServerTLSConfig); ok {
  453. t3, t4 := newTLS.getTlsKeyTimestamps()
  454. if t1 != t3 {
  455. ret["PrivateKeyFile"] = newTLS.PrivateKeyFile
  456. }
  457. if t2 != t4 {
  458. ret["PublicKeyFile"] = newTLS.PublicKeyFile
  459. }
  460. }
  461. }
  462. return ret
  463. }
  464. // Convert fields of a struct to a map
  465. // only able to convert int, bool, slice-of-strings and string; not recursive
  466. // slices are marshal'd to json for convenient comparison later
  467. func structtomap(obj interface{}) map[string]interface{} {
  468. ret := make(map[string]interface{}, 0)
  469. v := reflect.ValueOf(obj)
  470. t := v.Type()
  471. for index := 0; index < v.NumField(); index++ {
  472. vField := v.Field(index)
  473. fName := t.Field(index).Name
  474. k := vField.Kind()
  475. switch k {
  476. case reflect.Int:
  477. fallthrough
  478. case reflect.Int64:
  479. value := vField.Int()
  480. ret[fName] = value
  481. case reflect.String:
  482. value := vField.String()
  483. ret[fName] = value
  484. case reflect.Bool:
  485. value := vField.Bool()
  486. ret[fName] = value
  487. case reflect.Slice:
  488. ret[fName] = vField.Interface().([]string)
  489. }
  490. }
  491. return ret
  492. }