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

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