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

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