config.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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/log"
  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. // TLS Configuration
  35. TLS ServerTLSConfig `json:"tls,omitempty"`
  36. // LogFile is where the logs go. Use path to file, or "stderr", "stdout" or "off".
  37. // defaults to AppConfig.Log file setting
  38. LogFile string `json:"log_file,omitempty"`
  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. // Listen interface specified in <ip>:<port> - defaults to 127.0.0.1:2525
  43. ListenInterface string `json:"listen_interface"`
  44. // MaxSize is the maximum size of an email that will be accepted for delivery.
  45. // Defaults to 10 Mebibytes
  46. MaxSize int64 `json:"max_size"`
  47. // Timeout specifies the connection timeout in seconds. Defaults to 30
  48. Timeout int `json:"timeout"`
  49. // MaxClients controls how many maximum clients we can handle at once.
  50. // Defaults to defaultMaxClients
  51. MaxClients int `json:"max_clients"`
  52. // IsEnabled set to true to start the server, false will ignore it
  53. IsEnabled bool `json:"is_enabled"`
  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. // TLS Protocols to use. [0] = min, [1]max
  60. // Use Go's default if empty
  61. Protocols []string `json:"protocols,omitempty"`
  62. // TLS Ciphers to use.
  63. // Use Go's default if empty
  64. Ciphers []string `json:"ciphers,omitempty"`
  65. // TLS Curves to use.
  66. // Use Go's default if empty
  67. Curves []string `json:"curves,omitempty"`
  68. // PrivateKeyFile path to cert private key in PEM format.
  69. PrivateKeyFile string `json:"private_key_file"`
  70. // PublicKeyFile path to cert (public key) chain in PEM format.
  71. PublicKeyFile string `json:"public_key_file"`
  72. // TLS Root cert authorities to use. "A PEM encoded CA's certificate file.
  73. // Defaults to system's root CA file if empty
  74. RootCAs string `json:"root_cas_file,omitempty"`
  75. // declares the policy the server will follow for TLS Client Authentication.
  76. // Use Go's default if empty
  77. ClientAuthType string `json:"client_auth_type,omitempty"`
  78. // The following used to watch certificate changes so that the TLS can be reloaded
  79. _privateKeyFileMtime int64
  80. _publicKeyFileMtime int64
  81. // controls whether the server selects the
  82. // client's most preferred cipher suite
  83. PreferServerCipherSuites bool `json:"prefer_server_cipher_suites,omitempty"`
  84. // StartTLSOn should we offer STARTTLS command. Cert must be valid.
  85. // False by default
  86. StartTLSOn bool `json:"start_tls_on,omitempty"`
  87. // AlwaysOn run this server as a pure TLS server, i.e. SMTPS
  88. AlwaysOn bool `json:"tls_always_on,omitempty"`
  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 fmt.Errorf("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 fmt.Errorf(
  379. "could not stat key for server [%s], %s",
  380. iface,
  381. err.Error())
  382. }
  383. if sc.TLS.PrivateKeyFile == "" {
  384. sc.TLS._privateKeyFileMtime = time.Now().Unix()
  385. return nil
  386. }
  387. if sc.TLS.PublicKeyFile == "" {
  388. sc.TLS._publicKeyFileMtime = time.Now().Unix()
  389. return nil
  390. }
  391. if info, err := os.Stat(sc.TLS.PrivateKeyFile); err == nil {
  392. sc.TLS._privateKeyFileMtime = info.ModTime().Unix()
  393. } else {
  394. return statErr(sc.ListenInterface, err)
  395. }
  396. if info, err := os.Stat(sc.TLS.PublicKeyFile); err == nil {
  397. sc.TLS._publicKeyFileMtime = info.ModTime().Unix()
  398. } else {
  399. return statErr(sc.ListenInterface, err)
  400. }
  401. return nil
  402. }
  403. // Validate validates the server's configuration.
  404. func (sc *ServerConfig) Validate() error {
  405. var errs Errors
  406. if sc.TLS.StartTLSOn || sc.TLS.AlwaysOn {
  407. if sc.TLS.PublicKeyFile == "" {
  408. errs = append(errs, errors.New("PublicKeyFile is empty"))
  409. }
  410. if sc.TLS.PrivateKeyFile == "" {
  411. errs = append(errs, errors.New("PrivateKeyFile is empty"))
  412. }
  413. if _, err := tls.LoadX509KeyPair(sc.TLS.PublicKeyFile, sc.TLS.PrivateKeyFile); err != nil {
  414. errs = append(errs, fmt.Errorf("cannot use TLS config for [%s], %v", sc.ListenInterface, err))
  415. }
  416. }
  417. if len(errs) > 0 {
  418. return errs
  419. }
  420. return nil
  421. }
  422. // Gets the timestamp of the TLS certificates. Returns a unix time of when they were last modified
  423. // when the config was read. We use this info to determine if TLS needs to be re-loaded.
  424. func (stc *ServerTLSConfig) getTlsKeyTimestamps() (int64, int64) {
  425. return stc._privateKeyFileMtime, stc._publicKeyFileMtime
  426. }
  427. // Returns value changes between struct a & struct b.
  428. // Results are returned in a map, where each key is the name of the field that was different.
  429. // a and b are struct values, must not be pointer
  430. // and of the same struct type
  431. func getChanges(a interface{}, b interface{}) map[string]interface{} {
  432. ret := make(map[string]interface{}, 5)
  433. compareWith := structtomap(b)
  434. for key, val := range structtomap(a) {
  435. if sliceOfStr, ok := val.([]string); ok {
  436. val, _ = json.Marshal(sliceOfStr)
  437. val = string(val.([]uint8))
  438. }
  439. if sliceOfStr, ok := compareWith[key].([]string); ok {
  440. compareWith[key], _ = json.Marshal(sliceOfStr)
  441. compareWith[key] = string(compareWith[key].([]uint8))
  442. }
  443. if val != compareWith[key] {
  444. ret[key] = compareWith[key]
  445. }
  446. }
  447. // detect changes to TLS keys (have the key files been modified?)
  448. if oldTLS, ok := a.(ServerTLSConfig); ok {
  449. t1, t2 := oldTLS.getTlsKeyTimestamps()
  450. if newTLS, ok := b.(ServerTLSConfig); ok {
  451. t3, t4 := newTLS.getTlsKeyTimestamps()
  452. if t1 != t3 {
  453. ret["PrivateKeyFile"] = newTLS.PrivateKeyFile
  454. }
  455. if t2 != t4 {
  456. ret["PublicKeyFile"] = newTLS.PublicKeyFile
  457. }
  458. }
  459. }
  460. return ret
  461. }
  462. // Convert fields of a struct to a map
  463. // only able to convert int, bool, slice-of-strings and string; not recursive
  464. // slices are marshal'd to json for convenient comparison later
  465. func structtomap(obj interface{}) map[string]interface{} {
  466. ret := make(map[string]interface{})
  467. v := reflect.ValueOf(obj)
  468. t := v.Type()
  469. for index := 0; index < v.NumField(); index++ {
  470. vField := v.Field(index)
  471. fName := t.Field(index).Name
  472. k := vField.Kind()
  473. switch k {
  474. case reflect.Int:
  475. fallthrough
  476. case reflect.Int64:
  477. value := vField.Int()
  478. ret[fName] = value
  479. case reflect.String:
  480. value := vField.String()
  481. ret[fName] = value
  482. case reflect.Bool:
  483. value := vField.Bool()
  484. ret[fName] = value
  485. case reflect.Slice:
  486. ret[fName] = vField.Interface().([]string)
  487. }
  488. }
  489. return ret
  490. }