-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathplugin-signature-verifier.ts
More file actions
359 lines (307 loc) · 10.5 KB
/
Copy pathplugin-signature-verifier.ts
File metadata and controls
359 lines (307 loc) · 10.5 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
import type { Logger } from '@objectstack/spec/contracts';
import type { PluginMetadata } from '../plugin-loader.js';
// Conditionally import crypto for Node.js environments
let cryptoModule: typeof import('crypto') | null = null;
if (typeof (globalThis as any).window === 'undefined') {
try {
// Dynamic import for Node.js crypto module (using eval to avoid bundling issues)
// @ts-ignore - dynamic require for Node.js
cryptoModule = eval('require("crypto")');
} catch {
// Crypto module not available (e.g., browser environment)
}
}
/**
* Plugin Signature Configuration
* Controls how plugin signatures are verified
*/
export interface PluginSignatureConfig {
/**
* Map of publisher IDs to their trusted public keys
* Format: { 'com.objectstack': '-----BEGIN PUBLIC KEY-----...' }
*/
trustedPublicKeys: Map<string, string>;
/**
* Signature algorithm to use
* - RS256: RSA with SHA-256
* - ES256: ECDSA with SHA-256
*/
algorithm: 'RS256' | 'ES256';
/**
* Strict mode: reject plugins without signatures
* - true: All plugins must be signed
* - false: Unsigned plugins are allowed with warning
*/
strictMode: boolean;
/**
* Allow self-signed plugins in development
*/
allowSelfSigned?: boolean;
}
/**
* Plugin Signature Verification Result
*/
export interface SignatureVerificationResult {
verified: boolean;
error?: string;
publisherId?: string;
algorithm?: string;
signedAt?: Date;
}
/**
* Plugin Signature Verifier
*
* Implements cryptographic verification of plugin signatures to ensure:
* 1. Plugin integrity - code hasn't been tampered with
* 2. Publisher authenticity - plugin comes from trusted source
* 3. Non-repudiation - publisher cannot deny signing
*
* Architecture:
* - Uses Node.js crypto module for signature verification
* - Supports RSA (RS256) and ECDSA (ES256) algorithms
* - Verifies against trusted public key registry
* - Computes hash of plugin code for integrity check
*
* Security Model:
* - Public keys are pre-registered and trusted
* - Plugin signature is verified before loading
* - Strict mode rejects unsigned plugins
* - Development mode allows self-signed plugins
*/
export class PluginSignatureVerifier {
private config: PluginSignatureConfig;
private logger: Logger;
constructor(config: PluginSignatureConfig, logger: Logger) {
this.config = config;
this.logger = logger;
this.validateConfig();
}
/**
* Verify plugin signature
*
* @param plugin - Plugin metadata with signature
* @returns Verification result
* @throws Error if verification fails in strict mode
*/
async verifyPluginSignature(plugin: PluginMetadata): Promise<SignatureVerificationResult> {
// Handle unsigned plugins
if (!plugin.signature) {
return this.handleUnsignedPlugin(plugin);
}
try {
// 1. Extract publisher ID from plugin name (reverse domain notation)
const publisherId = this.extractPublisherId(plugin.name);
// 2. Get trusted public key for publisher
const publicKey = this.config.trustedPublicKeys.get(publisherId);
if (!publicKey) {
const error = `No trusted public key for publisher: ${publisherId}`;
this.logger.warn(error, { plugin: plugin.name, publisherId });
if (this.config.strictMode && !this.config.allowSelfSigned) {
throw new Error(error);
}
return {
verified: false,
error,
publisherId,
};
}
// 3. Compute plugin code hash
const pluginHash = this.computePluginHash(plugin);
// 4. Verify signature using crypto module
const isValid = await this.verifyCryptoSignature(
pluginHash,
plugin.signature,
publicKey
);
if (!isValid) {
const error = `Signature verification failed for plugin: ${plugin.name}`;
this.logger.error(error, undefined, { plugin: plugin.name, publisherId });
throw new Error(error);
}
this.logger.info(`✅ Plugin signature verified: ${plugin.name}`, {
plugin: plugin.name,
publisherId,
algorithm: this.config.algorithm,
});
return {
verified: true,
publisherId,
algorithm: this.config.algorithm,
};
} catch (error) {
this.logger.error(`Signature verification error: ${plugin.name}`, error as Error);
if (this.config.strictMode) {
throw error;
}
return {
verified: false,
error: (error as Error).message,
};
}
}
/**
* Register a trusted public key for a publisher
*/
registerPublicKey(publisherId: string, publicKey: string): void {
this.config.trustedPublicKeys.set(publisherId, publicKey);
this.logger.info(`Trusted public key registered for: ${publisherId}`);
}
/**
* Remove a trusted public key
*/
revokePublicKey(publisherId: string): void {
this.config.trustedPublicKeys.delete(publisherId);
this.logger.warn(`Public key revoked for: ${publisherId}`);
}
/**
* Get list of trusted publishers
*/
getTrustedPublishers(): string[] {
return Array.from(this.config.trustedPublicKeys.keys());
}
// Private methods
private handleUnsignedPlugin(plugin: PluginMetadata): SignatureVerificationResult {
if (this.config.strictMode) {
const error = `Plugin missing signature (strict mode): ${plugin.name}`;
this.logger.error(error, undefined, { plugin: plugin.name });
throw new Error(error);
}
this.logger.warn(`⚠️ Plugin not signed: ${plugin.name}`, {
plugin: plugin.name,
recommendation: 'Consider signing plugins for production environments',
});
return {
verified: false,
error: 'Plugin not signed',
};
}
private extractPublisherId(pluginName: string): string {
// Extract publisher from reverse domain notation
// Example: "com.objectstack.engine.objectql" -> "com.objectstack"
const parts = pluginName.split('.');
if (parts.length < 2) {
throw new Error(`Invalid plugin name format: ${pluginName} (expected reverse domain notation)`);
}
// Return first two parts (domain reversed)
return `${parts[0]}.${parts[1]}`;
}
private computePluginHash(plugin: PluginMetadata): string {
// In browser environment, use SubtleCrypto
if (typeof (globalThis as any).window !== 'undefined') {
return this.computePluginHashBrowser(plugin);
}
// In Node.js environment, use crypto module
return this.computePluginHashNode(plugin);
}
private computePluginHashNode(plugin: PluginMetadata): string {
// Use pre-loaded crypto module
if (!cryptoModule) {
this.logger.warn('crypto module not available, using fallback hash');
return this.computePluginHashFallback(plugin);
}
// Compute hash of plugin code
const pluginCode = this.serializePluginCode(plugin);
return cryptoModule.createHash('sha256').update(pluginCode).digest('hex');
}
private computePluginHashBrowser(plugin: PluginMetadata): string {
// Browser environment - use simple hash for now
// In production, should use SubtleCrypto for proper cryptographic hash
this.logger.debug('Using browser hash (SubtleCrypto integration pending)');
return this.computePluginHashFallback(plugin);
}
private computePluginHashFallback(plugin: PluginMetadata): string {
// Simple hash fallback (not cryptographically secure)
const pluginCode = this.serializePluginCode(plugin);
let hash = 0;
for (let i = 0; i < pluginCode.length; i++) {
const char = pluginCode.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32-bit integer
}
return hash.toString(16);
}
private serializePluginCode(plugin: PluginMetadata): string {
// Serialize plugin code for hashing
// Include init, start, destroy functions
const parts: string[] = [
plugin.name,
plugin.version,
plugin.init.toString(),
];
if (plugin.start) {
parts.push(plugin.start.toString());
}
if (plugin.destroy) {
parts.push(plugin.destroy.toString());
}
return parts.join('|');
}
private async verifyCryptoSignature(
data: string,
signature: string,
publicKey: string
): Promise<boolean> {
// In browser environment, use SubtleCrypto
if (typeof (globalThis as any).window !== 'undefined') {
return this.verifyCryptoSignatureBrowser(data, signature, publicKey);
}
// In Node.js environment, use crypto module
return this.verifyCryptoSignatureNode(data, signature, publicKey);
}
private verifyCryptoSignatureNode(
data: string,
signature: string,
publicKey: string
): boolean {
if (!cryptoModule) {
this.logger.error('Crypto module not available for signature verification');
return false;
}
try {
// Create verify object based on algorithm
if (this.config.algorithm === 'ES256') {
// ECDSA verification - requires lowercase 'sha256'
const verify = cryptoModule.createVerify('sha256');
verify.update(data);
return verify.verify(
{
key: publicKey,
format: 'pem',
type: 'spki',
},
signature,
'base64'
);
} else {
// RSA verification (RS256)
const verify = cryptoModule.createVerify('RSA-SHA256');
verify.update(data);
return verify.verify(publicKey, signature, 'base64');
}
} catch (error) {
this.logger.error('Signature verification failed', error as Error);
return false;
}
}
private async verifyCryptoSignatureBrowser(
_data: string,
_signature: string,
_publicKey: string
): Promise<boolean> {
// Browser implementation using SubtleCrypto
// TODO: Implement SubtleCrypto-based verification
this.logger.warn('Browser signature verification not yet implemented');
return false;
}
private validateConfig(): void {
if (!this.config.trustedPublicKeys || this.config.trustedPublicKeys.size === 0) {
this.logger.warn('No trusted public keys configured - all signatures will fail');
}
if (!this.config.algorithm) {
throw new Error('Signature algorithm must be specified');
}
if (!['RS256', 'ES256'].includes(this.config.algorithm)) {
throw new Error(`Unsupported algorithm: ${this.config.algorithm}`);
}
}
}