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

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