@opscompass/opscompass-cli 1.0.36 → 1.0.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,545 @@
1
+ /* ---------------------------------------------------------------------------
2
+ # File Name : data gathering - maskValues.js
3
+ #
4
+ # Programmer: Michael Stone
5
+ #
6
+ # Library to allow for masking of sensitive values
7
+ #
8
+ # Modification History:
9
+ # 2024-10-09 mss: Initial revision
10
+ #
11
+ #--------------------------------------------------------------------------- */
12
+
13
+ "use strict";
14
+
15
+ const fs = require("fs");
16
+ const path = require("path");
17
+ const { utilsModule: utils } = require("./utils");
18
+ const { opscompassHome } = require("../environment/current"); // For compatibility with the OpsCompass CLI
19
+
20
+ // Resources to check for sensitive attributes
21
+ const maskTypes = {
22
+ md5: "md5",
23
+ sha256: "sha256",
24
+ };
25
+
26
+ /**
27
+ * Return a sqlite3 db object (create if necessary)
28
+ */
29
+ const sqlite3 = require("sqlite3").verbose();
30
+ class MaskDb {
31
+ company = undefined;
32
+ db = undefined;
33
+ getDb() {
34
+ return this.db;
35
+ }
36
+
37
+ dbFilePath = undefined;
38
+ getFilePath() {
39
+ return this.dbFilePath;
40
+ }
41
+
42
+ maskColumns = [
43
+ { name: "name", type: "TEXT NOT NULL UNIQUE", index: "mask_name_idx" },
44
+ { name: "value", type: "TEXT NOT NULL", index: "mask_value_idx" },
45
+ ];
46
+
47
+ constructor(dbFileName, company = global?.company || "unspecified-company") {
48
+ this.company = company;
49
+ this.dbFilePath = path.join(opscompassHome, "configs", company, dbFileName);
50
+ // It is possible that this will be the first time we need that directory
51
+ fs.mkdirSync(path.dirname(this.dbFilePath), { recursive: true });
52
+
53
+ return new Promise((resolve, reject) => {
54
+ this.db = new sqlite3.Database(this.dbFilePath, (err) => {
55
+ if (err) {
56
+ reject("Could not connect to database", err);
57
+ } else {
58
+ // console.log("Connected to database");
59
+ this.createTable("mask", this.maskColumns)
60
+ .then(() => {
61
+ // console.log("Table and indexes created successfully");
62
+ resolve(this);
63
+ })
64
+ .catch((err) => reject("Could not create tables", err));
65
+ }
66
+ });
67
+ });
68
+ }
69
+
70
+ async createTable(tableName, columns) {
71
+ return new Promise((resolve, reject) => {
72
+ const columnsDefinition = columns
73
+ .map((column) => {
74
+ let definition = `${column.name} ${column.type} NOT NULL`;
75
+ return definition;
76
+ })
77
+ .join(", ");
78
+
79
+ const sql = `CREATE TABLE IF NOT EXISTS ${tableName} (${columnsDefinition})`;
80
+
81
+ this.db.run(sql, (err) => {
82
+ if (err) {
83
+ reject(`Could not create table ${tableName}: ${err}`);
84
+ } else {
85
+ // console.log(`Table ${tableName} created or already exists`);
86
+ resolve();
87
+ }
88
+ });
89
+ }).then(async () => {
90
+ // console.log("Creating indexes...");
91
+ await this.createIndexes(tableName, columns);
92
+ });
93
+ }
94
+
95
+ async createIndexes(tableName, columns) {
96
+ const indexPromises = columns.map((column) => {
97
+ if (column.index) {
98
+ const indexSql = `CREATE INDEX IF NOT EXISTS idx_${tableName}_${column.name} ON ${tableName} (${column.name})`;
99
+ return new Promise((resolve, reject) => {
100
+ this.db.run(indexSql, (err) => {
101
+ if (err) {
102
+ reject(`Could not create index on ${column.name}: ${err}`);
103
+ } else {
104
+ // console.log(`Index on ${column.name} created or already exists`);
105
+ resolve();
106
+ }
107
+ });
108
+ });
109
+ }
110
+ return Promise.resolve();
111
+ });
112
+ return Promise.all(indexPromises);
113
+ }
114
+
115
+ dumpTable(tableName, mask = undefined) {
116
+ const maskType = path.basename(this.dbFilePath).split("-")[1];
117
+ const sql =
118
+ `SELECT * FROM ${tableName}` +
119
+ (mask ? ` WHERE value = '${mask}'` : "") +
120
+ " ORDER BY name DESC";
121
+ this.db.all(sql, [], (err, rows) => {
122
+ if (err) {
123
+ console.error(`Could not retrieve data from table ${tableName}:`, err);
124
+ } else {
125
+ console.error(`\nContents of ${tableName} table (${this.dbFilePath}):`);
126
+ console.log(`{\n "${path.basename(this.dbFilePath)}": [`);
127
+ let rowCt = 0;
128
+ rows.forEach((row) => {
129
+ row.mask = `oc$mask-${maskType}:{${row.value}}`;
130
+ console.log(
131
+ " ",
132
+ process.stdout.isTTY ? row : JSON.stringify(row),
133
+ ++rowCt < rows.length ? "," : ""
134
+ );
135
+ });
136
+ console.log(" ]\n}\n");
137
+ }
138
+ });
139
+ }
140
+
141
+ close() {
142
+ this.db.close((err) => {
143
+ if (err) {
144
+ console.error("Could not close the database", err);
145
+ } else {
146
+ // console.log("Database connection closed");
147
+ }
148
+ });
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Process arguments for the maskValues module
154
+ */
155
+ function processArgs(action, args) {
156
+ let maskType = undefined;
157
+
158
+ if (!action) {
159
+ return printHelp("action must be specified");
160
+ }
161
+
162
+ // Determine the type of mask we are going to use
163
+ let maskTest = args.indexOf("--type");
164
+ if (maskTest < 0) {
165
+ switch (action.toLowerCase()) {
166
+ case "help":
167
+ printHelp();
168
+ process.exit(0);
169
+ // case "get": // not meant to call directly
170
+ case "lookup":
171
+ // The type is after the '-' in oc$mask-{type}
172
+ const matchResult = args[0].match(/.*-(.+):{(.*)}/);
173
+ if (!matchResult) {
174
+ return printHelp("invalid mask format");
175
+ }
176
+ const testMask = matchResult.splice(1);
177
+ maskType = maskTypes[testMask[0]];
178
+ if (!maskType) {
179
+ return printHelp(`unknown mask type (${testMask[0]})`);
180
+ }
181
+ break;
182
+ case "set":
183
+ case "dumptable":
184
+ case "dump-table":
185
+ // Special case for dumpTable allow property=hash (as specified in defaults.maskValues)
186
+ if (action.startsWith("dump")) {
187
+ maskType = maskTypes[args[0].split("=")[1]];
188
+ break;
189
+ }
190
+ return printHelp(`mask type must be provided for ${action}`);
191
+ default:
192
+ return printHelp(`unknown action (${action})`);
193
+ }
194
+ } else {
195
+ maskType = maskTypes[args[maskTest + 1]];
196
+ if (maskType) args.splice(maskTest, 2);
197
+ }
198
+
199
+ if (!maskType) {
200
+ return printHelp(`unknown mask type (${args[maskTest + 1]})`);
201
+ }
202
+
203
+ // console.log(
204
+ // `processArgs (${action}): maskType = ${maskType}\n args =`,
205
+ // args
206
+ // );
207
+ return maskType;
208
+ }
209
+
210
+ /**
211
+ * Print the help message for the maskValues module
212
+ */
213
+ function printHelp(errMsg) {
214
+ console.error("Actions available for maskValues:\n");
215
+ console.error(
216
+ " dumpTable:",
217
+ "dumps the mask table for the specified property"
218
+ );
219
+ console.error(" lookup:", "gets a value from mask");
220
+ console.error(" set:", "sets a value to mask");
221
+ console.error(
222
+ "\nParameters:\n",
223
+ " --type (",
224
+ Object.keys(maskTypes).join(" | "),
225
+ ")\t[required]\n",
226
+ " property[=value]\t[required]\n"
227
+ );
228
+ if (errMsg) {
229
+ console.error("\nERROR:", errMsg);
230
+ console.error();
231
+ process.exit(255);
232
+ }
233
+ console.error();
234
+ }
235
+
236
+ /**
237
+ * Extract server name from a server spec
238
+ * @param {string} serverSpec - The server spec
239
+ * @returns {string} - The server name
240
+
241
+ * Examples:
242
+ * SQL Server: [protocol:]server[\instance_name][,port]
243
+ * Oracle: [[protocol:]//]server[:port][/[service_name][:server_type][/instance_name]]
244
+ */
245
+ function getServerName(serverSpec) {
246
+ // The regex ^(?:[^:\/]+:)?(?:\/\/)?([^:\/\\,]+) works as follows:
247
+ // ^(?:[^:\/]+:)?: Optionally matches the protocol part, which can be followed by a colon.
248
+ // (?:\/\/)?: Optionally matches the //.
249
+ // ([^:\/\\,]+): Captures the server portion, which is the first part that doesn’t include :, /, \, or ,.
250
+ const regex = /^(?:[^:\/]+:)?(?:\/\/)?([^:\/\\,]+)/;
251
+ const match = serverSpec.match(regex);
252
+ const serverName = match ? match[1] : null;
253
+
254
+ // Make sure we're not dealing with an already masked value
255
+ if (serverSpec.startsWith("oc$mask-")) {
256
+ return printHelp(`masked value found for serverName (${serverSpec})`);
257
+ }
258
+
259
+ // Return an object with the server name and short name
260
+ let shortName = serverName;
261
+ if (!utils.isIPv4(serverName)) {
262
+ shortName = serverName.split(".")[0];
263
+ }
264
+ return {
265
+ serverSpec: serverSpec,
266
+ serverName: serverName,
267
+ shortName: shortName,
268
+ };
269
+ }
270
+ // Test some examples of server syntax:
271
+ // for (const test of [
272
+ // "protocol:server\\instance_name,port",
273
+ // "protocol://server:port/service_name:server_type/instance_name",
274
+ // "server\\instance_name,port",
275
+ // "//server:port/service_name:server_type/instance_name",
276
+ // ]) {
277
+ // console.error(` test (${test}): ${getServerName(test)}`);
278
+ // }
279
+ // process.exit(0);
280
+
281
+ /**
282
+ * Dump the mask table, args should contain the property[=type], eg. server[=md5]
283
+ * where property is the name of the property to mask
284
+ *
285
+ * maskType and property determine the name of the file (eg. mask-md5-server)
286
+ *
287
+ * It was thought to be able to pass more than one arg, but
288
+ * currently only uses the first one, and relies on maskType to be set
289
+ * by the caller
290
+ * @param {Array} args - The arguments for the action
291
+ */
292
+ async function dumpMaskTable(maskType, args) {
293
+ const [prop, value] = args[0].split("=");
294
+ const dbname = `mask-${maskType}-${prop}`;
295
+ const maskDb = await new MaskDb(dbname).then((db) => {
296
+ // console.log("db opened:", db);
297
+ return db;
298
+ });
299
+ maskDb.dumpTable("mask");
300
+ }
301
+
302
+ /**
303
+ * Lookup the specified value and dump matching records
304
+ * @param {Array} args - The arguments for the action
305
+ */
306
+ async function lookupMask(maskType, args) {
307
+ const [prop, value] = args[0].split("=");
308
+ const dbname = `mask-${maskType}-${prop}`;
309
+
310
+ // The type is after the '-' in oc$mask-{type} and should match the maskType
311
+ const testMask = value.match(/.*-(.+):{(.*)}/).splice(1);
312
+ if (testMask.length !== 2 || testMask[0] !== maskType) {
313
+ return printHelp(`invalid property value (${args[0]})`);
314
+ }
315
+
316
+ const maskDb = await new MaskDb(dbname).then((db) => {
317
+ // console.log("db opened:", db);
318
+ return db;
319
+ });
320
+ maskDb.dumpTable("mask", testMask[1]);
321
+ }
322
+
323
+ /**
324
+ * Get the masked value for the given setting
325
+ * @param {Array} args - The arguments for the action
326
+ */
327
+ async function getMask(maskType, args) {
328
+ if (args.length === 0 || args[0].indexOf("=") < 0) {
329
+ return printHelp("no property=value provided");
330
+ }
331
+ const [prop, value] = args[0].split("=");
332
+ const dbname = `mask-${maskType}-${prop}`;
333
+ // console.error(`getMask (${maskType}): ${prop} = ${value}`);
334
+
335
+ // The type is after the '-' in oc$mask-{type} and should match the maskType
336
+ const testMask = value.match(/.*-(.+):{(.*)}/).splice(1);
337
+ if (testMask.length !== 2 || testMask[0] !== maskType) {
338
+ return printHelp(`invalid property value (${args[0]})`);
339
+ }
340
+
341
+ const maskDb = await new MaskDb(dbname).then((db) => {
342
+ // console.log("db opened:", db);
343
+ return db;
344
+ });
345
+ const unmaskedValue = await new Promise((resolve, reject) => {
346
+ maskDb.db.get(
347
+ // This only seems to get the first row, not all rows, so we get the longest name
348
+ `SELECT name FROM mask WHERE value = ? ORDER BY name DESC`,
349
+ [testMask[1]],
350
+ (err, row) => {
351
+ if (err) {
352
+ reject(`Could not retrieve data from table mask: ${err}`);
353
+ } else {
354
+ resolve(row ? row.name : `unknown-${maskType}`);
355
+ }
356
+ }
357
+ );
358
+ });
359
+ // This function is called during get-monitoring-configuration --asFile, so we do
360
+ // not want to print the message because it will mess up the JSON output
361
+ // console.error(`${prop}: ${unmaskedValue}`);
362
+ return unmaskedValue;
363
+ }
364
+
365
+ /**
366
+ * Set the masked value for the given setting
367
+ * @param {Array} args - The arguments for the action
368
+ */
369
+ async function setMask(maskType, args) {
370
+ const [prop, value] = args[0].split("=");
371
+ const dbname = `mask-${maskType}-${prop}`;
372
+ let maskString = value;
373
+
374
+ // Determine the mask function to use
375
+ let maskFn = undefined;
376
+ switch (maskType) {
377
+ case maskTypes.md5:
378
+ maskFn = utils.md5sum;
379
+ break;
380
+ case maskTypes.sha256:
381
+ maskFn = utils.sha256sum;
382
+ break;
383
+ default:
384
+ return printHelp(`unknown mask type (${maskType})`);
385
+ }
386
+ console.error(`masking value (${maskType}): ${prop}=${value}`);
387
+
388
+ const maskDb = await new MaskDb(dbname).then((db) => {
389
+ // console.log("db opened:", db);
390
+ return db;
391
+ });
392
+
393
+ let maskValue = undefined;
394
+ switch (prop) {
395
+ case "server":
396
+ const server = getServerName(value);
397
+
398
+ maskValue = maskFn(server.shortName.toLowerCase());
399
+ maskString = `oc$mask-${maskType}:{${maskValue}}`;
400
+ // console.error(
401
+ // `setMask (${maskType}): ${prop} =`,
402
+ // JSON.stringify(server, null, 2) + " in database:",
403
+ // dbname
404
+ // );
405
+
406
+ // Insert or update value in the mask table
407
+ await maskDb.db.run(
408
+ `INSERT INTO mask(name, value) VALUES(?, ?)
409
+ ON CONFLICT(name)
410
+ DO UPDATE SET value=excluded.value;`,
411
+ [server.serverName, maskValue]
412
+ );
413
+ // Save the short name as well
414
+ if (server.serverName !== server.shortName) {
415
+ await maskDb.db.run(
416
+ `INSERT INTO mask(name, value) VALUES(?, ?)
417
+ ON CONFLICT(name)
418
+ DO UPDATE SET value=excluded.value;`,
419
+ [server.shortName, maskValue]
420
+ );
421
+ }
422
+ maskDb.close();
423
+
424
+ // If the value contained more information we need to save that too
425
+ if (value === server.serverName) {
426
+ console.log(`${server.serverSpec}:`, maskString);
427
+ return maskString;
428
+ }
429
+ // Intentional fall throught: we want to save the original value as well
430
+ default:
431
+ maskValue = maskFn(value);
432
+ maskString = `oc$mask-${maskType}:{${maskValue}}`;
433
+
434
+ // Insert or update value in the mask table
435
+ await maskDb.db.run(
436
+ `INSERT INTO mask(name, value) VALUES(?, ?)
437
+ ON CONFLICT(name)
438
+ DO UPDATE SET value=excluded.value;`,
439
+ [value, maskValue]
440
+ );
441
+ }
442
+ console.log(`${value}:`, maskString);
443
+ return maskString;
444
+ }
445
+
446
+ /**
447
+ * Function to mask local values in a configuration object
448
+ * This modifies the original object
449
+ *
450
+ * @param {} obj
451
+ * @returns void
452
+ */
453
+ async function maskObjValues(obj) {
454
+ // if (this) console.error("masking object:\n", JSON.stringify(obj, null, 2));
455
+ if (global.valuesMask && global.valuesMask.length > 0) {
456
+ // Recurse through all properties
457
+ for (let k in obj) {
458
+ if (typeof obj[k] === "undefined") continue;
459
+ if (typeof obj[k] === "object") {
460
+ await maskObjValues(obj[k]);
461
+ } else {
462
+ // if the value is supposed to be masked, encrypt it
463
+ for (const maskProperty of global.valuesMask.filter((mask) => {
464
+ // console.error(
465
+ // `Comparing "${k}" (${typeof k}) === "${
466
+ // mask.property
467
+ // }" (${typeof mask.property}):`,
468
+ // k === mask.property
469
+ // );
470
+ return k === mask.property;
471
+ })) {
472
+ // console.error(`Masking: ${k}=${obj[k]}`);
473
+ obj[k] = await setMask(maskProperty.maskType, [`${k}=${obj[k]}`]);
474
+ }
475
+ }
476
+ }
477
+ // // If we are at the top level, print the masked object
478
+ // if (this) {
479
+ // console.error("masked object:\n", JSON.stringify(obj, null, 2));
480
+ // // process.exit(0);
481
+ // }
482
+ }
483
+ }
484
+
485
+ /**
486
+ * Function to resolve locally masked values in a configuration object
487
+ * This modifies the original object
488
+ *
489
+ * @param {} obj
490
+ * @returns void
491
+ */
492
+ async function unmaskObjValues(obj) {
493
+ // Recurse through all properties of obj
494
+ for (const k in obj) {
495
+ if (typeof obj[k] === "object") {
496
+ await unmaskObjValues(obj[k]);
497
+ } else {
498
+ // if the value is an encrypted string, decrypt it
499
+ if (typeof obj[k] === "string" && obj[k].match(/^oc\$mask-/)) {
500
+ const match = obj[k].match(/^oc\$mask-(.+):/);
501
+ const maskType = match ? match[1] : null;
502
+ if (maskType) {
503
+ obj[k] = await getMask(maskType, [`${k}=${obj[k]}`]);
504
+ }
505
+ }
506
+ }
507
+ }
508
+ }
509
+
510
+ /** maskValues module
511
+ * @param {string} action - The action to perform
512
+ * @param {Array} args - The arguments for the action
513
+ * @returns {void}
514
+ */
515
+ let maskValues = (action, ...args) => {
516
+ const maskType = processArgs(action, args);
517
+ // console.log(`maskValues (${action}):`, args);
518
+
519
+ if (action === undefined) return printHelp();
520
+ switch (action.toLowerCase()) {
521
+ case "help":
522
+ return printHelp();
523
+ case "lookup":
524
+ return lookupMask(maskType, args);
525
+ case "set":
526
+ return setMask(maskType, args);
527
+ // "get" is not meant to be called interactively
528
+ // case "get":
529
+ // return getMask(maskType as any, args);
530
+ case "dumptable":
531
+ case "dump-table":
532
+ return dumpMaskTable(maskType, args);
533
+ }
534
+ };
535
+
536
+ maskValues.requiresLogin = false;
537
+
538
+ maskValues.printHelp = printHelp;
539
+ maskValues.setMask = setMask;
540
+ maskValues.getMask = getMask;
541
+ maskValues.maskTypes = maskTypes;
542
+ maskValues.maskObjValues = maskObjValues;
543
+ maskValues.unmaskObjValues = unmaskObjValues;
544
+
545
+ module.exports = maskValues;