-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgo_tcp_server.go
1631 lines (1367 loc) · 49.8 KB
/
go_tcp_server.go
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
IMPROVED TCP SERVER FOR LINUX CLOUD REPORT
Key fixes implemented:
1. INIT Response Format - Ensured exact format matching with "200-KEY=xxx\r\n200 LEN=y\r\n"
2. Crypto Key Generation - Fixed special handling for ID=9 with hardcoded key "D5F22NE-"
3. INFO Command Response - Added proper formatting with ID, expiry date, and validation fields
4. MD5 Hashing - Used MD5 instead of SHA1 for AES key generation to match Delphi's DCPcrypt
5. Base64 Handling - Improved padding handling for Base64 encoding/decoding
6. Enhanced Logging - Added detailed logging at each step of encryption/decryption
7. Validation - Added encryption validation testing with sample data
This improved server should correctly handle authentication with the Delphi client.
*/
package main
import (
"bufio"
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"encoding/base64"
"fmt"
"io"
"log"
"math/rand"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"compress/zlib"
"io/ioutil"
)
// Configuration constants
const (
DEBUG_MODE = true
USE_FIXED_DEBUG_KEY = true
KEY_LENGTH = 4 // 4 characters like in logs
CONNECTION_TIMEOUT = 300 // 5 minutes
INACTIVITY_CHECK_INT = 60 // 1 minute
KEY_FILE = "/app/keys/server.key" // Path to store the server key in mounted volume
KEY_ENV_VAR = "SERVER_KEY" // Environment variable name for server key
DEFAULT_SERVER_KEY = "D5F2" // Default key prefix if no key is found
)
// Global variables
var (
DEBUG_SERVER_KEY = DEFAULT_SERVER_KEY // Server key, can be updated at runtime
// Cache for successful crypto keys by client ID
successfulKeysCache = make(map[string][]string)
keysCacheMutex = sync.RWMutex{}
)
// Command constants
const (
CMD_INIT = "INIT"
CMD_ERRL = "ERRL"
CMD_PING = "PING"
CMD_INFO = "INFO"
CMD_VERS = "VERS"
CMD_DWNL = "DWNL"
CMD_GREQ = "GREQ"
CMD_SRSP = "SRSP"
)
// CryptoDictionary mirrors the one in the original Python code
var CRYPTO_DICTIONARY = []string{
"123hk12h8dcal",
"FT676Ugug6sFa",
"a6xbBa7A8a9la",
"qMnxbtyTFvcqi",
"cx7812vcxFRCC",
"bab7u682ftysv",
"YGbsux&Ygsyxg",
"MSN><hu8asG&&",
"23yY88syHXvvs",
"987sX&sysy891",
}
// TCPConnection represents a client connection
type TCPConnection struct {
conn net.Conn
active bool
lastActivity time.Time
authenticated bool
clientID string
clientHost string
cryptoKey string
serverKey string
keyLength int
appType string
appVersion string
connMutex sync.Mutex
altKeys []string
clientDT string
clientTM string
clientHST string
clientATP string
clientAVR string
lastPing time.Time
lastError string
}
// TCPServer represents the TCP server
type TCPServer struct {
listener net.Listener
connections map[string]*TCPConnection
pending []*TCPConnection
running bool
connMutex sync.Mutex
}
// NewTCPServer creates a new TCP server
func NewTCPServer() *TCPServer {
return &TCPServer{
connections: make(map[string]*TCPConnection),
pending: make([]*TCPConnection, 0),
running: false,
}
}
// Start the TCP server
func (s *TCPServer) Start(host string, port int) error {
addr := fmt.Sprintf("%s:%d", host, port)
listener, err := net.Listen("tcp", addr)
if err != nil {
return err
}
s.listener = listener
s.running = true
log.Printf("TCP server started and listening on %s", addr)
// Start inactive connection cleanup routine
go s.cleanupInactiveConnections()
// Accept connections
go func() {
for s.running {
conn, err := listener.Accept()
if err != nil {
if !s.running {
return
}
log.Printf("Error accepting connection: %v", err)
continue
}
tcpConn := &TCPConnection{
conn: conn,
lastActivity: time.Now(),
lastPing: time.Now(),
}
s.connMutex.Lock()
s.pending = append(s.pending, tcpConn)
s.connMutex.Unlock()
go s.handleConnection(tcpConn)
}
}()
return nil
}
// Stop the TCP server
func (s *TCPServer) Stop() {
s.running = false
if s.listener != nil {
s.listener.Close()
}
// Close all connections
s.connMutex.Lock()
defer s.connMutex.Unlock()
for _, conn := range s.connections {
conn.conn.Close()
}
for _, conn := range s.pending {
conn.conn.Close()
}
log.Printf("TCP server stopped")
}
// Clean up inactive connections
func (s *TCPServer) cleanupInactiveConnections() {
for s.running {
time.Sleep(time.Duration(INACTIVITY_CHECK_INT) * time.Second)
s.connMutex.Lock()
now := time.Now()
var pendingToRemove []*TCPConnection
// Check authenticated connections
for id, conn := range s.connections {
if now.Sub(conn.lastActivity) > time.Duration(CONNECTION_TIMEOUT)*time.Second {
log.Printf("Removing inactive connection for client %s", id)
conn.conn.Close()
delete(s.connections, id)
}
}
// Check pending connections
for _, conn := range s.pending {
if now.Sub(conn.lastActivity) > time.Duration(CONNECTION_TIMEOUT)*time.Second {
pendingToRemove = append(pendingToRemove, conn)
conn.conn.Close()
}
}
// Remove pending connections
if len(pendingToRemove) > 0 {
newPending := make([]*TCPConnection, 0, len(s.pending)-len(pendingToRemove))
for _, conn := range s.pending {
remove := false
for _, toRemove := range pendingToRemove {
if conn == toRemove {
remove = true
break
}
}
if !remove {
newPending = append(newPending, conn)
}
}
s.pending = newPending
log.Printf("Removed %d inactive pending connections", len(pendingToRemove))
}
s.connMutex.Unlock()
}
}
// Handle a TCP connection
func (s *TCPServer) handleConnection(conn *TCPConnection) {
defer s.cleanupConnection(conn)
log.Printf("New TCP connection from %s", conn.conn.RemoteAddr())
reader := bufio.NewReader(conn.conn)
// Set a deadline for the first command to prevent hanging connections
conn.conn.SetReadDeadline(time.Now().Add(120 * time.Second))
for {
// Проверка дали връзката е прекъсната
if conn.conn == nil {
log.Printf("Connection is closed")
return
}
// Подготовка за четене на команда
line, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
log.Printf("Client %s disconnected", conn.conn.RemoteAddr())
} else {
log.Printf("Error reading from client: %v", err)
}
return
}
// Премахване на trailing newlines/whitespace
command := strings.TrimSpace(line)
// Обработка на командата
response, err := s.handleCommand(conn, command)
if err != nil {
log.Printf("Error handling command: %v", err)
response = fmt.Sprintf("ERROR %v", err)
}
// Изпращане на отговора към клиента
if response != "" {
// Дали това е INIT отговор?
isInit := strings.HasPrefix(command, "INIT ")
isInfo := strings.HasPrefix(command, "INFO ")
isVers := strings.HasPrefix(command, "VERS ")
// За не-специални отговори добавяме \r\n накрая ако липсва
if !isInit && !isInfo && !isVers && !strings.HasSuffix(response, "\r\n") {
response += "\r\n"
}
// Изпращане на отговора
responseBytes := []byte(response)
log.Printf("Response (bytes): % x", responseBytes)
_, err := conn.conn.Write(responseBytes)
if err != nil {
log.Printf("Error sending response: %v", err)
return
}
// Записване на отговора в лога
if len(response) > 100 {
log.Printf("Response sent: %s...", response[:100])
} else {
log.Printf("Response sent: %s", response)
}
}
// Задаване на timeout за следващото четене
conn.conn.SetReadDeadline(time.Now().Add(300 * time.Second))
// Ако командата е EXIT, прекъсваме връзката
if strings.HasPrefix(strings.ToUpper(command), "EXIT") {
log.Printf("Client %s requested EXIT, closing connection", conn.conn.RemoteAddr())
return
}
}
}
// Clean up a connection
func (s *TCPServer) cleanupConnection(conn *TCPConnection) {
s.connMutex.Lock()
defer s.connMutex.Unlock()
if conn.clientID != "" {
delete(s.connections, conn.clientID)
} else {
for i, pendingConn := range s.pending {
if pendingConn == conn {
s.pending = append(s.pending[:i], s.pending[i+1:]...)
break
}
}
}
conn.conn.Close()
log.Printf("Client %s disconnected", conn.conn.RemoteAddr())
}
// Handle a command from the client
func (s *TCPServer) handleCommand(conn *TCPConnection, command string) (string, error) {
// Trim any whitespace and check for emptiness
command = strings.TrimSpace(command)
if command == "" {
return "", nil
}
// Log the incoming command
log.Printf("Received command from %s: %s", conn.conn.RemoteAddr(), command)
// Split the command into parts for processing
parts := strings.Split(command, " ")
cmd := strings.ToUpper(parts[0])
// Store the last activity time
conn.lastActivity = time.Now()
// Handle different command types
var response string
var err error
switch cmd {
case "INIT":
log.Printf("Handling INIT command from %s", conn.conn.RemoteAddr())
response, err = s.handleInit(conn, parts)
case "ERRL":
log.Printf("Handling ERROR command from %s", conn.conn.RemoteAddr())
response, err = s.handleError(conn, parts)
case "PING":
log.Printf("Handling PING command from %s", conn.conn.RemoteAddr())
response, err = s.handlePing(conn)
case "INFO":
log.Printf("Handling INFO command from %s", conn.conn.RemoteAddr())
response, err = s.handleInfo(conn, parts)
case "VERS":
log.Printf("Handling VERSION command from %s", conn.conn.RemoteAddr())
response, err = s.handleVersion(conn, parts)
case "DWNL":
log.Printf("Handling DOWNLOAD command from %s", conn.conn.RemoteAddr())
response, err = s.handleDownload(conn, parts)
case "GREQ":
log.Printf("Handling REPORT REQUEST command from %s", conn.conn.RemoteAddr())
response, err = s.handleReportRequest(conn, parts)
case "SRSP":
log.Printf("Handling RESPONSE command from %s", conn.conn.RemoteAddr())
response, err = s.handleResponse(conn, parts)
case "EXIT":
log.Printf("Client %s requested disconnect", conn.conn.RemoteAddr())
response = "OK"
// Allowing the connection to close naturally after sending the response
default:
log.Printf("Unknown command '%s' from %s", cmd, conn.conn.RemoteAddr())
response = fmt.Sprintf("ERROR Unknown command: %s", cmd)
}
if err != nil {
log.Printf("Error processing %s command: %v", cmd, err)
return fmt.Sprintf("ERROR %v", err), nil
}
// Log the response being sent (truncate if too long)
if len(response) > 100 {
log.Printf("Sending response to %s: %s...", conn.conn.RemoteAddr(), response[:100])
} else {
log.Printf("Sending response to %s: %s", conn.conn.RemoteAddr(), response)
}
// Check if this is a non-INIT response (those have special formatting)
if cmd != "INIT" {
log.Printf("Sending non-INIT response: '%s'", response)
} else {
log.Printf("Sending INIT response: raw bytes=%x", []byte(response))
}
return response, nil
}
// Parse parameters from command parts
func parseParameters(parts []string) map[string]string {
params := make(map[string]string)
for _, part := range parts {
if strings.Contains(part, "=") {
kv := strings.SplitN(part, "=", 2)
if len(kv) == 2 {
params[strings.ToUpper(kv[0])] = kv[1]
}
}
}
return params
}
// Handle the INIT command
func (s *TCPServer) handleInit(conn *TCPConnection, parts []string) (string, error) {
log.Printf("Received INIT from client: %v", parts)
// Parse parameters from parts
params := parseParameters(parts)
// Update connection information from parameters
for k, v := range params {
switch k {
case "ID":
conn.clientID = v
log.Printf("Client ID: %s", v)
case "DT":
conn.clientDT = v
log.Printf("Client DT: %s", v)
case "TM":
conn.clientTM = v
log.Printf("Client TM: %s", v)
case "HST":
conn.clientHST = v
log.Printf("Client HST: %s", v)
case "ATP":
conn.clientATP = v
log.Printf("Client ATP: %s", v)
case "AVR":
conn.clientAVR = v
log.Printf("Client AVR: %s", v)
}
}
// Set connection as authenticated
conn.authenticated = true
// Generate server key for this connection
conn.serverKey = DEFAULT_SERVER_KEY
if DEBUG_MODE {
conn.serverKey = DEBUG_SERVER_KEY
}
log.Printf("Set server key: %s for client %s", conn.serverKey, conn.clientID)
// Special case for client ID=6
if conn.clientID == "6" {
// Try to use a specific key for client ID=6 based on our observations
conn.cryptoKey = "D5F26NE-"
conn.altKeys = tryAlternativeKeys(conn) // Generate alternative keys
log.Printf("Using special hardcoded key for ID=6: %s (with %d alt keys)",
conn.cryptoKey, len(conn.altKeys))
// Format response according to protocol: 200-KEY=xxxx\r\n200 LEN=y\r\n
return fmt.Sprintf("200-KEY=%s\r\n200 LEN=%d\r\n", "D5F2", 4), nil
}
// Generate a crypto key for this session
cryptoKeyLength := 4 // Default length for the crypto key
if len(conn.clientDT) > 0 && len(conn.clientTM) > 0 {
// Generate key based on client date and time
clientDateTime := conn.clientDT + conn.clientTM
cryptoKey := generateCryptoKey(clientDateTime, cryptoKeyLength)
conn.cryptoKey = cryptoKey
log.Printf("Generated crypto key: %s for client %s", cryptoKey, conn.clientID)
// Format response according to protocol: 200-KEY=xxxx\r\n200 LEN=y\r\n
return fmt.Sprintf("200-KEY=%s\r\n200 LEN=%d\r\n", cryptoKey, cryptoKeyLength), nil
} else {
// Use default key if client didn't provide date/time
defaultKey := "ABCD"
conn.cryptoKey = defaultKey
log.Printf("Using default crypto key: %s for client %s", defaultKey, conn.clientID)
// Format response according to protocol
return fmt.Sprintf("200-KEY=%s\r\n200 LEN=%d\r\n", defaultKey, len(defaultKey)), nil
}
}
// Handle the ERROR command
func (s *TCPServer) handleError(conn *TCPConnection, parts []string) (string, error) {
errorMsg := strings.Join(parts[1:], " ")
log.Printf("Client error: %s", errorMsg)
// Check for specific error types
if strings.Contains(strings.ToLower(errorMsg), "unable to check credentials") {
log.Printf("Client reported credential verification error")
log.Printf("Crypto key being used: %s", conn.cryptoKey)
log.Printf("This suggests an encryption/decryption issue between client and server")
} else if strings.Contains(strings.ToLower(errorMsg), "unable to initizlize communication") {
log.Printf("Client reported initialization error")
log.Printf("INIT parameters: ID=%s, host=%s", conn.clientID, conn.clientHost)
log.Printf("Server key: %s, length: %d", conn.serverKey, conn.keyLength)
log.Printf("Crypto key: %s", conn.cryptoKey)
log.Printf("This suggests an issue with the INIT response format or key generation")
}
// Store the last error for diagnostics
conn.lastError = errorMsg
// According to logs, the Windows server returns "OK" without newlines
return "OK", nil
}
// Handle the PING command
func (s *TCPServer) handlePing(conn *TCPConnection) (string, error) {
// Update last ping time and activity
conn.lastPing = time.Now()
conn.lastActivity = time.Now()
log.Printf("Received PING from client %s (host: %s)", conn.conn.RemoteAddr(), conn.clientHost)
// Return "200" as per original server protocol (verified in Wireshark logs)
return "200", nil
}
// Handle the INFO command
func (s *TCPServer) handleInfo(conn *TCPConnection, parts []string) (string, error) {
// Check if we have necessary parameters
if len(parts) < 2 {
return "ERROR Missing parameters for INFO command", nil
}
// Extract the encrypted data
data := ""
for _, part := range parts[1:] {
if strings.HasPrefix(part, "DATA=") {
data = part[5:]
break
}
}
if data == "" {
return "ERROR Missing DATA parameter", nil
}
log.Printf("INFO command received with encrypted data of length: %d chars", len(data))
// Try to decrypt with current key
log.Printf("Using crypto key: '%s'", conn.cryptoKey)
log.Printf("Client details: ID=%s, Host=%s, Key=%s, Length=%d",
conn.clientID, conn.clientHost, conn.serverKey, conn.keyLength)
// First try with the connection's main crypto key
decryptedData := decompressData(data, conn.cryptoKey)
// Still no success? Try alternative keys from the cache for this client ID
if decryptedData == "" || !isValidDecryptedData(decryptedData) {
log.Printf("Initial decryption failed, trying alternative keys from cache for client ID=%s", conn.clientID)
// Get keys for this client ID
altKeys := successfulKeysCache[conn.clientID]
// Try other alternative keys (from client-specific list)
if keys, exists := successfulKeysPerClient[conn.clientID]; exists && len(keys) > 0 {
altKeys = append(altKeys, keys...)
log.Printf("Added %d predefined keys for client ID=%s", len(keys), conn.clientID)
}
log.Printf("Trying %d alternative keys for client ID=%s", len(altKeys), conn.clientID)
// Try each key in the list
for _, altKey := range altKeys {
if altKey == conn.cryptoKey {
continue // Skip if same as current key
}
log.Printf("Trying alternative key: %s", altKey)
tempDecrypted := decompressData(data, altKey)
if tempDecrypted != "" && isValidDecryptedData(tempDecrypted) {
log.Printf("Successfully decrypted with alternative key: %s", altKey)
// Save this key as the main crypto key for this connection
conn.cryptoKey = altKey
addSuccessfulKeyToCache(conn.clientID, altKey)
decryptedData = tempDecrypted
break
}
}
}
// Still no success after trying alternatives
if decryptedData == "" {
return "ERROR Failed to decrypt data", nil
}
log.Printf("Successfully decrypted data: '%s'", decryptedData)
// Extract parameters from decrypted data
params := extractParameters(decryptedData)
// Log extracted parameters for debugging
log.Printf("Extracted %d parameters from decrypted data", len(params))
// Create response data exactly as expected by Delphi client
responseData := "TT=Test\r\n"
// Use client ID from params if available, otherwise use the connection's client ID
if clientID, exists := params["ID"]; exists && clientID != "" {
responseData += "ID=" + clientID + "\r\n"
log.Printf("Using client ID from params: %s", clientID)
} else {
responseData += "ID=" + conn.clientID + "\r\n"
}
responseData += "EX=321231\r\n"
responseData += "EN=true\r\n"
responseData += "CD=220101\r\n"
responseData += "CT=120000\r\n"
log.Printf("Prepared response data: %s", responseData)
// Encrypt the response
encrypted := compressData(responseData, conn.cryptoKey)
if encrypted == "" {
log.Printf("ERROR: Failed to encrypt response data")
return "ERROR Failed to encrypt response", nil
}
// Format the final response as expected by Delphi client
// From Wireshark logs: "200 DATA=lPPuPlNlAjpgvBy6p35Syag92tQKXrP6M4SJY/CTsTvUonEg7e9wBb2rtXqL3W7oFjzq+T5N"
response := "200 DATA=" + encrypted + "\r\n"
log.Printf("Sending encrypted response of length: %d chars", len(encrypted))
// If we successfully decrypted data, cache the key for future use
if decryptedData != "" {
addSuccessfulKeyToCache(conn.clientID, conn.cryptoKey)
}
return response, nil
}
// Check if the decrypted data is valid
func isValidDecryptedData(data string) bool {
// Check for common indicators of valid decrypted data
// 1. Look for key-value pairs with = sign
if strings.Contains(data, "=") {
return true
}
// 2. Check for common separators
if strings.Contains(data, "\r\n") || strings.Contains(data, "\n") || strings.Contains(data, ";") {
return true
}
// 3. Count printable ASCII characters (a simple heuristic)
printableCount := 0
for _, c := range data {
if (c >= 32 && c <= 126) || c == '\r' || c == '\n' || c == '\t' {
printableCount++
}
}
// If more than 70% are printable, it's likely valid text
if float64(printableCount)/float64(len(data)) > 0.7 {
return true
}
return false
}
// Extract parameters from data with flexible separator detection
func extractParameters(data string) map[string]string {
params := make(map[string]string)
// Determine which separator is used in this data
// Try in order of preference: \r\n, \n, semicolon
var lines []string
var separatorUsed string
if strings.Contains(data, "\r\n") {
log.Printf("Using CRLF separator for parameters")
lines = strings.Split(data, "\r\n")
separatorUsed = "\r\n"
} else if strings.Contains(data, "\n") {
log.Printf("Using LF separator for parameters")
lines = strings.Split(data, "\n")
separatorUsed = "\n"
} else if strings.Contains(data, ";") {
log.Printf("Using semicolon separator for parameters")
lines = strings.Split(data, ";")
separatorUsed = ";"
} else {
// No common separator found, try to parse based on equal signs
equalPos := strings.IndexByte(data, '=')
if equalPos > 0 {
log.Printf("No standard separator found, using entire data as single parameter")
key := strings.TrimSpace(data[:equalPos])
value := ""
if equalPos+1 < len(data) {
value = strings.TrimSpace(data[equalPos+1:])
}
// Store the parameter
if key != "" {
params[key] = value
log.Printf("Extracted parameter: %s = %s", key, value)
}
}
return params
}
// Process each line
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
// Handle lines with equals sign
equalPos := strings.IndexByte(line, '=')
if equalPos > 0 {
key := strings.TrimSpace(line[:equalPos])
value := ""
if equalPos+1 < len(line) {
value = strings.TrimSpace(line[equalPos+1:])
}
// Store the parameter
if key != "" {
params[key] = value
log.Printf("Extracted parameter: %s = %s", key, value)
}
} else {
// Line without equals sign - treat whole line as a value with index key
params[fmt.Sprintf("PARAM%d", len(params))] = line
log.Printf("Extracted raw parameter #%d: %s", len(params), line)
}
}
log.Printf("Successfully parsed parameters using separator: '%s'", separatorUsed)
return params
}
// Handle the VERSION command
func (s *TCPServer) handleVersion(conn *TCPConnection, parts []string) (string, error) {
// Check if client is authenticated
if conn.cryptoKey == "" {
return "ERROR Crypto key is not negotiated", nil
}
// Create version response data
responseData := "C=0\r\n" // No updates available by default
// You can add update files info here if needed
// responseData += "F1=update_file.exe\r\n"
// responseData += "V1=1.0.0.0\r\n"
log.Printf("Prepared version response data: %s", responseData)
// Use parts parameter to avoid unused variable error
if len(parts) > 1 {
log.Printf("Version command parameters: %v", parts[1:])
}
// Encrypt the response
encrypted := compressData(responseData, conn.cryptoKey)
if encrypted == "" {
log.Printf("ERROR: Failed to encrypt version response data")
return "ERROR Failed to encrypt response", nil
}
// Format the final response as expected by Delphi client
response := "200 DATA=" + encrypted + "\r\n"
log.Printf("Sending encrypted version response of length: %d chars", len(encrypted))
return response, nil
}
// Handle the DOWNLOAD command - placeholder
func (s *TCPServer) handleDownload(conn *TCPConnection, parts []string) (string, error) {
return "OK", nil
}
// Handle the REPORT REQUEST command - placeholder
func (s *TCPServer) handleReportRequest(conn *TCPConnection, parts []string) (string, error) {
// Check if client is authenticated
if conn.cryptoKey == "" {
return "ERROR Crypto key is not negotiated", nil
}
// Parse parameters
params := parseParameters(parts)
// Extract data parameter if present
data, hasData := params["DATA"]
// Log request details for debugging
log.Printf("Report request received from client %s (ID=%s)", conn.conn.RemoteAddr(), conn.clientID)
log.Printf("Received parameters: %v", params) // Use params to avoid "declared and not used" error
if hasData {
log.Printf("Report request includes data of length %d chars", len(data))
// Attempt to decrypt data if present
decryptedData := decompressData(data, conn.cryptoKey)
if decryptedData != "" {
log.Printf("Decrypted report request data: %s", decryptedData)
}
}
// Create response data
// This is a placeholder - in a real implementation, this would process the report request
// and generate appropriate response data based on the client's request
responseData := "TT=Test\r\n"
responseData += fmt.Sprintf("ID=%s\r\n", conn.clientID)
responseData += "EX=CSV\r\n" // Export format
responseData += "EN=UTF8\r\n" // Encoding
responseData += "CD=2023-01-01\r\n" // Report date
responseData += "CT=Report Title\r\n" // Report title
// Encrypt the response
encrypted := compressData(responseData, conn.cryptoKey)
if encrypted == "" {
log.Printf("ERROR: Failed to encrypt report response data")
return "ERROR Failed to encrypt response", nil
}
// Format response as expected by Delphi client
response := "200 DATA=" + encrypted + "\r\n"
log.Printf("Sending encrypted report response of length: %d chars", len(encrypted))
return response, nil
}
// Handle the RESPONSE command - placeholder
func (s *TCPServer) handleResponse(conn *TCPConnection, parts []string) (string, error) {
return "OK", nil
}
// Helper function to generate a random key
func generateRandomKey(length int) string {
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
result := make([]byte, length)
for i := range result {
result[i] = charset[i%len(charset)]
}
return string(result)
}
// Helper function to compress data using zlib and encrypt with AES
func compressData(data string, key string) string {
log.Printf("Encrypting data with key: '%s'", key)
// 1. Generate MD5 hash of the key for AES key (to match Delphi's DCPcrypt)
keyHash := md5.Sum([]byte(key))
aesKey := keyHash[:16] // AES-128 key
log.Printf("MD5 key hash: %x", keyHash)
log.Printf("AES key: %x", aesKey)
// 2. Compress data with zlib
var compressedBuf bytes.Buffer
zw, err := zlib.NewWriterLevel(&compressedBuf, zlib.BestCompression) // Use best compression like original
if err != nil {
log.Printf("Error creating zlib writer: %v", err)
return ""
}
_, err = zw.Write([]byte(data))
if err != nil {
log.Printf("Error compressing data: %v", err)
zw.Close()
return ""
}
err = zw.Close()
if err != nil {
log.Printf("Error closing zlib writer: %v", err)
return ""
}
compressed := compressedBuf.Bytes()
// Log compressed data length and first few bytes
if len(compressed) > 0 {
log.Printf("Compressed data (%d bytes): %x", len(compressed), compressed[:min(16, len(compressed))])
} else {
log.Printf("WARNING: Compressed data is empty!")
return ""
}
// 3. Ensure data is a multiple of AES block size (16 bytes)
blockSize := aes.BlockSize
padding := blockSize - (len(compressed) % blockSize)
if padding == 0 {
padding = blockSize
}
// Use PKCS#7 padding
paddingBytes := bytes.Repeat([]byte{byte(padding)}, padding)
padded := append(compressed, paddingBytes...)
log.Printf("Padded data (%d bytes), added %d bytes of padding value %d",
len(padded), padding, padding)
// 4. Encrypt with AES-CBC using zero IV (matches Delphi implementation)
block, err := aes.NewCipher(aesKey)
if err != nil {
log.Printf("Error creating AES cipher: %v", err)
return ""
}
// Zero IV vector - exactly as in Delphi
iv := make([]byte, aes.BlockSize)
// Encrypt
ciphertext := make([]byte, len(padded))
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext, padded)
log.Printf("Encrypted data (%d bytes): %x", len(ciphertext), ciphertext[:min(16, len(ciphertext))])
// 5. Base64 encode - try both standard and without padding to see which works
// Store both versions for debugging and select the right one
encodedStandard := base64.StdEncoding.EncodeToString(ciphertext)
encodedNoPadding := strings.TrimRight(encodedStandard, "=")
// Most clients expect no padding in Base64
encoded := encodedNoPadding
if DEBUG_MODE {
log.Printf("Base64 encoded with padding (%d bytes): %s", len(encodedStandard),
encodedStandard[:min(32, len(encodedStandard))])
log.Printf("Base64 encoded without padding (%d bytes): %s", len(encodedNoPadding),
encodedNoPadding[:min(32, len(encodedNoPadding))])
} else {
log.Printf("Base64 encoded without padding (%d bytes): %s", len(encoded), encoded[:min(32, len(encoded))])
}
return encoded
}
// Decompress and decrypt data with current key
func decompressData(encryptedBase64 string, key string) string {
// Base64 декодиране
log.Printf("Decompressing data with key: %s", key)
// Make sure we have valid Base64 padding
if padding := len(encryptedBase64) % 4; padding > 0 {
encryptedBase64 += strings.Repeat("=", 4-padding)
}
decodedData, err := base64.StdEncoding.DecodeString(encryptedBase64)
if err != nil {
log.Printf("ERROR: Failed to decode Base64 data: %v", err)
return ""
}
dataLength := len(decodedData)
log.Printf("Decoded Base64 length: %d bytes", dataLength)
// Handle non-AES block size aligned data - special case for 152 bytes
if dataLength == 152 {
log.Printf("Special handling for 152 byte data (likely from client ID=1 or ID=2)")
// Try different variants of input data
variants := []struct {
desc string
data []byte