MonitorSaurausRex.MainMenu.java Source code

Java tutorial

Introduction

Here is the source code for MonitorSaurausRex.MainMenu.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package MonitorSaurausRex;

import java.awt.Toolkit;
import java.awt.event.*;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author Shirley Atkinson
 */
public class MainMenu extends javax.swing.JFrame {

    public File[] listOfFilesAndFolders;
    private String encryptOrDecrypt = "decrypt";
    public int ChangeCounter;
    public boolean checkPause = false;
    public boolean loopCheck = true;
    String user = System.getProperty("user.name");

    private boolean anyEncFileExists(File[] listOfFilesAndFolders) {
        for (File file : listOfFilesAndFolders) {
            String filePath = file.getAbsoluteFile().toString();
            if (!file.isDirectory()
                    && filePath.substring(filePath.length() - 4, filePath.length()).equals(".enc")) {
                System.out.println(file.getAbsoluteFile() + " is already encrypted");
                Toolkit.getDefaultToolkit().beep();
                JOptionPane.showMessageDialog(null,
                        "1 or more files are already encrypted !! \nPlease de-select them.");
                return true;
            }
        }
        return false;
    }

    private boolean allAreEncFiles(File[] listOfFilesAndFolders) {
        for (File file : listOfFilesAndFolders) {
            String filePath = file.getAbsoluteFile().toString();
            if (!file.isDirectory()
                    && !filePath.substring(filePath.length() - 4, filePath.length()).equals(".enc")) {
                System.out.println(file.getAbsoluteFile() + " is not encrypted");
                Toolkit.getDefaultToolkit().beep();
                JOptionPane.showMessageDialog(null,
                        "1 or more files are not encrypted !! \nPlease de-select them.");
                return false;
            }

        }
        return false;
    }

    /**
     *
     */

    /**
     * Creates new form NewJFrame
     */
    public MainMenu() {
        initComponents();
    }

    public void close() {

        WindowEvent winClosingEvent = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
        Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
    }

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

        imgStatus = new javax.swing.JLabel();
        QuarantineButton = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setAutoRequestFocus(false);
        setLocationByPlatform(true);
        setResizable(false);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        imgStatus.setIcon(
                new javax.swing.ImageIcon(getClass().getResource("/MonitorSaurausRex/Images/systemSafe.PNG"))); // NOI18N
        getContentPane().add(imgStatus, new org.netbeans.lib.awtextra.AbsoluteConstraints(710, 450, -1, -1));

        QuarantineButton.setIcon(new javax.swing.ImageIcon(
                getClass().getResource("/MonitorSaurausRex/Images/QuarantineButton.png"))); // NOI18N
        QuarantineButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                QuarantineButtonMouseClicked(evt);
            }
        });
        getContentPane().add(QuarantineButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 240, -1, -1));

        jLabel2.setIcon(new javax.swing.ImageIcon(
                getClass().getResource("/MonitorSaurausRex/Images/protectSystemButton.png"))); // NOI18N
        jLabel2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel2MouseClicked(evt);
            }
        });
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 170, -1, -1));

        jLabel3.setIcon(
                new javax.swing.ImageIcon(getClass().getResource("/MonitorSaurausRex/Images/AdminButton.png"))); // NOI18N
        jLabel3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel3MouseClicked(evt);
            }
        });
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 310, -1, -1));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setIcon(
                new javax.swing.ImageIcon(getClass().getResource("/MonitorSaurausRex/Images/HomeBackNew_1.png"))); // NOI18N
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 900, 510));

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

    private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel3MouseClicked
        this.dispose();
        AdminLogin A = new AdminLogin();
        A.setVisible(true);
    }//GEN-LAST:event_jLabel3MouseClicked

    private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel2MouseClicked

        this.dispose();
        MonitorDirectory();

    }//GEN-LAST:event_jLabel2MouseClicked

    private void QuarantineButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_QuarantineButtonMouseClicked
        try {
            SelfQuarantine();

        } catch (IOException ex) {
            Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_QuarantineButtonMouseClicked

    /**
     * @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(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        }
        //</editor-fold>
        //</editor-fold>

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

        /* Use an appropriate Look and Feel */
        try {
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            //UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        } catch (UnsupportedLookAndFeelException | IllegalAccessException | InstantiationException
                | ClassNotFoundException ex) {
        }
        /* Turn off metal's use of bold fonts */
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        //Schedule a job for the event-dispatching thread:
        //adding TrayIcon.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        //Check the SystemTray support
        if (!SystemTray.isSupported()) {
            System.out.println("SystemTray is not supported");
            return;
        }
        final PopupMenu popup = new PopupMenu();
        final TrayIcon trayIcon = new TrayIcon(createImage("Logo.png", "tray icon"));
        final SystemTray tray = SystemTray.getSystemTray();
        trayIcon.setImageAutoSize(true);
        // Create a popup menu components
        MenuItem aboutItem = new MenuItem("About");
        CheckboxMenuItem cb1 = new CheckboxMenuItem("Menu");
        CheckboxMenuItem cb2 = new CheckboxMenuItem("Quarantine!");
        Menu displayMenu = new Menu("Actions");
        MenuItem errorItem = new MenuItem("Cut Connections");
        MenuItem warningItem = new MenuItem("Send Reports");
        MenuItem infoItem = new MenuItem("Kill Processes");
        MenuItem exitItem = new MenuItem("Exit");

        //Add components to popup menu
        popup.add(aboutItem);
        popup.addSeparator();
        popup.add(cb1);
        popup.add(cb2);
        popup.addSeparator();
        popup.add(displayMenu);
        displayMenu.add(errorItem);
        displayMenu.add(warningItem);
        displayMenu.add(infoItem);
        popup.add(exitItem);

        trayIcon.setPopupMenu(popup);

        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
            return;
        }

        trayIcon.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "This dialog box is run from System Tray");
            }
        });

        aboutItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null,
                        "MonitorSaurausRex, Designed for sec203 group project. The program was designed to be piece of software to combat Ransomware"
                                + " in a corparate enviroment. The Project was created by Luke Barlow, Dayan Patel, Rob Shire and Sian Skiggs.");
            }
        });

        cb1.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                int cb1Id = e.getStateChange();
                trayIcon.setImageAutoSize(true);
                if (cb1Id == ItemEvent.SELECTED) {
                    trayIcon.setImageAutoSize(true);
                } else {
                    trayIcon.setImageAutoSize(true);
                }
            }
        });

        cb2.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                int cb2Id = e.getStateChange();
                if (cb2Id == ItemEvent.SELECTED) {
                    trayIcon.setToolTip("Sun TrayIcon");
                } else {
                    trayIcon.setToolTip(null);
                }
            }
        });

        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                MenuItem item = (MenuItem) e.getSource();
                //TrayIcon.MessageType type = null;
                System.out.println(item.getLabel());
                if ("Error".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.ERROR;
                    trayIcon.displayMessage("Sun TrayIcon Demo", "This is an error message",
                            TrayIcon.MessageType.ERROR);

                } else if ("Warning".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.WARNING;
                    trayIcon.displayMessage("Sun TrayIcon Demo", "This is a warning message",
                            TrayIcon.MessageType.WARNING);

                } else if ("Info".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.INFO;
                    trayIcon.displayMessage("Sun TrayIcon Demo", "This is an info message",
                            TrayIcon.MessageType.INFO);

                } else if ("None".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.NONE;
                    trayIcon.displayMessage("Sun TrayIcon Demo", "This is an ordinary message",
                            TrayIcon.MessageType.NONE);
                }
            }
        };

        errorItem.addActionListener(listener);
        warningItem.addActionListener(listener);
        infoItem.addActionListener(listener);

        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                tray.remove(trayIcon);
                System.exit(0);
            }
        });
    }

    //Obtain the image URL
    protected static Image createImage(String path, String description) {
        URL imageURL = MainMenu.class.getResource(path);

        if (imageURL == null) {
            System.err.println("Resource not found: " + path);
            return null;
        } else {
            return (new ImageIcon(imageURL, description)).getImage();
        }
    }

    private boolean test;
    private TimerTask testTimer = null;

    public boolean MonitorDirectory() {

        Path directory = Paths.get("C:/Users/" + user + "/Documents/");
        try {
            WatchService fileSystemWatchService = FileSystems.getDefault().newWatchService();
            WatchKey watchKey = directory.register(fileSystemWatchService, StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);

            testTimer = new TimerTask() {

                @Override
                public void run() {
                    checkPause = true;
                    test = changeCheck();

                    if (test) {
                        testTimer.cancel();
                        System.out.println("Quaritnen sucsessfully activates");
                    }
                }

            };

            Timer timer = new Timer();
            timer.schedule(testTimer, 0, 1000);
            while (true) {
                WatchKey watchKeyActual = fileSystemWatchService.take();
                for (WatchEvent<?> event : watchKeyActual.pollEvents()) {

                    WatchEvent.Kind<?> eventKind = event.kind();

                    if (eventKind == StandardWatchEventKinds.OVERFLOW) {
                        continue;
                    }

                    WatchEvent<Path> eventPath = (WatchEvent<Path>) event;
                    Path fileName = eventPath.context();

                    //timerCheck(); ????? 
                    //http://stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java
                    //  boolean test = false;
                    if (checkPause == false) {
                        checkPause = true;
                    } else {
                        ChangeCounter++;
                        System.out.println("Event " + eventKind + " occurred on " + fileName);
                    }
                    if (test)
                        break;
                }
                boolean isReset = watchKeyActual.reset();
                if (!isReset || test) {
                    break;
                }
            }

        } catch (IOException | InterruptedException ioe) {
        }

        return true; /// EXIT METHOD
    }

    //to cancel run purge();
    public boolean changeCheck() {
        if (ChangeCounter > 5) {

            // https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html
            //Quarantine();
            return true;
        } else {
            ChangeCounter = 0;

            return (false);
        }

    }

    public void Quarantine() throws IOException {
        //contactAdmin();
        cutConnections();
        //killProcess();
        imgStatus.setIcon(
                new javax.swing.ImageIcon(getClass().getResource("/MonitorSaurausRex/Images/systemAlert.PNG"))); // NOI18N

    }

    public void SelfQuarantine() throws IOException, UnknownHostException, SQLException {
        //ScontactAdmin();
        //cutConnections();
        Encrypt("decrypt");
        //killProcess();
        imgStatus.setIcon(
                new javax.swing.ImageIcon(getClass().getResource("/MonitorSaurausRex/Images/systemAlert.PNG"))); // NOI18N

    }

    public void Encrypt(String input) {
        encryptOrDecrypt = input;
        if (encryptOrDecrypt.equals("encrypt")) {

            File theDir = new File("C:\\Users\\" + user + "\\Desktop\\MonSafe");

            // if the directory does not exist, create it
            if (!theDir.exists()) {
                boolean result = false;

                try {
                    theDir.mkdir();
                    result = true;
                } catch (SecurityException se) {
                    //handle it
                }
                if (result) {
                }
            }

            File source = new File("C:\\Users\\" + user + "\\Documents\\");
            File dest = new File("C:\\Users\\" + user + "\\Desktop\\MonSafe");
            try {
                FileUtils.copyDirectory(source, dest);
            } catch (IOException e) {
            }

            File dir = new File("C:\\Users\\" + user + "\\Desktop\\MonSafe");
            File[] newFilesAndFolders = this.listOfFilesAndFolders = dir.listFiles();

            int newLength = newFilesAndFolders.length + this.listOfFilesAndFolders.length;

            File[] combinedFileArray = new File[newLength];

            int i;

            for (i = 0; i < this.listOfFilesAndFolders.length; i++) {
                combinedFileArray[i] = this.listOfFilesAndFolders[i];
            }
            for (int j = 0; j < newFilesAndFolders.length; j++) {
                combinedFileArray[i++] = newFilesAndFolders[j];
            }

            this.listOfFilesAndFolders = combinedFileArray;

            if (encryptOrDecrypt.equalsIgnoreCase("encrypt") && !anyEncFileExists(listOfFilesAndFolders)) {
                new EncryptorAndDecryptor(listOfFilesAndFolders, "encrypt", new String("admin")).execute();

                dispose();
            }
        } else {
            File dir = new File("C:\\Users\\" + user + "\\Desktop\\MonSafe");
            File[] newFilesAndFolders = this.listOfFilesAndFolders = dir.listFiles();

            int newLength = newFilesAndFolders.length + this.listOfFilesAndFolders.length;

            File[] combinedFileArray = new File[newLength];

            int i;

            for (i = 0; i < this.listOfFilesAndFolders.length; i++) {
                combinedFileArray[i] = this.listOfFilesAndFolders[i];
            }
            for (int j = 0; j < newFilesAndFolders.length; j++) {
                combinedFileArray[i++] = newFilesAndFolders[j];
            }

            this.listOfFilesAndFolders = combinedFileArray;
            new EncryptorAndDecryptor(listOfFilesAndFolders, "decrypt", new String("admin")).execute();
            dispose();

        }
    }

    public void Decrypt() {
        if (encryptOrDecrypt == "decrypt") {

            File theDir = new File("C:\\Users\\" + user + "\\Desktop\\MonSafe");

            // if the directory does not exist, create it
            if (!theDir.exists()) {
                boolean result = false;

                try {
                    theDir.mkdir();
                    result = true;
                } catch (SecurityException se) {
                    //handle it
                }
                if (result) {
                    System.out.println("DIR created");
                }
            }

            File source = new File("C:\\Users\\" + user + "\\Desktop");
            File dest = new File("C:\\Users\\" + user + "\\Desktop\\MonSafe");
            try {
                FileUtils.copyDirectory(source, dest);
            } catch (IOException e) {
            }

            File dir = new File("C:\\Users\\" + user + "\\Desktop\\MonSafe");
            File[] newFilesAndFolders = this.listOfFilesAndFolders = dir.listFiles();

            int newLength = newFilesAndFolders.length + this.listOfFilesAndFolders.length;

            File[] combinedFileArray = new File[newLength];

            int i;

            for (i = 0; i < this.listOfFilesAndFolders.length; i++) {
                combinedFileArray[i] = this.listOfFilesAndFolders[i];
            }
            for (int j = 0; j < newFilesAndFolders.length; j++) {
                combinedFileArray[i++] = newFilesAndFolders[j];
            }

            this.listOfFilesAndFolders = combinedFileArray;

            if (encryptOrDecrypt.equalsIgnoreCase("encrypt") && !anyEncFileExists(listOfFilesAndFolders)) {
                new EncryptorAndDecryptor(listOfFilesAndFolders, "encrypt", new String("admin")).execute();

                dispose();
            }
        } else {
            File dir = new File("C:\\Users\\" + user + "\\Desktop\\MonSafe");
            File[] newFilesAndFolders = this.listOfFilesAndFolders = dir.listFiles();

            int newLength = newFilesAndFolders.length + this.listOfFilesAndFolders.length;

            File[] combinedFileArray = new File[newLength];

            int i;

            for (i = 0; i < this.listOfFilesAndFolders.length; i++) {
                combinedFileArray[i] = this.listOfFilesAndFolders[i];
            }
            for (int j = 0; j < newFilesAndFolders.length; j++) {
                combinedFileArray[i++] = newFilesAndFolders[j];
            }

            this.listOfFilesAndFolders = combinedFileArray;
            new EncryptorAndDecryptor(listOfFilesAndFolders, "decrypt", new String("admin")).execute();
            dispose();

        }
    }

    //ADD INSERT argument depending on quarantine type
    public void ScontactAdmin() throws UnknownHostException, SQLException {
        String TempUser = System.getProperty("user.name");
        String TempIP = Inet4Address.getLocalHost().getHostAddress();
        //DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        //Date date = new Date();
        //String timeStamp = (dateFormat.format(date));
        String timeStamp = "TEST";
        String tempTrig = "SelfTriggered";

        // String query = "INSERT INTO `records`(`User`, `IP Address`, `Triggered`, `System Time`) VALUES ([TempUser],[TempIP],[SelfTriggered],[timeStamp])";
        String query = "INSERT INTO `record`(`User`, `IP Address`, `Triggered`, `System Time`) VALUES ('" + TempUser
                + "','" + TempIP + "'," + tempTrig + "','" + timeStamp + "')";
        executeSQlQuery(query, "Inserted");
    }

    public Connection getConnection() throws SQLException {
        Connection con;
        con = DriverManager.getConnection("jdbc:mysql://localhost/monrex", "root", "");
        return con;
    }

    public void executeSQlQuery(String query, String message) throws SQLException {
        Connection con = getConnection();
        Statement st;
        try {
            st = con.createStatement();
            if ((st.executeUpdate(query)) == 1) {
                JOptionPane.showMessageDialog(null, "Data " + message + " Succefully");
            } else {
                JOptionPane.showMessageDialog(null, "Data Not " + message);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void contactAdmin() {
    }

    public static void cutConnections() throws IOException {
        Runtime.getRuntime().exec("ipconfig /release");
        //RUNASADMIN//Runtime.getRuntime().exec("netsh interface set interface name=\"Ethernet\" admin=disabled");
    }

    public static void killProcess() {
        //PROCESSKILLCODE
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel QuarantineButton;
    private javax.swing.JLabel imgStatus;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    // End of variables declaration//GEN-END:variables

}