-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathumas.py
1464 lines (1195 loc) · 37.2 KB
/
umas.py
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
#!/usr/bin/python
from __future__ import print_function
from datetime import datetime
import time
import sys
import getopt
import os
import logging
import iptc
import subprocess
from aux import *
from ftplib import FTP
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
k=0
t="";
IP_DST=""
SPORT_TCP=1128
DPORT=502
SYN=2
ACK=16
PSH_ACK=24
RST=4
FC="5A" #90 Hex
blocksize=0
blocksize_str=""
trans=0
rule = iptc.Rule()
Command_File="commands.cmd"
FW27Code=""
HwDesc=""
CRC32=""
bytes_to_read=[64,264, 64, 1014, 998, 1008, 1014]
memory_block_sizes=[0,23296,16128,16128,16128,16128,16128,16128,16128,16128,0,0,0,0,0,0,0,2047,22272,65535]
trans_creciente=True
#########################################################################################
#################### UMAS PROTOCOL FUNCTIONS ###################################
#########################################################################################
##########################################
# GENERIC SEND COMMANDO (Modbus XX YY ZZ)
##########################################
def send_command(comando):
global t
global trans
if trans_creciente:
trans+=1
else:
trans=1
trans_str=InttoHex(trans)
# write_screen("Enviando comando:"+comando+"...")
longitud=hex((len(comando)+7)/3).replace('0x', '')
if len(longitud) == 1:
longitud = '00 0'+longitud
if len(longitud) == 2:
longitud = '00 '+longitud
if len(longitud) == 3:
longitud = '0'+longitud
longitud=InttoHex(2+len(comando.replace(" ",""))/2)
data=""+trans_str+" 00 00 "+longitud+" 00 5a "+comando
d=data.replace(" ","").decode('hex')
if t:
p=IP(dst=IP_DST)/TCP(sport=t.dport, dport=DPORT, flags=PSH_ACK, seq=t.ack, ack=t.seq+1)/Raw(load=d)
else:
port=RandNum(1024,65535)
p=IP(dst=IP_DST)/TCP(sport=port, dport=DPORT, flags=PSH_ACK)/Raw(load=d)
t=sr1(p,verbose=is_verbose(), timeout=3)
return t
##########################################
# Auxiliary function to extract UMAS_packet
##########################################
def get_UMAS_packet(packet):
#print(str(packet))
try:
rawLoad = packet.getlayer(Raw).load
rawLoadHex=rawLoad.encode("HEX").replace('0x','')
UMAS_packet=rawLoadHex[16:] # Deberia comenzar con 00fe o similar
return UMAS_packet
except:
return None
##########################################
# Check error
##########################################
def check_error(text):
cadn=str(t)[46:56].encode("HEX").replace('0x','')
if (cadn.find("fd") > 0):
print (text + "("+cadn+")")
reset_connection()
sys.exit(1)
##########################################
#Negotiation
##########################################
def tcp_negotiation(IP_RCV):
##################
#SYN
global t
global SPORT_TCP
global IP_DST
port=RandNum(1024,65535)
IP_DST=IP_RCV
time.sleep(0.1)
r=IP(dst=IP_RCV)/TCP(sport=port, dport=DPORT, flags=SYN, options=[ ('MSS', 1460), ('NOP', 1), ('NOP', 1), ('SAckOK','')])
t=sr1(r,verbose=is_verbose())
time.sleep(0.1)
##################
#ACK
p=IP(dst=IP_DST)/TCP(sport=t.dport, dport=DPORT, seq=t.ack, ack=t.seq+1, flags=16)
send(p,verbose=is_verbose())
SPORT_TCP=t.dport
def get_HwId():
return HwId
def get_FwId():
return FwId
def get_FwLoc():
return FwLoc
def get_HwDesc():
return HwDesc
def get_CRC32():
return CRC32
def get_Ir():
return Ir
def get_IP():
return IP_DST
def set_IP(IP_str):
global IP_DST
IP_DST=IP_str
def get_Port():
return port;
##########################################
#Modbus 00 02
##########################################
def device_information():
global FwId
global HwId
global HwDesc
global FwLoc
global Ir
packet_received=send_command("00 02 00")
while (len(str(packet_received))<62):
packet_received=send_command("00 02 00")
response=str(packet_received).encode("HEX").replace('0x','')
pos=response.find("00fe")
if (pos<0):
write_screen("Error: Could not get device information")
else:
FwId=str(HextoByte(response[pos+22: pos+24]))+"."+str(response[pos+20: pos+22])
# print("FwId:"+FwId)
Ir=HextoInt(response[pos+28: pos+32],"LITTLE-ENDIAN")
# print("Ir:"+str(Ir))
HwId=str(HextoByte(response[pos+32: pos+34]))+"."+str(HextoByte(response[pos+34: pos+36]))+"."+str(HextoByte(response[pos+36: pos+38]))+"."+str(HextoByte(response[pos+38: pos+40]))
# print("HwId:"+HwId)
FwLoc=str(HextoByte(response[pos+40: pos+42]))+"."+str(HextoByte(response[pos+42: pos+44]))+"."+str(HextoByte(response[pos+44: pos+46]))+"."+str(HextoByte(response[pos+46: pos+48]))
# print("FwLoc:"+FwLoc)
device_desc_length=HextoByte(response[pos+48: pos+50])
# print("length:"+str(device_desc_length))
HwDesc=HextoString(response[pos+50:pos+50+(device_desc_length*2)])
# print("HWDesc:"+str(HwDesc))
return packet
##########################################
# READ COILS (Modbus 00 24)
##########################################
def read_coils(start, num_coil):
global t
if (start>=0 and start<512 and num_coil>0 and num_coil<512 and start+num_coil<512):
while (num_coil > 0):
if num_coil>248:
nr=248
else:
nr=num_coil
s=hex(start).replace('0x', '')
start_hex_str=""
if (len(s)==1):
start_hex_str='0'+s+" 00"
if (len(s)==2):
start_hex_str=s+" 00"
if (len(s)==3):
start_hex_str=s[1:]+" 0"+s[0]
if (len(s)==4):
start_hex_str=s[-2:]+" "+s[:2]
e=hex(nr).replace('0x', '')
end_hex_str=""
if (len(e)==1):
end_hex_str='0'+e+" 00"
if (len(e)==2):
end_hex_str=e+" 00"
if (len(e)==3):
end_hex_str=e[1:]+" 0"+e[0]
if (len(e)==4):
end_hex_str=s[-2:]+" "+s[:2]
data="00 24 01 00 02 "+start_hex_str+" 00 00 "+end_hex_str
packet_received=send_command(data)
time.sleep(0.6)
print (str(packet_received)[92:].encode("HEX"))
num_coil-=248
start+=248
else:
write_screen("Error: direccion de inicio o longitud de coils invalidos")
##########################################
# WRITE COILS (Modbus 00 25)
##########################################
def write_coils(start, num_coil, arr_list):
global t
if (start>=0 and start <1024 and num_coil>0 and num_coil<1024 and start+num_coil<1024 and len(arr_list)>=num_coil):
arr_pos=0
while (num_coil > 0):
if num_coil>248:
nr=248
else:
nr=num_coil
for i in arr_list[arr_pos:arr_pos+nr]:
if i:
data_stream=data_stream+"1"
else:
data_stream=data_stream+"0"
data_stream=data_stream+" "+word_str
s=hex(start).replace('0x', '')
start_hex_str=""
if (len(s)==1):
start_hex_str='0'+s+" 00"
if (len(s)==2):
start_hex_str=s+" 00"
if (len(s)==3):
start_hex_str=s[1:]+" 0"+s[0]
if (len(s)==4):
start_hex_str=s[-2:]+" "+s[:2]
e=hex(nr).replace('0x', '')
end_hex_str=""
if (len(e)==1):
end_hex_str='0'+e+" 00"
if (len(e)==2):
end_hex_str=e+" 00"
if (len(e)==3):
end_hex_str=e[1:]+" 0"+e[0]
if (len(e)==4):
end_hex_str=s[-2:]+" "+s[:2]
data="00 25 01 00 02 "+start_hex_str+" 00 00 "+end_hex_str+" "+data_stream
packet_received=send_command(data)
time.sleep(0.6)
print (str(packet_received)[92:].encode("HEX"))
num_reg-=248
#######################################################################
# REQUEST INSTANCES OF UNLOCATED VARIABLES (Modbus 00 20, block 01 2e)
#######################################################################
def request_instances_unlocated_variables():
code="00 20"
subcode="01 2e"
starting="00 00"
length="F7 03" #1013
data=code+" "+subcode+" "+starting+" 00 00 00 "+length
packet_received=send_command(data)
print (str(packet_received)[92:].encode("HEX"))
starting="F7 03"
length="0b 00" #11 hasta 1024
data=code+" "+subcode+" "+starting+" 00 00 00 "+length
send_command(data)
print (str(packet_received)[92:].encode("HEX"))
#######################################################################
# REQUEST FUNCTION BLOCK INSTANCES (Modbus 00 20, block 01 32)
#######################################################################
def request_function_block_instances():
code="00 20"
subcode="01 32"
starting="00 00"
length="F7 03" #1013
data=code+" "+subcode+" "+starting+" 00 00 00 "+length
packet_received=send_command(data)
print (str(packet_received)[92:].encode("HEX"))
################ATENCION!!! FALTAN 3!!! ####################
##########################################
# READ HOLDING REGISTERS (Modbus 00 24)
##########################################
def read_holding_registers(start, num_reg):
global t
if (start>=0 and start <1024 and num_reg>0 and num_reg<1024 and start+num_reg<1024):
while (num_reg > 0):
if num_reg>508:
nr=508
else:
nr=num_reg
s=hex(start).replace('0x', '')
start_hex_str=""
if (len(s)==1):
start_hex_str='0'+s+" 00"
if (len(s)==2):
start_hex_str=s+" 00"
if (len(s)==3):
start_hex_str=s[1:]+" 0"+s[0]
if (len(s)==4):
start_hex_str=s[-2:]+" "+s[:2]
e=hex(nr).replace('0x', '')
end_hex_str=""
if (len(e)==1):
end_hex_str='0'+e+" 00"
if (len(e)==2):
end_hex_str=e+" 00"
if (len(e)==3):
end_hex_str=e[1:]+" 0"+e[0]
if (len(e)==4):
end_hex_str=s[-2:]+" "+s[:2]
data="00 24 01 00 03 "+start_hex_str+" 00 00 "+end_hex_str
packet_received=send_command(data)
time.sleep(0.6)
print (str(packet_received)[92:].encode("HEX"))
num_reg-=508
start+=508
else:
write_screen("Error: invalid starting address o register length")
##########################################
# WRITE HOLDING REGISTERS (Modbus 00 25)
##########################################
def write_holding_registers(start, num_reg, arr_list):
global t
if (start>=0 and start <1024 and num_reg>0 and num_reg<1024 and start+num_reg<1024 and len(arr_list)>=num_reg):
arr_pos=0
while (num_reg > 0):
if num_reg>508:
nr=508
else:
nr=num_reg
for i in arr_list[arr_pos:arr_pos+nr]:
s=hex(i).replace('0x', '')
word_str=""
if (len(s)==1):
word_str='0'+s+" 00"
if (len(s)==2):
word_str=s+" 00"
if (len(s)==3):
word_str=s[1:]+" 0"+s[0]
if (len(s)==4):
word_str=s[-2:]+" "+s[:2]
data_stream=data_stream+" "+word_str
s=hex(start).replace('0x', '')
start_hex_str=""
if (len(s)==1):
start_hex_str='0'+s+" 00"
if (len(s)==2):
start_hex_str=s+" 00"
if (len(s)==3):
start_hex_str=s[1:]+" 0"+s[0]
if (len(s)==4):
start_hex_str=s[-2:]+" "+s[:2]
e=hex(nr).replace('0x', '')
end_hex_str=""
if (len(e)==1):
end_hex_str='0'+e+" 00"
if (len(e)==2):
end_hex_str=e+" 00"
if (len(e)==3):
end_hex_str=e[1:]+" 0"+e[0]
if (len(e)==4):
end_hex_str=s[-2:]+" "+s[:2]
data="00 25 01 00 03 "+start_hex_str+" 00 00 "+end_hex_str+" "+data_stream
packet_received=send_command(data)
time.sleep(0.6)
print (str(packet_received)[92:].encode("HEX"))
num_reg-=508
start+=508
##########################################
# KEEPALIVE2 (Modbus 01 12)
##########################################
def send_keep_alive2():
if (FwId=="2.70"):
pck=send_command(FW27Code+"12")
else:
pck=send_command("01 12")
##########################################
# KEEP ALIVE (Modbus 01 04)
##########################################
def send_keep_alive():
global PLC_Running
global CRC32
if (FwId=="2.70"):
c=FW27Code+"04"
else:
c="00 04"
UMAS_packet=None
while not UMAS_packet:
packet_received=send_command(c)
cadn=str(packet_received).encode("HEX").replace('0x','')
UMAS_packet=get_UMAS_packet(packet_received)
CRC32=UMAS_packet[20:28]
#print ("El CRC es: "+CRC32)
if (cadn[-12:-10] == "02"):
PLC_Running=True
else:
PLC_Running=False
return packet_received
##########################################
# RESET CONNECTION
##########################################
def reset_connection():
write_screen("\nResetting connection...")
global t
send_command("00 58 01 00 00 00 00 FF FF 00 00")
time.sleep(0.3)
#send_keep_alive();
#time.sleep(0.3)
#send_command("00 58 01 80 00 00 00 00 00 FB 03")
#send_keep_alive();
#time.sleep(0.3)
if t:
r=IP(dst=IP_DST)/TCP(sport=t.dport, dport=DPORT, seq=t.ack, ack=t.seq+1, flags=RST)
else:
r=IP(dst=IP_DST)/TCP(sport=SPORT_TCP, dport=DPORT, flags=RST)
t=send(r,verbose=is_verbose())
remove_iptables_rule()
write_screen("\nModifying iptables..\n")
##########################################
# REPEAT (Modbus 00 0A 00)
##########################################
def repeat(text):
global t
global trans
if trans_creciente:
trans+=1
else:
trans=1
longitud=hex(len(text)+5).replace('0x', '')
if len(longitud) == 1:
longitud = '00 0'+longitud
if len(longitud) == 2:
longitud = '00 '+longitud
if len(longitud) == 3:
longitud='0'+longitud
data=InttoHex(trans)+" 00 00 "+longitud+" 00 5a 00 0A 00 "
data=data.split(" ")
d = ''.join(data)+toHex(text)
d=d.decode('hex')
if t:
p=IP(dst=IP_DST)/TCP(sport=t.dport, dport=DPORT, flags=PSH_ACK, seq=t.ack, ack=t.seq+1)/Raw(load=d)
else:
port=RandNum(1024,65535)
p=IP(dst=IP_DST)/TCP(sport=port, dport=DPORT, flags=PSH_ACK)/Raw(load=d)
t=sr1(p,verbose=is_verbose())
##########################################
# INIT - First packet sent to PLC (Modbus 00 01 00)
##########################################
def init():
global blocksize
global blocksize_str
global blocksize_orig
packet_received=send_command("00 01 00")
response=str(packet_received).encode("HEX").replace('0x','')
pos=response.find("00fe")
blocksize=HextoInt(response[pos+4:pos+8],"LITTLE-ENDIAN")-8
blocksize_str=InttoHex(blocksize,"LITTLE-ENDIAN")
blocksize_orig=response[pos+4:pos+8]
#write_screen("Assigning block size to: "+ blocksize)
##########################################
# Memory Dump
##########################################
# Section: string that represents an 16 bit hex number in little-endian mode. For instance "13 00" means section 0x13h
# Filename: string with the name of the File that will be written
def memory_dump(section_str, Filename=None):
global t
global trans
write_screen ("\nDumping memory block "+section_str+"h ...")
code="00 20"
starting_str="00 00"
length_str=blocksize_str
starting=HextoInt(starting_str,"LITTLE-ENDIAN")
length=HextoInt(length_str,"LITTLE-ENDIAN")
Continue=True
f=None
if Filename:
f=open(Filename, "wb")
else:
set_verb(True)
while (Continue):
if trans_creciente:
trans+=1
else:
trans=1
#data=""+InttoHex(trans)+" 00 00 00 0D 00 5a "+code+" 00 "+section+" "+starting_str+" 00 00 "+length_str
#data=data.split(" ")
#d = ''.join(data).decode('hex')
#if t:
#p=IP(dst=IP_DST)/TCP(sport=t.dport, dport=DPORT, flags=PSH_ACK, seq=t.ack, ack=t.seq+1)/Raw(load=d)
#else:
#port=RandNum(1024,65535)
#p=IP(dst=IP_DST)/TCP(sport=port, dport=DPORT, flags=PSH_ACK)/Raw(load=d)
#t=sr1(p,verbose=is_verbose())
#time.sleep(0.9)
packet_received=send_command(code+" 00 "+ section_str+" "+starting_str+" 00 00 "+length_str)
time.sleep(0.9)
cadn=str(packet_received)[46:54].encode("HEX").replace('0x','')
if (cadn.find("fd")>0):
check_error("\nAn error ocurred while dumping block starting in "+starting_str)
else:
if f:
f.write(str(t)[54:])
else:
write_screen (str(t)[54:])
time.sleep(0.3)
starting+=length
#Depending of the block read, we can read more or less bytes, or we will brick the PLC
ss=HextoInt(section_str.replace(" ",""),"LITTLE-ENDIAN")
dot()
if (ss>=19):
#13h to 2eh
if (starting > 65535):
Continue=False
else:
if (starting > memory_block_sizes[ss]):
Continue=False
starting_str=InttoHex(starting, "LITTLE-ENDIAN")
#On the other hand if the reply is too short is because there's no extra info
if (len(str(t))<80):
Continue=False
if f:
f.close()
write_screen("\nSuccessfully dumped "+str(starting -length)+" bytes.\n")
##########################################
# GET INTERNAL CARD INFO (Modbus 00 06 00)
##########################################
def get_internal_card_info():
pck=send_command("00 06 00")
##########################################
#Modbus Read Sections 13&14
##########################################
def read_sections13_14():
global t
global trans
code="00 20"
section="13 00" # little endian
length_str="64 00" #little-endian
starting_str="00 00"
if trans_creciente:
trans+=1
else:
trans=1
data=""+InttoHex(trans)+" 00 00 00 0D 00 5a "+code+" 00 "+section+" "+starting_str+" 00 00 "+length_str
data=data.split(" ")
d = ''.join(data).decode('hex')
if t:
p=IP(dst=IP_DST)/TCP(sport=t.dport, dport=DPORT, flags=PSH_ACK, seq=t.ack, ack=t.seq+1)/Raw(load=d)
else:
port=RandNum(1024,65535)
p=IP(dst=IP_DST)/TCP(sport=port, dport=DPORT, flags=PSH_ACK)/Raw(load=d)
t=sr1(p,verbose=is_verbose())
time.sleep(0.9)
starting_str=length_str
length_str="9C 00"
if trans_creciente:
trans+=1
else:
trans=1
data=""+InttoHex(trans)+" 00 00 00 0D 00 5a "+code+" 00 "+section+" "+starting_str+" 00 00 "+length_str
data=data.split(" ")
d = ''.join(data).decode('hex')
if t:
p=IP(dst=IP_DST)/TCP(sport=t.dport, dport=DPORT, flags=PSH_ACK, seq=t.ack, ack=t.seq+1)/Raw(load=d)
else:
port=RandNum(1024,65535)
p=IP(dst=IP_DST)/TCP(sport=port, dport=DPORT, flags=PSH_ACK)/Raw(load=d)
t=sr1(p,verbose=is_verbose())
time.sleep(0.9)
###### Block 14 ###
section="14 00" # little endian
length_str="64 00" #little-endian
starting_str="00 00"
if trans_creciente:
trans+=1
else:
trans=1
data=""+InttoHex(trans)+" 00 00 00 0D 00 5a "+code+" 00 "+section+" "+starting_str+" 00 00 "+length_str
data=data.split(" ")
d = ''.join(data).decode('hex')
if t:
p=IP(dst=IP_DST)/TCP(sport=t.dport, dport=DPORT, flags=PSH_ACK, seq=t.ack, ack=t.seq+1)/Raw(load=d)
else:
port=RandNum(1024,65535)
p=IP(dst=IP_DST)/TCP(sport=port, dport=DPORT, flags=PSH_ACK)/Raw(load=d)
t=sr1(p,verbose=is_verbose())
time.sleep(0.9)
######
starting_str=length_str
length_str=blocksize_str
starting=HextoInt(starting_str,"LITTLE-ENDIAN")
length=HextoInt(length_str,"LITTLE-ENDIAN")
while (starting+length < 1604):
if trans_creciente:
trans+=1
else:
trans=1
data=""+InttoHex(trans)+" 00 00 00 0D 00 5a "+code+" 00 "+section+" "+starting_str+" 00 00 "+length_str
data=data.split(" ")
d = ''.join(data).decode('hex')
if t:
p=IP(dst=IP_DST)/TCP(sport=t.dport, dport=DPORT, flags=PSH_ACK, seq=t.ack, ack=t.seq+1)/Raw(load=d)
else:
port=RandNum(1024,65535)
p=IP(dst=IP_DST)/TCP(sport=port, dport=DPORT, flags=PSH_ACK)/Raw(load=d)
t=sr1(p,verbose=is_verbose())
time.sleep(0.9)
starting+=length
starting_str=InttoHex(starting, "LITTLE-ENDIAN")
length_left=1604-starting
if trans_creciente:
trans+=1
else:
trans=1
data=""+InttoHex(trans)+" 00 00 00 0D 00 5a "+code+" 00 "+section+" "+starting_str+" 00 00 "+InttoHex(length_left, "LITTLE-ENDIAN")
data=data.split(" ")
d = ''.join(data).decode('hex')
if t:
p=IP(dst=IP_DST)/TCP(sport=t.dport, dport=DPORT, flags=PSH_ACK, seq=t.ack, ack=t.seq+1)/Raw(load=d)
else:
port=RandNum(1024,65535)
p=IP(dst=IP_DST)/TCP(sport=port, dport=DPORT, flags=PSH_ACK)/Raw(load=d)
t=sr1(p,verbose=is_verbose())
time.sleep(0.9)
##########################################
# GET INTERNAL CARD INFO (Modbus 00 06 00)
##########################################
def get_internal_card_info():
pck=send_command("00 06 00")
return pck
##########################################
# INICIALIZATION
##########################################
def initialize(IP_DST):
write_screen("\nModifying iptables..")
create_iptables_rule("502")
write_screen("\nInitializong connection..")
tcp_negotiation(IP_DST);
#0x02
pckt=device_information();
dot()
time.sleep(0.6)
dot()
#0x01
init();
#0x0A
repeat("T"*(blocksize+4));
#0x03
#0x0304
#0x0304
#0x04
send_command("00 03 00")
time.sleep(0.3)
send_command("00 03 04")
time.sleep(0.3)
send_command("00 03 04")
time.sleep(0.3)
send_command("00 04")
time.sleep(0.3)
#0x01
init()
a=""
dot()
for i in range (1,blocksize+4):
b=hex(i).replace('0x', '')
if len(b) == 1:
b = '0'+b
a=a+b[-2:]+" "
dot()
#0x0A
send_command("00 0A 00 "+a)
time.sleep(0.3)
# send_command("00 04")
# time.sleep(0.3)
# send_command("00 04")
# time.sleep(0.3)
# dot()
##########################################
# Download Strategy
##########################################
def download_strategy(Filename):
global t
global blocksize
write_screen ("\nInitializing strategy download..")
send_keep_alive2();
time.sleep(0.5)
send_keep_alive();
time.sleep(0.3)
read_sections13_14()
dot()
if (FwId=="2.70"):
first_code=FW27Code
else:
first_code="01"
write_screen ("\nDownloading strategy..")
pck=send_command(first_code+" 33 00 01 "+blocksize_orig)
time.sleep(0.6)
f=open(Filename, "wb")
keep_reading=True
i=1
while keep_reading:
b=BytetoHex(i)
dot()
#Lanzamos la peticion:
time.sleep(0.6)
packet_received=send_command(first_code+" 34 00 01 "+b+" 00")
if (len(str(packet_received))!=54):
cadn=str(packet_received)[46:54].encode("HEX").replace('0x','')
if (cadn.find("fd")>0):
packet_received=send_command(first_code+" 34 00 01 "+b+" 00")
time.sleep(0.3)
cadn=str(packet_received)[46:54].encode("HEX").replace('0x','')
if (cadn.find("fd")>0):
check_error("\nAn error ocurred while downloading block "+str(i)+" on strategy download")
else:
f.write(str(t)[54:])
time.sleep(0.3)
else:
f.write(str(t)[54:])
time.sleep(0.3)
i+=1
else:
keep_reading=False
#Closing read file both in PLC and locally
block_num_str=BytetoHex(i)
pck=send_command(first_code+" 35 00 01 "+block_num_str+" 00")
dot()
f.write(str(t)[54:-6])
f.close()
#Extra info for verbose mode
time.sleep(0.3)
write_screen ("\nSuccessful download!!")
cad="\n"+str(i)+" memory blocks were downloaded"
write_screen(cad)
##########################################
# Upload Strategy
##########################################
def upload_strategy(Filename):
global t
upload_initialization()
write_screen("\nUploading_strategy")
if (FwId=="2.70"):
first_code=FW27Code
else:
first_code="01"
#START STRATEGY UPLOAD
dot()
pck=send_command(first_code+" 30 00 01")
time.sleep(0.6)
pck=send_keep_alive();
time.sleep(0.3)
f=open(Filename, "rb")
k=0
block_num=0
bytes_left=True
#blocksize=1012
while bytes_left:
#blocks 0 and 1 are the same (both with block_num 1)
if (block_num==0):
b=hex(block_num+1).replace('0x', '')
else:
b=hex(block_num).replace('0x', '')
if len(b) == 1:
b = '0'+b
dot()
if (block_num!=1):
block=f.read(blocksize-1);
cad=""
for ch in block:
c=hex(ord(ch)).replace('0x','')
if len(c)==1:
c='0'+c
cad=cad+" "+c
longitud=len(block)
d=hex(longitud).replace('0x', '')
e=""
if (len(d)==1):
e='0'+d+" 00"
if (len(d)==2):
e=d+" 00"
if (len(d)==3):
e=d[1:]+" 0"+d[0]
if (len(d)==4):
e=d[-2:]+" "+d[:2]
#if (block_num==12):
#bytes_left=False
block_num+=1
#Send request only if there bytes left to send, otherwise break the loop
if (longitud>0):
k=k+1
#write_screen (cad)
pck=send_command(first_code+" 31 00 01 "+b+" 00 "+e+cad)
time.sleep(0.6)
check_error("\nError: An error ocurred while uploading block "+str(k)+" on strategy upload")
else:
bytes_left=False
#CLOSE CONNECTION
time.sleep(0.6)
dot()
b=hex(k-1).replace('0x', '')
if len(b) == 1:
b = '0'+b
pck=send_command(first_code+" 32 00 01 "+b+" 00")
cadn=str(t)[46:100].encode("HEX").replace('0x','')
if ((cadn.find(first_code+"fd") > 0)):
print("\nError. Strategy upload failed ("+cadn+")")
else:
write_screen ("\nSuccessful upload!!")
write_screen("\nApprox. "+str(k)+" Kb were uploaded")
f.close()
time.sleep(0.6)
##########################################
# Upload initialization
##########################################
def upload_initialization():
write_screen ("\nInitializing strategy upload..")
pck=send_keep_alive2();
time.sleep(0.5)
pck=send_keep_alive();
time.sleep(0.5)
pck=send_keep_alive2();
time.sleep(0.5)
pck=send_keep_alive();
time.sleep(0.3)