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

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