Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .vscode-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,18 @@ module.exports = defineConfig([{
mocha: {
timeout: 20000,
},
}, {
// Tests that run commands needing an open folder, like Run Analysis.
label: 'workspace',
files: 'out/test-workspace/**/*.test.js',
version: '1.140.0',
workspaceFolder: './src/test-workspace/fixture',
launchArgs: [
'--disable-gpu',
'--disable-gpu-sandbox',
'--disable-dev-shm-usage',
],
mocha: {
timeout: 60000,
},
}]);
17 changes: 12 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# CoreTrace VS Code Extension

CoreTrace VS Code brings the power of the `ctrace` security and quality analysis framework directly into Visual Studio Code. It provides seamless static and dynamic analysis for C and C++ projects, surfacing vulnerabilities, code defects, and stack diagnostics directly in your editor.
CoreTrace VS Code brings the power of the `ctrace` security and quality analysis framework directly into Visual Studio Code. It provides seamless static and dynamic analysis for C, C++ and Python projects, surfacing vulnerabilities, code defects, and stack diagnostics directly in your editor.

---

Expand Down Expand Up @@ -50,7 +50,7 @@ Precise C/C++ static analysis requires knowledge of compiler flags, include dire
> ```

### 6. Incremental Workspace Scans
Save time on repetitive scans. CoreTrace computes file content hashes and only re-analyzes C/C++ files that have changed since their last analysis; the results of the other files are reused, even after restarting VS Code.
Save time on repetitive scans. CoreTrace computes file content hashes and only re-analyzes C/C++ and Python files that have changed since their last analysis; the results of the other files are reused, even after restarting VS Code. Python files are re-analyzed when a dependency manifest changes (`requirements*.txt`, `pyproject.toml`, `setup.py`, lock files…).
- The cache is invalidated for every file when a header, `compile_commands.json`, the `ctrace` binary or the analysis options change, since any of these can change the result of an unmodified source file.
- Run **Clear Analysis Cache** to force a full scan, or set `ctrace.workspace.incremental` to `false` to disable the cache.

Expand Down Expand Up @@ -80,6 +80,13 @@ The gear icon opens the analysis settings, grouped by purpose:
- Options that do not apply to the current scan mode say so on a single line.
- **Reset to defaults** restores everything in two clicks. Settings stored in `settings.json` (timeout, incremental scans, analysis models…) are one click away.


### 11. Python Analysis
With `ctrace` 0.85 or newer, Python files (`.py`) are analyzed by `coretrace-python-analyzer`, which ships with `ctrace`: there is nothing to install.
- It reports, among others, dangerous `eval`, hardcoded credentials, weak cryptography, insecure TLS or temporary files, and taint flows from web frameworks (Flask, Django, FastAPI…) into command, SQL or NoSQL injection, path traversal, SSRF and XSS.
- Run it on the active `.py` file, or with **Scan Workspace**, which then covers C/C++ and Python files and skips virtual environments and caches (`.venv`, `venv`, `site-packages`, `__pycache__`…).
- Turn it on or off with `coretrace-python-analyzer` in the **Static** tools menu. C/C++ files never receive it, so older `ctrace` binaries keep working for them.
- Findings get the same diagnostics, CWE links and ignore actions as C/C++ findings. The CodeLens, the Stack Tree and dynamic analysis stay C/C++ only.
---

## ⚙️ Requirements & Prerequisites
Expand Down Expand Up @@ -111,8 +118,8 @@ Access these commands from the Command Palette (`Ctrl+Shift+P` / `Cmd+Shift+P`):

| Command | Title | Description |
|---|---|---|
| `ctrace.runAnalysis` | **Run Analysis** | Runs analysis on the currently active C/C++ file. |
| `ctrace.runWorkspaceAnalysis` | **Run Workspace Analysis** | Analyzes all modified C/C++ files in the workspace. |
| `ctrace.runAnalysis` | **Run Analysis** | Runs analysis on the currently active C/C++ or Python file. |
| `ctrace.runWorkspaceAnalysis` | **Run Workspace Analysis** | Analyzes all modified C/C++ and Python files in the workspace. |
| `ctrace.installDependencies` | **CoreTrace: Install Analyzers & Dependencies** | Installs or repairs external static analyzers (`cppcheck`, `flawfinder`, `ikos`, `tscancode`). |
| `ctrace.clearAnalysisCache` | **Clear Analysis Cache** | Clears cached analysis results to force a full re-scan. |
| `ctrace.focusStackFunction` | **CoreTrace: View Function in Stack Visualizer** | Opens the Stack Visualizer on a function. |
Expand Down Expand Up @@ -174,7 +181,7 @@ npm run compile
npm test
```

The test suite runs inside a downloaded VS Code instance (`@vscode/test-cli`). Press `F5` in VS Code to start an Extension Development Host with the extension loaded.
The test suite runs inside a downloaded VS Code instance (`@vscode/test-cli`), in two configurations: `unit` without a folder, and `workspace` with `src/test-workspace/fixture` open, for commands like Run Analysis that need one. Press `F5` in VS Code to start an Extension Development Host with the extension loaded.

`src/test/params.integration.test.ts` runs every analysis parameter through a real `ctrace`. It uses the binary named by `CTRACE_BIN`, or a `ctrace` file at the repository root, and is skipped when there is none, as on CI.

Expand Down
16 changes: 12 additions & 4 deletions media/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@
const smtSecondaryGroup = document.getElementById('smt-secondary-group');
const smtModeSelect = document.getElementById('smt-mode');
const persistedState = vscode.getState() || {};
// Static tools of the versions that did not save knownStaticTools.
const LEGACY_STATIC_TOOLS = ['cppcheck', 'flawfinder', 'ikos', 'tscancode', 'ctrace_stack_analyzer'];
// While a search forces sections open: the ones to reopen afterwards.
let settingsSearchRestore = null;
let analysisProfile = 'full';
Expand Down Expand Up @@ -211,7 +213,7 @@
if (fileLabel) {
fileLabel.textContent = workspace
? 'All C/C++ files in workspace'
: (lastFileName || 'Open a C/C++ file to analyse');
: (lastFileName || 'Open a C/C++ or Python file to analyse');
}
[onlyDirGroup, excludeDirGroup].forEach(group => {
if (!group) { return; }
Expand Down Expand Up @@ -363,7 +365,8 @@

setScanMode(persistedState.scanWorkspace === true);
setAnalysisProfile(saved.analysisProfile || 'full');
restoreToolSelection('.static-tool', saved.staticTools, saved.staticEnabled !== false, saved.dynamicTools);
restoreToolSelection('.static-tool', saved.staticTools, saved.staticEnabled !== false, saved.dynamicTools,
persistedState.knownStaticTools || LEGACY_STATIC_TOOLS);
restoreToolSelection('.dynamic-tool', saved.dynamicTools, saved.dynamicEnabled !== false);
const isWs = persistedState.scanWorkspace === true;
setValue('only-function', saved.onlyFunction || '');
Expand Down Expand Up @@ -401,6 +404,7 @@
vscode.setState({
uiState: readCtraceUiState(),
scanWorkspace,
knownStaticTools: [...document.querySelectorAll('.static-tool')].map(tool => tool.value),
openSections: openSectionKeys(),
});
refreshSettingsIndicators();
Expand Down Expand Up @@ -605,10 +609,14 @@
return Array.from(document.querySelectorAll(`${selector}:checked`)).map(element => element.value);
}

function restoreToolSelection(selector, savedTools, enabled, fallbackSavedTools) {
function restoreToolSelection(selector, savedTools, enabled, fallbackSavedTools, knownTools) {
const selected = Array.isArray(savedTools) ? savedTools : null;
document.querySelectorAll(selector).forEach(tool => {
if (selected) {
if (selected && Array.isArray(knownTools) && !knownTools.includes(tool.value)) {
// A tool added since this state was saved: the user never
// turned it off, so it starts on like in a fresh install.
tool.checked = enabled;
} else if (selected) {
const inSaved = selected.includes(tool.value);
const inFallback = Array.isArray(fallbackSavedTools) && fallbackSavedTools.includes(tool.value);
tool.checked = inSaved || inFallback;
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "coretrace",
"displayName": "CoreTrace",
"description": "Integration for CoreTrace CLI",
"description": "Security and quality analysis of C, C++ and Python code with the CoreTrace CLI",
"version": "0.3.6",
"publisher": "CoreTrace",
"icon": "icon.png",
Expand All @@ -12,6 +12,7 @@
"keywords": [
"c",
"cpp",
"python",
"security",
"static analysis",
"audit",
Expand Down
3 changes: 2 additions & 1 deletion src/SidebarProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ export class SidebarProvider implements vscode.WebviewViewProvider, vscode.Dispo
<!-- Current file -->
<div class="file-pill" id="file-pill">
<i data-lucide="file-code-2"></i>
<span id="file-label">Open a C/C++ file to analyse</span>
<span id="file-label">Open a C/C++ or Python file to analyse</span>
</div>

<!-- Scan mode -->
Expand Down Expand Up @@ -261,6 +261,7 @@ export class SidebarProvider implements vscode.WebviewViewProvider, vscode.Dispo
<label><input type="checkbox" class="static-tool" value="ikos" checked><span>ikos</span></label>
<label><input type="checkbox" class="static-tool" value="tscancode" checked><span>tscancode</span></label>
<label><input type="checkbox" class="static-tool" value="ctrace_stack_analyzer" checked><span>ctrace_stack_analyzer</span></label>
<label title="Python files (.py), ctrace 0.85 or newer"><input type="checkbox" class="static-tool" value="coretrace-python-analyzer" checked><span>coretrace-python-analyzer</span></label>
</div>
</div>
<div class="analysis-mode-menu">
Expand Down
14 changes: 12 additions & 2 deletions src/ctrace/CommandBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,19 @@ export function parseAndValidateParams(raw: string): string[] {
tokens.push(m[1].replace(/^["']|["']$/g, ''));
}

const safe = /^--?[a-zA-Z0-9][a-zA-Z0-9._\-:/\\=,@]*$/;
// The name is strict. The value only has to stay free of what a shell
// interprets: every token is single-quoted again before use, and real
// paths contain spaces, parentheses, ~ (C:\Users\RUNNER~1) or accents.
const safeName = /^--?[a-zA-Z0-9][a-zA-Z0-9._\-]*$/;
const unsafeValue = /[$`;&|<>'"\r\n\0]/;
// Entry points are function names, never paths.
const functionList = /^[a-zA-Z0-9_:~,]*$/;
for (const token of tokens) {
if (!safe.test(token)) {
const eq = token.indexOf('=');
const name = eq < 0 ? token : token.slice(0, eq);
const value = eq < 0 ? '' : token.slice(eq + 1);
if (!safeName.test(name) || unsafeValue.test(value)
|| (name === '--entry-points' && !functionList.test(value))) {
throw new Error(`Unsafe CLI parameter rejected: "${token}"`);
}
}
Expand Down
15 changes: 12 additions & 3 deletions src/ctrace/WorkspaceScanner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,15 @@ export async function partitionFiles(files: string[], contextKey: string): Promi
* header in the workspace. Header edits therefore invalidate the whole cache,
* since an unchanged .c file may include a changed header.
*/
export async function analysisContextKey(values: unknown[], dependencyFiles: (string | undefined)[]): Promise<string> {
export async function analysisContextKey(
values: unknown[],
dependencyFiles: (string | undefined)[],
dependencyGlob: string = HEADER_GLOB
): Promise<string> {
const hash = crypto.createHash('sha1');
hash.update(JSON.stringify(values));
const headers = await vscode.workspace.findFiles(HEADER_GLOB, EXCLUDE_GLOB);
const statFiles = [...dependencyFiles.filter((f): f is string => Boolean(f)), ...headers.map(u => u.fsPath).sort()];
const dependencies = await vscode.workspace.findFiles(dependencyGlob, EXCLUDE_GLOB);
const statFiles = [...dependencyFiles.filter((f): f is string => Boolean(f)), ...dependencies.map(u => u.fsPath).sort()];
for (const file of statFiles) {
try {
const stat = await fs.promises.stat(file);
Expand All @@ -146,6 +150,11 @@ export async function analysisContextKey(values: unknown[], dependencyFiles: (st
}

const HEADER_GLOB = '**/*.{h,hh,hpp,hxx,h++,inl,inc,ipp,tpp}';
/**
* What a Python result depends on besides the file itself: the dependency
* rules of the Python analyzer read the project's requirement manifests.
*/
export const PYTHON_MANIFEST_GLOB = '**/{requirements*.txt,pyproject.toml,setup.py,setup.cfg,Pipfile,Pipfile.lock,poetry.lock,uv.lock,advisories.json}';
/** Directories that should never be scanned (build artifacts, vendored code…) */
const EXCLUDE_GLOB = '{**/node_modules/**,**/build/**,**/out/**,**/dist/**,**/.git/**,**/CMakeFiles/**,**/cmake-build-*/**}';

Expand Down
Loading
Loading