| 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380 |
2×
2×
2×
2×
2×
2×
2×
401×
38×
401×
57×
382×
2×
38×
38×
38×
2×
361×
361×
361×
361×
266×
361×
361×
361×
361×
361×
361×
2×
19×
20×
38×
2×
38×
2×
19×
2×
1×
1×
1×
2×
19×
19×
19×
19×
19×
19×
1×
19×
19×
19×
19×
19×
19×
19×
19×
19×
19×
19×
1×
1×
3×
3×
1×
1×
3×
1×
1×
3×
3×
3×
3×
3×
2×
19×
19×
19×
19×
19×
19×
19×
19×
19×
95×
19×
19×
19×
19×
19×
19×
38×
19×
228×
19×
38×
19×
19×
266×
19×
19×
| 'use strict';
const _ = require('lodash');
const URL = require('url');
const Q = require('q');
const classification = require(__dirname + '/classification');
// all functions here are unary, so that they may "pre-compile"
const matches = {
'equal' : v => {
const v_low = v.toLowerCase();
return (ua => ua === v_low);
},
'not_equal': v => {
const v_low = v.toLowerCase();
return (ua => ua !== v_low);
},
'contains': v => {
const v_low = v.toLowerCase();
return (ua => ua.indexOf(v_low) >= 0);
},
'starts_with': v => {
const v_low = v.toLowerCase();
return (ua => ua.startsWith(v_low));
},
'ends_with': v => {
const v_low = v.toLowerCase();
return (ua => ua.endsWith(v_low));
},
// cannot lowercase v, need to tell RegExp to ignore case instead
'regex': v => RegExp.prototype.test.bind(new RegExp(v, 'i'))
};
// not_allowed is the UI artifact. It is used in exit mode (upgrade_action) and
// it means the transition from entry mode is not allowed. To me this is no
// different from specifying upgrade_action==entry_action, and that's what I
// translate them to using max().
const actionMap = {not_allowed: 0,
block: 1,
read_only: 2,
read_write: 3,
direct: 4
};
/**
* @function* explanations
* @desc Given a Tally-like object with score, produces a list of any
* explanations from this Tally-like, or any nested Tally-like from the trace.
*
* Assumes tally is either primitive, or an object that may contain score,
* explain or trace attributes.
*
* @param {any} tally - a primitive, or a Tally-like object to traverse
* @yield {[Int, object]} produces pairs of [Int, object], where the head item
* represents the score, and the last item an object that represents the
* explanation
*/
function* explanations(tally) {
if (tally.explain) {
yield [tally.score, tally.explain];
}
if (tally.trace) {
for(let t in tally.trace) {
yield* explanations(tally.trace[t]);
}
}
}
const Tally = function() {
const self = this;
self.score = 0;
self.trace = {};
};
// tally can add the score from a given function or Tally or number
Tally.prototype.tally = function(f) {
const self = this;
// FIXME: that's what ...rest is for, but our version of node doesn't support
// that at the moment
const rest = Array.from(arguments).slice(1);
const name = typeof f === 'string' ? f: undefined;
if (name !== undefined) {
f = rest.shift();
}
const tally = typeof f === 'function' ?
f.apply(null, rest):
f;
const score = typeof tally === 'object'? tally.score: tally;
Iif (typeof score !== 'number') {
throw new Error(tally.error.toString() ||
'Expected Tally-like, but found score is ' +
typeof score + '; keys: ' + Object.keys(tally));
}
self.score += score;
self.trace[name || f.displayName || f.name || 'noname'] = tally;
return self;
};
/**
* @function explanations
* @desc Traverses this Tally and any nested Tally-like in trace to obtain
* an array of explanations, where they are available, sorted in descending
* order of the classification score.
*/
Tally.prototype.explanations = function() {
return Array.from(explanations(this))
.sort((a,b) => b[0]-a[0])
.map(a => a[1]);
};
// looks at x and returns either left(x.left) if not x.right, or right(x.right)
function either(x, left, right) {
return x.right ? right(x.right): left(x.left);
}
// Copies x, and adds fields from object produced by f, if x.right.
// If not x.right, just returns x.
function rightDefaults(x, f) {
return either(x, () => x, (r) => _.defaults(f(r) || {}, x));
}
// This function validates subject_rules and produces {right:...}
// at each level of nesting for valid rules, and {left: 'diagnostic message'}
// for rules that contain references to unknown matchers
function validateSubjectRules(subject_rules) {
return subject_rules.map(
s_rule => {
const match = {'all' : _.every,
'any' : _.some}[s_rule.match];
return _.defaults(match &&
{ right: match,
rules: s_rule.subject_attributes.map(
r_spec => {
const fn = matches[r_spec.relation];
let fn_ap;
try {
fn_ap = fn && fn(r_spec.value);
}catch(e) {
fn_ap = undefined;
}
return _.defaults(
fn_ap && {right: fn_ap,
attribute: r_spec.attribute.toLowerCase()} ||
fn && {left: 'Bad constant "' + r_spec.value +
'" for relation: ' + r_spec.relation} ||
{left: 'Unknown relation: ' + r_spec.relation},
r_spec);
}),
id: s_rule.id
} ||
{left: 'Unknown match: ' + s_rule.match},
s_rule);
});
}
module.exports = {
policyUserAttributes: safemailPolicy =>
_.uniq(_.flatten(
safemailPolicy.subject_rules.map(
s_rule => _.map(s_rule.subject_attributes, 'attribute')
)
)),
validateSubjectRules: validateSubjectRules,
pdp: (urlScore, attributeSearchResult, safemailPolicy) => {
Iif (!attributeSearchResult) {
attributeSearchResult = {};
}
Iif (!attributeSearchResult.attributes) {
attributeSearchResult.attributes = [];
}
Iif (!urlScore || !urlScore.riskScore || !safemailPolicy) {
return {error: 'URL score and safemail policy are required',
url_score: urlScore,
attribute_search_result: attributeSearchResult};
}
// produce a structure of the policy that represents a trace of
// role assignment decision-making.
// the principle is simple: if the section is applicable, it is mapped
// to {right: ...}; if there is a problem or the rule cannot be evaluated,
// it is mapped to {left: 'diagnostic message'}
if (!safemailPolicy.validated_subject_rules) {
safemailPolicy.validated_subject_rules =
validateSubjectRules(safemailPolicy.subject_rules);
}
const userAttributes = {};
Object.keys(attributeSearchResult.attributes).forEach(
k => {
userAttributes[k.toLowerCase()] = attributeSearchResult.
attributes[k].map(v => v.toLowerCase());
}
);
const valid_rules = safemailPolicy.validated_subject_rules;
// applicable rules is a copy of valid_rules with ua filled in for each
// s_rule.r_spec with right for which we have found userAttributes,
// or left with an diagnostic message
const applicable_rules = valid_rules.map(
s_rule => rightDefaults(s_rule, () =>
({rules: s_rule.rules.map(
r_spec => rightDefaults(r_spec, () =>
({ua: userAttributes[r_spec.attribute] &&
userAttributes[r_spec.attribute].length > 0 &&
{right: userAttributes[r_spec.attribute]} ||
{left: 'No value for attribute: ' +
r_spec.attribute}
})))
}))
);
const userRole = applicable_rules.find(
s_rule => either(s_rule,
() => false,
match => match(s_rule.rules,
rule => rule.right &&
rule.ua.right &&
rule.ua.right.some(rule.right)
)
)
);
Iif (!userRole) {
// TODO: the policy should contain default role
return {error: 'User does not match any role. Assume default action.',
url_score: urlScore,
attribute_search_result: attributeSearchResult,
role_assignment_policy_trace: applicable_rules};
}
if (!safemailPolicy.validated_action_map && safemailPolicy.entry_actions){
safemailPolicy.validated_action_map = {};
safemailPolicy.entry_actions.forEach(action => {
let c = safemailPolicy
.validated_action_map[action.subject_rule_id];
if (!c) {
c = {};
safemailPolicy.validated_action_map[action.subject_rule_id]=c;
}
c[action.risk_score] = {
entry_action: action.isolation_action in actionMap &&
action.isolation_action,
user_experience_banner: action.user_experience_banner
};
});
Eif (safemailPolicy.upgrade_actions) {
safemailPolicy.upgrade_actions.forEach(action => {
let c = safemailPolicy
.validated_action_map[action.subject_rule_id];
Iif (!c) {
c = {};
safemailPolicy.validated_action_map[action.subject_rule_id]=c;
}
Iif (!c[action.risk_score]) {
c[action.risk_score] = {};
}
const rs = c[action.risk_score];
rs.upgrade_action = action.isolation_action in actionMap &&
action.isolation_action;
});
}
}
function max(a1, a2) {
return (actionMap[a1] || 0) > (actionMap[a2] || 0) ? a1: a2;
}
const riskScore = urlScore.riskScore;
const actions = safemailPolicy.validated_action_map[userRole.id] || {};
const riskScoreAction = actions[riskScore] || {};
const entry_action = riskScoreAction.entry_action || 'block';
const upgrade_action_rule = riskScoreAction.upgrade_action || 'block';
const upgrade_action = max(entry_action, upgrade_action_rule);
return {decision: {
selected_rule: userRole.id,
user_experience_banner: riskScoreAction.user_experience_banner||
'basic',
entry_action: entry_action,
upgrade_action: upgrade_action
},
url_score: urlScore,
attribute_search_result: attributeSearchResult,
role_assignment_policy_trace: applicable_rules};
},
uceToTally: uceResponse => {
const t = classification.uceClassifiers.reduce(
(acc, classifier) => acc.tally(classifier, uceResponse),
new Tally()
);
t.uceResponse = uceResponse;
return t;
},
countryCodeToTally: cs => classification.countryScore(cs),
// Asynchronously collects scores from all classifiers. May skip waiting for
// some classifiers, if the risk score can be shown to not change. Place the
// slowest responding asynchronous classifiers first, the synchronous ones
// last.
riskScore: (asyncs, urlString) => {
try {
// parts of URL may be case-sensitive (like path),
// but for this analysis we don't need to distinguish that
const url = URL.parse(urlString.toLowerCase());
// fire off async classifiers, and compute sync classifier scores
// asyncClassifiers: [Q([string, Tally|int])]
// syncClassifiers: [[string, Tally|int]]
const asyncClassifiers = asyncs.map(
c => Q.all([c.displayName || c.name,
c(url)]
));
// urlClassifiers: [URL -> Tally|int]
const syncClassifiers = classification.urlClassifiers.map(
c => [c.displayName || c.name, c(url)]
);
// lazyScore: Q(either any Tally)
// folding the array of classifiers permits to build a computation that
// stops evaluating the chain once tally reaches HIGH_RISK_THRESHOLD.
// good URLs (that is, most of the URLs) will wait for all classifiers
// to provide a score, so we use Q.all as it is much simpler.
// TODO: do we care to complicate this logic for bad URLs to possibly
// get a score sooner? This should affect only really bad URLs.
const lazyScore = Q.all(asyncClassifiers)
.then(scores => {
Eif (scores.every(c => c[1] !== undefined &&
c[1].score !== undefined)) {
return scores;
} else {
// replacing all failed asynchronous classifiers
// with a single risk score - needed for UCE as
// per UK-412
return scores
.filter(c => c[1] !== undefined &&
c[1].score !== undefined)
.concat([['failed_async',
classification.MED_RISK_THRESHOLD - 1]]);
}
})
.then(scores => syncClassifiers.concat(scores)
.reduce(
// (Tally, [string, Tally|()->Tally]) -> Tally
(acc, score) => acc.tally.apply(acc, score),
new Tally()
)
)
.then(tally => ({
riskScore:
tally.score < classification.MED_RISK_THRESHOLD?
'low':
tally.score < classification.HIGH_RISK_THRESHOLD?
'medium':
'high',
tally: tally
})
);
// .fail to be handled by the caller
return lazyScore;
} catch(e) {
return Q.Promise((resolve, reject) => reject(e));
}
}
};
|