summaryrefslogtreecommitdiffstats
path: root/comm/mail/components/accountcreation/Sanitizer.jsm
blob: d6bc3918bcfb67f8bcf141c197cbb166a5b5da23 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const EXPORTED_SYMBOLS = ["Sanitizer"];

const { AccountCreationUtils } = ChromeUtils.import(
  "resource:///modules/accountcreation/AccountCreationUtils.jsm"
);

const { cleanUpHostName, isLegalHostNameOrIP } = ChromeUtils.import(
  "resource:///modules/hostnameUtils.jsm"
);

/**
 * This is a generic input validation lib. Use it when you process
 * data from the network.
 *
 * Just a few functions which verify, for security purposes, that the
 * input variables (strings, if nothing else is noted) are of the expected
 * type and syntax.
 *
 * The functions take a string (unless noted otherwise) and return
 * the expected datatype in JS types. If the value is not as expected,
 * they throw exceptions.
 */

// To debug, set mail.setup.loglevel="All" and kDebug = true.
var kDebug = false;

var Sanitizer = {
  integer(unchecked) {
    if (typeof unchecked == "number" && !isNaN(unchecked)) {
      return unchecked;
    }

    var r = parseInt(unchecked);
    if (isNaN(r)) {
      throw new MalformedException("no_number.error", unchecked);
    }

    return r;
  },

  integerRange(unchecked, min, max) {
    var int = this.integer(unchecked);
    if (int < min) {
      throw new MalformedException("number_too_small.error", unchecked);
    }

    if (int > max) {
      throw new MalformedException("number_too_large.error", unchecked);
    }

    return int;
  },

  boolean(unchecked) {
    if (typeof unchecked == "boolean") {
      return unchecked;
    }

    if (unchecked == "true") {
      return true;
    }

    if (unchecked == "false") {
      return false;
    }

    throw new MalformedException("boolean.error", unchecked);
  },

  string(unchecked) {
    return String(unchecked);
  },

  nonemptystring(unchecked) {
    if (!unchecked) {
      throw new MalformedException("string_empty.error", unchecked);
    }

    return this.string(unchecked);
  },

  /**
   * Allow only letters, numbers, "-" and "_".
   *
   * Empty strings not allowed (good idea?).
   */
  alphanumdash(unchecked) {
    var str = this.nonemptystring(unchecked);
    if (!/^[a-zA-Z0-9\-\_]*$/.test(str)) {
      throw new MalformedException("alphanumdash.error", unchecked);
    }

    return str;
  },

  /**
   * DNS hostnames like foo.bar.example.com
   * Allow only letters, numbers, "-" and "."
   * Empty strings not allowed.
   * Currently does not support IDN (international domain names).
   */
  hostname(unchecked) {
    let str = cleanUpHostName(this.nonemptystring(unchecked));

    // Allow placeholders. TODO move to a new hostnameOrPlaceholder()
    // The regex is "anything, followed by one or more (placeholders than
    // anything)".  This doesn't catch the non-placeholder case, but that's
    // handled down below.
    if (/^[a-zA-Z0-9\-\.]*(%[A-Z0-9]+%[a-zA-Z0-9\-\.]*)+$/.test(str)) {
      return str;
    }

    if (!isLegalHostNameOrIP(str)) {
      throw new MalformedException("hostname_syntax.error", unchecked);
    }

    return str.toLowerCase();
  },

  /**
   * A value which resembles an email address.
   */
  emailAddress(unchecked) {
    let str = this.nonemptystring(unchecked);
    if (!/^[a-z0-9\-%+_\.\*]+@[a-z0-9\-\.]+\.[a-z]+$/i.test(str)) {
      throw new MalformedException("emailaddress_syntax.error", unchecked);
    }

    return str.toLowerCase();
  },

  /**
   * A non-chrome URL that's safe to request.
   */
  url(unchecked) {
    var str = this.string(unchecked);

    // DANGER ZONE: data:text/javascript or data:text/html can contain
    // JavaScript code, run in the caller's security context, and might allow
    // arbitrary code execution, so these must be prevented at all costs.
    // PNG and JPEG data: URLs are fine.  But SVG is again dangerous,
    // it can contain javascript, so it would create a critical security hole.
    // Talk to BenB or bz before relaxing *any* of the checks in this function.
    if (
      str.startsWith("data:image/png;") ||
      str.startsWith("data:image/jpeg;")
    ) {
      return new URL(str).href;
    }

    if (!str.startsWith("http:") && !str.startsWith("https:")) {
      throw new MalformedException("url_scheme.error", unchecked);
    }

    var uri;
    try {
      uri = Services.io.newURI(str);
      uri = uri.QueryInterface(Ci.nsIURL);
    } catch (e) {
      throw new MalformedException("url_parsing.error", unchecked);
    }

    if (uri.scheme != "http" && uri.scheme != "https") {
      throw new MalformedException("url_scheme.error", unchecked);
    }

    return uri.spec;
  },

  /**
   * A value which should be shown to the user in the UI as label
   */
  label(unchecked) {
    return this.string(unchecked);
  },

  /**
   * Allows only certain values as input, otherwise throw.
   *
   * @param unchecked {Any} The value to check
   * @param allowedValues {Array} List of values that |unchecked| may have.
   * @param defaultValue {Any} (Optional) If |unchecked| does not match
   *       anything in |mapping|, a |defaultValue| can be returned instead of
   *       throwing an exception. The latter is the default and happens when
   *       no |defaultValue| is passed.
   * @throws MalformedException
   */
  enum(unchecked, allowedValues, defaultValue) {
    for (let allowedValue of allowedValues) {
      if (allowedValue == unchecked) {
        return allowedValue;
      }
    }
    // value is bad
    if (typeof defaultValue == "undefined") {
      throw new MalformedException("allowed_value.error", unchecked);
    }
    return defaultValue;
  },

  /**
   * Like enum, allows only certain (string) values as input, but allows the
   * caller to specify another value to return instead of the input value. E.g.,
   * if unchecked == "foo", return 1, if unchecked == "bar", return 2,
   * otherwise throw. This allows to translate string enums into integer enums.
   *
   * @param unchecked {Any} The value to check
   * @param mapping {Object} Associative array. property name is the input
   *       value, property value is the output value. E.g. the example above
   *       would be: { foo: 1, bar : 2 }.
   *       Use quotes when you need freaky characters: "baz-" : 3.
   * @param defaultValue {Any} (Optional) If |unchecked| does not match
   *       anything in |mapping|, a |defaultValue| can be returned instead of
   *       throwing an exception. The latter is the default and happens when
   *       no |defaultValue| is passed.
   * @throws MalformedException
   */
  translate(unchecked, mapping, defaultValue) {
    for (var inputValue in mapping) {
      if (inputValue == unchecked) {
        return mapping[inputValue];
      }
    }
    // value is bad
    if (typeof defaultValue == "undefined") {
      throw new MalformedException("allowed_value.error", unchecked);
    }
    return defaultValue;
  },
};

function MalformedException(msgID, uncheckedBadValue) {
  var stringBundle = AccountCreationUtils.getStringBundle(
    "chrome://messenger/locale/accountCreationUtil.properties"
  );
  var msg = stringBundle.GetStringFromName(msgID);
  if (typeof kDebug != "undefined" && kDebug) {
    msg += " (bad value: " + uncheckedBadValue + ")";
  }
  AccountCreationUtils.Exception.call(this, msg);
}
MalformedException.prototype = Object.create(
  AccountCreationUtils.Exception.prototype
);
MalformedException.prototype.constructor = MalformedException;