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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611
  1. // Copyright (c) 2017 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "fmt"
  6. "regexp"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/ergochat/irc-go/ircfmt"
  12. "github.com/ergochat/ergo/irc/custime"
  13. "github.com/ergochat/ergo/irc/passwd"
  14. "github.com/ergochat/ergo/irc/sno"
  15. "github.com/ergochat/ergo/irc/utils"
  16. )
  17. // "enabled" callbacks for specific nickserv commands
  18. func servCmdRequiresAccreg(config *Config) bool {
  19. return config.Accounts.Registration.Enabled
  20. }
  21. func servCmdRequiresAuthEnabled(config *Config) bool {
  22. return config.Accounts.AuthenticationEnabled
  23. }
  24. func servCmdRequiresNickRes(config *Config) bool {
  25. return config.Accounts.AuthenticationEnabled && config.Accounts.NickReservation.Enabled
  26. }
  27. func servCmdRequiresBouncerEnabled(config *Config) bool {
  28. return config.Accounts.Multiclient.Enabled
  29. }
  30. func servCmdRequiresEmailReset(config *Config) bool {
  31. return config.Accounts.Registration.EmailVerification.Enabled &&
  32. config.Accounts.Registration.EmailVerification.PasswordReset.Enabled
  33. }
  34. const nickservHelp = `NickServ lets you register, log in to, and manage an account.`
  35. var (
  36. nickservCommands = map[string]*serviceCommand{
  37. "clients": {
  38. handler: nsClientsHandler,
  39. help: `Syntax: $bCLIENTS LIST [nickname]$b
  40. CLIENTS LIST shows information about the clients currently attached, via
  41. the server's multiclient functionality, to your nickname. An administrator
  42. can use this command to list another user's clients.
  43. Syntax: $bCLIENTS LOGOUT [nickname] [client_id/all]$b
  44. CLIENTS LOGOUT detaches a single client, or all clients currently attached
  45. to your nickname. An administrator can use this command to logout another
  46. user's clients.`,
  47. helpShort: `$bCLIENTS$b can list and logout the sessions attached to a nickname.`,
  48. enabled: servCmdRequiresBouncerEnabled,
  49. minParams: 1,
  50. },
  51. "drop": {
  52. handler: nsDropHandler,
  53. help: `Syntax: $bDROP [nickname]$b
  54. DROP de-links the given (or your current) nickname from your user account.`,
  55. helpShort: `$bDROP$b de-links your current (or the given) nickname from your user account.`,
  56. enabled: servCmdRequiresNickRes,
  57. authRequired: true,
  58. },
  59. "enforce": {
  60. hidden: true,
  61. handler: nsEnforceHandler,
  62. help: `Syntax: $bENFORCE [method]$b
  63. ENFORCE is an alias for $bGET enforce$b and $bSET enforce$b. See the help
  64. entry for $bSET$b for more information.`,
  65. authRequired: true,
  66. enabled: servCmdRequiresNickRes,
  67. },
  68. "ghost": {
  69. handler: nsGhostHandler,
  70. help: `Syntax: $bGHOST <nickname>$b
  71. GHOST disconnects the given user from the network if they're logged in with the
  72. same user account, letting you reclaim your nickname.`,
  73. helpShort: `$bGHOST$b reclaims your nickname.`,
  74. enabled: servCmdRequiresNickRes,
  75. authRequired: true,
  76. minParams: 1,
  77. },
  78. "group": {
  79. handler: nsGroupHandler,
  80. help: `Syntax: $bGROUP$b
  81. GROUP links your current nickname with your logged-in account, so other people
  82. will not be able to use it.`,
  83. helpShort: `$bGROUP$b links your current nickname to your user account.`,
  84. enabled: servCmdRequiresNickRes,
  85. authRequired: true,
  86. },
  87. "identify": {
  88. handler: nsIdentifyHandler,
  89. help: `Syntax: $bIDENTIFY <username> [password]$b
  90. IDENTIFY lets you login to the given username using either password auth, or
  91. certfp (your client certificate) if a password is not given.`,
  92. helpShort: `$bIDENTIFY$b lets you login to your account.`,
  93. enabled: servCmdRequiresAuthEnabled,
  94. minParams: 1,
  95. },
  96. "list": {
  97. handler: nsListHandler,
  98. help: `Syntax: $bLIST [regex]$b
  99. LIST returns the list of registered nicknames, which match the given regex.
  100. If no regex is provided, all registered nicknames are returned.`,
  101. helpShort: `$bLIST$b searches the list of registered nicknames.`,
  102. enabled: servCmdRequiresAuthEnabled,
  103. capabs: []string{"accreg"},
  104. minParams: 0,
  105. },
  106. "info": {
  107. handler: nsInfoHandler,
  108. help: `Syntax: $bINFO [username]$b
  109. INFO gives you information about the given (or your own) user account.`,
  110. helpShort: `$bINFO$b gives you information on a user account.`,
  111. },
  112. "register": {
  113. handler: nsRegisterHandler,
  114. // TODO: "email" is an oversimplification here; it's actually any callback, e.g.,
  115. // person@example.com, mailto:person@example.com, tel:16505551234.
  116. help: `Syntax: $bREGISTER <password> [email]$b
  117. REGISTER lets you register your current nickname as a user account. If the
  118. server allows anonymous registration, you can omit the e-mail address.
  119. If you are currently logged in with a TLS client certificate and wish to use
  120. it instead of a password to log in, send * as the password.`,
  121. helpShort: `$bREGISTER$b lets you register a user account.`,
  122. enabled: servCmdRequiresAccreg,
  123. minParams: 1,
  124. maxParams: 2,
  125. },
  126. "sadrop": {
  127. handler: nsDropHandler,
  128. help: `Syntax: $bSADROP <nickname>$b
  129. SADROP forcibly de-links the given nickname from the attached user account.`,
  130. helpShort: `$bSADROP$b forcibly de-links the given nickname from its user account.`,
  131. capabs: []string{"accreg"},
  132. enabled: servCmdRequiresNickRes,
  133. minParams: 1,
  134. },
  135. "saregister": {
  136. handler: nsSaregisterHandler,
  137. help: `Syntax: $bSAREGISTER <username> [password]$b
  138. SAREGISTER registers an account on someone else's behalf.
  139. This is for use in configurations that require SASL for all connections;
  140. an administrator can set use this command to set up user accounts.`,
  141. helpShort: `$bSAREGISTER$b registers an account on someone else's behalf.`,
  142. enabled: servCmdRequiresAuthEnabled,
  143. capabs: []string{"accreg"},
  144. minParams: 1,
  145. },
  146. "sessions": {
  147. hidden: true,
  148. handler: nsClientsHandler,
  149. help: `Syntax: $bSESSIONS [nickname]$b
  150. SESSIONS is an alias for $bCLIENTS LIST$b. See the help entry for $bCLIENTS$b
  151. for more information.`,
  152. enabled: servCmdRequiresBouncerEnabled,
  153. },
  154. "unregister": {
  155. handler: nsUnregisterHandler,
  156. help: `Syntax: $bUNREGISTER <username> [code]$b
  157. UNREGISTER lets you delete your user account (or someone else's, if you're an
  158. IRC operator with the correct permissions). To prevent accidental
  159. unregistrations, a verification code is required; invoking the command without
  160. a code will display the necessary code.`,
  161. helpShort: `$bUNREGISTER$b lets you delete your user account.`,
  162. enabled: servCmdRequiresAuthEnabled,
  163. minParams: 1,
  164. },
  165. "erase": {
  166. handler: nsUnregisterHandler,
  167. help: `Syntax: $bERASE <username> [code]$b
  168. ERASE deletes all records of an account, allowing it to be re-registered.
  169. This should be used with caution, because it violates an expectation that
  170. account names are permanent identifiers. Typically, UNREGISTER should be
  171. used instead. A confirmation code is required; invoking the command
  172. without a code will display the necessary code.`,
  173. helpShort: `$bERASE$b erases all records of an account, allowing reuse.`,
  174. enabled: servCmdRequiresAuthEnabled,
  175. capabs: []string{"accreg"},
  176. minParams: 1,
  177. },
  178. "verify": {
  179. handler: nsVerifyHandler,
  180. help: `Syntax: $bVERIFY <username> <code>$b
  181. VERIFY lets you complete an account registration, if the server requires email
  182. or other verification.`,
  183. helpShort: `$bVERIFY$b lets you complete account registration.`,
  184. enabled: servCmdRequiresAccreg,
  185. minParams: 2,
  186. },
  187. "passwd": {
  188. handler: nsPasswdHandler,
  189. help: `Syntax: $bPASSWD <current> <new> <new_again>$b
  190. Or: $bPASSWD <username> <new>$b
  191. PASSWD lets you change your account password. You must supply your current
  192. password and confirm the new one by typing it twice. If you're an IRC operator
  193. with the correct permissions, you can use PASSWD to reset someone else's
  194. password by supplying their username and then the desired password. To
  195. indicate an empty password, use * instead.`,
  196. helpShort: `$bPASSWD$b lets you change your password.`,
  197. enabled: servCmdRequiresAuthEnabled,
  198. minParams: 2,
  199. },
  200. "password": {
  201. aliasOf: "passwd",
  202. },
  203. "get": {
  204. handler: nsGetHandler,
  205. help: `Syntax: $bGET <setting>$b
  206. GET queries the current values of your account settings. For more information
  207. on the settings and their possible values, see HELP SET.`,
  208. helpShort: `$bGET$b queries the current values of your account settings`,
  209. authRequired: true,
  210. enabled: servCmdRequiresAuthEnabled,
  211. minParams: 1,
  212. },
  213. "saget": {
  214. handler: nsGetHandler,
  215. help: `Syntax: $bSAGET <account> <setting>$b
  216. SAGET queries the values of someone else's account settings. For more
  217. information on the settings and their possible values, see HELP SET.`,
  218. helpShort: `$bSAGET$b queries the current values of another user's account settings`,
  219. enabled: servCmdRequiresAuthEnabled,
  220. minParams: 2,
  221. capabs: []string{"accreg"},
  222. },
  223. "set": {
  224. handler: nsSetHandler,
  225. helpShort: `$bSET$b modifies your account settings`,
  226. // these are broken out as separate strings so they can be translated separately
  227. helpStrings: []string{
  228. `Syntax $bSET <setting> <value>$b
  229. SET modifies your account settings. The following settings are available:`,
  230. `$bENFORCE$b
  231. 'enforce' lets you specify a custom enforcement mechanism for your registered
  232. nicknames. Your options are:
  233. 1. 'none' [no enforcement, overriding the server default]
  234. 2. 'strict' [you must already be authenticated to use the nick]
  235. 3. 'default' [use the server default]`,
  236. `$bMULTICLIENT$b
  237. If 'multiclient' is enabled and you are already logged in and using a nick, a
  238. second client of yours that authenticates with SASL and requests the same nick
  239. is allowed to attach to the nick as well (this is comparable to the behavior
  240. of IRC "bouncers" like ZNC). Your options are 'on' (allow this behavior),
  241. 'off' (disallow it), and 'default' (use the server default value).`,
  242. `$bAUTOREPLAY-LINES$b
  243. 'autoreplay-lines' controls the number of lines of channel history that will
  244. be replayed to you automatically when joining a channel. Your options are any
  245. positive number, 0 to disable the feature, and 'default' to use the server
  246. default.`,
  247. `$bREPLAY-JOINS$b
  248. 'replay-joins' controls whether replayed channel history will include
  249. lines for join and part. This provides more information about the context of
  250. messages, but may be spammy. Your options are 'always' and the default of
  251. 'commands-only' (the messages will be replayed in CHATHISTORY output, but not
  252. during autoreplay).`,
  253. `$bALWAYS-ON$b
  254. 'always-on' controls whether your nickname/identity will remain active
  255. even while you are disconnected from the server. Your options are 'true',
  256. 'false', and 'default' (use the server default value).`,
  257. `$bAUTOREPLAY-MISSED$b
  258. 'autoreplay-missed' is only effective for always-on clients. If enabled,
  259. if you have at most one active session, the server will remember the time
  260. you disconnect and then replay missed messages to you when you reconnect.
  261. Your options are 'on' and 'off'.`,
  262. `$bDM-HISTORY$b
  263. 'dm-history' is only effective for always-on clients. It lets you control
  264. how the history of your direct messages is stored. Your options are:
  265. 1. 'off' [no history]
  266. 2. 'ephemeral' [a limited amount of temporary history, not stored on disk]
  267. 3. 'on' [history stored in a permanent database, if available]
  268. 4. 'default' [use the server default]`,
  269. `$bAUTO-AWAY$b
  270. 'auto-away' is only effective for always-on clients. If enabled, you will
  271. automatically be marked away when all your sessions are disconnected, and
  272. automatically return from away when you connect again.`,
  273. `$bEMAIL$b
  274. 'email' controls the e-mail address associated with your account (if the
  275. server operator allows it, this address can be used for password resets).
  276. As an additional security measure, if you have a password set, you must
  277. provide it as an additional argument to $bSET$b, for example,
  278. SET EMAIL test@example.com hunter2`,
  279. },
  280. authRequired: true,
  281. enabled: servCmdRequiresAuthEnabled,
  282. minParams: 2,
  283. },
  284. "saset": {
  285. handler: nsSetHandler,
  286. help: `Syntax: $bSASET <account> <setting> <value>$b
  287. SASET modifies the values of someone else's account settings. For more
  288. information on the settings and their possible values, see HELP SET.`,
  289. helpShort: `$bSASET$b modifies another user's account settings`,
  290. enabled: servCmdRequiresAuthEnabled,
  291. minParams: 3,
  292. capabs: []string{"accreg"},
  293. },
  294. "sendpass": {
  295. handler: nsSendpassHandler,
  296. help: `Syntax: $bSENDPASS <account>$b
  297. SENDPASS sends a password reset email to the email address associated with
  298. the target account. The reset code in the email can then be used with the
  299. $bRESETPASS$b command.`,
  300. helpShort: `$bSENDPASS$b initiates an email-based password reset`,
  301. enabled: servCmdRequiresEmailReset,
  302. minParams: 1,
  303. },
  304. "resetpass": {
  305. handler: nsResetpassHandler,
  306. help: `Syntax: $bRESETPASS <account> <code> <password>$b
  307. RESETPASS resets an account password, using a reset code that was emailed as
  308. the result of a previous $bSENDPASS$b command.`,
  309. helpShort: `$bRESETPASS$b completes an email-based password reset`,
  310. enabled: servCmdRequiresEmailReset,
  311. minParams: 3,
  312. },
  313. "cert": {
  314. handler: nsCertHandler,
  315. help: `Syntax: $bCERT <LIST | ADD | DEL> [account] [certfp]$b
  316. CERT examines or modifies the SHA-256 TLS certificate fingerprints that can
  317. be used to log into an account. Specifically, $bCERT LIST$b lists the
  318. authorized fingerprints, $bCERT ADD <fingerprint>$b adds a new fingerprint, and
  319. $bCERT DEL <fingerprint>$b removes a fingerprint. If you're an IRC operator
  320. with the correct permissions, you can act on another user's account, for
  321. example with $bCERT ADD <account> <fingerprint>$b. See the operator manual
  322. for instructions on how to compute the fingerprint.`,
  323. helpShort: `$bCERT$b controls a user account's certificate fingerprints`,
  324. enabled: servCmdRequiresAuthEnabled,
  325. minParams: 1,
  326. },
  327. "suspend": {
  328. handler: nsSuspendHandler,
  329. help: `Syntax: $bSUSPEND ADD <nickname> [DURATION duration] [reason]$b
  330. $bSUSPEND DEL <nickname>$b
  331. $bSUSPEND LIST$b
  332. Suspending an account disables it (preventing new logins) and disconnects
  333. all associated clients. You can specify a time limit or a reason for
  334. the suspension. The $bDEL$b subcommand reverses a suspension, and the $bLIST$b
  335. command lists all current suspensions.`,
  336. helpShort: `$bSUSPEND$b manages account suspensions`,
  337. minParams: 1,
  338. capabs: []string{"ban"},
  339. },
  340. "rename": {
  341. handler: nsRenameHandler,
  342. help: `Syntax: $bRENAME <account> <newname>$b
  343. RENAME allows a server administrator to change the name of an account.
  344. Currently, you can only change the canonical casefolding of an account
  345. (e.g., you can change "Alice" to "alice", but not "Alice" to "Amanda").`,
  346. helpShort: `$bRENAME$b renames an account`,
  347. minParams: 2,
  348. capabs: []string{"accreg"},
  349. },
  350. "verifyemail": {
  351. handler: nsVerifyEmailHandler,
  352. authRequired: true,
  353. minParams: 1,
  354. hidden: true,
  355. },
  356. }
  357. )
  358. func nsGetHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  359. var account string
  360. if command == "saget" {
  361. account = params[0]
  362. params = params[1:]
  363. } else {
  364. account = client.Account()
  365. }
  366. accountData, err := server.accounts.LoadAccount(account)
  367. if err == errAccountDoesNotExist {
  368. service.Notice(rb, client.t("No such account"))
  369. return
  370. } else if err != nil {
  371. service.Notice(rb, client.t("Error loading account data"))
  372. return
  373. }
  374. displaySetting(service, params[0], accountData.Settings, client, rb)
  375. }
  376. func displaySetting(service *ircService, settingName string, settings AccountSettings, client *Client, rb *ResponseBuffer) {
  377. config := client.server.Config()
  378. switch strings.ToLower(settingName) {
  379. case "enforce":
  380. storedValue := settings.NickEnforcement
  381. serializedStoredValue := nickReservationToString(storedValue)
  382. service.Notice(rb, fmt.Sprintf(client.t("Your stored nickname enforcement setting is: %s"), serializedStoredValue))
  383. serializedActualValue := nickReservationToString(configuredEnforcementMethod(config, storedValue))
  384. service.Notice(rb, fmt.Sprintf(client.t("Given current server settings, your nickname is enforced with: %s"), serializedActualValue))
  385. case "autoreplay-lines":
  386. if settings.AutoreplayLines == nil {
  387. service.Notice(rb, fmt.Sprintf(client.t("You will receive the server default of %d lines of autoreplayed history"), config.History.AutoreplayOnJoin))
  388. } else {
  389. service.Notice(rb, fmt.Sprintf(client.t("You will receive %d lines of autoreplayed history"), *settings.AutoreplayLines))
  390. }
  391. case "replay-joins":
  392. switch settings.ReplayJoins {
  393. case ReplayJoinsCommandsOnly:
  394. service.Notice(rb, client.t("You will see JOINs and PARTs in /HISTORY output, but not in autoreplay"))
  395. case ReplayJoinsAlways:
  396. service.Notice(rb, client.t("You will see JOINs and PARTs in /HISTORY output and in autoreplay"))
  397. }
  398. case "multiclient":
  399. if !config.Accounts.Multiclient.Enabled {
  400. service.Notice(rb, client.t("This feature has been disabled by the server administrators"))
  401. } else {
  402. switch settings.AllowBouncer {
  403. case MulticlientAllowedServerDefault:
  404. if config.Accounts.Multiclient.AllowedByDefault {
  405. service.Notice(rb, client.t("Multiclient functionality is currently enabled for your account, but you can opt out"))
  406. } else {
  407. service.Notice(rb, client.t("Multiclient functionality is currently disabled for your account, but you can opt in"))
  408. }
  409. case MulticlientDisallowedByUser:
  410. service.Notice(rb, client.t("Multiclient functionality is currently disabled for your account"))
  411. case MulticlientAllowedByUser:
  412. service.Notice(rb, client.t("Multiclient functionality is currently enabled for your account"))
  413. }
  414. }
  415. case "always-on":
  416. stored := settings.AlwaysOn
  417. actual := persistenceEnabled(config.Accounts.Multiclient.AlwaysOn, stored)
  418. service.Notice(rb, fmt.Sprintf(client.t("Your stored always-on setting is: %s"), userPersistentStatusToString(stored)))
  419. if actual {
  420. service.Notice(rb, client.t("Given current server settings, your client is always-on"))
  421. } else {
  422. service.Notice(rb, client.t("Given current server settings, your client is not always-on"))
  423. }
  424. case "autoreplay-missed":
  425. stored := settings.AutoreplayMissed
  426. if stored {
  427. alwaysOn := persistenceEnabled(config.Accounts.Multiclient.AlwaysOn, settings.AlwaysOn)
  428. if alwaysOn {
  429. service.Notice(rb, client.t("Autoreplay of missed messages is enabled"))
  430. } else {
  431. service.Notice(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"))
  432. }
  433. } else {
  434. service.Notice(rb, client.t("Your account is not configured to receive autoreplayed missed messages"))
  435. }
  436. case "auto-away":
  437. stored := settings.AutoAway
  438. alwaysOn := persistenceEnabled(config.Accounts.Multiclient.AlwaysOn, settings.AlwaysOn)
  439. actual := persistenceEnabled(config.Accounts.Multiclient.AutoAway, settings.AutoAway)
  440. service.Notice(rb, fmt.Sprintf(client.t("Your stored auto-away setting is: %s"), userPersistentStatusToString(stored)))
  441. if actual && alwaysOn {
  442. service.Notice(rb, client.t("Given current server settings, auto-away is enabled for your client"))
  443. } else if actual && !alwaysOn {
  444. service.Notice(rb, client.t("Because your client is not always-on, auto-away is disabled"))
  445. } else if !actual {
  446. service.Notice(rb, client.t("Given current server settings, auto-away is disabled for your client"))
  447. }
  448. case "dm-history":
  449. effectiveValue := historyEnabled(config.History.Persistent.DirectMessages, settings.DMHistory)
  450. service.Notice(rb, fmt.Sprintf(client.t("Your stored direct message history setting is: %s"), historyStatusToString(settings.DMHistory)))
  451. service.Notice(rb, fmt.Sprintf(client.t("Given current server settings, your direct message history setting is: %s"), historyStatusToString(effectiveValue)))
  452. case "email":
  453. if settings.Email != "" {
  454. service.Notice(rb, fmt.Sprintf(client.t("Your stored e-mail address is: %s"), settings.Email))
  455. } else {
  456. service.Notice(rb, client.t("You have no stored e-mail address"))
  457. }
  458. default:
  459. service.Notice(rb, client.t("No such setting"))
  460. }
  461. }
  462. func userPersistentStatusToString(status PersistentStatus) string {
  463. // #1544: "mandatory" as a user setting should display as "enabled"
  464. result := persistentStatusToString(status)
  465. if result == "mandatory" {
  466. result = "enabled"
  467. }
  468. return result
  469. }
  470. func nsSetHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  471. var privileged bool
  472. var account string
  473. if command == "saset" {
  474. privileged = true
  475. account = params[0]
  476. params = params[1:]
  477. } else {
  478. account = client.Account()
  479. }
  480. key := strings.ToLower(params[0])
  481. // unprivileged NS SET EMAIL is different because it requires a confirmation
  482. if !privileged && key == "email" {
  483. nsSetEmailHandler(service, client, params, rb)
  484. return
  485. }
  486. var munger settingsMunger
  487. var finalSettings AccountSettings
  488. var err error
  489. switch key {
  490. case "pass", "password":
  491. service.Notice(rb, client.t("To change a password, use the PASSWD command. For details, /msg NickServ HELP PASSWD"))
  492. return
  493. case "enforce":
  494. var method NickEnforcementMethod
  495. method, err = nickReservationFromString(params[1])
  496. if err != nil {
  497. err = errInvalidParams
  498. break
  499. }
  500. // updating enforcement settings is special-cased, because it requires
  501. // an update to server.accounts.accountToMethod
  502. finalSettings, err = server.accounts.SetEnforcementStatus(account, method)
  503. if err == nil {
  504. finalSettings.NickEnforcement = method // success
  505. }
  506. case "autoreplay-lines":
  507. var newValue *int
  508. if strings.ToLower(params[1]) != "default" {
  509. val, err_ := strconv.Atoi(params[1])
  510. if err_ != nil || val < 0 {
  511. err = errInvalidParams
  512. break
  513. }
  514. newValue = new(int)
  515. *newValue = val
  516. }
  517. munger = func(in AccountSettings) (out AccountSettings, err error) {
  518. out = in
  519. out.AutoreplayLines = newValue
  520. return
  521. }
  522. case "multiclient":
  523. var newValue MulticlientAllowedSetting
  524. if strings.ToLower(params[1]) == "default" {
  525. newValue = MulticlientAllowedServerDefault
  526. } else {
  527. var enabled bool
  528. enabled, err = utils.StringToBool(params[1])
  529. if enabled {
  530. newValue = MulticlientAllowedByUser
  531. } else {
  532. newValue = MulticlientDisallowedByUser
  533. }
  534. }
  535. if err == nil {
  536. munger = func(in AccountSettings) (out AccountSettings, err error) {
  537. out = in
  538. out.AllowBouncer = newValue
  539. return
  540. }
  541. }
  542. case "replay-joins":
  543. var newValue ReplayJoinsSetting
  544. newValue, err = replayJoinsSettingFromString(params[1])
  545. if err == nil {
  546. munger = func(in AccountSettings) (out AccountSettings, err error) {
  547. out = in
  548. out.ReplayJoins = newValue
  549. return
  550. }
  551. }
  552. case "always-on":
  553. // #821: it's problematic to alter the value of always-on if you're not
  554. // the (actual or potential) always-on client yourself. make an exception
  555. // for `saset` to give operators an escape hatch (any consistency problems
  556. // can probably be fixed by restarting the server):
  557. if command != "saset" {
  558. details := client.Details()
  559. if details.nick != details.accountName {
  560. err = errNickAccountMismatch
  561. }
  562. }
  563. if err == nil {
  564. var newValue PersistentStatus
  565. newValue, err = persistentStatusFromString(params[1])
  566. // "opt-in" and "opt-out" don't make sense as user preferences
  567. if err == nil && newValue != PersistentOptIn && newValue != PersistentOptOut {
  568. munger = func(in AccountSettings) (out AccountSettings, err error) {
  569. out = in
  570. out.AlwaysOn = newValue
  571. return
  572. }
  573. }
  574. }
  575. case "autoreplay-missed":
  576. var newValue bool
  577. newValue, err = utils.StringToBool(params[1])
  578. if err == nil {
  579. munger = func(in AccountSettings) (out AccountSettings, err error) {
  580. out = in
  581. out.AutoreplayMissed = newValue
  582. return
  583. }
  584. }
  585. case "auto-away":
  586. var newValue PersistentStatus
  587. newValue, err = persistentStatusFromString(params[1])
  588. // "opt-in" and "opt-out" don't make sense as user preferences
  589. if err == nil && newValue != PersistentOptIn && newValue != PersistentOptOut {
  590. munger = func(in AccountSettings) (out AccountSettings, err error) {
  591. out = in
  592. out.AutoAway = newValue
  593. return
  594. }
  595. }
  596. case "dm-history":
  597. var newValue HistoryStatus
  598. newValue, err = historyStatusFromString(params[1])
  599. if err == nil {
  600. munger = func(in AccountSettings) (out AccountSettings, err error) {
  601. out = in
  602. out.DMHistory = newValue
  603. return
  604. }
  605. }
  606. case "email":
  607. newValue := params[1]
  608. munger = func(in AccountSettings) (out AccountSettings, err error) {
  609. out = in
  610. out.Email = newValue
  611. return
  612. }
  613. default:
  614. err = errInvalidParams
  615. }
  616. if munger != nil {
  617. finalSettings, err = server.accounts.ModifyAccountSettings(account, munger)
  618. }
  619. switch err {
  620. case nil:
  621. service.Notice(rb, client.t("Successfully changed your account settings"))
  622. displaySetting(service, key, finalSettings, client, rb)
  623. case errInvalidParams, errAccountDoesNotExist, errFeatureDisabled, errAccountUnverified, errAccountUpdateFailed:
  624. service.Notice(rb, client.t(err.Error()))
  625. case errNickAccountMismatch:
  626. service.Notice(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()))
  627. default:
  628. // unknown error
  629. service.Notice(rb, client.t("An error occurred"))
  630. }
  631. }
  632. // handle unprivileged NS SET EMAIL, which sends a confirmation code
  633. func nsSetEmailHandler(service *ircService, client *Client, params []string, rb *ResponseBuffer) {
  634. config := client.server.Config()
  635. if !config.Accounts.Registration.EmailVerification.Enabled {
  636. rb.Notice(client.t("E-mail verification is disabled"))
  637. return
  638. }
  639. if !nsLoginThrottleCheck(service, client, rb) {
  640. return
  641. }
  642. var password string
  643. if len(params) > 2 {
  644. password = params[2]
  645. }
  646. account := client.Account()
  647. errorMessage := nsConfirmPassword(client.server, account, password)
  648. if errorMessage != "" {
  649. service.Notice(rb, client.t(errorMessage))
  650. return
  651. }
  652. err := client.server.accounts.NsSetEmail(client, params[1])
  653. switch err {
  654. case nil:
  655. service.Notice(rb, client.t("Check your e-mail for instructions on how to confirm your change of address"))
  656. case errLimitExceeded:
  657. service.Notice(rb, client.t("Try again later"))
  658. default:
  659. // if appropriate, show the client the error from the attempted email sending
  660. if rErr := registrationCallbackErrorText(config, client, err); rErr != "" {
  661. service.Notice(rb, rErr)
  662. } else {
  663. service.Notice(rb, client.t("An error occurred"))
  664. }
  665. }
  666. }
  667. func nsVerifyEmailHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  668. err := server.accounts.NsVerifyEmail(client, params[0])
  669. switch err {
  670. case nil:
  671. service.Notice(rb, client.t("Successfully changed your account settings"))
  672. displaySetting(service, "email", client.AccountSettings(), client, rb)
  673. case errAccountVerificationInvalidCode:
  674. service.Notice(rb, client.t(err.Error()))
  675. default:
  676. service.Notice(rb, client.t("An error occurred"))
  677. }
  678. }
  679. func nsDropHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  680. sadrop := command == "sadrop"
  681. var nick string
  682. if len(params) > 0 {
  683. nick = params[0]
  684. } else {
  685. nick = client.NickCasefolded()
  686. }
  687. err := server.accounts.SetNickReserved(client, nick, sadrop, false)
  688. if err == nil {
  689. service.Notice(rb, fmt.Sprintf(client.t("Successfully ungrouped nick %s with your account"), nick))
  690. } else if err == errAccountNotLoggedIn {
  691. service.Notice(rb, client.t("You're not logged into an account"))
  692. } else if err == errAccountCantDropPrimaryNick {
  693. service.Notice(rb, client.t("You can't ungroup your primary nickname (try unregistering your account instead)"))
  694. } else {
  695. service.Notice(rb, client.t("Could not ungroup nick"))
  696. }
  697. }
  698. func nsGhostHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  699. nick := params[0]
  700. ghost := server.clients.Get(nick)
  701. if ghost == nil {
  702. service.Notice(rb, client.t("No such nick"))
  703. return
  704. } else if ghost == client {
  705. service.Notice(rb, client.t("You can't GHOST yourself (try /QUIT instead)"))
  706. return
  707. } else if ghost.AlwaysOn() {
  708. service.Notice(rb, client.t("You can't GHOST an always-on client"))
  709. return
  710. }
  711. authorized := false
  712. account := client.Account()
  713. if account != "" {
  714. // the user must either own the nick, or the target client
  715. authorized = (server.accounts.NickToAccount(nick) == account) || (ghost.Account() == account)
  716. }
  717. if !authorized {
  718. service.Notice(rb, client.t("You don't own that nick"))
  719. return
  720. }
  721. ghost.Quit(fmt.Sprintf(ghost.t("GHOSTed by %s"), client.Nick()), nil)
  722. ghost.destroy(nil)
  723. }
  724. func nsGroupHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  725. nick := client.Nick()
  726. err := server.accounts.SetNickReserved(client, nick, false, true)
  727. if err == nil {
  728. service.Notice(rb, fmt.Sprintf(client.t("Successfully grouped nick %s with your account"), nick))
  729. } else if err == errAccountTooManyNicks {
  730. service.Notice(rb, client.t("You have too many nicks reserved already (you can remove some with /NS DROP)"))
  731. } else if err == errNicknameReserved {
  732. service.Notice(rb, client.t("That nickname is already reserved by someone else"))
  733. } else {
  734. service.Notice(rb, client.t("Error reserving nickname"))
  735. }
  736. }
  737. func nsLoginThrottleCheck(service *ircService, client *Client, rb *ResponseBuffer) (success bool) {
  738. throttled, remainingTime := client.checkLoginThrottle()
  739. if throttled {
  740. service.Notice(rb, fmt.Sprintf(client.t("Please wait at least %v and try again"), remainingTime))
  741. }
  742. return !throttled
  743. }
  744. func nsIdentifyHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  745. if client.LoggedIntoAccount() {
  746. service.Notice(rb, client.t("You're already logged into an account"))
  747. return
  748. }
  749. var err error
  750. loginSuccessful := false
  751. var username, passphrase string
  752. if len(params) == 1 {
  753. if rb.session.certfp != "" {
  754. username = params[0]
  755. } else {
  756. // XXX undocumented compatibility mode with other nickservs, allowing
  757. // /msg NickServ identify passphrase
  758. username = client.NickCasefolded()
  759. passphrase = params[0]
  760. }
  761. } else {
  762. username = params[0]
  763. passphrase = params[1]
  764. }
  765. // try passphrase
  766. if passphrase != "" {
  767. err = server.accounts.AuthenticateByPassphrase(client, username, passphrase)
  768. loginSuccessful = (err == nil)
  769. }
  770. // try certfp
  771. if !loginSuccessful && rb.session.certfp != "" {
  772. err = server.accounts.AuthenticateByCertificate(client, rb.session.certfp, rb.session.peerCerts, "")
  773. loginSuccessful = (err == nil)
  774. }
  775. nickFixupFailed := false
  776. if loginSuccessful {
  777. if !fixupNickEqualsAccount(client, rb, server.Config(), service.prefix) {
  778. loginSuccessful = false
  779. // fixupNickEqualsAccount sends its own error message, don't send another
  780. nickFixupFailed = true
  781. }
  782. }
  783. if loginSuccessful {
  784. sendSuccessfulAccountAuth(service, client, rb, true)
  785. } else if !nickFixupFailed {
  786. service.Notice(rb, fmt.Sprintf(client.t("Authentication failed: %s"), authErrorToMessage(server, err)))
  787. }
  788. }
  789. func nsListHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  790. if !client.HasRoleCapabs("accreg") {
  791. service.Notice(rb, client.t("Insufficient privileges"))
  792. return
  793. }
  794. var searchRegex *regexp.Regexp
  795. if len(params) > 0 {
  796. var err error
  797. searchRegex, err = regexp.Compile(params[0])
  798. if err != nil {
  799. service.Notice(rb, client.t("Invalid regex"))
  800. return
  801. }
  802. }
  803. service.Notice(rb, ircfmt.Unescape(client.t("*** $bNickServ LIST$b ***")))
  804. nicks := server.accounts.AllNicks()
  805. for _, nick := range nicks {
  806. if searchRegex == nil || searchRegex.MatchString(nick) {
  807. service.Notice(rb, fmt.Sprintf(" %s", nick))
  808. }
  809. }
  810. service.Notice(rb, ircfmt.Unescape(client.t("*** $bEnd of NickServ LIST$b ***")))
  811. }
  812. func nsInfoHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  813. if !server.Config().Accounts.AuthenticationEnabled && !client.HasRoleCapabs("accreg") {
  814. service.Notice(rb, client.t("This command has been disabled by the server administrators"))
  815. return
  816. }
  817. var accountName string
  818. if len(params) > 0 {
  819. nick := params[0]
  820. if server.Config().Accounts.NickReservation.Enabled {
  821. accountName = server.accounts.NickToAccount(nick)
  822. if accountName == "" {
  823. service.Notice(rb, client.t("That nickname is not registered"))
  824. return
  825. }
  826. } else {
  827. accountName = nick
  828. }
  829. } else {
  830. accountName = client.Account()
  831. if accountName == "" {
  832. service.Notice(rb, client.t("You're not logged into an account"))
  833. return
  834. }
  835. }
  836. account, err := server.accounts.LoadAccount(accountName)
  837. if err != nil || !account.Verified {
  838. service.Notice(rb, client.t("Account does not exist"))
  839. return
  840. }
  841. service.Notice(rb, fmt.Sprintf(client.t("Account: %s"), account.Name))
  842. registeredAt := account.RegisteredAt.Format(time.RFC1123)
  843. service.Notice(rb, fmt.Sprintf(client.t("Registered at: %s"), registeredAt))
  844. if account.Name == client.AccountName() || client.HasRoleCapabs("accreg") {
  845. if account.Settings.Email != "" {
  846. service.Notice(rb, fmt.Sprintf(client.t("Email address: %s"), account.Settings.Email))
  847. }
  848. }
  849. // TODO nicer formatting for this
  850. for _, nick := range account.AdditionalNicks {
  851. service.Notice(rb, fmt.Sprintf(client.t("Additional grouped nick: %s"), nick))
  852. }
  853. listRegisteredChannels(service, accountName, rb)
  854. if account.Suspended != nil {
  855. service.Notice(rb, suspensionToString(client, *account.Suspended))
  856. }
  857. }
  858. func listRegisteredChannels(service *ircService, accountName string, rb *ResponseBuffer) {
  859. client := rb.session.client
  860. channels := client.server.accounts.ChannelsForAccount(accountName)
  861. service.Notice(rb, fmt.Sprintf(client.t("Account %s has %d registered channel(s)."), accountName, len(channels)))
  862. for _, channel := range rb.session.client.server.accounts.ChannelsForAccount(accountName) {
  863. service.Notice(rb, fmt.Sprintf(client.t("Registered channel: %s"), channel))
  864. }
  865. }
  866. func nsRegisterHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  867. details := client.Details()
  868. passphrase := params[0]
  869. var email string
  870. if 1 < len(params) {
  871. email = params[1]
  872. }
  873. certfp := rb.session.certfp
  874. if passphrase == "*" {
  875. if certfp == "" {
  876. service.Notice(rb, client.t("You must be connected with TLS and a client certificate to do this"))
  877. return
  878. } else {
  879. passphrase = ""
  880. }
  881. }
  882. if passphrase != "" {
  883. cfPassphrase, err := Casefold(passphrase)
  884. if err == nil && cfPassphrase == details.nickCasefolded {
  885. service.Notice(rb, client.t("Usage: REGISTER <passphrase> [email]")) // #1179
  886. return
  887. }
  888. }
  889. if !nsLoginThrottleCheck(service, client, rb) {
  890. return
  891. }
  892. config := server.Config()
  893. account := details.nick
  894. if config.Accounts.NickReservation.ForceGuestFormat {
  895. matches := config.Accounts.NickReservation.guestRegexp.FindStringSubmatch(account)
  896. if matches == nil || len(matches) < 2 {
  897. service.Notice(rb, client.t("Erroneous nickname"))
  898. return
  899. }
  900. account = matches[1]
  901. }
  902. callbackNamespace, callbackValue, validationErr := parseCallback(email, config)
  903. if validationErr != nil {
  904. service.Notice(rb, client.t("Registration requires a valid e-mail address"))
  905. return
  906. }
  907. err := server.accounts.Register(client, account, callbackNamespace, callbackValue, passphrase, rb.session.certfp)
  908. if err == nil {
  909. if callbackNamespace == "*" {
  910. err = server.accounts.Verify(client, account, "")
  911. if err == nil && fixupNickEqualsAccount(client, rb, config, service.prefix) {
  912. sendSuccessfulRegResponse(service, client, rb)
  913. }
  914. } else {
  915. messageTemplate := client.t("Account created, pending verification; verification code has been sent to %s")
  916. message := fmt.Sprintf(messageTemplate, callbackValue)
  917. service.Notice(rb, message)
  918. announcePendingReg(client, rb, account)
  919. }
  920. } else {
  921. // details could not be stored and relevant numerics have been dispatched, abort
  922. message := registrationErrorToMessage(config, client, err)
  923. service.Notice(rb, client.t(message))
  924. }
  925. }
  926. func nsSaregisterHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  927. var account, passphrase string
  928. account = params[0]
  929. if 1 < len(params) && params[1] != "*" {
  930. passphrase = params[1]
  931. }
  932. err := server.accounts.SARegister(account, passphrase)
  933. if err != nil {
  934. var errMsg string
  935. if err == errAccountAlreadyRegistered || err == errAccountAlreadyVerified {
  936. errMsg = client.t("Account already exists")
  937. } else if err == errAccountBadPassphrase {
  938. errMsg = client.t("Passphrase contains forbidden characters or is otherwise invalid")
  939. } else {
  940. server.logger.Error("services", "unknown error from saregister", err.Error())
  941. errMsg = client.t("Could not register")
  942. }
  943. service.Notice(rb, errMsg)
  944. } else {
  945. service.Notice(rb, fmt.Sprintf(client.t("Successfully registered account %s"), account))
  946. 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))
  947. }
  948. }
  949. func nsUnregisterHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  950. erase := command == "erase"
  951. username := params[0]
  952. var verificationCode string
  953. if len(params) > 1 {
  954. verificationCode = params[1]
  955. }
  956. if username == "" {
  957. service.Notice(rb, client.t("You must specify an account"))
  958. return
  959. }
  960. var accountName string
  961. var registeredAt time.Time
  962. if erase {
  963. // account may not be in a loadable state, e.g., if it was unregistered
  964. accountName = username
  965. // make the confirmation code nondeterministic for ERASE
  966. registeredAt = server.ctime
  967. } else {
  968. account, err := server.accounts.LoadAccount(username)
  969. if err == errAccountDoesNotExist {
  970. service.Notice(rb, client.t("Invalid account name"))
  971. return
  972. } else if err != nil {
  973. service.Notice(rb, client.t("Internal error"))
  974. return
  975. }
  976. accountName = account.Name
  977. registeredAt = account.RegisteredAt
  978. }
  979. if !(accountName == client.AccountName() || client.HasRoleCapabs("accreg")) {
  980. service.Notice(rb, client.t("Insufficient oper privs"))
  981. return
  982. }
  983. expectedCode := utils.ConfirmationCode(accountName, registeredAt)
  984. if expectedCode != verificationCode {
  985. if erase {
  986. service.Notice(rb, ircfmt.Unescape(client.t("$bWarning: erasing this account will allow it to be re-registered; consider UNREGISTER instead.$b")))
  987. } else {
  988. service.Notice(rb, ircfmt.Unescape(client.t("$bWarning: unregistering this account will remove its stored privileges.$b")))
  989. service.Notice(rb, ircfmt.Unescape(client.t("$bNote that an unregistered account name remains reserved and cannot be re-registered.$b")))
  990. service.Notice(rb, ircfmt.Unescape(client.t("$bIf you are having problems with your account, contact an administrator.$b")))
  991. }
  992. service.Notice(rb, fmt.Sprintf(client.t("To confirm, run this command: %s"), fmt.Sprintf("/NS %s %s %s", strings.ToUpper(command), accountName, expectedCode)))
  993. return
  994. }
  995. err := server.accounts.Unregister(accountName, erase)
  996. if err == errAccountDoesNotExist {
  997. service.Notice(rb, client.t(err.Error()))
  998. } else if err != nil {
  999. service.Notice(rb, client.t("Error while unregistering account"))
  1000. } else {
  1001. service.Notice(rb, fmt.Sprintf(client.t("Successfully unregistered account %s"), accountName))
  1002. server.logger.Info("accounts", "client", client.Nick(), "unregistered account", accountName)
  1003. 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))
  1004. }
  1005. }
  1006. func nsVerifyHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1007. username, code := params[0], params[1]
  1008. err := server.accounts.Verify(client, username, code)
  1009. var errorMessage string
  1010. if err != nil {
  1011. switch err {
  1012. case errAccountAlreadyLoggedIn, errAccountVerificationInvalidCode, errAccountAlreadyVerified:
  1013. errorMessage = err.Error()
  1014. default:
  1015. errorMessage = errAccountVerificationFailed.Error()
  1016. }
  1017. }
  1018. if errorMessage != "" {
  1019. service.Notice(rb, client.t(errorMessage))
  1020. return
  1021. }
  1022. if fixupNickEqualsAccount(client, rb, server.Config(), service.prefix) {
  1023. sendSuccessfulRegResponse(service, client, rb)
  1024. }
  1025. }
  1026. func nsConfirmPassword(server *Server, account, passphrase string) (errorMessage string) {
  1027. accountData, err := server.accounts.LoadAccount(account)
  1028. if err != nil {
  1029. errorMessage = `You're not logged into an account`
  1030. } else {
  1031. hash := accountData.Credentials.PassphraseHash
  1032. if hash != nil {
  1033. if passphrase == "" {
  1034. errorMessage = `You must supply a password`
  1035. } else if passwd.CompareHashAndPassword(hash, []byte(passphrase)) != nil {
  1036. errorMessage = `Password incorrect`
  1037. }
  1038. }
  1039. }
  1040. return
  1041. }
  1042. func nsPasswdHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1043. var target string
  1044. var newPassword string
  1045. var errorMessage string
  1046. var oper *Oper
  1047. switch len(params) {
  1048. case 2:
  1049. oper = client.Oper()
  1050. if !oper.HasRoleCapab("accreg") {
  1051. errorMessage = `Insufficient privileges`
  1052. } else {
  1053. target, newPassword = params[0], params[1]
  1054. if newPassword == "*" {
  1055. newPassword = ""
  1056. }
  1057. message := fmt.Sprintf("Operator %s ran NS PASSWD for account %s", oper.Name, target)
  1058. server.snomasks.Send(sno.LocalOpers, message)
  1059. server.logger.Info("opers", message)
  1060. }
  1061. case 3:
  1062. target = client.Account()
  1063. newPassword = params[1]
  1064. if newPassword == "*" {
  1065. newPassword = ""
  1066. }
  1067. checkPassword := params[2]
  1068. if checkPassword == "*" {
  1069. checkPassword = "" // #1883
  1070. }
  1071. if target == "" {
  1072. errorMessage = `You're not logged into an account`
  1073. } else if newPassword != checkPassword {
  1074. errorMessage = `Passwords do not match`
  1075. } else {
  1076. if !nsLoginThrottleCheck(service, client, rb) {
  1077. return
  1078. }
  1079. errorMessage = nsConfirmPassword(server, target, params[0])
  1080. }
  1081. default:
  1082. errorMessage = `Invalid parameters`
  1083. }
  1084. if errorMessage != "" {
  1085. service.Notice(rb, client.t(errorMessage))
  1086. return
  1087. }
  1088. err := server.accounts.setPassword(target, newPassword, oper != nil)
  1089. switch err {
  1090. case nil:
  1091. service.Notice(rb, client.t("Password changed"))
  1092. case errEmptyCredentials:
  1093. service.Notice(rb, client.t("You can't delete your password unless you add a certificate fingerprint"))
  1094. case errCredsExternallyManaged:
  1095. service.Notice(rb, client.t("Your account credentials are managed externally and cannot be changed here"))
  1096. case errCASFailed:
  1097. service.Notice(rb, client.t("Try again later"))
  1098. case errAccountDoesNotExist:
  1099. service.Notice(rb, client.t("Account does not exist"))
  1100. default:
  1101. server.logger.Error("internal", "could not upgrade user password:", err.Error())
  1102. service.Notice(rb, client.t("Password could not be changed due to server error"))
  1103. }
  1104. }
  1105. func nsEnforceHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1106. newParams := []string{"enforce"}
  1107. if len(params) == 0 {
  1108. nsGetHandler(service, server, client, "get", newParams, rb)
  1109. } else {
  1110. newParams = append(newParams, params[0])
  1111. nsSetHandler(service, server, client, "set", newParams, rb)
  1112. }
  1113. }
  1114. func nsClientsHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1115. var verb string
  1116. if command == "sessions" {
  1117. // Legacy "SESSIONS" command is an alias for CLIENTS LIST.
  1118. verb = "list"
  1119. } else if len(params) > 0 {
  1120. verb = strings.ToLower(params[0])
  1121. params = params[1:]
  1122. }
  1123. switch verb {
  1124. case "list":
  1125. nsClientsListHandler(service, server, client, params, rb)
  1126. case "logout":
  1127. nsClientsLogoutHandler(service, server, client, params, rb)
  1128. default:
  1129. service.Notice(rb, client.t("Invalid parameters"))
  1130. }
  1131. }
  1132. func nsClientsListHandler(service *ircService, server *Server, client *Client, params []string, rb *ResponseBuffer) {
  1133. target := client
  1134. hasPrivs := client.HasRoleCapabs("ban")
  1135. if 0 < len(params) {
  1136. target = server.clients.Get(params[0])
  1137. if target == nil {
  1138. service.Notice(rb, client.t("No such nick"))
  1139. return
  1140. }
  1141. if target != client && !hasPrivs {
  1142. service.Notice(rb, client.t("Command restricted"))
  1143. return
  1144. }
  1145. }
  1146. sessionData, currentIndex := target.AllSessionData(rb.session, hasPrivs)
  1147. service.Notice(rb, fmt.Sprintf(client.t("Nickname %[1]s has %[2]d attached clients(s)"), target.Nick(), len(sessionData)))
  1148. for i, session := range sessionData {
  1149. if currentIndex == i {
  1150. service.Notice(rb, fmt.Sprintf(client.t("Client %d (currently attached client):"), session.sessionID))
  1151. } else {
  1152. service.Notice(rb, fmt.Sprintf(client.t("Client %d:"), session.sessionID))
  1153. }
  1154. if session.deviceID != "" {
  1155. service.Notice(rb, fmt.Sprintf(client.t("Device ID: %s"), session.deviceID))
  1156. }
  1157. service.Notice(rb, fmt.Sprintf(client.t("IP address: %s"), session.ip.String()))
  1158. service.Notice(rb, fmt.Sprintf(client.t("Hostname: %s"), session.hostname))
  1159. if hasPrivs {
  1160. service.Notice(rb, fmt.Sprintf(client.t("Connection: %s"), session.connInfo))
  1161. }
  1162. service.Notice(rb, fmt.Sprintf(client.t("Created at: %s"), session.ctime.Format(time.RFC1123)))
  1163. service.Notice(rb, fmt.Sprintf(client.t("Last active: %s"), session.atime.Format(time.RFC1123)))
  1164. if session.certfp != "" {
  1165. service.Notice(rb, fmt.Sprintf(client.t("Certfp: %s"), session.certfp))
  1166. }
  1167. for _, capStr := range session.caps {
  1168. if capStr != "" {
  1169. service.Notice(rb, fmt.Sprintf(client.t("IRCv3 CAPs: %s"), capStr))
  1170. }
  1171. }
  1172. }
  1173. }
  1174. func nsClientsLogoutHandler(service *ircService, server *Server, client *Client, params []string, rb *ResponseBuffer) {
  1175. if len(params) < 1 {
  1176. service.Notice(rb, client.t("Missing client ID to logout (or \"all\")"))
  1177. return
  1178. }
  1179. target := client
  1180. if len(params) >= 2 {
  1181. // CLIENTS LOGOUT [nickname] [client ID]
  1182. target = server.clients.Get(params[0])
  1183. if target == nil {
  1184. service.Notice(rb, client.t("No such nick"))
  1185. return
  1186. }
  1187. // User must have "kill" privileges to logout other user sessions.
  1188. if target != client {
  1189. oper := client.Oper()
  1190. if !oper.HasRoleCapab("kill") {
  1191. service.Notice(rb, client.t("Insufficient oper privs"))
  1192. return
  1193. }
  1194. }
  1195. params = params[1:]
  1196. }
  1197. var sessionToDestroy *Session // target.destroy(nil) will logout all sessions
  1198. if strings.ToLower(params[0]) != "all" {
  1199. sessionID, err := strconv.ParseInt(params[0], 10, 64)
  1200. if err != nil {
  1201. service.Notice(rb, client.t("Client ID to logout should be an integer (or \"all\")"))
  1202. return
  1203. }
  1204. // Find the client ID that the user requested to logout.
  1205. sessions := target.Sessions()
  1206. for _, session := range sessions {
  1207. if session.sessionID == sessionID {
  1208. sessionToDestroy = session
  1209. }
  1210. }
  1211. if sessionToDestroy == nil {
  1212. service.Notice(rb, client.t("Specified client ID does not exist"))
  1213. return
  1214. }
  1215. }
  1216. target.destroy(sessionToDestroy)
  1217. if (sessionToDestroy != nil && rb.session != sessionToDestroy) || client != target {
  1218. if sessionToDestroy != nil {
  1219. service.Notice(rb, client.t("Successfully logged out session"))
  1220. } else {
  1221. service.Notice(rb, client.t("Successfully logged out all sessions"))
  1222. }
  1223. }
  1224. }
  1225. func nsCertHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1226. verb := strings.ToLower(params[0])
  1227. params = params[1:]
  1228. var target, certfp string
  1229. switch verb {
  1230. case "list":
  1231. if 1 <= len(params) {
  1232. target = params[0]
  1233. }
  1234. case "add", "del":
  1235. if 2 <= len(params) {
  1236. target, certfp = params[0], params[1]
  1237. } else if len(params) == 1 {
  1238. certfp = params[0]
  1239. } else if len(params) == 0 && verb == "add" && rb.session.certfp != "" {
  1240. certfp = rb.session.certfp // #1059
  1241. } else {
  1242. service.Notice(rb, client.t("Invalid parameters"))
  1243. return
  1244. }
  1245. default:
  1246. service.Notice(rb, client.t("Invalid parameters"))
  1247. return
  1248. }
  1249. hasPrivs := client.HasRoleCapabs("accreg")
  1250. if target != "" && !hasPrivs {
  1251. service.Notice(rb, client.t("Insufficient privileges"))
  1252. return
  1253. } else if target == "" {
  1254. target = client.Account()
  1255. if target == "" {
  1256. service.Notice(rb, client.t("You're not logged into an account"))
  1257. return
  1258. }
  1259. }
  1260. var err error
  1261. switch verb {
  1262. case "list":
  1263. accountData, err := server.accounts.LoadAccount(target)
  1264. if err == errAccountDoesNotExist {
  1265. service.Notice(rb, client.t("Account does not exist"))
  1266. return
  1267. } else if err != nil {
  1268. service.Notice(rb, client.t("An error occurred"))
  1269. return
  1270. }
  1271. certfps := accountData.Credentials.Certfps
  1272. service.Notice(rb, fmt.Sprintf(client.t("There are %[1]d certificate fingerprint(s) authorized for account %[2]s."), len(certfps), accountData.Name))
  1273. for i, certfp := range certfps {
  1274. service.Notice(rb, fmt.Sprintf("%d: %s", i+1, certfp))
  1275. }
  1276. return
  1277. case "add":
  1278. err = server.accounts.addRemoveCertfp(target, certfp, true, hasPrivs)
  1279. case "del":
  1280. err = server.accounts.addRemoveCertfp(target, certfp, false, hasPrivs)
  1281. }
  1282. switch err {
  1283. case nil:
  1284. if verb == "add" {
  1285. service.Notice(rb, client.t("Certificate fingerprint successfully added"))
  1286. } else {
  1287. service.Notice(rb, client.t("Certificate fingerprint successfully removed"))
  1288. }
  1289. case errNoop:
  1290. if verb == "add" {
  1291. service.Notice(rb, client.t("That certificate fingerprint was already authorized"))
  1292. } else {
  1293. service.Notice(rb, client.t("Certificate fingerprint not found"))
  1294. }
  1295. case errAccountDoesNotExist:
  1296. service.Notice(rb, client.t("Account does not exist"))
  1297. case errLimitExceeded:
  1298. service.Notice(rb, client.t("You already have too many certificate fingerprints"))
  1299. case utils.ErrInvalidCertfp:
  1300. service.Notice(rb, client.t("Invalid certificate fingerprint"))
  1301. case errCertfpAlreadyExists:
  1302. service.Notice(rb, client.t("That certificate fingerprint is already associated with another account"))
  1303. case errEmptyCredentials:
  1304. service.Notice(rb, client.t("You can't remove all your certificate fingerprints unless you add a password"))
  1305. case errCredsExternallyManaged:
  1306. service.Notice(rb, client.t("Your account credentials are managed externally and cannot be changed here"))
  1307. case errCASFailed:
  1308. service.Notice(rb, client.t("Try again later"))
  1309. default:
  1310. server.logger.Error("internal", "could not modify certificates:", err.Error())
  1311. service.Notice(rb, client.t("An error occurred"))
  1312. }
  1313. }
  1314. func nsSuspendHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1315. subCmd := strings.ToLower(params[0])
  1316. params = params[1:]
  1317. switch subCmd {
  1318. case "add":
  1319. nsSuspendAddHandler(service, server, client, command, params, rb)
  1320. case "del", "delete", "remove":
  1321. nsSuspendRemoveHandler(service, server, client, command, params, rb)
  1322. case "list":
  1323. nsSuspendListHandler(service, server, client, command, params, rb)
  1324. default:
  1325. service.Notice(rb, client.t("Invalid parameters"))
  1326. }
  1327. }
  1328. func nsSuspendAddHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1329. if len(params) == 0 {
  1330. service.Notice(rb, client.t("Invalid parameters"))
  1331. return
  1332. }
  1333. account := params[0]
  1334. params = params[1:]
  1335. var duration time.Duration
  1336. if 2 <= len(params) && strings.ToLower(params[0]) == "duration" {
  1337. var err error
  1338. cDuration, err := custime.ParseDuration(params[1])
  1339. if err != nil {
  1340. service.Notice(rb, client.t("Invalid time duration for NS SUSPEND"))
  1341. return
  1342. }
  1343. duration = time.Duration(cDuration)
  1344. params = params[2:]
  1345. }
  1346. var reason string
  1347. if len(params) != 0 {
  1348. reason = strings.Join(params, " ")
  1349. }
  1350. name := client.Oper().Name
  1351. err := server.accounts.Suspend(account, duration, name, reason)
  1352. switch err {
  1353. case nil:
  1354. service.Notice(rb, fmt.Sprintf(client.t("Successfully suspended account %s"), account))
  1355. case errAccountDoesNotExist:
  1356. service.Notice(rb, client.t("No such account"))
  1357. default:
  1358. service.Notice(rb, client.t("An error occurred"))
  1359. }
  1360. }
  1361. func nsSuspendRemoveHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1362. if len(params) == 0 {
  1363. service.Notice(rb, client.t("Invalid parameters"))
  1364. return
  1365. }
  1366. err := server.accounts.Unsuspend(params[0])
  1367. switch err {
  1368. case nil:
  1369. service.Notice(rb, fmt.Sprintf(client.t("Successfully un-suspended account %s"), params[0]))
  1370. case errAccountDoesNotExist:
  1371. service.Notice(rb, client.t("No such account"))
  1372. case errNoop:
  1373. service.Notice(rb, client.t("Account was not suspended"))
  1374. default:
  1375. service.Notice(rb, client.t("An error occurred"))
  1376. }
  1377. }
  1378. // sort in reverse order of creation time
  1379. type ByCreationTime []AccountSuspension
  1380. func (a ByCreationTime) Len() int { return len(a) }
  1381. func (a ByCreationTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  1382. func (a ByCreationTime) Less(i, j int) bool { return a[i].TimeCreated.After(a[j].TimeCreated) }
  1383. func nsSuspendListHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1384. listAccountSuspensions(client, rb, service.prefix)
  1385. }
  1386. func listAccountSuspensions(client *Client, rb *ResponseBuffer, source string) {
  1387. suspensions := client.server.accounts.ListSuspended()
  1388. sort.Sort(ByCreationTime(suspensions))
  1389. nick := client.Nick()
  1390. rb.Add(nil, source, "NOTICE", nick, fmt.Sprintf(client.t("There are %d active account suspensions."), len(suspensions)))
  1391. for _, suspension := range suspensions {
  1392. rb.Add(nil, source, "NOTICE", nick, suspensionToString(client, suspension))
  1393. }
  1394. }
  1395. func suspensionToString(client *Client, suspension AccountSuspension) (result string) {
  1396. duration := client.t("indefinite")
  1397. if suspension.Duration != time.Duration(0) {
  1398. duration = suspension.Duration.String()
  1399. }
  1400. ts := suspension.TimeCreated.Format(time.RFC1123)
  1401. reason := client.t("No reason given.")
  1402. if suspension.Reason != "" {
  1403. reason = fmt.Sprintf(client.t("Reason: %s"), suspension.Reason)
  1404. }
  1405. return fmt.Sprintf(client.t("Account %[1]s suspended at %[2]s. Duration: %[3]s. %[4]s"), suspension.AccountName, ts, duration, reason)
  1406. }
  1407. func nsSendpassHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1408. if !nsLoginThrottleCheck(service, client, rb) {
  1409. return
  1410. }
  1411. account := params[0]
  1412. var message string
  1413. err := server.accounts.NsSendpass(client, account)
  1414. switch err {
  1415. case nil:
  1416. server.snomasks.Send(sno.LocalAccounts, fmt.Sprintf("Client %s sent a password reset for account %s", client.Nick(), account))
  1417. message = `Successfully sent password reset email`
  1418. case errAccountDoesNotExist, errAccountUnverified, errAccountSuspended:
  1419. message = err.Error()
  1420. case errValidEmailRequired:
  1421. message = `That account is not associated with an email address`
  1422. case errLimitExceeded:
  1423. message = `Try again later`
  1424. default:
  1425. server.logger.Error("services", "error in NS SENDPASS", err.Error())
  1426. message = `An error occurred`
  1427. }
  1428. rb.Notice(client.t(message))
  1429. }
  1430. func nsResetpassHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1431. if !nsLoginThrottleCheck(service, client, rb) {
  1432. return
  1433. }
  1434. var message string
  1435. err := server.accounts.NsResetpass(client, params[0], params[1], params[2])
  1436. switch err {
  1437. case nil:
  1438. message = `Successfully reset account password`
  1439. case errAccountDoesNotExist, errAccountUnverified, errAccountSuspended, errAccountBadPassphrase:
  1440. message = err.Error()
  1441. case errAccountInvalidCredentials:
  1442. message = `Code did not match`
  1443. default:
  1444. server.logger.Error("services", "error in NS RESETPASS", err.Error())
  1445. message = `An error occurred`
  1446. }
  1447. rb.Notice(client.t(message))
  1448. }
  1449. func nsRenameHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1450. oldName, newName := params[0], params[1]
  1451. err := server.accounts.Rename(oldName, newName)
  1452. if err != nil {
  1453. service.Notice(rb, fmt.Sprintf(client.t("Couldn't rename account: %s"), client.t(err.Error())))
  1454. return
  1455. }
  1456. service.Notice(rb, client.t("Successfully renamed account"))
  1457. if server.Config().Accounts.NickReservation.ForceNickEqualsAccount {
  1458. if curClient := server.clients.Get(oldName); curClient != nil {
  1459. renameErr := performNickChange(client.server, client, curClient, nil, newName, rb)
  1460. if renameErr != nil && renameErr != errNoop {
  1461. service.Notice(rb, fmt.Sprintf(client.t("Warning: could not rename affected client: %v"), err))
  1462. }
  1463. }
  1464. }
  1465. }