1

I am doing some CTF for fun and I got stuck, I run binary with python script with subprocessing, The problem is the script need to send to the read function in the binary empty input to not change the current value (if there is a way to make the read operation fail and return -1, it will be cool to know also how to do)(if there is a way to make the read operation fail and return -1, it will be cool to know also how to do), and continue the running without closing the pipes or something.

short example to illustrate the problem: python script

import subprocess
import signal
import time
import os

def read_all(pipe, timeout=0.5):
    start = time.time()
    content = b''
    while True:
        line = pipe.readline()
        if line != b'':
            content += line
        if time.time() - start >= timeout:
            return content.decode('utf-8')

ps = subprocess.Popen('./test', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
os.set_blocking(ps.stdout.fileno(), False)

print(read_all(ps.stdout))
ps.stdin.write(b'')
ps.stdin.flush()
print(read_all(ps.stdout))

test.c:

#include<stdio.h>
#include<stdlib.h>

#define some_random_value 0

int main()
{
        int num = some_random_value;
        setvbuf(stdout, NULL, _IONBF, 0);

        printf("Communication with the python code\n");
        printf("Enter Something: \n");
        printf("%d bytes read\n", read(0, &num, 0x4));

        if (num == some_random_value)
                printf("SUCCESS\n");
        if (num != some_random_value)
                printf("FAILED\n");

        //continue chatting, input, output etc...
        return 0;
}

In this example the binary want continue the execution pass the read function so it's not good

  • But if I close the pipe could how could I send something afterwards? – nadav levin Jul 27 '23 at 16:18
  • You can't send something after EOF in a pipe. That's only allowed in regular files (by adding to the file) and terminals (EOF happens when you type Ctl-d on an empty line, but you can keep reading after that). – Barmar Jul 27 '23 at 16:23
  • Also, writing an empty string doesn't do anything. I'm not sure what you expect that write and flush to do. – Barmar Jul 27 '23 at 16:25
  • You seem to be trying to use the pipe like a datagram socket. But it's a character stream, there are no messages. – Barmar Jul 27 '23 at 16:26

1 Answers1

0

You send EOF by closing the pipe:

ps.stdin.close()

I don't think there's any way to trigger an error when reading from the pipe. Errors from read() are usually due to problems in the parameters. The only situation I can think of where a sender can trigger read errors is with TCP sockets, if the sender sends a RST segment before the reader tries to read (I think this will cause an ENOTCONN error).

Barmar
  • 741,623
  • 53
  • 500
  • 612