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.0KB

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