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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601
  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', 'never', and the default
  251. of 'commands-only' (the messages will be replayed in /HISTORY 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 TLS certificate fingerprints that can be used to
  317. log into an account. Specifically, $bCERT LIST$b lists the authorized
  318. 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.`,
  322. helpShort: `$bCERT$b controls a user account's certificate fingerprints`,
  323. enabled: servCmdRequiresAuthEnabled,
  324. minParams: 1,
  325. },
  326. "suspend": {
  327. handler: nsSuspendHandler,
  328. help: `Syntax: $bSUSPEND ADD <nickname> [DURATION duration] [reason]$b
  329. $bSUSPEND DEL <nickname>$b
  330. $bSUSPEND LIST$b
  331. Suspending an account disables it (preventing new logins) and disconnects
  332. all associated clients. You can specify a time limit or a reason for
  333. the suspension. The $bDEL$b subcommand reverses a suspension, and the $bLIST$b
  334. command lists all current suspensions.`,
  335. helpShort: `$bSUSPEND$b manages account suspensions`,
  336. minParams: 1,
  337. capabs: []string{"accreg"},
  338. },
  339. "rename": {
  340. handler: nsRenameHandler,
  341. help: `Syntax: $bRENAME <account> <newname>$b
  342. RENAME allows a server administrator to change the name of an account.
  343. Currently, you can only change the canonical casefolding of an account
  344. (e.g., you can change "Alice" to "alice", but not "Alice" to "Amanda").`,
  345. helpShort: `$bRENAME$b renames an account`,
  346. minParams: 2,
  347. capabs: []string{"accreg"},
  348. },
  349. "verifyemail": {
  350. handler: nsVerifyEmailHandler,
  351. authRequired: true,
  352. minParams: 1,
  353. hidden: true,
  354. },
  355. }
  356. )
  357. func nsGetHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  358. var account string
  359. if command == "saget" {
  360. account = params[0]
  361. params = params[1:]
  362. } else {
  363. account = client.Account()
  364. }
  365. accountData, err := server.accounts.LoadAccount(account)
  366. if err == errAccountDoesNotExist {
  367. service.Notice(rb, client.t("No such account"))
  368. return
  369. } else if err != nil {
  370. service.Notice(rb, client.t("Error loading account data"))
  371. return
  372. }
  373. displaySetting(service, params[0], accountData.Settings, client, rb)
  374. }
  375. func displaySetting(service *ircService, settingName string, settings AccountSettings, client *Client, rb *ResponseBuffer) {
  376. config := client.server.Config()
  377. switch strings.ToLower(settingName) {
  378. case "enforce":
  379. storedValue := settings.NickEnforcement
  380. serializedStoredValue := nickReservationToString(storedValue)
  381. service.Notice(rb, fmt.Sprintf(client.t("Your stored nickname enforcement setting is: %s"), serializedStoredValue))
  382. serializedActualValue := nickReservationToString(configuredEnforcementMethod(config, storedValue))
  383. service.Notice(rb, fmt.Sprintf(client.t("Given current server settings, your nickname is enforced with: %s"), serializedActualValue))
  384. case "autoreplay-lines":
  385. if settings.AutoreplayLines == nil {
  386. service.Notice(rb, fmt.Sprintf(client.t("You will receive the server default of %d lines of autoreplayed history"), config.History.AutoreplayOnJoin))
  387. } else {
  388. service.Notice(rb, fmt.Sprintf(client.t("You will receive %d lines of autoreplayed history"), *settings.AutoreplayLines))
  389. }
  390. case "replay-joins":
  391. switch settings.ReplayJoins {
  392. case ReplayJoinsCommandsOnly:
  393. service.Notice(rb, client.t("You will see JOINs and PARTs in /HISTORY output, but not in autoreplay"))
  394. case ReplayJoinsAlways:
  395. service.Notice(rb, client.t("You will see JOINs and PARTs in /HISTORY output and in autoreplay"))
  396. case ReplayJoinsNever:
  397. service.Notice(rb, client.t("You will not see JOINs and PARTs in /HISTORY output or in autoreplay"))
  398. }
  399. case "multiclient":
  400. if !config.Accounts.Multiclient.Enabled {
  401. service.Notice(rb, client.t("This feature has been disabled by the server administrators"))
  402. } else {
  403. switch settings.AllowBouncer {
  404. case MulticlientAllowedServerDefault:
  405. if config.Accounts.Multiclient.AllowedByDefault {
  406. service.Notice(rb, client.t("Multiclient functionality is currently enabled for your account, but you can opt out"))
  407. } else {
  408. service.Notice(rb, client.t("Multiclient functionality is currently disabled for your account, but you can opt in"))
  409. }
  410. case MulticlientDisallowedByUser:
  411. service.Notice(rb, client.t("Multiclient functionality is currently disabled for your account"))
  412. case MulticlientAllowedByUser:
  413. service.Notice(rb, client.t("Multiclient functionality is currently enabled for your account"))
  414. }
  415. }
  416. case "always-on":
  417. stored := settings.AlwaysOn
  418. actual := persistenceEnabled(config.Accounts.Multiclient.AlwaysOn, stored)
  419. service.Notice(rb, fmt.Sprintf(client.t("Your stored always-on setting is: %s"), userPersistentStatusToString(stored)))
  420. if actual {
  421. service.Notice(rb, client.t("Given current server settings, your client is always-on"))
  422. } else {
  423. service.Notice(rb, client.t("Given current server settings, your client is not always-on"))
  424. }
  425. case "autoreplay-missed":
  426. stored := settings.AutoreplayMissed
  427. if stored {
  428. alwaysOn := persistenceEnabled(config.Accounts.Multiclient.AlwaysOn, settings.AlwaysOn)
  429. if alwaysOn {
  430. service.Notice(rb, client.t("Autoreplay of missed messages is enabled"))
  431. } else {
  432. 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"))
  433. }
  434. } else {
  435. service.Notice(rb, client.t("Your account is not configured to receive autoreplayed missed messages"))
  436. }
  437. case "auto-away":
  438. stored := settings.AutoAway
  439. alwaysOn := persistenceEnabled(config.Accounts.Multiclient.AlwaysOn, settings.AlwaysOn)
  440. actual := persistenceEnabled(config.Accounts.Multiclient.AutoAway, settings.AutoAway)
  441. service.Notice(rb, fmt.Sprintf(client.t("Your stored auto-away setting is: %s"), userPersistentStatusToString(stored)))
  442. if actual && alwaysOn {
  443. service.Notice(rb, client.t("Given current server settings, auto-away is enabled for your client"))
  444. } else if actual && !alwaysOn {
  445. service.Notice(rb, client.t("Because your client is not always-on, auto-away is disabled"))
  446. } else if !actual {
  447. service.Notice(rb, client.t("Given current server settings, auto-away is disabled for your client"))
  448. }
  449. case "dm-history":
  450. effectiveValue := historyEnabled(config.History.Persistent.DirectMessages, settings.DMHistory)
  451. service.Notice(rb, fmt.Sprintf(client.t("Your stored direct message history setting is: %s"), historyStatusToString(settings.DMHistory)))
  452. service.Notice(rb, fmt.Sprintf(client.t("Given current server settings, your direct message history setting is: %s"), historyStatusToString(effectiveValue)))
  453. case "email":
  454. if settings.Email != "" {
  455. service.Notice(rb, fmt.Sprintf(client.t("Your stored e-mail address is: %s"), settings.Email))
  456. } else {
  457. service.Notice(rb, client.t("You have no stored e-mail address"))
  458. }
  459. default:
  460. service.Notice(rb, client.t("No such setting"))
  461. }
  462. }
  463. func userPersistentStatusToString(status PersistentStatus) string {
  464. // #1544: "mandatory" as a user setting should display as "enabled"
  465. result := persistentStatusToString(status)
  466. if result == "mandatory" {
  467. result = "enabled"
  468. }
  469. return result
  470. }
  471. func nsSetHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  472. var privileged bool
  473. var account string
  474. if command == "saset" {
  475. privileged = true
  476. account = params[0]
  477. params = params[1:]
  478. } else {
  479. account = client.Account()
  480. }
  481. key := strings.ToLower(params[0])
  482. // unprivileged NS SET EMAIL is different because it requires a confirmation
  483. if !privileged && key == "email" {
  484. nsSetEmailHandler(service, client, params, rb)
  485. return
  486. }
  487. var munger settingsMunger
  488. var finalSettings AccountSettings
  489. var err error
  490. switch key {
  491. case "pass", "password":
  492. service.Notice(rb, client.t("To change a password, use the PASSWD command. For details, /msg NickServ HELP PASSWD"))
  493. return
  494. case "enforce":
  495. var method NickEnforcementMethod
  496. method, err = nickReservationFromString(params[1])
  497. if err != nil {
  498. err = errInvalidParams
  499. break
  500. }
  501. // updating enforcement settings is special-cased, because it requires
  502. // an update to server.accounts.accountToMethod
  503. finalSettings, err = server.accounts.SetEnforcementStatus(account, method)
  504. if err == nil {
  505. finalSettings.NickEnforcement = method // success
  506. }
  507. case "autoreplay-lines":
  508. var newValue *int
  509. if strings.ToLower(params[1]) != "default" {
  510. val, err_ := strconv.Atoi(params[1])
  511. if err_ != nil || val < 0 {
  512. err = errInvalidParams
  513. break
  514. }
  515. newValue = new(int)
  516. *newValue = val
  517. }
  518. munger = func(in AccountSettings) (out AccountSettings, err error) {
  519. out = in
  520. out.AutoreplayLines = newValue
  521. return
  522. }
  523. case "multiclient":
  524. var newValue MulticlientAllowedSetting
  525. if strings.ToLower(params[1]) == "default" {
  526. newValue = MulticlientAllowedServerDefault
  527. } else {
  528. var enabled bool
  529. enabled, err = utils.StringToBool(params[1])
  530. if enabled {
  531. newValue = MulticlientAllowedByUser
  532. } else {
  533. newValue = MulticlientDisallowedByUser
  534. }
  535. }
  536. if err == nil {
  537. munger = func(in AccountSettings) (out AccountSettings, err error) {
  538. out = in
  539. out.AllowBouncer = newValue
  540. return
  541. }
  542. }
  543. case "replay-joins":
  544. var newValue ReplayJoinsSetting
  545. newValue, err = replayJoinsSettingFromString(params[1])
  546. if err == nil {
  547. munger = func(in AccountSettings) (out AccountSettings, err error) {
  548. out = in
  549. out.ReplayJoins = newValue
  550. return
  551. }
  552. }
  553. case "always-on":
  554. // #821: it's problematic to alter the value of always-on if you're not
  555. // the (actual or potential) always-on client yourself. make an exception
  556. // for `saset` to give operators an escape hatch (any consistency problems
  557. // can probably be fixed by restarting the server):
  558. if command != "saset" {
  559. details := client.Details()
  560. if details.nick != details.accountName {
  561. err = errNickAccountMismatch
  562. }
  563. }
  564. if err == nil {
  565. var newValue PersistentStatus
  566. newValue, err = persistentStatusFromString(params[1])
  567. // "opt-in" and "opt-out" don't make sense as user preferences
  568. if err == nil && newValue != PersistentOptIn && newValue != PersistentOptOut {
  569. munger = func(in AccountSettings) (out AccountSettings, err error) {
  570. out = in
  571. out.AlwaysOn = newValue
  572. return
  573. }
  574. }
  575. }
  576. case "autoreplay-missed":
  577. var newValue bool
  578. newValue, err = utils.StringToBool(params[1])
  579. if err == nil {
  580. munger = func(in AccountSettings) (out AccountSettings, err error) {
  581. out = in
  582. out.AutoreplayMissed = newValue
  583. return
  584. }
  585. }
  586. case "auto-away":
  587. var newValue PersistentStatus
  588. newValue, err = persistentStatusFromString(params[1])
  589. // "opt-in" and "opt-out" don't make sense as user preferences
  590. if err == nil && newValue != PersistentOptIn && newValue != PersistentOptOut {
  591. munger = func(in AccountSettings) (out AccountSettings, err error) {
  592. out = in
  593. out.AutoAway = newValue
  594. return
  595. }
  596. }
  597. case "dm-history":
  598. var newValue HistoryStatus
  599. newValue, err = historyStatusFromString(params[1])
  600. if err == nil {
  601. munger = func(in AccountSettings) (out AccountSettings, err error) {
  602. out = in
  603. out.DMHistory = newValue
  604. return
  605. }
  606. }
  607. case "email":
  608. newValue := params[1]
  609. munger = func(in AccountSettings) (out AccountSettings, err error) {
  610. out = in
  611. out.Email = newValue
  612. return
  613. }
  614. default:
  615. err = errInvalidParams
  616. }
  617. if munger != nil {
  618. finalSettings, err = server.accounts.ModifyAccountSettings(account, munger)
  619. }
  620. switch err {
  621. case nil:
  622. service.Notice(rb, client.t("Successfully changed your account settings"))
  623. displaySetting(service, key, finalSettings, client, rb)
  624. case errInvalidParams, errAccountDoesNotExist, errFeatureDisabled, errAccountUnverified, errAccountUpdateFailed:
  625. service.Notice(rb, client.t(err.Error()))
  626. case errNickAccountMismatch:
  627. 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()))
  628. default:
  629. // unknown error
  630. service.Notice(rb, client.t("An error occurred"))
  631. }
  632. }
  633. // handle unprivileged NS SET EMAIL, which sends a confirmation code
  634. func nsSetEmailHandler(service *ircService, client *Client, params []string, rb *ResponseBuffer) {
  635. config := client.server.Config()
  636. if !config.Accounts.Registration.EmailVerification.Enabled {
  637. rb.Notice(client.t("E-mail verification is disabled"))
  638. return
  639. }
  640. if !nsLoginThrottleCheck(service, client, rb) {
  641. return
  642. }
  643. var password string
  644. if len(params) > 2 {
  645. password = params[2]
  646. }
  647. account := client.Account()
  648. errorMessage := nsConfirmPassword(client.server, account, password)
  649. if errorMessage != "" {
  650. service.Notice(rb, client.t(errorMessage))
  651. return
  652. }
  653. err := client.server.accounts.NsSetEmail(client, params[1])
  654. switch err {
  655. case nil:
  656. service.Notice(rb, client.t("Check your e-mail for instructions on how to confirm your change of address"))
  657. case errLimitExceeded:
  658. service.Notice(rb, client.t("Try again later"))
  659. default:
  660. // if appropriate, show the client the error from the attempted email sending
  661. if rErr := registrationCallbackErrorText(config, client, err); rErr != "" {
  662. service.Notice(rb, rErr)
  663. } else {
  664. service.Notice(rb, client.t("An error occurred"))
  665. }
  666. }
  667. }
  668. func nsVerifyEmailHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  669. err := server.accounts.NsVerifyEmail(client, params[0])
  670. switch err {
  671. case nil:
  672. service.Notice(rb, client.t("Successfully changed your account settings"))
  673. displaySetting(service, "email", client.AccountSettings(), client, rb)
  674. case errAccountVerificationInvalidCode:
  675. service.Notice(rb, client.t(err.Error()))
  676. default:
  677. service.Notice(rb, client.t("An error occurred"))
  678. }
  679. }
  680. func nsDropHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  681. sadrop := command == "sadrop"
  682. var nick string
  683. if len(params) > 0 {
  684. nick = params[0]
  685. } else {
  686. nick = client.NickCasefolded()
  687. }
  688. err := server.accounts.SetNickReserved(client, nick, sadrop, false)
  689. if err == nil {
  690. service.Notice(rb, fmt.Sprintf(client.t("Successfully ungrouped nick %s with your account"), nick))
  691. } else if err == errAccountNotLoggedIn {
  692. service.Notice(rb, client.t("You're not logged into an account"))
  693. } else if err == errAccountCantDropPrimaryNick {
  694. service.Notice(rb, client.t("You can't ungroup your primary nickname (try unregistering your account instead)"))
  695. } else {
  696. service.Notice(rb, client.t("Could not ungroup nick"))
  697. }
  698. }
  699. func nsGhostHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  700. nick := params[0]
  701. ghost := server.clients.Get(nick)
  702. if ghost == nil {
  703. service.Notice(rb, client.t("No such nick"))
  704. return
  705. } else if ghost == client {
  706. service.Notice(rb, client.t("You can't GHOST yourself (try /QUIT instead)"))
  707. return
  708. } else if ghost.AlwaysOn() {
  709. service.Notice(rb, client.t("You can't GHOST an always-on client"))
  710. return
  711. }
  712. authorized := false
  713. account := client.Account()
  714. if account != "" {
  715. // the user must either own the nick, or the target client
  716. authorized = (server.accounts.NickToAccount(nick) == account) || (ghost.Account() == account)
  717. }
  718. if !authorized {
  719. service.Notice(rb, client.t("You don't own that nick"))
  720. return
  721. }
  722. ghost.Quit(fmt.Sprintf(ghost.t("GHOSTed by %s"), client.Nick()), nil)
  723. ghost.destroy(nil)
  724. }
  725. func nsGroupHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  726. nick := client.Nick()
  727. err := server.accounts.SetNickReserved(client, nick, false, true)
  728. if err == nil {
  729. service.Notice(rb, fmt.Sprintf(client.t("Successfully grouped nick %s with your account"), nick))
  730. } else if err == errAccountTooManyNicks {
  731. service.Notice(rb, client.t("You have too many nicks reserved already (you can remove some with /NS DROP)"))
  732. } else if err == errNicknameReserved {
  733. service.Notice(rb, client.t("That nickname is already reserved by someone else"))
  734. } else {
  735. service.Notice(rb, client.t("Error reserving nickname"))
  736. }
  737. }
  738. func nsLoginThrottleCheck(service *ircService, client *Client, rb *ResponseBuffer) (success bool) {
  739. throttled, remainingTime := client.checkLoginThrottle()
  740. if throttled {
  741. service.Notice(rb, fmt.Sprintf(client.t("Please wait at least %v and try again"), remainingTime))
  742. }
  743. return !throttled
  744. }
  745. func nsIdentifyHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  746. if client.LoggedIntoAccount() {
  747. service.Notice(rb, client.t("You're already logged into an account"))
  748. return
  749. }
  750. var err error
  751. loginSuccessful := false
  752. var username, passphrase string
  753. if len(params) == 1 {
  754. if rb.session.certfp != "" {
  755. username = params[0]
  756. } else {
  757. // XXX undocumented compatibility mode with other nickservs, allowing
  758. // /msg NickServ identify passphrase
  759. username = client.NickCasefolded()
  760. passphrase = params[0]
  761. }
  762. } else {
  763. username = params[0]
  764. passphrase = params[1]
  765. }
  766. // try passphrase
  767. if passphrase != "" {
  768. err = server.accounts.AuthenticateByPassphrase(client, username, passphrase)
  769. loginSuccessful = (err == nil)
  770. }
  771. // try certfp
  772. if !loginSuccessful && rb.session.certfp != "" {
  773. err = server.accounts.AuthenticateByCertificate(client, rb.session.certfp, rb.session.peerCerts, "")
  774. loginSuccessful = (err == nil)
  775. }
  776. nickFixupFailed := false
  777. if loginSuccessful {
  778. if !fixupNickEqualsAccount(client, rb, server.Config(), service.prefix) {
  779. loginSuccessful = false
  780. // fixupNickEqualsAccount sends its own error message, don't send another
  781. nickFixupFailed = true
  782. }
  783. }
  784. if loginSuccessful {
  785. sendSuccessfulAccountAuth(service, client, rb, true)
  786. } else if !nickFixupFailed {
  787. service.Notice(rb, fmt.Sprintf(client.t("Authentication failed: %s"), authErrorToMessage(server, err)))
  788. }
  789. }
  790. func nsListHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  791. if !client.HasRoleCapabs("accreg") {
  792. service.Notice(rb, client.t("Insufficient privileges"))
  793. return
  794. }
  795. var searchRegex *regexp.Regexp
  796. if len(params) > 0 {
  797. var err error
  798. searchRegex, err = regexp.Compile(params[0])
  799. if err != nil {
  800. service.Notice(rb, client.t("Invalid regex"))
  801. return
  802. }
  803. }
  804. service.Notice(rb, ircfmt.Unescape(client.t("*** $bNickServ LIST$b ***")))
  805. nicks := server.accounts.AllNicks()
  806. for _, nick := range nicks {
  807. if searchRegex == nil || searchRegex.MatchString(nick) {
  808. service.Notice(rb, fmt.Sprintf(" %s", nick))
  809. }
  810. }
  811. service.Notice(rb, ircfmt.Unescape(client.t("*** $bEnd of NickServ LIST$b ***")))
  812. }
  813. func nsInfoHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  814. if !server.Config().Accounts.AuthenticationEnabled && !client.HasRoleCapabs("accreg") {
  815. service.Notice(rb, client.t("This command has been disabled by the server administrators"))
  816. return
  817. }
  818. var accountName string
  819. if len(params) > 0 {
  820. nick := params[0]
  821. if server.Config().Accounts.NickReservation.Enabled {
  822. accountName = server.accounts.NickToAccount(nick)
  823. if accountName == "" {
  824. service.Notice(rb, client.t("That nickname is not registered"))
  825. return
  826. }
  827. } else {
  828. accountName = nick
  829. }
  830. } else {
  831. accountName = client.Account()
  832. if accountName == "" {
  833. service.Notice(rb, client.t("You're not logged into an account"))
  834. return
  835. }
  836. }
  837. account, err := server.accounts.LoadAccount(accountName)
  838. if err != nil || !account.Verified {
  839. service.Notice(rb, client.t("Account does not exist"))
  840. return
  841. }
  842. service.Notice(rb, fmt.Sprintf(client.t("Account: %s"), account.Name))
  843. registeredAt := account.RegisteredAt.Format(time.RFC1123)
  844. service.Notice(rb, fmt.Sprintf(client.t("Registered at: %s"), registeredAt))
  845. if account.Name == client.AccountName() || client.HasRoleCapabs("accreg") {
  846. if account.Settings.Email != "" {
  847. service.Notice(rb, fmt.Sprintf(client.t("Email address: %s"), account.Settings.Email))
  848. }
  849. }
  850. // TODO nicer formatting for this
  851. for _, nick := range account.AdditionalNicks {
  852. service.Notice(rb, fmt.Sprintf(client.t("Additional grouped nick: %s"), nick))
  853. }
  854. listRegisteredChannels(service, accountName, rb)
  855. if account.Suspended != nil {
  856. service.Notice(rb, suspensionToString(client, *account.Suspended))
  857. }
  858. }
  859. func listRegisteredChannels(service *ircService, accountName string, rb *ResponseBuffer) {
  860. client := rb.session.client
  861. channels := client.server.accounts.ChannelsForAccount(accountName)
  862. service.Notice(rb, fmt.Sprintf(client.t("Account %s has %d registered channel(s)."), accountName, len(channels)))
  863. for _, channel := range rb.session.client.server.accounts.ChannelsForAccount(accountName) {
  864. service.Notice(rb, fmt.Sprintf(client.t("Registered channel: %s"), channel))
  865. }
  866. }
  867. func nsRegisterHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  868. details := client.Details()
  869. passphrase := params[0]
  870. var email string
  871. if 1 < len(params) {
  872. email = params[1]
  873. }
  874. certfp := rb.session.certfp
  875. if passphrase == "*" {
  876. if certfp == "" {
  877. service.Notice(rb, client.t("You must be connected with TLS and a client certificate to do this"))
  878. return
  879. } else {
  880. passphrase = ""
  881. }
  882. }
  883. if passphrase != "" {
  884. cfPassphrase, err := Casefold(passphrase)
  885. if err == nil && cfPassphrase == details.nickCasefolded {
  886. service.Notice(rb, client.t("Usage: REGISTER <passphrase> [email]")) // #1179
  887. return
  888. }
  889. }
  890. if !nsLoginThrottleCheck(service, client, rb) {
  891. return
  892. }
  893. config := server.Config()
  894. account := details.nick
  895. if config.Accounts.NickReservation.ForceGuestFormat {
  896. matches := config.Accounts.NickReservation.guestRegexp.FindStringSubmatch(account)
  897. if matches == nil || len(matches) < 2 {
  898. service.Notice(rb, client.t("Erroneous nickname"))
  899. return
  900. }
  901. account = matches[1]
  902. }
  903. callbackNamespace, callbackValue, validationErr := parseCallback(email, config)
  904. if validationErr != nil {
  905. service.Notice(rb, client.t("Registration requires a valid e-mail address"))
  906. return
  907. }
  908. err := server.accounts.Register(client, account, callbackNamespace, callbackValue, passphrase, rb.session.certfp)
  909. if err == nil {
  910. if callbackNamespace == "*" {
  911. err = server.accounts.Verify(client, account, "")
  912. if err == nil && fixupNickEqualsAccount(client, rb, config, service.prefix) {
  913. sendSuccessfulRegResponse(service, client, rb)
  914. }
  915. } else {
  916. messageTemplate := client.t("Account created, pending verification; verification code has been sent to %s")
  917. message := fmt.Sprintf(messageTemplate, callbackValue)
  918. service.Notice(rb, message)
  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 && passwd.CompareHashAndPassword(hash, []byte(passphrase)) != nil {
  1033. errorMessage = `Password incorrect`
  1034. }
  1035. }
  1036. return
  1037. }
  1038. func nsPasswdHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1039. var target string
  1040. var newPassword string
  1041. var errorMessage string
  1042. var oper *Oper
  1043. switch len(params) {
  1044. case 2:
  1045. oper = client.Oper()
  1046. if !oper.HasRoleCapab("accreg") {
  1047. errorMessage = `Insufficient privileges`
  1048. } else {
  1049. target, newPassword = params[0], params[1]
  1050. if newPassword == "*" {
  1051. newPassword = ""
  1052. }
  1053. message := fmt.Sprintf("Operator %s ran NS PASSWD for account %s", oper.Name, target)
  1054. server.snomasks.Send(sno.LocalOpers, message)
  1055. server.logger.Info("opers", message)
  1056. }
  1057. case 3:
  1058. target = client.Account()
  1059. newPassword = params[1]
  1060. if newPassword == "*" {
  1061. newPassword = ""
  1062. }
  1063. if target == "" {
  1064. errorMessage = `You're not logged into an account`
  1065. } else if newPassword != params[2] {
  1066. errorMessage = `Passwords do not match`
  1067. } else {
  1068. if !nsLoginThrottleCheck(service, client, rb) {
  1069. return
  1070. }
  1071. errorMessage = nsConfirmPassword(server, target, params[0])
  1072. }
  1073. default:
  1074. errorMessage = `Invalid parameters`
  1075. }
  1076. if errorMessage != "" {
  1077. service.Notice(rb, client.t(errorMessage))
  1078. return
  1079. }
  1080. err := server.accounts.setPassword(target, newPassword, oper != nil)
  1081. switch err {
  1082. case nil:
  1083. service.Notice(rb, client.t("Password changed"))
  1084. case errEmptyCredentials:
  1085. service.Notice(rb, client.t("You can't delete your password unless you add a certificate fingerprint"))
  1086. case errCredsExternallyManaged:
  1087. service.Notice(rb, client.t("Your account credentials are managed externally and cannot be changed here"))
  1088. case errCASFailed:
  1089. service.Notice(rb, client.t("Try again later"))
  1090. case errAccountDoesNotExist:
  1091. service.Notice(rb, client.t("Account does not exist"))
  1092. default:
  1093. server.logger.Error("internal", "could not upgrade user password:", err.Error())
  1094. service.Notice(rb, client.t("Password could not be changed due to server error"))
  1095. }
  1096. }
  1097. func nsEnforceHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1098. newParams := []string{"enforce"}
  1099. if len(params) == 0 {
  1100. nsGetHandler(service, server, client, "get", newParams, rb)
  1101. } else {
  1102. newParams = append(newParams, params[0])
  1103. nsSetHandler(service, server, client, "set", newParams, rb)
  1104. }
  1105. }
  1106. func nsClientsHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1107. var verb string
  1108. if command == "sessions" {
  1109. // Legacy "SESSIONS" command is an alias for CLIENTS LIST.
  1110. verb = "list"
  1111. } else if len(params) > 0 {
  1112. verb = strings.ToLower(params[0])
  1113. params = params[1:]
  1114. }
  1115. switch verb {
  1116. case "list":
  1117. nsClientsListHandler(service, server, client, params, rb)
  1118. case "logout":
  1119. nsClientsLogoutHandler(service, server, client, params, rb)
  1120. default:
  1121. service.Notice(rb, client.t("Invalid parameters"))
  1122. }
  1123. }
  1124. func nsClientsListHandler(service *ircService, server *Server, client *Client, params []string, rb *ResponseBuffer) {
  1125. target := client
  1126. hasPrivs := client.HasRoleCapabs("ban")
  1127. if 0 < len(params) {
  1128. target = server.clients.Get(params[0])
  1129. if target == nil {
  1130. service.Notice(rb, client.t("No such nick"))
  1131. return
  1132. }
  1133. if target != client && !hasPrivs {
  1134. service.Notice(rb, client.t("Command restricted"))
  1135. return
  1136. }
  1137. }
  1138. sessionData, currentIndex := target.AllSessionData(rb.session, hasPrivs)
  1139. service.Notice(rb, fmt.Sprintf(client.t("Nickname %[1]s has %[2]d attached clients(s)"), target.Nick(), len(sessionData)))
  1140. for i, session := range sessionData {
  1141. if currentIndex == i {
  1142. service.Notice(rb, fmt.Sprintf(client.t("Client %d (currently attached client):"), session.sessionID))
  1143. } else {
  1144. service.Notice(rb, fmt.Sprintf(client.t("Client %d:"), session.sessionID))
  1145. }
  1146. if session.deviceID != "" {
  1147. service.Notice(rb, fmt.Sprintf(client.t("Device ID: %s"), session.deviceID))
  1148. }
  1149. service.Notice(rb, fmt.Sprintf(client.t("IP address: %s"), session.ip.String()))
  1150. service.Notice(rb, fmt.Sprintf(client.t("Hostname: %s"), session.hostname))
  1151. if hasPrivs {
  1152. service.Notice(rb, fmt.Sprintf(client.t("Connection: %s"), session.connInfo))
  1153. }
  1154. service.Notice(rb, fmt.Sprintf(client.t("Created at: %s"), session.ctime.Format(time.RFC1123)))
  1155. service.Notice(rb, fmt.Sprintf(client.t("Last active: %s"), session.atime.Format(time.RFC1123)))
  1156. if session.certfp != "" {
  1157. service.Notice(rb, fmt.Sprintf(client.t("Certfp: %s"), session.certfp))
  1158. }
  1159. for _, capStr := range session.caps {
  1160. if capStr != "" {
  1161. service.Notice(rb, fmt.Sprintf(client.t("IRCv3 CAPs: %s"), capStr))
  1162. }
  1163. }
  1164. }
  1165. }
  1166. func nsClientsLogoutHandler(service *ircService, server *Server, client *Client, params []string, rb *ResponseBuffer) {
  1167. if len(params) < 1 {
  1168. service.Notice(rb, client.t("Missing client ID to logout (or \"all\")"))
  1169. return
  1170. }
  1171. target := client
  1172. if len(params) >= 2 {
  1173. // CLIENTS LOGOUT [nickname] [client ID]
  1174. target = server.clients.Get(params[0])
  1175. if target == nil {
  1176. service.Notice(rb, client.t("No such nick"))
  1177. return
  1178. }
  1179. // User must have "kill" privileges to logout other user sessions.
  1180. if target != client {
  1181. oper := client.Oper()
  1182. if !oper.HasRoleCapab("kill") {
  1183. service.Notice(rb, client.t("Insufficient oper privs"))
  1184. return
  1185. }
  1186. }
  1187. params = params[1:]
  1188. }
  1189. var sessionToDestroy *Session // target.destroy(nil) will logout all sessions
  1190. if strings.ToLower(params[0]) != "all" {
  1191. sessionID, err := strconv.ParseInt(params[0], 10, 64)
  1192. if err != nil {
  1193. service.Notice(rb, client.t("Client ID to logout should be an integer (or \"all\")"))
  1194. return
  1195. }
  1196. // Find the client ID that the user requested to logout.
  1197. sessions := target.Sessions()
  1198. for _, session := range sessions {
  1199. if session.sessionID == sessionID {
  1200. sessionToDestroy = session
  1201. }
  1202. }
  1203. if sessionToDestroy == nil {
  1204. service.Notice(rb, client.t("Specified client ID does not exist"))
  1205. return
  1206. }
  1207. }
  1208. target.destroy(sessionToDestroy)
  1209. if (sessionToDestroy != nil && rb.session != sessionToDestroy) || client != target {
  1210. if sessionToDestroy != nil {
  1211. service.Notice(rb, client.t("Successfully logged out session"))
  1212. } else {
  1213. service.Notice(rb, client.t("Successfully logged out all sessions"))
  1214. }
  1215. }
  1216. }
  1217. func nsCertHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1218. verb := strings.ToLower(params[0])
  1219. params = params[1:]
  1220. var target, certfp string
  1221. switch verb {
  1222. case "list":
  1223. if 1 <= len(params) {
  1224. target = params[0]
  1225. }
  1226. case "add", "del":
  1227. if 2 <= len(params) {
  1228. target, certfp = params[0], params[1]
  1229. } else if len(params) == 1 {
  1230. certfp = params[0]
  1231. } else if len(params) == 0 && verb == "add" && rb.session.certfp != "" {
  1232. certfp = rb.session.certfp // #1059
  1233. } else {
  1234. service.Notice(rb, client.t("Invalid parameters"))
  1235. return
  1236. }
  1237. default:
  1238. service.Notice(rb, client.t("Invalid parameters"))
  1239. return
  1240. }
  1241. hasPrivs := client.HasRoleCapabs("accreg")
  1242. if target != "" && !hasPrivs {
  1243. service.Notice(rb, client.t("Insufficient privileges"))
  1244. return
  1245. } else if target == "" {
  1246. target = client.Account()
  1247. if target == "" {
  1248. service.Notice(rb, client.t("You're not logged into an account"))
  1249. return
  1250. }
  1251. }
  1252. var err error
  1253. switch verb {
  1254. case "list":
  1255. accountData, err := server.accounts.LoadAccount(target)
  1256. if err == errAccountDoesNotExist {
  1257. service.Notice(rb, client.t("Account does not exist"))
  1258. return
  1259. } else if err != nil {
  1260. service.Notice(rb, client.t("An error occurred"))
  1261. return
  1262. }
  1263. certfps := accountData.Credentials.Certfps
  1264. service.Notice(rb, fmt.Sprintf(client.t("There are %[1]d certificate fingerprint(s) authorized for account %[2]s."), len(certfps), accountData.Name))
  1265. for i, certfp := range certfps {
  1266. service.Notice(rb, fmt.Sprintf("%d: %s", i+1, certfp))
  1267. }
  1268. return
  1269. case "add":
  1270. err = server.accounts.addRemoveCertfp(target, certfp, true, hasPrivs)
  1271. case "del":
  1272. err = server.accounts.addRemoveCertfp(target, certfp, false, hasPrivs)
  1273. }
  1274. switch err {
  1275. case nil:
  1276. if verb == "add" {
  1277. service.Notice(rb, client.t("Certificate fingerprint successfully added"))
  1278. } else {
  1279. service.Notice(rb, client.t("Certificate fingerprint successfully removed"))
  1280. }
  1281. case errNoop:
  1282. if verb == "add" {
  1283. service.Notice(rb, client.t("That certificate fingerprint was already authorized"))
  1284. } else {
  1285. service.Notice(rb, client.t("Certificate fingerprint not found"))
  1286. }
  1287. case errAccountDoesNotExist:
  1288. service.Notice(rb, client.t("Account does not exist"))
  1289. case errLimitExceeded:
  1290. service.Notice(rb, client.t("You already have too many certificate fingerprints"))
  1291. case utils.ErrInvalidCertfp:
  1292. service.Notice(rb, client.t("Invalid certificate fingerprint"))
  1293. case errCertfpAlreadyExists:
  1294. service.Notice(rb, client.t("That certificate fingerprint is already associated with another account"))
  1295. case errEmptyCredentials:
  1296. service.Notice(rb, client.t("You can't remove all your certificate fingerprints unless you add a password"))
  1297. case errCredsExternallyManaged:
  1298. service.Notice(rb, client.t("Your account credentials are managed externally and cannot be changed here"))
  1299. case errCASFailed:
  1300. service.Notice(rb, client.t("Try again later"))
  1301. default:
  1302. server.logger.Error("internal", "could not modify certificates:", err.Error())
  1303. service.Notice(rb, client.t("An error occurred"))
  1304. }
  1305. }
  1306. func nsSuspendHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1307. subCmd := strings.ToLower(params[0])
  1308. params = params[1:]
  1309. switch subCmd {
  1310. case "add":
  1311. nsSuspendAddHandler(service, server, client, command, params, rb)
  1312. case "del", "delete", "remove":
  1313. nsSuspendRemoveHandler(service, server, client, command, params, rb)
  1314. case "list":
  1315. nsSuspendListHandler(service, server, client, command, params, rb)
  1316. default:
  1317. service.Notice(rb, client.t("Invalid parameters"))
  1318. }
  1319. }
  1320. func nsSuspendAddHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1321. if len(params) == 0 {
  1322. service.Notice(rb, client.t("Invalid parameters"))
  1323. return
  1324. }
  1325. account := params[0]
  1326. params = params[1:]
  1327. var duration time.Duration
  1328. if 2 <= len(params) && strings.ToLower(params[0]) == "duration" {
  1329. var err error
  1330. cDuration, err := custime.ParseDuration(params[1])
  1331. if err != nil {
  1332. service.Notice(rb, client.t("Invalid time duration for NS SUSPEND"))
  1333. return
  1334. }
  1335. duration = time.Duration(cDuration)
  1336. params = params[2:]
  1337. }
  1338. var reason string
  1339. if len(params) != 0 {
  1340. reason = strings.Join(params, " ")
  1341. }
  1342. name := client.Oper().Name
  1343. err := server.accounts.Suspend(account, duration, name, reason)
  1344. switch err {
  1345. case nil:
  1346. service.Notice(rb, fmt.Sprintf(client.t("Successfully suspended account %s"), account))
  1347. case errAccountDoesNotExist:
  1348. service.Notice(rb, client.t("No such account"))
  1349. default:
  1350. service.Notice(rb, client.t("An error occurred"))
  1351. }
  1352. }
  1353. func nsSuspendRemoveHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1354. if len(params) == 0 {
  1355. service.Notice(rb, client.t("Invalid parameters"))
  1356. return
  1357. }
  1358. err := server.accounts.Unsuspend(params[0])
  1359. switch err {
  1360. case nil:
  1361. service.Notice(rb, fmt.Sprintf(client.t("Successfully un-suspended account %s"), params[0]))
  1362. case errAccountDoesNotExist:
  1363. service.Notice(rb, client.t("No such account"))
  1364. case errNoop:
  1365. service.Notice(rb, client.t("Account was not suspended"))
  1366. default:
  1367. service.Notice(rb, client.t("An error occurred"))
  1368. }
  1369. }
  1370. // sort in reverse order of creation time
  1371. type ByCreationTime []AccountSuspension
  1372. func (a ByCreationTime) Len() int { return len(a) }
  1373. func (a ByCreationTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  1374. func (a ByCreationTime) Less(i, j int) bool { return a[i].TimeCreated.After(a[j].TimeCreated) }
  1375. func nsSuspendListHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1376. listAccountSuspensions(client, rb, service.prefix)
  1377. }
  1378. func listAccountSuspensions(client *Client, rb *ResponseBuffer, source string) {
  1379. suspensions := client.server.accounts.ListSuspended()
  1380. sort.Sort(ByCreationTime(suspensions))
  1381. nick := client.Nick()
  1382. rb.Add(nil, source, "NOTICE", nick, fmt.Sprintf(client.t("There are %d active account suspensions."), len(suspensions)))
  1383. for _, suspension := range suspensions {
  1384. rb.Add(nil, source, "NOTICE", nick, suspensionToString(client, suspension))
  1385. }
  1386. }
  1387. func suspensionToString(client *Client, suspension AccountSuspension) (result string) {
  1388. duration := client.t("indefinite")
  1389. if suspension.Duration != time.Duration(0) {
  1390. duration = suspension.Duration.String()
  1391. }
  1392. ts := suspension.TimeCreated.Format(time.RFC1123)
  1393. reason := client.t("No reason given.")
  1394. if suspension.Reason != "" {
  1395. reason = fmt.Sprintf(client.t("Reason: %s"), suspension.Reason)
  1396. }
  1397. return fmt.Sprintf(client.t("Account %[1]s suspended at %[2]s. Duration: %[3]s. %[4]s"), suspension.AccountName, ts, duration, reason)
  1398. }
  1399. func nsSendpassHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1400. if !nsLoginThrottleCheck(service, client, rb) {
  1401. return
  1402. }
  1403. account := params[0]
  1404. var message string
  1405. err := server.accounts.NsSendpass(client, account)
  1406. switch err {
  1407. case nil:
  1408. server.snomasks.Send(sno.LocalAccounts, fmt.Sprintf("Client %s sent a password reset for account %s", client.Nick(), account))
  1409. message = `Successfully sent password reset email`
  1410. case errAccountDoesNotExist, errAccountUnverified, errAccountSuspended:
  1411. message = err.Error()
  1412. case errValidEmailRequired:
  1413. message = `That account is not associated with an email address`
  1414. case errLimitExceeded:
  1415. message = `Try again later`
  1416. default:
  1417. server.logger.Error("services", "error in NS SENDPASS", err.Error())
  1418. message = `An error occurred`
  1419. }
  1420. rb.Notice(client.t(message))
  1421. }
  1422. func nsResetpassHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1423. if !nsLoginThrottleCheck(service, client, rb) {
  1424. return
  1425. }
  1426. var message string
  1427. err := server.accounts.NsResetpass(client, params[0], params[1], params[2])
  1428. switch err {
  1429. case nil:
  1430. message = `Successfully reset account password`
  1431. case errAccountDoesNotExist, errAccountUnverified, errAccountSuspended, errAccountBadPassphrase:
  1432. message = err.Error()
  1433. case errAccountInvalidCredentials:
  1434. message = `Code did not match`
  1435. default:
  1436. server.logger.Error("services", "error in NS RESETPASS", err.Error())
  1437. message = `An error occurred`
  1438. }
  1439. rb.Notice(client.t(message))
  1440. }
  1441. func nsRenameHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1442. oldName, newName := params[0], params[1]
  1443. err := server.accounts.Rename(oldName, newName)
  1444. if err != nil {
  1445. service.Notice(rb, fmt.Sprintf(client.t("Couldn't rename account: %s"), client.t(err.Error())))
  1446. return
  1447. }
  1448. service.Notice(rb, client.t("Successfully renamed account"))
  1449. if server.Config().Accounts.NickReservation.ForceNickEqualsAccount {
  1450. if curClient := server.clients.Get(oldName); curClient != nil {
  1451. renameErr := performNickChange(client.server, client, curClient, nil, newName, rb)
  1452. if renameErr != nil && renameErr != errNoop {
  1453. service.Notice(rb, fmt.Sprintf(client.t("Warning: could not rename affected client: %v"), err))
  1454. }
  1455. }
  1456. }
  1457. }