0
# TLS Implementation
1
2
Complete TLS client and server implementation for secure network communications. Node-forge provides a pure JavaScript TLS implementation supporting multiple versions and cipher suites for secure data transmission.
3
4
## Capabilities
5
6
### TLS Connection Creation
7
8
Create TLS client and server connections with configurable security parameters.
9
10
```javascript { .api }
11
/**
12
* Create TLS connection
13
* @param options - TLS connection options
14
* @returns TLS connection object
15
*/
16
forge.tls.createConnection(options: TLSConnectionOptions): TLSConnection;
17
18
interface TLSConnectionOptions {
19
/** True for server mode, false for client mode */
20
server?: boolean;
21
/** Session ID for session resumption */
22
sessionId?: string;
23
/** Certificate store for trusted CAs */
24
caStore?: Certificate[] | CertificateStore;
25
/** Supported cipher suites */
26
cipherSuites?: CipherSuite[];
27
/** Supported TLS versions */
28
virtualHost?: string;
29
/** Verify callback for certificate validation */
30
verify?: (connection: TLSConnection, verified: boolean, depth: number, certs: Certificate[]) => boolean;
31
/** Connected callback */
32
connected?: (connection: TLSConnection) => void;
33
/** TLS ready callback */
34
tlsDataReady?: (connection: TLSConnection) => void;
35
/** Data ready callback */
36
dataReady?: (connection: TLSConnection) => void;
37
/** Closed callback */
38
closed?: (connection: TLSConnection) => void;
39
/** Error callback */
40
error?: (connection: TLSConnection, error: any) => void;
41
/** Get certificate callback (for server) */
42
getCertificate?: (connection: TLSConnection, hint: any) => Certificate;
43
/** Get private key callback (for server) */
44
getPrivateKey?: (connection: TLSConnection, cert: Certificate) => PrivateKey;
45
}
46
47
interface TLSConnection {
48
/** Connection version */
49
version: {major: number, minor: number};
50
/** Connection state */
51
state: {
52
serverConnectionEnd: boolean;
53
clientConnectionEnd: boolean;
54
read: string;
55
write: string;
56
};
57
/** Session information */
58
session: TLSSession;
59
/** Handshake state */
60
handshaking: boolean;
61
/** Handshake messages */
62
handshakes: any;
63
64
/**
65
* Prepare TLS data for transmission
66
* @param data - Data to send
67
*/
68
prepare(data: string): void;
69
70
/**
71
* Process received TLS data
72
* @param data - Received TLS data
73
*/
74
process(data: string): void;
75
76
/**
77
* Close TLS connection
78
* @param cleartext - True to close cleartext connection too
79
*/
80
close(cleartext?: boolean): void;
81
82
/** Buffer for TLS data ready to send */
83
tlsData: ByteStringBuffer;
84
/** Buffer for application data ready to read */
85
data: ByteStringBuffer;
86
/** True if TLS handshake is complete */
87
isConnected: boolean;
88
/** True if connection is closed */
89
isClosed: boolean;
90
}
91
92
interface TLSSession {
93
/** Session ID */
94
id: string;
95
/** TLS version */
96
version: {major: number, minor: number};
97
/** Negotiated cipher suite */
98
cipherSuite: CipherSuite;
99
/** Compression method */
100
compressionMethod: number;
101
/** Server certificate */
102
serverCertificate: Certificate;
103
/** Client certificate (if used) */
104
clientCertificate?: Certificate;
105
}
106
```
107
108
**Usage Examples:**
109
110
```javascript
111
const forge = require('node-forge');
112
113
// Create TLS client connection
114
const client = forge.tls.createConnection({
115
server: false,
116
caStore: [caCertificate], // Trusted CA certificates
117
virtualHost: 'example.com',
118
verify: (connection, verified, depth, certs) => {
119
console.log(`Certificate verification: ${verified} at depth ${depth}`);
120
return verified;
121
},
122
connected: (connection) => {
123
console.log('TLS handshake complete');
124
// Send application data
125
connection.prepare('GET / HTTP/1.1\r\nHost: example.com\r\n\r\n');
126
},
127
tlsDataReady: (connection) => {
128
// Send TLS data over the network
129
const tlsData = connection.tlsData.getBytes();
130
socket.write(tlsData);
131
},
132
dataReady: (connection) => {
133
// Process received application data
134
const appData = connection.data.getBytes();
135
console.log('Received:', appData);
136
},
137
error: (connection, error) => {
138
console.error('TLS error:', error);
139
}
140
});
141
142
// Create TLS server connection
143
const server = forge.tls.createConnection({
144
server: true,
145
getCertificate: (connection, hint) => {
146
return serverCertificate;
147
},
148
getPrivateKey: (connection, cert) => {
149
return serverPrivateKey;
150
},
151
connected: (connection) => {
152
console.log('Client connected via TLS');
153
},
154
dataReady: (connection) => {
155
const request = connection.data.getBytes();
156
console.log('Client request:', request);
157
158
// Send HTTP response
159
const response = 'HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World!';
160
connection.prepare(response);
161
}
162
});
163
164
// Process network data
165
socket.on('data', (data) => {
166
client.process(data.toString('binary'));
167
});
168
```
169
170
### TLS Cipher Suites
171
172
Supported cipher suites for TLS connections with different security levels.
173
174
```javascript { .api }
175
/**
176
* Available cipher suites
177
*/
178
forge.tls.CipherSuites: {
179
/** RSA with AES 128 CBC and SHA-1 */
180
TLS_RSA_WITH_AES_128_CBC_SHA: [0x00, 0x2f];
181
/** RSA with AES 256 CBC and SHA-1 */
182
TLS_RSA_WITH_AES_256_CBC_SHA: [0x00, 0x35];
183
/** RSA with AES 128 CBC and SHA-256 */
184
TLS_RSA_WITH_AES_128_CBC_SHA256: [0x00, 0x3c];
185
/** RSA with AES 256 CBC and SHA-256 */
186
TLS_RSA_WITH_AES_256_CBC_SHA256: [0x00, 0x3d];
187
/** RSA with 3DES EDE CBC and SHA-1 */
188
TLS_RSA_WITH_3DES_EDE_CBC_SHA: [0x00, 0x0a];
189
};
190
191
interface CipherSuite {
192
/** Cipher suite identifier */
193
id: number[];
194
/** Cipher suite name */
195
name: string;
196
/** Key exchange algorithm */
197
keyExchange: string;
198
/** Bulk cipher algorithm */
199
cipher: string;
200
/** MAC algorithm */
201
mac: string;
202
/** True if AEAD cipher */
203
aead: boolean;
204
}
205
```
206
207
**Usage Examples:**
208
209
```javascript
210
// Configure specific cipher suites
211
const secureConnection = forge.tls.createConnection({
212
server: false,
213
cipherSuites: [
214
forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA256,
215
forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA256
216
],
217
// ... other options
218
});
219
220
// Get supported cipher suites
221
const supportedSuites = Object.keys(forge.tls.CipherSuites);
222
console.log('Supported cipher suites:', supportedSuites);
223
```
224
225
### TLS Protocol Versions
226
227
Support for multiple TLS protocol versions with version negotiation.
228
229
```javascript { .api }
230
/**
231
* TLS version constants
232
*/
233
forge.tls.Versions: {
234
TLS_1_0: {major: 3, minor: 1};
235
TLS_1_1: {major: 3, minor: 2};
236
TLS_1_2: {major: 3, minor: 3};
237
};
238
239
/**
240
* Supported TLS versions array
241
*/
242
forge.tls.SupportedVersions: Array<{major: number, minor: number}>;
243
```
244
245
**Usage Examples:**
246
247
```javascript
248
// Force specific TLS version
249
const tlsConnection = forge.tls.createConnection({
250
server: false,
251
version: forge.tls.Versions.TLS_1_2, // Force TLS 1.2
252
// ... other options
253
});
254
255
// Check negotiated version
256
connection.connected = (conn) => {
257
console.log(`Connected using TLS ${conn.version.major}.${conn.version.minor}`);
258
};
259
```
260
261
### TLS Record Layer
262
263
Low-level TLS record layer operations for custom TLS implementations.
264
265
```javascript { .api }
266
/**
267
* TLS content types
268
*/
269
forge.tls.ContentType: {
270
change_cipher_spec: 20;
271
alert: 21;
272
handshake: 22;
273
application_data: 23;
274
heartbeat: 24;
275
};
276
277
/**
278
* TLS handshake types
279
*/
280
forge.tls.HandshakeType: {
281
hello_request: 0;
282
client_hello: 1;
283
server_hello: 2;
284
certificate: 11;
285
server_key_exchange: 12;
286
certificate_request: 13;
287
server_hello_done: 14;
288
certificate_verify: 15;
289
client_key_exchange: 16;
290
finished: 20;
291
};
292
293
/**
294
* TLS alert levels and descriptions
295
*/
296
forge.tls.Alert: {
297
Level: {
298
warning: 1;
299
fatal: 2;
300
};
301
Description: {
302
close_notify: 0;
303
unexpected_message: 10;
304
bad_record_mac: 20;
305
record_overflow: 22;
306
handshake_failure: 40;
307
bad_certificate: 42;
308
certificate_expired: 45;
309
certificate_unknown: 46;
310
internal_error: 80;
311
};
312
};
313
```
314
315
### TLS Session Management
316
317
Manage TLS sessions for connection resumption and performance optimization.
318
319
```javascript { .api }
320
/**
321
* Session cache for TLS resumption
322
*/
323
interface SessionCache {
324
/** Cache session */
325
setSession(id: string, session: TLSSession): void;
326
/** Retrieve session */
327
getSession(id: string): TLSSession | null;
328
/** Remove session */
329
removeSession(id: string): void;
330
/** Clear all sessions */
331
clear(): void;
332
}
333
334
/**
335
* Create session cache
336
*/
337
function createSessionCache(): SessionCache;
338
```
339
340
**Usage Examples:**
341
342
```javascript
343
// Create session cache for resumption
344
const sessionCache = {
345
sessions: new Map(),
346
347
setSession(id, session) {
348
this.sessions.set(id, {
349
...session,
350
timestamp: Date.now()
351
});
352
},
353
354
getSession(id) {
355
const session = this.sessions.get(id);
356
if (session && Date.now() - session.timestamp < 24 * 60 * 60 * 1000) { // 24 hours
357
return session;
358
}
359
this.sessions.delete(id);
360
return null;
361
},
362
363
removeSession(id) {
364
this.sessions.delete(id);
365
},
366
367
clear() {
368
this.sessions.clear();
369
}
370
};
371
372
// Use session cache with TLS connection
373
const connection = forge.tls.createConnection({
374
server: true,
375
sessionCache: sessionCache,
376
// ... other options
377
});
378
```
379
380
### TLS Extensions
381
382
Support for TLS extensions including SNI (Server Name Indication).
383
384
```javascript { .api }
385
/**
386
* Server Name Indication (SNI) support
387
*/
388
interface SNICallback {
389
(servername: string): {
390
certificate: Certificate;
391
privateKey: PrivateKey;
392
};
393
}
394
395
/**
396
* TLS extension support
397
*/
398
interface TLSExtensions {
399
/** Server name indication */
400
server_name?: string;
401
/** Application Layer Protocol Negotiation */
402
application_layer_protocol_negotiation?: string[];
403
}
404
```
405
406
**Usage Examples:**
407
408
```javascript
409
// Server with SNI support
410
const sniConnection = forge.tls.createConnection({
411
server: true,
412
getCertificate: (connection, hint) => {
413
const servername = hint.server_name || 'default';
414
const certs = {
415
'example.com': exampleCert,
416
'test.com': testCert,
417
'default': defaultCert
418
};
419
return certs[servername] || certs.default;
420
},
421
getPrivateKey: (connection, cert) => {
422
// Return corresponding private key
423
return privateKeys[cert.subject.getField('CN').value] || defaultPrivateKey;
424
}
425
});
426
427
// Client with SNI
428
const sniClient = forge.tls.createConnection({
429
server: false,
430
virtualHost: 'example.com', // Enables SNI
431
// ... other options
432
});
433
```
434
435
### Error Handling and Debugging
436
437
Handle TLS errors and debug connection issues.
438
439
```javascript
440
// Comprehensive error handling
441
const connection = forge.tls.createConnection({
442
server: false,
443
verify: (connection, verified, depth, certs) => {
444
if (!verified) {
445
console.warn(`Certificate verification failed at depth ${depth}`);
446
// Log certificate details for debugging
447
certs.forEach((cert, index) => {
448
console.log(`Certificate ${index}:`, {
449
subject: cert.subject.getField('CN')?.value,
450
issuer: cert.issuer.getField('CN')?.value,
451
validity: {
452
notBefore: cert.validity.notBefore,
453
notAfter: cert.validity.notAfter
454
}
455
});
456
});
457
}
458
return verified; // or return true to ignore certificate errors (not recommended)
459
},
460
error: (connection, error) => {
461
console.error('TLS Error:', {
462
message: error.message,
463
alertLevel: error.level,
464
alertDescription: error.description
465
});
466
467
// Handle specific error types
468
if (error.description === forge.tls.Alert.Description.certificate_expired) {
469
console.error('Server certificate has expired');
470
} else if (error.description === forge.tls.Alert.Description.handshake_failure) {
471
console.error('TLS handshake failed - check cipher suite compatibility');
472
}
473
},
474
closed: (connection) => {
475
console.log('TLS connection closed');
476
if (connection.error) {
477
console.log('Connection closed due to error:', connection.error);
478
}
479
}
480
});
481
482
// Debug handshake process
483
connection.handshaking = true;
484
connection.handshakes = forge.tls.createHandshakes(connection);
485
486
// Monitor handshake messages
487
const originalProcess = connection.process;
488
connection.process = function(data) {
489
console.log('Processing TLS data:', data.length, 'bytes');
490
const result = originalProcess.call(this, data);
491
492
if (this.handshaking) {
493
console.log('Handshake state:', this.state);
494
}
495
496
return result;
497
};
498
499
try {
500
// TLS operations
501
connection.process(tlsData);
502
connection.prepare(applicationData);
503
504
} catch (error) {
505
// Handle errors:
506
// - Handshake failures
507
// - Certificate verification errors
508
// - Protocol version mismatches
509
// - Cipher suite incompatibilities
510
// - Network connectivity issues
511
console.error('TLS operation failed:', error.message);
512
}
513
```
514
515
### Performance Optimization
516
517
Optimize TLS connections for better performance.
518
519
**Usage Examples:**
520
521
```javascript
522
// Connection pooling for clients
523
class TLSConnectionPool {
524
constructor(options) {
525
this.options = options;
526
this.connections = new Map();
527
this.maxConnections = 10;
528
}
529
530
getConnection(host) {
531
if (!this.connections.has(host)) {
532
const connection = forge.tls.createConnection({
533
...this.options,
534
virtualHost: host
535
});
536
this.connections.set(host, connection);
537
}
538
return this.connections.get(host);
539
}
540
541
closeAll() {
542
for (const [host, connection] of this.connections) {
543
connection.close();
544
}
545
this.connections.clear();
546
}
547
}
548
549
// Optimized buffer management
550
function optimizedTLSHandler(connection) {
551
let dataBuffer = forge.util.createBuffer();
552
553
connection.dataReady = (conn) => {
554
// Accumulate data to reduce processing overhead
555
dataBuffer.putBytes(conn.data.getBytes());
556
557
// Process complete messages
558
while (dataBuffer.length() >= expectedMessageLength) {
559
const message = dataBuffer.getBytes(expectedMessageLength);
560
processMessage(message);
561
}
562
};
563
}
564
```