@arifbiswas/git-pre-push 1.0.18 → 1.0.20
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.
- package/README.md +199 -323
- package/bin/cli.js +14 -0
- package/package.json +1 -1
- package/src/advancedScanner.js +6 -0
- package/src/archive.js +352 -0
- package/src/envGuard.js +262 -0
- package/src/fullScanner.js +371 -0
- package/src/index.js +42 -0
- package/src/malwareCleaner.js +4 -3
- package/src/menu.js +52 -43
- package/src/reporter.js +1 -1
- package/src/utils/git.js +2 -2
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Full Scan: scans EVERYTHING in a folder, not only git repositories.
|
|
3
|
+
*
|
|
4
|
+
* gitsafty full-scan <folder> [--clean] [--json]
|
|
5
|
+
*
|
|
6
|
+
* - every file in every sub-folder, git repository or not
|
|
7
|
+
* - inside archives (zip, jar, apk, ipa, vsix, tar, tar.gz, gz, 7z, rar, ...),
|
|
8
|
+
* also archives inside archives, read in memory (nothing is extracted)
|
|
9
|
+
* - git persistence tricks in every repository it passes (.git/hooks, config)
|
|
10
|
+
* - IDE auto-run tasks and disguised / executable file names
|
|
11
|
+
*
|
|
12
|
+
* Dependency folders (node_modules, composer vendor, Pods, virtualenvs, package
|
|
13
|
+
* caches ...) are skipped: they are downloaded packages, not your code.
|
|
14
|
+
*
|
|
15
|
+
* Confirmed malware is removed only with --clean:
|
|
16
|
+
* loose file -> repaired or removed (backup kept)
|
|
17
|
+
* inside archive -> the whole archive is moved to quarantine (backup kept),
|
|
18
|
+
* because an archive can't be safely rewritten
|
|
19
|
+
* Backups go to ~/.gitsafty/quarantine/<time>/ (read-only), with report.json.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const fs = require('fs');
|
|
23
|
+
const os = require('os');
|
|
24
|
+
const path = require('path');
|
|
25
|
+
const { detectMalware, sha256, CONFIRMED } = require('./rules/malware');
|
|
26
|
+
const { checkFilename } = require('./rules/filenames');
|
|
27
|
+
const { inspectIdeConfig } = require('./rules/ideConfig');
|
|
28
|
+
const { gitPersistenceFindings } = require('./advancedScanner');
|
|
29
|
+
const { removeConfirmedMalware, notifyDesktop } = require('./malwareCleaner');
|
|
30
|
+
const { walkArchive, detectArchiveType } = require('./archive');
|
|
31
|
+
const { colors } = require('./reporter');
|
|
32
|
+
|
|
33
|
+
// Downloaded packages and caches: never scanned by Full Scan.
|
|
34
|
+
const DEPENDENCY_DIRS = new Set([
|
|
35
|
+
'node_modules', 'bower_components', 'jspm_packages', '.pnpm-store', '.yarn', '.npm', '.bun',
|
|
36
|
+
'vendor', // composer (PHP), bundler, go
|
|
37
|
+
'Pods', 'Carthage', '.gradle', '.m2', '.ivy2', '.dart_tool', '.pub-cache', '.pub',
|
|
38
|
+
'.venv', 'venv', 'site-packages', '__pycache__', '.tox', '.mypy_cache', '.pytest_cache',
|
|
39
|
+
'.nuget', '.cargo', '.rustup', '.cache', 'DerivedData', '.expo', '.next', '.nuxt',
|
|
40
|
+
'.turbo', '.parcel-cache', '.svelte-kit', '.angular', '.git',
|
|
41
|
+
// GitSafty's own quarantine (backups of removed malware) and the trash
|
|
42
|
+
'.gitsafty', 'gitsafty-quarantine', '.Trash', '$RECYCLE.BIN'
|
|
43
|
+
]);
|
|
44
|
+
// Package manager files: lock files and manifests of dependencies, not code that runs.
|
|
45
|
+
const PACKAGE_FILES = new Set([
|
|
46
|
+
'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb', 'npm-shrinkwrap.json',
|
|
47
|
+
'composer.lock', 'Gemfile.lock', 'Podfile.lock', 'Cargo.lock', 'poetry.lock', 'Pipfile.lock',
|
|
48
|
+
'pubspec.lock', 'go.sum', 'packages.lock.json', 'gradle.lockfile', 'mix.lock', 'flake.lock'
|
|
49
|
+
]);
|
|
50
|
+
// document.pdf.exe style names, and Windows script/screensaver types that are almost only used by malware.
|
|
51
|
+
const DECEPTIVE_NAME = /\.(pdf|docx?|xlsx?|pptx?|txt|jpe?g|png|gif|mp4|mp3|zip|rar)\.(exe|scr|com|bat|cmd|vbs|js|jse|ps1|hta|lnk)$|\.(scr|pif|cpl|hta|vbe|jse|wsf)$/i;
|
|
52
|
+
const KNOWN_GOOD_SCRIPTS = new Set(['gradlew.bat', 'mvnw.cmd', 'gradlew', 'mvnw']);
|
|
53
|
+
|
|
54
|
+
const MAX_FILE = 32 * 1024 * 1024;
|
|
55
|
+
const MAX_ARCHIVE = 1024 * 1024 * 1024;
|
|
56
|
+
|
|
57
|
+
function home() {
|
|
58
|
+
return process.env.HOME || process.env.USERPROFILE || os.homedir();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function isWin() {
|
|
62
|
+
return process.platform === 'win32';
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function skipEntry(inner) {
|
|
66
|
+
const norm = inner.replace(/\\/g, '/');
|
|
67
|
+
return PACKAGE_FILES.has(norm.split('/').pop()) || norm.split('/').slice(0, -1).some(s => DEPENDENCY_DIRS.has(s));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function readHead(full, n = 512) {
|
|
71
|
+
let fd;
|
|
72
|
+
try {
|
|
73
|
+
fd = fs.openSync(full, 'r');
|
|
74
|
+
const b = Buffer.alloc(n);
|
|
75
|
+
const len = fs.readSync(fd, b, 0, n, 0);
|
|
76
|
+
return b.subarray(0, len);
|
|
77
|
+
} catch (_) {
|
|
78
|
+
return null;
|
|
79
|
+
} finally {
|
|
80
|
+
if (fd !== undefined) try { fs.closeSync(fd); } catch (_) {}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Findings for one piece of content (loose file or archive entry). */
|
|
85
|
+
function inspectContent(displayPath, innerPath, buf, { names = true } = {}) {
|
|
86
|
+
const out = [];
|
|
87
|
+
for (const f of detectMalware(innerPath, buf)) out.push({ category: 'malware', ...f, filePath: displayPath });
|
|
88
|
+
const base = innerPath.split('/').pop();
|
|
89
|
+
// Only names that are almost never legitimate: plain .exe/.dll/.bin are normal in downloads and app bundles.
|
|
90
|
+
const nameRule = names && !KNOWN_GOOD_SCRIPTS.has(base) ? checkFilename(innerPath) : null;
|
|
91
|
+
if (nameRule && (DECEPTIVE_NAME.test(base) || /^Known malicious/.test(nameRule.rule))) {
|
|
92
|
+
out.push({ category: 'file', verdict: 'SUSPECT', severity: 'CRITICAL', name: nameRule.rule, description: 'Disguised or known-malicious file name.', filePath: displayPath });
|
|
93
|
+
}
|
|
94
|
+
const norm = innerPath.replace(/\\/g, '/');
|
|
95
|
+
if (/(^|\/)\.vscode\/(tasks|settings)\.json$/.test(norm) || /(^|\/)\.idea\/workspace\.xml$/.test(norm)) {
|
|
96
|
+
for (const f of inspectIdeConfig(innerPath, buf.toString('utf8'))) {
|
|
97
|
+
out.push({ category: 'ide', verdict: 'SUSPECT', ...f, filePath: displayPath });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Scans a folder. Pure: nothing is changed.
|
|
105
|
+
* @returns {object} result
|
|
106
|
+
*/
|
|
107
|
+
function fullScan(root, { onProgress } = {}) {
|
|
108
|
+
const abs = path.resolve(root);
|
|
109
|
+
const result = {
|
|
110
|
+
root: abs,
|
|
111
|
+
files: 0,
|
|
112
|
+
archives: [],
|
|
113
|
+
repos: [],
|
|
114
|
+
skippedDirs: 0,
|
|
115
|
+
tooLarge: [],
|
|
116
|
+
unreadable: 0,
|
|
117
|
+
findings: []
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const walk = (dir) => {
|
|
121
|
+
let entries;
|
|
122
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) { result.unreadable++; return; }
|
|
123
|
+
if (entries.some(e => e.name === '.git')) {
|
|
124
|
+
result.repos.push(dir);
|
|
125
|
+
const rel = path.relative(abs, dir).replace(/\\/g, '/');
|
|
126
|
+
for (const f of gitPersistenceFindings(dir)) {
|
|
127
|
+
result.findings.push({ ...f, filePath: rel ? `${rel}/${f.filePath}` : f.filePath, repo: dir });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
for (const e of entries) {
|
|
131
|
+
if (e.isSymbolicLink()) continue;
|
|
132
|
+
const full = path.join(dir, e.name);
|
|
133
|
+
if (e.isDirectory()) {
|
|
134
|
+
if (DEPENDENCY_DIRS.has(e.name)) {
|
|
135
|
+
if (e.name !== '.git' && e.name !== '.gitsafty' && e.name !== 'gitsafty-quarantine') result.skippedDirs++;
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
walk(full);
|
|
139
|
+
} else if (e.isFile()) {
|
|
140
|
+
if (PACKAGE_FILES.has(e.name)) continue;
|
|
141
|
+
scanFile(full);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
const scanFile = (full) => {
|
|
147
|
+
const rel = path.relative(abs, full).replace(/\\/g, '/');
|
|
148
|
+
let st;
|
|
149
|
+
try { st = fs.statSync(full); } catch (_) { result.unreadable++; return; }
|
|
150
|
+
if (!st.size) return;
|
|
151
|
+
result.files++;
|
|
152
|
+
if (onProgress && result.files % 200 === 0) onProgress(result);
|
|
153
|
+
|
|
154
|
+
const head = readHead(full);
|
|
155
|
+
if (!head) { result.unreadable++; return; }
|
|
156
|
+
const type = detectArchiveType(head, full);
|
|
157
|
+
const limit = type ? MAX_ARCHIVE : MAX_FILE;
|
|
158
|
+
if (st.size > limit) { result.tooLarge.push(rel); return; }
|
|
159
|
+
|
|
160
|
+
let buf;
|
|
161
|
+
try { buf = fs.readFileSync(full); } catch (_) { result.unreadable++; return; }
|
|
162
|
+
result.findings.push(...inspectContent(rel, rel, buf));
|
|
163
|
+
|
|
164
|
+
if (!type) return;
|
|
165
|
+
if (/\.(docx|xlsx|pptx|odt|ods|odp|epub)$/i.test(full) && st.size > 64 * 1024 * 1024) return;
|
|
166
|
+
const before = result.findings.length;
|
|
167
|
+
const stats = walkArchive(buf, path.basename(full), (inner, data) => {
|
|
168
|
+
const innerName = inner.split('!/').pop();
|
|
169
|
+
result.findings.push(...inspectContent(`${rel}!/${inner}`, innerName, data).map(f => ({ ...f, archive: rel })));
|
|
170
|
+
}, { skipEntry });
|
|
171
|
+
const own = result.findings.slice(before);
|
|
172
|
+
result.archives.push({
|
|
173
|
+
path: rel,
|
|
174
|
+
type: stats.type,
|
|
175
|
+
entries: stats.entries,
|
|
176
|
+
scanned: stats.scanned,
|
|
177
|
+
encrypted: stats.encrypted,
|
|
178
|
+
problems: stats.problems,
|
|
179
|
+
sha256: sha256(buf),
|
|
180
|
+
malware: own.filter(f => f.verdict === CONFIRMED).length
|
|
181
|
+
});
|
|
182
|
+
// Password-protected archives with programs inside: a common way to sneak malware past scanners.
|
|
183
|
+
const risky = stats.encrypted.filter(n => /\.(exe|scr|com|bat|cmd|ps1|vbs|js|jse|hta|msi|dll|lnk|jar|apk|sh|py)$/i.test(n));
|
|
184
|
+
if (risky.length) {
|
|
185
|
+
result.findings.push({
|
|
186
|
+
category: 'archive', verdict: 'SUSPECT', severity: 'CRITICAL', archive: rel, filePath: rel,
|
|
187
|
+
name: 'Password-protected archive with programs inside',
|
|
188
|
+
description: `Could not be scanned (encrypted): ${risky.slice(0, 3).join(', ')}${risky.length > 3 ? ' …' : ''}. Malware is often sent like this. Do not open it unless you trust the sender.`
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
const st = fs.statSync(abs);
|
|
194
|
+
if (st.isFile()) scanFile(abs); else walk(abs);
|
|
195
|
+
return result;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Copies a file to the quarantine folder (read-only) and deletes it. */
|
|
199
|
+
function quarantineWhole(full, rel, quarantineDir) {
|
|
200
|
+
const target = path.join(quarantineDir, 'files', `${rel.replace(/\.\./g, '_')}.quarantined`);
|
|
201
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
202
|
+
fs.copyFileSync(full, target);
|
|
203
|
+
try { fs.chmodSync(target, 0o400); } catch (_) {}
|
|
204
|
+
fs.unlinkSync(full);
|
|
205
|
+
return target;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Removes confirmed malware found by fullScan().
|
|
210
|
+
* @returns {{ quarantineDir: string|null, results: Array<{file, action, ok, error?}> }}
|
|
211
|
+
*/
|
|
212
|
+
function removeFullScanMalware(result) {
|
|
213
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
214
|
+
const quarantineDir = path.join(home(), '.gitsafty', 'quarantine', `full-scan-${stamp}`);
|
|
215
|
+
const confirmed = result.findings.filter(f => f.verdict === CONFIRMED && f.category === 'malware');
|
|
216
|
+
const results = [];
|
|
217
|
+
|
|
218
|
+
// 1. Archives with malware inside: quarantine the whole archive.
|
|
219
|
+
const archives = [...new Set(confirmed.filter(f => f.archive).map(f => f.archive))];
|
|
220
|
+
for (const rel of archives) {
|
|
221
|
+
const full = path.join(result.root, rel);
|
|
222
|
+
try {
|
|
223
|
+
const backup = quarantineWhole(full, rel, quarantineDir);
|
|
224
|
+
results.push({ file: rel, action: 'archive-quarantined', ok: true, backup });
|
|
225
|
+
} catch (err) {
|
|
226
|
+
results.push({ file: rel, action: 'failed', ok: false, error: err.message });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// 2. Loose files: same repair engine as clone/pull (strip, remove task/script, or remove file).
|
|
231
|
+
const loose = [...new Set(confirmed.filter(f => !f.archive && !archives.includes(f.filePath)).map(f => f.filePath))];
|
|
232
|
+
if (loose.length) {
|
|
233
|
+
const r = removeConfirmedMalware(loose, result.root, { reason: 'full-scan', quarantineDir });
|
|
234
|
+
results.push(...r.results);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
if (results.length) {
|
|
238
|
+
fs.mkdirSync(quarantineDir, { recursive: true });
|
|
239
|
+
const reportPath = path.join(quarantineDir, 'full-scan-report.json');
|
|
240
|
+
fs.writeFileSync(reportPath, JSON.stringify({ createdAt: new Date().toISOString(), root: result.root, results }, null, 2), { mode: 0o600 });
|
|
241
|
+
}
|
|
242
|
+
return { quarantineDir: results.length ? quarantineDir : null, results };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function annotate(result, clean) {
|
|
246
|
+
const byFile = new Map();
|
|
247
|
+
for (const r of (clean && clean.results) || []) byFile.set(r.file, r);
|
|
248
|
+
for (const f of result.findings) {
|
|
249
|
+
const res = f.verdict === CONFIRMED && f.category === 'malware' ? (byFile.get(f.archive) || byFile.get(f.filePath)) : null;
|
|
250
|
+
if (res && res.ok && res.action === 'archive-quarantined') f.action = { removed: true, text: 'Removed: the whole archive was moved to quarantine (backup kept)' };
|
|
251
|
+
else if (res && res.ok && res.action === 'quarantined') f.action = { removed: true, text: 'Removed: whole file was malware (backup kept)' };
|
|
252
|
+
else if (res && res.ok && res.action === 'repaired') f.action = { removed: true, text: 'Removed: malware cut out, rest of the file kept' };
|
|
253
|
+
else if (res && !res.ok) f.action = { removed: false, text: res.action === 'manual' ? 'Needs manual removal' : `Could not remove: ${res.error || 'unknown error'}` };
|
|
254
|
+
else if (f.verdict === CONFIRMED) f.action = { removed: false, text: 'Not removed (report only; run with --clean)' };
|
|
255
|
+
else if (f.fixCommand) f.action = { removed: false, text: `Not yours? Remove it: ${f.fixCommand}` };
|
|
256
|
+
else f.action = { removed: false, text: 'Review it yourself (never removed automatically)' };
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function writeReport(result) {
|
|
261
|
+
const dir = path.join(home(), '.gitsafty', 'reports');
|
|
262
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
263
|
+
const file = path.join(dir, `full-scan-${path.basename(result.root)}-${new Date().toISOString().replace(/[:.]/g, '-')}.json`);
|
|
264
|
+
fs.writeFileSync(file, JSON.stringify({ createdAt: new Date().toISOString(), ...result }, null, 2), { mode: 0o600 });
|
|
265
|
+
return file;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function printFindings(result) {
|
|
269
|
+
const groups = new Map();
|
|
270
|
+
for (const f of result.findings) {
|
|
271
|
+
const key = f.archive || f.filePath.split('/')[0];
|
|
272
|
+
if (!groups.has(key)) groups.set(key, []);
|
|
273
|
+
groups.get(key).push(f);
|
|
274
|
+
}
|
|
275
|
+
for (const [key, list] of groups) {
|
|
276
|
+
const malware = list.some(f => f.verdict === CONFIRMED);
|
|
277
|
+
const allRemoved = list.every(f => f.action.removed);
|
|
278
|
+
const color = malware && !allRemoved ? colors.red : allRemoved ? colors.green : colors.yellow;
|
|
279
|
+
const isArchive = list.some(f => f.archive === key);
|
|
280
|
+
console.log(`\n${color}${colors.bold}${isArchive ? '🗜️ ' : '📁'} ${key}${colors.reset}`);
|
|
281
|
+
for (const f of list.slice(0, 30)) {
|
|
282
|
+
const tag = f.verdict === CONFIRMED ? `${colors.red}${colors.bold}MALWARE${colors.reset}`
|
|
283
|
+
: f.severity === 'CRITICAL' ? `${colors.red}${colors.bold}DANGER${colors.reset}` : `${colors.yellow}${(f.category || 'review').toUpperCase()}${colors.reset}`;
|
|
284
|
+
console.log(` ${tag} ${f.name}`);
|
|
285
|
+
console.log(` ${colors.dim}${f.filePath}${f.lineNumber ? ':' + f.lineNumber : ''}${colors.reset}`);
|
|
286
|
+
if (f.description && f.category === 'archive') console.log(` ${colors.dim}${f.description}${colors.reset}`);
|
|
287
|
+
const c = f.action.removed ? colors.green : (f.verdict === CONFIRMED ? colors.red : colors.dim);
|
|
288
|
+
console.log(` ${c}→ ${f.action.text}${colors.reset}`);
|
|
289
|
+
}
|
|
290
|
+
if (list.length > 30) console.log(` ${colors.dim}… ${list.length - 30} more in the JSON report${colors.reset}`);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Runs Full Scan and prints the result.
|
|
296
|
+
* @returns {number} exit code (1 when malware or critical findings remain)
|
|
297
|
+
*/
|
|
298
|
+
function runFullScan(target, { clean = false, json = false } = {}) {
|
|
299
|
+
const abs = path.resolve(target || process.cwd());
|
|
300
|
+
if (!fs.existsSync(abs)) {
|
|
301
|
+
console.error(`${colors.red}✖ Not found: ${abs}${colors.reset}`);
|
|
302
|
+
return 1;
|
|
303
|
+
}
|
|
304
|
+
const started = Date.now();
|
|
305
|
+
const tty = !json && process.stdout.isTTY;
|
|
306
|
+
if (!json) {
|
|
307
|
+
console.log(`\n${colors.cyan}${colors.bold}🧪 Full Scan${colors.reset} ${colors.dim}${abs}${colors.reset}`);
|
|
308
|
+
console.log(`${colors.dim}Every file and every archive (zip, jar, apk, tar, gz, 7z, rar …), git repository or not · skipping node_modules, vendor & package caches · ${clean ? 'auto-remove confirmed malware' : 'report only'}${colors.reset}\n`);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const result = fullScan(abs, {
|
|
312
|
+
onProgress: tty ? (r) => process.stdout.write(`\r${colors.dim} scanned ${r.files} files, ${r.archives.length} archives…${colors.reset}`) : null
|
|
313
|
+
});
|
|
314
|
+
if (tty) process.stdout.write('\r\x1b[K');
|
|
315
|
+
|
|
316
|
+
const clean_ = clean && result.findings.some(f => f.verdict === CONFIRMED && f.category === 'malware') ? removeFullScanMalware(result) : null;
|
|
317
|
+
annotate(result, clean_);
|
|
318
|
+
result.clean = clean_;
|
|
319
|
+
const reportPath = writeReport(result);
|
|
320
|
+
|
|
321
|
+
if (json) {
|
|
322
|
+
process.stdout.write(JSON.stringify({ reportPath, ...result }, null, 2) + '\n');
|
|
323
|
+
} else {
|
|
324
|
+
if (result.findings.length) {
|
|
325
|
+
console.log(`${colors.bold}${colors.cyan}━━━━━━━━━━━━━━━━━━ What was found ━━━━━━━━━━━━━━━━━━${colors.reset}`);
|
|
326
|
+
printFindings(result);
|
|
327
|
+
}
|
|
328
|
+
const problemArchives = result.archives.filter(a => a.problems.length || a.encrypted.length);
|
|
329
|
+
if (problemArchives.length) {
|
|
330
|
+
console.log(`\n${colors.yellow}${colors.bold}Archives that could not be fully checked${colors.reset}`);
|
|
331
|
+
for (const a of problemArchives.slice(0, 20)) {
|
|
332
|
+
const why = [...(a.encrypted.length ? [`${a.encrypted.length} encrypted file(s)`] : []), ...a.problems.slice(0, 2).map(p => `${p.entry}: ${p.reason}`)];
|
|
333
|
+
console.log(` ${colors.yellow}⚠${colors.reset} ${a.path} ${colors.dim}${why.join('; ')}${colors.reset}`);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const confirmed = result.findings.filter(f => f.verdict === CONFIRMED);
|
|
338
|
+
const removed = result.findings.filter(f => f.action.removed);
|
|
339
|
+
const review = result.findings.filter(f => !f.action.removed && f.verdict !== CONFIRMED);
|
|
340
|
+
const infectedArchives = result.archives.filter(a => a.malware);
|
|
341
|
+
console.log(`\n${colors.bold}Summary${colors.reset} ${colors.dim}(${((Date.now() - started) / 1000).toFixed(1)}s)${colors.reset}`);
|
|
342
|
+
console.log(` Files scanned : ${result.files} (${result.repos.length} git repo(s) inside; non-git folders included)`);
|
|
343
|
+
console.log(` Archives opened : ${result.archives.length} (${result.archives.reduce((n, a) => n + a.scanned, 0)} files inside)`);
|
|
344
|
+
console.log(` ${confirmed.length ? colors.red : colors.green}Malware : ${confirmed.length}${infectedArchives.length ? ` (${infectedArchives.length} archive(s))` : ''}${colors.reset}`);
|
|
345
|
+
console.log(` ${removed.length ? colors.green : colors.dim}Removed : ${removed.length}${colors.reset}`);
|
|
346
|
+
console.log(` ${review.length ? colors.yellow : colors.green}To review : ${review.length}${colors.reset}`);
|
|
347
|
+
console.log(` ${colors.dim}Skipped : ${result.skippedDirs} dependency folder(s) (node_modules, vendor …)${result.tooLarge.length ? `, ${result.tooLarge.length} file(s) too large` : ''}${colors.reset}`);
|
|
348
|
+
if (clean_ && clean_.quarantineDir) console.log(` ${colors.dim}Backups : ${clean_.quarantineDir}${colors.reset}`);
|
|
349
|
+
console.log(`\n ${colors.dim}Full report: ${reportPath}${colors.reset}`);
|
|
350
|
+
const left = confirmed.filter(f => !f.action.removed);
|
|
351
|
+
if (left.length && !clean) {
|
|
352
|
+
console.log(`\n ${colors.bold}Remove the confirmed malware:${colors.reset} ${colors.cyan}gitsafty full-scan "${abs}" --clean${colors.reset}`);
|
|
353
|
+
}
|
|
354
|
+
if (removed.length && result.repos.length) {
|
|
355
|
+
console.log(` ${colors.dim}Files inside git repositories changed in the working tree only: check git status there and commit the fix.${colors.reset}`);
|
|
356
|
+
}
|
|
357
|
+
console.log('');
|
|
358
|
+
if (confirmed.length) notifyDesktop('GitSafty Full Scan', `${confirmed.length} malware finding(s) in ${path.basename(abs)}. Check the terminal.`);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const open = result.findings.filter(f => !f.action.removed && (f.verdict === CONFIRMED || f.severity === 'CRITICAL'));
|
|
362
|
+
return open.length ? 1 : 0;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
module.exports = {
|
|
366
|
+
fullScan,
|
|
367
|
+
runFullScan,
|
|
368
|
+
removeFullScanMalware,
|
|
369
|
+
DEPENDENCY_DIRS,
|
|
370
|
+
PACKAGE_FILES
|
|
371
|
+
};
|
package/src/index.js
CHANGED
|
@@ -259,6 +259,46 @@ async function runPrePush() {
|
|
|
259
259
|
|
|
260
260
|
const pushes = parsePrePushInput(stdinData);
|
|
261
261
|
|
|
262
|
+
// .env must never reach the remote: block, then fix (ignore + remove from unpushed commits).
|
|
263
|
+
if (pushes.length && loadConfig(process.cwd()).envGuard !== false) {
|
|
264
|
+
const { guardEnvOnPush } = require('./envGuard');
|
|
265
|
+
let env;
|
|
266
|
+
try {
|
|
267
|
+
env = guardEnvOnPush(pushes, process.cwd());
|
|
268
|
+
} catch (err) {
|
|
269
|
+
env = { blocked: true, files: ['.env'], fixes: [], manual: [`Automatic fix failed (${err.message}). Run: git rm --cached .env && echo .env >> .gitignore && git commit -am "Remove .env"`] };
|
|
270
|
+
}
|
|
271
|
+
if (env.blocked) {
|
|
272
|
+
console.log(`\n${colors.red}${colors.bold}✖ PUSH BLOCKED: .env file in this push${colors.reset} ${colors.dim}(${env.files.join(', ')})${colors.reset}`);
|
|
273
|
+
console.log(`${colors.dim}.env files hold passwords and API keys. GitSafty never lets them reach the remote.${colors.reset}\n`);
|
|
274
|
+
for (const f of env.fixes) console.log(` ${colors.green}✔${colors.reset} ${f}`);
|
|
275
|
+
for (const m of env.manual) console.log(` ${colors.yellow}⚠${colors.reset} ${m}`);
|
|
276
|
+
if (env.alreadyOnRemote) {
|
|
277
|
+
console.log(` ${colors.yellow}⚠ The remote already had a .env from an earlier push. This push removes it, but it is still in the remote's history: change (rotate) every key in it.${colors.reset}`);
|
|
278
|
+
}
|
|
279
|
+
// Push the cleaned commits now (once; the inner push runs the hooks again).
|
|
280
|
+
const remote = process.argv[3];
|
|
281
|
+
const config = loadConfig(process.cwd());
|
|
282
|
+
let pushed = false;
|
|
283
|
+
if (remote && !env.manual.length && env.repush.length && !process.env.GITSAFTY_ENV_REPUSH && config.envGuardAutoPush !== false) {
|
|
284
|
+
console.log(`\n${colors.cyan}Pushing the fixed commits (without .env) to ${remote}...${colors.reset}`);
|
|
285
|
+
const r = require('child_process').spawnSync('git', ['push', remote, ...env.repush.map(p => `${p.ref}:${p.remoteRef}`)], {
|
|
286
|
+
stdio: 'inherit',
|
|
287
|
+
env: { ...process.env, GITSAFTY_ENV_REPUSH: '1' }
|
|
288
|
+
});
|
|
289
|
+
pushed = r.status === 0;
|
|
290
|
+
}
|
|
291
|
+
if (pushed) {
|
|
292
|
+
console.log(`\n${colors.green}${colors.bold}✔ Fixed and pushed without .env.${colors.reset}`);
|
|
293
|
+
console.log(`${colors.dim}Git prints "failed to push" below for the ORIGINAL push (the one with .env). That one was stopped on purpose; your code is on the remote.${colors.reset}\n`);
|
|
294
|
+
} else {
|
|
295
|
+
console.log(`\n${colors.bold}Now run ${colors.cyan}git push${colors.reset}${colors.bold} again.${colors.reset}${env.manual.length ? '' : ' Nothing else to do.'}\n`);
|
|
296
|
+
}
|
|
297
|
+
notifyDesktop('GitSafty: .env blocked', pushed ? '.env was removed and your code was pushed without it.' : `.env was kept out of the push${env.manual.length ? '' : ' and fixed automatically'}.`);
|
|
298
|
+
process.exit(1);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
262
302
|
let allFiles = [];
|
|
263
303
|
let combinedDiff = '';
|
|
264
304
|
|
|
@@ -336,6 +376,8 @@ function runManualScan() {
|
|
|
336
376
|
|
|
337
377
|
if (!isGitRepo()) {
|
|
338
378
|
console.error(`${colors.red}Error: Current directory is not a git repository.${colors.reset}`);
|
|
379
|
+
console.error(`${colors.dim}To scan a plain folder, zip files or projects that are not git repositories, use Full Scan:${colors.reset}`);
|
|
380
|
+
console.error(` ${colors.cyan}gitsafty full-scan .${colors.reset} ${colors.dim}(add --clean to remove confirmed malware)${colors.reset}\n`);
|
|
339
381
|
process.exit(1);
|
|
340
382
|
}
|
|
341
383
|
|
package/src/malwareCleaner.js
CHANGED
|
@@ -116,12 +116,13 @@ function applyRepairs(relPath, original, findings) {
|
|
|
116
116
|
*
|
|
117
117
|
* @param {string[]} files repo-relative paths that had CONFIRMED findings
|
|
118
118
|
* @param {string} cwd repo root
|
|
119
|
-
* @param {{ reason?: string }} [options]
|
|
119
|
+
* @param {{ reason?: string, quarantineDir?: string }} [options]
|
|
120
120
|
*/
|
|
121
121
|
function removeConfirmedMalware(files, cwd = process.cwd(), options = {}) {
|
|
122
|
-
const gitDir = gitDirOf(cwd) || path.join(cwd, '.git');
|
|
123
122
|
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
124
|
-
|
|
123
|
+
// Outside a git repository (Full Scan) the caller gives its own quarantine folder.
|
|
124
|
+
const quarantineDir = options.quarantineDir ||
|
|
125
|
+
path.join(gitDirOf(cwd) || path.join(cwd, '.git'), 'gitsafty-quarantine', stamp);
|
|
125
126
|
|
|
126
127
|
const results = [];
|
|
127
128
|
|
package/src/menu.js
CHANGED
|
@@ -25,37 +25,38 @@ function ask(question) {
|
|
|
25
25
|
async function runInteractiveMenu() {
|
|
26
26
|
banner();
|
|
27
27
|
|
|
28
|
-
const item = (n,
|
|
29
|
-
console.log(` ${colors.green}
|
|
30
|
-
const section = (title) => console.log(`\n ${colors.
|
|
31
|
-
|
|
32
|
-
console.log(`\n${colors.bold}
|
|
33
|
-
|
|
34
|
-
section('
|
|
35
|
-
item(1, '
|
|
36
|
-
item(2, '
|
|
37
|
-
item(
|
|
38
|
-
item(
|
|
39
|
-
|
|
40
|
-
section('
|
|
41
|
-
item(
|
|
42
|
-
item(
|
|
43
|
-
item(
|
|
44
|
-
item(
|
|
45
|
-
item(
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
item(
|
|
50
|
-
item(
|
|
51
|
-
item(
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
item(
|
|
56
|
-
item(
|
|
57
|
-
item(
|
|
58
|
-
|
|
28
|
+
const item = (n, title, desc) =>
|
|
29
|
+
console.log(` ${colors.green}${String(n).padStart(2)}.${colors.reset} ${colors.bold}${title.padEnd(34)}${colors.reset} ${colors.dim}${desc}${colors.reset}`);
|
|
30
|
+
const section = (title) => console.log(`\n ${colors.cyan}${title}${colors.reset}`);
|
|
31
|
+
|
|
32
|
+
console.log(`\n${colors.bold}What do you want to do?${colors.reset}`);
|
|
33
|
+
|
|
34
|
+
section('Protect your code');
|
|
35
|
+
item(1, 'Protect this project', 'Check every push, clone and pull in this project');
|
|
36
|
+
item(2, 'Protect all projects on this PC', 'Same, for every git project on this computer');
|
|
37
|
+
item(3, 'Scan every git pull', 'Also when git says "Already up to date" (on/off)');
|
|
38
|
+
item(4, 'Remove protection', 'Uninstall GitSafty from this project or this PC');
|
|
39
|
+
|
|
40
|
+
section('Scan and clean');
|
|
41
|
+
item(5, 'Scan this project', 'Find malware here and remove it automatically');
|
|
42
|
+
item(6, 'Scan all projects in a folder', 'Malware, hidden backdoors and leaked passwords/keys');
|
|
43
|
+
item(7, 'Scan everything in a folder', 'Also zip/rar files and folders that are not git projects');
|
|
44
|
+
item(8, 'Scan all git repos under a folder', 'Quick malware check, e.g. your whole disk');
|
|
45
|
+
item(9, 'Clean this project', 'Move malware files in this project to quarantine');
|
|
46
|
+
item(10, 'Scan a GitHub repo before cloning', 'Check a GitHub link without downloading it');
|
|
47
|
+
|
|
48
|
+
section('Safe GitHub login (stay logged out)');
|
|
49
|
+
item(11, 'Turn on safe GitHub login', 'Touch ID / Windows Hello / password before every push');
|
|
50
|
+
item(12, 'Check safe login status', 'See if your GitHub login is protected');
|
|
51
|
+
item(13, 'Test safe login', 'Try the unlock prompt once');
|
|
52
|
+
item(14, 'Turn off safe login', 'Go back to normal git login');
|
|
53
|
+
|
|
54
|
+
section('Help and tools');
|
|
55
|
+
item(15, 'Fix problems', 'Find what is broken and how to fix it');
|
|
56
|
+
item(16, 'Check for updates', 'Install the newest GitSafty');
|
|
57
|
+
item(17, 'Add GitSafty to GitHub Actions', 'Check every push on GitHub too');
|
|
58
|
+
item(18, 'See a demo', 'Show what a blocked push looks like');
|
|
59
|
+
console.log(`\n ${colors.dim} 0. Exit${colors.reset}\n`);
|
|
59
60
|
|
|
60
61
|
const rl = readline.createInterface({
|
|
61
62
|
input: process.stdin,
|
|
@@ -63,7 +64,7 @@ async function runInteractiveMenu() {
|
|
|
63
64
|
});
|
|
64
65
|
|
|
65
66
|
const choice = await new Promise((resolve) => {
|
|
66
|
-
rl.question(`${colors.bold}${colors.yellow}Enter
|
|
67
|
+
rl.question(`${colors.bold}${colors.yellow}Enter a number (0-18): ${colors.reset}`, (ans) => {
|
|
67
68
|
rl.close();
|
|
68
69
|
resolve(ans.trim());
|
|
69
70
|
});
|
|
@@ -92,12 +93,12 @@ async function runInteractiveMenu() {
|
|
|
92
93
|
break;
|
|
93
94
|
}
|
|
94
95
|
|
|
95
|
-
case '
|
|
96
|
+
case '5': {
|
|
96
97
|
runManualScan();
|
|
97
98
|
break;
|
|
98
99
|
}
|
|
99
100
|
|
|
100
|
-
case '
|
|
101
|
+
case '10': {
|
|
101
102
|
const askRl = readline.createInterface({
|
|
102
103
|
input: process.stdin,
|
|
103
104
|
output: process.stdout
|
|
@@ -127,7 +128,7 @@ async function runInteractiveMenu() {
|
|
|
127
128
|
break;
|
|
128
129
|
}
|
|
129
130
|
|
|
130
|
-
case '
|
|
131
|
+
case '9': {
|
|
131
132
|
console.log(`\n${colors.cyan}Scanning workspace for injected malware scripts to quarantine...${colors.reset}`);
|
|
132
133
|
const { getAllRepoFiles } = require('./utils/git');
|
|
133
134
|
scanAndCleanRepo(getAllRepoFiles(), process.cwd(), { reason: 'clean' });
|
|
@@ -144,7 +145,7 @@ async function runInteractiveMenu() {
|
|
|
144
145
|
break;
|
|
145
146
|
}
|
|
146
147
|
|
|
147
|
-
case '
|
|
148
|
+
case '18': {
|
|
148
149
|
console.log(`\n${colors.cyan}Simulating a malicious push intercept test...${colors.reset}\n`);
|
|
149
150
|
const mockFiles = ['src/app.js', 'temp_auto_push.bat', '.vscode/tasks.json'];
|
|
150
151
|
const mockDiff = `+ powershell.exe -enc SQBFAFgAIAAoAE4AZQB3...
|
|
@@ -158,7 +159,7 @@ async function runInteractiveMenu() {
|
|
|
158
159
|
break;
|
|
159
160
|
}
|
|
160
161
|
|
|
161
|
-
case '
|
|
162
|
+
case '17': {
|
|
162
163
|
const res = setupGitHubAction();
|
|
163
164
|
if (res.success) {
|
|
164
165
|
console.log(`\n${colors.green}${colors.bold}✔ ${res.message}${colors.reset}\n`);
|
|
@@ -168,7 +169,7 @@ async function runInteractiveMenu() {
|
|
|
168
169
|
break;
|
|
169
170
|
}
|
|
170
171
|
|
|
171
|
-
case '
|
|
172
|
+
case '4': {
|
|
172
173
|
const { isGitRepo } = require('./utils/git');
|
|
173
174
|
let global = !isGitRepo(process.cwd());
|
|
174
175
|
if (!global) {
|
|
@@ -184,14 +185,14 @@ async function runInteractiveMenu() {
|
|
|
184
185
|
break;
|
|
185
186
|
}
|
|
186
187
|
|
|
187
|
-
case '
|
|
188
|
+
case '16': {
|
|
188
189
|
const pkg = require('../package.json');
|
|
189
190
|
const { checkUpdateManual } = require('./updateNotifier');
|
|
190
191
|
await checkUpdateManual(pkg.version);
|
|
191
192
|
break;
|
|
192
193
|
}
|
|
193
194
|
|
|
194
|
-
case '
|
|
195
|
+
case '8': {
|
|
195
196
|
const folder = await ask(`\n${colors.bold}${colors.cyan}? Folder to sweep (Enter = ${process.cwd()}): ${colors.reset}`);
|
|
196
197
|
const removeAnswer = await ask(`${colors.bold}${colors.cyan}? Automatically remove CONFIRMED malware? Suspicious items are never touched. (Y/n): ${colors.reset}`);
|
|
197
198
|
const clean = !/^n(o)?$/i.test(removeAnswer);
|
|
@@ -234,7 +235,7 @@ async function runInteractiveMenu() {
|
|
|
234
235
|
break;
|
|
235
236
|
}
|
|
236
237
|
|
|
237
|
-
case '
|
|
238
|
+
case '6': {
|
|
238
239
|
const { runAdvancedScan } = require('./advancedScanner');
|
|
239
240
|
const folder = await ask(`\n${colors.bold}${colors.cyan}? Folder that contains your projects (Enter = ${process.cwd()}): ${colors.reset}`);
|
|
240
241
|
const deep = await ask(`${colors.bold}${colors.cyan}? Deep scan incl. node_modules & ignored files? Slower. (y/N): ${colors.reset}`);
|
|
@@ -246,7 +247,7 @@ async function runInteractiveMenu() {
|
|
|
246
247
|
break;
|
|
247
248
|
}
|
|
248
249
|
|
|
249
|
-
case '
|
|
250
|
+
case '3': {
|
|
250
251
|
const shell = require('./shellIntegration');
|
|
251
252
|
const on = shell.shellIntegrationStatus().installed.length > 0;
|
|
252
253
|
const answer = await ask(`\n${colors.bold}${colors.cyan}? Pull scan is ${on ? 'ON' : 'OFF'}. Turn it ${on ? 'off' : 'on'}? (y/N): ${colors.reset}`);
|
|
@@ -262,9 +263,17 @@ async function runInteractiveMenu() {
|
|
|
262
263
|
break;
|
|
263
264
|
}
|
|
264
265
|
|
|
266
|
+
case '7': {
|
|
267
|
+
const { runFullScan } = require('./fullScanner');
|
|
268
|
+
const folder = await ask(`\n${colors.bold}${colors.cyan}? Folder to scan completely (Enter = ${process.cwd()}): ${colors.reset}`);
|
|
269
|
+
const clean = await ask(`${colors.bold}${colors.cyan}? Automatically remove CONFIRMED malware? An infected archive is moved to quarantine whole (backup kept). (Y/n): ${colors.reset}`);
|
|
270
|
+
runFullScan(folder || process.cwd(), { clean: !/^n(o)?$/i.test(clean) });
|
|
271
|
+
break;
|
|
272
|
+
}
|
|
273
|
+
|
|
265
274
|
case '0':
|
|
266
275
|
default:
|
|
267
|
-
console.log(`\n${colors.dim}Goodbye
|
|
276
|
+
console.log(`\n${colors.dim}Goodbye!${colors.reset}\n`);
|
|
268
277
|
break;
|
|
269
278
|
}
|
|
270
279
|
}
|
package/src/reporter.js
CHANGED
|
@@ -28,7 +28,7 @@ const symbols = {
|
|
|
28
28
|
|
|
29
29
|
function banner() {
|
|
30
30
|
console.log(`\n${colors.cyan}${colors.bold}================================================================${colors.reset}`);
|
|
31
|
-
console.log(`${colors.cyan}${colors.bold}
|
|
31
|
+
console.log(`${colors.cyan}${colors.bold} GitSafty: Malware & Secret Guard for Git${colors.reset}`);
|
|
32
32
|
console.log(`${colors.cyan}${colors.bold}================================================================${colors.reset}`);
|
|
33
33
|
}
|
|
34
34
|
|
package/src/utils/git.js
CHANGED
|
@@ -101,10 +101,10 @@ function parsePrePushInput(stdinText) {
|
|
|
101
101
|
*/
|
|
102
102
|
function getChangedFiles(diffRange, cwd = process.cwd()) {
|
|
103
103
|
// Use git diff-tree or git log to extract changed filenames
|
|
104
|
-
const output = runGit(`diff-tree --no-commit-id --name-only -r ${diffRange}`, cwd);
|
|
104
|
+
const output = runGit(`diff-tree --no-commit-id --name-only --diff-filter=d -r ${diffRange}`, cwd);
|
|
105
105
|
if (!output) {
|
|
106
106
|
// Fallback to git log
|
|
107
|
-
const logOutput = runGit(`log ${diffRange} --name-only --oneline`, cwd);
|
|
107
|
+
const logOutput = runGit(`log ${diffRange} --name-only --oneline --diff-filter=d`, cwd);
|
|
108
108
|
if (!logOutput) return [];
|
|
109
109
|
const files = new Set();
|
|
110
110
|
for (const line of logOutput.split('\n')) {
|