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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. // Copyright (c) 2017 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "fmt"
  6. "github.com/goshuirc/irc-go/ircfmt"
  7. )
  8. // "enabled" callbacks for specific nickserv commands
  9. func servCmdRequiresAccreg(config *Config) bool {
  10. return config.Accounts.Registration.Enabled
  11. }
  12. func servCmdRequiresAuthEnabled(config *Config) bool {
  13. return config.Accounts.AuthenticationEnabled
  14. }
  15. func servCmdRequiresNickRes(config *Config) bool {
  16. return config.Accounts.AuthenticationEnabled && config.Accounts.NickReservation.Enabled
  17. }
  18. func nsEnforceEnabled(config *Config) bool {
  19. return servCmdRequiresNickRes(config) && config.Accounts.NickReservation.AllowCustomEnforcement
  20. }
  21. var (
  22. // ZNC's nickserv module will not detect this unless it is:
  23. // 1. sent with prefix `nickserv`
  24. // 2. contains the string "identify"
  25. // 3. contains at least one of several other magic strings ("msg" works)
  26. nsTimeoutNotice = `This nickname is reserved. Please login within %v (using $b/msg NickServ IDENTIFY <password>$b or SASL)`
  27. )
  28. const nickservHelp = `NickServ lets you register and login to an account.
  29. To see in-depth help for a specific NickServ command, try:
  30. $b/NS HELP <command>$b
  31. Here are the commands you can use:
  32. %s`
  33. var (
  34. nickservCommands = map[string]*serviceCommand{
  35. "drop": {
  36. handler: nsDropHandler,
  37. help: `Syntax: $bDROP [nickname]$b
  38. DROP de-links the given (or your current) nickname from your user account.`,
  39. helpShort: `$bDROP$b de-links your current (or the given) nickname from your user account.`,
  40. enabled: servCmdRequiresNickRes,
  41. authRequired: true,
  42. },
  43. "enforce": {
  44. handler: nsEnforceHandler,
  45. help: `Syntax: $bENFORCE [method]$b
  46. ENFORCE lets you specify a custom enforcement mechanism for your registered
  47. nicknames. Your options are:
  48. 1. 'none' [no enforcement, overriding the server default]
  49. 2. 'timeout' [anyone using the nick must authenticate before a deadline,
  50. or else they will be renamed]
  51. 3. 'strict' [you must already be authenticated to use the nick]
  52. 4. 'default' [use the server default]
  53. With no arguments, queries your current enforcement status.`,
  54. helpShort: `$bENFORCE$b lets you change how your nicknames are reserved.`,
  55. authRequired: true,
  56. enabled: nsEnforceEnabled,
  57. },
  58. "ghost": {
  59. handler: nsGhostHandler,
  60. help: `Syntax: $bGHOST <nickname>$b
  61. GHOST disconnects the given user from the network if they're logged in with the
  62. same user account, letting you reclaim your nickname.`,
  63. helpShort: `$bGHOST$b reclaims your nickname.`,
  64. authRequired: true,
  65. minParams: 1,
  66. },
  67. "group": {
  68. handler: nsGroupHandler,
  69. help: `Syntax: $bGROUP$b
  70. GROUP links your current nickname with your logged-in account, so other people
  71. will not be able to use it.`,
  72. helpShort: `$bGROUP$b links your current nickname to your user account.`,
  73. enabled: servCmdRequiresNickRes,
  74. authRequired: true,
  75. },
  76. "identify": {
  77. handler: nsIdentifyHandler,
  78. help: `Syntax: $bIDENTIFY <username> [password]$b
  79. IDENTIFY lets you login to the given username using either password auth, or
  80. certfp (your client certificate) if a password is not given.`,
  81. helpShort: `$bIDENTIFY$b lets you login to your account.`,
  82. minParams: 1,
  83. },
  84. "info": {
  85. handler: nsInfoHandler,
  86. help: `Syntax: $bINFO [username]$b
  87. INFO gives you information about the given (or your own) user account.`,
  88. helpShort: `$bINFO$b gives you information on a user account.`,
  89. },
  90. "register": {
  91. handler: nsRegisterHandler,
  92. // TODO: "email" is an oversimplification here; it's actually any callback, e.g.,
  93. // person@example.com, mailto:person@example.com, tel:16505551234.
  94. help: `Syntax: $bREGISTER <username> <email> [password]$b
  95. REGISTER lets you register a user account. If the server allows anonymous
  96. registration, you can send an asterisk (*) as the email address.
  97. If the password is left out, your account will be registered to your TLS client
  98. certificate (and you will need to use that certificate to login in future).`,
  99. helpShort: `$bREGISTER$b lets you register a user account.`,
  100. enabled: servCmdRequiresAccreg,
  101. minParams: 2,
  102. },
  103. "sadrop": {
  104. handler: nsDropHandler,
  105. help: `Syntax: $bSADROP <nickname>$b
  106. SADROP forcibly de-links the given nickname from the attached user account.`,
  107. helpShort: `$bSADROP$b forcibly de-links the given nickname from its user account.`,
  108. capabs: []string{"accreg"},
  109. enabled: servCmdRequiresNickRes,
  110. minParams: 1,
  111. },
  112. "saregister": {
  113. handler: nsSaregisterHandler,
  114. help: `Syntax: $bSAREGISTER <username> <password>$b
  115. SAREGISTER registers an account on someone else's behalf.
  116. This is for use in configurations that require SASL for all connections;
  117. an administrator can set use this command to set up user accounts.`,
  118. helpShort: `$bSAREGISTER$b registers an account on someone else's behalf.`,
  119. enabled: servCmdRequiresAuthEnabled,
  120. capabs: []string{"accreg"},
  121. minParams: 2,
  122. },
  123. "unregister": {
  124. handler: nsUnregisterHandler,
  125. help: `Syntax: $bUNREGISTER <username> [code]$b
  126. UNREGISTER lets you delete your user account (or someone else's, if you're an
  127. IRC operator with the correct permissions). To prevent accidental
  128. unregistrations, a verification code is required; invoking the command without
  129. a code will display the necessary code.`,
  130. helpShort: `$bUNREGISTER$b lets you delete your user account.`,
  131. enabled: servCmdRequiresAuthEnabled,
  132. minParams: 1,
  133. },
  134. "verify": {
  135. handler: nsVerifyHandler,
  136. help: `Syntax: $bVERIFY <username> <code>$b
  137. VERIFY lets you complete an account registration, if the server requires email
  138. or other verification.`,
  139. helpShort: `$bVERIFY$b lets you complete account registration.`,
  140. enabled: servCmdRequiresAccreg,
  141. minParams: 2,
  142. },
  143. "passwd": {
  144. handler: nsPasswdHandler,
  145. help: `Syntax: $bPASSWD <current> <new> <new_again>$b
  146. Or: $bPASSWD <username> <new>$b
  147. PASSWD lets you change your account password. You must supply your current
  148. password and confirm the new one by typing it twice. If you're an IRC operator
  149. with the correct permissions, you can use PASSWD to reset someone else's
  150. password by supplying their username and then the desired password.`,
  151. helpShort: `$bPASSWD$b lets you change your password.`,
  152. enabled: servCmdRequiresAuthEnabled,
  153. minParams: 2,
  154. },
  155. }
  156. )
  157. // nsNotice sends the client a notice from NickServ
  158. func nsNotice(rb *ResponseBuffer, text string) {
  159. rb.Add(nil, "NickServ", "NOTICE", rb.target.Nick(), text)
  160. }
  161. func nsDropHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  162. sadrop := command == "sadrop"
  163. var nick string
  164. if len(params) > 0 {
  165. nick = params[0]
  166. } else {
  167. nick = client.NickCasefolded()
  168. }
  169. err := server.accounts.SetNickReserved(client, nick, sadrop, false)
  170. if err == nil {
  171. nsNotice(rb, fmt.Sprintf(client.t("Successfully ungrouped nick %s with your account"), nick))
  172. } else if err == errAccountNotLoggedIn {
  173. nsNotice(rb, client.t("You're not logged into an account"))
  174. } else if err == errAccountCantDropPrimaryNick {
  175. nsNotice(rb, client.t("You can't ungroup your primary nickname (try unregistering your account instead)"))
  176. } else {
  177. nsNotice(rb, client.t("Could not ungroup nick"))
  178. }
  179. }
  180. func nsGhostHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  181. nick := params[0]
  182. ghost := server.clients.Get(nick)
  183. if ghost == nil {
  184. nsNotice(rb, client.t("No such nick"))
  185. return
  186. } else if ghost == client {
  187. nsNotice(rb, client.t("You can't GHOST yourself (try /QUIT instead)"))
  188. return
  189. }
  190. authorized := false
  191. account := client.Account()
  192. if account != "" {
  193. // the user must either own the nick, or the target client
  194. authorized = (server.accounts.NickToAccount(nick) == account) || (ghost.Account() == account)
  195. }
  196. if !authorized {
  197. nsNotice(rb, client.t("You don't own that nick"))
  198. return
  199. }
  200. ghost.Quit(fmt.Sprintf(ghost.t("GHOSTed by %s"), client.Nick()))
  201. ghost.destroy(false)
  202. }
  203. func nsGroupHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  204. nick := client.Nick()
  205. err := server.accounts.SetNickReserved(client, nick, false, true)
  206. if err == nil {
  207. nsNotice(rb, fmt.Sprintf(client.t("Successfully grouped nick %s with your account"), nick))
  208. } else if err == errAccountTooManyNicks {
  209. nsNotice(rb, client.t("You have too many nicks reserved already (you can remove some with /NS DROP)"))
  210. } else if err == errNicknameReserved {
  211. nsNotice(rb, client.t("That nickname is already reserved by someone else"))
  212. } else {
  213. nsNotice(rb, client.t("Error reserving nickname"))
  214. }
  215. }
  216. func nsLoginThrottleCheck(client *Client, rb *ResponseBuffer) (success bool) {
  217. throttled, remainingTime := client.loginThrottle.Touch()
  218. if throttled {
  219. nsNotice(rb, fmt.Sprintf(client.t("Please wait at least %v and try again"), remainingTime))
  220. return false
  221. }
  222. return true
  223. }
  224. func nsIdentifyHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  225. if client.LoggedIntoAccount() {
  226. nsNotice(rb, client.t("You're already logged into an account"))
  227. return
  228. }
  229. loginSuccessful := false
  230. var username, passphrase string
  231. if len(params) == 1 {
  232. if client.certfp != "" {
  233. username = params[0]
  234. } else {
  235. // XXX undocumented compatibility mode with other nickservs, allowing
  236. // /msg NickServ identify passphrase
  237. username = client.NickCasefolded()
  238. passphrase = params[0]
  239. }
  240. } else {
  241. username = params[0]
  242. passphrase = params[1]
  243. }
  244. // try passphrase
  245. if passphrase != "" {
  246. if !nsLoginThrottleCheck(client, rb) {
  247. return
  248. }
  249. err := server.accounts.AuthenticateByPassphrase(client, username, passphrase)
  250. loginSuccessful = (err == nil)
  251. }
  252. // try certfp
  253. if !loginSuccessful && client.certfp != "" {
  254. err := server.accounts.AuthenticateByCertFP(client)
  255. loginSuccessful = (err == nil)
  256. }
  257. if loginSuccessful {
  258. sendSuccessfulSaslAuth(client, rb, true)
  259. } else {
  260. nsNotice(rb, client.t("Could not login with your TLS certificate or supplied username/password"))
  261. }
  262. }
  263. func nsInfoHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  264. var accountName string
  265. if len(params) > 0 {
  266. nick := params[0]
  267. if server.AccountConfig().NickReservation.Enabled {
  268. accountName = server.accounts.NickToAccount(nick)
  269. if accountName == "" {
  270. nsNotice(rb, client.t("That nickname is not registered"))
  271. return
  272. }
  273. } else {
  274. accountName = nick
  275. }
  276. } else {
  277. accountName = client.Account()
  278. if accountName == "" {
  279. nsNotice(rb, client.t("You're not logged into an account"))
  280. return
  281. }
  282. }
  283. account, err := server.accounts.LoadAccount(accountName)
  284. if err != nil || !account.Verified {
  285. nsNotice(rb, client.t("Account does not exist"))
  286. return
  287. }
  288. nsNotice(rb, fmt.Sprintf(client.t("Account: %s"), account.Name))
  289. registeredAt := account.RegisteredAt.Format("Jan 02, 2006 15:04:05Z")
  290. nsNotice(rb, fmt.Sprintf(client.t("Registered at: %s"), registeredAt))
  291. // TODO nicer formatting for this
  292. for _, nick := range account.AdditionalNicks {
  293. nsNotice(rb, fmt.Sprintf(client.t("Additional grouped nick: %s"), nick))
  294. }
  295. for _, channel := range server.accounts.ChannelsForAccount(accountName) {
  296. nsNotice(rb, fmt.Sprintf(client.t("Registered channel: %s"), channel))
  297. }
  298. }
  299. func nsRegisterHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  300. // get params
  301. account, email := params[0], params[1]
  302. var passphrase string
  303. if len(params) > 2 {
  304. passphrase = params[2]
  305. }
  306. certfp := client.certfp
  307. if passphrase == "" && certfp == "" {
  308. nsNotice(rb, client.t("You need to either supply a passphrase or be connected via TLS with a client cert"))
  309. return
  310. }
  311. if client.LoggedIntoAccount() {
  312. nsNotice(rb, client.t("You're already logged into an account"))
  313. return
  314. }
  315. if !nsLoginThrottleCheck(client, rb) {
  316. return
  317. }
  318. // band-aid to let users know if they mix up the order of registration params
  319. if email == "*" {
  320. nsNotice(rb, client.t("Registering your account with no email address"))
  321. } else {
  322. nsNotice(rb, fmt.Sprintf(client.t("Registering your account with email address %s"), email))
  323. }
  324. config := server.AccountConfig()
  325. var callbackNamespace, callbackValue string
  326. noneCallbackAllowed := false
  327. for _, callback := range config.Registration.EnabledCallbacks {
  328. if callback == "*" {
  329. noneCallbackAllowed = true
  330. }
  331. }
  332. // XXX if ACC REGISTER allows registration with the `none` callback, then ignore
  333. // any callback that was passed here (to avoid confusion in the case where the ircd
  334. // has no mail server configured). otherwise, register using the provided callback:
  335. if noneCallbackAllowed {
  336. callbackNamespace = "*"
  337. } else {
  338. callbackNamespace, callbackValue = parseCallback(email, config)
  339. if callbackNamespace == "" {
  340. nsNotice(rb, client.t("Registration requires a valid e-mail address"))
  341. return
  342. }
  343. }
  344. err := server.accounts.Register(client, account, callbackNamespace, callbackValue, passphrase, client.certfp)
  345. if err == nil {
  346. if callbackNamespace == "*" {
  347. err = server.accounts.Verify(client, account, "")
  348. if err == nil {
  349. sendSuccessfulRegResponse(client, rb, true)
  350. }
  351. } else {
  352. messageTemplate := client.t("Account created, pending verification; verification code has been sent to %s")
  353. message := fmt.Sprintf(messageTemplate, fmt.Sprintf("%s:%s", callbackNamespace, callbackValue))
  354. nsNotice(rb, message)
  355. }
  356. }
  357. // details could not be stored and relevant numerics have been dispatched, abort
  358. if err != nil {
  359. errMsg, _ := registrationErrorToMessageAndCode(err)
  360. nsNotice(rb, errMsg)
  361. return
  362. }
  363. }
  364. func nsSaregisterHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  365. account, passphrase := params[0], params[1]
  366. err := server.accounts.Register(nil, account, "admin", "", passphrase, "")
  367. if err == nil {
  368. err = server.accounts.Verify(nil, account, "")
  369. }
  370. if err != nil {
  371. var errMsg string
  372. if err == errAccountAlreadyRegistered || err == errAccountAlreadyVerified {
  373. errMsg = client.t("Account already exists")
  374. } else if err == errAccountBadPassphrase {
  375. errMsg = client.t("Passphrase contains forbidden characters or is otherwise invalid")
  376. } else {
  377. server.logger.Error("services", "unknown error from saregister", err.Error())
  378. errMsg = client.t("Could not register")
  379. }
  380. nsNotice(rb, errMsg)
  381. } else {
  382. nsNotice(rb, fmt.Sprintf(client.t("Successfully registered account %s"), account))
  383. }
  384. }
  385. func nsUnregisterHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  386. username := params[0]
  387. var verificationCode string
  388. if len(params) > 1 {
  389. verificationCode = params[1]
  390. }
  391. if username == "" {
  392. nsNotice(rb, client.t("You must specify an account"))
  393. return
  394. }
  395. account, err := server.accounts.LoadAccount(username)
  396. if err == errAccountDoesNotExist {
  397. nsNotice(rb, client.t("Invalid account name"))
  398. return
  399. } else if err != nil {
  400. nsNotice(rb, client.t("Internal error"))
  401. return
  402. }
  403. cfname, _ := CasefoldName(username)
  404. if !(cfname == client.Account() || client.HasRoleCapabs("accreg")) {
  405. nsNotice(rb, client.t("Insufficient oper privs"))
  406. return
  407. }
  408. expectedCode := unregisterConfirmationCode(account.Name, account.RegisteredAt)
  409. if expectedCode != verificationCode {
  410. nsNotice(rb, ircfmt.Unescape(client.t("$bWarning: unregistering this account will remove its stored privileges.$b")))
  411. nsNotice(rb, fmt.Sprintf(client.t("To confirm account unregistration, type: /NS UNREGISTER %[1]s %[2]s"), cfname, expectedCode))
  412. return
  413. }
  414. err = server.accounts.Unregister(cfname)
  415. if err == errAccountDoesNotExist {
  416. nsNotice(rb, client.t(err.Error()))
  417. } else if err != nil {
  418. nsNotice(rb, client.t("Error while unregistering account"))
  419. } else {
  420. nsNotice(rb, fmt.Sprintf(client.t("Successfully unregistered account %s"), cfname))
  421. server.logger.Info("accounts", "client", client.Nick(), "unregistered account", cfname)
  422. }
  423. }
  424. func nsVerifyHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  425. username, code := params[0], params[1]
  426. err := server.accounts.Verify(client, username, code)
  427. var errorMessage string
  428. if err == errAccountVerificationInvalidCode || err == errAccountAlreadyVerified {
  429. errorMessage = err.Error()
  430. } else if err != nil {
  431. errorMessage = errAccountVerificationFailed.Error()
  432. }
  433. if errorMessage != "" {
  434. nsNotice(rb, client.t(errorMessage))
  435. return
  436. }
  437. sendSuccessfulRegResponse(client, rb, true)
  438. }
  439. func nsPasswdHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  440. var target string
  441. var newPassword string
  442. var errorMessage string
  443. hasPrivs := client.HasRoleCapabs("accreg")
  444. if !hasPrivs && !nsLoginThrottleCheck(client, rb) {
  445. return
  446. }
  447. switch len(params) {
  448. case 2:
  449. if !hasPrivs {
  450. errorMessage = "Insufficient privileges"
  451. } else {
  452. target, newPassword = params[0], params[1]
  453. }
  454. case 3:
  455. target = client.Account()
  456. if target == "" {
  457. errorMessage = "You're not logged into an account"
  458. } else if params[1] != params[2] {
  459. errorMessage = "Passwords do not match"
  460. } else {
  461. // check that they correctly supplied the preexisting password
  462. _, err := server.accounts.checkPassphrase(target, params[0])
  463. if err != nil {
  464. errorMessage = "Password incorrect"
  465. } else {
  466. newPassword = params[1]
  467. }
  468. }
  469. default:
  470. errorMessage = "Invalid parameters"
  471. }
  472. if errorMessage != "" {
  473. nsNotice(rb, client.t(errorMessage))
  474. return
  475. }
  476. err := server.accounts.setPassword(target, newPassword)
  477. if err == nil {
  478. nsNotice(rb, client.t("Password changed"))
  479. } else {
  480. server.logger.Error("internal", "could not upgrade user password:", err.Error())
  481. nsNotice(rb, client.t("Password could not be changed due to server error"))
  482. }
  483. }
  484. func nsEnforceHandler(server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  485. if len(params) == 0 {
  486. status := server.accounts.getStoredEnforcementStatus(client.Account())
  487. nsNotice(rb, fmt.Sprintf(client.t("Your current nickname enforcement is: %s"), status))
  488. } else {
  489. method, err := nickReservationFromString(params[0])
  490. if err != nil {
  491. nsNotice(rb, client.t("Invalid parameters"))
  492. return
  493. }
  494. err = server.accounts.SetEnforcementStatus(client.Account(), method)
  495. if err == nil {
  496. nsNotice(rb, client.t("Enforcement method set"))
  497. } else {
  498. server.logger.Error("internal", "couldn't store NS ENFORCE data", err.Error())
  499. nsNotice(rb, client.t("An error occurred"))
  500. }
  501. }
  502. }