forked from Yepoleb/adbtools
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathconfedit.py
More file actions
executable file
·1445 lines (1206 loc) · 55.2 KB
/
confedit.py
File metadata and controls
executable file
·1445 lines (1206 loc) · 55.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
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/env python3
#
# decrypt and modify the router configuration file to recover VOIP and
# other passwords in plain text and to unlock hidden or disabled
# functions.
#
# License informations are available in the LICENSE file
#
import tempfile
import string
import random
import re
import sys
import base64
import os
import io
import queue
import logging
import signal
import tkinter as tk
import configparser
import gettext
import locale
from pathlib import Path
from tkinter import *
from tkinter.scrolledtext import ScrolledText
from tkinter import ttk , VERTICAL, HORIZONTAL, N, S, E, W
from tkinter.filedialog import askopenfilename, asksaveasfilename
from Cryptodome.Cipher import AES # requires pycrypto
from lxml import etree as ET
from io import StringIO
#------------------------------------------------------------------------------
# Some variable meanings:
# data_in encrypted configuration binary file in this binary string
# data_out decrypted configuration file: xml binary string
# cpedata_bin encrypted cpe configuration in binary string
# cpedata_hex encrypted cpe configuration in base64 encoded binary string
# cpedata_out decrypted cpe configuration file: xml binary string
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# global variables pointing to default file names
#------------------------------------------------------------------------------
mydir = sys.path[0] # not correct on exe file from pyinstaller
mydir = os.path.dirname(os.path.realpath(__file__))
down_pem = mydir + '/download.pem'
up_pem = mydir + '/upload.pem'
randomstr = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(4))
tmpradix = tempfile.gettempdir() + '/' + randomstr + '-'
tmpconf = tmpradix + 'conf.xml'
tmpconfcpe = tmpradix + 'confcpe.xml'
fversion = mydir + '/version'
homedir = str(Path.home())
defaultdir = homedir
loaded_bin = 0 # binary config loaded
loaded_xml = 0 # xml config loaded
loaded_cpe = 0 # cpe xml config loaded
versionstr = ''
load_pems_done = 0 # pem files loaded
inidir = os.environ.get('APPDATA',homedir) # default location for .confedit.ini
inifile = inidir + '/.confedit.ini'
userinifile = inifile # ini file in user folder
proginifile = mydir + '/.confedit.ini' # ini file in program folder
blank20 = ' '
def language_set(lan):
global _
if (os.path.isdir(mydir + '/locale/' + lan)):
slan = gettext.translation('adbtools2', localedir='locale', languages=[lan])
slan.install()
else:
_ = lambda s: s
def language_default():
global iniconfig
lan = 'EN'
try:
lan = iniconfig['global']['Language']
except:
(lancode, lanenc) = locale.getdefaultlocale()
lancode2=lancode[0:2]
if (os.path.isdir(mydir + '/locale/' + lancode)):
lan = lancode
if (os.path.isdir(mydir + '/locale/' + lancode2)):
lan = lancode2
else:
lan = 'en'
return lan
def show_restricted():
global cpedata_out
sout = get_restricted(cpedata_out)
logger.log(linfo,sout)
def save_restricted():
global cpedata_out
global defaultdir
sout = get_restricted(cpedata_out)
name = asksaveasfilename(initialdir=defaultdir,
filetypes =((_("Text file"), "*.txt"),(_("All Files"),"*.*")),
title = _("Restricted Text File")
)
print (name)
#Using try in case user types in unknown file or closes without choosing a file.
try:
with open(name,'w') as f:
f.write(sout)
except:
print(_("Error writing: "),name)
sys.exit(1)
defaultdir=os.path.dirname(name)
#------------------------------------------------------------------------------
# read_inifile read the initial configuration file and careate one if it
# does not exist
#------------------------------------------------------------------------------
def read_inifile():
global iniconfig
global inifile
global defaultdir
iniconfig = configparser.ConfigParser()
if os.path.isfile(inifile):
iniconfig.read(inifile)
defaultdir=iniconfig['global']['SaveLoadDir']
else:
iniconfig['global'] = {'LogDebug': 'yes',
'SaveLoadDirLastLocation': 'yes',
'SaveLoadDir': defaultdir,
'PreferenceInProgramFolder': 'no',
'Language': language_default()}
write_inifile()
#------------------------------------------------------------------------------
# write_inifile write the configuration file, iniconfig dictionary must
# already exist
#------------------------------------------------------------------------------
def write_inifile():
global iniconfig
global inifile
with open(inifile,'w') as configfile:
iniconfig.write(configfile)
#------------------------------------------------------------------------------
# get_restricted return a string with restricted commands in the cpe xml
# input: xml_str it is cpedata_out
#------------------------------------------------------------------------------
def get_restricted(xml_str):
global rtr_ip
global sweb # restricted web commands
global scli # restricted cli commands
mystr = re.sub(b'<!-- DATA.*', b'', xml_str, 0, re.DOTALL)
xmltree = ET.parse(io.BytesIO(mystr))
xmlroot = xmltree.getroot()
sweb = '';
scli = '';
for i in xmlroot.findall(".//X_ADB_AccessControl/Feature/PagePath"):
web = i.text
parent = i.getparent()
perm = ''
for child in parent:
if child.tag == 'Permissions':
perm = child.text
print(i.text)
print(perm)
if perm == '0000':
print(web[0:4])
if web[0:4] == 'dboa':
sweb = sweb + "\n" + " " + "http://" + rtr_ip.get() + "/ui/" + web
else:
scli = scli + "\n" + " " + web
sout="\nRestricted web urls\n" + sweb + "\n" + "\nRestricted CLI commands\n" + scli
return(sout)
#------------------------------------------------------------------------------
# <PagePath>dboard/storage/ftpserver</PagePath>
# <Origin>CPE</Origin>
# <Permissions>2221</Permissions>
# <PagePath>clish/configure/management/webGui</PagePath>
# <Origin>CPE</Origin>
# <Permissions>0000</Permissions>
def enable_restricted_web():
global cpedata_out
cpedata_out = re.sub(b'(<PagePath>dboa\S+</PagePath>.\s+<Origin>\S+.\s+<Permissions>)0000',b'\g<1>2221',cpedata_out, 0, re.DOTALL)
logger.log(lerr,_("Unlocked restricted web pages"))
get_info(cpedata_out) # update router status info
def enable_restricted_cli():
global cpedata_out
cpedata_out = re.sub(b'(<PagePath>clis\S+</PagePath>.\s+<Origin>\S+.\s+<Permissions>)0000',b'\g<1>2221',cpedata_out, 0, re.DOTALL)
cpedata_out = re.sub(b'(<PagePath>clis\S+ EnableButtonbackToFactory</PagePath>.\s+<Origin>\S+.\s+<Permissions>)0000',b'\g<1>2221',cpedata_out, 0, re.DOTALL)
logger.log(lerr,_("Unlocked restricted commands in CLI"))
get_info(cpedata_out) # update router status info
#<Name>dlinkddns.com</Name>
#<Name>dlinkdns.com</Name>
def fix_dlinkddns():
global cpedata_out
cpedata_out = re.sub(b'<Name>dlinkdns.com</Name>',b'<Name>dlinkddns.com</Name>',cpedata_out, 0, re.DOTALL)
logger.log(lerr,_("Fixed dlinkdns -> dlinkddns"))
get_info(cpedata_out) # update router status info
#------------------------------------------------------------------------------
# get_info setup router info textvariables
# input xml_str binary string, xml or cpe xml conf file
#------------------------------------------------------------------------------
def get_info (xml_str):
global rtr_hwversion
global sweb
global scli
mystr = re.sub(b'<!-- DATA.*', b'', xml_str, 0, re.DOTALL)
xmltree = ET.parse(io.BytesIO(mystr))
xmlroot = xmltree.getroot()
sout = '';
for i in xmlroot.findall(".//DeviceInfo/HardwareVersion"):
rtr_hwversion.set(i.text)
for i in xmlroot.findall(".//DeviceInfo/Manufacturer"):
rtr_manufacturer.set(i.text)
for i in xmlroot.findall(".//DeviceInfo/ModelName"):
rtr_modelname.set(i.text)
for i in xmlroot.findall(".//DeviceInfo/SerialNumber"):
rtr_serial.set(i.text)
for i in xmlroot.findall(".//DeviceInfo/X_DLINK_fw_upgr_permitted"):
rtr_fwupgrade.set(i.text)
print("rtr_fwupgrade.get():" + rtr_fwupgrade.get() + ":")
if rtr_fwupgrade.get() == blank20 :
rtr_fwupgrade.set('undef')
for i in xmlroot.findall(".//DeviceInfo/X_DLINK_customer_ID"):
rtr_customerid.set(i.text)
for i in xmlroot.findall(".//DeviceInfo/X_DLINK_BsdGuiVisible"):
rtr_bsdgui.set(i.text)
for i in xmlroot.findall(".//DeviceInfo/X_DLINK_AllowFirmwareDowngrade"):
rtr_fwdowngrade.set(i.text)
print("rtr_fwupgrade.get():" + rtr_fwupgrade.get() + ":")
if rtr_fwdowngrade.get() == blank20 :
rtr_fwdowngrade.set('undef')
for i in xmlroot.findall(".//IP/Interface/IPv4Address/IPAddress"):
parent = i.getparent()
granpa = parent.getparent()
for child in granpa:
if (child.tag == 'Alias') and (child.text == 'Bridge'):
rtr_ip.set(i.text)
for i in xmlroot.findall(".//IP/Interface/IPv4Address/SubnetMask"):
parent = i.getparent()
granpa = parent.getparent()
for child in granpa:
if (child.tag == 'Alias') and (child.text == 'Bridge'):
rtr_mask.set(i.text)
sout = get_restricted(cpedata_out)
if (sweb == ''):
rtr_rwebgui.set(_('Unlocked'))
else:
rtr_rwebgui.set(_('Locked'))
if (scli == ''):
rtr_rcli.set(_('Unlocked'))
else:
rtr_rcli.set(_('Locked'))
if (re.search(b'<Name>dlinkddns.com</Name>',cpedata_out,0)):
rtr_fixddns.set(_('Fixed'))
else:
rtr_fixddns.set(_('Not Fixed'))
#------------------------------------------------------------------------------
# get_passwords return a string text file with passwords xml string
# input xml_str binary string, xml or cpe xml conf file
# rturn text string
#------------------------------------------------------------------------------
def get_passwords (xml_str):
mystr = re.sub(b'<!-- DATA.*', b'', xml_str, 0, re.DOTALL)
xmltree = ET.parse(io.BytesIO(mystr))
xmlroot = xmltree.getroot()
sout = '';
for s in [ 'AuthPassword', 'Password' ]:
for i in xmlroot.findall(".//" + s):
parent = i.getparent()
granpa = parent.getparent()
try: granpa2s = granpa.getparent().tag
except: granpa2s=''
if ((granpa2s != 'X_ADB_MobileModem') and i.text is not None):
sout = sout + granpa2s + '/' + granpa.tag + '/' + parent.tag + "\n"
for child in parent:
if (child.tag in ['Name', 'AuthUserName', 'Password', 'AuthPassword', 'Username',
'Enable', 'Url', 'Alias', 'Hostname' ]):
sout = sout + " " + "%-15s" % (child.tag) + " " + child.text + "\n"
sout = sout + "\n"
return(sout)
#------------------------------------------------------------------------------
# check_enable_menu - check and, if needed, enable menut items
#------------------------------------------------------------------------------
def check_enable_menu ():
global loaded_bin
global loaded_xml
global loaded_cpe
global filem
global infom
global editm
global menubar
global rtr_hwversion
global rtr_manufacturer
global rtr_modelname
global rtr_serial
global rtr_fwupgrade
global rtr_customerid
global rtr_bsdgui
global rtr_fwdowngrade
global rtr_ip
global rtr_mask
global rtr_rwebgui
global rtr_rcli
global rtr_fixddns
print("check_enable_menu - loaded_bin, loaded_xml, loaded_cpe",loaded_bin,loaded_xml,loaded_cpe)
if ((loaded_bin == 1 ) or ((loaded_xml == 1) and (loaded_cpe == 1))):
filem.entryconfig(4, state = NORMAL) # save as bin config
filem.entryconfig(5, state = NORMAL) # save as xml config
filem.entryconfig(6, state = NORMAL) # save as cpe xml config
editm.entryconfig(1, state = NORMAL) # enable/unlock restricted webgui
editm.entryconfig(2, state = NORMAL) # enable/unlock restricted CLI commands
editm.entryconfig(3, state = NORMAL) # enable firmware downgrade
editm.entryconfig(4, state = NORMAL) # enable fix dlinkdns -> dlinkddns
else:
filem.entryconfig(4, state = DISABLED) # save as bin config
filem.entryconfig(5, state = DISABLED) # save as xml config
filem.entryconfig(6, state = DISABLED) # save as cpe xml config
if ((loaded_bin == 1) or (loaded_xml == 1) or (loaded_cpe == 1)):
infom.entryconfig(1, state = NORMAL) # show passwords
infom.entryconfig(3, state = NORMAL) # save passwords
else:
infom.entryconfig(1, state = DISABLED) # show passwords
infom.entryconfig(3, state = DISABLED) # save passwords
if ((loaded_bin == 1) or (loaded_cpe == 1)):
infom.entryconfig(2, state = NORMAL) # show restricted commands
infom.entryconfig(4, state = NORMAL) # save restricted commands
else:
infom.entryconfig(2, state = DISABLED) # show restricted commands
infom.entryconfig(4, state = DISABLED) # save restricted commands
if ((loaded_bin == 0) and (loaded_cpe == 0)):
rtr_hwversion.set(blank20)
rtr_manufacturer.set(blank20)
rtr_modelname.set(blank20)
rtr_serial.set(blank20)
rtr_fwupgrade.set(blank20)
rtr_customerid.set(blank20)
rtr_bsdgui.set(blank20)
rtr_fwdowngrade.set(blank20)
rtr_ip.set(blank20)
rtr_mask.set(blank20)
rtr_rwebgui.set(blank20)
rtr_rcli.set(blank20)
rtr_fixddns.set(blank20)
logger.log(level,_("check_enable_menu - done"))
#------------------------------------------------------------------------------
# load_pems - load pem files
#------------------------------------------------------------------------------
def load_pems():
global pemconf_data, pemcpe_data
try:
with open(down_pem, "rb") as f:
pemconf_data = f.read()
except:
logger.log(lerr,_("load_pems - error opening "), down_pem)
popupmsg(_('Severe Error'), _("A severe error occoured in 'load_pems'.\nFile missing: ") + down_pem +"\n")
conferror_quit(1)
try:
with open(up_pem, "rb") as f:
pemcpe_data = f.read()
except:
logger.log(lerr,_("load_pems - error opening "), up_pem)
popupmsg(_('Severe Error'), _("A severe error occoured in 'load_pems'.\nFile missing: ") + up_pem + "\n")
conferror_quit(1)
load_pems_done = 1
logger.log(ldebug,_("load_pems - done"))
logger.log(ldebug,_("len 1: ") + str(len(pemconf_data)))
logger.log(ldebug,_("len 2: ") + str(len(pemcpe_data)))
#------------------------------------------------------------------------------
# about -
#------------------------------------------------------------------------------
def about():
global versionstr
global fversion
aboutstr=''
aboutstr=aboutstr.join([_("ADB Configuration Editor (confedit)\nCopyright (c) 2018 Valerio Di Giampietro (main program)\nCopyright (c) 2017 Gabriel Huber (decrypting algorithm)\nCopyright (c) 2017 Benjamin Bertrand (windows interface)\n\nLicense informations available in the LICENSE file\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n")])
if (versionstr == ''):
with open(fversion,"r") as f:
versionstr = f.read()
logger.log(ldebug,_("about - reading ") + fversion)
popupmsg(_('About'), aboutstr + _("Program version: ") + versionstr + "\n")
#------------------------------------------------------------------------------
# enable_fw_upgrade enable fw upgrade/downgrade
#------------------------------------------------------------------------------
def enable_fw_upgrade():
global cpedata_out
global rtr_fwupgrade
global rtr_fwdowngrade
cpedata_out = re.sub(b'<X_DLINK_fw_upgr_permitted>false</X_DLINK_fw_upgr_permitted>',
b'<X_DLINK_fw_upgr_permitted>true</X_DLINK_fw_upgr_permitted>',
cpedata_out,
0,
re.DOTALL)
cpedata_out = re.sub(b'<X_DLINK_AllowFirmwareDowngrade>false</X_DLINK_AllowFirmwareDowngrade>',
b'<X_DLINK_AllowFirmwareDowngrade>true</X_DLINK_AllowFirmwareDowngrade>',
cpedata_out,
0,
re.DOTALL)
if (rtr_fwupgrade.get() == 'undef'):
print ("rtr_fwupgrade is undef")
cpedata_out = re.sub(b'(</X_ADB_TR098Ready>.)(\s+<X_DLINK_customer_ID>\S+.)',
b'\g<1><X_DLINK_fw_upgr_permitted>true</X_DLINK_fw_upgr_permitted>\g<2>',
cpedata_out,
0,
re.DOTALL)
if (rtr_fwdowngrade.get() == 'undef'):
print ("rtr_fwdowngrade is undef")
cpedata_out = re.sub(b'(</X_DLINK_BsdGuiVisible>.)(\s+<X_ADB_PowerManagement\S+.)',
b'\g<1><X_DLINK_AllowFirmwareDowngrade>true</X_DLINK_AllowFirmwareDowngrade>\g<2>',
cpedata_out,
0,
re.DOTALL)
get_info(cpedata_out)
logger.log(lerr,_("enable_fw_upgrade - firmware upgrade/downgrade enabled"))
#------------------------------------------------------------------------------
# load_config - load binary router configuration file - ok
#------------------------------------------------------------------------------
def load_config(*args):
global data_out
global cpedata_out
global defaultdir
global loaded_bin
global loaded_xml
global loaded_cpe
global pemcpe_data
global pem_data
global xml_src
global cpexml_src
name = askopenfilename(initialdir=defaultdir,
filetypes =((_("Configuration File"), "*.bin"),(_("All Files"),"*.*")),
title = _("Binary Configuration File")
)
try:
logger.log(ldebug,_("load_config - loading ") + name)
except:
logger.log(ldebug,_("load_config - no file selected"))
return()
if (name == ''):
logger.log(ldebug,-("load_config - no file selected"))
return()
#Using try in case user types in unknown file or closes without choosing a file.
try:
with open(name,'rb') as f:
data_in = f.read()
except:
logger.log(lerr,_("load_config - error opening "),name)
logger.log(lerr,_("load_config - error opening "),name)
load_bin = 0
load_xml = 0
load_cpe = 0
check_enable_menu()
xml_src.set('')
cpexml_src.set('')
return()
defaultdir=os.path.dirname(name)
logger.log(ldebug,_("defaultdir: ") + defaultdir)
if (not load_pems_done):
load_pems()
logger.log(ldebug,_("len data_in: ") + str(len(data_in)))
# decrypt config
# Going for the popular choice...
IV = b"\x00" * AES.block_size
# Just take a random chunk out of the file and use it as our key
key = pemconf_data[0x20:0x30]
cipher = AES.new(key, AES.MODE_CBC, IV)
try:
data_out = cipher.decrypt(data_in)
except:
logger.log(ldebug,_("load_config - error in decrypting data\nWrong input file?"))
popupmsg(_('Error in input file'),_("Error in decrypting data\nWrong input file?"))
return()
# Padding is a badly implemented PKCS#7 where 16 bytes padding is ignored,
# so we have to check all previous bytes to see if it is valid.
padding_length = data_out[-1]
if (padding_length < AES.block_size) & (padding_length < len(data_out)):
for i in range(0, padding_length):
if data_out[-1 - i] != padding_length:
break
else:
data_out = data_out[:-padding_length]
#-------------------------------------------------------------------------
# extract the cpe xml data
#-------------------------------------------------------------------------
#<!-- CPE Data: DVA-5592/DVA-5592 system type : 963138_VD5920 -->
#<!-- DATA
#9V/jO+TpbscUypF/41d3Ej15nwHuUp+c4wBWV4uFWb1Zb/nS6QuDiLUoZeJ2s0mksjXrARR2
match = re.search(b'<!-- DATA.(.*).-->', data_out, re.DOTALL)
if match:
cpedata_hex = match.group(1)
else:
logger.log(lerr,_("load_config - error in finding hex data") + "\n")
popupmsg(_('Severe Error'), _("A severe error occurred in 'load_config'.\nUnable to extract CPE XML configuration."))
conferror_quit(2)
cpedata_bin = base64.b64decode(cpedata_hex)
key = pemcpe_data[0x20:0x30]
cipher = AES.new(key, AES.MODE_CBC, IV)
cpedata_out = cipher.decrypt(cpedata_bin)
# Padding is a badly implemented PKCS#7 where 16 bytes padding is ignored,
# so we have to check all previous bytes to see if it is valid.
padding_length = cpedata_out[-1]
if (padding_length < AES.block_size) & (padding_length < len(cpedata_out)):
for i in range(0, padding_length):
if cpedata_out[-1 - i] != padding_length:
break
else:
cpedata_out = cpedata_out[:-padding_length]
logger.log(ldebug,_("load_config - length cpedata_out ") + str(len(cpedata_out)))
loaded_bin = 1
loaded_xml = 0
loaded_cpe = 0
check_enable_menu()
#print_passwords()
get_info(cpedata_out)
xml_src.set(name)
cpexml_src.set(name)
#------------------------------------------------------------------------------
# load_xmlconfig - load xml router configuration file - ok
#------------------------------------------------------------------------------
def load_xmlconfig(*args):
global defaultdir
global loaded_bin
global loaded_xml
global loaded_cpe
global data_out
global defaultdir
name = askopenfilename(initialdir=defaultdir,
filetypes =((_("XML Configuration File"), "*.xml"),(_("All Files"),"*.*")),
title = _("XML Configuration File")
)
print (name)
try:
logger.log(ldebug,_("load_xmlconfig - loading ") + name)
except:
logger.log(ldebug,_("load_xmlconfig - no file selected"))
return()
if (name == ''):
logger.log(ldebug,_("load_xmlconfig - no file selected"))
return()
#Using try in case user types in unknown file or closes without choosing a file.
try:
with open(name,'rb') as f:
data_out = f.read()
except:
logger.log(lerr,_("load_xmlconfig - error opening "), name)
load_bin = 0
load_xml = 0
load_cpe = 0
check_enable_menu()
xml_src.set('')
cpexml_src.set('')
return()
defaultdir=os.path.dirname(name)
loaded_xml = 1
loaded_bin = 0
check_enable_menu()
if (not load_pems_done):
load_pems()
xml_src.set(name)
if (loaded_cpe == 0):
cpexml_src.set('')
check_enable_menu()
#------------------------------------------------------------------------------
# load_cpexmlconfig - load cpe xml router configuration file - ok
#------------------------------------------------------------------------------
def load_cpexmlconfig(*args):
global defaultdir
global cpedata_out
global loaded_cpe
global loaded_xml
global loaded_bin
name = askopenfilename(initialdir=defaultdir,
filetypes =(("CPE XML Configuration file", "*.xml"),("All Files","*.*")),
title = _("CPE XML Configuration File")
)
print (name)
try:
logger.log(ldebug,_("load_cpexmlconfig - loading ") + name)
except:
logger.log(ldebug,_("load_cpexmlconfig - no file selected"))
return()
if (name == ''):
logger.log(ldebug,-("load_cpexmlconfig - no file selected"))
return()
#Using try in case user types in unknown file or closes without choosing a file.
try:
with open(name,'rb') as f:
cpedata_out = f.read()
except:
logger.log(lerr,_("load_cpexmlconfig - error opening "),name)
load_bin = 0
load_xml = 0
load_cpe = 0
check_enable_menu()
xml_src.set('')
cpexml_src.set('')
return()
defaultdir=os.path.dirname(name)
loaded_cpe = 1
loaded_bin = 0
if (loaded_xml == 0):
xml_src.set('')
check_enable_menu()
if (not load_pems_done):
load_pems()
cpexml_src.set(name)
get_info(cpedata_out)
check_enable_menu()
#------------------------------------------------------------------------------
# save_config - save router binary configuration file - ok
#------------------------------------------------------------------------------
def save_config(*args):
global defaultdir
global data_out
global cpedata_out
global pemcpe_data
global pemconf_data
if (not load_pems_done):
load_pems()
# -------------------------------------------------------------------------
# encode and base 64 cpe data
# -------------------------------------------------------------------------
# Going for the popular choice...
IV = b"\x00" * AES.block_size
key = pemcpe_data[0x20:0x30]
cipher = AES.new(key, AES.MODE_CBC, IV)
padding_length = AES.block_size - (len(cpedata_out) % AES.block_size)
if padding_length != AES.block_size:
padding_byte = padding_length.to_bytes(1, "big")
cpedata_out += padding_byte * padding_length
cpedata_in = cipher.encrypt(cpedata_out)
cpedata_hex = base64.b64encode(cpedata_in)
cpedata2_hex = re.sub(b"(.{72})", b"\\1\n", cpedata_hex, 0, re.DOTALL)
# -------------------------------------------------------------------------
# insert data cpe in hex format inside the main xml data and encrypt all
# -------------------------------------------------------------------------
# #<!-- CPE Data: DVA-5592/DVA-5592 system type : 963138_VD5920 -->
# #<!-- DATA
# #9V/jO+TpbscUypF/41d3Ej15nwHuUp+c4wBWV4uFWb1Zb/nS6QuDiLUoZeJ2s0mksjXrARR2
data_out = re.sub(b'<!-- DATA\n(.*)\n-->',
b"<!-- DATA\n" + cpedata2_hex + b"\n-->",
data_out, 1, re.DOTALL)
key = pemconf_data[0x20:0x30]
cipher = AES.new(key, AES.MODE_CBC, IV)
padding_length = AES.block_size - (len(data_out) % AES.block_size)
if padding_length != AES.block_size:
padding_byte = padding_length.to_bytes(1, "big")
data_out += padding_byte * padding_length
data_in = cipher.encrypt(data_out)
# -------------------------------------------------------------------------
# write binary file
# -------------------------------------------------------------------------
name = asksaveasfilename(initialdir=defaultdir,
filetypes =((_("Binary Configuration File"), "*.bin"),(_("All Files"),"*.*")),
title =_("Binary Configuration File")
)
print (name)
try:
logger.log(ldebug,_("save_config - saving ") + name)
except:
logger.log(ldebug,_("save_config - no file selected"))
return()
if (name == ''):
logger.log(ldebug,_("save_config - no file selected"))
return()
#Using try in case user types in unknown file or closes without choosing a file.
try:
with open(name,'wb') as f:
f.write(data_in)
except:
logger.log(lerr,_("save_config - error opening "),name)
check_enable_menu()
return()
defaultdir=os.path.dirname(name)
#------------------------------------------------------------------------------
# save_xmlconfig - save router xml configuration file - ok
#------------------------------------------------------------------------------
def save_xmlconfig(*args):
global defaultdir
name = asksaveasfilename(initialdir=defaultdir,
filetypes =((_("XML configuration file"), "*.xml"),(_("All Files"),"*.*")),
title = _("Save XML Configuration File")
)
try:
logger.log(ldebug,_("save_xmlconfig - saving ") + name)
except:
logger.log(ldebug,_("save_xmlconfig - no file selected"))
return()
if (name == ''):
logger.log(ldebug,_("save_xmlconfig - no file selected"))
return()
#Using try in case user types in unknown file or closes without choosing a file.
try:
with open(name,'wb') as f:
f.write(data_out)
except:
logger.log(lerr,_("save_config - error opening "),name)
check_enable_menu()
return()
defaultdir=os.path.dirname(name)
#------------------------------------------------------------------------------
# save_cpexmlconfig - save router configuration file - ok
#------------------------------------------------------------------------------
def save_cpexmlconfig(*args):
global defaultdir
global cpedata_out
name = asksaveasfilename(initialdir=defaultdir,
filetypes =((_("XML Configuration File"), "*.xml"),(_("All Files"),"*.*")),
title = _("Save CPE XML Configuration File")
)
try:
logger.log(ldebug,_("save_cpexmlconfig - saving ") + name)
except:
logger.log(ldebug,_("save_cpexmlconfig - no file selected"))
return()
if (name == ''):
logger.log(ldebug,-("save_cpexmlconfig - no file selected"))
return()
#Using try in case user types in unknown file or closes without choosing a file.
try:
with open(name,'wb') as f:
f.write(cpedata_out)
except:
logger.log(lerr,_("save_cpexmlconfig - error opening "),name)
check_enable_menu()
return()
defaultdir=os.path.dirname(name)
#------------------------------------------------------------------------------
# confquit - quit the program
#------------------------------------------------------------------------------
def confquit(*args):
print("Conf quit")
sys.exit(0)
def conferror_quit(err):
logger.log(lerr,_("Exit with error ") + err)
sys.exit(err)
#------------------------------------------------------------------------------
# not_yet - print in the console the not implemented yet message
#------------------------------------------------------------------------------
def not_yet(mstr=''):
logger.log(lerr, mstr + _("not implemented yet\n"))
popupmsg(_('Info'),_("Not implemented yet"))
#------------------------------------------------------------------------------
# Main program start - set TK GUI based on
# https://github.com/beenje/tkinter-logging-text-widget
# Copyright (c) 2017, Benjamin Bertrand
#------------------------------------------------------------------------------
LARGE_FONT = ("Verdana", 12)
NORM_FONT = ("Helvetica", 10)
SMALL_FONT = ("Helvetica", 8)
logger = logging.getLogger(__name__)
class QueueHandler(logging.Handler):
"""Class to send logging records to a queue
It can be used from different threads
The ConsoleUi class polls this queue to display records in a ScrolledText widget
"""
# Example from Moshe Kaplan: https://gist.github.com/moshekaplan/c425f861de7bbf28ef06
# (https://stackoverflow.com/questions/13318742/python-logging-to-tkinter-text-widget) is not thread safe!
# See https://stackoverflow.com/questions/43909849/tkinter-python-crashes-on-new-thread-trying-to-log-on-main-thread
def __init__(self, log_queue):
super().__init__()
self.log_queue = log_queue
def emit(self, record):
self.log_queue.put(record)
class ConsoleUi:
"""Poll messages from a logging queue and display them in a scrolled text widget"""
def __init__(self, frame):
self.frame = frame
# Create a ScrolledText wdiget
self.scrolled_text = ScrolledText(frame, state='disabled', height=12)
self.scrolled_text.grid(row=0, column=0, sticky=(N, S, W, E),padx=3,pady=3)
self.scrolled_text.configure(font='TkFixedFont')
self.scrolled_text.tag_config('INFO', foreground='black')
self.scrolled_text.tag_config('DEBUG', foreground='gray')
self.scrolled_text.tag_config('WARNING', foreground='orange')
self.scrolled_text.tag_config('ERROR', foreground='red')
self.scrolled_text.tag_config('CRITICAL', foreground='red', underline=1)
# Create a logging handler using a queue
self.log_queue = queue.Queue()
self.queue_handler = QueueHandler(self.log_queue)
#formatter = logging.Formatter('%(asctime)s: %(message)s')
formatter = logging.Formatter('%(message)s')
self.queue_handler.setFormatter(formatter)
logger.addHandler(self.queue_handler)
# Start polling messages from the queue
self.frame.after(100, self.poll_log_queue)
def display(self, record):
msg = self.queue_handler.format(record)
self.scrolled_text.configure(state='normal')
self.scrolled_text.insert(tk.END, msg + '\n', record.levelname)
self.scrolled_text.configure(state='disabled')
# Autoscroll to the bottom
self.scrolled_text.yview(tk.END)
def poll_log_queue(self):
# Check every 100ms if there is a new message in the queue to display
while True:
try:
record = self.log_queue.get(block=False)
except queue.Empty:
break
else:
self.display(record)
self.frame.after(100, self.poll_log_queue)
class FormUi:
def __init__(self, frame):
self.frame = frame
# Create a combobbox to select the logging level
values = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
self.level = tk.StringVar()
ttk.Label(self.frame, text=_('Level:')).grid(column=0, row=0, sticky=W, padx=3, pady=3)
self.combobox = ttk.Combobox(
self.frame,
textvariable=self.level,
width=25,
state='readonly',
values=values
)
self.combobox.current(0)
self.combobox.grid(column=1, row=0, sticky=(W, E), padx=3, pady=3)
# Create a text field to enter a message
self.message = tk.StringVar()
ttk.Label(self.frame, text=_('Message:')).grid(column=0, row=1, sticky=W, padx=3, pady=3)
ttk.Entry(self.frame, textvariable=self.message, width=25).grid(column=1, row=1, sticky=(W, E), padx=3, pady=3)
# Add a button to log the message
self.button = ttk.Button(self.frame, text=_('Submit'), command=self.submit_message)
self.button.grid(column=1, row=2, sticky=W, padx=3, pady=3)
def submit_message(self):
# Get the logging level numeric value
lvl = getattr(logging, self.level.get())
logger.log(lvl, self.message.get())
class RouterInfo:
def __init__(self, frame):
global rtr_hwversion
global rtr_manufacturer
global rtr_modelname
global rtr_serial
global rtr_fwupgrade
global rtr_customerid
global rtr_bsdgui
global rtr_fwdowngrade
global rtr_ip
global rtr_mask
global rtr_rwebgui
global rtr_rcli
global rtr_fixddns
self.frame = frame
ttk.Label(self.frame, text=_('Hardware Version: ')).grid(column=0, row=1, sticky=W)
ttk.Label(self.frame, textvariable=rtr_hwversion).grid(column=1, row=1, sticky=W)
ttk.Label(self.frame, text=_('Manufacturer: ')).grid(column=0, row=2, sticky=W)
ttk.Label(self.frame, textvariable=rtr_manufacturer).grid(column=1, row=2, sticky=W)
ttk.Label(self.frame, text=_('Model Name: ')).grid(column=0, row=3, sticky=W)
ttk.Label(self.frame, textvariable=rtr_modelname).grid(column=1, row=3, sticky=W)
ttk.Label(self.frame, text=_('Router customer ID: ')).grid(column=0, row=4, sticky=W)
ttk.Label(self.frame, textvariable=rtr_customerid).grid(column=1, row=4, sticky=W)
ttk.Label(self.frame, text=_('Serial Number: ')).grid(column=0, row=5, sticky=W)
ttk.Label(self.frame, textvariable=rtr_serial).grid(column=1, row=5, sticky=W)