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.

nickserv.go 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  1. // Copyright (c) 2017 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/goshuirc/irc-go/ircfmt"
  10. "github.com/oragono/oragono/irc/modes"
  11. "github.com/oragono/oragono/irc/passwd"
  12. "github.com/oragono/oragono/irc/sno"
  13. "github.com/oragono/oragono/irc/utils"
  14. )
  15. // "enabled" callbacks for specific nickserv commands
  16. func servCmdRequiresAccreg(config *Config) bool {
  17. return config.Accounts.Registration.Enabled
  18. }
  19. func servCmdRequiresAuthEnabled(config *Config) bool {
  20. return config.Accounts.AuthenticationEnabled
  21. }
  22. func servCmdRequiresNickRes(config *Config) bool {
  23. return config.Accounts.AuthenticationEnabled && config.Accounts.NickReservation.Enabled
  24. }
  25. func servCmdRequiresBouncerEnabled(config *Config) bool {
  26. return config.Accounts.Multiclient.Enabled
  27. }
  28. const (
  29. nsPrefix = "NickServ!NickServ@localhost"
  30. // ZNC's nickserv module will not detect this unless it is:
  31. // 1. sent with prefix `nickserv`
  32. // 2. contains the string "identify"
  33. // 3. contains at least one of several other magic strings ("msg" works)
  34. nsTimeoutNotice = `This nickname is reserved. Please login within %v (using $b/msg NickServ IDENTIFY <password>$b or SASL), or switch to a different nickname.`
  35. )
  36. const nickservHelp = `NickServ lets you register, log in to, and manage an account.`
  37. var (
  38. nickservCommands = map[string]*serviceCommand{
  39. "drop": {
  40. handler: nsDropHandler,
  41. help: `Syntax: $bDROP [nickname]$b
  42. DROP de-links the given (or your current) nickname from your user account.`,
  43. helpShort: `$bDROP$b de-links your current (or the given) nickname from your user account.`,
  44. enabled: servCmdRequiresNickRes,
  45. authRequired: true,
  46. },
  47. "enforce": {
  48. hidden: true,
  49. handler: nsEnforceHandler,
  50. help: `Syntax: $bENFORCE [method]$b
  51. ENFORCE is an alias for $bGET enforce$b and $bSET enforce$b. See the help
  52. entry for $bSET$b for more information.`,
  53. authRequired: true,
  54. enabled: servCmdRequiresNickRes,
  55. },
  56. "ghost": {
  57. handler: nsGhostHandler,
  58. help: `Syntax: $bGHOST <nickname>$b
  59. GHOST disconnects the given user from the network if they're logged in with the
  60. same user account, letting you reclaim your nickname.`,
  61. helpShort: `$bGHOST$b reclaims your nickname.`,
  62. enabled: servCmdRequiresNickRes,
  63. authRequired: true,
  64. minParams: 1,
  65. },
  66. "group": {
  67. handler: nsGroupHandler,
  68. help: `Syntax: $bGROUP$b
  69. GROUP links your current nickname with your logged-in account, so other people
  70. will not be able to use it.`,
  71. helpShort: `$bGROUP$b links your current nickname to your user account.`,
  72. enabled: servCmdRequiresNickRes,
  73. authRequired: true,
  74. },
  75. "identify": {
  76. handler: nsIdentifyHandler,
  77. help: `Syntax: $bIDENTIFY <username> [password]$b
  78. IDENTIFY lets you login to the given username using either password auth, or
  79. certfp (your client certificate) if a password is not given.`,
  80. helpShort: `$bIDENTIFY$b lets you login to your account.`,
  81. enabled: servCmdRequiresAuthEnabled,
  82. minParams: 1,
  83. },
  84. "info": {
  85. handler: nsInfoHandler,
  86. help: `Syntax: $bINFO [username]$b
  87. INFO gives you information about the given (or your own) user account.`,
  88. helpShort: `$bINFO$b gives you information on a user account.`,
  89. },
  90. "register": {
  91. handler: nsRegisterHandler,
  92. // TODO: "email" is an oversimplification here; it's actually any callback, e.g.,
  93. // person@example.com, mailto:person@example.com, tel:16505551234.
  94. help: `Syntax: $bREGISTER <password> [email]$b
  95. REGISTER lets you register your current nickname as a user account. If the
  96. server allows anonymous registration, you can omit the e-mail address.
  97. If you are currently logged in with a TLS client certificate and wish to use
  98. it instead of a password to log in, send * as the password.`,
  99. helpShort: `$bREGISTER$b lets you register a user account.`,
  100. enabled: servCmdRequiresAccreg,
  101. minParams: 1,
  102. maxParams: 2,
  103. },
  104. "sadrop": {
  105. handler: nsDropHandler,
  106. help: `Syntax: $bSADROP <nickname>$b
  107. SADROP forcibly de-links the given nickname from the attached user account.`,
  108. helpShort: `$bSADROP$b forcibly de-links the given nickname from its user account.`,
  109. capabs: []string{"accreg"},
  110. enabled: servCmdRequiresNickRes,
  111. minParams: 1,
  112. },
  113. "saregister": {
  114. handler: nsSaregisterHandler,
  115. help: `Syntax: $bSAREGISTER <username> [password]$b
  116. SAREGISTER registers an account on someone else's behalf.
  117. This is for use in configurations that require SASL for all connections;
  118. an administrator can set use this command to set up user accounts.`,
  119. helpShort: `$bSAREGISTER$b registers an account on someone else's behalf.`,
  120. enabled: servCmdRequiresAuthEnabled,
  121. capabs: []string{"accreg"},
  122. minParams: 1,
  123. },
  124. "sessions": {
  125. handler: nsSessionsHandler,
  126. help: `Syntax: $bSESSIONS [nickname]$b
  127. SESSIONS lists information about the sessions currently attached, via
  128. the server's multiclient functionality, to your nickname. An administrator
  129. can use this command to list another user's sessions.`,
  130. helpShort: `$bSESSIONS$b lists the sessions attached to a nickname.`,
  131. enabled: servCmdRequiresBouncerEnabled,
  132. },
  133. "unregister": {
  134. handler: nsUnregisterHandler,
  135. help: `Syntax: $bUNREGISTER <username> [code]$b
  136. UNREGISTER lets you delete your user account (or someone else's, if you're an
  137. IRC operator with the correct permissions). To prevent accidental
  138. unregistrations, a verification code is required; invoking the command without
  139. a code will display the necessary code.`,
  140. helpShort: `$bUNREGISTER$b lets you delete your user account.`,
  141. enabled: servCmdRequiresAuthEnabled,
  142. minParams: 1,
  143. },
  144. "erase": {
  145. handler: nsUnregisterHandler,
  146. help: `Syntax: $bERASE <username> [code]$b
  147. ERASE deletes all records of an account, allowing it to be re-registered.
  148. This should be used with caution, because it violates an expectation that
  149. account names are permanent identifiers. Typically, UNREGISTER should be
  150. used instead. A confirmation code is required; invoking the command
  151. without a code will display the necessary code.`,
  152. helpShort: `$bERASE$b erases all records of an account, allowing reuse.`,
  153. enabled: servCmdRequiresAuthEnabled,
  154. capabs: []string{"accreg"},
  155. minParams: 1,
  156. },
  157. "verify": {
  158. handler: nsVerifyHandler,
  159. help: `Syntax: $bVERIFY <username> <code>$b
  160. VERIFY lets you complete an account registration, if the server requires email
  161. or other verification.`,
  162. helpShort: `$bVERIFY$b lets you complete account registration.`,
  163. enabled: servCmdRequiresAccreg,
  164. minParams: 2,
  165. },
  166. "passwd": {
  167. handler: nsPasswdHandler,
  168. help: `Syntax: $bPASSWD <current> <new> <new_again>$b
  169. Or: $bPASSWD <username> <new>$b
  170. PASSWD lets you change your account password. You must supply your current
  171. password and confirm the new one by typing it twice. If you're an IRC operator
  172. with the correct permissions, you can use PASSWD to reset someone else's
  173. password by supplying their username and then the desired password. To
  174. indicate an empty password, use * instead.`,
  175. helpShort: `$bPASSWD$b lets you change your password.`,
  176. enabled: servCmdRequiresAuthEnabled,
  177. minParams: 2,
  178. },
  179. "get": {
  180. handler: nsGetHandler,
  181. help: `Syntax: $bGET <setting>$b
  182. GET queries the current values of your account settings. For more information
  183. on the settings and their possible values, see HELP SET.`,
  184. helpShort: `$bGET$b queries the current values of your account settings`,
  185. authRequired: true,
  186. enabled: servCmdRequiresAuthEnabled,
  187. minParams: 1,
  188. },
  189. "saget": {
  190. handler: nsGetHandler,
  191. help: `Syntax: $bSAGET <account> <setting>$b
  192. SAGET queries the values of someone else's account settings. For more
  193. information on the settings and their possible values, see HELP SET.`,
  194. helpShort: `$bSAGET$b queries the current values of another user's account settings`,
  195. enabled: servCmdRequiresAuthEnabled,
  196. minParams: 2,
  197. capabs: []string{"accreg"},
  198. },
  199. "set": {
  200. handler: nsSetHandler,
  201. helpShort: `$bSET$b modifies your account settings`,
  202. // these are broken out as separate strings so they can be translated separately
  203. helpStrings: []string{
  204. `Syntax $bSET <setting> <value>$b
  205. SET modifies your account settings. The following settings are available:`,
  206. `$bENFORCE$b
  207. 'enforce' lets you specify a custom enforcement mechanism for your registered
  208. nicknames. Your options are:
  209. 1. 'none' [no enforcement, overriding the server default]
  210. 2. 'timeout' [anyone using the nick must authenticate before a deadline,
  211. or else they will be renamed]
  212. 3. 'strict' [you must already be authenticated to use the nick]
  213. 4. 'default' [use the server default]`,
  214. `$bMULTICLIENT$b
  215. If 'multiclient' is enabled and you are already logged in and using a nick, a
  216. second client of yours that authenticates with SASL and requests the same nick
  217. is allowed to attach to the nick as well (this is comparable to the behavior
  218. of IRC "bouncers" like ZNC). Your options are 'on' (allow this behavior),
  219. 'off' (disallow it), and 'default' (use the server default value).`,
  220. `$bAUTOREPLAY-LINES$b
  221. 'autoreplay-lines' controls the number of lines of channel history that will
  222. be replayed to you automatically when joining a channel. Your options are any
  223. positive number, 0 to disable the feature, and 'default' to use the server
  224. default.`,
  225. `$bREPLAY-JOINS$b
  226. 'replay-joins' controls whether replayed channel history will include
  227. lines for join and part. This provides more information about the context of
  228. messages, but may be spammy. Your options are 'always', 'never', and the default
  229. of 'commands-only' (the messages will be replayed in /HISTORY output, but not
  230. during autoreplay).`,
  231. `$bALWAYS-ON$b
  232. 'always-on' controls whether your nickname/identity will remain active
  233. even while you are disconnected from the server. Your options are 'true',
  234. 'false', and 'default' (use the server default value).`,
  235. `$bAUTOREPLAY-MISSED$b
  236. 'autoreplay-missed' is only effective for always-on clients. If enabled,
  237. if you have at most one active session, the server will remember the time
  238. you disconnect and then replay missed messages to you when you reconnect.
  239. Your options are 'on' and 'off'.`,
  240. `$bDM-HISTORY$b
  241. 'dm-history' is only effective for always-on clients. It lets you control
  242. how the history of your direct messages is stored. Your options are:
  243. 1. 'off' [no history]
  244. 2. 'ephemeral' [a limited amount of temporary history, not stored on disk]
  245. 3. 'on' [history stored in a permanent database, if available]
  246. 4. 'default' [use the server default]`,
  247. },
  248. authRequired: true,
  249. enabled: servCmdRequiresAuthEnabled,
  250. minParams: 2,
  251. },
  252. "saset": {
  253. handler: nsSetHandler,
  254. help: `Syntax: $bSASET <account> <setting> <value>$b
  255. SASET modifies the values of someone else's account settings. For more
  256. information on the settings and their possible values, see HELP SET.`,
  257. helpShort: `$bSASET$b modifies another user's account settings`,
  258. enabled: servCmdRequiresAuthEnabled,
  259. minParams: 3,
  260. capabs: []string{"accreg"},
  261. },
  262. "cert": {
  263. handler: nsCertHandler,
  264. help: `Syntax: $bCERT <LIST | ADD | DEL> [account] [certfp]$b
  265. CERT examines or modifies the TLS certificate fingerprints that can be used to
  266. log into an account. Specifically, $bCERT LIST$b lists the authorized
  267. fingerprints, $bCERT ADD <fingerprint>$b adds a new fingerprint, and
  268. $bCERT DEL <fingerprint>$b removes a fingerprint. If you're an IRC operator
  269. with the correct permissions, you can act on another user's account, for
  270. example with $bCERT ADD <account> <fingerprint>$b.`,
  271. helpShort: `$bCERT$b controls a user account's certificate fingerprints`,
  272. enabled: servCmdRequiresAuthEnabled,
  273. minParams: 1,
  274. },
  275. }
  276. )
  277. // nsNotice sends the client a notice from NickServ
  278. func nsNotice(rb *ResponseBuffer, text string) {
  279. // XXX i can't figure out how to use OragonoServices[servicename].prefix here
  280. // without creating a compile-time initialization loop
  281. rb.Add(nil, nsPrefix, "NOTICE", rb.target.Nick(), text)
  282. }
  283. func nsGetHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  284. var account string
  285. if command == "saget" {
  286. account = params[0]
  287. params = params[1:]
  288. } else {
  289. account = client.Account()
  290. }
  291. accountData, err := server.accounts.LoadAccount(account)
  292. if err == errAccountDoesNotExist {
  293. nsNotice(rb, client.t("No such account"))
  294. return
  295. } else if err != nil {
  296. nsNotice(rb, client.t("Error loading account data"))
  297. return
  298. }
  299. displaySetting(params[0], accountData.Settings, client, rb)
  300. }
  301. func displaySetting(settingName string, settings AccountSettings, client *Client, rb *ResponseBuffer) {
  302. config := client.server.Config()
  303. switch strings.ToLower(settingName) {
  304. case "enforce":
  305. storedValue := settings.NickEnforcement
  306. serializedStoredValue := nickReservationToString(storedValue)
  307. nsNotice(rb, fmt.Sprintf(client.t("Your stored nickname enforcement setting is: %s"), serializedStoredValue))
  308. serializedActualValue := nickReservationToString(configuredEnforcementMethod(config, storedValue))
  309. nsNotice(rb, fmt.Sprintf(client.t("Given current server settings, your nickname is enforced with: %s"), serializedActualValue))
  310. case "autoreplay-lines":
  311. if settings.AutoreplayLines == nil {
  312. nsNotice(rb, fmt.Sprintf(client.t("You will receive the server default of %d lines of autoreplayed history"), config.History.AutoreplayOnJoin))
  313. } else {
  314. nsNotice(rb, fmt.Sprintf(client.t("You will receive %d lines of autoreplayed history"), *settings.AutoreplayLines))
  315. }
  316. case "replay-joins":
  317. switch settings.ReplayJoins {
  318. case ReplayJoinsCommandsOnly:
  319. nsNotice(rb, client.t("You will see JOINs and PARTs in /HISTORY output, but not in autoreplay"))
  320. case ReplayJoinsAlways:
  321. nsNotice(rb, client.t("You will see JOINs and PARTs in /HISTORY output and in autoreplay"))
  322. case ReplayJoinsNever:
  323. nsNotice(rb, client.t("You will not see JOINs and PARTs in /HISTORY output or in autoreplay"))
  324. }
  325. case "multiclient":
  326. if !config.Accounts.Multiclient.Enabled {
  327. nsNotice(rb, client.t("This feature has been disabled by the server administrators"))
  328. } else {
  329. switch settings.AllowBouncer {
  330. case MulticlientAllowedServerDefault:
  331. if config.Accounts.Multiclient.AllowedByDefault {
  332. nsNotice(rb, client.t("Multiclient functionality is currently enabled for your account, but you can opt out"))
  333. } else {
  334. nsNotice(rb, client.t("Multiclient functionality is currently disabled for your account, but you can opt in"))
  335. }
  336. case MulticlientDisallowedByUser:
  337. nsNotice(rb, client.t("Multiclient functionality is currently disabled for your account"))
  338. case MulticlientAllowedByUser:
  339. nsNotice(rb, client.t("Multiclient functionality is currently enabled for your account"))
  340. }
  341. }
  342. case "always-on":
  343. stored := settings.AlwaysOn
  344. actual := persistenceEnabled(config.Accounts.Multiclient.AlwaysOn, stored)
  345. nsNotice(rb, fmt.Sprintf(client.t("Your stored always-on setting is: %s"), persistentStatusToString(stored)))
  346. if actual {
  347. nsNotice(rb, client.t("Given current server settings, your client is always-on"))
  348. } else {
  349. nsNotice(rb, client.t("Given current server settings, your client is not always-on"))
  350. }
  351. case "autoreplay-missed":
  352. stored := settings.AutoreplayMissed
  353. if stored {
  354. alwaysOn := persistenceEnabled(config.Accounts.Multiclient.AlwaysOn, settings.AlwaysOn)
  355. if alwaysOn {
  356. nsNotice(rb, client.t("Autoreplay of missed messages is enabled"))
  357. } else {
  358. nsNotice(rb, client.t("You have enabled autoreplay of missed messages, but you can't receive them because your client isn't set to always-on"))
  359. }
  360. } else {
  361. nsNotice(rb, client.t("Your account is not configured to receive autoreplayed missed messages"))
  362. }
  363. case "dm-history":
  364. effectiveValue := historyEnabled(config.History.Persistent.DirectMessages, settings.DMHistory)
  365. csNotice(rb, fmt.Sprintf(client.t("Your stored direct message history setting is: %s"), historyStatusToString(settings.DMHistory)))
  366. csNotice(rb, fmt.Sprintf(client.t("Given current server settings, your direct message history setting is: %s"), historyStatusToString(effectiveValue)))
  367. default:
  368. nsNotice(rb, client.t("No such setting"))
  369. }
  370. }
  371. func nsSetHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  372. var account string
  373. if command == "saset" {
  374. account = params[0]
  375. params = params[1:]
  376. } else {
  377. account = client.Account()
  378. }
  379. var munger settingsMunger
  380. var finalSettings AccountSettings
  381. var err error
  382. switch strings.ToLower(params[0]) {
  383. case "pass":
  384. nsNotice(rb, client.t("To change a password, use the PASSWD command. For details, /msg NickServ HELP PASSWD"))
  385. return
  386. case "enforce":
  387. var method NickEnforcementMethod
  388. method, err = nickReservationFromString(params[1])
  389. if err != nil {
  390. err = errInvalidParams
  391. break
  392. }
  393. // updating enforcement settings is special-cased, because it requires
  394. // an update to server.accounts.accountToMethod
  395. finalSettings, err = server.accounts.SetEnforcementStatus(account, method)
  396. if err == nil {
  397. finalSettings.NickEnforcement = method // success
  398. }
  399. case "autoreplay-lines":
  400. var newValue *int
  401. if strings.ToLower(params[1]) != "default" {
  402. val, err_ := strconv.Atoi(params[1])
  403. if err_ != nil || val < 0 {
  404. err = errInvalidParams
  405. break
  406. }
  407. newValue = new(int)
  408. *newValue = val
  409. }
  410. munger = func(in AccountSettings) (out AccountSettings, err error) {
  411. out = in
  412. out.AutoreplayLines = newValue
  413. return
  414. }
  415. case "multiclient":
  416. var newValue MulticlientAllowedSetting
  417. if strings.ToLower(params[1]) == "default" {
  418. newValue = MulticlientAllowedServerDefault
  419. } else {
  420. var enabled bool
  421. enabled, err = utils.StringToBool(params[1])
  422. if enabled {
  423. newValue = MulticlientAllowedByUser
  424. } else {
  425. newValue = MulticlientDisallowedByUser
  426. }
  427. }
  428. if err == nil {
  429. munger = func(in AccountSettings) (out AccountSettings, err error) {
  430. out = in
  431. out.AllowBouncer = newValue
  432. return
  433. }
  434. }
  435. case "replay-joins":
  436. var newValue ReplayJoinsSetting
  437. newValue, err = replayJoinsSettingFromString(params[1])
  438. if err == nil {
  439. munger = func(in AccountSettings) (out AccountSettings, err error) {
  440. out = in
  441. out.ReplayJoins = newValue
  442. return
  443. }
  444. }
  445. case "always-on":
  446. // #821: it's problematic to alter the value of always-on if you're not
  447. // the (actual or potential) always-on client yourself. make an exception
  448. // for `saset` to give operators an escape hatch (any consistency problems
  449. // can probably be fixed by restarting the server):
  450. if command != "saset" {
  451. details := client.Details()
  452. if details.nick != details.accountName {
  453. err = errNickAccountMismatch
  454. }
  455. }
  456. if err == nil {
  457. var newValue PersistentStatus
  458. newValue, err = persistentStatusFromString(params[1])
  459. // "opt-in" and "opt-out" don't make sense as user preferences
  460. if err == nil && newValue != PersistentOptIn && newValue != PersistentOptOut {
  461. munger = func(in AccountSettings) (out AccountSettings, err error) {
  462. out = in
  463. out.AlwaysOn = newValue
  464. return
  465. }
  466. }
  467. }
  468. case "autoreplay-missed":
  469. var newValue bool
  470. newValue, err = utils.StringToBool(params[1])
  471. if err == nil {
  472. munger = func(in AccountSettings) (out AccountSettings, err error) {
  473. out = in
  474. out.AutoreplayMissed = newValue
  475. return
  476. }
  477. }
  478. case "dm-history":
  479. var newValue HistoryStatus
  480. newValue, err = historyStatusFromString(params[1])
  481. if err == nil {
  482. munger = func(in AccountSettings) (out AccountSettings, err error) {
  483. out = in
  484. out.DMHistory = newValue
  485. return
  486. }
  487. }
  488. default:
  489. err = errInvalidParams
  490. }
  491. if munger != nil {
  492. finalSettings, err = server.accounts.ModifyAccountSettings(account, munger)
  493. }
  494. switch err {
  495. case nil:
  496. nsNotice(rb, client.t("Successfully changed your account settings"))
  497. displaySetting(params[0], finalSettings, client, rb)
  498. case errInvalidParams, errAccountDoesNotExist, errFeatureDisabled, errAccountUnverified, errAccountUpdateFailed:
  499. nsNotice(rb, client.t(err.Error()))
  500. case errNickAccountMismatch:
  501. nsNotice(rb, fmt.Sprintf(client.t("Your nickname must match your account name %s exactly to modify this setting. Try changing it with /NICK, or logging out and back in with the correct nickname."), client.AccountName()))
  502. default:
  503. // unknown error
  504. nsNotice(rb, client.t("An error occurred"))
  505. }
  506. }
  507. func nsDropHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  508. sadrop := command == "sadrop"
  509. var nick string
  510. if len(params) > 0 {
  511. nick = params[0]
  512. } else {
  513. nick = client.NickCasefolded()
  514. }
  515. err := server.accounts.SetNickReserved(client, nick, sadrop, false)
  516. if err == nil {
  517. nsNotice(rb, fmt.Sprintf(client.t("Successfully ungrouped nick %s with your account"), nick))
  518. } else if err == errAccountNotLoggedIn {
  519. nsNotice(rb, client.t("You're not logged into an account"))
  520. } else if err == errAccountCantDropPrimaryNick {
  521. nsNotice(rb, client.t("You can't ungroup your primary nickname (try unregistering your account instead)"))
  522. } else {
  523. nsNotice(rb, client.t("Could not ungroup nick"))
  524. }
  525. }
  526. func nsGhostHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  527. nick := params[0]
  528. ghost := server.clients.Get(nick)
  529. if ghost == nil {
  530. nsNotice(rb, client.t("No such nick"))
  531. return
  532. } else if ghost == client {
  533. nsNotice(rb, client.t("You can't GHOST yourself (try /QUIT instead)"))
  534. return
  535. } else if ghost.AlwaysOn() {
  536. nsNotice(rb, client.t("You can't GHOST an always-on client"))
  537. return
  538. }
  539. authorized := false
  540. account := client.Account()
  541. if account != "" {
  542. // the user must either own the nick, or the target client
  543. authorized = (server.accounts.NickToAccount(nick) == account) || (ghost.Account() == account)
  544. }
  545. if !authorized {
  546. nsNotice(rb, client.t("You don't own that nick"))
  547. return
  548. }
  549. ghost.Quit(fmt.Sprintf(ghost.t("GHOSTed by %s"), client.Nick()), nil)
  550. ghost.destroy(nil)
  551. }
  552. func nsGroupHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  553. nick := client.Nick()
  554. err := server.accounts.SetNickReserved(client, nick, false, true)
  555. if err == nil {
  556. nsNotice(rb, fmt.Sprintf(client.t("Successfully grouped nick %s with your account"), nick))
  557. } else if err == errAccountTooManyNicks {
  558. nsNotice(rb, client.t("You have too many nicks reserved already (you can remove some with /NS DROP)"))
  559. } else if err == errNicknameReserved {
  560. nsNotice(rb, client.t("That nickname is already reserved by someone else"))
  561. } else {
  562. nsNotice(rb, client.t("Error reserving nickname"))
  563. }
  564. }
  565. func nsLoginThrottleCheck(client *Client, rb *ResponseBuffer) (success bool) {
  566. client.stateMutex.Lock()
  567. throttled, remainingTime := client.loginThrottle.Touch()
  568. client.stateMutex.Unlock()
  569. if throttled {
  570. nsNotice(rb, fmt.Sprintf(client.t("Please wait at least %v and try again"), remainingTime))
  571. return false
  572. }
  573. return true
  574. }
  575. func nsIdentifyHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  576. if client.LoggedIntoAccount() {
  577. nsNotice(rb, client.t("You're already logged into an account"))
  578. return
  579. }
  580. var err error
  581. loginSuccessful := false
  582. var username, passphrase string
  583. if len(params) == 1 {
  584. if rb.session.certfp != "" {
  585. username = params[0]
  586. } else {
  587. // XXX undocumented compatibility mode with other nickservs, allowing
  588. // /msg NickServ identify passphrase
  589. username = client.NickCasefolded()
  590. passphrase = params[0]
  591. }
  592. } else {
  593. username = params[0]
  594. passphrase = params[1]
  595. }
  596. // try passphrase
  597. if passphrase != "" {
  598. if !nsLoginThrottleCheck(client, rb) {
  599. return
  600. }
  601. err = server.accounts.AuthenticateByPassphrase(client, username, passphrase)
  602. loginSuccessful = (err == nil)
  603. }
  604. // try certfp
  605. if !loginSuccessful && rb.session.certfp != "" {
  606. err = server.accounts.AuthenticateByCertFP(client, rb.session.certfp, "")
  607. loginSuccessful = (err == nil)
  608. }
  609. nickFixupFailed := false
  610. if loginSuccessful {
  611. if !fixupNickEqualsAccount(client, rb, server.Config()) {
  612. loginSuccessful = false
  613. // fixupNickEqualsAccount sends its own error message, don't send another
  614. nickFixupFailed = true
  615. }
  616. }
  617. if loginSuccessful {
  618. sendSuccessfulAccountAuth(client, rb, true, true)
  619. } else if !nickFixupFailed {
  620. nsNotice(rb, fmt.Sprintf(client.t("Authentication failed: %s"), authErrorToMessage(server, err)))
  621. }
  622. }
  623. func nsInfoHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  624. if !server.Config().Accounts.AuthenticationEnabled && !client.HasRoleCapabs("accreg") {
  625. nsNotice(rb, client.t("This command has been disabled by the server administrators"))
  626. return
  627. }
  628. var accountName string
  629. if len(params) > 0 {
  630. nick := params[0]
  631. if server.Config().Accounts.NickReservation.Enabled {
  632. accountName = server.accounts.NickToAccount(nick)
  633. if accountName == "" {
  634. nsNotice(rb, client.t("That nickname is not registered"))
  635. return
  636. }
  637. } else {
  638. accountName = nick
  639. }
  640. } else {
  641. accountName = client.Account()
  642. if accountName == "" {
  643. nsNotice(rb, client.t("You're not logged into an account"))
  644. return
  645. }
  646. }
  647. account, err := server.accounts.LoadAccount(accountName)
  648. if err != nil || !account.Verified {
  649. nsNotice(rb, client.t("Account does not exist"))
  650. return
  651. }
  652. nsNotice(rb, fmt.Sprintf(client.t("Account: %s"), account.Name))
  653. registeredAt := account.RegisteredAt.Format(time.RFC1123)
  654. nsNotice(rb, fmt.Sprintf(client.t("Registered at: %s"), registeredAt))
  655. // TODO nicer formatting for this
  656. for _, nick := range account.AdditionalNicks {
  657. nsNotice(rb, fmt.Sprintf(client.t("Additional grouped nick: %s"), nick))
  658. }
  659. for _, channel := range server.accounts.ChannelsForAccount(accountName) {
  660. nsNotice(rb, fmt.Sprintf(client.t("Registered channel: %s"), channel))
  661. }
  662. }
  663. func nsRegisterHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  664. details := client.Details()
  665. passphrase := params[0]
  666. var email string
  667. if 1 < len(params) {
  668. email = params[1]
  669. }
  670. certfp := rb.session.certfp
  671. if passphrase == "*" {
  672. if certfp == "" {
  673. nsNotice(rb, client.t("You must be connected with TLS and a client certificate to do this"))
  674. return
  675. } else {
  676. passphrase = ""
  677. }
  678. }
  679. if !nsLoginThrottleCheck(client, rb) {
  680. return
  681. }
  682. config := server.Config()
  683. account := details.nick
  684. if config.Accounts.NickReservation.ForceGuestFormat {
  685. matches := config.Accounts.NickReservation.guestRegexp.FindStringSubmatch(account)
  686. if matches == nil || len(matches) < 2 {
  687. nsNotice(rb, client.t("Erroneous nickname"))
  688. return
  689. }
  690. account = matches[1]
  691. }
  692. var callbackNamespace, callbackValue string
  693. noneCallbackAllowed := false
  694. for _, callback := range config.Accounts.Registration.EnabledCallbacks {
  695. if callback == "*" {
  696. noneCallbackAllowed = true
  697. }
  698. }
  699. // XXX if ACC REGISTER allows registration with the `none` callback, then ignore
  700. // any callback that was passed here (to avoid confusion in the case where the ircd
  701. // has no mail server configured). otherwise, register using the provided callback:
  702. if noneCallbackAllowed {
  703. callbackNamespace = "*"
  704. } else {
  705. callbackNamespace, callbackValue = parseCallback(email, config.Accounts)
  706. if callbackNamespace == "" || callbackValue == "" {
  707. nsNotice(rb, client.t("Registration requires a valid e-mail address"))
  708. return
  709. }
  710. }
  711. err := server.accounts.Register(client, account, callbackNamespace, callbackValue, passphrase, rb.session.certfp)
  712. if err == nil {
  713. if callbackNamespace == "*" {
  714. err = server.accounts.Verify(client, account, "")
  715. if err == nil && fixupNickEqualsAccount(client, rb, config) {
  716. sendSuccessfulRegResponse(client, rb, true)
  717. }
  718. } else {
  719. messageTemplate := client.t("Account created, pending verification; verification code has been sent to %s")
  720. message := fmt.Sprintf(messageTemplate, fmt.Sprintf("%s:%s", callbackNamespace, callbackValue))
  721. nsNotice(rb, message)
  722. }
  723. } else {
  724. // details could not be stored and relevant numerics have been dispatched, abort
  725. message, _ := registrationErrorToMessageAndCode(err)
  726. nsNotice(rb, client.t(message))
  727. }
  728. }
  729. func nsSaregisterHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  730. var account, passphrase string
  731. account = params[0]
  732. if 1 < len(params) && params[1] != "*" {
  733. passphrase = params[1]
  734. }
  735. err := server.accounts.SARegister(account, passphrase)
  736. if err != nil {
  737. var errMsg string
  738. if err == errAccountAlreadyRegistered || err == errAccountAlreadyVerified {
  739. errMsg = client.t("Account already exists")
  740. } else if err == errAccountBadPassphrase {
  741. errMsg = client.t("Passphrase contains forbidden characters or is otherwise invalid")
  742. } else {
  743. server.logger.Error("services", "unknown error from saregister", err.Error())
  744. errMsg = client.t("Could not register")
  745. }
  746. nsNotice(rb, errMsg)
  747. } else {
  748. nsNotice(rb, fmt.Sprintf(client.t("Successfully registered account %s"), account))
  749. server.snomasks.Send(sno.LocalAccounts, fmt.Sprintf(ircfmt.Unescape("Operator $c[grey][$r%s$c[grey]] registered account $c[grey][$r%s$c[grey]] with SAREGISTER"), client.Oper().Name, account))
  750. }
  751. }
  752. func nsUnregisterHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  753. erase := command == "erase"
  754. username := params[0]
  755. var verificationCode string
  756. if len(params) > 1 {
  757. verificationCode = params[1]
  758. }
  759. if username == "" {
  760. nsNotice(rb, client.t("You must specify an account"))
  761. return
  762. }
  763. var accountName string
  764. var registeredAt time.Time
  765. if erase {
  766. // account may not be in a loadable state, e.g., if it was unregistered
  767. accountName = username
  768. // make the confirmation code nondeterministic for ERASE
  769. registeredAt = server.ctime
  770. } else {
  771. account, err := server.accounts.LoadAccount(username)
  772. if err == errAccountDoesNotExist {
  773. nsNotice(rb, client.t("Invalid account name"))
  774. return
  775. } else if err != nil {
  776. nsNotice(rb, client.t("Internal error"))
  777. return
  778. }
  779. accountName = account.Name
  780. registeredAt = account.RegisteredAt
  781. }
  782. if !(accountName == client.AccountName() || client.HasRoleCapabs("accreg")) {
  783. nsNotice(rb, client.t("Insufficient oper privs"))
  784. return
  785. }
  786. expectedCode := utils.ConfirmationCode(accountName, registeredAt)
  787. if expectedCode != verificationCode {
  788. if erase {
  789. nsNotice(rb, ircfmt.Unescape(client.t("$bWarning: erasing this account will allow it to be re-registered; consider UNREGISTER instead.$b")))
  790. nsNotice(rb, fmt.Sprintf(client.t("To confirm account erase, type: /NS ERASE %[1]s %[2]s"), accountName, expectedCode))
  791. } else {
  792. nsNotice(rb, ircfmt.Unescape(client.t("$bWarning: unregistering this account will remove its stored privileges.$b")))
  793. nsNotice(rb, fmt.Sprintf(client.t("To confirm account unregistration, type: /NS UNREGISTER %[1]s %[2]s"), accountName, expectedCode))
  794. }
  795. return
  796. }
  797. err := server.accounts.Unregister(accountName, erase)
  798. if err == errAccountDoesNotExist {
  799. nsNotice(rb, client.t(err.Error()))
  800. } else if err != nil {
  801. nsNotice(rb, client.t("Error while unregistering account"))
  802. } else {
  803. nsNotice(rb, fmt.Sprintf(client.t("Successfully unregistered account %s"), accountName))
  804. server.logger.Info("accounts", "client", client.Nick(), "unregistered account", accountName)
  805. client.server.snomasks.Send(sno.LocalAccounts, fmt.Sprintf(ircfmt.Unescape("Client $c[grey][$r%s$c[grey]] unregistered account $c[grey][$r%s$c[grey]]"), client.NickMaskString(), accountName))
  806. }
  807. }
  808. func nsVerifyHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  809. username, code := params[0], params[1]
  810. err := server.accounts.Verify(client, username, code)
  811. var errorMessage string
  812. if err != nil {
  813. switch err {
  814. case errAccountAlreadyLoggedIn, errAccountVerificationInvalidCode, errAccountAlreadyVerified:
  815. errorMessage = err.Error()
  816. default:
  817. errorMessage = errAccountVerificationFailed.Error()
  818. }
  819. }
  820. if errorMessage != "" {
  821. nsNotice(rb, client.t(errorMessage))
  822. return
  823. }
  824. if fixupNickEqualsAccount(client, rb, server.Config()) {
  825. sendSuccessfulRegResponse(client, rb, true)
  826. }
  827. }
  828. func nsPasswdHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  829. var target string
  830. var newPassword string
  831. var errorMessage string
  832. hasPrivs := client.HasRoleCapabs("accreg")
  833. switch len(params) {
  834. case 2:
  835. if !hasPrivs {
  836. errorMessage = `Insufficient privileges`
  837. } else {
  838. target, newPassword = params[0], params[1]
  839. if newPassword == "*" {
  840. newPassword = ""
  841. }
  842. }
  843. case 3:
  844. target = client.Account()
  845. if target == "" {
  846. errorMessage = `You're not logged into an account`
  847. } else if params[1] != params[2] {
  848. errorMessage = `Passwords do not match`
  849. } else {
  850. if !nsLoginThrottleCheck(client, rb) {
  851. return
  852. }
  853. accountData, err := server.accounts.LoadAccount(target)
  854. if err != nil {
  855. errorMessage = `You're not logged into an account`
  856. } else {
  857. hash := accountData.Credentials.PassphraseHash
  858. if hash != nil && passwd.CompareHashAndPassword(hash, []byte(params[0])) != nil {
  859. errorMessage = `Password incorrect`
  860. } else {
  861. newPassword = params[1]
  862. if newPassword == "*" {
  863. newPassword = ""
  864. }
  865. }
  866. }
  867. }
  868. default:
  869. errorMessage = `Invalid parameters`
  870. }
  871. if errorMessage != "" {
  872. nsNotice(rb, client.t(errorMessage))
  873. return
  874. }
  875. err := server.accounts.setPassword(target, newPassword, hasPrivs)
  876. switch err {
  877. case nil:
  878. nsNotice(rb, client.t("Password changed"))
  879. case errEmptyCredentials:
  880. nsNotice(rb, client.t("You can't delete your password unless you add a certificate fingerprint"))
  881. case errCredsExternallyManaged:
  882. nsNotice(rb, client.t("Your account credentials are managed externally and cannot be changed here"))
  883. case errCASFailed:
  884. nsNotice(rb, client.t("Try again later"))
  885. default:
  886. server.logger.Error("internal", "could not upgrade user password:", err.Error())
  887. nsNotice(rb, client.t("Password could not be changed due to server error"))
  888. }
  889. }
  890. func nsEnforceHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  891. newParams := []string{"enforce"}
  892. if len(params) == 0 {
  893. nsGetHandler(server, client, "get", newParams, rb)
  894. } else {
  895. newParams = append(newParams, params[0])
  896. nsSetHandler(server, client, "set", newParams, rb)
  897. }
  898. }
  899. func nsSessionsHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  900. target := client
  901. if 0 < len(params) {
  902. target = server.clients.Get(params[0])
  903. if target == nil {
  904. nsNotice(rb, client.t("No such nick"))
  905. return
  906. }
  907. // same permissions check as RPL_WHOISACTUALLY for now:
  908. if target != client && !client.HasMode(modes.Operator) {
  909. nsNotice(rb, client.t("Command restricted"))
  910. return
  911. }
  912. }
  913. sessionData, currentIndex := target.AllSessionData(rb.session)
  914. nsNotice(rb, fmt.Sprintf(client.t("Nickname %[1]s has %[2]d attached session(s)"), target.Nick(), len(sessionData)))
  915. for i, session := range sessionData {
  916. if currentIndex == i {
  917. nsNotice(rb, fmt.Sprintf(client.t("Session %d (currently attached session):"), i+1))
  918. } else {
  919. nsNotice(rb, fmt.Sprintf(client.t("Session %d:"), i+1))
  920. }
  921. nsNotice(rb, fmt.Sprintf(client.t("IP address: %s"), session.ip.String()))
  922. nsNotice(rb, fmt.Sprintf(client.t("Hostname: %s"), session.hostname))
  923. nsNotice(rb, fmt.Sprintf(client.t("Created at: %s"), session.ctime.Format(time.RFC1123)))
  924. nsNotice(rb, fmt.Sprintf(client.t("Last active: %s"), session.atime.Format(time.RFC1123)))
  925. if session.certfp != "" {
  926. nsNotice(rb, fmt.Sprintf(client.t("Certfp: %s"), session.certfp))
  927. }
  928. }
  929. }
  930. func nsCertHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  931. verb := strings.ToLower(params[0])
  932. params = params[1:]
  933. var target, certfp string
  934. switch verb {
  935. case "list":
  936. if 1 <= len(params) {
  937. target = params[0]
  938. }
  939. case "add", "del":
  940. if 2 <= len(params) {
  941. target, certfp = params[0], params[1]
  942. } else if len(params) == 1 {
  943. certfp = params[0]
  944. } else {
  945. nsNotice(rb, client.t("Invalid parameters"))
  946. return
  947. }
  948. default:
  949. nsNotice(rb, client.t("Invalid parameters"))
  950. return
  951. }
  952. hasPrivs := client.HasRoleCapabs("accreg")
  953. if target != "" && !hasPrivs {
  954. nsNotice(rb, client.t("Insufficient privileges"))
  955. return
  956. } else if target == "" {
  957. target = client.Account()
  958. if target == "" {
  959. nsNotice(rb, client.t("You're not logged into an account"))
  960. return
  961. }
  962. }
  963. var err error
  964. switch verb {
  965. case "list":
  966. accountData, err := server.accounts.LoadAccount(target)
  967. if err == errAccountDoesNotExist {
  968. nsNotice(rb, client.t("Account does not exist"))
  969. return
  970. } else if err != nil {
  971. nsNotice(rb, client.t("An error occurred"))
  972. return
  973. }
  974. certfps := accountData.Credentials.Certfps
  975. nsNotice(rb, fmt.Sprintf(client.t("There are %[1]d certificate fingerprint(s) authorized for account %[2]s."), len(certfps), accountData.Name))
  976. for i, certfp := range certfps {
  977. nsNotice(rb, fmt.Sprintf("%d: %s", i+1, certfp))
  978. }
  979. return
  980. case "add":
  981. err = server.accounts.addRemoveCertfp(target, certfp, true, hasPrivs)
  982. case "del":
  983. err = server.accounts.addRemoveCertfp(target, certfp, false, hasPrivs)
  984. }
  985. switch err {
  986. case nil:
  987. if verb == "add" {
  988. nsNotice(rb, client.t("Certificate fingerprint successfully added"))
  989. } else {
  990. nsNotice(rb, client.t("Certificate fingerprint successfully removed"))
  991. }
  992. case errNoop:
  993. if verb == "add" {
  994. nsNotice(rb, client.t("That certificate fingerprint was already authorized"))
  995. } else {
  996. nsNotice(rb, client.t("Certificate fingerprint not found"))
  997. }
  998. case errAccountDoesNotExist:
  999. nsNotice(rb, client.t("Account does not exist"))
  1000. case errLimitExceeded:
  1001. nsNotice(rb, client.t("You already have too many certificate fingerprints"))
  1002. case utils.ErrInvalidCertfp:
  1003. nsNotice(rb, client.t("Invalid certificate fingerprint"))
  1004. case errCertfpAlreadyExists:
  1005. nsNotice(rb, client.t("That certificate fingerprint is already associated with another account"))
  1006. case errEmptyCredentials:
  1007. nsNotice(rb, client.t("You can't remove all your certificate fingerprints unless you add a password"))
  1008. case errCredsExternallyManaged:
  1009. nsNotice(rb, client.t("Your account credentials are managed externally and cannot be changed here"))
  1010. case errCASFailed:
  1011. nsNotice(rb, client.t("Try again later"))
  1012. default:
  1013. server.logger.Error("internal", "could not modify certificates:", err.Error())
  1014. nsNotice(rb, client.t("An error occurred"))
  1015. }
  1016. }