config.go 17 KB

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