-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodeql-analyze.php
More file actions
231 lines (185 loc) · 7.13 KB
/
codeql-analyze.php
File metadata and controls
231 lines (185 loc) · 7.13 KB
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
#!/usr/bin/env php
<?php
/**
* CodeQL Security Analysis Script
* Cross-platform tool for analyzing C/C++ code with CodeQL
*/
class CodeQLAnalyzer {
private string $codeqlPath;
private string $projectRoot;
private string $dbName = 'codeql-db';
public function __construct() {
$this->projectRoot = __DIR__;
$this->detectCodeQL();
}
private function detectCodeQL(): void {
$possiblePaths = [
'e:\php\codeql-bundle-win64\codeql\codeql.exe',
'e:\php\codeql-bundle-win64\codeql\codeql',
'/usr/local/bin/codeql',
getenv('HOME') . '/codeql/codeql',
];
foreach ($possiblePaths as $path) {
if (file_exists($path)) {
$this->codeqlPath = $path;
$this->log("✓ Found CodeQL at: {$path}");
return;
}
}
$which = PHP_OS_FAMILY === 'Windows' ? 'where' : 'which';
exec("{$which} codeql 2>&1", $output, $code);
if ($code === 0 && !empty($output[0])) {
$this->codeqlPath = 'codeql';
$this->log("✓ Found CodeQL in PATH");
return;
}
$this->error("CodeQL not found! Please install or set path.");
}
private function log(string $message): void {
echo "[" . date('H:i:s') . "] {$message}\n";
}
private function error(string $message): never {
echo "\n❌ ERROR: {$message}\n\n";
exit(1);
}
private function exec(string $command): array {
$this->log("Running: {$command}");
exec($command . ' 2>&1', $output, $code);
return ['output' => $output, 'code' => $code];
}
public function createDatabase(?string $buildCommand = null): void {
$this->log("Step 1: Creating CodeQL database...");
if (is_dir($this->dbName)) {
$this->log("Removing old database...");
$this->removeDirectory($this->dbName);
}
$this->log("Using source-root mode (no actual compilation needed)");
$noopCmd = PHP_OS_FAMILY === 'Windows' ? 'echo CodeQL' : 'echo CodeQL';
$cmd = sprintf(
'%s database create %s --language=cpp --command=%s --source-root=. --overwrite',
escapeshellarg($this->codeqlPath),
escapeshellarg($this->dbName),
escapeshellarg($noopCmd)
);
$result = $this->exec($cmd);
if ($result['code'] !== 0) {
$this->error("Failed to create database:\n" . implode("\n", $result['output']));
}
$this->log("✓ Database created successfully");
}
public function analyze(string $queryPack = 'cpp-security-and-quality'): void {
$this->log("Step 2: Running security analysis...");
if (!is_dir($this->dbName)) {
$this->error("Database not found. Run createDatabase() first.");
}
$sarifFile = 'codeql-results.sarif';
$cmd = sprintf(
'%s database analyze %s %s --format=sarif-latest --output=%s',
escapeshellarg($this->codeqlPath),
escapeshellarg($this->dbName),
escapeshellarg($queryPack),
escapeshellarg($sarifFile)
);
$result = $this->exec($cmd);
if ($result['code'] !== 0) {
$this->error("Analysis failed:\n" . implode("\n", $result['output']));
}
$this->log("✓ SARIF results saved to: {$sarifFile}");
$csvFile = 'codeql-results.csv';
$cmd = sprintf(
'%s database analyze %s %s --format=csv --output=%s',
escapeshellarg($this->codeqlPath),
escapeshellarg($this->dbName),
escapeshellarg($queryPack),
escapeshellarg($csvFile)
);
$this->exec($cmd);
$this->log("✓ CSV results saved to: {$csvFile}");
$this->showSummary($sarifFile);
}
private function showSummary(string $sarifFile): void {
if (!file_exists($sarifFile)) {
return;
}
$sarif = json_decode(file_get_contents($sarifFile), true);
if (!isset($sarif['runs'][0]['results'])) {
$this->log("\n✓ No security issues found!");
return;
}
$results = $sarif['runs'][0]['results'];
$total = count($results);
$byLevel = [];
foreach ($results as $result) {
$level = $result['level'] ?? 'note';
$byLevel[$level] = ($byLevel[$level] ?? 0) + 1;
}
echo "\n" . str_repeat('=', 50) . "\n";
echo "CodeQL Analysis Summary\n";
echo str_repeat('=', 50) . "\n";
echo "Total issues found: {$total}\n";
foreach ($byLevel as $level => $count) {
$icon = match($level) {
'error' => '❌',
'warning' => '⚠️',
default => 'ℹ️'
};
echo " {$icon} {$level}: {$count}\n";
}
echo str_repeat('=', 50) . "\n\n";
echo "To view detailed results:\n";
echo " - Install CodeQL extension in VS Code\n";
echo " - Open: {$sarifFile}\n";
echo " - Or check: codeql-results.csv\n\n";
}
private function removeDirectory(string $dir): void {
if (PHP_OS_FAMILY === 'Windows') {
exec('rmdir /s /q ' . escapeshellarg($dir));
} else {
exec('rm -rf ' . escapeshellarg($dir));
}
}
public function cleanup(): void {
$this->log("Cleaning up database...");
if (is_dir($this->dbName)) {
$this->removeDirectory($this->dbName);
$this->log("✓ Database removed");
}
}
public function runFullAnalysis(): void {
echo "\n";
echo "╔════════════════════════════════════════════════╗\n";
echo "║ CodeQL Security Analysis for PHP HTTP Server ║\n";
echo "╚════════════════════════════════════════════════╝\n";
echo "\n";
$this->createDatabase();
$this->analyze();
echo "\n✓ Analysis complete!\n\n";
}
}
$options = getopt('hcq:', ['help', 'cleanup', 'query:']);
if (isset($options['h']) || isset($options['help'])) {
echo <<<HELP
CodeQL Security Analyzer
Usage: php codeql-analyze.php [options]
Options:
-h, --help Show this help message
-c, --cleanup Remove CodeQL database and exit
-q, --query <pack> Specify query pack (default: cpp-security-and-quality)
Examples:
php codeql-analyze.php # Run full analysis
php codeql-analyze.php -q cpp-security # Use specific query pack
php codeql-analyze.php --cleanup # Clean up database
Available query packs:
- cpp-security-and-quality (recommended)
- cpp-security-extended
- codeql/cpp-queries
HELP;
exit(0);
}
$analyzer = new CodeQLAnalyzer();
if (isset($options['c']) || isset($options['cleanup'])) {
$analyzer->cleanup();
exit(0);
}
$queryPack = $options['q'] ?? $options['query'] ?? 'cpp-security-and-quality';
$analyzer->runFullAnalysis();