├── .gitignore ├── LICENSE ├── Makefile ├── README.md └── src ├── Makefile ├── TODO ├── bstrings.c ├── include ├── bool.h └── version.h └── version.in /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Object files 5 | *.o 6 | *.ko 7 | *.obj 8 | *.elf 9 | 10 | # Linker output 11 | *.ilk 12 | *.map 13 | *.exp 14 | 15 | # Precompiled Headers 16 | *.gch 17 | *.pch 18 | 19 | # Libraries 20 | *.lib 21 | *.a 22 | *.la 23 | *.lo 24 | 25 | # Shared objects (inc. Windows DLLs) 26 | *.dll 27 | *.so 28 | *.so.* 29 | *.dylib 30 | 31 | # Executables 32 | *.exe 33 | *.out 34 | *.app 35 | *.i*86 36 | *.x86_64 37 | *.hex 38 | 39 | # Debug files 40 | *.dSYM/ 41 | *.su 42 | *.idb 43 | *.pdb 44 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PREFIX=/usr/local 2 | 3 | all: 4 | +$(MAKE) -C src/ 5 | 6 | install: 7 | install -m 0755 src/bstrings $(PREFIX)/bin 8 | 9 | clean: 10 | +${MAKE} -C src/ clean 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Binary String Toolkit 2 | ## Summary 3 | The Binary String Toolkit or BST for short is a rather simple utility to 4 | convert binary strings to various formats suitable for inclusions in source 5 | codes, such as those used to develop exploits and Proof of Concepts in the 6 | security field. 7 | 8 | ## Features 9 | * Convert and dump binary files to standard output in a binary string format. 10 | * Convert a plain hexadecimal input string to an hex escaped version. 11 | * Generate a sequence of bad characters for detecting bad chars in buffers. 12 | * Limit the width of binary strings for a better readability of your exploit codes. 13 | * Format binary strings in your favorite programming or scripting language's syntax, such as: 14 | * C/C++ 15 | * Python 16 | * PowerShell 17 | * Perform automatic variable block indentation ready for copy/paste inclusions. 18 | 19 | ## Dependencies 20 | * POSIX C Library 21 | * C Compiler 22 | * GCC 23 | * LLVM Clang 24 | * GNU Make 25 | * Git 26 | 27 | ## Building 28 | To build and install the 'bstrings' binary on your system, simply do: 29 | ``` 30 | $ git clone https://github.com/e3prom/bst 31 | $ cd bst 32 | $ make 33 | # by default, bstrings is installed in /usr/local/bin. 34 | $ sudo make install 35 | ``` 36 | 37 | ## Usage 38 | The below example show how an assembled shellcode can be quickly dumped (-D) 39 | to standard output in a hexadecimal escaped (-x) binary string of 16 hexadecimal 40 | digits width (or 8 bytes), with Python syntax formatting and an indentation level 41 | of 4 space characters: 42 | ``` 43 | $ bstrings --verbose -x -D lnx-execve-setreuid-x86_64 -w8 -i 4 --syntax=python 44 | [*] Convert hexadecimal input to an escaped binary string. 45 | [+] Binary string width is limited to 8 bytes. 46 | [+] Output binary string using python language syntax. 47 | [+] Indentation level set to 4 space character(s). 48 | shellcode = "" 49 | shellcode += "\x31\xc0\x48\x89\xc7\x48\x89\xc6" 50 | shellcode += "\x48\x89\xc2\xb0\x71\x0f\x05\x31" 51 | shellcode += "\xc0\x50\x48\xbb\x2f\x62\x69\x6e" 52 | shellcode += "\x2f\x2f\x73\x68\x53\x48\x89\xe7" 53 | shellcode += "\x50\x48\x89\xe6\x57\x48\x89\xe2" 54 | shellcode += "\xb0\x3b\x0f\x05" 55 | ``` 56 | 57 | You can also use bstrings to output an automatically indented bad character 58 | sequence, and thus in your favorite programming language: 59 | ``` 60 | $ bstrings --verbose -b -w12 -i 4 --syntax=c -n badchar 61 | [*] Generating bad character binary string. 62 | [+] Binary string width is limited to 12 bytes. 63 | unsigned char badchar[] = 64 | "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c" 65 | "\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18" 66 | "\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24" 67 | "\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30" 68 | "\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c" 69 | "\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48" 70 | "\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54" 71 | "\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60" 72 | "\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c" 73 | "\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78" 74 | "\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80\x81\x82\x83\x84" 75 | "\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90" 76 | "\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c" 77 | "\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8" 78 | "\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4" 79 | "\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0" 80 | "\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc" 81 | "\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8" 82 | "\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4" 83 | "\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0" 84 | "\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc" 85 | "\xfd\xfe\xff" 86 | ``` 87 | 88 | For a list of supported command-line options, simply execute bstrings with the ```--help``` switch: 89 | ``` 90 | $ bstrings --help 91 | Usage: bstrings [OPTION]... 92 | Convert input to specified binary string format. 93 | 94 | At least one of the below options must be given: 95 | -D, --dump-file=FILE Convert and Dump RAW content of file FILE 96 | -x, --hex-escape Escape input hexadecimal string 97 | -b, --gen-badchar Generate a bad character sequence string 98 | 99 | The below switches are optional: 100 | -f, --file=FILE Read hex input from file FILE instead of stdin 101 | -w, --width=BYTES Break binary strings to specified length in bytes 102 | -s, --syntax=LANG Output variable using syntax of LANG 103 | -i, --indent=LENGTH Perform indentation for given character length 104 | -n, --var-name=VAR Specify string variable name (verbose mode) 105 | -h, --help Display this help 106 | --interactive Enter interactive mode 107 | --verbose Enable verbose output 108 | --version Print version information 109 | 110 | The below languages are supported (case-sensitive): 111 | C C Programming Language 112 | python Python Programming Language 113 | powershell PowerShell Automation and Scripting Language 114 | 115 | ``` 116 | 117 | ## Contribution 118 | Feel free to contribute to this project by submitting your codes and by reporting issues and bugs 119 | 120 | ## Software License 121 | This software is licensed under the terms of the GNU General Public License. 122 | -------------------------------------------------------------------------------- /src/Makefile: -------------------------------------------------------------------------------- 1 | CC=gcc 2 | CFLAGS=-O1 -Wall -Wextra -Wformat -Wformat-security -fPIE -fstack-protector-all -D_FORTIFY_SOURCE=2 3 | LDFLAGS= 4 | GIT=/usr/bin/git 5 | 6 | TARGET = bstrings 7 | OBJECTS = $(SOURCES:.c=.o) 8 | SOURCES = bstrings.c version.c 9 | 10 | all: $(SOURCES) $(TARGET) 11 | 12 | $(TARGET): $(OBJECTS) 13 | $(CC) $(LDFLAGS) $(OBJECTS) -o $@ 14 | 15 | .c.o: 16 | $(CC) $(CFLAGS) -c $< -o $@ 17 | 18 | version.c: check 19 | cat version.in > version.c 20 | awk 'BEGIN {print "#include \"include/version.h\""}' >> version.c 21 | $(GIT) describe --abbrev=4 --always --tags | \ 22 | awk '{print "const char * program_version = \""$$0"\";"} END {}' >> version.c 23 | $(GIT) rev-parse HEAD | awk '{print "const char * program_build = \""$$0"\";"} END {}' >> version.c 24 | date --utc | awk 'BEGIN {} {print "const char * program_build_time = \""$$0"\";"} END {}' >> version.c 25 | 26 | check: check-if-git-exists 27 | check-if-git-exists: ; @which git >/dev/null 28 | 29 | clean: 30 | rm $(TARGET) $(OBJECTS) 31 | rm version.c 32 | -------------------------------------------------------------------------------- /src/TODO: -------------------------------------------------------------------------------- 1 | * --hex-uppercase switch to output all upper-case hexadecimal binary string. 2 | OK binary string decorations 3 | OK limit row width for -D alone 4 | OK indentation and variable name support. 5 | - fix syntax support/decoration for bad characters sequence. 6 | - limit size of indentation. 7 | - report input/ouput length in bytes. 8 | - remove characters from bad characters sequence. 9 | - accept output from debugger to find bad characters. 10 | - unicode and base64 binary strings support. 11 | -------------------------------------------------------------------------------- /src/bstrings.c: -------------------------------------------------------------------------------- 1 | /* vi:set tw=80 ts=8 sw=4 sts=4 et: 2 | * 3 | * Binary String Toolkit 4 | * 5 | * Copyright (C) 2018 Nicolas Chabbey 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 2 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | */ 18 | 19 | /* 20 | * bstrings.c - main program source file 21 | */ 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include "include/bool.h" 29 | #include "include/version.h" 30 | 31 | #define BADCHAR_HEX_SEQLEN 511 /* badchar hex digits sequence length */ 32 | #define MAX_FILENAME_LENGTH 512 /* max filename length on filesystems */ 33 | #define MAX_ARGUMENT_LENGTH 255 /* max length of option's argument */ 34 | #define MIN_ITER_TIL_LCHUNK 8 /* min heap chunk size until larger chunks 35 | are allocated from memory */ 36 | 37 | /* declare the 'verbose_flag' global integer */ 38 | static int verbose_flag; 39 | /* declare the 'interactive_flag' global integer */ 40 | static int interactive_flag; 41 | 42 | static void print_usage(FILE *stream, char *program_name) 43 | { 44 | fprintf(stream, "Usage: %s [OPTION]...\n", program_name); 45 | fprintf(stream, " Convert input to specified binary string format.\n\n"); 46 | fprintf(stream, " At least one of the below options must be given:\n\ 47 | -D, --dump-file=FILE Convert and Dump RAW content of file FILE\n\ 48 | -x, --hex-escape Escape input hexadecimal string\n\ 49 | -b, --gen-badchar Generate a bad character sequence string\n\ 50 | \n"); 51 | fprintf(stream, " The below switches are optional:\n\ 52 | -f, --file=FILE Read hex input from file FILE instead of stdin\n\ 53 | -w, --width=BYTES Break binary strings to specified length in bytes\n\ 54 | -s, --syntax=LANG Output variable using syntax of LANG\n\ 55 | -i, --indent=LENGTH Perform indentation for given character length\n\ 56 | -n, --var-name=VAR Specify string variable name (verbose mode)\n\ 57 | -h, --help Display this help\n\ 58 | --interactive Enter interactive mode\n\ 59 | --verbose Enable verbose output\n\ 60 | --version Print version information\n\ 61 | \n"); 62 | fprintf(stream, " The below languages are supported (case-sensitive):\n\ 63 | C C Programming Language\n\ 64 | python Python Programming Language\n\ 65 | powershell PowerShell Automation and Scripting Language\n\ 66 | \n"); 67 | } 68 | 69 | static void print_version(FILE *stream, char *program_name) 70 | { 71 | /* version & copyright */ 72 | fprintf(stream, "Binary String Toolkit (%s)\n", program_version); 73 | fprintf(stream, "Copyright (C) 2018 Nicolas Chabbey\n"); 74 | /* license statement */ 75 | fprintf(stream, "This program is free software: you can redistribute it " 76 | "and/or modify it\nunder the terms of the GNU General " 77 | "Public License as published by the\nFree Software " 78 | "Foundation, either version 2 of the License, or \n" 79 | "(at your option) any later version.\n" 80 | "This program has absolutely no warranty.\n"); 81 | /* source code, bug reporting & documentation */ 82 | fprintf(stream, "Source code, bug reporting and documentation available " 83 | "at:\n\n"); 84 | /* build & build time */ 85 | if(program_build != NULL) { 86 | fprintf(stream, "Git Build %s\nCompiled on %s\n", program_build, 87 | program_build_time); 88 | } 89 | /* help */ 90 | fprintf(stream, "For help enter \"%s --help\"\n", program_name); 91 | } 92 | 93 | /* struct 'bstring' definition */ 94 | struct bstring { 95 | /* declare pointer to character array 'ptr_char_array' */ 96 | char *ptr_char_array; 97 | /* declare pointer to unsigned integer 'ptr_array_size' */ 98 | unsigned int *ptr_array_size; 99 | /* declare unsigned integer 'output_lang' */ 100 | unsigned int output_lang; 101 | /* declare unsigned integer 'string_width' */ 102 | unsigned int string_width; 103 | /* declare unsigned integer 'indent_width' */ 104 | unsigned int indent_width; 105 | /* declare pointer to character array 'ptr_var_name' */ 106 | char *ptr_var_name; 107 | }; 108 | 109 | /* enumeration of read modes */ 110 | enum enum_read_modes { 111 | direct, /* direct input */ 112 | file_hex, /* read hex from file */ 113 | file_raw /* read raw data from file */ 114 | }; 115 | 116 | /* enumeration of supported languages */ 117 | enum enum_languages { 118 | C = 1, /* C Programming Language */ 119 | python, /* Python Programing Language */ 120 | powershell /* Powershell Automation and Scripting Language */ 121 | }; 122 | 123 | void output_hex_escaped_string(struct bstring *ptr_bstr) 124 | { 125 | /* declare integer i, c and ic */ 126 | unsigned int i, c, ic; 127 | 128 | /* initialize the hex escaped character array index to zero. 129 | * it keep track of the number of hex digits present in the binary string. 130 | */ 131 | int ai = 0; 132 | 133 | /* initialize local integer 'indent_width' to the value of the 134 | * 'indent_width' integer in struct pointed by 'ptr_bstr' pointer. 135 | */ 136 | unsigned int indent_width = ptr_bstr->indent_width; 137 | 138 | /* initialize integer 'invalidhexchar' to be used as a counter. */ 139 | int invalidhexchar = 0; 140 | 141 | /* if interactive flag set, start the binary string on a new line */ 142 | if (interactive_flag) 143 | putchar('\n'); 144 | 145 | /* if verbose flag set, perform indentation and output variable name */ 146 | if (verbose_flag == true) { 147 | /* indentation loop */ 148 | if (indent_width > 0) { 149 | for (ic = 0; ic < indent_width; ic++) { 150 | /* put space character (decimal: 32) */ 151 | putchar(32); 152 | } 153 | } 154 | /* print variable name matching specified language */ 155 | switch (ptr_bstr->output_lang) { 156 | case C: /* C */ 157 | if (ptr_bstr->ptr_var_name != NULL) 158 | printf("unsigned char %s[] =\n", ptr_bstr->ptr_var_name); 159 | else 160 | printf("unsigned char buffer[] =\n"); 161 | break; 162 | case python: /* Python */ 163 | if (ptr_bstr->ptr_var_name != NULL) 164 | printf("%s = \"\"\n", ptr_bstr->ptr_var_name); 165 | else 166 | printf("buffer = \"\"\n"); 167 | break; 168 | case powershell: /* PowerShell */ 169 | if (ptr_bstr->ptr_var_name != NULL) 170 | printf("[Byte[]] $%s = ", ptr_bstr->ptr_var_name); 171 | else 172 | printf("[Byte[]] $buf = "); 173 | break; 174 | 175 | } 176 | } 177 | 178 | /* for every character of the character array 'char_array' 179 | * loop through the body until we reach the end of the array. 180 | * Dont't forget to account for the extra byte of the array_size's size in 181 | * order to only print characters within the input string. 182 | */ 183 | for (i = 0; i < *ptr_bstr->ptr_array_size; i++) { 184 | /* initialize c to the i(th) element of the array */ 185 | c = ptr_bstr->ptr_char_array[i]; 186 | 187 | /* filter out any characters outside of the hexadecimal ASCII character 188 | * range. 189 | */ 190 | switch (c) { 191 | /* if the character is within the hexadecimal characters range. 192 | * ranges within switch case's constants are supported by GCC. 193 | */ 194 | case 48 ... 57: // 0-9 195 | case 65 ... 70: // A-F 196 | case 97 ... 102: // a-f 197 | /* if the hex escaped char array index is divible by two, 198 | * we've pair of hexadecimal characters (or byte) 199 | */ 200 | if (ai % 2 == 0) { 201 | /* if string_width is non-default or specified. */ 202 | if (ptr_bstr->string_width != 0) { 203 | /* if true, we are at the end of the line. 204 | * ensure integer 'ai' is non-zero so we don't insert 205 | * a new line character in the first row of output. 206 | * put a new line character every string_width's byte 207 | * value. 208 | */ 209 | if (ai % (ptr_bstr->string_width*2) == 0) { 210 | switch (ptr_bstr->output_lang) { 211 | case C: /* C syntax */ 212 | /* ensure we don't put an extra character 213 | * at the start of the binary string row 214 | * by verifying 'ai' is not zero. 215 | */ 216 | if (ai != 0) { putchar('\"'); } 217 | if (ai != 0) { putchar('\n'); } 218 | /* indentation loop, repeat space 219 | * character (decimal 32) for indent_width 220 | * value + 4 (or standard indent size). 221 | */ 222 | for (ic = 0; ic < indent_width+4; ic++) { 223 | putchar(32); 224 | } 225 | putchar('\"'); 226 | break; 227 | case python: /* Python syntax */ 228 | if (ai != 0) { putchar('\"'); } 229 | if (ai != 0) { putchar('\n'); } 230 | /* indentation loop */ 231 | for (ic = 0; ic < indent_width; ic++) { 232 | putchar(32); 233 | } 234 | /* if variable name specified */ 235 | if (ptr_bstr->ptr_var_name != NULL) { 236 | printf("%s += ", 237 | ptr_bstr->ptr_var_name); 238 | } else { 239 | printf("buffer += "); 240 | } 241 | putchar('\"'); 242 | break; 243 | case powershell: /* PowerShell */ 244 | break; 245 | default: 246 | if (ai != 0) { 247 | putchar('\n'); 248 | /* indentation loop */ 249 | for (ic = 0; ic < indent_width; ic++) { 250 | putchar(32); 251 | } 252 | } 253 | } 254 | } 255 | } 256 | switch (ptr_bstr->output_lang) { 257 | case powershell: /* PowerShell */ 258 | /* 0xH format */ 259 | putchar('0'); putchar('x'); putchar(c); 260 | break; 261 | default: 262 | /* \xH format */ 263 | putchar('\\'); putchar('x'); putchar(c); 264 | } 265 | } else { 266 | switch (ptr_bstr->output_lang) { 267 | case powershell: /* PowerShell */ 268 | if (ai == (int)(*ptr_bstr->ptr_array_size)-1) { 269 | putchar(c); 270 | } else { 271 | putchar(c); putchar(','); 272 | } 273 | break; 274 | default: 275 | putchar(c); 276 | } 277 | } 278 | /* Increase the hex escaped character array index so we keep 279 | * track of the pair of hexadecimal byte inside the binary 280 | * string. 281 | */ 282 | ai++; 283 | break; 284 | default: /* all non-hexadecimal characters */ 285 | /* catches all non-hexadcimal characters, excepted the 286 | * end-of-file, the new-line and the null characters 287 | * respectively. 288 | */ 289 | switch (c) { 290 | case EOF: break; // End of File 291 | case 10: break; // New Line 292 | case 0: break; // Null 293 | default: invalidhexchar++; 294 | } 295 | } 296 | } 297 | 298 | /* we've reached the end of the binary string output. */ 299 | switch (ptr_bstr->output_lang) { 300 | case C: putchar('\"'); putchar(59); break; 301 | case python: putchar('\"'); break; 302 | } 303 | putchar('\n'); 304 | 305 | if ((verbose_flag == true) && (invalidhexchar > 0)) { 306 | fprintf(stdout, "[-] Warning: %d non-hexadecimal character(s) " 307 | "detected in input.\n", invalidhexchar); 308 | } 309 | } 310 | 311 | void * alloc_heap_memory(unsigned int alloc_size) 312 | { 313 | /* use malloc() to allocate dynamic memory and then return to the caller 314 | * function the memory location allocated on the heap. 315 | */ 316 | void *ptr = malloc(alloc_size); 317 | 318 | /* error handling: on errors malloc() returns NULL. */ 319 | if (ptr == NULL) { 320 | fprintf(stderr, "Error: %d byte(s) memory allocation failure.\n", 321 | alloc_size); 322 | exit(EXIT_FAILURE); 323 | } 324 | 325 | return ptr; 326 | } 327 | 328 | void * realloc_heap_memory(void *ptr, unsigned int new_size) 329 | { 330 | /* call to realloc() to change the size of the memory block pointed to by 331 | * the pointer 'new_ptr' with the new size value in 'new_size'. 332 | */ 333 | void *new_ptr = realloc(ptr, new_size); 334 | 335 | /* error handling: on errors realloc() returns NULL. */ 336 | if (new_ptr == NULL) { 337 | fprintf(stderr, "Error: %d byte(s) memory re-allocation error.\n", 338 | new_size); 339 | exit(EXIT_FAILURE); 340 | } 341 | 342 | return new_ptr; 343 | } 344 | 345 | char * generate_badchar_sequence(char *ptr_badchar_array) 346 | { 347 | /* declare integer i */ 348 | int i; 349 | 350 | /* initialize bad char. character array pointer by calling 351 | * alloc_heap_memory() function with a fixed allocation size of 510 352 | * bytes, the latter being the length we need to hold all hex digits. 353 | */ 354 | ptr_badchar_array = (char *)realloc_heap_memory(ptr_badchar_array, 355 | sizeof(char) 356 | * BADCHAR_HEX_SEQLEN); 357 | 358 | /* initialize length integer */ 359 | unsigned int length = 0; 360 | 361 | /* simple linear hex digits generator */ 362 | for (i = 1; i < 256; i++) { 363 | /* leveraging snprintf() to store hexadecimal digits to the character 364 | * array pointed by 'ptr_badchar_array'. 365 | */ 366 | length += snprintf(ptr_badchar_array+length, 3, "%02x", i); 367 | } 368 | 369 | /* return the character array pointer to the caller function */ 370 | return ptr_badchar_array; 371 | } 372 | 373 | void read_and_store_char_input(struct bstring *ptr_bstr) 374 | { 375 | /* initialize integer 'c' which will hold input character. */ 376 | int c = 0; 377 | /* initialize unsigned integer 'i' which will be used as an array index. */ 378 | unsigned int i = 0; 379 | /* initialize unsigned integer 'as' which holds the memory allocation 380 | * size. Here the value must equals one character due to the memory 381 | * allocation being done after character write. */ 382 | unsigned int as = sizeof(char); 383 | 384 | /* if in interactive mode */ 385 | if (interactive_flag) 386 | printf("[+] Hit CTRL-D twice to terminate input.\n"); 387 | 388 | /* store each input character into the character array 'ptr_char_array' 389 | * until we reach EOF. 390 | */ 391 | while ((c = getchar()) != EOF) { 392 | ptr_bstr->ptr_char_array[i] = (char)c; 393 | /* perform small allocations until MIN_ITER_TIL_LCHUNK */ 394 | if (i < MIN_ITER_TIL_LCHUNK) { 395 | ptr_bstr->ptr_char_array = 396 | (char *)realloc_heap_memory(ptr_bstr->ptr_char_array, 397 | sizeof(char) * 398 | (*ptr_bstr->ptr_array_size+=1)); 399 | /* perform larger memory allocations in increments of 8 bytes. */ 400 | } else { 401 | /* when the index is divisible by the allocation size, perform a 402 | * new, larger memory allocation. This should reduce the number of 403 | * library calls to realloc(). 404 | */ 405 | if (i % as == 0) { 406 | ptr_bstr->ptr_char_array = 407 | (char *)realloc_heap_memory(ptr_bstr->ptr_char_array, 408 | sizeof(char) * 409 | (as+=(i/8)*8)+1); 410 | } 411 | /* update the array size */ 412 | (*ptr_bstr->ptr_array_size += 1); 413 | } 414 | 415 | /* unsigned integer overflow check for 'as'*/ 416 | if (UINT_MAX - ((i/8)*8) < as) { 417 | printf("Error: unsigned integer overflow detected.\n"); 418 | exit(EXIT_FAILURE); 419 | } 420 | 421 | /* increment the array index */ 422 | i++; 423 | } 424 | /* decrease the array size as it will always be size+1 after the while 425 | loop above. */ 426 | (*ptr_bstr->ptr_array_size -= 1); 427 | } 428 | 429 | void read_from_file(char *filename, struct bstring *ptr_bstr, int read_mode) 430 | { 431 | /* initialize integer 'c' */ 432 | int c = 0; 433 | /* declare pointer to FILE 'ptr_file_descriptor' */ 434 | FILE *ptr_file_descriptor; 435 | 436 | /* initialize pointer 'ptr_file_descriptor' */ 437 | ptr_file_descriptor = fopen(filename, "r"); 438 | 439 | /* if ptr_file_read is null, return an error and exit */ 440 | if (ptr_file_descriptor == NULL) { 441 | fprintf(stderr, "Error: input filename \"%s\" cannot be read.\n", 442 | filename); 443 | exit(EXIT_FAILURE); 444 | } 445 | 446 | /* before continuing let see in which mode we're in */ 447 | /* mode 1+: we read file and store content on the heap */ 448 | if ((read_mode == file_hex) || (read_mode == file_raw)) { 449 | /* initialize char array index */ 450 | int i = 0; 451 | 452 | /* initialize array size 'as' */ 453 | unsigned int as = sizeof(char); 454 | 455 | /* declare character array 'xc' of size '3' which is enough to hold 456 | * two hexadecimal digits + null-termination character. 457 | */ 458 | char xc[3]; 459 | 460 | switch (read_mode) { 461 | case file_hex: /* Read hexadecimal */ 462 | *(ptr_bstr->ptr_array_size) += 1; 463 | break; 464 | case file_raw: /* Read raw data */ 465 | ptr_bstr->ptr_char_array = 466 | (char *)realloc_heap_memory(ptr_bstr->ptr_char_array, 467 | sizeof(char)*2); 468 | /* when first dereferenced for realloc_heap_memory() below 469 | * the array size should be 2, and increased by two at each 470 | * iteration of the below while loop. -- fix heap-buffer 471 | * overflow. 472 | */ 473 | *(ptr_bstr->ptr_array_size) += 2; 474 | break; 475 | } 476 | 477 | while ((c = getc(ptr_file_descriptor)) != EOF) { 478 | switch (read_mode) { 479 | /* mode 1: we simply store the character in buffer. */ 480 | case file_hex: 481 | /* if newline character (0x0a), then simply ignore it */ 482 | if (c == 10) break; 483 | ptr_bstr->ptr_char_array[i] = (char)c; 484 | /* perform small 1-byte allocations until we reach 485 | * MIN_ITER_TIL_LCHUNK. 486 | */ 487 | if (i < MIN_ITER_TIL_LCHUNK) { 488 | /* the array size will be the number of characters + 489 | * one after we reach EOF character in input. 490 | */ 491 | ptr_bstr->ptr_char_array = 492 | (char *)realloc_heap_memory(ptr_bstr->ptr_char_array, 493 | sizeof(char) * ( 494 | *(ptr_bstr->ptr_array_size) 495 | +=1)); 496 | /* perform larger memory allocations in increments of 8 497 | * bytes. 498 | */ 499 | } else { 500 | /* when the index is divisible by the allocation size, 501 | * perform a new, larger memory allocation. This should 502 | * reduce the number of library calls to realloc(). 503 | */ 504 | if (i % as == 0) { 505 | /* realloc by a factor of 8 + 1 character to 506 | * accodomate the next character in the next 507 | * iteration. 508 | */ 509 | ptr_bstr->ptr_char_array = 510 | (char *)realloc_heap_memory(ptr_bstr->ptr_char_array, 511 | sizeof(char) * 512 | (as+=(i/8)*8)+1); 513 | } 514 | /* update the array size */ 515 | *(ptr_bstr->ptr_array_size) += 1; 516 | } 517 | i++; 518 | break; 519 | /* mode 2: here we use 'snprintf()' to format each read 520 | * character to hexadecimal. As two hex digits equal one byte, 521 | * we must grow our destination character array accordingly. 522 | */ 523 | case file_raw: 524 | snprintf(xc, 3, "%02x", c); 525 | ptr_bstr->ptr_char_array[i] = (char)xc[0]; 526 | ptr_bstr->ptr_char_array[i+1] = (char)xc[1]; 527 | /* heap memory allocation */ 528 | if (i < MIN_ITER_TIL_LCHUNK) { 529 | ptr_bstr->ptr_char_array = 530 | (char *)realloc_heap_memory(ptr_bstr->ptr_char_array, 531 | sizeof(char) * ( 532 | *(ptr_bstr->ptr_array_size) 533 | +=2)); 534 | } else { 535 | if (i % as == 0) { 536 | /* perform reallocation by a factor of 8 + 2 537 | * characters to accodomate them at the next 538 | * iteration. 539 | */ 540 | ptr_bstr->ptr_char_array = 541 | (char *)realloc_heap_memory(ptr_bstr->ptr_char_array, 542 | sizeof(char) * 543 | (as+=(i/8)*8)*2+2); 544 | } 545 | /* update the array size */ 546 | *(ptr_bstr->ptr_array_size) += 2; 547 | } 548 | i+=2; 549 | break; 550 | } 551 | /* unsigned integer overflow check for 'as' */ 552 | if (UINT_MAX - ((i/8)*8) < as) { 553 | printf("Error: unsigned integer overflow detected.\n"); 554 | exit(EXIT_FAILURE); 555 | } 556 | } 557 | /* otherwise: we read from file and output to stdout directly */ 558 | } else { 559 | /* get next character from file using getc() until we reach EOF */ 560 | while ((c = getc(ptr_file_descriptor)) != EOF) { 561 | printf("%02x", c); 562 | } 563 | } 564 | 565 | /* close opened file handler */ 566 | fclose(ptr_file_descriptor); 567 | 568 | /* adjust array size according to the read mode */ 569 | switch (read_mode) { 570 | case file_hex: 571 | (*ptr_bstr->ptr_array_size-=1); 572 | break; 573 | case file_raw: 574 | (*ptr_bstr->ptr_array_size-=2); 575 | break; 576 | } 577 | } 578 | 579 | int main(int argc, char *argv[]) 580 | { 581 | /* initialize all variables needed for command-line options handling using 582 | * the GNU C Library's getopt_long() function. 583 | */ 584 | int opt; 585 | 586 | /* initialize program's options flags */ 587 | bool doOutputHexEscapedString = false; 588 | bool doOutputBadCharString = false; 589 | bool doHexDumpFile = false; 590 | bool doReadFromFile = false; 591 | bool doLimitBinaryStringWidth = false; 592 | bool doLanguageDecoration = false; 593 | bool doPerformIndentation = false; 594 | 595 | /* declare 'fread_filename' character array */ 596 | char fread_filename[MAX_FILENAME_LENGTH+1]; 597 | 598 | /* initialize pointer 'ptr_bstr' for struct type 'bstring'. 599 | the struct is allocated and stored on the heap. 600 | */ 601 | struct bstring *ptr_bstr = (struct bstring *) 602 | alloc_heap_memory(sizeof *ptr_bstr); 603 | 604 | /* initialize pointer 'ptr_char_array' in struct pointed by 'ptr_bstr' */ 605 | ptr_bstr->ptr_char_array = (char *)alloc_heap_memory(sizeof(char)); 606 | 607 | /* initialize pointer 'ptr_array_size' in struct pointed by 'ptr_bstr' */ 608 | ptr_bstr->ptr_array_size = (unsigned int *) 609 | alloc_heap_memory(sizeof(unsigned int)); 610 | 611 | /* initialize 'ptr_var_name' in struct as pointed by 'ptr_bstr' to NULL */ 612 | ptr_bstr->ptr_var_name = NULL; 613 | 614 | /* initialize 'indent_width' in struct pointed by 'ptr_bstr' */ 615 | ptr_bstr->indent_width = 0; 616 | 617 | /* initialize 'arg_lang' character array */ 618 | char arg_lang[MAX_ARGUMENT_LENGTH] = "undefined"; 619 | 620 | /* getopt_long()'s long_options struct */ 621 | static struct option long_options[] = { 622 | /* verbosity flags */ 623 | {"verbose", no_argument, &verbose_flag, true}, 624 | {"quiet", no_argument, &verbose_flag, false}, 625 | {"interactive", no_argument, &interactive_flag, 1}, 626 | /* program actions */ 627 | {"hex-escape", no_argument, NULL, 'x'}, 628 | {"gen-badchar", no_argument, NULL, 'b'}, 629 | {"dump-file", required_argument, NULL, 'D'}, 630 | /* program options */ 631 | {"file", required_argument, NULL, 'f'}, 632 | {"width", required_argument, NULL, 'w'}, 633 | {"syntax", required_argument, NULL, 's'}, 634 | {"indent", required_argument, NULL, 'i'}, 635 | {"var-name", required_argument, NULL, 'n'}, 636 | /* version option */ 637 | {"version", no_argument, NULL, '@'}, 638 | /* help option */ 639 | {"help", no_argument, NULL, 'h'}, 640 | {0, 0, 0, 0} 641 | }; 642 | 643 | /* using getopt_long() from GNU C library to parse command-line options */ 644 | while ((opt = getopt_long(argc, argv, ":D:xbf:w:s:i:n:h", 645 | long_options, NULL)) != -1) { 646 | switch (opt) { 647 | /* handle getopt_long() return values */ 648 | case 0: /* getopt_long() set a flag, keep going */ 649 | break; 650 | case 1: /* getopt_long() points at a command-line argument */ 651 | break; 652 | case ':': /* an argument option is missing */ 653 | fprintf(stderr, "%s: option `-%c' require an argument.\n", 654 | argv[0], optopt); 655 | exit(EXIT_FAILURE); 656 | case '?': /* invalid option given */ 657 | case 'h': /* user ask for help */ 658 | default: 659 | print_usage(stderr, argv[0]); 660 | exit(EXIT_FAILURE); 661 | case '@': 662 | print_version(stderr, argv[0]); 663 | exit(EXIT_SUCCESS); 664 | /* program's commands and options */ 665 | case 'v': verbose_flag = true; break; 666 | case 'x': doOutputHexEscapedString = true; break; 667 | case 'b': doOutputBadCharString = true; break; 668 | case 'D': /* dump file content in hex */ 669 | if (optarg != NULL) { 670 | snprintf(fread_filename, MAX_FILENAME_LENGTH, "%s", 671 | optarg); 672 | doHexDumpFile = true; 673 | } 674 | break; 675 | case 'f': /* file to read from option */ 676 | if (optarg != NULL) { 677 | snprintf(fread_filename, MAX_FILENAME_LENGTH, "%s", 678 | optarg); 679 | doReadFromFile = true; 680 | } 681 | break; 682 | case 's': /* syntax option given */ 683 | if (optarg != NULL) { 684 | snprintf(arg_lang, MAX_ARGUMENT_LENGTH, "%s", optarg); 685 | doLanguageDecoration = true; 686 | } 687 | if (strcmp(arg_lang, "c") == 0 || strcmp(arg_lang, "C") == 0) { 688 | ptr_bstr->output_lang=1; 689 | } else if (strcmp(arg_lang, "python") == 0) { 690 | ptr_bstr->output_lang=2; 691 | } else if (strcmp(arg_lang, "powershell") == 0) { 692 | ptr_bstr->output_lang=3; 693 | } else { 694 | printf("[-] Error: Unknown specified language \"%s\".\n", 695 | arg_lang); 696 | exit(EXIT_FAILURE); 697 | } 698 | break; 699 | case 'i': /* indentation option given */ 700 | doPerformIndentation = true; 701 | if (optarg != NULL && atoi(optarg) > 0 && atoi(optarg) < 702 | MAX_ARGUMENT_LENGTH) { 703 | /* read the given indentation width from the command-line 704 | * option and convert it to integer using atoi() from the 705 | * GNU C library. 706 | */ 707 | ptr_bstr->indent_width = atoi(optarg); 708 | } else { 709 | /* if option given but out of range: */ 710 | ptr_bstr->indent_width = 0; 711 | } 712 | break; 713 | case 'n': /* variable name option given */ 714 | if (optarg != NULL) { 715 | /* don't forget to free the allocation later */ 716 | ptr_bstr->ptr_var_name = 717 | (char *)alloc_heap_memory(MAX_ARGUMENT_LENGTH); 718 | snprintf(ptr_bstr->ptr_var_name, MAX_ARGUMENT_LENGTH, 719 | "%s", optarg); 720 | } 721 | break; 722 | case 'w': /* binary string width option */ 723 | /* make sure 'optarg' isn't null before using it */ 724 | if (optarg != NULL) { 725 | /* using atoi() from the GNU C library to read the binary 726 | * string width from the command-line -w|--width option 727 | * argument. 728 | */ 729 | ptr_bstr->string_width = atoi(optarg); 730 | doLimitBinaryStringWidth = true; 731 | } 732 | break; 733 | } 734 | } 735 | 736 | /* simple conditional check to ensure at least a valid option is given at 737 | * the command-line, otherwise call print_usage() function. 738 | */ 739 | if ((optind < argc) || argc == 1) { 740 | print_usage(stdout, argv[0]); 741 | exit(EXIT_SUCCESS); 742 | } 743 | 744 | /* if -x|--hex-escape option is given */ 745 | if (doOutputHexEscapedString == true) { 746 | /* initialize integer pointed by 'ptr_array_size' */ 747 | *(ptr_bstr->ptr_array_size) = 0; 748 | /* toggle verbosity if flag set */ 749 | if (verbose_flag == true) { 750 | printf("[*] Convert hexadecimal input to an escaped binary string" 751 | ".\n"); 752 | if (doLimitBinaryStringWidth == true) { 753 | printf("[+] Binary string width is limited to %d bytes.\n", 754 | ptr_bstr->string_width); 755 | } 756 | if (doLanguageDecoration == true) { 757 | printf("[+] Output binary string using %s language syntax.\n", 758 | arg_lang); 759 | } 760 | if (doPerformIndentation == true) { 761 | printf("[+] Indentation level set to %d space character(s).\n", 762 | ptr_bstr->indent_width); 763 | } 764 | } 765 | /* if -D|--dump-file option is additionally given */ 766 | if (doHexDumpFile == true) { 767 | /* call to read_from_file() */ 768 | read_from_file(fread_filename, ptr_bstr, file_raw); 769 | /* if -f|--file option is given read from file instead of stdin */ 770 | } else if (doReadFromFile == true) { 771 | /* call to read_from_file() */ 772 | read_from_file(fread_filename, ptr_bstr, file_hex); 773 | } else { 774 | /* call to read_and_store_char_input() */ 775 | read_and_store_char_input(ptr_bstr); 776 | } 777 | /* call to output_hex_escaped_string() */ 778 | output_hex_escaped_string(ptr_bstr); 779 | /* call to free() for 'ptr_char_array' */ 780 | free(ptr_bstr->ptr_char_array); 781 | /* call to free() for 'ptr_array_size' */ 782 | free(ptr_bstr->ptr_array_size); 783 | /* free memory for ptr_bstr->ptr_var_name if not null */ 784 | if (ptr_bstr->ptr_var_name != NULL) 785 | free(ptr_bstr->ptr_var_name); 786 | /* call to free() for 'ptr_bstr' */ 787 | free(ptr_bstr); 788 | /* exit as we're the last action */ 789 | exit(EXIT_SUCCESS); 790 | } 791 | 792 | /* if -D|--dump-file option is given */ 793 | if (doHexDumpFile == true) { 794 | /* call to read_from_file() */ 795 | read_from_file(fread_filename, NULL, direct); 796 | /* exit as we're the last action */ 797 | exit(EXIT_SUCCESS); 798 | } 799 | 800 | /* if -b|--gen-badchar option is given */ 801 | if (doOutputBadCharString == true) { 802 | /* initialize integer 'array_size' to BADCHAR_HEX_SEQLEN bytes */ 803 | *(ptr_bstr->ptr_array_size) = BADCHAR_HEX_SEQLEN; 804 | /* toggle verbosity if flag set */ 805 | if (verbose_flag == true) { 806 | printf("[*] Generating bad character binary string.\n"); 807 | if (doLimitBinaryStringWidth == true) { 808 | printf("[+] Binary string width is limited to %d bytes.\n", 809 | ptr_bstr->string_width); 810 | } 811 | } 812 | /* call to generate_badchar_sequence() */ 813 | ptr_bstr->ptr_char_array = 814 | generate_badchar_sequence(ptr_bstr->ptr_char_array); 815 | /* call to output_hex_escaped_string() */ 816 | output_hex_escaped_string(ptr_bstr); 817 | /* calls to free() for the various allocated memory locations */ 818 | free(ptr_bstr->ptr_char_array); 819 | free(ptr_bstr->ptr_array_size); 820 | /* free memory for 'var_name' as pointed by 'ptr_bstr->ptr_var_name' 821 | * if the later pointer is not null. 822 | */ 823 | if (ptr_bstr->ptr_var_name != NULL) 824 | free(ptr_bstr->ptr_var_name); 825 | /* free allocation for struct pointed by ptr_bstr */ 826 | free(ptr_bstr); 827 | /* exit as we're the last action */ 828 | exit(EXIT_SUCCESS); 829 | } 830 | 831 | return 0; 832 | } 833 | -------------------------------------------------------------------------------- /src/include/bool.h: -------------------------------------------------------------------------------- 1 | /* vi:set tw=78 ts=8 sw=4 sts=4 et: 2 | * 3 | * This file is part of Binary String Toolkit. 4 | * 5 | */ 6 | 7 | /* 8 | * bool.h - add boolean type support 9 | */ 10 | 11 | typedef enum { false, true } bool; 12 | -------------------------------------------------------------------------------- /src/include/version.h: -------------------------------------------------------------------------------- 1 | /* vi:set tw=78 ts=8 sw=4 sts=4 et: 2 | * 3 | * This file is part of Binary String Toolkit. 4 | * 5 | */ 6 | 7 | /* 8 | * version.h - version information header file 9 | */ 10 | 11 | #ifndef VERSION_H 12 | #define VERSION_H 13 | 14 | extern const char * program_version; 15 | extern const char * program_build; 16 | extern const char * program_build_time; 17 | 18 | #endif /* #ifndef VERSION_H */ 19 | -------------------------------------------------------------------------------- /src/version.in: -------------------------------------------------------------------------------- 1 | /* vi:set tw=78 ts=8 sw=4 sts=4 et: 2 | * 3 | * This file is part of Binary String Toolkit. 4 | * 5 | * Copyright (C) 2018 Nicolas Chabbey 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 2 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | */ 18 | 19 | /* 20 | * version.c - version information header file 21 | */ 22 | 23 | --------------------------------------------------------------------------------