summaryrefslogtreecommitdiffhomepage
path: root/gui/src/main/windows-split-tunneling.ts
blob: a8915595e5a4f2816e0552aa0b92321f8fef93c8 (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
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
import { app, shell } from 'electron';
import fs from 'fs';
import path from 'path';
import { IApplication } from '../shared/application-types';
import log from '../shared/logging';
import {
  ArrayValue,
  DOS_HEADER,
  IMAGE_DATA_DIRECTORY,
  IMAGE_DIRECTORY_ENTRY_IMPORT,
  IMAGE_FILE_HEADER,
  IMAGE_IMPORT_MODULE_DIRECTORY,
  IMAGE_NT_HEADERS,
  IMAGE_NT_HEADERS64,
  ImageNtHeadersUnion,
  IMAGE_OPTIONAL_HEADER32,
  ImageOptionalHeaderUnion,
  PrimitiveValue,
  rvaToOffset as rvaToOffsetImpl,
  StructValue,
  Value,
  DWORD,
  IMAGE_DIRECTORY_ENTRY_RESOURCE,
  IMAGE_RESOURCE_DIRECTORY,
  IMAGE_RESOURCE_DIRECTORY_DATA_ENTRY,
  VS_VERSIONINFO,
  STRING_FILE_INFO,
  STRING_TABLE,
  StructWrapper,
  STRING_TABLE_STRING,
  IMAGE_RESOURCE_DIRECTORY_ID_ENTRY,
} from './windows-pe-parser';

interface ShortcutDetails {
  target: string;
  name: string;
  args?: string;
}

type RvaToOffset = (rva: number) => Promise<number>;

// Applications are found by scanning the start menu directories
const APPLICATION_PATHS = [
  `${process.env.ProgramData}/Microsoft/Windows/Start Menu/Programs`,
  `${process.env.AppData}/Microsoft/Windows/Start Menu/Programs`,
];

// Some applications might be falsely filtered from the application list. This allow-list specifies
// apps that are falsely filtered but should be included.
const APPLICATION_ALLOW_LIST = [
  'firefox.exe',
  'chrome.exe',
  'msedge.exe',
  'brave.exe',
  'iexplore.exe',
];

// Cache of all previously scanned shortcuts.
const shortcutCache: Record<string, ShortcutDetails> = {};
// Cache of all previously scanned applications.
const applicationCache: Record<string, IApplication> = {};
// List of shortcuts that have been added manually by the user.
const additionalShortcuts: ShortcutDetails[] = [];

// Finds applications by searching through the startmenu for shortcuts with and exe-file as target.
// If applicationPaths has a value, the returned applications are only the ones corresponding to
// those paths.
export async function getApplications(options: {
  applicationPaths?: string[];
  updateCaches?: boolean;
}): Promise<{ fromCache: boolean; applications: IApplication[] }> {
  const cacheIsEmpty = Object.keys(shortcutCache).length === 0;

  if (options.updateCaches || cacheIsEmpty) {
    await updateShortcutCache();
  }

  // Add excluded apps that are missing from the shortcut cache to it
  if (options.applicationPaths) {
    await Promise.all(options.applicationPaths.map(addApplicationToAdditionalShortcuts));
  }

  await updateApplicationCache();
  // If applicationPaths is supplied the returnvalue should only contain the applications
  // corresponding to those paths.
  const applications = Object.values(applicationCache)
    .filter(
      (application) =>
        options.applicationPaths === undefined ||
        options.applicationPaths.find(
          (applicationPath) =>
            applicationPath.toLowerCase() === application.absolutepath.toLowerCase(),
        ) !== undefined,
    )
    .sort((a, b) => a.name.localeCompare(b.name));

  return {
    fromCache: !options.updateCaches && !cacheIsEmpty,
    applications,
  };
}

// Adds either a shortcut or an executable to the additionalShortcuts list
export async function addApplicationPathToCache(applicationPath: string): Promise<string> {
  const parsedPath = path.parse(applicationPath);
  if (parsedPath.ext === '.lnk') {
    const shortcutDetiails = shell.readShortcutLink(path.resolve(applicationPath));
    additionalShortcuts.push({ ...shortcutDetiails, name: path.parse(applicationPath).name });
    return shortcutDetiails.target;
  } else {
    await addApplicationToAdditionalShortcuts(applicationPath);
    return applicationPath;
  }
}

// Reads the start-menu directories and adds all shortcuts, targeting applications using networking,
// to the shortcuts cache. Wheter or not an application use networking is determined by checking for
// "WS2_32.dll" in it's imports.
async function updateShortcutCache(): Promise<void> {
  const links = await Promise.all(APPLICATION_PATHS.map(findAllLinks));
  const resolvedLinks = removeDuplicates(resolveLinks(links.flat()));

  const shortcuts: ShortcutDetails[] = [];
  for (const shortcut of resolvedLinks) {
    if (
      APPLICATION_ALLOW_LIST.includes(path.basename(shortcut.target.toLowerCase())) ||
      (await importsDll(shortcut.target, 'WS2_32.dll'))
    ) {
      shortcuts.push(shortcut);
      shortcutCache[shortcut.target.toLowerCase()] = shortcut;
    }
  }
}

async function updateApplicationCache(): Promise<void> {
  const shortcuts = Object.values(shortcutCache).concat(additionalShortcuts);

  await Promise.all(
    shortcuts.map(async (shortcut) => {
      const lowercaseTarget = shortcut.target.toLowerCase();
      if (applicationCache[lowercaseTarget] === undefined) {
        applicationCache[lowercaseTarget] = await convertToSplitTunnelingApplication(shortcut);
      }

      return applicationCache[lowercaseTarget];
    }),
  );
}

// Add excluded apps that are missing from the shortcut cache to it
async function addApplicationToAdditionalShortcuts(applicationPath: string): Promise<void> {
  if (
    shortcutCache[applicationPath.toLowerCase()] === undefined &&
    !additionalShortcuts.some(
      (shortcut) => shortcut.target.toLowerCase() === applicationPath.toLowerCase(),
    )
  ) {
    additionalShortcuts.push({
      target: applicationPath,
      name: (await getProgramName(applicationPath)) ?? path.parse(applicationPath).name,
    });
  }
}

// Fins all links in a directory.
async function findAllLinks(path: string): Promise<string[]> {
  if (path.endsWith('.lnk')) {
    return [path];
  } else {
    const stat = await fs.promises.stat(path);
    if (stat.isDirectory()) {
      const contents = await fs.promises.readdir(path);
      const result = await Promise.all(contents.map((item) => findAllLinks(`${path}/${item}`)));
      return result.flat();
    } else {
      return [];
    }
  }
}

function resolveLinks(linkPaths: string[]): ShortcutDetails[] {
  return linkPaths
    .map((link) => {
      try {
        return {
          ...shell.readShortcutLink(path.resolve(link)),
          name: path.parse(link).name,
        };
      } catch {
        return null;
      }
    })
    .filter(
      (shortcut): shortcut is ShortcutDetails =>
        shortcut !== null &&
        !shortcut.target.endsWith('Mullvad VPN.exe') &&
        shortcut.target.endsWith('.exe') &&
        !shortcut.target.toLowerCase().includes('install') && // Covers "uninstall" as well.
        !shortcut.name.toLowerCase().includes('install'),
    );
}

async function getProgramName(exePath: string): Promise<string | undefined> {
  try {
    return await getProductName(exePath);
  } catch {
    return undefined;
  }
}

// Removes all duplicate shortcuts.
function removeDuplicates(shortcuts: ShortcutDetails[]): ShortcutDetails[] {
  const unique = shortcuts.reduce((shortcuts, shortcut) => {
    const lowercaseTarget = shortcut.target.toLowerCase();
    if (shortcuts[lowercaseTarget]) {
      if (
        shortcuts[lowercaseTarget].args &&
        shortcuts[lowercaseTarget].args !== '' &&
        (!shortcut.args || shortcut.args === '')
      ) {
        shortcuts[lowercaseTarget] = shortcut;
      }
    } else {
      shortcuts[lowercaseTarget] = shortcut;
    }
    return shortcuts;
  }, {} as Record<string, ShortcutDetails>);

  return Object.values(unique);
}

async function convertToSplitTunnelingApplication(
  shortcut: ShortcutDetails,
): Promise<IApplication> {
  return {
    absolutepath: shortcut.target,
    name: shortcut.name,
    icon: await retrieveIcon(shortcut.target),
  };
}

async function retrieveIcon(exe: string) {
  const icon = await app.getFileIcon(exe, { size: 'large' });
  return icon.toDataURL();
}

// Checks if the application at the supplied path imports a specific dll.
async function importsDll(path: string, dllName: string): Promise<boolean> {
  let fileHandle: fs.promises.FileHandle;
  try {
    fileHandle = await fs.promises.open(path, fs.constants.O_RDONLY);
  } catch (e) {
    return false;
  }

  const imports = await getExeImports(fileHandle, path);
  await fileHandle.close();
  return imports.map((name) => name.toLowerCase()).includes(dllName.toLowerCase());
}

async function getExeImports(fileHandle: fs.promises.FileHandle, path: string): Promise<string[]> {
  try {
    const tableOffsetResult = await getTableOffset(fileHandle, IMAGE_DIRECTORY_ENTRY_IMPORT);
    if (tableOffsetResult) {
      const { offset: importTableOffset, rvaToOffset } = tableOffsetResult;
      const moduleNames = await getImportModuleNames(fileHandle, importTableOffset, rvaToOffset);
      return moduleNames;
    } else {
      return [];
    }
  } catch (e) {
    log.error(`Failed to read .exe import table for ${path}.`, e);
    return [];
  }
}

async function readString(
  fileHandle: fs.promises.FileHandle,
  offset: number,
  encoding: 'ascii' | 'ucs2',
): Promise<{ value: string; endOffset: number }> {
  const characterSize = getCharacterSize(encoding);
  const buffer = Buffer.alloc(characterSize);
  await fileHandle.read(buffer, 0, characterSize, offset);

  const nextOffset = offset + characterSize;
  if (buffer.every((value) => value === 0)) {
    return { value: '', endOffset: nextOffset };
  } else {
    const { value: nextValue, endOffset } = await readString(fileHandle, nextOffset, encoding);
    const value = buffer.toString(encoding) + nextValue;
    return { value, endOffset };
  }
}

function getCharacterSize(encoding: 'ascii' | 'ucs2'): number {
  switch (encoding) {
    case 'ascii':
      return 1;
    case 'ucs2':
      return 2;
  }
}

// Finds and returns the NT header.
async function getNtHeader(
  fileHandle: fs.promises.FileHandle,
): Promise<StructValue<ImageNtHeadersUnion>> {
  // Check whether or not the file follows the PE format.
  const dosHeader = await Value.fromFile(fileHandle, 0, DOS_HEADER);
  const eMagic = dosHeader.get<PrimitiveValue>('e_magic').value();
  if (eMagic !== 0x5a4d) {
    throw new Error('Not a PE file');
  }

  const ntHeaderOffset = dosHeader.get<PrimitiveValue>('e_lfanew').value();

  // Check if this is a 32- or 64-bit exe-file and return the correct datatype.
  const ntHeader32 = await Value.fromFile(fileHandle, ntHeaderOffset, IMAGE_NT_HEADERS);
  const signature = ntHeader32.get<PrimitiveValue>('Signature').buffer.toString('ascii');
  if (signature !== 'PE\0\0') {
    throw new Error('Not a PE file');
  }

  const magic = ntHeader32
    .get<StructValue<typeof IMAGE_OPTIONAL_HEADER32>>('OptionalHeader')
    .get<PrimitiveValue>('Magic')
    .value();

  // magic is 0x20b for 64-bit executables.
  return magic === 0x20b
    ? Value.fromFile(fileHandle, ntHeaderOffset, IMAGE_NT_HEADERS64)
    : ntHeader32;
}

// Reads the import table and returns a list of the imported DLLs.
async function getImportModuleNames(
  fileHandle: fs.promises.FileHandle,
  importTableOffset: number,
  rvaToOffset: RvaToOffset,
): Promise<string[]> {
  const moduleNames: string[] = [];
  const entrySize = Value.sizeOf(IMAGE_IMPORT_MODULE_DIRECTORY);

  // eslint-disable-next-line no-constant-condition
  for (let i = 0; true; i++) {
    const importEntry = await Value.fromFile(
      fileHandle,
      importTableOffset + i * entrySize,
      IMAGE_IMPORT_MODULE_DIRECTORY,
    );
    const nameRva = importEntry.get('ModuleName').value();

    if (nameRva !== 0x0) {
      const offset = await rvaToOffset(nameRva);

      const { value: name } = await readString(fileHandle, offset, 'ascii');
      moduleNames.push(name);
    } else {
      return moduleNames;
    }
  }
}

async function getProductName(path: string): Promise<string | undefined> {
  let fileHandle: fs.promises.FileHandle;
  try {
    fileHandle = await fs.promises.open(path, fs.constants.O_RDONLY);
  } catch {
    return undefined;
  }

  try {
    const getTableOffsetResult = await getTableOffset(fileHandle, IMAGE_DIRECTORY_ENTRY_RESOURCE);

    if (getTableOffsetResult) {
      const { offset: resourceTableOffset, rvaToOffset } = getTableOffsetResult;
      const leafOffsets = await getResourceTreeLeafOffsets(
        fileHandle,
        resourceTableOffset,
        resourceTableOffset,
        rvaToOffset,
        [[16], [1], [0, 1033]],
      );

      const productName = await leafOffsets.reduce(async (alreadyFoundValue, leafOffset) => {
        const value = await alreadyFoundValue;
        if (value) {
          return value;
        } else {
          const strings = await getVsVersionInfoStrings(fileHandle, leafOffset);
          return strings.get('FileDescription') ?? strings.get('ProductName');
        }
      }, Promise.resolve() as Promise<string | undefined>);

      return productName;
    } else {
      return undefined;
    }
  } catch {
    return undefined;
  } finally {
    await fileHandle.close();
  }
}

async function getTableOffset(
  fileHandle: fs.promises.FileHandle,
  tableIndex: number,
): Promise<{ offset: number; rvaToOffset: RvaToOffset } | undefined> {
  const ntHeader = await getNtHeader(fileHandle);
  const fileHeader = ntHeader.get<StructValue<typeof IMAGE_FILE_HEADER>>('FileHeader');
  const optionalHeader = ntHeader.get<StructValue<ImageOptionalHeaderUnion>>('OptionalHeader');

  const tableRva = optionalHeader
    .get<ArrayValue<typeof IMAGE_DATA_DIRECTORY>>('DataDirectory')
    .nth(tableIndex)
    .get('VirtualAddress')
    .value();

  if (tableRva === 0x0) {
    return undefined;
  }

  const numberOfSections = fileHeader.get<PrimitiveValue>('NumberOfSections').value();
  const ntHeaderEndOffset =
    ntHeader.offset +
    ntHeader.get<PrimitiveValue<typeof DWORD>>('Signature').size +
    fileHeader.size +
    fileHeader.get<PrimitiveValue>('SizeOfOptionalHeader').value();

  const rvaToOffset = (rva: number) =>
    rvaToOffsetImpl(fileHandle, rva, numberOfSections, ntHeaderEndOffset);

  const tableOffset = await rvaToOffset(tableRva);

  return { offset: tableOffset, rvaToOffset };
}

// Searches the resource tree for the supplied paths and returns the leaves at the end of those
// paths.
async function getResourceTreeLeafOffsets(
  fileHandle: fs.promises.FileHandle,
  sectionOffset: number,
  tableOffset: number,
  rvaToOffset: (rva: number) => Promise<number>,
  [ids, ...path]: number[][],
): Promise<number[]> {
  const table = await Value.fromFile(fileHandle, tableOffset, IMAGE_RESOURCE_DIRECTORY);

  const numberOfNameEntries = table.get('NumberOfNameEntries').value();
  const numberOfIdEntries = table.get('NumberOfIdEntries').value();

  const leaves: number[] = [];

  for (let i = numberOfNameEntries; i < numberOfNameEntries + numberOfIdEntries; i++) {
    const offset =
      tableOffset +
      Value.sizeOf(IMAGE_RESOURCE_DIRECTORY) +
      i * Value.sizeOf(IMAGE_RESOURCE_DIRECTORY_ID_ENTRY);
    const entry = await Value.fromFile(fileHandle, offset, IMAGE_RESOURCE_DIRECTORY_ID_ENTRY);

    const id = entry.get('Id').value();
    if (!ids.includes(id)) {
      continue;
    }

    let offsetToData = entry.get('OffsetToData').value();
    // If the first bit is 1 then the offset points to another node, otherwise it point to a leaf.
    const isLeaf = (offsetToData & 0x80000000) === 0;

    if (isLeaf && path.length === 0) {
      const leafDataOffset = await getResourceTreeLeafValueOffset(
        fileHandle,
        sectionOffset + offsetToData,
        rvaToOffset,
      );

      leaves.push(leafDataOffset);
    } else if (!isLeaf) {
      offsetToData &= 0x7fffffff;

      const subTreeLeaves = await getResourceTreeLeafOffsets(
        fileHandle,
        sectionOffset,
        sectionOffset + offsetToData,
        rvaToOffset,
        path,
      );

      leaves.push(...subTreeLeaves);
    } else {
      continue;
    }
  }

  return leaves;
}

// Finds the Strings structures within the VS_VERSIONINFO structure and returns the contents.
async function getVsVersionInfoStrings(
  fileHandle: fs.promises.FileHandle,
  offset: number,
): Promise<Map<string, string>> {
  try {
    const stringFileInfoOffset = await getVsVersionInfoChildrenOffset(fileHandle, offset);

    const stringTableOffset = await getChildrenOffset(
      fileHandle,
      stringFileInfoOffset,
      STRING_FILE_INFO,
      (szKey) => szKey === 'StringFileInfo',
    );
    const stringTable = await Value.fromFile(fileHandle, stringTableOffset, STRING_TABLE);
    const stringTableLength = stringTable.get<PrimitiveValue>('wLength').value();

    const stringsOffset = await getChildrenOffset(
      fileHandle,
      stringTableOffset,
      STRING_TABLE,
      (szKey) => szKey.substr(4).toLowerCase() === '04b0',
    );

    const strings = await parseStrings(
      fileHandle,
      stringsOffset,
      stringTableOffset + stringTableLength,
    );

    return strings;
  } catch {
    return new Map();
  }
}

// Loops through the list of strings and returns a map with the contents.
async function parseStrings(
  fileHandle: fs.promises.FileHandle,
  stringsOffset: number,
  stringTableEnd: number,
): Promise<Map<string, string>> {
  const strings = new Map<string, string>();

  let currentStringOffset = stringsOffset;
  while (currentStringOffset < stringTableEnd) {
    const stringValue = await Value.fromFile(fileHandle, currentStringOffset, STRING_TABLE_STRING);
    const valueSize = (stringValue.get('wValueLength').value() - 1) * 2;

    const szKeyOffset = currentStringOffset + stringValue.size;
    const { value: szKey, endOffset } = await readString(fileHandle, szKeyOffset, 'ucs2');

    const valueOffset = alignDword(endOffset);
    const { buffer } = await fileHandle.read(Buffer.alloc(valueSize), 0, valueSize, valueOffset);
    const value = buffer.toString('ucs2');

    strings.set(szKey, value);
    currentStringOffset += alignDword(stringValue.get<PrimitiveValue>('wLength').value());
  }

  return strings;
}

async function getResourceTreeLeafValueOffset(
  fileHandle: fs.promises.FileHandle,
  offset: number,
  rvaToOffset: (rva: number) => Promise<number>,
): Promise<number> {
  const leaf = await Value.fromFile(fileHandle, offset, IMAGE_RESOURCE_DIRECTORY_DATA_ENTRY);
  const valueRva = leaf.get<PrimitiveValue>('DataRVA').value();
  const valueOffset = await rvaToOffset(valueRva);

  return valueOffset;
}

// Finds the offset to the Children field in the VS_VERSIONINFO structure.
async function getVsVersionInfoChildrenOffset(fileHandle: fs.promises.FileHandle, offset: number) {
  const valueValueOffset = await getChildrenOffset(
    fileHandle,
    offset,
    VS_VERSIONINFO,
    (szKey) => szKey === 'VS_VERSION_INFO',
  );
  const versionInfo = await Value.fromFile(fileHandle, offset, VS_VERSIONINFO);
  const versionInfoValueLength = versionInfo.get<PrimitiveValue>('wValueLength').value();
  const valuePadding2Offset = valueValueOffset + versionInfoValueLength;
  const valueChildrenOffset = alignDword(valuePadding2Offset);

  return valueChildrenOffset;
}

// Finds the offset to the Children field in any of the STRING_FILE_INFO, STRING_TABLE and
// STRING_TABLE_STRING structures.
async function getChildrenOffset(
  fileHandle: fs.promises.FileHandle,
  offset: number,
  datatype: StructWrapper,
  validateSzKey?: (szKey: string) => boolean,
) {
  const szKeyOffset = offset + Value.sizeOf(datatype);
  const { value, endOffset } = await readString(fileHandle, szKeyOffset, 'ucs2');
  if (validateSzKey && !validateSzKey(value)) {
    throw new Error(`Invalid szKey "${value}"`);
  }

  return alignDword(endOffset);
}

function alignDword(offset: number): number {
  return Math.ceil(offset / 4) * 4;
}