<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jayson Hurst on Medium]]></title>
        <description><![CDATA[Stories by Jayson Hurst on Medium]]></description>
        <link>https://medium.com/@jayo78?source=rss-b8f51d811181------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hFmDYqA-qaNi8BnJnVX6KA.png</url>
            <title>Stories by Jayson Hurst on Medium</title>
            <link>https://medium.com/@jayo78?source=rss-b8f51d811181------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:59:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jayo78/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Build ChatGPT]]></title>
            <link>https://medium.com/geekculture/how-to-build-chatgpt-a01f9bd6d8ab?source=rss-b8f51d811181------2</link>
            <guid isPermaLink="false">https://medium.com/p/a01f9bd6d8ab</guid>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Jayson Hurst]]></dc:creator>
            <pubDate>Fri, 13 Jan 2023 02:01:45 GMT</pubDate>
            <atom:updated>2023-01-13T02:01:45.551Z</atom:updated>
            <content:encoded><![CDATA[<p>A brief intro to building chatbots With GPT-3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vysw5_sQwIWPFelmPNxG5g.png" /><figcaption>A chatbot prompt that can remember past user input (by Author)</figcaption></figure><p>ChatGPT has blown up in the past month, gaining a million users in just a week. What’s crazy is that the underlying model, GPT-3 was debuted in 2020 and released for public access <a href="https://openai.com/blog/api-no-waitlist/">over a year ago</a>!</p><p>While the early versions of GPT-3 weren’t as advanced as the current <a href="https://beta.openai.com/docs/model-index-for-researchers">GPT-3.5 series</a>, they were still impressive. These models have been available through an API and a <a href="https://beta.openai.com/playground">playground web UI interface</a> that lets you tune certain parameters and test out prompts. GPT-3 certainly gained a lot of traction, but it was no where near the virality of ChatGPT.</p><p>What makes ChatGPT so successful, comparatively, is its accessibility as a <strong>straight-forward product</strong> for the <strong>average person</strong>, regardless of their knowledge of data science, language models, or AI.</p><p>In this article I overview how chat bots like ChatGPT can be implemented using a large language model like GPT-3.</p><h3>Motivation</h3><p>This article was written in part because of a tweet by <a href="https://twitter.com/goodside">Riley Goodside</a> explaining how ChatGPT was probably implemented.</p><h3>Riley Goodside on Twitter: &quot;How to make your own knock-off ChatGPT using GPT‑3 (text‑davinci‑003) - where you can customize the rules to your needs, and access the resulting chatbot over an API. pic.twitter.com/9jHrs91VHW / Twitter&quot;</h3><p>How to make your own knock-off ChatGPT using GPT‑3 (text‑davinci‑003) - where you can customize the rules to your needs, and access the resulting chatbot over an API. pic.twitter.com/9jHrs91VHW</p><p>Like other models in the GPT-3.5 series, ChatGPT was trained using <a href="https://huggingface.co/blog/rlhf">RLHF</a>, but much of it’s effectiveness comes from using a <strong>good prompt</strong>.</p><h3>The Prompt</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttd7gxCQCBZJnPR0u_9MPQ.png" /><figcaption>A prompt for a helpful chatbot named “Skippy”</figcaption></figure><p>Prompting is the process of instructing an AI to do something. As you have probably seen in ChatGPT examples online, you can prompt it to do just about anything. Common use cases are summarizing text, writing content based on a description, or creating things like poems, recipes, and much more.</p><p>ChatGPT is both a language model and user interface. The prompt input by a user to the interface is actually inserted into a larger prompt that contains the entire conversation between the user and ChatGPT. This allows the underlying language model to understand the context of the conversation and respond appropriately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*ppuT9DIz532MbRo3dcbQJA.png" /><figcaption>Example of inserting user prompt into a chatbot prompt</figcaption></figure><p>The model uses the data it was trained on to predict the best completion to this larger prompt that includes both new input and the previous conversation. It’s important to note that the language model isn’t responding to the prompt but rather figuring out what words come next based on probabilities it learned during pre-training.</p><p>GPT-3 is able to learn from a simple instruction or a few examples in the prompt. This is called <a href="https://arxiv.org/abs/2005.14165">few-shot learning</a>, or in context learning. In the chatbot prompt above, I create a fictitious chatbot named Skippy, and instruct it to provide responses to users. GPT-3 picks up on the back-and-forth format, USER: {user input} and SKIPPY: {skippy response}. GPT-3 understands that Skippy is a chatbot and the previous exchanges are a conversation, so that when we provide the next user input, &quot;Skippy&quot; will respond.</p><h4>Memorization</h4><p>Past exchanges between Skippy and the user get appended to the next prompt. Each time we give more user input and get more chatbot output, the prompt expands to incorporate this new exchange. This is how chatbots like Skippy and ChatGPT can <strong>remember previous inputs.</strong> There is a limit, however, to how much a GPT-3 chatbot can remember.</p><p>Prompts can get massive after several exchanges, especially if we are using the chatbot to generate long responses like blog posts. Prompts sent to GPT-3 are converted into tokens, which are individual words or parts of them. There is a limit of <a href="https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them">4097 tokens (about 3000 words)</a> for the combined prompt and generated response for GPT-3 models, including ChatGPT.</p><h4>A Few Examples</h4><p>There are many different use cases of chat bot prompts that store previous conversations. ChatGPT is meant to be an all purpose general assistant and in my experience, it rarely asks follow ups.</p><h4>Therapy chat bot that asks about your day</h4><p>In some cases it can be helpful to have a chat bot that actively asks questions and gets feedback from the user. Below is an example therapy chat bot prompt that will ask questions and follow ups to help a user think about their day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXKZDz7X6Td7EGQsZfGc_Q.gif" /><figcaption>Therapy chat bot prompt (by Author)</figcaption></figure><h4>Talk to your younger self using old journal entries</h4><p><a href="https://twitter.com/michellehuang42">Michelle Huang</a> used GPT-3 to have a chat with her younger self. The prompt uses some context, in this case old journal entries, paired with a chat bot style back and forth format. GPT-3 is able to mimic a personality based on these entries.</p><h3>michelle huang on Twitter: &quot;i trained an ai chatbot on my childhood journal entries - so that i could engage in real-time dialogue with my &quot;inner child&quot;some reflections below: / Twitter&quot;</h3><p>i trained an ai chatbot on my childhood journal entries - so that i could engage in real-time dialogue with my &quot;inner child&quot;some reflections below:</p><p>Prompt from the Tweet:</p><pre>The following is a conversation with Present Michelle (age [redacted]) and Young Michelle (age 14).</pre><pre>Young Michelle has written the following journal entries:</pre><pre>[diary entries here]</pre><pre>Present Michelle: [type your questions here]</pre><p>This is again using a few shot prompt, just now with added context. The author does note that diary entries can reach the token limit. In this case you could pick a select few entries or try and summarize several entries.</p><h3>Implementation</h3><p>I will walk through coding a simple GPT-3 powered chat bot in Python. Implementing GPT-3 into an app you are building is super easy because OpenAI has an API. You will need to create an account on OpenAI and get an API key. Check out their docs <a href="https://beta.openai.com/docs/introduction">here</a>.</p><p>Overview of what we need to do:</p><ol><li>Format user input into a chatbot prompt for GPT-3</li><li>Get the chatbot response as a completion from GPT-3</li><li>Update the prompt with both the user’s input and the chatbot’s response</li><li>Loop</li></ol><p>Here is the prompt I will use. We can use python to replace &lt;conversation history&gt; and &lt;user input&gt; with their actual values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e673e1f7070d382363bb1baa0617d330/href">https://medium.com/media/e673e1f7070d382363bb1baa0617d330/href</a></iframe><p>I keep track of both the next user input and the previous conversation. Below is the full code for a simple chat bot. New input/output between chatbot and user is appended each loop.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/051200947b3eb37a9524b046053a06fd/href">https://medium.com/media/051200947b3eb37a9524b046053a06fd/href</a></iframe><p>Copy and paste this code in a new python file and you should be able to run it in your terminal. Now all that’s left is to build a nice front-end that users can interact with! I implemented this example in Python for ease of understanding.</p><h4>Thanks for reading!</h4><p>I hope this was informative, please feel free to give some motivational claps, I’d love to write some more!</p><h4>Connect with Jayson Hurst</h4><p>You can find me on <a href="https://twitter.com/jayo782">Twitter</a> and <a href="https://www.linkedin.com/in/jayo78/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a01f9bd6d8ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-build-chatgpt-a01f9bd6d8ab">How to Build ChatGPT</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GPT-3 Prompt engineering: Solving discussion posts]]></title>
            <link>https://medium.com/@jayo78/solving-discussion-posts-with-gpt-3-7069e8f418f7?source=rss-b8f51d811181------2</link>
            <guid isPermaLink="false">https://medium.com/p/7069e8f418f7</guid>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[college]]></category>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[homework]]></category>
            <category><![CDATA[discussion]]></category>
            <dc:creator><![CDATA[Jayson Hurst]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 06:46:57 GMT</pubDate>
            <atom:updated>2023-01-12T22:37:54.810Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://openai.com/api/">GPT-3</a> is a large language model that is very capable of writing short form responses. Discussion posts are a common weekly assignment in many college courses. <strong>With the right prompting, GPT-3 can be used to solve these assignments in minutes.</strong></p><p>Here’s an example discussion question.</p><blockquote>“What are the most pressing environmental issues facing our planet today, and what steps can individuals take to help address these issues?”</blockquote><p>A prompt is the actual input to GPT-3 and can include instructions, context, and anything else. We can turn this into a simple prompt for GPT3 by prepending the instructions, “Respond to the following:” to it.</p><pre><strong>Respond to the following:<br></strong>What are the most pressing environmental issues facing our planet today, and what steps can individuals take to help address these issues?</pre><p>View outputs to this prompt in the video below. The outputs generated with this prompt aren’t consistent and a few are only a sentence or two. These results aren’t ideal. A good prompt should give <strong>specific instructions about format and content</strong>. You want to remove ambiguity in your language to improve consistency and quality. Here is a better prompt.</p><pre><strong>Write a highly detailed essay with introduction, body, and conclusion paragraphs responding to the following:<br></strong>What are the most pressing environmental issues facing our planet today, and what steps can individuals take to help address these issues?</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F778327269%3Fh%3D77d739ae72%26app_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F778327269&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1562033402-966c8cadf30910583cba070ab18caef3576d9a9c04b573439c2f93c9d29b92e5-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1105" frameborder="0" scrolling="no"><a href="https://medium.com/media/49da1dcae53114a16d8cb9ba579ba649/href">https://medium.com/media/49da1dcae53114a16d8cb9ba579ba649/href</a></iframe><p>The second prompt generates longer outputs with better structure on average. The use of the term ‘essay’ in the prompt was intentional, as GPT-3 can comprehend the definition of an essay and is thus more likely to generate coherent, structured responses.</p><h3>Many discussion questions suck for prompting.</h3><blockquote>“The Civil War a conflict over expansion? Agree our Disagree and why?”</blockquote><p>Here is a real discussion question from a college history course. It is not worded correctly and far too open ended. <strong>To get good discussion responses you need to rewrite the question into a well defined prompt.</strong> A well defined prompt for the discussion question above could be:</p><blockquote>“Explain the causes of the Civil War and whether expansion played a role in the conflict. Include evidence to support your argument.”</blockquote><p>Much better. Now we can add formatting and context directions.</p><pre><strong>Write a highly detailed discussion response, in the structure of an essay, responding to the following prompt:</strong><br>Expalin the causes of the Civil War and whether expansion played a role in the conflict. Include evidence to support your argument.</pre><h3>Automate well defined prompt rewriting with GPT3</h3><p>The rewriting example above was generated with OpenAI’s <a href="https://chat.openai.com/chat">ChatGPT</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJN15RMuw2Lu0r_cG_29pg.png" /><figcaption>chatGPT’s helpful response</figcaption></figure><h3>Iteration</h3><p>After crafting an effective prompt for your discussion question, you now need to refine the results GPT-3 generates. This may involve adjusting the output to adhere to constraints such as word count, or combining concepts from different generated results.</p><p>A simple method is to just generate a few outputs and select the parts of each that you like. A lot of times one of the outputs is sufficient in itself.</p><p>Another way to iterate is to start and then <strong>expand step by step</strong>. This requires more than one prompt: A starter prompt to write the initial paragraph or so and then other prompts to expand on what was already written.</p><p>Here is a potential philosophical discussion question:</p><blockquote>“Is math invented or discovered? Use careful reasoning to explain your answer.”</blockquote><p>Add it into a start prompt like this:</p><pre><strong>Write a beginning paragraph responding to the following:</strong><br>Is math invented or discovered? Use careful reasoning to explain your answer</pre><p>I generated a few responses and found one I liked:</p><pre><em>There is much debate among philosophers and mathematicians as to whether math is invented or discovered. Some argue that mathematical concepts and principles exist independently of human minds and can therefore be considered as discovered rather than invented. For example, the concept of numbers, ratios, and geometric shapes are observed in the natural world and can be abstracted and studied in a systematic way.</em></pre><p>Pretty good start, I then followed up with an expansion prompt, using the output of the previous prompt:</p><pre><strong>I am writing a detailed short essay responding to the following prompt:</strong> <br>Is math invented or discovered? Use careful reasoning to explain your answer. <br><br><strong>Here is what I have so far:</strong> There is much debate among philosophers and mathematicians as to whether math is invented or discovered. Some argue that mathematical concepts and principles exist independently of human minds and can therefore be considered as discovered rather than invented. For example, the concept of numbers, ratios, and geometric shapes are observed in the natural world and can be abstracted and studied in a systematic way. <br><br><strong>Write the next paragraph of my essay.</strong></pre><p>I generated a few expansions with this prompt and selected one I liked to end up with the following final result:</p><pre><em>There is much debate among philosophers and mathematicians as to whether math is invented or discovered. Some argue that mathematical concepts and principles exist independently of human minds and can therefore be considered as discovered rather than invented. For example, the concept of numbers, ratios, and geometric shapes are observed in the natural world and can be abstracted and studied in a systematic way.<br><br>On the other hand, some argue that math is largely an invention of the human mind. Mathematical principles are based on logical reasoning, which is a feature of the human mind. For instance, Euclidean geometry is based on abstract axioms and postulates, which are accepted as true without proof. As such, it can be argued that geometry is an invention of the human mind rather than a discovery. Similarly, mathematical formulas and equations are used to model and predict physical phenomena, which are again the result of human reasoning.</em></pre><p>Using expansion prompts, we can write more incrementally and iterate at each step. This is useful for when you need to <strong>produce a higher quality output and want to modify the incremental steps</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7069e8f418f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Windows API Hooking]]></title>
            <link>https://medium.com/geekculture/basic-windows-api-hooking-acb8d275e9b8?source=rss-b8f51d811181------2</link>
            <guid isPermaLink="false">https://medium.com/p/acb8d275e9b8</guid>
            <category><![CDATA[hooking]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[Jayson Hurst]]></dc:creator>
            <pubDate>Tue, 20 Jul 2021 03:05:18 GMT</pubDate>
            <atom:updated>2021-07-23T08:22:06.935Z</atom:updated>
            <content:encoded><![CDATA[<p>API hooking has been covered exhaustively over the past decade so this is my attempt at a logical tutorial for the reader and for the purpose of better understanding it myself. This is an important topic in the realm of malware, reverse engineering, and anything involving OS memory. When paired with process injection, hooking can either give an insight into what an executable attempts to do or maliciously intercept and alter any calls made to the WinAPI.</p><h4>Background</h4><p>I will be covering the popular technique of in-line hooking. This method simply attempts to replace the beginning few bytes of an exported function from a DLL loaded and used by the targeted executable/process. The overwrite will in some way jump to a memory location inside the process that you control. From there its up to you to decide what happens with the intercepted call. You could for example, hook CreateFile and once a call is intercepted, just drop it and return unsuccessfully. The effect in this example would be denying access to creating files, or if more targeted, denying access to only certain files.</p><p>Its easy to envision the usefulness of this powerful technique. There has been a lot of development using various hooking methods, including in game cheats, Anti-Virus/EDR, and malware. This guide is oriented for user-land hooking and seeks to provide you the core understanding of how it all works through a simple example.</p><h4>The Classic 5-Byte Hook</h4><p>We will be hooking the <a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messageboxa">MessageBoxA</a> function by replacing its first 5 bytes with a jmp instruction to our own function. The MessageBoxA function simply displays a pop up text box with a title and dialog. By hooking it we will be able to intercept calls and alter the arguments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*ZjcUeDy1fNd0KfxM.PNG" /></figure><p>Here I have disassembled user32.dll and found the function we would like to hook. The highlighted 5 bytes correspond to the assembly instructions directly to the right. This set of instructions is a fairly typical prologue found in many API functions.</p><p>By overwriting these first 5 bytes with a jmp instruction, we are redirecting execution to our own defined function. We will save the original bytes so that they can be referenced later when we want to pass execution back to the hooked function.</p><p>The jmp instruction is a relative jump to an offset starting from the next instruction’s address. The corresponding jmp opcode is E9 and it takes a 4 byte offset that we will need to calculate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/0*P2ntxJ78gmDvEtgX.PNG" /></figure><p>Lets first get the address of MessageBoxA in memory.</p><pre>// 1. get memory address of the MessageBoxA function from user32.dll <br>hinstLib= LoadLibraryA(TEXT(&quot;user32.dll&quot;));<br>function_address= GetProcAddress(hinstLib, &quot;MessageBoxA&quot;);</pre><p>We are using a technique called dynamic linking where we load the DLL that contains the function we want, using <a href="https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya">LoadLibraryA</a>. Then <a href="https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress">GetProcAddress</a> will give us the address of the function in memory. We can now save the first 5 bytes at the address we found into a buffer using <a href="https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-readprocessmemory">ReadProcessMemory</a>.</p><pre>// 2. save the first 5 bytes into saved_buffer<br>ReadProcessMemory(GetCurrentProcess(), function_address, saved_buffer, 5, NULL);</pre><p>Before we write our patch in, we need to calculate the offset (distance) from MessageBoxA to a proxy function that we will write in a sec. The jmp &lt;offset&gt; instruction will essentially move the instruction pointer (EIP) past the current instruction (5 bytes) and then add the offset: eip = eip + 5 + offset</p><p>Find the offset: offset = &lt;destination address&gt; - (&lt;source address&gt; + 5)</p><pre>proxy_address= &amp;proxy_function;<br>src= (DWORD)function_address + 5; <br>dst= (DWORD)proxy_address;<br>relative_offset= (DWORD *)(dst-src);</pre><p>Here is the complete implementation which then writes the patch to MessageBoxA in memory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c3430f5465dd9dd70b4cfaab39eba3c/href">https://medium.com/media/6c3430f5465dd9dd70b4cfaab39eba3c/href</a></iframe><p><em>*Quick note: WriteProcessMemory and ReadProcessMemory query the protections on the memory they are accessing and alter them accordingly. They really want you to succeed :)</em></p><p>The proxy function that we redirect execution to will need to accept the same parameters, have the same calling convention, and return the same type that MessageBoxA does.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed5b45e12023a6d028c0bcd9cca49e76/href">https://medium.com/media/ed5b45e12023a6d028c0bcd9cca49e76/href</a></iframe><p>Now we can print out the parameters meant for MessageBoxA, alter them, and then continue to the real MessageBoxA. If we just call MessageBoxA we will run into the hook again causing infinite recursion and a stack overflow. To prevent this we will first replace the bytes we overwrote with the original ones that were previously saved into a buffer.</p><p>This hook will only effect a call to MessageBoxA from within the same program. To tamper with another processes functions from imported DLLs would require injection, which will be covered in another article. View this example on <a href="https://github.com/jayo78/basic-hooking/blob/master/hook_v1.cpp">github</a>.</p><p>Since the proxy function re-writes the original bytes, which unhooks the function, we would need to continually hook MessageBoxA to intercept subsequent calls. Lets talk trampolines.</p><h4>Trampolines</h4><p>We can use a trampoline function to keep our hook intact while not causing infinite recursion. The trampoline’s job is to execute the original bytes from function that we hooked and then jump past the installed hook. We can call it from the proxy function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/0*m9P30k_8j7D6qZ9n.PNG" /></figure><p>By jumping 5 bytes past the original function’s address we are not executing the relative jmp to the proxy function, by passing the installed hook.</p><p>We are pushing the address of the hooked function + 5 and then using ret to jump to that address. These two instructions, which use a 4 byte address, total to 6 bytes. Our trampoline then will be 11 bytes. Lets build the trampoline by adding to the install_hook() function we already wrote.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49f9b4915252f5b82cea5638f66dc9ea/href">https://medium.com/media/49f9b4915252f5b82cea5638f66dc9ea/href</a></iframe><p>We first call <a href="https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc">VirtualAlloc</a> to allocate 11 bytes of memory. We need to specify the protection of this memory location as executable, readable, and writable. This will allow us to edit the allocated bytes and then later execute them. After writing the trampoline to memory we can call it from the proxy function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2edbcad91018bb179ce5b4b632a2e4c8/href">https://medium.com/media/2edbcad91018bb179ce5b4b632a2e4c8/href</a></iframe><p>View the full example on <a href="https://github.com/jayo78/basic-hooking/blob/master/hook_v2.cpp">github</a>. Please see <a href="http://jbremer.org/x86-api-hooking-demystified/">here</a> for more hooking examples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acb8d275e9b8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/basic-windows-api-hooking-acb8d275e9b8">Basic Windows API Hooking</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Reference Monitor]]></title>
            <link>https://medium.com/@jayo78/building-a-reference-monitor-9ae51513e148?source=rss-b8f51d811181------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ae51513e148</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[winapi]]></category>
            <category><![CDATA[process-injection]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[sandbox]]></category>
            <dc:creator><![CDATA[Jayson Hurst]]></dc:creator>
            <pubDate>Mon, 19 Jul 2021 18:01:29 GMT</pubDate>
            <atom:updated>2021-07-20T02:47:51.488Z</atom:updated>
            <content:encoded><![CDATA[<p>I will walk through creating a simple user-land program that is able to peek inside the functionality of a windows executable. It will do this by injecting code that installs inline API hooks to intercept and any calls made by an executable. These techniques are widely used to examine malicious programs dynamically or to ensure a secure execution environment when dealing with un-trusted users. Reference monitors are related to sandboxes because they control the environment a program executes in. The terms sandbox and reference monitor will be used interchangeably in this article.</p><h3>What is a reference monitor?</h3><p>A reference monitor is designed to examine the behavior of an executable and is largely used in Cybersecurity solutions for analyzing malware. There are a few open source projects like <a href="https://cuckoosandbox.org/">Cuckoo</a>.</p><p>The idea is to run a program in a controlled environment to see what it attempts to do. A native executable will need to reach out to the host operating system in order to have any functionality. For example, it might need to manipulate a file using the I/O functions or use sockets to connect to remote servers. In order to intercept these calls to the operating system, a monitor will need to sit in the middle of this communication.</p><p>Windows executables are compiled down to the binary <strong>PE file</strong> <a href="https://docs.microsoft.com/en-us/windows/win32/debug/pe-format">format</a>. The Windows API (win32 API) allows for user-land programs to interact with the Windows OS by providing functions in shared libraries called <em>Dynamically Linked Libraries</em>. When a program is executed, the OS maps it into memory where it now executes in a virtual address space with a bunch of essential DLLs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*7jasD6ImycyWjZ6iEJB2Cw.png" /></figure><p>This virtual address space is referred to as a process. Since every process essentially has their very own copy of Windows DLLs needed to execute, our sandbox will need to be injected into the executable’s process that we want to examine. Once injected the sandbox can insert changes known as <em>hooks</em> into the imported DLL functions that will now be used by the executable.</p><p>I will focus my attention on the actual implementation of injecting and installing hooks. There are extensive resources out there that do a better job than I would at explaining topics like processes, threads, OS internals, etc. I used many resources and I encourage the reader to extend their own research beyond this article where you find gaps in knowledge: <a href="http://www.binaryguard.com/bgc/malware/sandbox/2015/11/09/dissecting_inline_hooks.html">dissecting inline hooks</a>, <a href="http://jbremer.org/x86-api-hooking-demystified/">x86 api hooking demystified</a>, <a href="https://www.malwaretech.com/2015/01/inline-hooking-for-programmers-part-1.html">inline hooking for programmers</a>.</p><h3>Process Injection</h3><p>Processes are more than a space for a program to execute in. There is a lot of behind the scenes work done by the Windows OS in terms of the security of a program, communication with other processes, and access to shared resources. The birth of a process involves the mapping of a program’s memory on disk to virtual memory where it can begin executing. Windows separates address spaces using virtualization so they don’t bump into each other’s memory and so it can easily interface with each one individually — read <a href="https://answers.microsoft.com/en-us/windows/forum/windows_10-performance/physical-and-virtual-memory-in-windows-10/e36fb5bc-9ac8-49af-951c-e7d39b979938?auth=1">here</a>.</p><p>Knowing this OS functionality we can now begin looking at ways a process can access another processes memory using functions provided by the Windows API. I highly recommend checking out this <a href="https://www.elastic.co/blog/ten-process-injection-techniques-technical-survey-common-and-trending-process">post</a> on common process injection techniques. There are more in depth articles out there outlining many injection methods — see <a href="https://i.blackhat.com/USA-19/Thursday/us-19-Kotler-Process-Injection-Techniques-Gotta-Catch-Them-All-wp.pdf">here</a> — but for our sandbox we will be using <a href="http://blog.opensecurityresearch.com/2013/01/windows-dll-injection-basics.html">DLL injection</a>.</p><h3>The Injector</h3><p>Lets build our injector. It should be able to execute any program, enter its address space, and then install hooks.</p><p>We first need to open the executable we would like to examine, using <a href="https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa">CreateProcess</a>. This WinAPI function lets us create a child process in a suspended state, which will let us inject and install hooks before resuming its main thread. We can utilize <a href="https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread">CreateRemoteThread</a> and <a href="https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya">LoadLibraryA</a> to load our hooking DLL into the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*db_PEg16kfTjWqPImmyp2Q.png" /></figure><p>Here you can see the two components: the injector and the DLL that will be injected. The injector creates the process in suspended state and then starts a remote thread inside the new process. We can specify a function for the remote thread to execute. If we specify the function <a href="https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya">LoadLibrary</a> and pass it the path of a DLL, it will load that DLL into the address space. Perfect! So now we can specify the path of our own monitor DLL that can then start hooking functions from within the remote process. Lets look at the actual implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5333b110de4327b33a6dabb3c5daee8c/href">https://medium.com/media/5333b110de4327b33a6dabb3c5daee8c/href</a></iframe><p>The inject_DLL function is doing a lot of work here. It needs to take the path to our monitor DLL and inject code into the process we just opened that will actually load the monitor into the remote address space:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a30d61ba72aac7165e27018301ab957/href">https://medium.com/media/8a30d61ba72aac7165e27018301ab957/href</a></iframe><p>Alright when we create the remote thread in the process we want to inject we are only able to use resources from within its address space. We want access to LoadLibrary so we can load our DLL in. Thankfully LoadLibrary is exported by kernel32.dll (which is loaded into almost all user-land processes). LoadLibrary is loaded at the exact address in every process that imports kernel32. This means we can find its address in our current injector process, that also imports kernel32, and it’ll be in the same place in the remote process. Line 15 and 16 get its address.</p><p>We need to somehow pass LoadLibrary the path of our DLL as an argument. The issue is that the path is a string that isn’t in the remote process. We need to get it there. <a href="https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualallocex">VirtualAllocEx</a> will allocate read write memory in the remote process and <a href="https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-writeprocessmemory">WriteProcessMemory</a> will write to an address in a specific process. Convenient. We use these function to write the path string to the remote process’ memory.</p><p>We now have the address of LoadLibrary in the remote process and have written the argument we would like to pass to it as well. To finish off our injection we now use <a href="https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread">CreateRemoteThread</a> that lets us use the address of a function as a “start up routine.” The routine is basically just what the thread gets executed on. We specify the LoadLibrary address as our routine and also pass the address of the path that we wrote as a parameter to LoadLibrary. LoadLibrary will now execute in the remote process and load our DLL into memory. The DLL will execute, the remote thread will finish, and then the main thread can resume, now with any changes applied by our injected DLL.</p><h3>The Monitor</h3><p>I went over how to inject a DLL into a remote process, but then what? Well, once loaded into the remote process the DLL has access to all the WinAPI calls the process will use. We can intercept these calls and change the arguments sent and add logic that otherwise alters the behavior of the function. In this article we will just be intercepting the calls and printing out their arguments and then passing execution on to the original function. What I just described is known as hooking a function.</p><p>Since our injection method is DLL injection, our monitor will be written as a DLL. It will install hooks into common API calls once loaded into the remote process. Lets look at the common <a href="https://docs.microsoft.com/en-us/windows/win32/dlls/dllmain">DLL boilerplate</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bed9ab212b11039205e7dc9065b5c16/href">https://medium.com/media/0bed9ab212b11039205e7dc9065b5c16/href</a></iframe><p>DLLs can be attached to by a process and its threads in order to execute needed functionality, usually through an exported function. A normal use would be to call LoadLibrary on the DLL to get a handle and then GetProcAddress to find the desired exported function. The point of the switch cases, seen in DllMain, is so the DLL developer has a chance to set up structures/internals before an exported function is called. We won’t be exporting functions but will instead do our hooking from the entry point, which isn’t necessarily good <a href="https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices">practice</a>.</p><p>In the gist above we are installing a sample MessageBoxA hook when a process attaches to the DLL. This makes sense because remember our injector starts a thread in the remote process that then uses LoadLibrary to <em>attach</em> the remote process to the monitor DLL. Here is install_hook() :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/446fd27f4c645332903b5b2aedbb1a4a/href">https://medium.com/media/446fd27f4c645332903b5b2aedbb1a4a/href</a></iframe><p>There is a lot to unpack here. The hooking technique here is called inline hooking and it utilizes whats called a “trampoline.” I wrote a blog post on basic hooking so check that out for an in depth explanation. The basic gist is that we are overwriting the memory at the function we would like to hook. The overwrite contains instructions for a jump to a proxy function in memory we control (the injected DLL). This proxy function is where we can modify elements of the original function. We need a trampoline because if we want to pass execution back to the original function we need to bypass the original bytes our hook overwrote. Here is an example proxy function for MessageBoxA. It will take the arguments and alter them to print “yeet” instead of what text was originally given. The trampoline_address will be populated by inject_hook() before the proxy function is ever called.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3509dade11088dc4e99de6f0417f1439/href">https://medium.com/media/3509dade11088dc4e99de6f0417f1439/href</a></iframe><p>Recap: The target process has been injected with our injector, our DLL has executed in the remote process and the hooks installed. Lets make a simple test target executable:</p><pre>#include &lt;windows.h&gt;<br>#pragma comment(lib,&quot;user32.lib&quot;)<br>int main()<br>{<br>    MessageBoxA(NULL, &quot;hello&quot;, &quot;hello&quot;, MB_OK);<br>}</pre><p>To start injecting stuff we first need to compile our DLL code into an actual DLL. DLLs (.dll files) are similar to EXEs (.exe files), the difference is DLLs are meant to be shared. I used Microsoft’s compiler, <a href="https://docs.microsoft.com/en-us/cpp/build/reference/compiler-options?view=msvc-160&amp;viewFallbackFrom=vs-2019">MSVC</a> from the <a href="https://docs.microsoft.com/en-us/cpp/build/building-on-the-command-line?view=msvc-160&amp;viewFallbackFrom=vs-2019">command line</a> specifying the /LD option. Alternatively check this <a href="https://docs.microsoft.com/en-us/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp?view=msvc-160">article</a> out by Microsoft.</p><p>After compiling both your monitor DLL and injector, use the injector (injector.exe) like so: injector.exe &lt;test.exe&gt; &lt;path to DLL&gt;. View the injector and DLL code on <a href="https://github.com/jayo78/basic-hooking/tree/master/injection">github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ae51513e148" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>