├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── img └── interface.png └── plugin.json /.gitignore: -------------------------------------------------------------------------------- 1 | tags 2 | 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | env/ 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *,cover 48 | .hypothesis/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | 58 | # Flask stuff: 59 | instance/ 60 | .webassets-cache 61 | 62 | # Scrapy stuff: 63 | .scrapy 64 | 65 | # Sphinx documentation 66 | docs/_build/ 67 | 68 | # PyBuilder 69 | target/ 70 | 71 | # IPython Notebook 72 | .ipynb_checkpoints 73 | 74 | # pyenv 75 | .python-version 76 | 77 | # celery beat schedule file 78 | celerybeat-schedule 79 | 80 | # dotenv 81 | .env 82 | 83 | # virtualenv 84 | venv/ 85 | ENV/ 86 | 87 | # Spyder project settings 88 | .spyderproject 89 | 90 | # Rope project settings 91 | .ropeproject 92 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | Copyright 2024 0x434b 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BinaryNinja Shellcoder Plugin 2 | 3 | ## Overview 4 | 5 | Shellcoder is a lightweight plugin for Binary Ninja that enhances shellcode development and analysis. 6 | It provides a versatile interface for assembling, disassembling, and formatting shellcode, supporting multiple architectures and output formats akin to the online ShellStorm Assembler/Disassembler. 7 | 8 | ## Features 9 | 10 | - **Multi-architecture Support**: Compatible with all architectures supported by Binary Ninja. 11 | - **Flexible Input Formats**: 12 | - Assembly instructions 13 | - Inline hex format (e.g., "\x90\x90") 14 | - Space-separated hex format (e.g., 90 90) 15 | - **Multiple Output Formats**: 16 | - Inline hex 17 | - Space-separated hex 18 | - Python byte string 19 | - C-style array 20 | - Disassembled mnemonics (for disassembling) 21 | - **Customizable Mnemonic Display**: 22 | - Optional address display 23 | - Optional bytecode display 24 | - Adjustable base address for relative operations 25 | - **Comment usage**: 26 | - You can annotate your assembly/shellcode with comments (`#`, `//`, or `;`) 27 | - **Bad Character Identification**: Quickly identify and highlight problematic bytes in your shellcode. 28 | - **No External Dependencies**: Utilizes only Binary Ninja's built-in functionalities, ensuring a lightweight and easily deployable solution. 29 | 30 | ## Installation 31 | 32 | 1. Clone this repository or download the source code. 33 | 2. Copy the plugin file to your Binary Ninja plugins folder: 34 | - Windows: `%APPDATA%\Binary Ninja\plugins\` 35 | - Linux: `~/.binaryninja/plugins/` 36 | - macOS: `~/Library/Application Support/Binary Ninja/plugins/` 37 | 3. Restart Binary Ninja or reload plugins. 38 | 39 | ## Usage 40 | 41 | 1. Open Binary Ninja and navigate to the "Plugins" menu. 42 | 2. Select "Shellcoder" to open the plugin interface. 43 | 3. Enter your assembly code or hex-formatted shellcode in the input area. 44 | 4. Choose your desired output format and options. 45 | 5. Click "Assemble" to process your input. 46 | 6. View the results in the output area. 47 | 48 | _Note_: Alternatively you can use `CTRL+p` to open the command palette and search for the plugin. 49 | 50 | ## Showcase 51 | 52 | ![interface](img/interface.png) 53 | 54 | ## Contributing 55 | 56 | Contributions to the plugin are more than welcome! Here's how you can contribute: 57 | 58 | 1. Fork the repository. 59 | 2. Create a new branch for your feature or bug fix. 60 | 3. Commit your changes with clear, descriptive commit messages. 61 | 4. Push your branch and submit a pull request. 62 | 63 | Please ensure your code adheres to the existing style and includes appropriate tests and documentation whenever necessary. 64 | 65 | ## License 66 | 67 | This project is licensed under the Apache 2.0 License - see the [LICENSE](LICENSE) file for details. 68 | 69 | ## Acknowledgments 70 | 71 | - The Binary Ninja team for their excellent reverse engineering platform. 72 | - The ShellStorm online assembler/disassembler for giving me the idea. 73 | 74 | ## Contact 75 | 76 | For bug reports, feature requests, or general inquiries, please open an issue on the GitHub repository. 77 | 78 | --- 79 | 80 | Happy shellcoding! 81 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | from binaryninja import Architecture, BinaryView 2 | from binaryninjaui import UIAction, UIActionHandler, Menu, UIContext 3 | from PySide6.QtWidgets import ( 4 | QApplication, 5 | QWidget, 6 | QVBoxLayout, 7 | QHBoxLayout, 8 | QTextEdit, 9 | QPushButton, 10 | QComboBox, 11 | QLabel, 12 | QLineEdit, 13 | QCheckBox, 14 | QMessageBox, 15 | ) 16 | from PySide6.QtGui import QColor, QTextCharFormat, QTextCursor, QFont 17 | from PySide6.QtCore import QTimer 18 | 19 | import re 20 | from typing import List, Dict 21 | 22 | # Constants 23 | COMMENT_CHARS = ["#", ";", "//"] 24 | 25 | 26 | class AssemblerError(Exception): 27 | pass 28 | 29 | 30 | class DisassemblerError(Exception): 31 | pass 32 | 33 | 34 | class Assembler: 35 | def __init__(self) -> None: 36 | self.arch: Architecture = None 37 | 38 | def set_architecture(self, arch_name: str) -> None: 39 | try: 40 | self.arch = Architecture[arch_name] 41 | except KeyError: 42 | raise AssemblerError(f"Unsupported architecture: {arch_name}") 43 | 44 | def assemble(self, input_text: str) -> List[Dict]: 45 | assembled_instructions = [] 46 | for line in input_text.split("\n"): 47 | line = line.strip() 48 | if line.startswith(tuple(COMMENT_CHARS)): 49 | assembled_instructions.append({"type": "comment", "content": line}) 50 | elif line: 51 | try: 52 | result = self.arch.assemble(line) 53 | assembled_instructions.append( 54 | { 55 | "type": "instruction", 56 | "asm": line, 57 | "bytes": result, 58 | } 59 | ) 60 | except Exception as e: 61 | raise AssemblerError( 62 | f"Could not assemble line: '{line}'. Error: {str(e)}" 63 | ) 64 | 65 | if not assembled_instructions: 66 | raise AssemblerError("No instructions were assembled") 67 | 68 | return assembled_instructions 69 | 70 | def disassemble(self, input_bytes: bytes) -> List[Dict]: 71 | disassembled_instructions = [] 72 | bv = BinaryView.new(data=input_bytes) 73 | bv.arch = self.arch 74 | bv.platform = self.arch.standalone_platform 75 | 76 | offset = 0 77 | while offset < len(input_bytes): 78 | disassembly = bv.get_disassembly(offset) 79 | if disassembly is None: 80 | break 81 | instruction_length = len(bv.read(offset, self.arch.max_instr_length)) 82 | disassembled_instructions.append( 83 | { 84 | "type": "instruction", 85 | "asm": disassembly, 86 | "bytes": input_bytes[offset : offset + instruction_length], 87 | } 88 | ) 89 | offset += instruction_length 90 | 91 | if not disassembled_instructions: 92 | raise DisassemblerError("No instructions were disassembled") 93 | 94 | return disassembled_instructions 95 | 96 | def format_output( 97 | self, 98 | assembled_instructions: List[Dict], 99 | output_format: str, 100 | total_bytes: int, 101 | mnemonic_options: Dict = {}, 102 | ) -> str: 103 | if total_bytes == 0: 104 | return "No instructions to assemble" 105 | 106 | if output_format == "Inline": 107 | return ( 108 | '"' 109 | + "".join( 110 | f"\\x{b:02x}" 111 | for instr in assembled_instructions 112 | if instr["type"] == "instruction" 113 | for b in instr["bytes"] 114 | ) 115 | + '"' 116 | ) 117 | 118 | elif output_format == "Hex": 119 | return " ".join( 120 | f"{b:02x}" 121 | for instr in assembled_instructions 122 | if instr["type"] == "instruction" 123 | for b in instr["bytes"] 124 | ) 125 | 126 | elif output_format == "Python": 127 | lines = [] 128 | for instr in assembled_instructions: 129 | if instr["type"] == "comment": 130 | lines.append( 131 | f" {instr['content'].replace('//', '#').replace(';', '#')}" 132 | ) 133 | else: 134 | lines.append(f' b"{instr["bytes"].hex()}", # {instr["asm"]}') 135 | return ( 136 | "shellcode = [\n" 137 | + "\n".join(lines) 138 | + f"\n]\n\n# Total length: {total_bytes} bytes\n" 139 | f"shellcode_length = {total_bytes}\n" 140 | f"raw_shellcode = b''.join(shellcode)" 141 | ) 142 | 143 | elif output_format == "C-Array": 144 | lines = [] 145 | for instr in assembled_instructions: 146 | if instr["type"] == "comment": 147 | lines.append( 148 | f" {instr['content'].replace('#', '//').replace(';', '//')}" 149 | ) 150 | else: 151 | hex_bytes = [f"0x{b:02x}" for b in instr["bytes"]] 152 | lines.append(f" {', '.join(hex_bytes)}, // {instr['asm']}") 153 | return ( 154 | "unsigned char shellcode[] = {{\n" 155 | + "\n".join(lines) 156 | + f"\n}};\n\n// Total length: {total_bytes} bytes\n" 157 | f"const size_t shellcode_length = {total_bytes};" 158 | ) 159 | 160 | elif output_format == "Mnemonics": 161 | lines = [] 162 | address = mnemonic_options.get("base_address", 0) if mnemonic_options else 0 163 | for instr in assembled_instructions: 164 | if instr["type"] == "comment": 165 | lines.append(instr["content"]) 166 | else: 167 | line_parts = [] 168 | if mnemonic_options.get("show_addresses", True): 169 | line_parts.append(f"{address:08x}:") 170 | if mnemonic_options.get("show_bytecodes", True): 171 | line_parts.append(f"{instr['bytes'].hex():<16}") 172 | if mnemonic_options.get("show_instructions", True): 173 | line_parts.append(instr["asm"]) 174 | lines.append(" ".join(line_parts)) 175 | address += len(instr["bytes"]) 176 | return "\n".join(lines) 177 | 178 | else: 179 | raise AssemblerError(f"Unsupported output format: {output_format}") 180 | 181 | def search_pattern( 182 | self, assembled_bytes: bytes, pattern: str, respect_boundaries: bool 183 | ) -> List[Dict]: 184 | if respect_boundaries: 185 | hex_string = " ".join(f"{b:02x}" for b in assembled_bytes) 186 | byte_pattern = " ".join( 187 | pattern[i : i + 2] for i in range(0, len(pattern), 2) 188 | ) 189 | matches = list(re.finditer(byte_pattern, hex_string)) 190 | return [ 191 | { 192 | "offset": match.start() // 3, 193 | "matched": match.group().replace(" ", ""), 194 | } 195 | for match in matches 196 | ] 197 | else: 198 | hex_string = assembled_bytes.hex() 199 | matches = list(re.finditer(pattern, hex_string)) 200 | return [ 201 | {"offset": match.start() // 2, "matched": match.group()} 202 | for match in matches 203 | ] 204 | 205 | def check_bad_patterns( 206 | self, 207 | assembled_bytes: bytes, 208 | bad_patterns: List[bytes], 209 | respect_instructions: bool, 210 | ) -> List[Dict]: 211 | found_bad_patterns = [] 212 | instruction_width = 4 # Default to 4 bytes, adjust based on architecture 213 | 214 | for pattern in bad_patterns: 215 | for i in range(len(assembled_bytes) - len(pattern) + 1): 216 | if respect_instructions: 217 | instruction_start = (i // instruction_width) * instruction_width 218 | if i + len(pattern) > instruction_start + instruction_width: 219 | continue 220 | if assembled_bytes[i : i + len(pattern)] == pattern: 221 | found_bad_patterns.append({"offset": i, "pattern": pattern.hex()}) 222 | 223 | return found_bad_patterns 224 | 225 | 226 | class AssemblerWidget(QWidget): 227 | def __init__(self, parent=None): 228 | super(AssemblerWidget, self).__init__(parent) 229 | 230 | # To get a binaryview we can use the UIContext of the currently opened file/db 231 | view = UIContext.activeContext().getCurrentView() 232 | # Get the actual BinaryView from the UI view 233 | self.bv = view.getData() if view else None 234 | # Now we can access the architecture 235 | self._current_arch = self.bv.arch if self.bv else None 236 | self.assembler = Assembler() 237 | self.initUI() 238 | 239 | def initUI(self) -> None: 240 | layout = QVBoxLayout() 241 | 242 | # Architecture selection 243 | arch_layout = QHBoxLayout() 244 | arch_label = QLabel("Architecture:") 245 | self.arch_combo = QComboBox() 246 | for arch in list(Architecture): 247 | self.arch_combo.addItem(arch.name) 248 | if self._current_arch: 249 | self.arch_combo.setCurrentText(self._current_arch.name) 250 | arch_layout.addWidget(arch_label) 251 | arch_layout.addWidget(self.arch_combo) 252 | layout.addLayout(arch_layout) 253 | 254 | # Output format selection 255 | format_layout = QHBoxLayout() 256 | format_label = QLabel("Output Format:") 257 | self.format_combo = QComboBox() 258 | self.format_combo.addItems(["Inline", "Hex", "Python", "C-Array", "Mnemonics"]) 259 | self.format_combo.currentIndexChanged.connect(self.update_output) 260 | format_layout.addWidget(format_label) 261 | format_layout.addWidget(self.format_combo) 262 | layout.addLayout(format_layout) 263 | 264 | # Mnemonic format options (initially hidden) 265 | self.mnemonic_options = QWidget() 266 | mnemonic_layout = QHBoxLayout() 267 | self.show_addresses = QCheckBox("Addresses") 268 | self.show_addresses.setToolTip( 269 | "Enable this option to display the address of each instruction" 270 | ) 271 | self.show_bytecodes = QCheckBox("Bytecodes") 272 | self.show_bytecodes.setToolTip( 273 | "Enable this option to display the raw bytes of each instruction" 274 | ) 275 | self.show_bytecodes.setChecked(True) 276 | self.show_instructions = QCheckBox("Instructions") 277 | self.show_instructions.setToolTip( 278 | "Enable this option to display the mnemonic of each instruction" 279 | ) 280 | self.show_instructions.setChecked(True) 281 | mnemonic_layout.addWidget(self.show_addresses) 282 | mnemonic_layout.addWidget(self.show_bytecodes) 283 | mnemonic_layout.addWidget(self.show_instructions) 284 | self.mnemonic_options.setLayout(mnemonic_layout) 285 | self.mnemonic_options.hide() 286 | layout.addWidget(self.mnemonic_options) 287 | 288 | # Base address input 289 | self.base_address_widget = QWidget() 290 | base_address_layout = QHBoxLayout() 291 | base_address_label = QLabel("Base Address:") 292 | self.base_address_input = QLineEdit() 293 | self.base_address_input.setText("0") 294 | base_address_layout.addWidget(base_address_label) 295 | base_address_layout.addWidget(self.base_address_input) 296 | self.base_address_widget.setLayout(base_address_layout) 297 | self.base_address_widget.hide() 298 | layout.addWidget(self.base_address_widget) 299 | 300 | # Assembly input 301 | self.asm_input = QTextEdit() 302 | input_label = QLabel("Input:") 303 | self.asm_input.setPlaceholderText( 304 | "Enter assembly instructions (one per line), or inline/hex formatted shellcode" 305 | ) 306 | layout.addWidget(input_label) 307 | layout.addWidget(self.asm_input) 308 | 309 | # Assemble button 310 | self.assemble_button = QPushButton("Run") 311 | self.assemble_button.clicked.connect(self.assemble) 312 | layout.addWidget(self.assemble_button) 313 | 314 | # Output display 315 | self.output = QTextEdit() 316 | output_label = QLabel("Output:") 317 | self.output.setReadOnly(True) 318 | self.output.setFont(QFont("Monospace")) 319 | layout.addWidget(output_label) 320 | layout.addWidget(self.output) 321 | 322 | # Copy button 323 | self.copy_button = QPushButton("Copy Output") 324 | self.copy_button.clicked.connect(self.copy_output) 325 | layout.addWidget(self.copy_button) 326 | 327 | # Search pattern 328 | search_layout = QHBoxLayout() 329 | search_label = QLabel("Search pattern:") 330 | self.search_input = QLineEdit() 331 | self.search_input.setPlaceholderText( 332 | "Enter a regex pattern (e.g., 00.. or 00(?!FF))" 333 | ) 334 | self.search_button = QPushButton("Search") 335 | self.search_button.clicked.connect(self.search_pattern) 336 | self.byte_boundary_checkbox = QCheckBox("Respect byte boundaries") 337 | self.byte_boundary_checkbox.setChecked(True) 338 | search_layout.addWidget(search_label) 339 | search_layout.addWidget(self.search_input) 340 | search_layout.addWidget(self.search_button) 341 | search_layout.addWidget(self.byte_boundary_checkbox) 342 | layout.addLayout(search_layout) 343 | 344 | # Bad characters input 345 | bad_chars_layout = QHBoxLayout() 346 | bad_chars_label = QLabel("Bad patterns:") 347 | self.bad_chars_input = QLineEdit() 348 | self.bad_chars_input.setPlaceholderText( 349 | "Enter bad patterns (e.g., 00 0a 0d fffe)" 350 | ) 351 | self.bad_chars_check = QPushButton("Check Bad Patterns") 352 | self.bad_chars_check.clicked.connect(self.check_bad_patterns) 353 | bad_chars_layout.addWidget(bad_chars_label) 354 | bad_chars_layout.addWidget(self.bad_chars_input) 355 | bad_chars_layout.addWidget(self.bad_chars_check) 356 | layout.addLayout(bad_chars_layout) 357 | 358 | # Instruction boundary checkbox for bad pattern search 359 | self.instruction_size_checkbox = QCheckBox("Respect instruction boundaries") 360 | layout.addWidget(self.instruction_size_checkbox) 361 | 362 | # Length display 363 | length_layout = QHBoxLayout() 364 | length_label = QLabel("Length:") 365 | self.length_value = QLabel("0 bytes") 366 | length_layout.addWidget(length_label) 367 | length_layout.addWidget(self.length_value) 368 | length_layout.addStretch() 369 | layout.addLayout(length_layout) 370 | 371 | # Search results display 372 | self.search_results = QTextEdit() 373 | self.search_results.setReadOnly(True) 374 | layout.addWidget(QLabel("Search Results:")) 375 | layout.addWidget(self.search_results) 376 | 377 | # Info display 378 | self.info_display = QLabel() 379 | self.info_display.setWordWrap(True) 380 | layout.addWidget(self.info_display) 381 | 382 | self.setLayout(layout) 383 | 384 | # Connect signals 385 | self.format_combo.currentIndexChanged.connect(self.toggle_mnemonic_options) 386 | self.show_addresses.stateChanged.connect(self.update_output) 387 | self.show_bytecodes.stateChanged.connect(self.update_output) 388 | self.show_instructions.stateChanged.connect(self.update_output) 389 | self.base_address_input.textChanged.connect(self.update_output) 390 | 391 | def toggle_mnemonic_options(self, index): 392 | if self.format_combo.itemText(index) == "Mnemonics": 393 | self.mnemonic_options.show() 394 | self.base_address_widget.show() 395 | else: 396 | self.mnemonic_options.hide() 397 | self.base_address_widget.hide() 398 | self.update_output() 399 | 400 | def update_output(self): 401 | self.assemble() 402 | self.clear_highlighting() 403 | 404 | def clear_highlighting(self): 405 | cursor = self.output.textCursor() 406 | cursor.beginEditBlock() 407 | cursor.select(QTextCursor.Document) 408 | cursor.setCharFormat(QTextCharFormat()) 409 | cursor.clearSelection() 410 | cursor.endEditBlock() 411 | self.output.setTextCursor(cursor) 412 | 413 | def copy_output(self): 414 | output_text = self.output.toPlainText() 415 | QApplication.clipboard().setText(output_text) 416 | 417 | # Visual feedback 418 | original_text = self.copy_button.text() 419 | self.copy_button.setText("Copied!") 420 | self.copy_button.setEnabled(False) 421 | 422 | # Reset button after 1.5 seconds 423 | QTimer.singleShot(1500, lambda: self.reset_copy_button(original_text)) 424 | 425 | self.info_display.setText("Output copied to clipboard") 426 | 427 | def reset_copy_button(self, original_text): 428 | self.copy_button.setText(original_text) 429 | self.copy_button.setEnabled(True) 430 | 431 | def assemble(self) -> None: 432 | current_info = self.info_display.text() 433 | arch_name = self.arch_combo.currentText() 434 | output_format = self.format_combo.currentText() 435 | 436 | try: 437 | self.assembler.set_architecture(arch_name) 438 | input_text = self.asm_input.toPlainText() 439 | 440 | # Determine if input is assembly or raw bytes 441 | if all( 442 | all(c in "0123456789ABCDEFabcdef \\x\"'" for c in line.strip()) 443 | for line in input_text.split("\n") 444 | if line.strip() and not line.strip().startswith(tuple(COMMENT_CHARS)) 445 | ): 446 | # Raw bytes input 447 | processed_input = bytearray() 448 | for line in input_text.split("\n"): 449 | line = line.strip() 450 | if line.startswith(tuple(COMMENT_CHARS)): 451 | continue 452 | if line: 453 | if line.startswith('"') and line.endswith('"'): 454 | processed_input.extend( 455 | bytes.fromhex(line.strip('"').replace("\\x", "")) 456 | ) 457 | else: 458 | processed_input.extend(bytes.fromhex(line.replace(" ", ""))) 459 | assembled_instructions = self.assembler.disassemble(processed_input) 460 | else: 461 | # Assembly input 462 | assembled_instructions = self.assembler.assemble(input_text) 463 | 464 | total_bytes = sum( 465 | len(instr["bytes"]) 466 | for instr in assembled_instructions 467 | if instr["type"] == "instruction" 468 | ) 469 | 470 | mnemonic_options = { 471 | "show_addresses": self.show_addresses.isChecked(), 472 | "show_bytecodes": self.show_bytecodes.isChecked(), 473 | "show_instructions": self.show_instructions.isChecked(), 474 | "base_address": int(self.base_address_input.text(), 16), 475 | } 476 | formatted_output = self.assembler.format_output( 477 | assembled_instructions, output_format, total_bytes, mnemonic_options 478 | ) 479 | 480 | self.output.setPlainText(formatted_output) 481 | self.clear_highlighting() 482 | self.length_value.setText(f"{total_bytes} bytes") 483 | 484 | except (AssemblerError, DisassemblerError) as e: 485 | self.show_error(str(e)) 486 | finally: 487 | self.info_display.setText(current_info) 488 | 489 | def search_pattern(self): 490 | pattern = self.search_input.text() 491 | respect_boundaries = self.byte_boundary_checkbox.isChecked() 492 | assembled_text = self.output.toPlainText() 493 | 494 | try: 495 | # Extract raw bytes 496 | assembled_bytes = self.get_raw_bytes(assembled_text) 497 | 498 | matches = self.assembler.search_pattern( 499 | assembled_bytes, pattern, respect_boundaries 500 | ) 501 | 502 | self.search_results.clear() 503 | if matches: 504 | for match in matches: 505 | self.search_results.append( 506 | f"Offset {match['offset']}: {match['matched']}" 507 | ) 508 | self.info_display.setText(f"Found {len(matches)} match(es).") 509 | else: 510 | self.search_results.append("No matches found.") 511 | self.info_display.setText("No matches found.") 512 | 513 | except re.error as e: 514 | self.show_error(f"Invalid regex pattern: {str(e)}") 515 | 516 | def check_bad_patterns(self): 517 | bad_patterns_input = self.bad_chars_input.text().strip() 518 | assembled_text = self.output.toPlainText() 519 | respect_instructions = self.instruction_size_checkbox.isChecked() 520 | 521 | try: 522 | bad_patterns = [ 523 | bytes.fromhex(pattern.replace(" ", "")) 524 | for pattern in bad_patterns_input.split() 525 | ] 526 | assembled_bytes = self.get_raw_bytes(assembled_text) 527 | 528 | found_bad_patterns = self.assembler.check_bad_patterns( 529 | assembled_bytes, bad_patterns, respect_instructions 530 | ) 531 | 532 | self.search_results.clear() 533 | if found_bad_patterns: 534 | self.search_results.append("Bad patterns found:") 535 | for result in found_bad_patterns: 536 | self.search_results.append( 537 | f"Offset {result['offset']}: {result['pattern']}" 538 | ) 539 | self.info_display.setText( 540 | f"Found {len(found_bad_patterns)} bad pattern(s)." 541 | ) 542 | else: 543 | self.search_results.append("No bad patterns found.") 544 | self.info_display.setText("No bad patterns found.") 545 | 546 | # Highlight bad patterns in the output 547 | self.highlight_bad_patterns(assembled_text, found_bad_patterns) 548 | 549 | except ValueError as e: 550 | self.show_error( 551 | f"Invalid input. Use hex format (e.g., 00 0a 0d d287). Error: {str(e)}" 552 | ) 553 | 554 | def get_raw_bytes(self, assembled_text: str) -> bytes: 555 | if "\\x" in assembled_text: # Inline format 556 | return bytes.fromhex(assembled_text.replace('"', "").replace("\\x", "")) 557 | elif "shellcode = [" in assembled_text: # Python format 558 | hex_values = re.findall(r'b"([0-9a-fA-F]+)"', assembled_text) 559 | return b"".join(bytes.fromhex(value) for value in hex_values) 560 | elif "0x" in assembled_text: # C-Array format 561 | hex_values = re.findall(r"0x([0-9a-fA-F]{2})", assembled_text) 562 | return bytes.fromhex("".join(hex_values)) 563 | else: # Hex format 564 | return bytes.fromhex(re.sub(r"\s", "", assembled_text)) 565 | 566 | def highlight_bad_patterns( 567 | self, assembled_text: str, found_bad_patterns: List[Dict] 568 | ): 569 | cursor = self.output.textCursor() 570 | cursor.beginEditBlock() 571 | 572 | highlight_format = QTextCharFormat() 573 | highlight_format.setBackground(QColor(255, 200, 200)) # Light red background 574 | highlight_format.setForeground(QColor(0, 0, 0)) # Black text 575 | start = 0 576 | length = 0 577 | 578 | for result in found_bad_patterns: 579 | offset, pattern = result["offset"], result["pattern"] 580 | pattern_length = len(bytes.fromhex(pattern)) 581 | 582 | if "\\x" in assembled_text: # Inline format 583 | start = assembled_text.index('"') + 1 + offset * 4 584 | length = pattern_length * 4 585 | elif "shellcode = [" in assembled_text: # Python format 586 | # Find the correct chunk and highlight within it 587 | cumulative_length = 0 588 | for match in re.finditer(r'b"([0-9a-fA-F]+)"', assembled_text): 589 | chunk_length = len(match.group(1)) // 2 590 | if cumulative_length <= offset < cumulative_length + chunk_length: 591 | relative_offset = offset - cumulative_length 592 | start = match.start() + 2 + relative_offset * 2 593 | length = min(pattern_length, chunk_length - relative_offset) * 2 594 | break 595 | cumulative_length += chunk_length 596 | elif "0x" in assembled_text: # C-Array format 597 | hex_positions = [ 598 | m.start() for m in re.finditer(r"0x[0-9a-fA-F]{2}", assembled_text) 599 | ] 600 | start = hex_positions[offset] 601 | length = pattern_length * 4 602 | else: # Hex format 603 | start = offset * 3 604 | length = pattern_length * 3 - 1 605 | 606 | if not start: 607 | self.show_error("Could not find the start position for highlighting") 608 | if not length: 609 | self.show_error("Could not find the length for highlighting") 610 | cursor.setPosition(start) 611 | cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, length) 612 | cursor.mergeCharFormat(highlight_format) 613 | 614 | cursor.endEditBlock() 615 | self.output.setTextCursor(cursor) 616 | 617 | def show_error(self, message: str): 618 | QMessageBox.critical(self, "Error", message) 619 | self.search_results.setPlainText(f"Error: {message}") 620 | 621 | 622 | assembler_widget = None 623 | 624 | 625 | def run_plugin(bv) -> None: 626 | global assembler_widget 627 | assembler_widget = AssemblerWidget() 628 | assembler_widget.show() 629 | 630 | 631 | UIAction.registerAction("Shellcoder\\Run") 632 | UIActionHandler.globalActions().bindAction("Shellcoder\\Run", UIAction(run_plugin)) 633 | Menu.mainMenu("Plugins").addAction("Shellcoder\\Run", "Shellcoder") 634 | -------------------------------------------------------------------------------- /img/interface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xricksanchez/Shellcoder/cf7045e8fc2e3c9d4b3ce08f814c9e91d6c9a8bd/img/interface.png -------------------------------------------------------------------------------- /plugin.json: -------------------------------------------------------------------------------- 1 | { 2 | "api": [ 3 | "python3" 4 | ], 5 | "author": "434b", 6 | "description": "Interactive shellcode disassembler/assembler", 7 | "license": { 8 | "name": "Apache 2.0", 9 | "text": "Copyright 2024 0x434b Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License." 10 | }, 11 | "longdescription": "", 12 | "minimumbinaryninjaversion": 4526, 13 | "name": "Shellcoder", 14 | "platforms": [ 15 | "Darwin", 16 | "Linux", 17 | "Windows" 18 | ], 19 | "pluginmetadataversion": 2, 20 | "type": [ 21 | "helper" 22 | ], 23 | "version": "1.0.2" 24 | } 25 | --------------------------------------------------------------------------------