You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2014-2015 Edmund Huber
  3. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  4. // released under the MIT license
  5. package irc
  6. import (
  7. "crypto/tls"
  8. "errors"
  9. "fmt"
  10. "io/ioutil"
  11. "log"
  12. "strings"
  13. "time"
  14. "github.com/oragono/oragono/irc/custime"
  15. "github.com/oragono/oragono/irc/logger"
  16. "code.cloudfoundry.org/bytefmt"
  17. "gopkg.in/yaml.v2"
  18. )
  19. // PassConfig holds the connection password.
  20. type PassConfig struct {
  21. Password string
  22. }
  23. // TLSListenConfig defines configuration options for listening on TLS.
  24. type TLSListenConfig struct {
  25. Cert string
  26. Key string
  27. }
  28. // Config returns the TLS contiguration assicated with this TLSListenConfig.
  29. func (conf *TLSListenConfig) Config() (*tls.Config, error) {
  30. cert, err := tls.LoadX509KeyPair(conf.Cert, conf.Key)
  31. if err != nil {
  32. return nil, errors.New("tls cert+key: invalid pair")
  33. }
  34. return &tls.Config{
  35. Certificates: []tls.Certificate{cert},
  36. }, err
  37. }
  38. // PasswordBytes returns the bytes represented by the password hash.
  39. func (conf *PassConfig) PasswordBytes() []byte {
  40. bytes, err := DecodePasswordHash(conf.Password)
  41. if err != nil {
  42. log.Fatal("decode password error: ", err)
  43. }
  44. return bytes
  45. }
  46. // AccountRegistrationConfig controls account registration.
  47. type AccountRegistrationConfig struct {
  48. Enabled bool
  49. EnabledCallbacks []string `yaml:"enabled-callbacks"`
  50. Callbacks struct {
  51. Mailto struct {
  52. Server string
  53. Port int
  54. TLS struct {
  55. Enabled bool
  56. InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
  57. ServerName string `yaml:"servername"`
  58. }
  59. Username string
  60. Password string
  61. Sender string
  62. VerifyMessageSubject string `yaml:"verify-message-subject"`
  63. VerifyMessage string `yaml:"verify-message"`
  64. }
  65. }
  66. AllowMultiplePerConnection bool `yaml:"allow-multiple-per-connection"`
  67. }
  68. // ChannelRegistrationConfig controls channel registration.
  69. type ChannelRegistrationConfig struct {
  70. Enabled bool
  71. }
  72. // OperClassConfig defines a specific operator class.
  73. type OperClassConfig struct {
  74. Title string
  75. WhoisLine string
  76. Extends string
  77. Capabilities []string
  78. }
  79. // OperConfig defines a specific operator's configuration.
  80. type OperConfig struct {
  81. Class string
  82. Vhost string
  83. WhoisLine string `yaml:"whois-line"`
  84. Password string
  85. Modes string
  86. }
  87. // PasswordBytes returns the bytes represented by the password hash.
  88. func (conf *OperConfig) PasswordBytes() []byte {
  89. bytes, err := DecodePasswordHash(conf.Password)
  90. if err != nil {
  91. log.Fatal("decode password error: ", err)
  92. }
  93. return bytes
  94. }
  95. // RestAPIConfig controls the integrated REST API.
  96. type RestAPIConfig struct {
  97. Enabled bool
  98. Listen string
  99. }
  100. // ConnectionLimitsConfig controls the automated connection limits.
  101. type ConnectionLimitsConfig struct {
  102. Enabled bool
  103. CidrLenIPv4 int `yaml:"cidr-len-ipv4"`
  104. CidrLenIPv6 int `yaml:"cidr-len-ipv6"`
  105. IPsPerCidr int `yaml:"ips-per-subnet"`
  106. Exempted []string
  107. }
  108. // ConnectionThrottleConfig controls the automated connection throttling.
  109. type ConnectionThrottleConfig struct {
  110. Enabled bool
  111. CidrLenIPv4 int `yaml:"cidr-len-ipv4"`
  112. CidrLenIPv6 int `yaml:"cidr-len-ipv6"`
  113. ConnectionsPerCidr int `yaml:"max-connections"`
  114. DurationString string `yaml:"duration"`
  115. Duration time.Duration `yaml:"duration-time"`
  116. BanDurationString string `yaml:"ban-duration"`
  117. BanDuration time.Duration
  118. BanMessage string `yaml:"ban-message"`
  119. Exempted []string
  120. }
  121. // LoggingConfig controls a single logging method.
  122. type LoggingConfig struct {
  123. Method string
  124. MethodStdout bool
  125. MethodStderr bool
  126. MethodFile bool
  127. Filename string
  128. TypeString string `yaml:"type"`
  129. Types []string `yaml:"real-types"`
  130. ExcludedTypes []string `yaml:"real-excluded-types"`
  131. LevelString string `yaml:"level"`
  132. Level logger.Level `yaml:"level-real"`
  133. }
  134. // LineLenConfig controls line lengths.
  135. type LineLenConfig struct {
  136. Tags int
  137. Rest int
  138. }
  139. // STSConfig controls the STS configuration/
  140. type STSConfig struct {
  141. Enabled bool
  142. Duration time.Duration `yaml:"duration-real"`
  143. DurationString string `yaml:"duration"`
  144. Port int
  145. Preload bool
  146. }
  147. // Value returns the STS value to advertise in CAP
  148. func (sts *STSConfig) Value() string {
  149. val := fmt.Sprintf("duration=%d,", int(sts.Duration.Seconds()))
  150. if sts.Enabled && sts.Port > 0 {
  151. val += fmt.Sprintf(",port=%d", sts.Port)
  152. }
  153. if sts.Enabled && sts.Preload {
  154. val += ",preload"
  155. }
  156. return val
  157. }
  158. // StackImpactConfig is the config used for StackImpact's profiling.
  159. type StackImpactConfig struct {
  160. Enabled bool
  161. AgentKey string `yaml:"agent-key"`
  162. AppName string `yaml:"app-name"`
  163. }
  164. // Config defines the overall configuration.
  165. type Config struct {
  166. Network struct {
  167. Name string
  168. }
  169. Server struct {
  170. PassConfig
  171. Password string
  172. Name string
  173. Listen []string
  174. Wslisten string `yaml:"ws-listen"`
  175. TLSListeners map[string]*TLSListenConfig `yaml:"tls-listeners"`
  176. STS STSConfig
  177. RestAPI RestAPIConfig `yaml:"rest-api"`
  178. CheckIdent bool `yaml:"check-ident"`
  179. MOTD string
  180. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  181. MaxSendQString string `yaml:"max-sendq"`
  182. MaxSendQBytes uint64
  183. ConnectionLimits ConnectionLimitsConfig `yaml:"connection-limits"`
  184. ConnectionThrottle ConnectionThrottleConfig `yaml:"connection-throttling"`
  185. }
  186. Datastore struct {
  187. Path string
  188. }
  189. Accounts struct {
  190. Registration AccountRegistrationConfig
  191. AuthenticationEnabled bool `yaml:"authentication-enabled"`
  192. }
  193. Channels struct {
  194. DefaultModes *string `yaml:"default-modes"`
  195. Registration ChannelRegistrationConfig
  196. }
  197. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  198. Opers map[string]*OperConfig
  199. Logging []LoggingConfig
  200. Debug struct {
  201. StackImpact StackImpactConfig
  202. }
  203. Limits struct {
  204. AwayLen uint `yaml:"awaylen"`
  205. ChanListModes uint `yaml:"chan-list-modes"`
  206. ChannelLen uint `yaml:"channellen"`
  207. KickLen uint `yaml:"kicklen"`
  208. MonitorEntries uint `yaml:"monitor-entries"`
  209. NickLen uint `yaml:"nicklen"`
  210. TopicLen uint `yaml:"topiclen"`
  211. WhowasEntries uint `yaml:"whowas-entries"`
  212. LineLen LineLenConfig `yaml:"linelen"`
  213. }
  214. }
  215. // OperClass defines an assembled operator class.
  216. type OperClass struct {
  217. Title string
  218. WhoisLine string `yaml:"whois-line"`
  219. Capabilities map[string]bool // map to make lookups much easier
  220. }
  221. // OperatorClasses returns a map of assembled operator classes from the given config.
  222. func (conf *Config) OperatorClasses() (*map[string]OperClass, error) {
  223. ocs := make(map[string]OperClass)
  224. // loop from no extends to most extended, breaking if we can't add any more
  225. lenOfLastOcs := -1
  226. for {
  227. if lenOfLastOcs == len(ocs) {
  228. return nil, errors.New("OperClasses contains a looping dependency, or a class extends from a class that doesn't exist")
  229. }
  230. lenOfLastOcs = len(ocs)
  231. var anyMissing bool
  232. for name, info := range conf.OperClasses {
  233. _, exists := ocs[name]
  234. _, extendsExists := ocs[info.Extends]
  235. if exists {
  236. // class already exists
  237. continue
  238. } else if len(info.Extends) > 0 && !extendsExists {
  239. // class we extend on doesn't exist
  240. _, exists := conf.OperClasses[info.Extends]
  241. if !exists {
  242. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  243. }
  244. anyMissing = true
  245. continue
  246. }
  247. // create new operclass
  248. var oc OperClass
  249. oc.Capabilities = make(map[string]bool)
  250. // get inhereted info from other operclasses
  251. if len(info.Extends) > 0 {
  252. einfo, _ := ocs[info.Extends]
  253. for capab := range einfo.Capabilities {
  254. oc.Capabilities[capab] = true
  255. }
  256. }
  257. // add our own info
  258. oc.Title = info.Title
  259. for _, capab := range info.Capabilities {
  260. oc.Capabilities[capab] = true
  261. }
  262. if len(info.WhoisLine) > 0 {
  263. oc.WhoisLine = info.WhoisLine
  264. } else {
  265. oc.WhoisLine = "is a"
  266. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  267. oc.WhoisLine += "n"
  268. }
  269. oc.WhoisLine += " "
  270. oc.WhoisLine += oc.Title
  271. }
  272. ocs[name] = oc
  273. }
  274. if !anyMissing {
  275. // we've got every operclass!
  276. break
  277. }
  278. }
  279. return &ocs, nil
  280. }
  281. // Oper represents a single assembled operator's config.
  282. type Oper struct {
  283. Class *OperClass
  284. WhoisLine string
  285. Vhost string
  286. Pass []byte
  287. Modes string
  288. }
  289. // Operators returns a map of operator configs from the given OperClass and config.
  290. func (conf *Config) Operators(oc *map[string]OperClass) (map[string]Oper, error) {
  291. operators := make(map[string]Oper)
  292. for name, opConf := range conf.Opers {
  293. var oper Oper
  294. // oper name
  295. name, err := CasefoldName(name)
  296. if err != nil {
  297. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  298. }
  299. oper.Pass = opConf.PasswordBytes()
  300. oper.Vhost = opConf.Vhost
  301. class, exists := (*oc)[opConf.Class]
  302. if !exists {
  303. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  304. }
  305. oper.Class = &class
  306. if len(opConf.WhoisLine) > 0 {
  307. oper.WhoisLine = opConf.WhoisLine
  308. } else {
  309. oper.WhoisLine = class.WhoisLine
  310. }
  311. oper.Modes = strings.TrimSpace(opConf.Modes)
  312. // successful, attach to list of opers
  313. operators[name] = oper
  314. }
  315. return operators, nil
  316. }
  317. // TLSListeners returns a list of TLS listeners and their configs.
  318. func (conf *Config) TLSListeners() map[string]*tls.Config {
  319. tlsListeners := make(map[string]*tls.Config)
  320. for s, tlsListenersConf := range conf.Server.TLSListeners {
  321. config, err := tlsListenersConf.Config()
  322. config.ClientAuth = tls.RequestClientCert
  323. if err != nil {
  324. log.Fatal(err)
  325. }
  326. tlsListeners[s] = config
  327. }
  328. return tlsListeners
  329. }
  330. // LoadConfig loads the given YAML configuration file.
  331. func LoadConfig(filename string) (config *Config, err error) {
  332. data, err := ioutil.ReadFile(filename)
  333. if err != nil {
  334. return nil, err
  335. }
  336. err = yaml.Unmarshal(data, &config)
  337. if err != nil {
  338. return nil, err
  339. }
  340. // we need this so PasswordBytes returns the correct info
  341. if config.Server.Password != "" {
  342. config.Server.PassConfig.Password = config.Server.Password
  343. }
  344. if config.Network.Name == "" {
  345. return nil, errors.New("Network name missing")
  346. }
  347. if config.Server.Name == "" {
  348. return nil, errors.New("Server name missing")
  349. }
  350. if !IsHostname(config.Server.Name) {
  351. return nil, errors.New("Server name must match the format of a hostname")
  352. }
  353. if config.Datastore.Path == "" {
  354. return nil, errors.New("Datastore path missing")
  355. }
  356. if len(config.Server.Listen) == 0 {
  357. return nil, errors.New("Server listening addresses missing")
  358. }
  359. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  360. return nil, errors.New("Limits aren't setup properly, check them and make them sane")
  361. }
  362. if config.Server.STS.Enabled {
  363. config.Server.STS.Duration, err = custime.ParseDuration(config.Server.STS.DurationString)
  364. if err != nil {
  365. return nil, fmt.Errorf("Could not parse STS duration: %s", err.Error())
  366. }
  367. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  368. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  369. }
  370. }
  371. if config.Server.ConnectionThrottle.Enabled {
  372. config.Server.ConnectionThrottle.Duration, err = time.ParseDuration(config.Server.ConnectionThrottle.DurationString)
  373. if err != nil {
  374. return nil, fmt.Errorf("Could not parse connection-throttle duration: %s", err.Error())
  375. }
  376. config.Server.ConnectionThrottle.BanDuration, err = time.ParseDuration(config.Server.ConnectionThrottle.BanDurationString)
  377. if err != nil {
  378. return nil, fmt.Errorf("Could not parse connection-throttle ban-duration: %s", err.Error())
  379. }
  380. }
  381. if config.Limits.LineLen.Tags < 512 || config.Limits.LineLen.Rest < 512 {
  382. return nil, errors.New("Line lengths must be 512 or greater (check the linelen section under server->limits)")
  383. }
  384. var newLogConfigs []LoggingConfig
  385. for _, logConfig := range config.Logging {
  386. // methods
  387. methods := make(map[string]bool)
  388. for _, method := range strings.Split(logConfig.Method, " ") {
  389. if len(method) > 0 {
  390. methods[strings.ToLower(method)] = true
  391. }
  392. }
  393. if methods["file"] && logConfig.Filename == "" {
  394. return nil, errors.New("Logging configuration specifies 'file' method but 'filename' is empty")
  395. }
  396. logConfig.MethodFile = methods["file"]
  397. logConfig.MethodStdout = methods["stdout"]
  398. logConfig.MethodStderr = methods["stderr"]
  399. // levels
  400. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  401. if !exists {
  402. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  403. }
  404. logConfig.Level = level
  405. // types
  406. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  407. if len(typeStr) == 0 {
  408. continue
  409. }
  410. if typeStr == "-" {
  411. return nil, errors.New("Encountered logging type '-' with no type to exclude")
  412. }
  413. if typeStr[0] == '-' {
  414. typeStr = typeStr[1:]
  415. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  416. } else {
  417. logConfig.Types = append(logConfig.Types, typeStr)
  418. }
  419. }
  420. if len(logConfig.Types) < 1 {
  421. return nil, errors.New("Logger has no types to log")
  422. }
  423. newLogConfigs = append(newLogConfigs, logConfig)
  424. }
  425. config.Logging = newLogConfigs
  426. config.Server.MaxSendQBytes, err = bytefmt.ToBytes(config.Server.MaxSendQString)
  427. if err != nil {
  428. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  429. }
  430. return config, nil
  431. }