1

I am trying to make a program in python to brute force a ctf C program where you have to find a fruit salad recipe in order to get the flag.

what I want to do : I want to be able to write on the stdin of the C program in python.

Problem : the stdin of the process returned by Popen has a none value while stdout and stderr are correct.

output from my program :

start bruteforce...
<_io.BufferedReader name=3>
<_io.BufferedReader name=5>
None

code :

as you can see I am using print then exit before the loop to debug the process std, I don't understand why I get None when I print print(process.stdin)

!/usr/bin/python3

import random
import os
import sys
from subprocess import *
from contextlib import contextmanager
from io import StringIO

fruit = ["banana", "raspberry", "orange", "lemon"]
comb = ""
found = False

print("start bruteforce...")

process = Popen(['./fruit'], stdout=PIPE, stderr=PIPE)
print(process.stdout)
print(process.stderr)
print(process.stdin)
sys.exit(1)
while True:    
    for i in range(4):
        pick = random.choice(fruit)
        inp, output = process.stdin, process.stdout
        comb += pick
        comb += " "
        inp.write(pick)
        inp.write("\n")
        out = output.read().decode('utf-8')
        if "flag" in out:
            found = True
            break
    if found == True:
        print("found : " + com) 
        break
    print(comb + " : is not valid")
    comb = ""
os.kill(p.pid, signal.CTRL_C_EVENT)

thanks you !

Fosowl
  • 29
  • 1
  • 5
  • According to the docs [_"With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent."_](https://docs.python.org/3/library/subprocess.html#subprocess.Popen). So the subprocess gets the same input as the parent programm. I think you need to specify `stdin=PIPE` to get a handle to pass input to the programm. – Ackdari May 12 '20 at 10:28
  • thanks you ! I didn't paid much attention to the argument I pass to Popen and thought I didn't have to specify stdin !@Ackdari – Fosowl May 12 '20 at 10:42

2 Answers2

0

fixed thanks to Ackdari, I replaced :

process = Popen(['./fruit'], stdout=PIPE, stderr=PIPE)

with

process = Popen(['./fruit'], stdout=PIPE, stdin=PIPE)

since I am not using stderr anyways.

Fosowl
  • 29
  • 1
  • 5
-1

I want to be able to write on the stdin

This is forbidden, at least by POSIX standards, and makes no sense on Linux. As suggested by its name stdin is a standard input and you program should read not write it.

Of course, notice that pipe(7)-s have an input and an output. You are writing on your stdout and that is the stdin of the popen-ed process.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • He wants to write on the `stdin` of the child process not on its own, which is totally fine if the child process has its own stdin and it is writeable like a pipe. I think you missed the point of the question. – Ackdari May 12 '20 at 15:14