package exploitpack;

import java.awt.Color;
import java.awt.Toolkit;
import javax.swing.JOptionPane;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
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 UpdateManager extends javax.swing.JFrame {

    private String licenseType;
    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;

    /**
     * Creates new form UpdateManager
     */
    public UpdateManager() {
        initComponents();

        int lebar = this.getWidth() / 2;
        int tinggi = this.getHeight() / 2;
        int x = (Toolkit.getDefaultToolkit().getScreenSize().width / 2) - lebar;
        int y = (Toolkit.getDefaultToolkit().getScreenSize().height / 2) - tinggi;
        this.setLocation(x, y);
        this.setVisible(true);
        setDefaultCloseOperation(UpdateManager.DISPOSE_ON_CLOSE);
        getContentPane().setBackground(Color.WHITE);
        setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/exploitpack/resources/bug.png")));
        if (SplashScreen.filepath) {
            jButton2.setEnabled(true);
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaUpdate = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel6 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Exploit Pack - Update manager");
        setResizable(false);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exploitpack/resources/about.png"))); // NOI18N

        jButton1.setText("Close");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Update");
        jButton2.setEnabled(false);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText("Get the latest exploit modules from http://exploitpack.com");

        jTextAreaUpdate.setEditable(false);
        jTextAreaUpdate.setBackground(new java.awt.Color(1, 1, 1));
        jTextAreaUpdate.setColumns(20);
        jTextAreaUpdate.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
        jTextAreaUpdate.setForeground(new java.awt.Color(254, 254, 254));
        jTextAreaUpdate.setRows(5);
        jTextAreaUpdate.setText("Attention! The update process could take a few minutes...       \nClick update to start.\n\n[*] You need to be a Premium user to use the update manager.\n");
        jScrollPane1.setViewportView(jTextAreaUpdate);

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exploitpack/resources/updater.png"))); // NOI18N

        jLabel4.setText("Get updates, new modules, exploits and  the latest utilities with this manager");

        jLabel5.setText("Module sources: Exploit-DB, PacketStorm, Private stacks and Exploit Pack.");

        jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exploitpack/resources/up2.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jSeparator1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane1))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(53, 53, 53)
                                        .addComponent(jLabel8))
                                    .addComponent(jLabel6))
                                .addGap(0, 191, Short.MAX_VALUE)))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jSeparator2)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel3)
                        .addGap(35, 35, 35))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(2, 2, 2)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(2, 2, 2)
                        .addComponent(jLabel5))
                    .addComponent(jLabel3))
                .addGap(2, 2, 2)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        getAccessibleContext().setAccessibleName("Exploit Pack - Update modules");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        Thread agentServer = new Thread("agentThread") {
            @Override
            public void run() {
                try {
                    JOptionPane.showMessageDialog(null, "After getting the updates restart Exploit Pack", "Exploit Pack says:", JOptionPane.INFORMATION_MESSAGE);

                    URL urlExploits = new URL("https://raw.githubusercontent.com/offensive-security/exploit-database/master/files_exploits.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[6].replaceAll("\"", "").replaceAll("<", "").replaceAll(">", "").replaceAll("&", "").replaceAll("=", "").replaceAll("'", "").replaceAll("/", "");
                            String etype = exploit[5].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
                            if (!eauthor.equals("author")) {
                                jTextAreaUpdate.append("[!] Contacting official server: http://exploitpack.com" + "\n");
                                jTextAreaUpdate.append("[?] Downloading: " + ename + "\n");
                                jTextAreaUpdate.append("[*] Exploit number: " + enumber + "\n");
                                jTextAreaUpdate.append("[*] Path: " + epath + "\n");
                                jTextAreaUpdate.append("[*] Name: " + ename + "\n");
                                jTextAreaUpdate.append("[*] Date: " + edate + "\n");
                                jTextAreaUpdate.append("[*] Author: " + eauthor + "\n");
                                jTextAreaUpdate.append("[*] Platform: " + eplatform + "\n");
                                jTextAreaUpdate.append("[*] Type: " + etype + "\n");
                                jTextAreaUpdate.append("[*] Port: " + eport + "\n");
                                int len = jTextAreaUpdate.getDocument().getLength();
                                jTextAreaUpdate.setCaretPosition(len);
                            }
                        }
                    }
                    String zipName = "exploits/" + File.separator + "exploitsUpdate.zip";
                    try {
                        jTextAreaUpdate.append("[!] Please wait a few minutes.. \n");

                        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/exploits").toPath())) {
                            Files.delete(new File(zipName).toPath());
                            deleteDirectory("exploits/code/exploits");
                            Files.delete(new File("exploits/code/exploits").toPath());
                            deleteDirectory("exploits/exploitdb-master");
                        }

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

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

                } catch (IOException e) {
                    //   System.out.println(e);
                }
                JOptionPane.showMessageDialog(null, "Please restart Exploit Pack for the changes to take effect.", "Exploit Pack says:", JOptionPane.INFORMATION_MESSAGE);
                jTextAreaUpdate.append("[*] Update executed successfully! \n");
            }
        };
        agentServer.start();

    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;

                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(UpdateManager.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(UpdateManager.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(UpdateManager.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(UpdateManager.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new UpdateManager().setVisible(true);
            }
        });
    }

    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();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTextArea jTextAreaUpdate;
    // End of variables declaration//GEN-END:variables
}
