package exploitpack;

import java.awt.Color;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author jsacco
 */
public class NetworkMapper extends javax.swing.JFrame {

    // Configuration
    public String nmappath;
    public String pythonpath;
    public String ScannerOptions = "";
    Thread scannerThread;
    List<String> config = new ArrayList<>();
    StringBuilder pentestNote = new StringBuilder();
    Format formatter;
    Date date = new Date();
    Process processFuzzer;
    private String LogTime;

    /**
     * Creates new form ratWizard
     */
    public NetworkMapper() {
        try {
            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(ExploitWizard.DISPOSE_ON_CLOSE);
            getContentPane().setBackground(Color.WHITE);
            setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/exploitpack/resources/bug.png")));
            jTextFieldTargetH.setText(Inet4Address.getLocalHost().getHostAddress());

        } catch (UnknownHostException ex) {
            Logger.getLogger(NetworkMapper.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 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() {

        jTextField3 = new javax.swing.JTextField();
        jTextField5 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextFieldRatName = new javax.swing.JTextField();
        jTextFieldTargetH = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaLog = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();

        jTextField3.setText("jTextField1");

        jTextField5.setText("jTextField1");

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

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

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

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

        jLabel2.setText("<html>Exploit Pack network scan feature will help you map your network, create your targets list<br> and identify possible threats within your environment. For every host a new XML log file will be created, that you can use later on to match templates  and identify changes within your network infrastructure.</html>");

        jLabel3.setText("Scan name:");
        jLabel3.setToolTipText("");

        jLabel5.setText("IP / Hostname:");

        jTextFieldRatName.setText("My network scan");

        jTextFieldTargetH.setText("127.0.0.1");

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

        jTextAreaLog.setEditable(false);
        jTextAreaLog.setBackground(java.awt.Color.black);
        jTextAreaLog.setColumns(20);
        jTextAreaLog.setForeground(java.awt.Color.green);
        jTextAreaLog.setRows(5);
        jTextAreaLog.setText("[*] There is no scan running at this time.\n[*] Status: OK\n");
        jScrollPane1.setViewportView(jTextAreaLog);

        jLabel4.setFont(jLabel4.getFont().deriveFont(jLabel4.getFont().getStyle() | java.awt.Font.BOLD));
        jLabel4.setText("Status log of current scan:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jSeparator2))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(jButton2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButton1))
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(9, 9, 9)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel11))
                            .addComponent(jScrollPane1)
                            .addComponent(jSeparator1)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel5))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextFieldRatName, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(jTextFieldTargetH, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1)
                .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)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jTextFieldRatName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextFieldTargetH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel4))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
                        .addComponent(jLabel11)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 444, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(35, Short.MAX_VALUE))
        );

        jLabel2.getAccessibleContext().setAccessibleName("<html>This shell wizard helps you create your  personalized agent to use with Exploit Pack.  <br>The created script, if needed, could include also a custom shellcode<br> and converted into an executable file.</html>");

        pack();
        setLocationRelativeTo(null);
    }// </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
        FileReader fstream = null;
        try {
            // Read config file
            fstream = new FileReader("output/" + "config" + ".ep");
            BufferedReader in = new BufferedReader(fstream);
            String stringToAppend;
            while ((stringToAppend = in.readLine()) != null) {
                config.add(stringToAppend);
            }
            pythonpath = config.get(0);
            nmappath = config.get(1);
            ScannerOptions = config.get(2);

            scannerThread = new Thread("scannerThread") {
                @Override
                public void run() {
                    try {
                        // Exec wav RAT
                        AudioInputStream sourceAux;
                        AudioFormat f;
                        DataLine.Info inputAux;
                        File inputFileAux = new File("data/newauxiliarydeployed.wav");
                        Clip c;
                        sourceAux = AudioSystem.getAudioInputStream(inputFileAux);
                        f = sourceAux.getFormat();
                        inputAux = new DataLine.Info(Clip.class, f);
                        c = (Clip) AudioSystem.getLine(inputAux);
                        c.open(sourceAux);
                        c.start();

                        // Exec scan
                        JOptionPane.showMessageDialog(null, "Please wait, the scan could take a few minutes", "Exploit Pack says:", JOptionPane.INFORMATION_MESSAGE);
                        String cmd = nmappath + " " + ScannerOptions + " " + jTextFieldTargetH.getText() + " -oA log/" + jTextFieldTargetH.getText();
                        String line;
                        OutputStream stdin = null;
                        InputStream stderr = null;
                        InputStream stdout = null;
                        processFuzzer = Runtime.getRuntime().exec(cmd);
                        stdin = processFuzzer.getOutputStream();
                        stderr = processFuzzer.getErrorStream();
                        stdout = processFuzzer.getInputStream();

                        // "write" the parms into stdin
                        //stdin.write(line.getBytes());
                        stdin.flush();
                        stdin.close();

                        // Obtain local time
                        Format formatter;
                        Date date = new Date();
                        formatter = new SimpleDateFormat("HH:mm:ss");
                        LogTime = formatter.format(date);
                        jTextAreaLog.append("[" + LogTime + "]" + " A new nmap session has been initiated.\n");
                        // clean up if any output in stdout
                        BufferedReader brCleanUp
                                = new BufferedReader(new InputStreamReader(stdout));
                        while ((line = brCleanUp.readLine()) != null) {
                            jTextAreaLog.append(line + "\n");
                        }

                        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder dBuilder;
                        dBuilder = dbFactory.newDocumentBuilder();
                        Document doc = dBuilder.parse(new File("log/" + jTextFieldTargetH.getText() + ".xml"));
                        doc.getDocumentElement().normalize();
                        NodeList nList = doc.getElementsByTagName("port");
                        String openports = null;
                        for (int temp = 0; temp < nList.getLength(); temp++) {
                            Node nNode = nList.item(temp);
                            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                                // Create target
                                FileWriter fstream = null;
                                try {
                                    String name = jTextFieldTargetH.getText();
                                    fstream = new FileWriter("exploits/" + name + ".xml");
                                    BufferedWriter out = new BufferedWriter(fstream);
                                    out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                                    out.write("<Module><Exploit NameXML=\""
                                            + name
                                            + "\" CodeName=\"" + name + ".txt" + "\"  Platform=\"" + "windows" + "\" Service=\"" + "" + "\" Type=\"" + "notepad" + "\" RemotePort=\"" + "" + "\" LocalPort=\"\" ShellcodeAvailable=\"" + "" + "\" ShellPort=\"4444\" SpecialArgs=\"" + "" + "\"></Exploit>");
                                    out.write("<Information Author=\"" + "ExploitPack" + "\" Date=\""
                                            + new Timestamp(date.getTime())
                                            + "\" Vulnerability=\""
                                            + "none"
                                            + "\">\r\n" + "" + "</Information><Targets>" + "" + "</Targets></Module>");
                                    out.close();
                                    fstream = new FileWriter("exploits/code/" + name + ".txt");
                                    BufferedWriter outCode = new BufferedWriter(fstream);

                                    FileReader fstreamRead = null;
                                    fstreamRead = new FileReader("log/" + jTextFieldTargetH.getText() + ".nmap");
                                    BufferedReader in = new BufferedReader(fstreamRead);
                                    String stringToAppend;
                                    while ((stringToAppend = in.readLine()) != null) {
                                        pentestNote.append(stringToAppend + "\n");
                                    }
                                    outCode.write(pentestNote.toString().replaceAll("^,", "").replaceAll(",,", ",").replaceAll(",$", "").replaceAll("null", ""));
                                    pentestNote.insert(0, "# Pentest notes for: " + jTextFieldTargetH.getText() + " [Exploit Pack]" + "\n");
                                    outCode.close();

                                } catch (IOException ex) {
                                    Logger.getLogger(Notepad.class
                                            .getName()).log(Level.SEVERE, null, ex);
                                } finally {
                                    try {
                                        fstream.close();
                                    } catch (IOException ex) {
                                        Logger.getLogger(Notepad.class
                                                .getName()).log(Level.SEVERE, null, ex);
                                    }
                                }
                            }
                        }
                        File inputFileAux1 = new File("data/scanner.wav");
                        sourceAux = AudioSystem.getAudioInputStream(inputFileAux1);
                        f = sourceAux.getFormat();
                        inputAux = new DataLine.Info(Clip.class, f);
                        c = (Clip) AudioSystem.getLine(inputAux);
                        c.open(sourceAux);
                        c.start();
                        JOptionPane.showMessageDialog(null, jTextFieldTargetH.getText() + " added successfully to your targets. Go to Targets/Refresh to show them.", "Exploit Pack says:", JOptionPane.INFORMATION_MESSAGE);
                        jTextAreaLog.append("[ " + LogTime + " ] " + "The scan to: " + jTextFieldTargetH.getText() + " has finished." + "\r\n");

                    } catch (IOException | SAXException | ParserConfigurationException ex) {
                        Logger.getLogger(MainFrame.class
                                .getName()).log(Level.SEVERE, null, ex);
                        JOptionPane.showMessageDialog(null, "Nmap not found on your system, please check your preferences.", "Exploit Pack says:", JOptionPane.ERROR_MESSAGE);

                    } catch (UnsupportedAudioFileException | LineUnavailableException ex) {
                        Logger.getLogger(MainFrame.class
                                .getName()).log(Level.SEVERE, null, ex);
                    }
                }
            };
            scannerThread.start();

        } catch (FileNotFoundException ex) {
            Logger.getLogger(NetworkMapper.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(NetworkMapper.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fstream.close();
            } catch (IOException ex) {
                Logger.getLogger(NetworkMapper.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//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(NetworkMapper.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NetworkMapper.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NetworkMapper.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NetworkMapper.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

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

    // 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 jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTextArea jTextAreaLog;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextFieldRatName;
    private javax.swing.JTextField jTextFieldTargetH;
    // End of variables declaration//GEN-END:variables
}
