-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
725 lines (626 loc) · 25.2 KB
/
server.js
File metadata and controls
725 lines (626 loc) · 25.2 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
const WebSocket = require('ws');
const http = require('http');
const crypto = require('crypto');
const KeyManager = require('./key_manager');
/**
* Servidor Node.js para triangulação de conexões WebSocket
* Atua como intermediário conectando múltiplos clientes entre si
*
* SEGURANÇA:
* - Autenticação com chave secreta
* - Validação de assinatura HMAC nas mensagens
* - Token de sessão único
* - Validação de versão do software
*/
class WebSocketTriangulationServer {
constructor(port = 8080, secretKey = null) {
this.port = port;
this.clients = new Map(); // Map<clientId, {ws, metadata, token, authenticated, macAddress}>
this.clientCounter = 0;
this.server = null;
this.wss = null;
// Gerenciador de chaves dinâmicas
this.keyManager = new KeyManager('./keys_storage.json');
// Chave padrão (para primeira conexão - mantida para compatibilidade)
this.secretKey = this.keyManager.getDefaultKey();
if (secretKey) {
// Se fornecido explicitamente, atualiza chave padrão
this.keyManager.defaultKey = secretKey;
this.secretKey = secretKey;
}
this.softwareVersion = '1.0.0'; // Versão do software autorizado
this.softwareChecksum = process.env.SOFTWARE_CHECKSUM || null; // Checksum opcional
// Tokens pendentes de autenticação (temporário)
this.pendingAuth = new Map(); // Map<clientId, {challenge, timestamp}>
this.authTimeout = 30000; // 30 segundos para autenticar
console.log(`[Segurança] Sistema de chaves dinâmicas ativado`);
console.log(`[Segurança] Chave padrão: ${this.secretKey.substring(0, 8)}...`);
if (this.softwareChecksum) {
console.log(`[Segurança] Checksum do software validado`);
}
}
/**
* Gera chave secreta aleatória
*/
generateSecretKey() {
return crypto.randomBytes(32).toString('hex');
}
/**
* Gera hash HMAC para validação
*/
generateHMAC(data) {
return crypto.createHmac('sha256', this.secretKey)
.update(JSON.stringify(data))
.digest('hex');
}
/**
* Valida assinatura HMAC
*/
validateHMAC(data, signature) {
const expectedHMAC = this.generateHMAC(data);
return crypto.timingSafeEqual(
Buffer.from(signature, 'hex'),
Buffer.from(expectedHMAC, 'hex')
);
}
/**
* Gera token de sessão único
*/
generateSessionToken() {
return crypto.randomBytes(32).toString('hex');
}
/**
* Gera challenge para autenticação
*/
generateChallenge() {
return crypto.randomBytes(16).toString('hex');
}
/**
* Gera um ID único para cada cliente
*/
generateClientId() {
return `client_${++this.clientCounter}_${Date.now()}`;
}
/**
* Inicia o servidor WebSocket
*/
start() {
// Cria servidor HTTP
this.server = http.createServer();
// Cria servidor WebSocket
this.wss = new WebSocket.Server({
server: this.server,
perMessageDeflate: false,
maxPayload: 10 * 1024 * 1024 // 10MB para suportar imagens de tela
});
this.wss.on('connection', (ws, req) => {
this.handleConnection(ws, req);
});
this.server.listen(this.port, () => {
console.log(`[Servidor] Iniciado na porta ${this.port}`);
console.log(`[Servidor] Aguardando conexões WebSocket...`);
});
}
/**
* Manipula nova conexão de cliente
*/
handleConnection(ws, req) {
const clientId = this.generateClientId();
const clientIp = req.socket.remoteAddress;
// Armazena informações do cliente (não autenticado ainda)
this.clients.set(clientId, {
ws: ws,
id: clientId,
ip: clientIp,
connectedAt: new Date(),
authenticated: false,
token: null,
metadata: {}
});
console.log(`[Conexão] Cliente ${clientId.substring(0, 20)}... conectado de ${clientIp}`);
// Gera challenge para autenticação
const challenge = this.generateChallenge();
const timestamp = Date.now();
this.pendingAuth.set(clientId, { challenge, timestamp });
// Envia challenge para autenticação (TEMPO LIMITADO)
this.sendToClient(clientId, {
type: 'auth_challenge',
challenge: challenge,
timestamp: timestamp,
version: this.softwareVersion
});
// Timeout para autenticação
setTimeout(() => {
if (this.clients.has(clientId) && !this.clients.get(clientId).authenticated) {
console.log(`[Segurança] Cliente ${clientId} não autenticado a tempo - desconectando`);
this.handleDisconnection(clientId);
}
}, this.authTimeout);
// Manipula mensagens recebidas
ws.on('message', (data) => {
try {
const message = JSON.parse(data.toString());
// Verifica se o cliente ainda existe (pode ter sido desconectado)
const client = this.clients.get(clientId);
if (!client) {
// Cliente já foi desconectado, ignora mensagem
return;
}
// Se não está autenticado, só aceita mensagens de autenticação
if (!client.authenticated && message.type !== 'auth_response') {
console.log(`[⚠] Cliente ${clientId.substring(0, 20)}... tentou enviar mensagem sem autenticação`);
this.sendToClient(clientId, {
type: 'error',
message: 'Autenticação necessária'
});
this.handleDisconnection(clientId);
return;
}
// Validação de assinatura removida - autenticação é feita apenas uma vez na conexão
// A autenticação inicial já garante que o cliente é válido
// Descomentar abaixo apenas se precisar de validação de integridade por mensagem
/*
if (client.authenticated && message.type !== 'ping' && message.type !== 'pong') {
if (!this.validateMessageSignature(clientId, message)) {
this.handleDisconnection(clientId);
return;
}
}
*/
this.handleMessage(clientId, message);
} catch (error) {
console.error(`[Erro] Erro ao processar mensagem de ${clientId}:`, error.message);
// Só tenta enviar erro se o cliente ainda existir
if (this.clients.has(clientId)) {
this.sendToClient(clientId, {
type: 'error',
message: 'Formato de mensagem inválido'
});
}
}
});
// Manipula desconexão
ws.on('close', () => {
this.handleDisconnection(clientId);
});
// Manipula erros
ws.on('error', (error) => {
console.error(`[Erro] Erro na conexão de ${clientId}:`, error.message);
this.handleDisconnection(clientId);
});
}
/**
* Ordena objeto recursivamente para garantir ordem consistente no JSON
* Usa a mesma lógica do Python json.dumps(..., sort_keys=True)
*/
sortObjectKeys(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
// Arrays mantêm ordem, mas ordena objetos dentro deles
if (Array.isArray(obj)) {
return obj.map(item => this.sortObjectKeys(item));
}
// Objetos: ordena chaves alfabeticamente (como Python sort_keys=True)
const sorted = {};
const keys = Object.keys(obj).sort();
for (const key of keys) {
sorted[key] = this.sortObjectKeys(obj[key]);
}
return sorted;
}
/**
* Valida assinatura de mensagem
*/
validateMessageSignature(clientId, message) {
const client = this.clients.get(clientId);
if (!client || !client.token) {
return false;
}
// Remove assinatura antes de validar
const signature = message._sig;
const messageWithoutSig = { ...message };
delete messageWithoutSig._sig;
if (!signature) {
return false;
}
// Ordena chaves para garantir consistência com Python (sort_keys=True)
const sortedMessage = this.sortObjectKeys(messageWithoutSig);
// Usa os mesmos separadores do Python: separators=(',', ':') -> sem espaços
const messageJson = JSON.stringify(sortedMessage);
// Valida usando token do cliente
// Token é uma string hexadecimal, precisa converter para Buffer
const tokenBuffer = Buffer.from(client.token, 'hex');
const expectedHMAC = crypto.createHmac('sha256', tokenBuffer)
.update(messageJson)
.digest('hex');
const isValid = crypto.timingSafeEqual(
Buffer.from(signature, 'hex'),
Buffer.from(expectedHMAC, 'hex')
);
// Log apenas em caso de erro com mais detalhes
if (!isValid) {
console.log(`[⚠] Assinatura inválida de ${clientId.substring(0, 20)}... (tipo: ${messageWithoutSig.type || 'desconhecido'})`);
console.log(`[DEBUG] Mensagem JSON esperada: ${messageJson.substring(0, 200)}...`);
console.log(`[DEBUG] Assinatura recebida: ${signature.substring(0, 20)}...`);
console.log(`[DEBUG] Assinatura esperada: ${expectedHMAC.substring(0, 20)}...`);
}
return isValid;
}
/**
* Adiciona assinatura a mensagem antes de enviar
*/
signMessage(clientId, message) {
const client = this.clients.get(clientId);
if (client && client.token) {
// Ordena chaves para garantir consistência com Python (sort_keys=True)
const sortedMessage = this.sortObjectKeys(message);
// Token é uma string hexadecimal, precisa converter para Buffer
const tokenBuffer = Buffer.from(client.token, 'hex');
const signature = crypto.createHmac('sha256', tokenBuffer)
.update(JSON.stringify(sortedMessage))
.digest('hex');
message._sig = signature;
}
return message;
}
/**
* Manipula mensagens recebidas dos clientes
*/
handleMessage(fromClientId, message) {
const { type, target, data } = message;
switch (type) {
case 'auth_response':
// Processa autenticação
this.handleAuthentication(fromClientId, message);
break;
case 'ping':
// Responde ping com pong
this.sendToClient(fromClientId, {
type: 'pong',
timestamp: Date.now()
});
break;
case 'send':
// Envia mensagem para cliente específico
if (target) {
this.routeMessage(fromClientId, target, data);
} else {
this.sendToClient(fromClientId, {
type: 'error',
message: 'Destino não especificado'
});
}
break;
case 'broadcast':
// Envia mensagem para todos os clientes (exceto o remetente)
this.broadcastMessage(fromClientId, data);
break;
case 'get_clients':
// Retorna lista de clientes conectados
this.sendClientList(fromClientId);
break;
case 'set_metadata':
// Atualiza metadados do cliente
if (this.clients.has(fromClientId)) {
this.clients.get(fromClientId).metadata = {
...this.clients.get(fromClientId).metadata,
...data
};
this.sendToClient(fromClientId, {
type: 'metadata_updated',
metadata: this.clients.get(fromClientId).metadata
});
}
break;
default:
console.log(`[Mensagem] Tipo desconhecido: ${type} de ${fromClientId}`);
this.sendToClient(fromClientId, {
type: 'error',
message: `Tipo de mensagem desconhecido: ${type}`
});
}
}
/**
* Roteia mensagem de um cliente para outro
*/
routeMessage(fromClientId, toClientId, data) {
if (!this.clients.has(toClientId)) {
this.sendToClient(fromClientId, {
type: 'error',
message: `Cliente ${toClientId} não encontrado`
});
return;
}
const fromClient = this.clients.get(fromClientId);
const toClient = this.clients.get(toClientId);
// Envia mensagem para o destinatário
this.sendToClient(toClientId, {
type: 'message',
from: fromClientId,
data: data,
timestamp: Date.now()
});
// Confirma envio ao remetente
this.sendToClient(fromClientId, {
type: 'sent',
to: toClientId,
timestamp: Date.now()
});
console.log(`[Roteamento] ${fromClientId} -> ${toClientId}`);
}
/**
* Envia mensagem para todos os clientes (exceto o remetente)
*/
broadcastMessage(fromClientId, data) {
let sentCount = 0;
this.clients.forEach((client, clientId) => {
if (clientId !== fromClientId) {
this.sendToClient(clientId, {
type: 'broadcast',
from: fromClientId,
data: data,
timestamp: Date.now()
});
sentCount++;
}
});
// Confirma broadcast ao remetente
this.sendToClient(fromClientId, {
type: 'broadcast_sent',
recipients: sentCount,
timestamp: Date.now()
});
console.log(`[Broadcast] ${fromClientId} enviou para ${sentCount} clientes`);
}
/**
* Processa autenticação do cliente
*/
handleAuthentication(clientId, message) {
const client = this.clients.get(clientId);
if (!client) {
return;
}
const pending = this.pendingAuth.get(clientId);
if (!pending) {
console.log(`[Segurança] Cliente ${clientId} tentou autenticar sem challenge`);
this.handleDisconnection(clientId);
return;
}
const { challenge, timestamp } = pending;
const { clientSecret, response, softwareVersion, softwareChecksum, macAddress, isFirstConnection, deviceToken } = message;
// Valida timeout
if (Date.now() - timestamp > this.authTimeout) {
console.log(`[Segurança] Challenge expirado para ${clientId}`);
this.pendingAuth.delete(clientId);
this.handleDisconnection(clientId);
return;
}
// Valida versão do software
if (softwareVersion !== this.softwareVersion) {
console.log(`[Segurança] Versão do software inválida: ${softwareVersion} (esperado: ${this.softwareVersion})`);
this.sendToClient(clientId, {
type: 'auth_error',
message: 'Versão do software não autorizada'
});
this.handleDisconnection(clientId);
return;
}
// Valida checksum se configurado
if (this.softwareChecksum && softwareChecksum !== this.softwareChecksum) {
console.log(`[Segurança] Checksum do software inválido para ${clientId}`);
this.sendToClient(clientId, {
type: 'auth_error',
message: 'Software não autorizado'
});
this.handleDisconnection(clientId);
return;
}
// Valida MAC address
if (!macAddress) {
console.log(`[Segurança] MAC address não fornecido por ${clientId}`);
this.sendToClient(clientId, {
type: 'auth_error',
message: 'MAC address não fornecido'
});
this.handleDisconnection(clientId);
return;
}
// Normaliza MAC address
const macNormalized = this.keyManager.normalizeMac(macAddress);
client.macAddress = macNormalized;
// Verifica se é primeira conexão ou conexão subsequente
const isDeviceRegistered = this.keyManager.isDeviceRegistered(macNormalized);
const isFirstConn = (isFirstConnection === true) || (!isDeviceRegistered);
let authValid = false;
let shouldSendDeviceToken = false;
if (isFirstConn) {
// Primeira conexão: valida usando chave padrão
const expectedResponse = crypto.createHmac('sha256', this.secretKey)
.update(challenge + (clientSecret || ''))
.digest('hex');
if (response === expectedResponse) {
authValid = true;
// Registra dispositivo
this.keyManager.registerDevice(macNormalized);
// Deve enviar token derivado
shouldSendDeviceToken = true;
console.log(`[Segurança] Primeira conexão validada para MAC ${macNormalized.substring(0, 12)}...`);
}
} else {
// Conexão subsequente: valida usando token derivado
if (deviceToken) {
// Valida token derivado
if (this.keyManager.validateDeviceToken(macNormalized, deviceToken)) {
authValid = true;
// Valida também a resposta do challenge (para garantir que o cliente conhece o token)
const expectedResponse = crypto.createHmac('sha256', deviceToken)
.update(challenge + (clientSecret || ''))
.digest('hex');
if (response !== expectedResponse) {
authValid = false;
console.log(`[Segurança] Resposta do challenge inválida para ${macNormalized.substring(0, 12)}...`);
} else {
this.keyManager.updateDeviceLastSeen(macNormalized);
console.log(`[Segurança] Conexão subsequente validada para MAC ${macNormalized.substring(0, 12)}...`);
}
} else {
console.log(`[Segurança] Token derivado inválido para MAC ${macNormalized.substring(0, 12)}...`);
}
} else {
console.log(`[Segurança] Token derivado não fornecido para dispositivo registrado ${macNormalized.substring(0, 12)}...`);
}
}
if (!authValid) {
console.log(`[Segurança] Autenticação falhou para ${clientId} (MAC: ${macNormalized.substring(0, 12)}...)`);
this.sendToClient(clientId, {
type: 'auth_error',
message: 'Autenticação falhou'
});
this.handleDisconnection(clientId);
return;
}
// Autenticação bem-sucedida
const sessionToken = this.generateSessionToken();
client.authenticated = true;
client.token = sessionToken;
this.pendingAuth.delete(clientId);
console.log(`[✓] Cliente ${clientId.substring(0, 20)}... autenticado`);
// Prepara resposta de conexão
const connectionMessage = {
type: 'connection',
status: 'connected',
clientId: clientId,
token: sessionToken,
message: 'Autenticado e conectado ao servidor'
};
// Se é primeira conexão, envia token derivado
if (shouldSendDeviceToken) {
const deviceToken = this.keyManager.generateDeviceToken(macNormalized);
connectionMessage.deviceToken = deviceToken;
connectionMessage.isFirstConnection = true;
console.log(`[Segurança] Token derivado enviado para MAC ${macNormalized.substring(0, 12)}...`);
}
// Envia confirmação de conexão ao cliente
this.sendToClient(clientId, connectionMessage);
// Envia lista de clientes conectados
this.broadcastClientList();
}
/**
* Envia mensagem para um cliente específico
*/
sendToClient(clientId, message) {
if (!this.clients.has(clientId)) {
// Não loga erro aqui para evitar spam quando cliente já foi desconectado
return;
}
const client = this.clients.get(clientId);
if (!client) {
return;
}
if (client.ws && client.ws.readyState === WebSocket.OPEN) {
try {
// Assinatura removida - não precisa assinar mensagens do servidor
// Autenticação é feita apenas uma vez na conexão inicial
// Descomentar abaixo apenas se precisar assinar mensagens do servidor
/*
if (client.authenticated && message.type !== 'auth_challenge' && message.type !== 'auth_error') {
message = this.signMessage(clientId, message);
}
*/
client.ws.send(JSON.stringify(message));
} catch (error) {
console.error(`[Erro] Erro ao enviar para ${clientId}:`, error.message);
this.handleDisconnection(clientId);
}
}
}
/**
* Retorna lista de clientes para um cliente específico
*/
sendClientList(clientId) {
const clientsList = Array.from(this.clients.values()).map(client => ({
id: client.id,
ip: client.ip,
connectedAt: client.connectedAt,
metadata: client.metadata
}));
this.sendToClient(clientId, {
type: 'clients_list',
clients: clientsList,
total: clientsList.length
});
}
/**
* Envia lista atualizada de clientes para todos
*/
broadcastClientList() {
const clientsList = Array.from(this.clients.values()).map(client => ({
id: client.id,
ip: client.ip,
connectedAt: client.connectedAt,
metadata: client.metadata
}));
this.clients.forEach((client, clientId) => {
this.sendToClient(clientId, {
type: 'clients_updated',
clients: clientsList,
total: clientsList.length
});
});
}
/**
* Manipula desconexão de cliente
*/
handleDisconnection(clientId) {
if (this.clients.has(clientId)) {
this.clients.delete(clientId);
console.log(`[✗] Cliente ${clientId.substring(0, 20)}... desconectado (Total: ${this.clients.size})`);
// Notifica outros clientes sobre a desconexão
this.broadcastClientList();
}
}
/**
* Para o servidor
*/
stop() {
console.log('[Servidor] Encerrando servidor...');
// Fecha todas as conexões
this.clients.forEach((client, clientId) => {
if (client.ws.readyState === WebSocket.OPEN) {
client.ws.close();
}
});
this.clients.clear();
if (this.wss) {
this.wss.close();
}
if (this.server) {
this.server.close(() => {
console.log('[Servidor] Servidor encerrado');
});
}
}
}
// Inicia o servidor
const PORT = process.env.PORT || 8080;
// DEFINA A CHAVE SECRETA AQUI (ou use variável de ambiente SECRET_KEY)
const SECRET_KEY = process.env.SECRET_KEY || "minha_chave_secreta_12345"; // Altere para uma chave segura
const server = new WebSocketTriangulationServer(PORT, SECRET_KEY);
server.start();
// Exibe chave secreta se foi gerada automaticamente (para uso pelos clientes)
if (!process.env.SECRET_KEY) {
console.log(`[IMPORTANTE] Chave secreta gerada: ${server.secretKey}`);
console.log(`[IMPORTANTE] Configure esta chave nos clientes ou use: export SECRET_KEY=${server.secretKey}`);
}
// Tratamento de encerramento gracioso
process.on('SIGINT', () => {
console.log('\n[SIGINT] Recebido sinal de encerramento...');
server.stop();
process.exit(0);
});
process.on('SIGTERM', () => {
console.log('\n[SIGTERM] Recebido sinal de encerramento...');
server.stop();
process.exit(0);
});