Tuesday, January 29, 2013

Attributing Potentially Malicious URLs - Part 2

by Tony Lee.

This is the second part of a three part series covering how to handle potentially malicious URLs and IP addresses without getting burned by directly communicating with them. We'll cover various online resources and let you know which ones are our favorites and a little context around why we like them. In Part 1, Deobfuscating Potentially Malicious URLs, we laid the groundwork by covering policy, unshortening and deobfuscation. In Part 2 (Attributing Potentially Malicious URLs) we'll continue with WHOIS, GeoIP, and IP to URL.

Outline

  • WHOIS
  • Automatic Safe Deconstruction
  • GeoIP
  • IP to URL
  • Conclusion

First Get Permission If Needed

I won't force you to re-read this section but take this seriously and see the section of the same title in the First Article.

WHOIS

The WHOIS protocol is used to query databases that contain registration information for domains and IP addresses. WHOIS can often be used to provide attribution to a suspected malicious site—especially when the reverse DNS record is not populated or not very helpful. Even though there are WHOIS privacy companies that shield this information for a fee, it is still worth the few seconds to look up the data. It is also important to note that legitimate/large companies will not hide their registration information, so it will be easy to eliminate them from a list of IP addresses.

For the *Nix geeks out there, the command line whois works great. However, for some, a *Nix box is not always immediately available while these sites are always available if you have Internet access.

We observed over time, that when a particular WHOIS service becomes very popular, the hosting company attempts to monetize it by limiting queries to a few per day unless you pay a subscription. Additionally, the service may be abused by people scripting lookups which causes the WHOIS service provider to add a captcha to the site. Our favorite third party WHOIS services listed below are free and do not require CAPTCHAs:

DomainTools

The WHOIS functionality is free on DomainTools, however just about every other feature is a paid report or subscription. This site is still good at performing WHOIS queries because it accepts both IP and domain names in the same box as well as provides a screenshot of the site.



WHOis.net

Whois.net does a great job and accepts both IPs and domain names in the search box. This service also provides the registrar chain needed to obtain the authoritative answer.



GeoIP

GeoIP (also called geolocation) is the mapping of a physical geographic location to other identifiers—in this case an IP address. It is useful to combine this data with WHOIS information in order to gain more context around a suspicious host. Keep in mind though that all of the sites have a disclaimer pertaining to the accuracy of their data because the sites will not always be exactly correct. Take a look at whatismyipaddress’ disclaimer:

Geolocation technology can never be 100% accurate in providing the location of an IP address. When the IP address is a proxy server and it does not expose the user's IP address it is virtually impossible to locate the user. The country accuracy is estimated at about 99%. For IP addresses in the United States, it is 90% accurate on the state level, and 81% accurate within a 25 mile radius. Our world-wide users indicate 55% accurate within 25km.


Source: http://whatismyipaddress.com/ip-lookup

You will even find instances where multiple GeoIP data services will not coincide with one another. The reason for this appears to be that some services may fall back on WHOIS registration information if no other intelligence is available to them. Other, less reliable services seem to solely use the WHOIS information. We have outlined our favorite GeoIP Location services below with our reasons why they earned top picks:

IPLocation

The reason why we like IPLocation the best is because it sources data from three different GeoIP databases: IP2Location, IPligence, and MaxMind. Ironically, if you navigate directly to MaxMind, they cap your queries to only 25 per day. IPlocation does not seem to limit daily queries. From experience, it appears that MaxMind is more accurate than IP2Location and IPligence. For the example IP below, MaxMind’s results are only 5.1 miles away from the actual address.



whatsmyipaddress

We like whatsmyipaddress because it appears to be accurate and often coincides with or is very similar to MaxMind’s results. They also include a map of the area for convenience. In a real-world test, Whatsmyipaddress was only 5.5 miles away from the actual address (we used http://itouchmap.com/latlong.html to convert the lat/long coordinates into an address on Google maps).



Geobytes

Geobytes is another excellent service that provides a map and even a certainty rating along with longitude and latitude coordinates. When these coordinates are plugged into http://itouchmap.com/latlong.html, it shows that geobytes is only 2.4 miles off target. That is incredibly impressive.



IP to URL

The HTTP 1.1 protocol allows multiple websites to be hosted on a single IP address. Our goal in this process is to go from IP address back to the URL (domain), but notice that we did not call this section reverse DNS lookup... You will most commonly see this service called reverse IP lookup, however it is also called shared hosting lookup and a few other names as well. There are a handful of sites that provide this service, but why do these services even exist? Why can’t we just utilize DNS?

The problem is reverse DNS lookups will usually just result to a one to one, IP to hostname result.

For example: A reverse DNS lookup on a GoDaddy shared hosting server at 184.168.193.112 yields p3nw8sh246.shr.prod.phx3.secureserver.net. That is great, however there are probably close to 500 domains being hosted on this one server. There may times when you have an IP, but may be lacking a domain name—to make matters worse a reverse DNS record either doesn’t exist or is unhelpful as shown above. At this point of desperation, use one of the sites we have listed below to go from IP to hopefully a small amount of domains/URLs:

Using 161.69.13.43 (foundstone.com) as an example, we notice that there is no reverse DNS record—thus we must use reverse IP.

DomainTools Reverse IP

DomainTools does it again with a very useful and free service. They will provide up to 2000 virtual addresses on a single host. They also accept either an IP address or domain name.



Bing Search engine "ip:"

One under publicized feature of Bing is their ability to go from IP address to URL. Be warned though, if it is a hosting provider such as GoDaddy, you may have hundreds of sites hosted at a single URL. If the IP is a medium or large site, a reverse IP lookup will result in only a couple of hits.



Robtex

Robtex is an excellent multi-purpose online research tool. Just enter the IP address in the top left hand corner and click the “Lucky” button you will often be presented with lots of context around that IP address or hostname—including shared virtual addresses. Larger sites work better within Robtex and other tools—see the foundstone.com example below:



Using Robtex on the GoDaddy address above, shows that it will handle up to 100 share virtual addresses (a far cry from the 2000 from DomainTools—but still useful on larger domains):



Having multiple resources is always beneficial just in case one disappears or becomes a paid service.

Conclusion

In this article we examined a number of free sites to perform WHOIS, GeoIP location, and reverse IP queries. All of these services can be very useful in eliminating or determining attribution of suspicious URLs and IP addresses. Many of the sites expose an API for automated queries. The list that we provided here is not intended to be all encompassing. However, Googling for these sites does not always provide the best option either. Thus, if you have a favorite gem that was not included in this article please feel free to share it below—we are interested in your experiences as well. :)

Acknowledgements

Thanks goes out to Vimal Navis of McAfee and Drew Thompson of Foundstone for recommending some of these great third party resources.

Tuesday, January 22, 2013

Deobfuscating Potentially Malicious URLs - Part 1 Solution

a.k.a Fun with Google Redirects



By Tony Lee.

Hopefully you read last week’s blog post titled Deobfuscating Potentially Malicious URLs - Part 1 . In that article, we left you with a little challenge. We wanted to know what would happen if a user clicked the special link that we created (shown below)—however there is a caveat, you must figure out what happens without directly navigating to the site! Here's the link:

This means using your investigative skills and third party websites to reverse the link. So, if you have not taken the time to challenge yourself in reversing the link—please do so now. This article will spoil the fun by explaining what the link is, how we created it, how we would safely deconstruct it, how different browsers react, and how this was leveraged for fun to educate students about the danger of URL redirects.

Outline

  • Manual Safe Deconstruction
  • Automatic Safe Deconstruction
  • Obfuscation Process
  • Tracing the Click
  • Browser Compatibility
  • Real World Usage
  • Conclusion

Manual Safe Deconstruction

There plenty of methods we could have used to properly deconstruct this URL without risking our computer's health by clicking on the link. First, we can manually deobfuscate the URL using many of the sites we mentioned in last week's article. The general steps for this are:

  1. Unshorten the URL
  2. Discard URL trickery
  3. Convert Octal to Decimal
  4. URL decode
  5. WHOIS attribution


Unshorten the URL

For this step, we use one of the URL shorteners called tinyurlchecker. The following site did reverse our URL.



The result of the unshorten is getting back the monstrosity URL below:

 http://225.116.453.0-bank-login.htm@00000112.00000175.00000203.00000151/%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



Discard URL Trickery

The next step is simplifying the URL. Remember, we can remove anything from the http:// up to and including the '@'. For example, '225.116.453.0-bank-login.htm' in the following:

  • http://225.116.453.0-bank-login.htm@

This now yields:

 http://00000112.00000175.00000203.00000151/%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



Convert Octal to Decimal

Let's now convert those octals to dotted decimal so we can figure out the first site we are visiting. Octal to dotted decimal conversion can be accomplished by converting each octal separately (Microsoft calc in programmer mode is very useful for this task):

 Address: http://00000112.00000175.00000203.00000151 

Convert:  00000112 = 74    00000175 = 125     00000203 = 131    00000151 = 105

Becomes:  http://74.125.131.105



So now we have:

 http://74.125.131.105/%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



URL decode

As you can see, the URL above has a fair amount of encoding at the end which prevents us from easily viewing the intention of the URL. We can use a URL Decoder to decode the URL (discussed last week).

 /%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



When decoded, becomes:

 /url?sa=t&url=http://www.youtube.com/watch?v%3DoHg5SJYRHA0





After substitution we now we have:

 http://74.125.131.105/url?sa=t&url=http://www.youtube.com/watch?v%3DoHg5SJYRHA0



So now we know that the redirect is to youtube. But what is the target within youtube? When googling the last portion oHg5SJYRHA0, the first link is to Rick Roll'D.

But we still do not know who is redirecting the victim-we need to figure out who owns the IP address. Both reverse DNS lookup or WHOIS queries could reveal a little about the owner of the site. However, when trying to perform a reverse DNS lookup, it was less than helpful returning: vc-in-f105.1e100.net. Thus, for this we will try a WHOIS service.

WHOIS attribution

We will briefly discuss WHOIS in the next article; however, one of our favorites is DomainTools' WHOIS service. WHOIS records show that the site is registered to Google-which hosts the redirect.


Using manual analysis, we have all of the pieces of information needed to put together the events of this attack. The most succinct description is a Google URL redirect to a Rick Roll YouTube video that has been URL encoded, represented as Octal, with fake authentication wrapped in a TinyURL.

Automatic Safe Deconstruction

The manual deconstruction process discussed above obviously takes a decent amount of time and effort. However, there are a few sites that deserve recognition for being able to cut through the layers of obfuscation to shorten the analysis time. Some sites were good at providing the end results, others were better at breaking down the URL. Our favorites are below:

LongURL

In this example, LongURL took top honors because it provided at least one of the intermediate URLs and was able to go from shortened URL to the rick roll site (even providing the title of the page).



Unshorten.it

While unshorten.it did not provide any of the intermediate URLs, it did gracefully resolve the target completely and provided the title of the site.



Netdemon

While Netdemon could not get past the URLshortener, once the longer URL was entered, it performed best at breaking down the URL components.

 http://225.116.453.0-bank-login.htm@00000112.00000175.00000203.00000151/%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



As a result, netdemon was able to URL decode, remove the URL trickery, convert octal to dotted decimal, and pick out the URL parameters that was passed to Google. Its WHOIS could perform better though and provide more information without hitting a third party site. Still, overall it was very useful.



The point is that by using just a couple of automated sites, you can easily obtain every piece of critical data in a much shorter period of time than if you did this manually.

Obfuscation Process

To make this a somewhat challenging process, we incorporated a number of the techniques described in the last article. Here they are:

  • URL Redirection
  • Octal IP Representation
  • URL Encoding
  • URL Trickery
  • URL Shortening


URL Redirection

The only technique above that we did not mention in the previous article was URL redirects because we did not want to spoil the challenge. In very simplistic terms, a URL redirect is an application that accepts a parameter that allows the end user to be redirected to another page. This is a lot of fun for the attacker because it happens so quickly that the user does not have time to react and stop the next page from loading (thus when you see Rick dancing—evil has prevailed—mission accomplished!). URL redirects also allow the attacker to leverage the good name and reputation of the vulnerable site which helps the credibility of the link (as you will see in our example later). As a result, combine the fast nature of the redirect and the credibility leveraged and you get the perfect storm for a phish.

A simple example of a URL redirect:

  • http://www.vulnerablesite.com?URL=http://www.attacker.com


The user will in fact go to vulnerablesite.com first; however they will then be whisked away to attacker.com where the bad guy will most likely serve up malware, clone a page, or perform some other evil deeds.

The first challenge that the attacker faces is finding (or maybe hosting) a page that has a redirect to confuse the user. From an attacker’s point of view, it is best to leverage someone else’s page in order to leverage their credibility, but also to distance them from the attack.

The URL redirect we used in our special link is against Google (with their gracious permission for educational purposes):



That link will first take you to Google and then to YouTube for the Rick Roll (see the Fiddler proxy screenshot below to see how the attack works).



  • Step 1 - Initial request to the vulnerable web server with the parameter that will cause the redirect.
  • Step 2 - Response from the web server with a “Location” header that points to the site specified in the URL parameter in Step 1
  • Step 3 - User's browser following the direction of the vulnerable webserver by visiting the new Location specified in the response header


Octal IP Representation

There wasn't a particular reason to choose Octal other then to add an additional layer of difficulty to the challenge. The technique was covered in detail in our last post so we'll keep it short and sweet here.

  1. nslookup www.google.com resolved one of Google's web servers to 74.125.131.105.
  2. Using Microsoft's Calculator, we converted the IP address - 74 = 0112 125 = 0175 131 = 0203 105 = 0151.
  3. After adding some zero padding (any number of zeros can be used), we come up with http://00000112.00000175.00000203.00000151
  4. Replace "www.google.com" in our redirect URL


Here's our new URL:
 http://00000112.00000175.00000203.00000151/url?sa=t&url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoHg5SJYRHA0



URL Encoding

To further obfuscate, we URL encoded the parameters as follows:

ASCII URL Encoded
url %75%72%6C
sa %73%61
t %74
http %68%74%74%70
www.youtube.com %77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D
watch %77%61%74%63%68
DoHg5SJYRHA0 %44%6F%48%67%35%53%4A%59%52%48%41%30
When substituting the URL encoded characters above you go from:
 http://00000112.00000175.00000203.00000151/url?sa=t&url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoHg5SJYRHA0



To
 http://00000112.00000175.00000203.00000151/%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



URL trickery

As we saw last week, Chrome is the only browser that will send the user to the destination page without a warning when the URL is formatted as follows:

  • http://www.bank.com:login.html@google.com/


Thus, an attacker may not want to use this obfuscation unless they know they are targeting a Chrome audience. However, for your enjoyment, let's do it!!

 http://00000112.00000175.00000203.00000151/%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



becomes:

 http://225.116.453.0-bank-login.htm@00000112.00000175.00000203.00000151/%75%72%6C?%73%61=%74&%75%72%6C=%68%74%74%70%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2F%77%61%74%63%68%3Fv%3%44%6F%48%67%35%53%4A%59%52%48%41%30



Try it out in Chrome if you have it installed. Smooth as butter. IE will not work and Firefox prompts the user to confirm :( Ok, on to the last step!

URL Shortening

One last step for the obfuscation challenge is to take that monstrosity of a URL and shorten it with your favorite shortener. We used TinyUrl because it allows us to specify a memorable link such as TonysChallenge.



Tracing The Click

Do what does the traffic look like on this craziness when clicked? Take a look at the screenshot below for step by step explanation:



  • Step 1 - The user's browser initially hits TinyURL to unshorten the URL to the URL trickery address.
  • Step 2 - The browser removes the authentication piece and then navigates to the octal address with the URL parameter in place
  • Step 3 - The octal address resolves to Google and then Google responds with a Location header to redirect the user to Youtube goodness.
  • Step 4 - User follows the location header to Youtube for that final moment of realization where it is too late to take back their actions.


Browser Compatibility

As mentioned earlier, using IE on this link would not even work due to the URL authentication being removed from IE 7 and later. Using Firefox would prompt the user and potentially ruin a good opportunity for an attacker. Chrome on the other hand would have worked beautifully.

But think about this: Why would we want to use TinyURL when the site we were using as a redirector is Google?

Answer: We probably don't. If we keep the URL the way it is we leverage the reputation and credibility that Google has that they won't exploit users. Thus, see the following real world example that worked beautifully.

Real World Usage

The following is a real world example; however the name has been changed to protect the identity of the student. The date is real though-almost two years ago! :O

-----Original Message-----
From: John XXXXXX
Sent: Wednesday, February XX, 2011 7:59 AM
To: Lee, Anthony
Subject: late in today
Hi Tony.
Im in your web hacking class which started yesterday. Just letting you know ill be in late today - between 10 and 11.
Thanks,
John XXXXX




What in the world is someone supposed to do with that email? Here is one possible response (notice the similarity in the URL?) (evil laugh):

From: Lee, Anthony
Sent: Wednesday, February XX, 2011 11:21 AM
To: John
Subject: AUTORESPOND: late in today

Thank you for contacting the mailbox of Tony Lee. Due to increased spam from Google mail addresses, this mailbox uses Google mail authentication. Please click the following link to ensure your Google mail is authenticated and routed properly:

http://www.google.com/url?sa=t&source=web&cd=1&ved=0CB8QtwIwAA&url=http%3A%2F%2F%77%77%77%2E%79%6F%75%74%75%62%65%2E%63%6F%6D%2Fwatch%3Fv%3DoHg5SJYRHA0&rct=j&q=%72%69%63%6B%20%72%6F%6C%6C&ei=WPVbTaanApKwhAeSztSFDQ&usg=AFQjCNEcy3X8QxEz3ZqmxAznmt4YfNijBQ&sig2=20gwDFO8tMFtx6qEQyNSAg&cad=rja

Thank you

Tony Lee
[Removed signature block]

This email may contain confidential and privileged information for the sole use of the intended recipient. Any review or distribution by others is strictly prohibited. If you are not the intended recipient, please contact the sender and delete all copies. Thank you.




What do you think someone does when they receive this link? Well, they want their email to be routed properly and it is coming from google.com. There are no URL authentication tricks there, just a long URL. So they click it of course! Pure evil >:) But insanely funny. It helps students remember to be careful with URLs in emails.

Conclusion

We hope you had fun with the challenge and got to experiment with a few sites that will help you reverse potentially malicious URLs. Additionally, you should understand more about possible obfuscation techniques and as a bonus, now have a good way to Rick Roll your closest friends. :) Please make sure you visit us for more fun at:



Also, let us know in the comments below if you came up with a better way to safely deconstruct the URL. :) Have fun and happy hacking! (Thanks again to Google for letting us use this as a teaching aide)

Thursday, January 17, 2013

Getting Started With Lock Picking

By Jason Bevis and Brad Antoniewicz.



Lock picking is a hobby I first picked up many years ago and seem to always regain interest in. There's just something about being able to open a lock without a key that calls to my inner hacker. This article is for those who are interested in getting started with lock picking but aren't entirely sure where to begin.

The Tools

Like most hobbies, you'll need to invest a couple dollars in some tools and equipment. The lock pick villages at security conferences are a great place to pick up equipment. The Open Organization Of Lockpickers (ToooL) are always there and have awesome kits available for purchase. Here are some buying recommendations when you're first starting out. ToooL is recommended a lot because they are big supporters of the community, that being said, I promise, I'm not funded by them and their tools are good :)

Picks

ToooL's Beginner's Blend Pick Kit will run you $30.00. It contains the following:
  1. Standard Hook
  2. Euro Slim Hook
  3. Thick Half Diamond
  4. Thin Half Diamond
  5. Snake Rake
  6. Bogotá-style Wave Jiggler Rake
  7. Standard Tensioner
  8. Twist-Flex Tensioner


While the tension tools in ToooL's set are great to start off with, also look into the "Pry Bar" Tension tools offered by Peterson. They're unique in that they allow you to apply tension on the top of the keyhole rather then on the bottom which can get in the way.


It just wouldn't be right to leave out SouthOrd's 14 Piece MPXS-14 kit. It was one of the first sets I ever bought and has lasted me for years!

Locks

Practicing is really important, but if you're always practicing on the same lock, you won't really advance; so its equally important to learn different locks. Some require little or no tension whereas others require a significant amount of tension. Here are a couple to get you going:

ToooL's Basic Training Lock Set is $80.00. It will probably only take about 10 minutes to pick all 6 of the training locks even without any real training. Although it may seem at first seems there is little value in purchasing this training set, most people going back to these locks for practice.
ToooL's Advanced Training Lock Set is $55.00. It includes lock cylinders with 4 different security pins (mushroom, spool, etc.). Buying these is a luxury, but having a chance to go through all 4 locks is beneficial. It should take less than 5 minutes because all the locks only have one pin. There is value in this set, but probably not worth the money initially. It is good to run through them at least once which you can almost always do at a lockpick village
Master Locks can be found anywhere. Basic ones such as the 4 pin are typically easy even for a beginner (scarey when you think of how many places use Master locks). These locks can be purchased at any hardware store, pharmacy, etc. Most master locks appear to be easy however sometimes there are different pin settings and locks that can be more difficult.
U.S. Lock an be purchased at most hardware stores, locksmiths or on the internet. The one in the picture is much more of a pain then the Master because it has one "difficult" pin that makes life hard when using the standard tension wrench in ToooL's 8 piece set.
The Schlage Everest with the check pin (the little hole on the rear of the lock shown in the picture) is indeed challenging for a beginner. You'll find some YouTube videos where it takes hardcore enthusiasts five minutes (that's a long time, for them) to get into it. This one is particular good because he takes apart the lock and explains the key difference. Also notice the special tool he created to help with the check pin.

If you find yourself encountering the Schlage Everest a lot, Peterson Locksmith Tools actually has a special tension tool just for these locks.


If you can get past the Schlage Everest then try a Medeco lock. Many of these are used for fireman lock boxes to gain access to multiple apartment building units. Notice the special keying in the image below (from http://brandysafe.com/Residential/medecoresdiagram.html). A local locksmith told me one cylinder would cost $80.00 and they're really hard to pick.


The Basics

There is a ton of online resources to help you understand how locks work and how to pick them. We've thrown together a quick demonstration of using the hook and rake to pick on the of ToooL starter locks.



Schuyler Towne put together a really great set of videos that'll teach you a lot - he even shows the internals of the lock as its being picked.

lockpicking101 is another great site for information and getting in touch with lock picking enthusiasts in your area.

The Law

Beware - Lock picking can be frowned upon by authorities. The two laws every lock picking enthusiast should follow are:
  1. Never pick a lock you don't own
  2. Never pick a lock that's in use
The Legality of lock picks, possessing burglary tools, lock picks by state article from The Lock Pick Guide attempts to summarize the U.S. laws of lock picking and is a must read if you plan on getting started with the hobby.

Lock picking is good to learn and understand how to protect items physically. Understanding how to Lockpick will help gain knowledge of the specific weaknesses.

Tuesday, January 15, 2013

Deobfuscating Potentially Malicious URLs - Part 1

By Tony Lee.

When investigating network security incidents, there are two artifacts of malicious activity that require a great deal of research: Suspicious sites and suspicious files. Obviously, the investigator should never directly navigate to potentially malicious sites or open suspicious files--just in case they turn out to be malicious. Thus, one potential solution is to use third party investigative sites on the Internet. But how many resources are there and which ones are the best? We have compiled a list of our favorites and a little context around why we like them. This article will begin the focus on investigating potentially malicious URLs and IP addresses—while the next series will focus on what to do with files and hashes.

Part I of Investigating URLs and IP Addresses lays the groundwork by covering policy, unshortening and deobfuscation. All of the techniques may not be new to you, but the sites to analyze them may be. There is also a really fun challenge for the reader at the end that will require them to utilize many of the tools in this article to investigate a URL.

Outline

  • First Get Permission If Needed
  • Unshortening
  • Obfuscating
    • URI Tricks
    • IP Obfuscation
    • URL Encoding
  • Deobfuscating
  • Conclusion
  • Challenge!


First Get Permission If Needed

Before we cover deobfuscating URLs, we need to talk a little bit about permission and policy. If you are like me, you are thinking "Shoot me now". However, you must make sure that you have written permission stating that you are allowed to query or upload information to a third party site. If done without permission it could cost you your job. But why, what’s the big deal anyway?

There are a number of potential problems when using third party sites for investigating potentially malicious activity, but here are two major issues:

  1. You don't always know if that data you are transmitting is sensitive
  2. There is no expectation of privacy when utilizing a third party site


If you are the security team or security consultant for a large company—it may be impossible to know all of the intricate facets of your company’s business. Thus, hostnames or IP addresses could be sensitive along with any parameters that may be passed. Additionally, PDFs, word documents, binaries and other acquired suspicious files could contain company or partner sensitive information. You do not want to accidentally leak any of this potentially proprietary or secret information to a third party organization outside the reach of your company’s NDA. Take a moment to read some of the privacy statements on these sites. Most of them state that they may publicly share the submitted data with the Internet or privately share the data with select security professionals. See below for just one example of an honest disclaimer:

Privacy Information

Do not submit items of a confidential or classified nature to this site. The private option on submissions indicates that it will not be released to the public and will not be made generally available. However, it may be shared with security researchers and trusted individuals whose goal is to improve detection of threats. The privacy of submissions depends upon the user keeping the "Submission Permanent Link" a secret, therefore do not post the link publicly if you want to keep it private.

If you need true privacy, you should run jsunpack-n, which is the engine behind jsunpack and it runs locally.

Thanks for using jsunpack!

Source: http://jsunpack.jeek.org/privacy.html

This site is very forthcoming about their privacy policy—so please be careful when submitting data to third party sites. Ensure that both URL/IP addresses and files/hashes are not sensitive to your organization before submitting to Internet resources. Ok, now on to the fun stuff!

Unshortening

I can’t tell you how many times I have seen a shortened URL in an email, instant message, or alert. Even if they are benign, they should invoke a little bit of fear in the hearts of security practitioners. What once started out as a convenient way to share links has over time become a dangerous way to spread malware and phish users. To make matters worse, there is no shortage of URL shorteners (forgive the pun). Here are just a small fraction of them:

TinyURL Tiny Bitly Google Shortener
Ow.ly Twitter Shortener is.gd McAfee Shortener


Let’s take the following (potentially dangerous) example:

Who in the world wants to click this thing? No one should have volunteered—however, I am sure you have some users out there (inside your network) that would gladly click it. Even worse… chances are that you know them by first name! The attacker will probably claim that it is a link to some dancing cat or a cat playing the piano. Bingo! They have a click. Anyway, as security professionals, what can we do to investigate this hyperlink? Here are a few really great Internet resources below that can help you reverse this URL to figure out where this link goes:

Unshorten.it

Unshorten.it goes above and beyond by providing the unshortened URL, title of the page, a screenshot, and the web of trusts rating. Outstanding!


LongURL

LongURL also provides a screenshot for their unshortened URLs (if they have it), resolves the links and provides a screenshot if it is available. They advertise a pretty large range of shortening services that they can process (340 in total!).



Unshort.me

Unshort.me is more basic than the two mentioned above, however it does the job well. They advertise the ability to unshorten “t.co (Twitter), bit.ly, TinyURL, Google goo.gl, Facebok fb.me, tr.im, Ow.ly and others”



Unshorten.com

Similar to Unshort.me, Unshorten.com is also pretty basic, but will unshorten URLs. They advertise the ability to unshorten “TinyURL.com, SnipURL.com, NotLong.com, Metamark.net, zURL.ws and many others.”



Whew!!! All sites were able to unshorten the example URL and their answers were all the same. We are fortunate that the link was only a link to the Wikipedia page on URL shortening. However, it could have easily been malicious and thus, we cannot take a chance by directly navigating to the shortened URL.

Obfuscating

So, maybe you unshortened the URL and it still looks suspicious or scary. This could be due to a number of reasons such as URI tricks or encoding/representation tricks.

URI tricks

The general URL format is:

 protocol://username:password@host:port/resource



Where username, password, and port are all optional. Knowing that, now evaluate the following “simple” examples:

  1. http://www.example.com/a/page.html
  2. https://www.attacker.com:8443/attackscript.js
  3. https://www.bank.com:login.html@phisher.cn/


** Spend a minute to figure out the URLs above before reading the spoiler below **

URL one is something that you would typically see. Nice, simple and easy to understand.

URL two is not much different; it just changes the port and makes a request to a javascript file—still easy to understand as a security professional.

URL three is not a new concept, but it is still used for deception. It illustrates how the flexibility in URI components could be potentially misused in order to confuse unsuspecting users. At first glance, it appears that we will be navigating to bank.com. Whew! No problem, we are a member of bank.com and that is normal. However, upon closer inspection (remembering the URL format), the username is www.bank.com with a password of login.html. The real request is going to phisher.cn! The key take-away here is that anything between the http:// and the @ symbol may be irrelevant to navigation and can be used to trick the user.

Let’s see how different browsers handle this third URL, but because we do not want to go to phisher.cn we will change it to go to Google instead:

  • http://www.bank.com:login.html@google.com/


Chrome v23

Chrome understood the URL and correctly sent us to Google per URI RFCs—but maybe a little too willing to do so. Read on for other behaviors.



Internet Explorer 8

Internet explorer 8 throws an error message as seen below:



But why? Does IE not know how to handle authentication in the URL? According to a Microsoft support article, this is expected behavior as this feature was available in IE v3.0 – v6.0, but has been disabled by default in all other versions due to the potential to trick a user with it—exactly what we are discussing here.

Firefox 17.0.1

In my opinion Firefox handled the situation the best. It understood how to process the URL, however it warned the user that they are visiting google.com and that the URL might be a trick. Then it prompted the user to confirm their intentions.



If you understood all of the above URL scenarios without any help—you did great! Especially since there don’t seem to be too many tools out there that will dissect the URL (more on this later). To add to the issue, obfuscation gets even more challenging to reverse when combined with various forms of legitimate, but alternative representations.

IP obfuscation

First, note that the URL does not have to be a typical easy to remember name, think http://www.google.com. It could be provided via IP address (known as dotted decimal), DWORD, Hex, or even Octal. Let’s re-visit the third example that we provided above, but make some slight modifications:

Note: At the time of this writing, one of Google’s IP addresses is 74.125.131.105

  • http://www.bank.com:login.html@74.125.131.105
  • http://www.bank.com:login.html@1249739625/
  • http://www.bank.com:login.html@0x4a.0x7d.0x83.0x69/
  • http://www.bank.com:login.html@0112.0175.0203.0151/

Does anyone want to volunteer to click any of those? Probably not without investigating it first…

So, we know the first part between the http:// and the @ is a trick and most likely irrelevant to navigation. But what is the second part? The first is an obvious IP address, however the last three are obfuscated IP addresses in DWORD, Hex, and Octal format respectively. Let’s look at how we get these values using Google as an example:

DWORD conversion

Converting an IP address to a DWORD is not difficult and can be performed with a calculator. Take an IP address and perform the following math on it:

 (((((74*256) + 125) * 256) + 131) * 256) + 105



This math yields: 1249739625
You can now use this in a URL, for example: http://1249739625

Another way to convert an IP to a DWORD is to first convert each octect to hex (Microsoft calc in programmer mode), squash them together and use a calculator to convert that to decimal:

 74 = 0x4a     125 = 0x7d     131=0x83      105=0x69    =>     0x4a7d8369 = 1249739625



Either one works just fine.

Hex conversion

Converting an IP address to hex is the same as the second DWORD method we used above. Convert each octet to hex (Reminder: Microsoft calc in programmer mode):

 74 = 0x4a     125 = 0x7d     131=0x83      105=0x69 



Now put them all together with a dot in between and you have your hex address: http://0x4a.0x7d.0x83.0x69

Octal conversion

IP to Octal conversion can be accomplished by converting each octet to octal (can still use Microsoft calc in programmer mode)

 74 = 0112    125 = 0175     131 = 0203    105 = 0151 



Make sure you have a leading zero on the digits as this conveys octal format. Any number of zeros can be used. Separate the numbers with a dot.

Result: http://0112.0175.0203.0151

For hex and octal conversions you will be able to easily reverse the math to get back to the IP address. However, if you are wondering how to reverse the DWORD, here is a quick trick. Take the DWORD address and copy and paste that value as a decimal in Microsoft’s calculator using programmer mode. Then click the radio button to convert the value to hex, you will then get: 4A7D8369 which should look similar to your Hex conversion above.

We will look at some tools that can automatically reverse these formats in a bit. However, it is good to note that all three browsers above (Chrome, Firefox, and IE) all handled each of the formats above as expected and provided Google’s search page. Firefox is shown below:


URL Encoding

Another common obfuscation technique used to confuse the victim is encoding the URL—this is legitimately used when transmitting non-ASCII reserved characters over the Internet. URI’s have reserved characters which are used for more than just their literal meaning. According to RFC 3986, these reserved characters are:
! * ` ( ) ; : @ & = + $ , / ? # [ ]


In order to avoid immediate interpretation, characters can be encoded so they can be included within a URL—each browser may handle this differently though. Take a look at the following example:

  • ftp://foo:foo%40example.com@ftp.example.com/pub/a.txt


This example has a password that utilizes percent-encoding (aka URL/URI encoding) as part of the FTP password (an email address). Characters can be encoded by using a percent sign followed by their equivalent hex value. The ‘@’ character is represented by the hex value of 0x40—thus %40 in a URI will be converted by the application to the ‘@’ character. This same technique can be used in URLs to confuse the user and hide intention.

Now that you understand how IP obfuscation and character encoding works, feel free to use a character encoding and IP obfuscation calculator provided by RSnake to create your own links.

Real World Example

So the examples above are intended to be easy for demonstration purposes—but how about something harder?

  • http://225.116.453.0-bank-login.htm@00000112.00000175.00000203.00000151


This example is using the same tricks outlined above, but we are combining them to make the URL look more interesting. These can still be done by hand, but can be time consuming. Luckily, there are some third-party sites that will help you figure out what the URL is doing. Some are more advanced than others.

Netdemon

Netdemon definitely takes top honors in terms of decoding and breaking down a malicious URL. You can see in the example below, it was able to pick out the username, path, and file, as well as reverse the IP address. We have even seen it detect and report redirecting which is pretty impressive. Most tools are limited to just percent decoding when this goes above and beyond.



URL decoder

I like this encoder/decoder because it is simple and fast. The only downside is that it does not do very complex evaluations. It only encodes and decodes based on percent encoding/decoding.

Try to decode the following example:

  • %54%68%69%73%2B%69%73%2B%61%2B%73%65%63%72%65%74%2B%6D%65%73%73%61%67%65




Conclusion

In order to attribute a URL to an attacker, occasionally you must first understand how it is encoded and obfuscated. Hopefully this quick refresher has helped you to brush up on your obfuscation knowledge so you are now more proficient at deobfuscation. Additionally, we mentioned a handful of sites that can be very helpful when quickly processing a bunch of links. We understand that this is not an all-encompassing list and would love to hear about your favorite sites. Stay tuned for the rest of “Investigating URLs and IP Addresses” where we will cover the remaining topics including WHOIS, GeoIP, IP to URL, Reputation and evaluating content. That said… we leave you with this challenge.

Challenge

Evaluate the following URL without visiting it. Utilize on-line tools to figure out what the outcome of a click will be:

(Hint: The URL is most “enjoyable” when visited within Chrome— but don’t just click it… Reverse it first!)

We will provide the answer, how we created the link, and how we would reverse the link in next week’s blog post. Have fun. :)


Tuesday, January 8, 2013

Windows DLL Injection Basics

By Brad Antoniewicz.

DLL Injection is one of those things I've always sort of knew about but never actually implemented. Probably because I never *really* needed to. I'm not a big gamer and not really into the malware side of security. Actually, the only times I ever need to inject into a running process is during exploitation/post exploitation and Metasploit has spoiled me too much :)

So, early last week I decided to actually implement some of the well known Windows DLL injection techniques to keep my mind at ease. Hopefully this blog will get you accustomed to those techniques and maybe inspire you to implement them on your own.

Defined

DLL injection is the process of inserting code into a running process. The code we usually insert is in the form of a dynamic link library (DLL), since DLLs are meant to be loaded as needed at run time. However this doesn't mean we cannot inject assembly in any other form (executables, handwritten, etc..). It's important to note that you'll need to have an appropriate level of privileges on the system to start playing with other program's memory.

Overview

The Windows API actually offers a number of functions that allow us to attach and manipulate into other programs for debugging purposes. We'll leverage these methods to perform our DLL Injection. I've broken down DLL injection into four steps:
  1. Attach to the process
  2. Allocate Memory within the process
  3. Copy the DLL or the DLL Path into the processes memory and determine appropriate memory addresses
  4. Instruct the process to Execute your DLL

Each one of these steps can be accomplished through the use of one or more programming techniques which are summarized in the below graphic. It's important to understand the details/options present for each technique as they all have their positives and negatives.



Execution Starting Point

We have a couple of options (e.g. CreateRemoteThread(),NtCreateThreadEx(), etc...) when instructing the target process to launch our DLL. Unfortunately we can't just provide the name of our DLL to these functions, instead we have to provide a memory address to start execution at. We perform the Allocate and Copy steps to obtain space within the target process' memory and prepare it as an execution starting point.

There are two popular starting points: LoadLibraryA() and jumping to DllMain.

LoadLibraryA()

LoadLibraryA() is a kernel32.dll function used to load DLLs, executables, and other supporting libraries at run time. It takes a filename as its only parameter and magically makes everything work. This means that we just need to allocate some memory for the path to our DLL and set our execution starting point to the address of LoadLibraryA(), providing the memory address where the path lies as a parameter.

The major downside to LoadLibraryA() is that it registers the loaded DLL with the program and thus can be easily detected. Another slightly annoying caveat is that if a DLL has already been loaded once with LoadLibraryA(), it will not execute it. You can work around this issue but it's more code.

Jumping to DllMain (or another entry point)

An alternative method to LoadLibraryA() is load the entire DLL into memory, then determine the offset to the DLL's entry point. Using this method you can avoid registering the DLL with the program (stealthy) and repeatedly inject into a process.

Attaching to the Process




First we'll need a handle to the process so that we can interact with it. This is done with the OpenProcess() function. We'll also need request certain access rights in order for us to perform the tasks below. The specific access rights we request vary across Windows versions, however the following should work for most:


hHandle = OpenProcess( PROCESS_CREATE_THREAD | 
                       PROCESS_QUERY_INFORMATION | 
                       PROCESS_VM_OPERATION | 
                       PROCESS_VM_WRITE | 
                       PROCESS_VM_READ, 
                       FALSE, 
                       procID );


Allocating Memory




Before we can inject anything into another process, we'll need a place to put it. We'll use the VirtualAllocEx() function to do so.

VirtualAllocEx() takes amount of memory to allocate as one of its parameters. If we use LoadLibraryA(), we'll allocate space for the full path of the DLL and if we jump to the DllMain, we'll allocate space for the DLL's full contents.

DLL Path

Allocating space for just the DLL path slightly reduces the amount of code you'll need to write but not by much. It also requires you to use the LoadLibraryA() method which has some downsides (described above). That being said, it is a very popular method.

Use VirtualAllocEx() and allocate enough memory to support a string which contains the path to the DLL:


GetFullPathName(TEXT("somedll.dll"), 
                BUFSIZE, 
                dllPath, //Output to save the full DLL path
                NULL);

dllPathAddr = VirtualAllocEx(hHandle, 
                             0, 
                             strlen(dllPath), 
                             MEM_RESERVE|MEM_COMMIT, 
                             PAGE_EXECUTE_READWRITE);


Full DLL

Allocating space for the full DLL requires a little more code however it's also much more reliable and doesn't need to use LoadLibraryA().

First, open a handle to the DLL with CreateFileA() then calculate its size with GetFileSize() and pass it to VirtualAllocEx():


GetFullPathName(TEXT("somedll.dll"), 
                BUFSIZE, 
                dllPath, //Output to save the full DLL path
                NULL);

hFile = CreateFileA( dllPath, 
                     GENERIC_READ, 
                     0, 
                     NULL, 
                     OPEN_EXISTING, 
                     FILE_ATTRIBUTE_NORMAL, 
                     NULL );

dllFileLength = GetFileSize( hFile, 
                             NULL );

remoteDllAddr = VirtualAllocEx( hProcess, 
                                NULL, 
                                dllFileLength, 
                                MEM_RESERVE|MEM_COMMIT, 
                                PAGE_EXECUTE_READWRITE ); 


Copying the DLL/Determine Addresses

We can now copy the DLL (path or contents) to the target process space.

Now that we have space allocated in our target process, we can copy our DLL Path or the Full DLL (depending on the method you choose) into that process. We'll use WriteProcessMemory() to do so:

DLL Path


WriteProcessMemory(hHandle, 
                   dllPathAddr, 
                   dllPath, 
                   strlen(dllPath), 
                   NULL);


Full DLL

We'll first need to read our DLL into memory before we copy it to the remote processes.

lpBuffer = HeapAlloc( GetProcessHeap(), 
                      0, 
                      dllFileLength); 

ReadFile( hFile, 
          lpBuffer, 
          dllFileLength, 
          &dwBytesRead, 
          NULL );

WriteProcessMemory( hProcess, 
                    lpRemoteLibraryBuffer, 
                    lpBuffer,  
                    dllFileLength, 
                    NULL );


Determining our Execution Starting Point

Most execution functions take a memory address to start at, so we'll need to determine what that will be.

DLL Path and LoadLibraryA()

We'll search our own process memory for the starting address of LoadLibraryA(), then pass it to our execution function with the memory address of DLL Path as it's parameter. To get LoadLibraryA()'s address, we'll use GetModuleHandle() and GetProcAddress():

loadLibAddr = GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "LoadLibraryA");


Full DLL and Jump to DllMain

By copying the entire DLL into memory we can avoid registering our DLL with the process and more reliably inject. The somewhat difficult part of doing this is obtaining the entry point to our DLL when it's loaded in memory. Luckily enough, Stephen Fewer has made our lives easy. He's pioneered the Reflective DLL Injection technique which offers a greater level of stealth in comparison to existing methods. The LoadRemoteLibraryR() function included within his ReflectiveDLLInjection Inject project implements this entirely, however it limits our execution method to CreateRemoteThread(). So we'll use the GetReflectiveLoaderOffset() from it to determine our offset in our processes memory then use that offset plus the base address of the memory in the victim process we wrote our DLL to as the execution starting point. It's important to note here that the DLL we're injecting must complied with the appropriate includes and options so that it aligns itself with the ReflectiveDLLInjection method.

dwReflectiveLoaderOffset = GetReflectiveLoaderOffset(lpWriteBuff);


Executing the DLL!

At this point we have our DLL in memory and we know the memory address we'd like to start execution at. All that's really left is to tell our process to execute it. There are a couple of ways to do this.

CreateRemoteThread()

The CreateRemoteThread() function is probably the most widely known and used method. It's very reliable and works most times however you may want to use another method to avoid detection or if Microsoft changes something to cause CreateRemoteThread() to stop working.

Since CreateRemoteThread() is a very established function, you have a greater flexibility in how you use it. For instance, you can do things like use Python to do DLL injection!

rThread = CreateRemoteThread(hTargetProcHandle, NULL, 0, lpStartExecAddr, lpExecParam, 0, NULL);
WaitForSingleObject(rThread, INFINITE);


NtCreateThreadEx()

NtCreateThreadEx() is an undocumented ntdll.dll function. The trouble with undocumented functions is that they may disappear or change at any moment Microsoft decides. That being said, NtCreateThreadEx() came in good handy when Windows Vista's session separation affected CreateRemoteThread() DLL injection.

Detailed information about this method is described here:
NtCreateThreadEx() is a bit more complicated to call, we'll need a specific structure to pass to it and another to receive data from it. I've detailed the implementation here:


struct NtCreateThreadExBuffer {
 ULONG Size;
 ULONG Unknown1;
 ULONG Unknown2;
 PULONG Unknown3;
 ULONG Unknown4;
 ULONG Unknown5;
 ULONG Unknown6;
 PULONG Unknown7;
 ULONG Unknown8;
 }; 


typedef NTSTATUS (WINAPI *LPFUN_NtCreateThreadEx) (
 OUT PHANDLE hThread,
 IN ACCESS_MASK DesiredAccess,
 IN LPVOID ObjectAttributes,
 IN HANDLE ProcessHandle,
 IN LPTHREAD_START_ROUTINE lpStartAddress,
 IN LPVOID lpParameter,
 IN BOOL CreateSuspended,
 IN ULONG StackZeroBits,
 IN ULONG SizeOfStackCommit,
 IN ULONG SizeOfStackReserve,
 OUT LPVOID lpBytesBuffer
);

HANDLE bCreateRemoteThread(HANDLE hHandle, LPVOID loadLibAddr, LPVOID dllPathAddr) {

 HANDLE hRemoteThread = NULL;

 LPVOID ntCreateThreadExAddr = NULL;
 NtCreateThreadExBuffer ntbuffer;
 DWORD temp1 = 0; 
 DWORD temp2 = 0; 

 ntCreateThreadExAddr = GetProcAddress(GetModuleHandle(TEXT("ntdll.dll")), "NtCreateThreadEx");

 if( ntCreateThreadExAddr ) {
 
  ntbuffer.Size = sizeof(struct NtCreateThreadExBuffer);
  ntbuffer.Unknown1 = 0x10003;
  ntbuffer.Unknown2 = 0x8;
  ntbuffer.Unknown3 = &temp2;
  ntbuffer.Unknown4 = 0;
  ntbuffer.Unknown5 = 0x10004;
  ntbuffer.Unknown6 = 4;
  ntbuffer.Unknown7 = &temp1;
  ntbuffer.Unknown8 = 0;

  LPFUN_NtCreateThreadEx funNtCreateThreadEx = (LPFUN_NtCreateThreadEx)ntCreateThreadExAddr;
  NTSTATUS status = funNtCreateThreadEx(
          &hRemoteThread,
          0x1FFFFF,
          NULL,
          hHandle,
          (LPTHREAD_START_ROUTINE)loadLibAddr,
          dllPathAddr,
          FALSE,
          NULL,
          NULL,
          NULL,
          &ntbuffer
          );
  
  if (hRemoteThread == NULL) {
   printf("\t[!] NtCreateThreadEx Failed! [%d][%08x]\n", GetLastError(), status);
   return NULL;
  } else {
   return hRemoteThread;
  }
 } else {
  printf("\n[!] Could not find NtCreateThreadEx!\n");
 }
 return NULL;

}

Now we can call it very much like CreateRemoteThread():
rThread = bCreateRemoteThread(hTargetProcHandle, lpStartExecAddr, lpExecParam);
WaitForSingleObject(rThread, INFINITE);


Suspend, Inject, and Resume

Suspend, Inject, and Resume is an unofficial term to describe the method of injecting into process by attaching to it, suspending it and all of its threads, targeting a particular thread, saving the current registers, changing the instruction pointer to point to your executing starting point, and resuming the thread. This is a much more intrusive method, but works reliably and does not depend on additional function calls.

This method is a little more involved to implement. There is a great write up here:



VOID suspendInjectResume(HANDLE hHandle, LPVOID loadLibAddr, LPVOID dllPathAddr) {
 /*
  This is a mixture from the following sites:

   http://syprog.blogspot.com/2012/05/createremotethread-bypass-windows.html
   http://www.kdsbest.com/?p=159

 */

 HANDLE hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 );
 HANDLE hSnapshot2 = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 );
 HANDLE thread = NULL;
 THREADENTRY32 te;
 THREADENTRY32 te2;
 
 CONTEXT   ctx;
 DWORD firstThread = 0;
 HANDLE targetThread = NULL;

 LPVOID scAddr;

 int i;
 
 unsigned char sc[] = {
   // Push all flags
   0x9C,
   // Push all register
   0x60,
   // Push 3,4,5,6 (dllPathAddr)
   0x68, 0xAA, 0xAA, 0xAA, 0xAA, 
   // Mov eax, 8,9,10, 11 (loadLibAddr)
   0xB8, 0xBB, 0xBB, 0xBB, 0xBB,
   // Call eax
   0xFF, 0xD0,
   // Pop all register
   0x61,
   // Pop all flags
   0x9D,
   // Ret
   0xC3
  };

 te.dwSize = sizeof(THREADENTRY32);
 te2.dwSize = sizeof(THREADENTRY32);
 ctx.ContextFlags = CONTEXT_FULL;

 sc[3] = ((unsigned int) dllPathAddr & 0xFF);
 sc[4] = (((unsigned int) dllPathAddr >> 8 )& 0xFF);
 sc[5] = (((unsigned int) dllPathAddr >> 16 )& 0xFF);
 sc[6] = (((unsigned int) dllPathAddr >> 24 )& 0xFF);

 sc[8] = ((unsigned int) loadLibAddr & 0xFF);
 sc[9] = (((unsigned int) loadLibAddr >> 8 )& 0xFF);
 sc[10] = (((unsigned int) loadLibAddr >> 16 )& 0xFF);
 sc[11] = (((unsigned int) loadLibAddr >> 24 )& 0xFF);
 
 

 // Suspend Threads
 if(Thread32First(hSnapshot, &te)) {
  do {
   if(te.th32OwnerProcessID == GetProcessId(hHandle)) {
    if ( firstThread == 0 )
     firstThread = te.th32ThreadID;
    thread = OpenThread(THREAD_ALL_ACCESS | THREAD_GET_CONTEXT, FALSE, te.th32ThreadID);
    if(thread != NULL) {
     printf("\t[+] Suspending Thread 0x%08x\n", te.th32ThreadID);
     SuspendThread(thread);
     CloseHandle(thread);
    } else {
     printf("\t[+] Could not open thread!\n");
    }
   }
  } while(Thread32Next(hSnapshot, &te));
 } else {
  printf("\t[+] Could not Thread32First! [%d]\n", GetLastError());
  CloseHandle(hSnapshot);
  exit(-1);
 }
 CloseHandle(hSnapshot);

 printf("\t[+] Our Launcher Code:\n\t");
 for (i=0; i<17; i++)
  printf("%02x ",sc[i]);
 printf("\n");
 //  Get/Save EIP, Inject
 printf("\t[+] Targeting Thread 0x%08x\n",firstThread);
 targetThread = OpenThread(THREAD_ALL_ACCESS, FALSE, firstThread);
 if (GetThreadContext(targetThread, &ctx) == 0) 
  printf("[!] GetThreadContext Failed!\n");
 printf("\t[+] Current Registers: \n\t\tEIP[0x%08x] ESP[0x%08x]\n", ctx.Eip, ctx.Esp);

 printf("\t[+] Saving EIP for our return\n");
 ctx.Esp -= sizeof(unsigned int);
 WriteProcessMemory(hHandle, (LPVOID)ctx.Esp, (LPCVOID)&ctx.Eip, sizeof(unsigned int), NULL);
 printf("\t\tEIP[0x%08x] ESP[0x%08x] EBP[0x%08x]\n", ctx.Eip, ctx.Esp, ctx.Ebp);

 scAddr = VirtualAllocEx(hHandle, NULL, 17, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
 printf("\t[+] Allocating 17 bytes for our Launcher Code [0x%08x][%d]\n", scAddr, GetLastError());

 printf ("\t[+] Writing Launcher Code into targetThread [%d]\n", WriteProcessMemory(hHandle, scAddr, (LPCVOID)sc, 17, NULL));

 printf("\t[+] Setting EIP to LauncherCode\n");
 ctx.Eip = (DWORD)scAddr;
 printf("\t\tEIP[0x%08x] ESP[0x%08x]\n", ctx.Eip, ctx.Esp);

 if (SetThreadContext(targetThread, &ctx) == 0) 
  printf("[!] SetThreadContext Failed!\n");

 // Resume Threads
 hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 );
 te.dwSize = sizeof(THREADENTRY32);

 if(Thread32First(hSnapshot2, &te2)) {
  do {
   if(te2.th32OwnerProcessID == GetProcessId(hHandle)) {
    thread = OpenThread(THREAD_ALL_ACCESS | THREAD_GET_CONTEXT, FALSE, te2.th32ThreadID);
    if(thread != NULL) {
     printf("\t[+] Resuming Thread 0x%08x\n", te2.th32ThreadID);
     ResumeThread(thread);
     if (te2.th32ThreadID == firstThread) 
      WaitForSingleObject(thread, 5000);
     CloseHandle(thread);
    } else {
     printf("\t[+] Could not open thread!\n");
    }
   }
  } while(Thread32Next(hSnapshot2, &te2));
 } else {
  printf("\t[+] Could not Thread32First! [%d]\n", GetLastError());
  CloseHandle(hSnapshot2);
  exit(-1);
 }
 CloseHandle(hSnapshot2);
}


Side Note: DLL Proxying/DLL Hijacking

As a side note, DLL injection is very much different then DLL Proxying and Hijacking. For some reason, people tend to confuse these. The latter impersonates a legitimate DLL and essentially "tricks" the application to load it, while the former inserts a DLL into a process while its running.

DLL Proxying most commonly assumes you have full control over the application's install directory. The "attacker" renames the legitimate DLL and copies their own DLL into the install directory. When the application runs, it loads the attacker's DLL (since it's named correctly) and then the attacker's DLL relays the function calls to the legitimate one. DLL Proxying is most commonly used by the actual owner of the system as a method to extend application functionality. For instance, DLL proxying is popular in the gaming world. Lots of people use this technique to modify game functionality for cheating or other sorts of fun. "Spy" applications also leverage DLL Proxying in an attempt to capture user provided application values.

DLL Hijacking is similar to proxying but differs in that hijacking usually abuses Windows' DLL search order in order to compromise a system (or otherwise control the flow of the application). It doesn't usually require the attacker to have write permission to the application's installation directory but rather the directory where the application was launched. In the case that the application attempts to call a non-existent DLL or if an attacker was able to place a malicious DLL in the same directory as a file that launches a vulnerable application, the attacker's DLL would be loaded and code execution would be achieved. This is because Windows [used to] search for application DLLs in the current directory from which the application was loaded before most other locations.

dllInjector!

All of the techniques described here have been implemented in a small project called dllInjector that I'll release in the next upcoming weeks! For a sneak preview, check it out here: