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 37KB

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