Repository navigation
Expand file tree
/
Copy pathbytecode-verify
More file actions
executable file
·398 lines (377 loc) · 15.9 KB
/
Copy pathbytecode-verify
File metadata and controls
executable file
·398 lines (377 loc) · 15.9 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
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
#!/usr/bin/env php
<?php
// --- Rust-first dispatch -------------------------------------------------
// If a compiled Rust `bytecode-verify` is available, hand off to it (it is a
// byte-compatible reimplementation). Otherwise fall through to the PHP
// implementation below. Set BYTECODE_NO_RUST=1 to force the PHP path.
(static function (): void {
if (getenv('BYTECODE_NO_RUST') || PHP_SAPI !== 'cli' || !function_exists('proc_open')) {
return;
}
$root = getenv('BYTECODE_ROOT') ?: dirname(__DIR__, 2);
$candidates = [];
if ($explicit = getenv('BYTECODE_VERIFY_RS')) {
$candidates[] = $explicit;
}
$candidates[] = $root . '/rust/target/release/bytecode-verify';
$candidates[] = __DIR__ . '/bytecode-verify-rs';
$bin = null;
foreach ($candidates as $cand) {
if ($cand !== '' && is_file($cand) && is_executable($cand)) {
$bin = $cand;
break;
}
}
if ($bin === null) {
return;
}
// Hand the Rust tool the authoritative context the PHP version would use:
// the running interpreter's PHP_VERSION_ID (the container check pins to it)
// and the repo root (default vendor-key / pubkey resolution).
putenv('BYTECODE_PHP_VERSION_ID=' . PHP_VERSION_ID);
if (getenv('BYTECODE_ROOT') === false) {
putenv('BYTECODE_ROOT=' . dirname(__DIR__, 2));
}
global $argv;
$forward = array_slice($argv, 1);
$proc = @proc_open(
array_merge([$bin], $forward),
[0 => STDIN, 1 => STDOUT, 2 => STDERR],
$pipes
);
if (!is_resource($proc)) {
return; // could not launch -> fall back to PHP
}
exit(proc_close($proc));
})();
// --- end Rust-first dispatch ---------------------------------------------
function fail(string $message, int $code = 1): never
{
fwrite(STDERR, $message . PHP_EOL);
exit($code);
}
function u32le(string $bytes, int &$offset): int
{
if (strlen($bytes) < $offset + 4) {
fail('truncated container');
}
$value = unpack('V', substr($bytes, $offset, 4))[1];
$offset += 4;
return $value;
}
function u64le(string $bytes, int &$offset): int
{
if (strlen($bytes) < $offset + 8) {
fail('truncated container');
}
$parts = unpack('Vlo/Vhi', substr($bytes, $offset, 8));
$offset += 8;
return $parts['lo'] + ($parts['hi'] << 32);
}
function take(string $bytes, int &$offset, int $length): string
{
if ($length < 0 || strlen($bytes) < $offset + $length) {
fail('truncated container');
}
$value = substr($bytes, $offset, $length);
$offset += $length;
return $value;
}
function parse_bytc(string $path): array
{
$bytes = file_get_contents($path);
if ($bytes === false) {
fail("cannot read {$path}");
}
if (substr($bytes, 0, 4) !== 'BYTC') {
fail("not a BYTC container: {$path}");
}
$offset = 4;
$version = u32le($bytes, $offset);
if ($version !== 1 && $version !== 2) {
fail("{$path}: unsupported container version {$version}");
}
$phpVersionId = u32le($bytes, $offset);
$backendId = take($bytes, $offset, u32le($bytes, $offset));
$backendFormat = take($bytes, $offset, u32le($bytes, $offset));
$cipherId = null;
$keyId = '';
if ($version === 2) {
$cipherId = u32le($bytes, $offset);
$keyId = take($bytes, $offset, u32le($bytes, $offset));
}
$headerSize = $offset;
$nonce = take($bytes, $offset, u32le($bytes, $offset));
$tag = take($bytes, $offset, u32le($bytes, $offset));
$ciphertext = take($bytes, $offset, u64le($bytes, $offset));
if ($offset !== strlen($bytes)) {
fail("{$path}: trailing bytes after ciphertext");
}
return compact('bytes', 'version', 'phpVersionId', 'backendId', 'backendFormat', 'cipherId', 'keyId', 'headerSize', 'nonce', 'tag', 'ciphertext');
}
function resolve_ikm_hex(): string
{
$vendorKeyFile = getenv('BYTECODE_VENDOR_KEY_FILE') ?: dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'build' . DIRECTORY_SEPARATOR . 'vendor-secret.key';
$fileKey = is_file($vendorKeyFile) ? trim((string) file_get_contents($vendorKeyFile)) : '';
return getenv('BYTECODE_DEK') ?: getenv('BYTECODE_KEY') ?: getenv('OPDUMP_KEY') ?: getenv('BYTECODE_VENDOR_KEY') ?: $fileKey;
}
function decrypt_test_container(string $path): int
{
$container = parse_bytc($path);
if ($container['version'] !== 2) {
fail("{$path}: decrypt-test requires BYTC2");
}
$ikmHex = resolve_ikm_hex();
if (!preg_match('/\A[0-9a-fA-F]{64}\z/', $ikmHex)) {
fail('decrypt-test requires BYTECODE_KEY/OPDUMP_KEY/BYTECODE_VENDOR_KEY/BYTECODE_DEK or build/vendor-secret.key');
}
$aad = substr($container['bytes'], 0, $container['headerSize']);
$key = hash_hkdf('sha256', hex2bin($ikmHex), 32, 'bytecode-v2', $container['keyId']);
$plain = openssl_decrypt($container['ciphertext'], 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $container['nonce'], $container['tag'], $aad);
if ($plain === false) {
fail("{$path}: decrypt-test failed (wrong key or tampered container)");
}
if ($container['backendId'] === 'php-zend-opdump' && substr($plain, 0, 4) !== 'OPD2') {
fail("{$path}: decrypt-test payload is not OPD2");
}
return strlen($plain);
}
function verify_container(string $path, bool $decryptTest): array
{
$container = parse_bytc($path);
if ($container['phpVersionId'] !== PHP_VERSION_ID) {
fail("{$path}: PHP_VERSION_ID {$container['phpVersionId']} does not match " . PHP_VERSION_ID);
}
$isPhp = $container['backendId'] === 'php-zend-opdump' && $container['backendFormat'] === 'OPD2';
$isAsset = $container['backendId'] === 'bytecode-asset' && $container['backendFormat'] === 'RAW1';
if (!$isPhp && !$isAsset) {
fail("{$path}: unsupported backend {$container['backendId']}/{$container['backendFormat']}");
}
if ($container['version'] === 2 && $container['cipherId'] !== 1) {
fail("{$path}: unsupported cipher_id {$container['cipherId']}");
}
if (strlen($container['nonce']) !== 12 || strlen($container['tag']) !== 16) {
fail("{$path}: unsupported nonce/tag length");
}
$result = [
'path' => $path,
'backend' => $container['backendId'],
'backend_format' => $container['backendFormat'],
'sha256' => hash('sha256', $container['bytes']),
'size' => strlen($container['bytes']),
];
if ($decryptTest) {
$result['payload_size'] = decrypt_test_container($path);
}
return $result;
}
function seal_policy_message(array $seal): string
{
$keys = [
'machine_id',
'domains',
'ips',
'hostnames',
'fingerprints',
'expires_at',
'license_id',
'activation_token',
'revocation_url',
'unlock_policy',
];
$message = "bytecode-seal-policy-v1\n";
foreach ($keys as $key) {
$value = (string) ($seal[$key] ?? '');
$message .= $key . ':' . ($value !== '' ? $value : '-') . "\n";
}
return $message;
}
$args = array_slice($argv, 1);
if (!$args || in_array($args[0] ?? '', ['-h', '--help'], true)) {
fwrite(STDERR, "Usage: bytecode-verify [--decrypt-test] <manifest.json|encoded-file>\n");
fwrite(STDERR, "\nValidates BYTC headers, manifest hashes, sizes, map entries, and optionally decrypts every container.\n");
exit($args ? 0 : 2);
}
$decryptTest = false;
while ($args && str_starts_with($args[0], '-')) {
$arg = array_shift($args);
if ($arg === '--decrypt-test') {
$decryptTest = true;
continue;
}
fwrite(STDERR, "unknown option: {$arg}\n");
exit(2);
}
if (count($args) !== 1) {
fwrite(STDERR, "Usage: bytecode-verify [--decrypt-test] <manifest.json|encoded-file>\n");
exit(2);
}
$target = $args[0];
$baseDir = is_dir($target) ? $target : dirname($target);
$files = [];
if (is_dir($target)) {
$manifestPath = rtrim($target, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'bytecode.manifest.json';
} else {
$manifestPath = $target;
}
if (is_file($manifestPath) && substr($manifestPath, -5) === '.json') {
$manifest = json_decode(file_get_contents($manifestPath), true);
if (!is_array($manifest) || ($manifest['format'] ?? '') !== 'bytecode-manifest-v1') {
fail("invalid manifest: {$manifestPath}");
}
$baseDir = dirname($manifestPath);
$mapName = $manifest['map'] ?? 'bytecode.map';
$mapPath = $baseDir . DIRECTORY_SEPARATOR . $mapName;
$mapOutputs = [];
if (is_file($mapPath)) {
foreach (file($mapPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) {
if ($line[0] === '#') {
continue;
}
$parts = explode("\t", $line, 2);
if (count($parts) !== 2 || $parts[0] === '' || $parts[1] === '') {
fail("invalid map line in {$mapPath}");
}
$mapOutputs[$parts[1]] = $parts[0];
$mappedPath = $baseDir . DIRECTORY_SEPARATOR . $parts[1];
if (!is_file($mappedPath)) {
fail("{$mapPath}: mapped container missing: {$parts[1]}");
}
}
} else {
fail("manifest map missing: {$mapPath}");
}
foreach ($manifest['files'] ?? [] as $entry) {
$output = $entry['output'] ?? '';
$backend = $entry['backend'] ?? 'php-zend-opdump';
if ($backend === 'php-zend-opdump' && !isset($mapOutputs[$output])) {
fail("{$mapPath}: missing output for manifest entry {$output}");
}
$path = $baseDir . DIRECTORY_SEPARATOR . $output;
$result = verify_container($path, $decryptTest);
if (($entry['backend'] ?? '') !== '' && $entry['backend'] !== $result['backend']) {
fail("{$path}: manifest backend mismatch");
}
$expectedFormat = $entry['backend_format'] ?? ($backend === 'php-zend-opdump' ? 'OPD2' : '');
if ($expectedFormat !== '' && $expectedFormat !== $result['backend_format']) {
fail("{$path}: manifest backend_format mismatch");
}
if (($entry['sha256'] ?? '') !== $result['sha256']) {
fail("{$path}: manifest sha256 mismatch");
}
if (($entry['size'] ?? 0) !== $result['size']) {
fail("{$path}: manifest size mismatch");
}
$files[] = $path;
}
$sigPath = $baseDir . DIRECTORY_SEPARATOR . 'bytecode.manifest.sig';
if (!is_file($sigPath)) {
fail("manifest signature missing: {$sigPath}");
}
$sig = trim(file_get_contents($sigPath));
if (!preg_match('/\A[0-9a-f]{64}\z/', $sig)) {
fail("{$sigPath}: malformed signature (expected 64 hex chars)");
}
// Cryptographic verification needs the same IKM the loader resolves via
// BYTECODE_KEY/OPDUMP_KEY -- license-mode (RSA-wrapped DEK) builds can
// only get a structural check here without also implementing an RSA
// unwrap in this tool, so this stays a hex-shape check in that case.
$vendorKeyFile = getenv('BYTECODE_VENDOR_KEY_FILE') ?: dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'build' . DIRECTORY_SEPARATOR . 'vendor-secret.key';
$fileKey = is_file($vendorKeyFile) ? trim((string) file_get_contents($vendorKeyFile)) : '';
$ikmHex = getenv('BYTECODE_KEY') ?: getenv('OPDUMP_KEY') ?: getenv('BYTECODE_VENDOR_KEY') ?: $fileKey;
if (preg_match('/\A[0-9a-fA-F]{64}\z/', $ikmHex)) {
$sigKey = hash_hkdf('sha256', hex2bin($ikmHex), 32, 'bytecode-manifest-auth', '');
$expected = hash_hmac('sha256', file_get_contents($manifestPath) . "\0" . file_get_contents($mapPath), $sigKey);
if (!hash_equals($expected, $sig)) {
fail("{$sigPath}: signature mismatch (wrong key, or manifest/map tampered)");
}
}
// Vendor seal (bytecode.seal.json): structural digest check always; full
// Ed25519 signature check when a vendor public key PEM is provided via
// BYTECODE_VENDOR_PUBKEY or OPDUMP_VENDOR_PUBKEY_FILE -- the same anchor the
// loader trusts. This lets a build be verified end-to-end before shipping.
$sealPath = $baseDir . DIRECTORY_SEPARATOR . 'bytecode.seal.json';
if (is_file($sealPath)) {
$seal = json_decode(file_get_contents($sealPath), true);
if (!is_array($seal) || ($seal['format'] ?? '') !== 'bytecode-seal-v1' || ($seal['alg'] ?? '') !== 'Ed25519') {
fail("invalid bytecode.seal.json: {$sealPath}");
}
$manifestSha = hash_file('sha256', $manifestPath);
$mapSha = hash_file('sha256', $mapPath);
if (($seal['manifest_sha256'] ?? '') !== $manifestSha) {
fail("{$sealPath}: manifest_sha256 does not match bytecode.manifest.json");
}
if (($seal['map_sha256'] ?? '') !== $mapSha) {
fail("{$sealPath}: map_sha256 does not match bytecode.map");
}
$licensePath = $baseDir . DIRECTORY_SEPARATOR . 'bytecode.license.json';
$licenseSha = is_file($licensePath) ? hash_file('sha256', $licensePath) : null;
if ($licenseSha !== null) {
if (($seal['license_sha256'] ?? '') !== $licenseSha) {
fail("{$sealPath}: license_sha256 does not match bytecode.license.json");
}
} elseif (isset($seal['license_sha256'])) {
fail("{$sealPath}: seal covers a bytecode.license.json that is missing");
}
$policySha = $seal['policy_sha256'] ?? null;
if (is_string($policySha) && $policySha !== '') {
$actualPolicySha = hash('sha256', seal_policy_message($seal));
if (!hash_equals(strtolower($policySha), $actualPolicySha)) {
fail("{$sealPath}: policy_sha256 does not match signed policy fields");
}
}
$pubKey = getenv('BYTECODE_VENDOR_PUBKEY') ?: getenv('OPDUMP_VENDOR_PUBKEY_FILE') ?: '';
if ($pubKey !== '') {
if (!is_file($pubKey)) {
fail("vendor public key does not exist: {$pubKey}");
}
$message = "bytecode-seal-v1\n"
. "manifest:{$manifestSha}\n"
. "map:{$mapSha}\n"
. 'license:' . ($licenseSha ?? '-') . "\n";
if (is_string($policySha) && $policySha !== '') {
$message .= "policy:{$policySha}\n";
}
$signature = base64_decode((string) ($seal['signature'] ?? ''), true);
if ($signature === false || strlen($signature) !== 64) {
fail("{$sealPath}: malformed Ed25519 signature");
}
$msgTmp = tempnam(sys_get_temp_dir(), 'seal-msg');
$sigTmp = tempnam(sys_get_temp_dir(), 'seal-sig');
file_put_contents($msgTmp, $message);
file_put_contents($sigTmp, $signature);
$descriptors = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
$proc = proc_open(
['openssl', 'pkeyutl', '-verify', '-pubin', '-inkey', $pubKey, '-rawin', '-in', $msgTmp, '-sigfile', $sigTmp],
$descriptors,
$pipes
);
$stdout = $stderr = '';
if (is_resource($proc)) {
fclose($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exit = proc_close($proc);
} else {
$exit = 1;
}
@unlink($msgTmp);
@unlink($sigTmp);
if ($exit !== 0 || !str_contains($stdout . $stderr, 'Signature Verified Successfully')) {
fail("{$sealPath}: Ed25519 seal signature is NOT valid for {$pubKey}");
}
echo "vendor seal: Ed25519 signature verified against {$pubKey}", PHP_EOL;
} else {
echo "vendor seal: digests match (set BYTECODE_VENDOR_PUBKEY to verify the Ed25519 signature)", PHP_EOL;
}
}
} else {
verify_container($target, $decryptTest);
$files[] = $target;
}
echo 'verified ', count($files), ' file(s) metadata/hash/map consistency', PHP_EOL;
if ($decryptTest) {
echo 'decrypt-test: PASS', PHP_EOL;
}