Understanding and Fixing the Error
Error Message:
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 26: character maps to <undefined>
Cause:
This error occurs because Python is trying to read the dorks.txt file using the default encoding (cp1252 on Windows), but the file contains characters that aren't supported by this encoding.
Solution:
Specify the correct encoding (utf-8 is commonly used) when opening the file. Modify the line where you open dorks.txt as follows:
dorks = open('dorks.txt', 'r', encoding='utf-8')
This should resolve the UnicodeDecodeError.
Creating a GUI with PyQt6
To create a user-friendly GUI for your script using PyQt6 with a dark theme, white text, customizable options, and a real-time feedback text box, follow the steps below.
1. Install Required Packages
Ensure you have the necessary packages installed:
pip install PyQt6 requests beautifulsoup4 selenium sty
Note: You might also need to install the appropriate WebDriver for Selenium (e.g., ChromeDriver) and ensure it's in your system's PATH.
2. PyQt6 GUI Implementation
Below is a complete PyQt6 application that mirrors your original script's functionality. It includes:
- Input Field: To enter the target URL.
- Browse Button: To select the
dorks.txt file.
- Start Button: To initiate the vulnerability check.
- Options: Placeholder for additional configurable options.
- Feedback Text Box: Displays real-time logs and results.
import sys
import argparse
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common import keys
from selenium.webdriver.support.ui import Select
from PyQt6.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QLineEdit, QPushButton, QTextEdit, QFileDialog, QMessageBox, QCheckBox
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal
from sty import fg, bg, ef, rs
# Worker Thread for running the vulnerability check
class VulnerabilityChecker(QThread):
log_signal = pyqtSignal(str)
finished_signal = pyqtSignal()
def __init__(self, target, dorks_file, options_dict):
super().__init__()
self.target = target
self.dorks_file = dorks_file
self.options_dict = options_dict
def run(self):
try:
# Initialize WebDriver with options
options = Options()
options.add_experimental_option("prefs", {"profile.default_content_setting_values.notifications": 2})
if self.options_dict.get('headless'):
options.add_argument("--headless")
browser = webdriver.Chrome(options=options)
query = 'https://www.google.com/search?ei=Rar6XdWJDe2g5OUPvs2MmAM&q='
# Open dorks file with specified encoding
try:
dorks = open(self.dorks_file, 'r', encoding='utf-8')
except UnicodeDecodeError:
self.log_signal.emit(f"{fg.red}Failed to decode {self.dorks_file}. Please ensure it's encoded in UTF-8.{rs.fg}")
browser.quit()
self.finished_signal.emit()
return
output = []
def check_vulnerability(browser, target, dork):
url = f'{query}{dork.strip()} site:{target}'
browser.get(url)
try:
# Search for reCaptcha
browser.find_element("id", 'captcha-form')
self.log_signal.emit(f"{fg.yellow}Google is trying to block you... solve captcha and wait.{rs.fg}")
QMessageBox.warning(None, "Captcha Detected", "Google is trying to block you with a captcha. Please solve it manually and then press OK to continue.")
except:
try:
browser.find_element("id", 'result-stats')
self.log_signal.emit(f"{bg.red}{fg.white} [ *** VULNERABILITY DETECTED! *** ] - {dork} site:{target} {rs.fg}{rs.bg}")
output.append(f'{dork} site:{target}')
except:
self.log_signal.emit(f"{fg.gray}Dork failed - {dork} site:{target}{rs.fg}")
for dork in dorks:
self.log_signal.emit(f"{fg.blue}Checking dork: {dork.strip()}{rs.fg}")
check_vulnerability(browser, self.target, dork)
browser.quit()
# Save output to a file
if output:
with open('vulnerable_sites.txt', 'w', encoding='utf-8') as f_out:
for line in output:
f_out.write(line + '\n')
self.log_signal.emit(f"{fg.green}Vulnerable sites have been saved to vulnerable_sites.txt{rs.fg}")
else:
self.log_signal.emit(f"{fg.yellow}No vulnerabilities detected.{rs.fg}")
except Exception as e:
self.log_signal.emit(f"{fg.red}An error occurred: {str(e)}{rs.fg}")
finally:
self.finished_signal.emit()
# Main Application Window
class App(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("GDAT - Google Dorking Assessment Tool")
self.setGeometry(100, 100, 800, 600)
self.setStyleSheet("background-color: #2b2b2b; color: white;")
self.initUI()
def initUI(self):
layout = QVBoxLayout()
# Target URL Input
h_target = QHBoxLayout()
lbl_target = QLabel("Target Domain:")
lbl_target.setStyleSheet("color: white;")
self.input_target = QLineEdit()
self.input_target.setPlaceholderText("Enter target domain (e.g., example.com)")
self.input_target.setStyleSheet("background-color: #3c3f41; color: white;")
h_target.addWidget(lbl_target)
h_target.addWidget(self.input_target)
layout.addLayout(h_target)
# Dorks File Selection
h_dorks = QHBoxLayout()
lbl_dorks = QLabel("Dorks File:")
lbl_dorks.setStyleSheet("color: white;")
self.input_dorks = QLineEdit()
self.input_dorks.setPlaceholderText("Select dorks.txt file")
self.input_dorks.setStyleSheet("background-color: #3c3f41; color: white;")
btn_browse = QPushButton("Browse")
btn_browse.setStyleSheet("background-color: #555555; color: white;")
btn_browse.clicked.connect(self.browse_file)
h_dorks.addWidget(lbl_dorks)
h_dorks.addWidget(self.input_dorks)
h_dorks.addWidget(btn_browse)
layout.addLayout(h_dorks)
# Options
h_options = QHBoxLayout()
self.checkbox_headless = QCheckBox("Headless Mode")
self.checkbox_headless.setStyleSheet("color: white;")
h_options.addWidget(self.checkbox_headless)
# Add more options here if needed
layout.addLayout(h_options)
# Start Button
btn_start = QPushButton("Start Check")
btn_start.setStyleSheet("background-color: #007acc; color: white;")
btn_start.clicked.connect(self.start_check)
layout.addWidget(btn_start)
# Feedback Text Box
lbl_feedback = QLabel("Feedback:")
lbl_feedback.setStyleSheet("color: white;")
self.text_feedback = QTextEdit()
self.text_feedback.setReadOnly(True)
self.text_feedback.setStyleSheet("background-color: #1e1e1e; color: white;")
layout.addWidget(lbl_feedback)
layout.addWidget(self.text_feedback)
self.setLayout(layout)
def browse_file(self):
file_path, _ = QFileDialog.getOpenFileName(self, "Select Dorks File", "", "Text Files (*.txt)")
if file_path:
self.input_dorks.setText(file_path)
def start_check(self):
target = self.input_target.text().strip()
dorks_file = self.input_dorks.text().strip()
if not target:
QMessageBox.warning(self, "Input Error", "Please enter a target domain.")
return
if not dorks_file:
QMessageBox.warning(self, "Input Error", "Please select a dorks.txt file.")
return
options = {
'headless': self.checkbox_headless.isChecked()
}
# Disable the start button to prevent multiple clicks
self.findChild(QPushButton, "Start Check").setEnabled(False)
# Clear previous feedback
self.text_feedback.clear()
# Start the worker thread
self.worker = VulnerabilityChecker(target, dorks_file, options)
self.worker.log_signal.connect(self.update_feedback)
self.worker.finished_signal.connect(self.check_finished)
self.worker.start()
def update_feedback(self, message):
# Format the message with HTML for colors
# Example message: "{fg.red}Error Message{rs.fg}"
formatted_message = self.parse_style(message)
self.text_feedback.append(formatted_message)
self.text_feedback.verticalScrollBar().setValue(self.text_feedback.verticalScrollBar().maximum())
def check_finished(self):
self.findChild(QPushButton, "Start Check").setEnabled(True)
self.text_feedback.append("<br><b>Check Completed.</b>")
def parse_style(self, message):
# Simple parser for sty library formatting to HTML
# This can be expanded for more comprehensive styling
import re
# Define regex patterns for sty color codes
patterns = {
fg.red: '<span style="color:red;">',
fg.green: '<span style="color:green;">',
fg.yellow: '<span style="color:gold;">',
fg.blue: '<span style="color:blue;">',
fg.gray: '<span style="color:gray;">',
bg.red: '<span style="background-color:red;">',
bg.bg: '<span style="background-color:black;">', # Example
rs.fg: '</span>',
rs.bg: '</span>',
}
# Replace sty codes with HTML tags
for code, tag in patterns.items():
message = message.replace(str(code), tag)
return message
# Run the application
def main():
app = QApplication(sys.argv)
# Set dark theme
app.setStyle("Fusion")
dark_palette = app.palette()
dark_palette.setColor(app.palette().Window, Qt.GlobalColor.black)
dark_palette.setColor(app.palette().WindowText, Qt.GlobalColor.white)
dark_palette.setColor(app.palette().Base, Qt.GlobalColor.black)
dark_palette.setColor(app.palette().AlternateBase, Qt.GlobalColor.darkGray)
dark_palette.setColor(app.palette().ToolTipBase, Qt.GlobalColor.white)
dark_palette.setColor(app.palette().ToolTipText, Qt.GlobalColor.white)
dark_palette.setColor(app.palette().Text, Qt.GlobalColor.white)
dark_palette.setColor(app.palette().Button, Qt.GlobalColor.black)
dark_palette.setColor(app.palette().ButtonText, Qt.GlobalColor.white)
dark_palette.setColor(app.palette().BrightText, Qt.GlobalColor.red)
app.setPalette(dark_palette)
window = App()
window.show()
sys.exit(app.exec())
if __name__ == '__main__':
main()
3. Explanation of the GUI Components
4. Enhancements and Options
-
Headless Mode:
- The checkbox allows users to run the Selenium browser in headless mode, which means the browser window won't appear during execution. This is useful for running scans without distractions.
-
Real-Time Feedback:
- The feedback text box updates in real-time with color-coded messages indicating the status of each dork check, successes, failures, and errors.
-
Error Handling:
- Provides user-friendly error messages and prompts, such as when a captcha is detected or when input fields are missing.
5. Running the Application
-
Ensure Dependencies Are Installed:
- Install PyQt6 and other required packages as mentioned earlier.
- Download and place the appropriate WebDriver (e.g.,
chromedriver.exe for Chrome) in your system's PATH or specify its path in the script.
-
Prepare dorks.txt:
- Ensure your
dorks.txt file is encoded in utf-8 to avoid decoding errors.
-
Execute the Script:
-
Using the GUI:
- Enter the target domain.
- Browse and select the
dorks.txt file.
- Choose any desired options (e.g., Headless Mode).
- Click "Start Check" to begin the vulnerability assessment.
- Monitor the real-time feedback in the text box.
Additional Recommendations
-
WebDriver Management:
-
Enhance Error Handling:
- Implement more granular exception handling to capture and log specific errors.
- Validate user inputs more thoroughly.
-
Extend GUI Features:
- Add progress indicators (e.g., a progress bar) to show scan progress.
- Allow users to configure more options, such as the number of threads or timeout settings.
-
Security Considerations:
- Ensure that the tool is used ethically and legally. Unauthorized scanning of websites can be illegal and unethical.
By following the above steps and utilizing the provided PyQt6 implementation, you can transform your command-line script into a user-friendly GUI application with enhanced functionality and better error handling.