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.

strings.go 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2014-2015 Edmund Huber
  3. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  4. // released under the MIT license
  5. package irc
  6. import (
  7. "fmt"
  8. "regexp"
  9. "strings"
  10. "github.com/ergochat/confusables"
  11. "golang.org/x/text/cases"
  12. "golang.org/x/text/secure/precis"
  13. "golang.org/x/text/unicode/norm"
  14. "golang.org/x/text/width"
  15. "github.com/ergochat/ergo/irc/utils"
  16. )
  17. const (
  18. precisUTF8MappingToken = "rfc8265"
  19. // space can't be used
  20. // , is used as a separator
  21. // * is used in mask matching
  22. // ? is used in mask matching
  23. // . denotes a server name
  24. // ! separates nickname from username
  25. // @ separates username from hostname
  26. // : means trailing
  27. protocolBreakingNameCharacters = " ,*?.!@:"
  28. // #1436: we discovered that these characters are problematic,
  29. // so we're disallowing them in new nicks/account names, but allowing
  30. // previously registered names
  31. disfavoredNameCharacters = `<>'";#`
  32. )
  33. var (
  34. // reviving the old ergonomadic nickname regex:
  35. // in permissive mode, allow arbitrary letters, numbers, punctuation, and symbols
  36. permissiveCharsRegex = regexp.MustCompile(`^[\pL\pN\pP\pS]*$`)
  37. )
  38. type Casemapping uint
  39. const (
  40. // "precis" is the default / zero value:
  41. // casefolding/validation: PRECIS + ircd restrictions (like no *)
  42. // confusables detection: standard skeleton algorithm
  43. CasemappingPRECIS Casemapping = iota
  44. // "ascii" is the traditional ircd behavior:
  45. // casefolding/validation: must be pure ASCII and follow ircd restrictions, ASCII lowercasing
  46. // confusables detection: none
  47. CasemappingASCII
  48. // "permissive" is an insecure mode:
  49. // casefolding/validation: arbitrary unicodes that follow ircd restrictions, unicode casefolding
  50. // confusables detection: standard skeleton algorithm (which may be ineffective
  51. // over the larger set of permitted identifiers)
  52. CasemappingPermissive
  53. )
  54. // XXX this is a global variable without explicit synchronization.
  55. // it gets set during the initial Server.applyConfig and cannot be changed by rehash:
  56. // this happens-before all IRC connections and all casefolding operations.
  57. var globalCasemappingSetting Casemapping = CasemappingPRECIS
  58. // XXX analogous unsynchronized global variable controlling utf8 validation
  59. // if this is off, you get the traditional IRC behavior (relaying any valid RFC1459
  60. // octets) and invalid utf8 messages are silently dropped for websocket clients only.
  61. // if this is on, invalid utf8 inputs get a FAIL reply.
  62. var globalUtf8EnforcementSetting bool
  63. // Each pass of PRECIS casefolding is a composition of idempotent operations,
  64. // but not idempotent itself. Therefore, the spec says "do it four times and hope
  65. // it converges" (lolwtf). Golang's PRECIS implementation has a "repeat" option,
  66. // which provides this functionality, but unfortunately it's not exposed publicly.
  67. func iterateFolding(profile *precis.Profile, oldStr string) (str string, err error) {
  68. str = oldStr
  69. // follow the stabilizing rules laid out here:
  70. // https://tools.ietf.org/html/draft-ietf-precis-7564bis-10.html#section-7
  71. for i := 0; i < 4; i++ {
  72. str, err = profile.CompareKey(str)
  73. if err != nil {
  74. return "", err
  75. }
  76. if oldStr == str {
  77. break
  78. }
  79. oldStr = str
  80. }
  81. if oldStr != str {
  82. return "", errCouldNotStabilize
  83. }
  84. return str, nil
  85. }
  86. // Casefold returns a casefolded string, without doing any name or channel character checks.
  87. func Casefold(str string) (string, error) {
  88. return casefoldWithSetting(str, globalCasemappingSetting)
  89. }
  90. func casefoldWithSetting(str string, setting Casemapping) (string, error) {
  91. switch setting {
  92. default:
  93. return iterateFolding(precis.UsernameCaseMapped, str)
  94. case CasemappingASCII:
  95. return foldASCII(str)
  96. case CasemappingPermissive:
  97. return foldPermissive(str)
  98. }
  99. }
  100. // CasefoldChannel returns a casefolded version of a channel name.
  101. func CasefoldChannel(name string) (string, error) {
  102. if len(name) == 0 {
  103. return "", errStringIsEmpty
  104. }
  105. // don't casefold the preceding #'s
  106. var start int
  107. for start = 0; start < len(name) && name[start] == '#'; start += 1 {
  108. }
  109. if start == 0 {
  110. // no preceding #'s
  111. return "", errInvalidCharacter
  112. }
  113. lowered, err := Casefold(name[start:])
  114. if err != nil {
  115. return "", err
  116. }
  117. // space can't be used
  118. // , is used as a separator
  119. // * is used in mask matching
  120. // ? is used in mask matching
  121. if strings.ContainsAny(lowered, " ,*?") {
  122. return "", errInvalidCharacter
  123. }
  124. return name[:start] + lowered, err
  125. }
  126. // CasefoldName returns a casefolded version of a nick/user name.
  127. func CasefoldName(name string) (string, error) {
  128. lowered, err := Casefold(name)
  129. if err != nil {
  130. return "", err
  131. } else if len(lowered) == 0 {
  132. return "", errStringIsEmpty
  133. }
  134. // # is a channel prefix
  135. // ~&@%+ are channel membership prefixes
  136. // - I feel like disallowing
  137. if strings.ContainsAny(lowered, protocolBreakingNameCharacters) || strings.ContainsAny(string(lowered[0]), "#~&@%+-") {
  138. return "", errInvalidCharacter
  139. }
  140. return lowered, err
  141. }
  142. // CasefoldTarget returns a casefolded version of an IRC target, i.e.
  143. // it determines whether the target is a channel name or nickname and
  144. // applies the appropriate casefolding rules.
  145. func CasefoldTarget(name string) (string, error) {
  146. if strings.HasPrefix(name, "#") {
  147. return CasefoldChannel(name)
  148. } else {
  149. return CasefoldName(name)
  150. }
  151. }
  152. // returns true if the given name is a valid ident, using a mix of Insp and
  153. // Chary's ident restrictions.
  154. func isIdent(name string) bool {
  155. if len(name) < 1 {
  156. return false
  157. }
  158. for i := 0; i < len(name); i++ {
  159. chr := name[i]
  160. if (chr >= 'a' && chr <= 'z') || (chr >= 'A' && chr <= 'Z') || (chr >= '0' && chr <= '9') {
  161. continue // alphanumerics
  162. }
  163. if i == 0 {
  164. return false // first char must be alnum
  165. }
  166. switch chr {
  167. case '[', '\\', ']', '^', '_', '{', '|', '}', '-', '.', '`':
  168. continue // allowed chars
  169. default:
  170. return false // disallowed chars
  171. }
  172. }
  173. return true
  174. }
  175. // Skeleton produces a canonicalized identifier that tries to catch
  176. // homoglyphic / confusable identifiers. It's a tweaked version of the TR39
  177. // skeleton algorithm. We apply the skeleton algorithm first and only then casefold,
  178. // because casefolding first would lose some information about visual confusability.
  179. // This has the weird consequence that the skeleton is not a function of the
  180. // casefolded identifier --- therefore it must always be computed
  181. // from the original (unfolded) identifier and stored/tracked separately from the
  182. // casefolded identifier.
  183. func Skeleton(name string) (string, error) {
  184. switch globalCasemappingSetting {
  185. default:
  186. return realSkeleton(name)
  187. case CasemappingASCII:
  188. // identity function is fine because we independently case-normalize in Casefold
  189. return name, nil
  190. }
  191. }
  192. func realSkeleton(name string) (string, error) {
  193. // XXX the confusables table includes some, but not all, fullwidth->standard
  194. // mappings for latin characters. do a pass of explicit width folding,
  195. // same as PRECIS:
  196. name = width.Fold.String(name)
  197. name = confusables.SkeletonTweaked(name)
  198. // internationalized lowercasing for skeletons; this is much more lenient than
  199. // Casefold. In particular, skeletons are expected to mix scripts (which may
  200. // violate the bidi rule). We also don't care if they contain runes
  201. // that are disallowed by PRECIS, because every identifier must independently
  202. // pass PRECIS --- we are just further canonicalizing the skeleton.
  203. return cases.Fold().String(name), nil
  204. }
  205. // maps a nickmask fragment to an expanded, casefolded wildcard:
  206. // Shivaram@good-fortune -> *!shivaram@good-fortune
  207. // EDMUND -> edmund!*@*
  208. func CanonicalizeMaskWildcard(userhost string) (expanded string, err error) {
  209. userhost = strings.TrimSpace(userhost)
  210. var nick, user, host string
  211. bangIndex := strings.IndexByte(userhost, '!')
  212. strudelIndex := strings.IndexByte(userhost, '@')
  213. if bangIndex != -1 && bangIndex < strudelIndex {
  214. nick = userhost[:bangIndex]
  215. user = userhost[bangIndex+1 : strudelIndex]
  216. host = userhost[strudelIndex+1:]
  217. } else if bangIndex != -1 && strudelIndex == -1 {
  218. nick = userhost[:bangIndex]
  219. user = userhost[bangIndex+1:]
  220. } else if bangIndex != -1 && strudelIndex < bangIndex {
  221. // @ before !, fail
  222. return "", errNicknameInvalid
  223. } else if bangIndex == -1 && strudelIndex != -1 {
  224. user = userhost[:strudelIndex]
  225. host = userhost[strudelIndex+1:]
  226. } else if bangIndex == -1 && strudelIndex == -1 {
  227. nick = userhost
  228. } else {
  229. // shouldn't be possible
  230. return "", errInvalidParams
  231. }
  232. if nick == "" {
  233. nick = "*"
  234. }
  235. if nick != "*" {
  236. // XXX wildcards are not accepted with most unicode nicks,
  237. // because the * character breaks casefolding
  238. nick, err = Casefold(nick)
  239. if err != nil {
  240. return "", err
  241. }
  242. }
  243. if user == "" {
  244. user = "*"
  245. }
  246. if user != "*" {
  247. user = strings.ToLower(user)
  248. }
  249. if host == "" {
  250. host = "*"
  251. }
  252. if host != "*" {
  253. host = strings.ToLower(host)
  254. }
  255. expanded = fmt.Sprintf("%s!%s@%s", nick, user, host)
  256. if utils.SafeErrorParam(expanded) != expanded {
  257. err = errInvalidCharacter
  258. }
  259. return
  260. }
  261. func foldASCII(str string) (result string, err error) {
  262. if !IsPrintableASCII(str) {
  263. return "", errInvalidCharacter
  264. }
  265. return strings.ToLower(str), nil
  266. }
  267. func IsPrintableASCII(str string) bool {
  268. for i := 0; i < len(str); i++ {
  269. // allow space here because it's technically printable;
  270. // it will be disallowed later by CasefoldName/CasefoldChannel
  271. chr := str[i]
  272. if chr < ' ' || chr > '~' {
  273. return false
  274. }
  275. }
  276. return true
  277. }
  278. func foldPermissive(str string) (result string, err error) {
  279. if !permissiveCharsRegex.MatchString(str) {
  280. return "", errInvalidCharacter
  281. }
  282. // YOLO
  283. str = norm.NFD.String(str)
  284. str = cases.Fold().String(str)
  285. str = norm.NFD.String(str)
  286. return str, nil
  287. }
  288. // Reduce, e.g., `alice!~u@host` to `alice`
  289. func NUHToNick(nuh string) (nick string) {
  290. if idx := strings.IndexByte(nuh, '!'); idx != -1 {
  291. return nuh[0:idx]
  292. }
  293. return nuh
  294. }