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.

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