-
Notifications
You must be signed in to change notification settings - Fork 1
/
htb
executable file
·896 lines (850 loc) · 36.9 KB
/
htb
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
#!/usr/bin/python3
# coding:utf-8
# Author : taiQui
import requests,json,argparse,re
from getkey import keys
import readchar
from os.path import isfile
from os import getcwd,getenv
import urllib3
urllib3.disable_warnings()
HOME = getenv('HOME')
def parser():
parser = argparse.ArgumentParser()
parser.add_argument('-t','--test_mode',help="activate test mode - run only test methode",action="store_true")
parser.add_argument('-x','--execute',help="run this command")
return parser.parse_args()
class Color:
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
ORANGE = '\033[33m'
BOLD = '\033[1m'
def getCMD(cmd):
command = cmd.split(' ')[0]
args = cmd.split(' ')[1:]
return command,args
def getContent(msg):
box_pwn = "(?:.*)profile\/\d+\">(.*)<\/a> owned (.*) on <a(?:.*)profile\/(?:\d+)\">(.*)<\/a> <a(?:.*)"
chall_pwn = "(?:.*)profile\/\d+\">(.*)<\/a> solved challenge <(?:.*)>(.*)<(?:.*)><(?:.*)> from <(?:.*)>(.*)<(?:.*)><(?:.*)"
new_box_incoming = "(?:.*)Get ready to spill some (?:.* blood .*! <.*>)(.*)<(?:.* available in <.*>)(.*)<(?:.*)><(?:.*)"
new_box_out= "(?:.*)>(.*)<(?:.*) is mass-powering on! (?:.*)"
vip_upgrade= "(?:.*)profile\/\d+\">(.*)<\/a> became a <(?:.*)><(?:.*)><(?:.*)> V.I.P <(?:.*)"
new_people = "(?:.*)profile\/\d+\">(.*)<\/a> just joined! Be polite and say hi :\)</p>"
speak = "(?:.*)profile\/\d+\">(.*)</a>(?:.*)</span>:(.*)</p>"
respect = "(?:.*)profile\/\d+\">(.*)</a> gave <span class=\"text-warning\">(?:.*)profile\/\d+\">(.*)</a></p>"
respect2 = "(?:.*)profile\/\d+\">(.*)</a> believes that (.*) is so pro! <span class=\"text-success\">\[ \+1 (.*)</p>"
badge = "(?:.*)profile\/\d+\">(.*)</a> has been awarded the <span class=\"c-white\">(.*)</span> badge.</p>"
reset = "(?:.*)profile\/\d+\">(.*)</a> issued a <span class=\"text-danger\">(.*)</span> on <span class=\"c-white\">(.*)</span> <span class=\"text-success\">\[(.*)\]</span> </p>"
fortress = "(?:.*)profile\/\d+\">(.*)</a> got flag <span class=\"text-success\">(.*)</span> from <a href=\"https://www.hackthebox.eu/.*\">(.*)</a> <span class=\"c-white\"><i class=\"fab fa-fort-awesome\"></i> .*</a></p>"
reset2 = "(?:.*)profile\/\d+\">(.*)</a> requested a <span class=\"text-danger\">reset</span> on <span class=\"c-white\">(.*)</span> <span class=\"text-success\">\[(.*)\]</span> \[Type <span class=\"c-white\">(.*)</span> <span class=\"text-success\">(.*)</span> within one minute to vote to cancel it.]</p>"
# get = re.compile(box_pwn).findall(msg)
# if len(get) > 0:
# return "{} owned {} on {}".format(get[0][0],get[0][1],get[0][2])
# get = re.compile(chall_pwn).findall(msg)
# if len(get) > 0:
# return "{} solved {} from {} category".format(get[0][0],get[0][1],get[0][2])
# get = re.compile(new_box_incoming).findall(msg)
# if len(get) > 0:
# return ' '.join(get)
# get = re.compile(new_box_out).findall(msg)
# if len(get) > 0:
# return ' '.join(get)
# get = re.compile(vip_upgrade).findall(msg)
# if len(get) > 0:
# return '{} just become V.I.P'.format(get[0])
# get = re.compile(new_people).findall(msg)
# if len(get) > 0:
# return "{} just joined the shoutbox".format(get[0])
get = re.compile(speak).findall(msg)
if len(get) > 0:
return "{} : {}".format(get[0][0],get[0][1])
# get = re.compile(respect).findall(msg)
# if len(get) > 0:
# return "{} give respect to {}".format(get[0][0],get[0][1])
# get = re.compile(respect2).findall(msg)
# if len(get) > 0:
# return("{} give respect to {}".format(get[0][0],get[0][1]))
# get = re.compile(badge).findall(msg)
# if len(get) > 0:
# return "{} got {} badge !".format(get[0][0],get[0][1])
get = re.compile(reset).findall(msg)
if len(get) > 0:
return "{} issued a {} on {} from [{}]".format(get[0][0],get[0][1],get[0][2],get[0][3])
# get = re.compile(fortress).findall(msg)
# if len(get) > 0:
# return "{} got flag {} from {}".format(get[0][0],get[0][1],get[0][2])
get = re.compile(reset2).findall(msg)
if len(get) > 0:
return "{} ask for reset {} in [{}] type {} {} to cancel it".format(get[0][0],get[0][1],get[0][2],get[0][3],get[0][4])
return None
class HTB:
def __init__(self,API_KEY):
self.api_key = API_KEY
self.session = requests.Session()
self.BOXS = None
self.active = None
self.isvip = self.isVIP()
def getAllBox(self,_number=None,_active=True):
boxs = self.requests("https://www.hackthebox.eu/api/machines/get/all",_json=True)[::-1]
owned = self.getOwned(_active=_active,_send=True)
spawned = self.getSpawned(_send=True)
toprint = len(boxs) if _number == None else _number
BOX = []
for i in range(toprint):
tmp = {}
user,root = HTB.isOwned(boxs[i]['id'],owned)
if _active:
if boxs[i]['retired'] == False:
BOX.append(self.box2dic(boxs[i],user=user,root=root,spawned=spawned))
else:
BOX.append(self.box2dic(boxs[i],user=user,root=root,spawned=spawned))
self.BOXS = BOX
self.active = _active
return BOX
def box2dic(self,r,user=None,root=None,spawned=None):
tmp = {}
tmp['name'] = r['name']
tmp['os'] = r['os']
tmp['ip'] = r['ip']
tmp['id'] = r['id']
tmp['rating'] = str(r['rating'])
tmp['points'] = str(r['points'])
tmp['user'] = str(r['user_owns'])
tmp['root'] = str(r['root_owns'])
if spawned != None:
try:
tmp['spawned'] = HTB.isUp(r['id'],spawned)
except:
tmp['spawned'] = None
else:
tmp['spawned'] = None
if user:
tmp['owned_user'] = True
else:
tmp['owned_user'] = False
if root:
tmp['owned_root'] = True
else:
tmp['owned_root'] = False
# tmp['spawned'] = isUp(r['id'],spawned)
return tmp
def getSpawned(self,_send=False):
r = self.requests("https://www.hackthebox.eu/api/machines/spawned/",_json=True)
try:
if not _send:
for box in r:
HTB.printBox(self.getBoxById(box['id'],_noprint=True))
else:
boxs = []
for box in r:
boxs.append(box)
return boxs
except:
print("[-] You are probably not VIP")
return
def isVIP(self):
r = self.requests("https://www.hackthebox.eu/api/machines/spawned/",_json=True)
if "success" in r:
if r['success'] == "0":
return False
else:
print("Not implemented case found - contact dev with response below")
print(r)
else:
return True
@staticmethod
def isOwned(id,owned):
for box in owned:
if id == box['id']:
return box['owned_user'],box['owned_root']
return None,None
@staticmethod
def isUp(id,spawned):
for i in spawned:
if i['id'] == id:
return i['spawned']
return False
@staticmethod
def rate2Color(point):
if point == 20:
return Color.BOLD+Color.GREEN+"[+]"+Color.RESET
if point == 30:
return Color.BOLD+Color.ORANGE+"[+]"+Color.RESET
if point == 40:
return Color.BOLD+Color.RED+"[+]"+Color.RESET
else:
return Color.BOLD+Color.WHITE+"[+]"+Color.RESET
def getAssigned(self):
return self.requests("https://www.hackthebox.eu/api/machines/assigned",_json=True)[0]['id']
def getBetterRated(self,_active=True,_number=None):
boxs = None
if _active != self.active:
boxs = self.getAllBox(_active=_active)
else:
boxs = self.BOXS if self.BOXS != None else self.getAllBox(_active=_active)
newlist = sorted(boxs, key=lambda k: k['rating'])[::-1]
print("="*(len("Best Rating")+4))
print(" Best Rating")
print("="*(len("Best Rating")+4))
max = _number if _number != None else 10
for i in range(max):
self.printBox(newlist[i])
def getBoxByName(self,name,_active=False):
boxs = None
if _active != self.active:
boxs = self.getAllBox(_active=_active)
else:
boxs = self.BOXS if self.BOXS != None else self.getAllBox(_active=_active)
print("="*(len(" Result for {}".format(name))+4))
print(" Result for {}".format(name))
print("="*(len(" Result for {}".format(name))+4))
for box in boxs:
if box['name'].lower() == name.lower():
HTB.printBox(box)
return
def getBoxById(self,id,_active=False,_noprint=False):
boxs = None
if _active != self.active:
boxs = self.getAllBox(_active=_active)
else:
boxs = self.BOXS if self.BOXS != None else self.getAllBox(_active=_active)
if not _noprint:
print("="*(len(" Result for {}".format(id))+4))
print(" Result for {}".format(id))
print("="*(len(" Result for {}".format(id))+4))
for box in boxs:
if int(box['id']) == int(id):
return box
def getOwned(self,_active=True,_send=False):
r = self.requests("https://www.hackthebox.eu/api/machines/owns",_json=True)
if _send:
return r
for owned in r:
HTB.printBox(self.getBoxById(owned['id'],_noprint=True))
def getActiveNotOwned(self,_active=True):
boxs = None
if _active != self.active:
boxs = self.getAllBox(_active=_active)
else:
boxs = self.BOXS if self.BOXS != None else self.getAllBox(_active=_active)
r = self.requests("https://www.hackthebox.eu/api/machines/owns",_json=True)
ids = [a['id'] for a in r]
for box in boxs:
if box['id'] not in ids:
HTB.printBox(box)
else:
for owned in r:
if owned['id'] == box['id']:
if owned['owned_user'] ^ owned['owned_root']:
HTB.printBox(box)
def getBoxByDifficulty(self,difficulty,_active=True,_number=None):
boxs = None
if _active != self.active:
boxs = self.getAllBox(_active=_active)
else:
boxs = self.BOXS if self.BOXS != None else self.getAllBox(_active=_active)
if not difficulty.isdigit():
if difficulty.lower() in ['easy','ez','facile']:
difficulty = 20
elif difficulty.lower() in ['medium','moyen','normal']:
difficulty = 30
elif difficulty.lower() == "hard":
difficulty = 40
elif difficulty == "insane":
difficulty = 50
else:
raise Exception("Difficulty not understood for {}".format(difficulty))
print("="*(len(" Box with difficulty {}".format(difficulty))+4))
print(" Box with difficulty {}".format(difficulty))
print("="*(len(" Box with difficulty {}".format(difficulty))+4))
max = _number if _number != None else len(boxs)
for i in range(len(boxs)):
if int(boxs[i]['points']) == int(difficulty):
HTB.printBox(boxs[i])
@staticmethod
def printBox(box):
print(HTB.rate2Color(int(box['points']))+" {} (ID: {}{}{}) {}{}★{}".format(box['name'],Color.BLUE,box['id'],Color.RESET,box['rating'],Color.YELLOW,Color.RESET))
print(" {} - {}{}{}".format(box['os'],Color.YELLOW,box['ip'],Color.RESET))
user = ""
root = ""
if box['owned_user']:
user = "{} U{}: {}".format(Color.GREEN,Color.RESET,box['user'])
else:
user = "{} U{}: {}".format(Color.RED,Color.RESET,box['user'])
if box['owned_root']:
root = "{} R{}: {}".format(Color.GREEN,Color.RESET,box['root'])
else:
root = "{} R{}: {}".format(Color.RED,Color.RESET,box['root'])
if box['spawned']:
print(" Points: {} | {}{}{} | {} | {}".format(box['points'],Color.GREEN,"\u25cf",Color.RESET,user,root))
elif box['spawned'] == False:
print(" Points: {} | {}{}{} | {} | {}".format(box['points'],Color.RED,"\u25cf",Color.RESET,user,root))
else:
print(" Points: {} | {} | {}".format(box['points'],user,root))
print("")
def getBoxByOS(self,os,_active=True,_number=None):
boxs = None
if _active != self.active:
boxs = self.getAllBox(_active=_active)
else:
boxs = self.BOXS if self.BOXS != None else self.getAllBox(_active=_active)
print("="*(len("Searching for {} OS Boxs".format(os))+4))
print(" Searching for {} OS Boxs".format(os))
print("="*(len("Searching for {} OS Boxs".format(os))+4))
max = _number if _number != None else 30
for i in range(len(boxs)):
if boxs[i]['os'].lower() == os.lower():
self.printBox(boxs[i])
def setFlag(self,id,flag,difficulty=5,_name=None):
if _name != None :
id = self.getIdByName(_name)
if id == -1:
raise Exception('No box found for name {}'.format(_name))
print(id)
r = self.requests("https://www.hackthebox.eu/api/machines/own",method="POST",data={"flag":flag,"id":id,"difficulty":difficulty*10},_json=True)
if r['success'] == '1':
print("Nice Job !")
else:
print("Try again !")
def reset(self,id,_name=None):
if _name != None :
id = self.getIdByName(_name)
if id == -1:
raise Exception('No box found for name {}'.format(_name))
r = self.requests("https://www.hackthebox.eu/api/vm/reset/{}".format(id),method="POST",_json=True)
if not int(r['success']):
print("[-] Error reset : {}".format(r))
else:
print('{}. [{:d}/{:d}].'.format(r['output'], r['used'], r['total']))
def start(self,id,_name=None):
if _name != None :
id = self.getIdByName(_name)
if id == -1:
raise Exception('No box found for name {}'.format(_name))
r = self.requests("https://www.hackthebox.eu/api/vm/vip/assign/{}".format(id),method="POST",_json=True)
print(r['status'])
if "Incorrect lab type" in r['status']:
print("You are probably not VIP")
elif "You already have an active machine." in r['status']:
print("Your current Active machine is :")
HTB.printBox(htb.getBoxById(htb.getAssigned()))
def stop(self,id,_name=None):
if _name != None :
id = self.getIdByName(_name)
if id == -1:
raise Exception('No box found for name {}'.format(_name))
r = self.requests("https://www.hackthebox.eu/api/vm/vip/remove/{}".format(id),method="POST",_json=True)
print(r['status'])
if "Incorrect lab type" in r['status']:
print("You are probably not VIP")
def extend(self,id,_name=None):
if _name != None :
id = self.getIdByName(_name)
if id == -1:
raise Exception('No box found for name {}'.format(_name))
r = self.requests("https://www.hackthebox.eu/api/vm/vip/extend/{}".format(id),method="POST",_json=True)
print(r['status'])
if "Incorrect lab type" in r['status']:
print("You are probably not VIP")
def getByFilter(self,OS,difficulty,_active=True):
if not difficulty.isdigit():
if difficulty.lower() in ['easy','ez','facile']:
difficulty = 20
elif difficulty.lower() in ['medium','moyen','normal']:
difficulty = 30
elif difficulty.lower() == "hard":
difficulty = 40
elif difficulty == "insane":
difficulty = 50
else:
raise Exception("Difficulty not understood for {}".format(difficulty))
boxs = None
if _active != self.active:
boxs = self.getAllBox(_active=_active)
else:
boxs = self.BOXS if self.BOXS != None else self.getAllBox(_active=_active)
print("="*(len("OS : {} | Difficulty : {}".format(OS,difficulty))+4))
print(" Searching with filter")
print("OS : {} | Difficulty : {}".format(OS,difficulty))
print("="*(len("OS : {} | Difficulty : {}".format(OS,difficulty))+4))
for box in boxs:
if box['os'].lower() == OS and box['points'] == str(difficulty):
HTB.printBox(box)
def getIdByName(self,name,_active=False):
boxs = None
if _active != self.active:
boxs = self.getAllBox(_active=_active)
else:
boxs = self.BOXS if self.BOXS != None else self.getAllBox(_active=_active)
for box in boxs:
if box['name'].lower() == name.lower():
return box['id']
return -1
def shoutBox(self):
import time
cache = []
print("="*(len(" Shoutbox")+4))
print(" Shoutbox - Ctrl+c to leave")
print("="*(len(" Shoutbox")+4))
while True:
try:
r = self.requests("https://www.hackthebox.eu/api/shouts/get/initial/html/5",method="POST",_json=True)
for msg in r['html']:
tmp = getContent(msg)
if tmp == None:
continue
if tmp not in cache:
if len(cache) <= 5:
cache.append(tmp)
print(" -> {}".format(tmp))
else:
cache = cache[1:]
cache.append(tmp)
print(" -> {}".format(tmp))
time.sleep(1)
except KeyboardInterrupt:
print("[*] Type exit or quit to leave shoutbox, or a message to send to the shoutbox")
tmp = input("$~ ")
if tmp.lower() in ['exit','quit']:
return
else:
if self.send2Shoutbox(tmp):
print("[+] Message Sent !")
def getPersonnalInfo(self,name=None):
if name == None:
name = input('Give your HTB name : ')
# print(";"+name+";")
# # name = ""
try:
r = self.requests("https://www.hackthebox.eu/api/user/id",data={"username":name},_json=True,method="POST")
except:
print(f"Name : {name} not found !" )
return
print(r)
if r == "":
print("No Users found for name : {}".format(name))
return
if "message" in r:
if r['message'] == "":
print("No Users found for name : {}".format(name))
return
else:
print("Special case found, contact dev and show this : ")
print(r)
# print("Username : {} - id : {}".format(r['username'],r['id']))
# print("Point : {} - User : {} - Root : {}".format(r['points'],r['userOwns'],r['rootOwns']))
# print('Rank : {}'.format(r['rank']))
print('Profil URL : https://www.hackthebox.eu/home/users/profile/{}'.format(r['id']))
def getBoxByName(self,name,_active=False):
boxs = None
if _active != self.active:
boxs = self.getAllBox(_active=_active)
else:
boxs = self.BOXS if self.BOXS != None else self.getAllBox(_active=_active)
print("="*(len(" Result for {}".format(name))+4))
print(" Result for {}".format(name))
print("="*(len(" Result for {}".format(name))+4))
for box in boxs:
if box['name'].lower() == name.lower():
HTB.printBox(box)
return
def getBoxById(self,id,_active=False,_noprint=False):
boxs = None
if _active != self.active:
boxs = self.getAllBox(_active=_active)
else:
boxs = self.BOXS if self.BOXS != None else self.getAllBox(_active=_active)
if not _noprint:
print("="*(len(" Result for {}".format(id))+4))
print(" Result for {}".format(id))
print("="*(len(" Result for {}".format(id))+4))
for box in boxs:
if int(box['id']) == int(id):
return box
def getOwned(self,_active=True,_send=False):
r = self.requests("https://www.hackthebox.eu/api/machines/owns",_json=True)
if _send:
return r
for owned in r:
HTB.printBox(self.getBoxById(owned['id'],_noprint=True))
def getActiveNotOwned(self,_active=True):
boxs = None
if _active != self.active:
boxs = self.getAllBox(_active=_active)
else:
boxs = self.BOXS if self.BOXS != None else self.getAllBox(_active=_active)
r = self.requests("https://www.hackthebox.eu/api/machines/owns",_json=True)
ids = [a['id'] for a in r]
for box in boxs:
if box['id'] not in ids:
HTB.printBox(box)
else:
for owned in r:
if owned['id'] == box['id']:
if owned['owned_user'] ^ owned['owned_root']:
HTB.printBox(box)
def getBoxByDifficulty(self,difficulty,_active=True,_number=None):
boxs = None
if _active != self.active:
boxs = self.getAllBox(_active=_active)
else:
boxs = self.BOXS if self.BOXS != None else self.getAllBox(_active=_active)
if not difficulty.isdigit():
if difficulty.lower() in ['easy','ez','facile']:
difficulty = 20
elif difficulty.lower() in ['medium','moyen','normal']:
difficulty = 30
elif difficulty.lower() == "hard":
difficulty = 40
elif difficulty == "insane":
difficulty = 50
else:
raise Exception("Difficulty not understood for {}".format(difficulty))
print("="*(len(" Box with difficulty {}".format(difficulty))+4))
print(" Box with difficulty {}".format(difficulty))
print("="*(len(" Box with difficulty {}".format(difficulty))+4))
max = _number if _number != None else len(boxs)
for i in range(len(boxs)):
if int(boxs[i]['points']) == int(difficulty):
HTB.printBox(boxs[i])
@staticmethod
def printBox(box):
print(HTB.rate2Color(int(box['points']))+" {} (ID: {}{}{}) {}{}★{}".format(box['name'],Color.BLUE,box['id'],Color.RESET,box['rating'],Color.YELLOW,Color.RESET))
print(" {} - {}{}{}".format(box['os'],Color.YELLOW,box['ip'],Color.RESET))
user = ""
root = ""
if box['owned_user']:
user = "{} U{}: {}".format(Color.GREEN,Color.RESET,box['user'])
else:
user = "{} U{}: {}".format(Color.RED,Color.RESET,box['user'])
if box['owned_root']:
root = "{} R{}: {}".format(Color.GREEN,Color.RESET,box['root'])
else:
root = "{} R{}: {}".format(Color.RED,Color.RESET,box['root'])
if box['spawned']:
print(" Points: {} | {}{}{} | {} | {}".format(box['points'],Color.GREEN,"\u25cf",Color.RESET,user,root))
elif box['spawned'] == False:
print(" Points: {} | {}{}{} | {} | {}".format(box['points'],Color.RED,"\u25cf",Color.RESET,user,root))
else:
print(" Points: {} | {} | {}".format(box['points'],user,root))
print("")
def getBoxByOS(self,os,_active=True,_number=None):
boxs = None
if _active != self.active:
boxs = self.getAllBox(_active=_active)
else:
boxs = self.BOXS if self.BOXS != None else self.getAllBox(_active=_active)
print("="*(len("Searching for {} OS Boxs".format(os))+4))
print(" Searching for {} OS Boxs".format(os))
print("="*(len("Searching for {} OS Boxs".format(os))+4))
max = _number if _number != None else 30
for i in range(len(boxs)):
if boxs[i]['os'].lower() == os.lower():
self.printBox(boxs[i])
def test(self):
# BOXS = self.getAllBox(_active=True)
CHALLS = self.requests("https://www.hackthebox.eu/api/challenges/stego",_json=True)
print(CHALLS)
def send2Shoutbox(self,text):
r = self.requests("https://www.hackthebox.eu/api/shouts/new",method="POST",data = { "text" : text },_json=True)
return r['success'] == '1'
def requests(self,url,method="GET",data=None,_json=False):
head = {
'User-Agent' : 'YOLO HTB',
'Authorization' : 'Bearer {}'.format(self.api_key),
'Accept-Encoding': 'gzip, deflate',
'Accept' : 'application/json',
'Connection' : 'Close',
}
if method == "GET":
r = self.session.get(url,headers=head,verify=False)
if r.status_code == 401:
raise Exception("Bad API key")
if _json:
return r.json()
return r.text
elif method == "POST":
r = self.session.post(url,headers=head,data=data,verify=False)
if r.status_code == 401:
raise Exception("Bad API key")
if _json:
return r.json()
return r.text
class pile:
def __init__(self):
self.pos = 0
self.liste = []
def getUP(self):
self.pos -= 1
if self.pos < 0:
self.pos = 0
tmp = self.liste[self.pos]
return tmp
def getDOWN(self):
self.pos += 1
if self.pos >= len(self.liste) -1:
self.pos = len(self.liste) -1
tmp = self.liste[self.pos]
return tmp
def set(self,item):
self.liste.append(item)
self.found()
def found(self):
self.pos = len(self.liste)
stack = pile()
def getInput():
global stack
buffer = ""
cmd = ""
print("{}$~{} \33[5m_\33[25m ".format(Color.RED,Color.RESET),end="\r")
# buffer = getkey()
while buffer != "\r":
buffer = str(readchar.readkey())
if buffer == "":
continue
# ENTER
if buffer == "\r":
break
# CTRL + c
if buffer == "\x03":
return "quit"
# tab
if buffer == "\t":
if len(cmd) == 0:
print(' '.join(available_commands))
else:
aux = []
for i in available_commands:
if i.startswith(cmd):
aux.append(i)
if len(aux) == 1:
cmd = aux[0]
else:
aux = ' '.join(aux)
print("{} ".format(aux))
# up arrow
elif buffer == keys.UP:
if len(stack.liste) > 0:
cmd = stack.getUP()
# down arrow
elif buffer == keys.DOWN:
if len(stack.liste) > 0:
cmd = stack.getDOWN()
# delete
elif buffer == keys.BACKSPACE:
# print("DELETE")
cmd = cmd[:-1]
else:
cmd += buffer
print("{}$~{} {}\33[5m_\33[25m ".format(Color.RED,Color.RESET,cmd),end="\r")
print("{}$~{} {} ".format(Color.RED,Color.RESET,cmd))
stack.set(cmd)
return cmd
available_commands = ['reset','flag','getboxs','gbbo','gbbd','gbbr','getboxbyname','getowned','getnotowned','shoutbox','profile','getbyfilter','setActive','setNumber','exit','quit','q']
if __name__ == "__main__":
args = parser()
key = ""
if not isfile(HOME+"/.htb_api.txt"):
print("[+] First time using HackTheBox API")
print("[+] Enter your API_key, it will be save in your Home directory")
key = input("[+] Enter your key : ")
with open(HOME+'/.htb_api.txt','w') as f:
f.write(key)
else:
with open(HOME+'/.htb_api.txt','r') as f:
key = f.read().replace('\n','')
htb = HTB(key)
htb.isVIP()
# htb.getPersonnalInfo()
# exit()
if args.test_mode:
htb.test()
exit()
print("HTB Shell - put help to get info")
if htb.isvip:
print("You are VIP")
available_commands += ['start','stop','extend','getspawned']
else:
print("You are not VIP")
if args.execute != None:
cmd = args.execute
else:
cmd = ""
cmd = getInput()
active = True
number = 20
while cmd.lower() not in ['exit','quit','q']:
try:
command,args = getCMD(cmd)
if command.lower() == "help":
print("="*(len("HELP")+4))
print(" HELP")
print("="*(len("HELP")+4))
if htb.isvip:
print("\n{}start{} ID".format(Color.GREEN,Color.RESET))
print(" Start Box")
print("{}stop{} ID".format(Color.GREEN,Color.RESET))
print(" Stop Box")
print("{}extend{} ID".format(Color.GREEN,Color.RESET))
print(" Extend Box time")
print("{}getspawned{}".format(Color.GREEN,Color.RESET))
print(" Get spawned box")
print("{}reset{} ID".format(Color.GREEN,Color.RESET))
print(" Reset Box")
print("{}flag{} ID FLAG [DIFFICULTY 1-10]".format(Color.GREEN,Color.RESET))
print(" Submit Flag")
print("{}getboxs{}".format(Color.GREEN,Color.RESET))
print(" Get all box")
print("{}gbbo{} OS".format(Color.GREEN,Color.RESET))
print(" Get Box by OS")
print("{}gbbd{} difficulty (points)".format(Color.GREEN,Color.RESET))
print(" Get Box by difficulty")
print("{}gbbr{}".format(Color.GREEN,Color.RESET))
print(" Get Box sorted by rating")
print("{}getboxbyname{} NAME".format(Color.GREEN,Color.RESET))
print(" Get Box by name")
print("{}getowned{}".format(Color.GREEN,Color.RESET))
print(" Get Box owned")
print("{}getnotowned{}".format(Color.GREEN,Color.RESET))
print(" Get Active box not owned yet")
print("{}shoutbox{}".format(Color.GREEN,Color.RESET))
print(" Listen the shoutbox, permit to send to the shoutbox too")
print("{}profile{} name".format(Color.GREEN,Color.RESET))
print(" Get profile by name")
print("{}getbyfilter{} OS difficulty".format(Color.GREEN,Color.RESET))
print(" Get Box by some filter")
print("{}setActive{}".format(Color.GREEN,Color.RESET))
print(" Inverse active values, if you want or not get only active box from research ")
print("{}setNumber{} number".format(Color.GREEN,Color.RESET))
print(" Put the Box's number to print - default all active or 20")
print("{}exit{} or {}quit{} or {}q{} to quit".format(Color.GREEN,Color.RESET,Color.GREEN,Color.RESET,Color.GREEN,Color.RESET))
print(Color.YELLOW+"ID"+Color.BLUE+" can be ID number or Box name")
print(Color.YELLOW+"Difficulty "+Color.BLUE+"for getboxbydifficulty can be Number or strings like \"easy\""+Color.RESET)
elif command.lower() == "setactive":
if active:
active = False
print("[+] Active variable set to False")
else:
active = True
print("[+] Active variable set to True")
elif command.lower() == "setnumber":
if len(args) == 0:
print("[-] No args set to 20 by default")
number = 20
else:
if not args[0].isdigit():
print("[-] Args value error, set to 20 by default")
number = 20
else:
print("[+] Number set to {}".format(args[0]))
number = int(args[0])
elif command.lower() == "start":
if len(args) == 0:
print("[-] Syntax error : start ID")
else:
if args[0].isdigit():
htb.start(args[0])
else:
htb.start(args[0],_name=args[0])
elif command.lower() == "stop":
if len(args) == 0:
print("[-] Syntax error : stop ID")
else:
if args[0].isdigit():
htb.stop(args[0])
else:
htb.stop(args[0],_name=args[0])
elif command.lower() == "extend":
if len(args) == 0:
print("[-] Syntax error : extend ID")
else:
if args[0].isdigit():
htb.extend(args[0])
else:
htb.extend(args[0],_name=args[0])
elif command.lower() == "reset":
if len(args) == 0:
print("[-] Syntax error : reset ID")
else:
if args[0].isdigit():
htb.reset(args[0])
else:
htb.reset(args[0],_name=args[0])
elif command.lower() == "flag":
difficulty = 5
if len(args) == 0 or len(args) == 1:
print("[-] Syntax error : flag ID FLAG [DIFFICULTY]")
else:
if len(args) < 3:
difficulty = 5
else:
if args[2].isdigit():
if int(difficulty) <= 0 or int(difficulty) > 10:
print("Difficulty not valid for {} - set to 5 by default".format(difficulty))
difficulty = 5
else:
difficulty = int(args[2])
else:
print("Difficulty not valid for {} - Set to 5 by default".format(difficulty))
difficulty = 5
if args[0].isdigit():
htb.setFlag(args[0],args[1],difficulty=difficulty)
else:
htb.setFlag(args[0],args[1],difficulty=difficulty,_name=args[0])
elif command.lower() == "getboxs":
print("="*(len(" All Box")+4))
print(" All Box")
print("="*(len(" All Box")+4))
for i in htb.getAllBox(_number=number,_active=active):
HTB.printBox(i)
elif command.lower() == "gbbo":
if len(args) == 0:
print("[-] Syntax error : gbbo OS")
else:
htb.getBoxByOS(args[0],_number=number,_active=active)
elif command.lower() == "gbbd":
if len(args) == 0:
print("[-] Syntax error : gbbd difficulty")
else:
htb.getBoxByDifficulty(args[0],_number=number,_active=active)
elif command.lower() == "gbbr":
htb.getBetterRated(_active=active,_number=number)
elif command.lower() == "getboxbyname":
if len(args) == 0:
print('[-] Syntax error getboxbyname NAME')
else:
htb.getBoxByName(args[0])
elif command.lower() == "getowned":
htb.getOwned(_active=active,_send=False)
elif command.lower() == "getnotowned":
htb.getActiveNotOwned()
elif command.lower() == "getspawned":
htb.getSpawned()
elif command.lower() == "shoutbox":
htb.shoutBox()
elif command.lower() == "getbyfilter":
if len(args) != 2:
print("[-] Syntaxe error : getbyfilter OS difficulty")
else:
htb.getByFilter(args[0],args[1],_active=active)
elif command.lower() == "profile":
if len(args) >= 1:
htb.getPersonnalInfo(name=args[0])
else:
htb.getPersonnalInfo()
else:
print("[-] Command not found")
except Exception as e:
print("Error in command: {}".format(e))
# raise(e)
# cmd = input("{}$~{} ".format(Color.RED,Color.RESET))
cmd = getInput()
# a.getBoxByDifficulty("e,_active=False)