# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'tampilan.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QProcess
from PyQt5.QtWidgets import QMessageBox
import shutil
import csv

from web_crawling.mainCrawl import *
from A1.mainInject import *
from A2.mainBrokAuth import *
from A2.packet_sniffer import *
from A4.mainIDOR import *
from A5.mainSecMisconf import *


class Ui_MainWindow(object):

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(760, 600)
        MainWindow.setAutoFillBackground(False)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(20, 90, 661, 19))
        self.label.setObjectName("label")

        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(20, 30, 571, 19))
        self.label_2.setObjectName("label_2")

        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(20, 150, 571, 19))
        self.label_3.setObjectName("label_3")

        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(20, 110, 721, 27))
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit.textChanged.connect(self.ableButton_1)

        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(20, 50, 721, 27))
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_2.textChanged.connect(self.ableButton_1)

        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setEnabled(True)
        self.lineEdit_3.setGeometry(QtCore.QRect(20, 170, 611, 27))
        self.lineEdit_3.setFrame(True)
        self.lineEdit_3.setReadOnly(False)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.lineEdit_3.setPlaceholderText(os.getcwd())

        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(20, 300, 721, 211))
        self.textEdit.setObjectName("textEdit")

        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(20, 220, 88, 27))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.setDisabled(True)
        self.pushButton.clicked.connect(self.attack_clk)

        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(120, 220, 88, 27))
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.setDisabled(True)
        self.pushButton_2.clicked.connect(self.open_file_log)

        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(220, 220, 88, 27))
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_3.setDisabled(True)
        self.pushButton_3.clicked.connect(self.cancel_clk)

        self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_4.setGeometry(QtCore.QRect(640, 170, 101, 27))
        self.pushButton_4.setObjectName("pushButton_4")
        self.pushButton_4.clicked.connect(self.dest_clk)

        self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
        self.progressBar.setEnabled(True)
        self.progressBar.setGeometry(QtCore.QRect(20, 260, 721, 23))
        self.progressBar.setAutoFillBackground(False)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setTextVisible(False)
        self.progressBar.setObjectName("progressBar")

        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Assessment Tools Web Apps Testing Aplication"))
        self.label.setText(_translate("MainWindow", "Input URL / Ip address target : "))
        self.pushButton.setText(_translate("MainWindow", "Attack"))
        self.pushButton_2.setText(_translate("MainWindow", "Log"))
        self.pushButton_3.setText(_translate("MainWindow", "Cancel"))
        self.label_2.setText(_translate("MainWindow", "Enter your project name :"))
        self.pushButton_4.setText(_translate("MainWindow", "Select folder"))
        self.label_3.setText(_translate("MainWindow", "Folder destination to save your project : (OPTIONAL)"))

    def attack_clk(self):
        self.textEdit.clear()
        if self.cek_requirement():
            for cek in self.cek_requirement():
                self.textEdit.append(cek)
            return
        self.alamatURL = self.lineEdit.text()
        prName = self.lineEdit_2.text()

        if not self.lineEdit_3.text():
            self.dirFolder = os.getcwd() + "/" + prName
        else:
            self.dirFolder = self.lineEdit_3.text() + "/" + prName

        cek = cek_webserver_link(self.alamatURL)
        if cek:
            if cek != self.alamatURL:
                self.textEdit.append("[+]url redirected to : " + str(cek))
                self.alamatURL = cek
            if os.path.exists(self.dirFolder) is True:
                reply = self.messageBoxYesNo("Warning", "The project you want to save already exists. Do you want to delete it ?")
                if reply is True:
                    self.textEdit.append("Delete Existing Folder")
                    shutil.rmtree(self.dirFolder)
                    if os.path.exists(self.dirFolder) is True:
                        self.showMessageBox("Warning", "can not delete the folder. please cek your folder or file")
                    else:
                        self.make_thread_atk()
                elif reply is False:
                    self.make_thread_atk()
            elif os.path.exists(self.dirFolder) is False:
                self.make_thread_atk()
        else:
            self.showMessageBox("Warning", "Web server is Down or Not Found")

    def cancel_clk(self):
        self.textEdit.append("program try to cancel process, please wait")
        self.attack.cancel_progress()
        self.pushButton_3.setDisabled(True)

    def progress_done(self):
        self.pushButton_3.setDisabled(True)
        self.pushButton.setDisabled(False)

    def make_log_file(self, dir):
        full_dir = dir + "/log.csv"
        if cek_file_exist(full_dir):
            os.remove(full_dir)
            if cek_file_exist(full_dir):
                return False

        header = ['No', 'Kategori', 'Tipe Serangan', 'URL', 'Tingkat Resiko']

        with open(full_dir, 'w') as csvFile:
            write = csv.writer(csvFile)
            write.writerow(header)
        csvFile.close()

    def make_thread_atk(self):
        create_project_dir(self.dirFolder)
        cek_log = self.make_log_file(self.dirFolder)
        if cek_log is False:
            self.showMessageBox("Warning", "log file not delete, please check folder or delete by manual")
            return None
        self.progressBar.setValue(0)
        self.pushButton_2.setDisabled(False)
        self.pushButton_3.setDisabled(False)
        self.pushButton.setDisabled(True)

        self.attack = Attack()
        self.attack.update_progress.connect(self.inc_pogres_bar)
        self.attack.update_output.connect(self.text_edit_update)
        self.attack.progress_done.connect(self.progress_done)
        self.p = threading.Thread(target=self.attack.boot, args=(self.alamatURL, self.dirFolder))
        self.p.daemon = True
        self.p.start()


    def dest_clk(self):
        self.folderPath = QtWidgets.QFileDialog.getExistingDirectory()
        self.lineEdit_3.setText(self.folderPath)

    def showMessageBox(self, title, message):
        mesBox = QtWidgets.QMessageBox()
        mesBox.setIcon(QtWidgets.QMessageBox.Warning)
        mesBox.setWindowTitle(title)
        mesBox.setText(message)
        mesBox.setStandardButtons(QtWidgets.QMessageBox.Ok)
        mesBox.exec_()

    def messageBoxYesNo(self, title, message):
        mesBox = QtWidgets.QMessageBox.question(QtWidgets.QMessageBox(), title, message, QMessageBox.Ok | QMessageBox.No, QtWidgets.QMessageBox.No)
        if mesBox == QtWidgets.QMessageBox.Ok:
            return True
        elif mesBox == QtWidgets.QMessageBox.No:
            return False
        mesBox.exec_()

    def ableButton_1(self):
        if len(self.lineEdit.text()) > 0 and len(self.lineEdit_2.text()) > 0:
            self.pushButton.setDisabled(False)
        else:
            self.pushButton.setDisabled(True)

    def open_file_log(self):
        file = self.dirFolder + "/log.csv"
        cek = cek_file_exist(file)
        if cek is True:
            subprocess.Popen(["xdg-open", file])
        else:
            self.showMessageBox("warning", "file Log not found")

    def inc_pogres_bar(self, x):
        self.progressBar.setValue((100 * (x / 5)))

    def text_edit_update(self, teks):
        self.textEdit.append(teks)

    def cek_requirement(self):
        cek = list()
        if not cek_file_exist("/opt/asetulweb/config.ini"):
            cek.append("not found config.ini in /opt/asetulweb/")
        else:
            config = ConfigParser()
            config.read('/opt/asetulweb/config.ini')
            db = str(config.get('settings', 'db'))
            if not cek_file_exist(db + "db/db_login.txt"):
                cek.append("not found db_login.txt")
            if not cek_file_exist(db + "db/db_outdated.txt"):
                cek.append("not found db_outdated.txt")
            if not cek_file_exist(db + "db/db_password.txt"):
                cek.append("not found db_password.txt")
            if not cek_file_exist(db + "db/db_trav_vuln.txt"):
                cek.append("not found db_trav_vuln.txt")
            if not cek_file_exist(db + "db/db_username.txt"):
                cek.append("not found db_username.txt")
            if not cek_file_exist(db + "db/db_travelsal.txt"):
                cek.append("not found db_travelsal.txt")
            if cek:
                cek.append("please cek db value in config.ini or permission")
        return cek


class Attack(QtCore.QObject):

    update_progress = QtCore.pyqtSignal(int)
    update_output = QtCore.pyqtSignal(str)
    progress_done = QtCore.pyqtSignal()
    angka = 0

    def boot(self, url, path):
        path_cvs = path + "/log.csv"
        self.run = True

        while self.run is True:
            dirFolder = path
            create_project_dir(dirFolder)
            self.update_progress.emit(1)

            self.update_output.emit("\n[+]Crawling")
            try:
                crawl = MainCrawl(url, dirFolder)
                self.update_output.emit("[+]Link has been crawled : " + crawl.return_output() + "\n")
            except:
                self.update_output.emit("[+]crawling stop or error in middle prossess")
                output = str(len(file_to_list(dirFolder + "/crawled.txt")))
                self.update_output.emit("[+]Link has been crawled : " + output +"\n")
            self.update_progress.emit(2)
            if self.run is False:
                break

            self.update_output.emit("\n[+]Injection Attack")
            inject = mainInject(url)
            for output in inject.return_output():
                self.update_output.emit("-" + output)
            with open(path_cvs, 'a') as csv_file:
                writer = csv.writer(csv_file)
                for output in inject.return_output_csv():
                    self.angka += 1
                    data = [self.angka, output[0], output[1], output[2], output[3]]
                    writer.writerow(data)
            csv_file.close()
            self.update_progress.emit(2)
            if self.run is False:
                break

            self.update_output.emit("\n[+]Broken Authentication Attack")
            A2 = MainBrokAuth(url, dirFolder)
            for output in A2.return_output():
                self.update_output.emit("-" + str(output))
            with open(path_cvs, 'a') as csv_file:
                writer = csv.writer(csv_file)
                for output in A2.return_output_csv():
                    self.angka += 1
                    data = [self.angka, "A2", output[0], output[1], "Severe"]
                    writer.writerow(data)
            csv_file.close()
            self.update_progress.emit(3)
            if self.run is False:
                break

            self.update_output.emit("\n[+]IDOR Attack")
            A4 = MainIdor(url, dirFolder)
            for output in A4.return_output():
                self.update_output.emit("-" + str(output))
            with open(path_cvs, 'a') as csv_file:
                writer = csv.writer(csv_file)
                for output in A4.return_output_csv():
                    self.angka += 1
                    data = [self.angka, "A4", output[0], output[1], "Moderate"]
                    writer.writerow(data)
            csv_file.close()
            self.update_progress.emit(4)
            if self.run is False:
                break

            self.update_output.emit("\n[+]Security Misconfiguration")
            A5 = mainSecMisconf(url, dirFolder)
            for output in A5.return_output():
                self.update_output.emit("-" + output)
            with open(path_cvs, 'a') as csv_file:
                writer = csv.writer(csv_file)
                for output in A5.return_output_cvs():
                    self.angka += 1
                    data = [self.angka, "A5", output[0], output[1], "Moderate"]
                    writer.writerow(data)
            csv_file.close()
            self.update_progress.emit(5)


            self.run = False
        self.update_output.emit("\nDone")
        self.progress_done.emit()

    def cancel_progress(self):
        self.run = False

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
