all files / src/controllers/ classification.js

88.08% Statements 170/193
69.02% Branches 127/184
100% Functions 9/9
87.57% Lines 162/185
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 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650                                        38× 950×     38×     38×                       95× 2480×     95×     95×                     950× 38×       38×                       190× 2136×     190×         190×                     38× 38× 17×     21×   32×       21× 21×                   19×       19×       19×                                 53× 53× 106× 61×   45×   106×                                           32× 13×                                                                 61× 45×   16×     61×                             19× 19×   21× 21× 21×   21× 19×   19×                                                 19×     19× 19×                                               19× 19×                 19×   19×                             19×     19×   19×                                           19× 19×                               19× 19×                 19× 19×               19× 19×         19×             19× 19× 19×             19× 19×                     19× 19×                     19× 19× 19×                   19× 19×                   19× 19× 19× 19×       19×                   76×   19× 19× 76×     76×           19×                 19× 19×                   19× 19×                                                 36×     36× 342× 342× 342× 38×         304×     342×         36× 36×       20× 19× 19× 19× 19×                                                         10×   24×                        
'use strict';
 
const fs = require('fs');
const config = require(__dirname + '/../config');
const uce_maps = require(__dirname + '/uce-maps');
const net = require('net');
 
 
// So far the classifiers are treating the arrays as matching any, not all.
// When such a requirement arises, we will add support for that.
 
// These functions return objects with an indicator of whether a match was
// found. If match is truthy, it must also contain a splits array indicating
// where in the input string the match or matches were found.
 
/**
 * @function equals
 * @desc Evaluates whether a given execution context field value equals any of
 * the strings.
 * @param {string} field - the value; may be falsy
 * @param {array} names - the list of strings to match
 * @return {object} match set to truthy, if field can be found in names, and
 *    sets splits reflecting the match
 */
function equals(field, names) {
   const res = {
      match: field && names.find(n => field === n)
   };
 
   Iif (res.match) {
      res.splits = ['', res.match];
   }
   return res;
}
 
/**
 * @function endsWith
 * @desc Evaluates whether a given execution context field value ends with any
 * of the strings.
 * @param {string} field - the value; may be falsy
 * @param {array} names - the list of strings to match
 * @return {object} match set to truthy, if field ends with one of the
 *    substrings found in names, and sets splits reflecting the match
 */
function endsWith(field, names) {
   const res = {
      match: field && names.find(n => field.endsWith(n))
   };
 
   if (res.match) {
      res.splits = [field.substring(0, field.length - res.match.length),
                    res.match];
   }
   return res;
}
 
/**
 * @function domainEndsWith
 * @desc Evaluates whether a given hostname ends with any of the domain names.
 * @param {string} field - the value; may be falsy
 * @param {array} names - the list of strings to match
 * @return {object} match set to truthy, if field as a domain name ends with one
 *    of the substrings found in names, and sets splits reflecting the match
 */
function domainEndsWith(field, names) {
   const r = endsWith(field, names.map(s => '.' + s));
   Iif (r.match) {
      return r;
   }
 
   return equals(field, names);
}
 
/**
 * @function contains
 * @desc Evaluates whether a given execution context field value contains any of
 * the strings.
 * @param {string} field - the value; may be falsy
 * @param {array} names - the list of strings to match
 * @return {object} match set to truthy, if field contains any one of the names,
 *    and sets splits reflecting the first match
 */
function contains(field, names) {
   const res = {
      match: field && names.find(n => field.indexOf(n) >= 0)
   };
 
   if (res.match) {
      const idx = field.indexOf(res.match);
      res.splits = [ field.substring(0, idx),
                     res.match,
                     field.substring(idx+res.match.length)
                   ];
   }
   return res;
}
 
/**
 * @function count
 * @desc Counts the number of occurrences of substr in str.
 * @param {string} str - the value; may be falsy
 * @param {string} substr - the substring to look for
 * @return {object} match set to an integer number of occurrences; if non-zero,
 *    sets splits reflecting all the occurrences of substr in str.
 */
function count(str, substr) {
   const splits = str && str.split(substr);
   if (!splits || splits.length === 1) {
      return {match: 0};
   }
 
   const res = {
      splits: splits.slice(1)
               .reduce((a,b) => a.concat([substr, b]), [splits[0]])
   };
 
   // split will return at least one string
   res.match = splits.length - 1;
   return res;
}
 
/**
 * @function isIP
 * @desc Tests if a given string is a IP address.
 * @param {string} host - the string representing a host name
 * @return {object} match set to true, if it is a IP address, and sets splits
 *    to reflect the whole string matched
 */
function isIP(host) {
   const res = {
      match: net.isIP(host)
   };
 
   Iif (res.match) {
      res.splits = ['', host];
   }
 
   return res;
}
 
/**
 * @function* splitsToExplain
 * @desc Flattens a tree of splits into an array of pairs ['plain'|'bold', s].
 * This is to support explainURL, which combines plaintext URL parts with URL
 * parts with splits. Nesting the parts of URLs is a natural way to represent
 * the URL structure as described at
 * https://nodejs.org/api/url.html#url_url_strings_and_url_objects
 * - for example, query is a part of search, which is a part of path, which is a
 * part of href.
 *
 * @param {array{subtree|string}} splits - an array of either strings
 *       representing the splits of the part of the URL, or subtrees, which get
 *       flattened recursively
 */
function* splitsToExplain(splits) {
   let plain = true;
   for(let s of splits) {
      if (typeof s !== 'object') {
         yield [plain, s];
      } else {
         yield* splitsToExplain(s);
      }
      plain = !plain;
   }
}
 
/**
 * @function explainURL
 * @desc Given a object representing a part of URL that was analysed,
 * reconstructs the text, making the selected part bold.
 *
 * Assumes this points to the env with the URL parts.
 *
 * Technically, explainURL supports arbitrary number of URL parts, but
 * the use case is for just one part, since at the moment not more than one
 * split can be stored in the global namespace.
 *
 * @param {object} orig - the original URL
 * @param {object} url - parts of the URL that were split.
 * @return {array} - plain and bold parts of the URL
 */
function explainURL(orig, url) {
   // helper functions taking the splits from the given object,
   // or, if that is not specified, from the original URL in the execution
   // context
   const field = n => url[n] || [orig[n] || ''];
   const separator = (n, s) => [url[n] || orig[n] ? s: ''];
 
 
   if (!url.href) {
      if (!url.host && (url.hostname || url.port)) {
         url.host = [
            field('hostname'),
            separator('port', ':'),
            field('port')
         ];
      }
 
      if (!url.path) {
         Iif (!url.search && url.query) {
            url.search = [['?'], url.query];
         }
 
         Iif (url.pathname || url.search) {
            url.path = [
               field('pathname'),
               field('search')
            ];
         }
      }
 
      url.href = [
         field('protocol'),
         separator('protocol', '//'),
         field('auth'),
         separator('auth', '@'),
         field('host'),
         field('path'),
         field('hash')
      ];
   }
 
   // flatten the tree to an array of plain and bold
   const splits = Array.from(splitsToExplain(url.href));
 
   // now reduce to a chain of tokens with alternating style:
   // concatenate consecutive tokens of the same style
   const res = [''];
   let plain = true;
   for(let s of splits) {
      if (s[0] === plain) {
         res[res.length - 1] += s[1];
      } else {
         res.push(s[1]);
      }
 
      plain = s[0];
   }
 
   return res;
}
 
 
const classifiers = {
   uce_classifiers: {
      /**
       * @function uce_cats
       * @desc Given the config of UCE categories to score map and a UCE
       * response, computes the score. Additionally to the score and explain,
       * maintains a trace indicating how much each category scored for logging
       * purposes.
       */
      uce_cats: (env, uce_response) => {
         const trace = {};
         const culprits = uce_response.webroot_cats
                        .map((c) => {
                           const score = env.scoreMap[c.name] || 0;
                           trace[c.name] = score;
                           return [c.name, score];
                        })
                        .filter((c) => c[1]);
         const score = culprits.reduce((score, c) => score + c[1], 0);
 
         return {
            score: score,
            trace: trace,
            explain: score &&
               {
                  cats: {
                     type: 'array',
                     val: culprits
                        .sort((a,b) => b[1] - a[1])
                        .reduce((acc, c) => {
                           const n =
                              uce_maps.webrootMailRiskCategoriesMap[c[0]] ||
                              c[0];
                           Eif (acc.indexOf(n) < 0) {
                              acc.push(n);
                           }
                           return acc;
                        }, []) // unique culprits
                  }
               }
         };
      },
 
      /**
       * @function uce_reputation
       * @desc Given the config and the UCE response, computes the score based
       * on reputation.
       */
      uce_reputation: (env, uce_response) => {
         const reputations = uce_response.reputation &&
                             uce_maps.ipReputation(uce_response.reputation) ||
                             [];
         Eif (reputations.find(r => r[0] === 'ok')) {
            return {score: 0};
         }
 
         if (reputations.find(r =>
               ['dns timeout','dns error'].indexOf(r[0]) >= 0
            )) {
            return {score: env.uncertainty_weight};
         }
 
         return {
            score: env.weight,
            explain: {reputation: {
               type: 'array',
               val: Array.from(new Set(reputations.map(r => r[1])))
            }}
         };
      },
 
      /**
       * @function uce_malware
       * @desc Given the config and the UCE response, computes the score based
       * on the malware indicator.
       */
      uce_malware: (env, uce_response) => {
         const score = uce_response.malware === 'ok'? 0: env.weight;
         return {
            score: score,
            explain: score && {
               malware: [uce_maps.mdbCategories(uce_response.malware)]
            }
         };
      },
 
      dynamicDNS: (env, uce_response) => {
         const dynDNS = uce_response.risk_factors &&
                        uce_response.risk_factors.dynDNS || {};
         return {
            score: dynDNS.explain ? env.weight: 0,
            explain: dynDNS.explain && {
               url: dynDNS.explain
            }
         };
      },
 
      /**
       * @function alexaRank
       * @desc Given a classification configuration with ranks sorted in
       *    descending order, and a UCE response with risk_factors, produces a
       *    score with explanation.
       */
      alexaRank: (env, uce_response) => {
         const rank = uce_response.risk_factors &&
                      uce_response.risk_factors.alexaRank || {};
 
         const res = 'rank' in rank ?
                        env.ranks.find(a => a[0] <= rank.rank) || [0, 0]:
                        env.ranks[0];
         return {
            score: res[1],
            explain: res[1] && {
               rank: [res[2]]
            }
         };
      }
   },
 
   /**
    * A collection of URL classifiers that compute the score by looking at the
    * URL as a string. They all take a parsed URL as the second argument.
    *
    * Their names are self-explanatory and correspond to the section in
    * classification.json where config contains lists of strings to look for.
    */
   url_classifiers: {
      phishTarget: (env, url) => {
         // NB: hostname component's classification overrides other factors.
         //     (e.g. 'http://www.ebay.com/?phish=google.com' is classified as
         //            non-phishing by virtue of 'www.ebay.com' being considered
         //            legitimate, despite the presence of '?phish=google.com')
         let res = contains(url.hostname, env.value);
         Iif (res.match) {
            const parts = url.hostname.split('.').reverse();
            const idx = parts.indexOf(res.match);
            const secondary = ['co', 'com'];
            // Ignore any matching gTLDs, second level domains, and a subset of
            // third level domains.
            if (idx === 0 || idx === 1 || (idx === 2 &&
                                           secondary.indexOf(parts[1]) !== -1)) {
               res.match = undefined;
            }
            return {
               score: res.match? env.weight: 0,
               explain: res.match &&
                        {url: explainURL(url, {hostname: res.splits})}
            };
         } else {
            res = contains(url.href, env.value);
            return {
               score: res.match? env.weight: 0,
               explain: res.match &&
                        {url: explainURL(url, {href: res.splits})}
            };
         }
      },
 
      exploitPath: (env, url) => {
         const res = contains(url.path, env.value);
         return {
            score: res.match? env.weight: 0,
            explain: res.match &&
                     {url: explainURL(url, {path: res.splits})}
         };
      },
 
      dots: (env, url) => {
         const res = count(url.hostname, '.');
         const score = res.match < env.less_certain_threshold?
                  0:
                  res.match === env.less_certain_threshold?
                     env.less_certain_weight:
                     env.weight;
         return {
            score: score,
            explain: score && {url: explainURL(url, {hostname: res.splits})}
         };
      },
 
      dashes: (env, url) => {
         const res = count(url.hostname, '-');
         const score = res.match >= env.threshold? env.weight: 0;
         return {
            score: score,
            explain: score && {url: explainURL(url, {hostname: res.splits})}
         };
      },
 
      suspectCountry: (env, url) => {
         const res = endsWith(url.hostname, env.value);
         return {
            score: res.match? env.weight: 0,
            explain: res.match &&
                     {
                        url: explainURL(url, {hostname: res.splits}),
                        tld: [env.tldToCountry[res.splits[1]] || res.splits[1]]
                     }
         };
      },
 
      badTLD: (env, url) => {
         const res = endsWith(url.hostname, env.value);
         return {
            score: res.match? env.weight: 0,
            explain: res.match &&
                     {
                        url: explainURL(url, {hostname: res.splits}),
                        tld: [res.splits[1]]
                     }
         };
      },
 
      sketchyWebHost: (env, url) => {
         const res = domainEndsWith(url.hostname, env.value);
         const res1 = res.match? res: contains(url.hostname, env.cvalue);
         return {
            score: res1.match? env.weight: 0,
            explain: res1.match &&
                     {
                        url: explainURL(url, {hostname: res1.splits})
                     }
         };
      },
 
      hostIsIp: (env, url) => {
         const res = isIP(url.hostname);
         return {
            score: res.match? env.weight: 0,
            explain: res.match &&
                     {
                        url: explainURL(url, {hostname: res.splits})
                     }
         };
      },
 
      httpInURL: (env, url) => {
         const res = contains(url.path, env.value);
         const res1 = !res.match && contains(url.hostname, env.value);
         const score = res.match || res1.match? env.weight: 0;
         const highlight = res.match?
                           {path: res.splits}:
                           {hostname: res1.splits};
 
         return {
            score: score,
            explain: score &&
                     {
                        url: explainURL(url, highlight)
                     }
         };
      },
 
      fakeTLD: (env, url) => {
         let r = endsWith(url.hostname, env.value.map(tld => '-' + tld));
 
         Eif (!r.match) {
            for(let tld of env.value) {
               r = contains(
                     url.hostname,
                     ['-' + tld + '.', '-' + tld + '-', '.' + tld + '-']);
               Iif (r.match) {
                  break;
               }
            }
         }
 
         return {
            score: r.match? env.weight: 0,
            explain: r.match && {
                     url: explainURL(url, {hostname: r.splits})
                  }
         };
      },
 
      urlShorteners: (env, url) => {
         const res = domainEndsWith(url.hostname, env.value);
         return {
            score: res.match? env.weight: 0,
            explain: res.match &&
                     {
                        url: explainURL(url, {hostname: res.splits})
                     }
         };
      },
 
      unusualPort: (env, url) => {
         Eif (!url.port) {
            return {score: 0};
         }
 
         const res = equals(url.port, env.value);
         return {
            score: !res.match? env.weight: 0,
            explain: !res.match &&
                     {
                        url: explainURL(url, {port: ['', url.port]})
                     }
         };
      }
   }
};
 
 
/**
 * @function bind
 * @desc A helper function performing common wrapping of classifiers. Given a
 * classifier, a config, and the name to assign to it, wraps the processing to
 * catch errors and reorganize the return value to include factor_name.
 *
 * If classifier throws an exception, it is propagated to the caller as an
 * object with error, but no score.
 */
function bind(f, env, displayName) {
   Iif (!f) {
      throw new Error('Could not find a classifier for ' + displayName);
   }
   const risk_scorer = context => {
      try {
         const res = f(env, context);
         if (res.score && res.explain) {
            res.explain = {
               factor_name: displayName,
               attributes: res.explain
            };
         } else {
            delete res.explain;
         }
 
         return res;
      } catch(e) {
         return {error: displayName + ': Not applicable: ' + e.message};
      }
   };
   risk_scorer.displayName = displayName;
   return risk_scorer;
}
 
 
const countryScore = env => {
   const blacklist = new Set(env.blacklist);
   return (env, countries) => {
      const country_names = countries && countries.map(c => c.country.names.en);
      const uniq = Array.from(new Set(country_names || []));
      const res = uniq.filter(c => blacklist.has(c));
      const score = res && res.length > 0 ? env.weight: 0;
      return {
         score: score,
         explain: score && {
            countries: res
         }
      };
   };
};
 
/**
 * @function init
 * @desc The module initialization. It is done here, so that the module
 * requiring it may choose non-default behaviour.
 *
 * Populates the contents of module.exports with the classification functions
 * bound to config take from classificaiton.json (or the given stream).
 *
 * @param {object} cfg - the PnR-E config; will use the default, if omitted
 * @param {string} stream - the classification.json contents; if omitted, will
 *     use the default file defined in cfg
 */
const init = (cfg, stream) => {
   try {
      delete exports.error;
      cfg = cfg || config;
      exports.MED_RISK_THRESHOLD =
         parseInt(cfg.pnr_enforcement.med_risk_threshold, 10);
      exports.HIGH_RISK_THRESHOLD =
         parseInt(cfg.pnr_enforcement.high_risk_threshold, 10);
 
      const CLASSIFICATION_JSON = cfg.pnr_enforcement
                                       .url_classification_config;
      const json = JSON.parse(
                     stream ||
                     fs.readFileSync(CLASSIFICATION_JSON).toString()
                   );
 
      const c_uce_classifiers = classifiers.uce_classifiers;
      const j_uce_classifiers = json.uce_classifiers;
      exports.uceClassifiers = Object.keys(c_uce_classifiers)
         .map(k => bind(c_uce_classifiers[k], j_uce_classifiers[k], k));
 
      const c_url_classifiers = classifiers.url_classifiers;
      const j_url_classifiers = json.url_classifiers;
      exports.urlClassifiers = Object.keys(c_url_classifiers)
         .map(k => bind(c_url_classifiers[k], j_url_classifiers[k], k));
 
      exports.countryScore = bind(countryScore(json.countryScore),
                                  json.countryScore,
                                  'geolocation');
   } catch(e) {
      exports.error = e;
   }
 
   return exports;
};
 
module.exports = exports = {
   init: init
};