How to send an eof to a process/server in pwntools?

5.1k Views Asked by At

I was trying to make read return 0 in a program (the one in the while loop), and then execute the second read properly, which worked perfectly by hand, with CTRL-D. However I wanted to do the same in pwntools (p = process("./test")). I have already tried to send the eof character with p.sendline("\x04") but didn't work. The program took the input like "\x0a\x04". p.send() doesn't change anything. This is my test program:

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

int main(void) {
   char buf[24];
   while(1) {
      if(read(0,buf,16)==0) {
         break;
      }
   }
   read(0,buf,16);
   return 0;
}

I hope anyone can help me.

1

There are 1 best solutions below

0
On

It depends on the type of connection.

If it is a pipe or a socket, there is no other way than closing the connection.

But if it is a pseudo-terminal (you can enforce it in pwntools by using process(..., stdin=PTY)), you can use the terminal line editing capabilities of the operating system (see termios(3) for the description of canonical mode), you can send it an EOF mark with p.send(b'\4') (i.e. Ctrl+D).

So your final code should look something like:

from pwn import *

p = process('./test', stdin=PTY)
p.send(b'\4')  # mind the b before binary data literal (text is not bytes)

# then something else maybe
p.interactive()