package exploitpack;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;

/**
 *
 * @author jsacco
 */
public class Exploits implements Runnable {

    String URL = "http://www.exploit-db.com";
    String page = "/search/?action=search&filter_page=1";
    String description = "&filter_description=";
    String text = "&filter_exploit_text=";
    String author = "&filter_author=";
    String platform = "&filter_platform=45";
    String type = "&filter_type=2";
    String lang = "&filter_lang_id=0";
    String port = "&filter_port=";
    String OSVDB = "&filter_osvdb=";
    String CVE = "&filter_cve=";
    URL url;
    BufferedReader in;
    String readPage;

    public Exploits() {
    }

    @Override
    public void run() {
        try {

            URL urlExploits = new URL("https://github.com/offensive-security/exploit-database/raw/master/files.csv");
            try ( // Read all the text returned by the server
                    BufferedReader inBuffer = new BufferedReader(
                            new InputStreamReader(urlExploits.openStream()))) {
                String exploitLine;
                String cvsSplitBy = ",";
                while ((exploitLine = inBuffer.readLine()) != null) {

                    // use comma as separator
                    String[] exploit = exploitLine.split(cvsSplitBy);
                    String enumber = exploit[0];
                    String epath = exploit[1];
                    String ename = exploit[2].replaceAll("\"", "").replaceAll("<", "").replaceAll(">", "").replaceAll("&", "").replaceAll("=", "").replaceAll("'", "").replaceAll("/", "");
                    String edate = exploit[3].replaceAll("\"", "").replaceAll("<", "").replaceAll(">", "").replaceAll("&", "").replaceAll("=", "").replaceAll("'", "").replaceAll("/", "");
                    String eauthor = exploit[4].replaceAll("\"", "").replaceAll("<", "").replaceAll(">", "").replaceAll("&", "").replaceAll("=", "").replaceAll("'", "").replaceAll("/", "");
                    String eplatform = exploit[5].replaceAll("\"", "").replaceAll("<", "").replaceAll(">", "").replaceAll("&", "").replaceAll("=", "").replaceAll("'", "").replaceAll("/", "");
                    String etype = exploit[6].replaceAll("\"", "").replaceAll("<", "").replaceAll(">", "").replaceAll("&", "").replaceAll("=", "").replaceAll("'", "").replaceAll("/", "");
                    String eport = exploit[7].replaceAll("\"", "").replaceAll("<", "").replaceAll(">", "").replaceAll("&", "").replaceAll("=", "").replaceAll("'", "").replaceAll("/", "");
                    
                    try {
                        // Create file
                        FileWriter fstream = new FileWriter("exploits/" + ename + ".xml");
                        BufferedWriter out = new BufferedWriter(fstream);
                        String Shellcode = "RE";
                        out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                        out.write("<Module><Exploit NameXML=\""
                                + ename
                                + "\" CodeName=\"" + epath + "\"  Platform=\"" + eplatform + "\" Service=\"" + eport + "\" Type=\"" + etype + "\" RemotePort=\"" + eport + "\" LocalPort=\"\" ShellcodeAvailable=\"" + Shellcode + "\" ShellPort=\"4444\" SpecialArgs=\"\"></Exploit>");
                        out.write("<Information Author=\"" + stripNonValidXMLCharacters(eauthor) + "\" Date=\""
                                + edate
                                + "\" Vulnerability=\""
                                + enumber
                                + "\">\r\n" + stripNonValidXMLCharacters(ename) + "</Information><Targets>" + eplatform + "</Targets></Module>");
                        out.close();
                        
                    } catch (IOException ex) {
                        Logger.getLogger(ExploitWizard.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    //DEBUG
                    System.out.println("");
                    System.out.println("Number:" + enumber);
                    System.out.println("Path:" + epath);
                    System.out.println("Name:" + ename);
                    System.out.println("Date:" + edate);
                    System.out.println("Author:" + eauthor);
                    System.out.println("Platform:" + eplatform);
                    System.out.println("Type:" + etype);
                    System.out.println("Port:" + eport);
                }
            }
            String zipName = "exploits/" + File.separator + "exploitsUpdate.zip";
            try {
                URL urlDownload = new URL("https://github.com/offensive-security/exploit-database/archive/master.zip");
                Path targetPath = new File(zipName).toPath();
                Files.copy(urlDownload.openStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
                ZipFile zipFile = new ZipFile(zipName);
                zipFile.extractAll("exploits/");

                // Remove files and directories
                if (Files.exists(new File("exploits/code/platforms").toPath())) {
                    Files.delete(new File(zipName).toPath());
                    deleteDirectory("exploits/code/platforms");
                    Files.delete(new File("exploits/code/platforms").toPath());
                    deleteDirectory("exploits/exploit-database-master");
                }

                Files.move(new File("exploits/exploit-database-master/platforms").toPath(), new File("exploits/code/platforms").toPath(), StandardCopyOption.REPLACE_EXISTING);
                Files.delete(new File(zipName).toPath());

                deleteDirectory("exploits/exploit-database-master");

            } catch (ZipException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            System.out.println(e);
        }
    }

    public void deleteDirectory(String directory) throws IOException {
        File f = new File(directory);
        File[] files = f.listFiles();
        for (File file : files) {
            file.delete();
        }
        Files.delete(new File("exploits/exploit-database-master").toPath());
    }

    public static String stripNonValidXMLCharacters(String in) {
        StringBuilder out = new StringBuilder(); // Used to hold the output.
        char current; // Used to reference the current character.

        if (in == null || ("".equals(in))) {
            return ""; // vacancy test.
        }
        for (int i = 0; i < in.length(); i++) {
            current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen.
            if ((current == 0x9)
                    || (current == 0xA)
                    || (current == 0xD)
                    || ((current >= 0x20) && (current <= 0xD7FF))
                    || ((current >= 0xE000) && (current <= 0xFFFD))
                    || ((current >= 0x10000) && (current <= 0x10FFFF))) {
                out.append(current);
            }
        }
        return out.toString();
    }
}
