Android App Hacking – Hero Defense

[Intro]

Here I will show you how to disassemble an android game, and modify its files to obtain an advantage like god-mode.

[Tools]

  1. APK Downloader
  2. dex2jar
  3. jd-gui
  4. IDA Pro or similar disassembler
  5. Binary patcher
  6. ZipSigner

[Tutorial]

The steps for this project are as follow:

  1. Download the Hero Defense APK.
  2. Extract its contents.
  3. Turn its dex file into a .jar file.
  4. Dissasemble it.
  5. Dissasemble the shared library containing its API.
  6. Patch the library.
  7. Repackage the APK.
  8. Sign the APK.

The first thing you need to do is download the APK.  This can be done by using your android device, or you can do it from your pc using the APK Downloader from evozi.  Once you have the APK downloaded you can rename it to a .zip file and use any zip utility to extract its contents. You will see a classes.dex file at the root of your directory, you can turn this file into a jar with the dex2jar utility.  After you have done that you got yourself a dex2jar.jar file containing all the game’s class files.  You can load those class files using jd-gui and begin reading the code.

After reading the code for a few minutes it becomes apparent that the game is not written in java, but instead is written in c++ using native shared library. In order to modify the game’s behavior in any meaningful way we have to patch that libdawn.so lib.  So we crank up IDA Pro and see what we can do.

dawn

Loading dawn.so in IDA Pro on my computer takes about 5 minutes to index all the exports in dawn. But after a while you can see that there are many interesting names being exported.  One such name is Hero::underAttack(float), which as the name would suggest handles what is supposed to happen when our hero is under attack.

Going through the underAttack function we can see that a value is loaded into R3, then checked against the value of 0.  If the comparison is true then we take the conditional jump into isAlive, if not we go somewhere else.

graph view

By setting the value being checked against R3, we can ensure that the conditional jump will never be taken, and we will avoid any actions regarding that branch.  In this case that turns out to be the branch where the damage is calculated and dealt to our hero, so by modifying it we end up with a hero that takes hits (visual effects), but no damage or death.

opcode modification

 

graph view modified

 

So after we modify the bytes, we use IDA Pro to generate a diff and we then patch the libdawn.so binary.  After successfully patching we throw it back into the original game apk, load into our device, and sign it with zipsign.

patching

Once signed we are ready to go.

[Conclusion]

I hope this wasn’t too hard to follow.   If you are having a hard time following this drop a comment.

The hack in action can be seen here:

Influence: The Psychology of Persuasion

Influence

Influence: The Psychology of Persuasion (Collins Business Essentials)
presents an in-depth look into the many persuasive tools available to us in our everyday human interactions. In this book Dr. Cialdini puts his decades of experience in the fields of psychology and marketing to teach you how to be an effective and persuasive communicator.

I picked up Influence: The Psychology of Persuasion (Collins Business Essentials) as part of a package of some twenty or so books regarding influence and storytelling for my trial library. When I ordered it I was not sure what to expect or if it would be worth my time, but once I sat down to read it I quickly realized that this book was a gold mine. Throughout the book Dr. Cialdini guides you through the intricacies of human behaviour, and in the process discusses what causes us to make the decisions that we make. Every chapter of the book is divided into key elements of our decision-making process, and in each one of those chapters Dr. Cialdini explains, through research studies, why those elements play a significant part in our lives.

In Influence: The Psychology of Persuasion (Collins Business Essentials) Dr. Cialdini explores six tools that can be used to persuade others:

  1. Reciprocity: The feeling of indebtedness we have when others have extended a favour to us.
  2. Commitment and Consistency: The unwillingness of people to change their minds once they have committed to an idea publicly,
  3. Social Proof: People will do things that they see other people doing.
  4. Authority: People will do things when commanded by authority figures.
  5. Liking: People’s willingness to be persuaded by people that they like.
  6. Scarcity: People tend to value information more when they perceive it to be scarce.

By learning how to apply these principles we can gain an advantage when trying to persuade, whether it be those we deal with on a daily basis, or a jury panel ready to decide someone’s fate, and Dr. Cialdini does an excellent job of explaining how these principles work in this book. Overall this is a great book, it is simple, to the point, and not incredibly boring like some of the more “scientific” publications out there.  If you’re looking to learn the basics of persuasion I give this book a 8/10.

Sony Sued Over PSN Security Breach, Faces Millions in Damages

On May 11th, 2011 James Campo filed a class action suit in the U.S. District Court for the Northern District of California seeking relief for all parties injured by Sony’s subpar security practices that led to the compromise of personal information of millions of subscribers.

The complaint breaks down as follows:

  1. Breach of express warranty: Sony failed to protect customers’ personal information as promised in its privacy policy.
  2. Negligence: Sony failed to use reasonable care in handling customers’ personal information and in informing customers of the security breach.
  3. Gross Negligence: Sony knowingly failed to implement proper security measures to safeguard customer data.
  4. Negligence Per Se: Sony violated California Civil Code section 1798.82 that requires a timely disclosure when a breach of security takes place.
  5. Unlawful Business Practices: Violations under a plethora of statutes basically saying that Sony’s conduct and business practices are injurious to consumers.
  6. Unlawful Business Practices: By advertising Sony’s system and the PSN as safe even though Sony knew or should have known they had inherent defects.
  7. Violation of California Civil Code section 1798.80: Sony failed to disclose to plaintiffs the security breach without unreasonable delay.
  8. Breach of Implied Contract: Plaintiffs provided Sony their personal information in order to buy online content or play games, implicit in this transaction was Sony’s promise to use reasonable care in safeguarding that information.
  9. Bailment: Sony was the bailor of plaintiffs personal information and breached this duty by not exercising reasonable care over it.
  10. Injunctive Relief: Plaintiff wants Sony to fix the security flaws, disclose to the list of those whose information was compromised and remedy the effects of the disclosure of the confidential information.

Sony has yet to file an answer to the complaint and we probably won’t be seeing one for a bit but what is clear is that Sony faces millions/billions of dollars in damages and is likely to settle and take better care of their network security from now on.

A copy of the original complaint can be found here

Sony Sued Over FFXIII-What Sony Really Thinks of Your Rights as a Consumer

Almost a year ago Mr. Daniel Wolf filed a class action suit against Sony and Square Enix due to Final Fantasy XIII allegedly bricking his PS3 along with others. The complaint, which states multiple violations of California consumer laws can be found here. A quick google search reveals multiple users that have had their consoles destroyed by the game and at this point it isn’t clear whether it is due to a defect in the PS3, a defect in FFX13, or both.

In its motion to dismiss defendant Sony admits the allegations that there are “100′s of complaints” but in a surprising twist claims that hundreds of people getting their consoles bricked is an insignificant amount compared to the millions of copies sold. I’m sure to Sony that sounds like a small price to pay but it doesn’t sit so well with the consumer who just had his shiny new toy destroyed and now needs to pay $250 to get it fixed. And besides, if hundreds of broken PS3s is “insignificant” to Sony then why does the multimedia giant refuse to repair the consoles free of charge? Sony’s stance however, might make legal sense since Mr. Wolf is trying to certify a class of all FFXIII buyers and not just the ones that have suffered actual damage from the game.

Sony’s second stance is one that will likely get some heads turning. In its motion to dismiss Sony claims something to the effect that the PS3 only has a 1 year warranty and whatever happens to it afterwards is not Sony’s concern. This stance means that those whose PS3 is over 1 year old should be at risk of having it damaged without any remedy even though it could very well be Sony’s fault that creates the damage. Sony’s motion was filed in March 2011 and it will certainly be some time before this controversy is resolved but this case is worth following as it will set the tone for what consumers’ rights are after the express warranty has expired when their products are damaged as a result of the manufacturer’s misconduct.

Complaint

Motion to Dismiss

Setting the Virtual Stage

Virtual Real Estate

We begin our immersion into the world of computers and the law by analyzing the four year old case Bragg v. Linden Research, Inc. 487 F. Supp. 2d 593. In Bragg, the plaintiff who is apparently a lawyer brought suit because Linden Research(the maker of Second Life) closed his account after the plaintiff allegedly used an exploit to acquire a Second Life parcel of land at far below market value. Bragg brought claims under the Pennsylvania Unfair Trade Practices and Consumer Protection Law, California Unfair and Deceptive Practices Act, California Consumer Legal Remedies Act, fraud, conversion, intentional interference with contractual relations, breach of contract, and tortious breach of the covenant of good faith and fair dealing along with violation of California Civil Code section 1812.600.

After removing to Federal court defendant Linden attempted to compel arbitration as stipulated in the Second Life EULA which Bragg had agreed to. The Second Life arbitration agreement at the time stated:

Any dispute or claim arising out of or in connection with this Agreement or the performance, breach or termination thereof, shall be finally settled by binding arbitration in San Francisco, California under the Rules of Arbitration of the International Chamber of Commerce by three arbitrators appointed in accordance with said rules…. Notwithstanding the foregoing, either party may apply to any court of competent jurisdiction for injunctive relief or enforcement of this arbitration provision without breach of this arbitration provision.

If the arbitration agreement stood, the parties would be forced to arbitrate their claims leading to more expense to Bragg, a substantial likelihood of a smaller award for damages and most importantly the arbitration was to be confidential so that future plaintiffs bringing actions against Linden would not benefit from precedent. Fortunately for Bragg and gamers worldwide, the court found that the arbitration clause was unconscionable because it, coupled with other terms of the EULA which allowed Linden to cancel accounts for any reason, allowed the stronger party to choose its forum while forcing the weaker party to only one forum(arbitration in SF). Another important factor was the cost differential. Although the parties couldn’t come to an agreement as to the cost of arbitration, the average of the estimates provided was over $10,000. If this provision was upheld, it was clear that many plaintiffs would be kept from having their day in court as it wouldn’t make sense for a person to spend tens of thousands of dollars to litigate small claims which are more typical.

So what does it all mean for gamers everywhere? At least in California contract conditions which put the weaker party in a disfavorable position so as to keep it from having its day in court will not be enforced. Furthermore, at least in the context of Second Life where the defendants had an ongoing advertising campaign claiming that gamers could actually “own” property the courts will uphold a gamer’s right to protect his virtual property from unfair taking by game companies.

Ehrhardt’s Florida Evidence

Ehrhardt

Ehrhardt’s Florida Evidence is the evidence book that teaches you everything you ever wanted to know about the Florida evidence code, and then some.

With clear and concise language, this book carefully guides you through the Florida evidence code, breaking down important and complicated sections into subsections for easy understanding of the material. Particularly useful are the book’s numerous parenthetical citations on the bottom half of every page. Not only does the author do a fantastic job of explaining each section of the Florida evidence code, but by making references to the applicable caselaw, the reader is able to follow up on any doubts that remain.

Ehrhardt’s Florida Evidence dedicates over 260 pages to hearsay, making it one of the most complete sources on the subject. As expected, the book focuses on the technical aspects of the rule as applied in Florida caselaw, and is replete with applicable caselaw throughout this entire chapter. If you’re like me and find the many challenges embedded in the hearsay rule and its many exceptions exciting, Ehrhardt’s Florida Evidence is the right book for you.

Something I found particularly useful is the book’s chapter on authentication of documents. In it the author covers the many different permissible ways of having a document authenticated, when a document is self-authenticating, and when no authentication is required. Ehrhardt’s Florida Evidence is certainly a valuable source to keep handy when figuring out whether a document needs to be authenticated, and if so whether the witness or method you have in mind can get it done.

With 1082 pages of solid, on point knowledge, and an appended full copy of the Florida Evidence Code, Ehrhardt’s Florida Evidence deserves a 10/10. I only wish I had gotten my hands on this wonderful resource months ago.

Clandestine Group Development With Tor’s Hidden Service Protocol

Intro

Sometimes you have a great software project you want to work on for the benefit of the community. It is so great in fact, that engaging in development is outright illegal, and the company who’s patents you are infringing upon is not afraid to come after you with a lawsuit. So you are left with a very hot programming endeavour, and the need to have a cooperative effort with others in the community to make it happen within a short period of time.

This is exactly what Tor’s Hidden Service Protocol was created for! I kid…it was created for worthy goals like promoting free speech and political dissent in oppressive regimes, but its all the same for our goals.

The Setup of the Hidden Service

Setting up a hidden repository with git and tor is pretty simple:

  1. First, you open up torrc and type in the port and directory for your hidden service.
  2. Make sure that the user/directory for your hidden service exists and is accessible.
  3. Modify your sshd_config to not accept connections from anywhere but localhost.
  4. Install and configure gitolite normally.
  5. Run tor.
  6. Locate your hidden_service directory and note what the hostname for the hidden service is. Ex: xxxxasas.onion
  7. Distribute tor service hostname anonymously.
  8. A good method could be having users post public keys in a forum that you can check anonymously.

Example of key directory for a working repo:

The Setup of client (Windows)

In order for the contributors to be able to access your repository they need to take the following steps:

1. Modify the .ssh/config file as follows:

Host hostname.onion
User g
PreferredAuthentications publickey
Compression yes
ProxyCommand /bin/connect.exe -S 127.0.0.1:9050 %h %p
IdentityFile "C:\Documents and Settings\Administrator\.ssh\YOURKEY"

2. Clone the repo-git clone g@hostname.onion:RepoName

These instructions assume that YOURKEY is a valid key that the repository owner has already added to the repo.

Clones and updates of the repository through the service will be subject to increased latency, like pretty much anything else you do through tor.  Its part of the deal, deal with it.

Conclusion

Learning how to use the tor hidden service protocol is probably one of the easiest, most useful things you’ll ever learn.  Use it carefully and effectively and you will be able to promote solidarity in the community.  Use it recklessly and carelessly and you might just find yourself facing that lawsuit you intended to avoid in the first place.

NOTE: As with every encryption technology, nothing is 100% safe.  Use at your own risk and don’t come crying to me if something goes wrong.  At the end of the day look on the bright side-at least you’re not risking getting killed if it fails, like some other people are.

cheers,

emist

Reversing: Secrets of Reverse Engineering


Reverse engineering is a skill, a craft, a creative process that cannot be learned from just reading a book.  With that said, Reversing: Secrets of Reverse Engineering offers great guidance into the process, and unlike other self proclaimed “hacker essentials,” this book delivers what it promises and then some. This book starts the reader off from the basics of compiled languages, explaining the intricacies of compiler optimized assembly output.  And proceeds to show various reversing sessions of native Windows API implementations.  Guiding the reader step by step in the process of turning the assembly code into higher level code.

The later chapters deal with inspecting malaware, with the author analysing a popular backdoor program, and tracing its functionality in order to discover the server it connects to, its password, and its command list.  The book also extensively covers anti-reversing, and anti-debugging techniques, dedicating a full chapter to these.

In its final chapters, the book introduces techniques for reversing vm-based implementations like Java and the .Net platform.  With the increasing popularity of this type of implementations, this is surely a skill that will become more useful as time goes by.  The appendix in this book is incredibly useful.  Appendix A is a quick reference guide for translating common high level constructs into assembly language.  Appendix B is a quick reference to common arithmetic as optimized by the compiler.  Appendix C gives an in-depth analysis of how data is laid out in the system, and how the many standard calling conventions are represented.

Overall Reversing: Secrets of Reverse Engineering is one of the most well-written, detailed, and useful books on the subject and it deserves a 9/10.  If you are looking for a fantastic book on the subject, look no further.

[JAVA] Bypassing Licensing Schemes Through Bytecode Modification

[Intro]

I have been meaning to write a bot for Objection!, a game whose purpose is to test your ability to identify objectionable questions during a simulated trial.  While I have a valid key, I am only allowed to install it in one computer at a time.  Since I use my laptop more often than anything else, I installed the game there so I have it handy when I wish to use it for its intended purpose.

In the meantime, I had to come up with a solution so I can use the game on my development machine to write my bot. When I attempted to decompile the code, modify the licensing part, and recompile the code, I was hit with a bunch of repeated declarations and other ambiguous code (about 300 or so errors).  Needles to say…I’m way too lazy to manually resolve all those problems to recompile.  The next best(laziest) option was to modify the bytcode of the compiled classes so that I can do the same thing, without having to worry about recompiling and fixing all the issues.

[Tools]

  1. Eclipse
  2. ASM

Eclipse is as decent an IDE as any to do java work, and the existence of a bytecode-generating plugin for it makes it a top pick for this kind of work.

ASM is by far the fastest, most efficient java bytecode manipulation library out there right now.  Its use of the visitor pattern makes things kind of strange(at least for me), but after a while it kinda makes sense.

[Prologue]

To make things simple I extracted the game’s jar to its corresponding parts.  This is so I can directly load the classes and don’t have to worry about using JarFile or anything like that to load the JarEntry(s) etc.

[Tutorial]

First, I ran the game without a valid key.  This gives you an objection! game where you are allowed to play but are not allowed to advance passed level 1.

After quickly tracing through the decompiled code(the one that doesn’t compile back), I reached the area of code that prompted this message on what I assume is an invalid install.  This is an area inside of the “run()” method of the obj class.

Once I knew where the check was, it was only a matter of generating the proper asm calls to reproduce the method and then going in the bytecode and replacing that check with something more useful.  In order to produce the needed asm calls, I used the ASMify utility that is shipped with the ASM library.  This utility will take a class file and turn it into asm calls.  The relevant method’s needed asm calls look like this:

And the same code after modifying the if statement to fit our needs looks like this:

Launching the game with our loader after modifying the bytecode of the obj class, and obtaining the necessary score to reach level two now yields the following screen:

[Conclusion]

This was a brief introduction into how to use ASM to dynamically modify bytecode to bypass a simple licensing scheme.  If you are interested into how to actually load the game and modify the class, the full working source code can be found here.

Creating Custom JAR Loaders With ClassLoaders

[Note] This article is part one of a two part series on making a bot for a java game [/Note]

[Intro]

As part of being in the trial team we were given a game called Objection! which is a really old/DOS-looking kind of game with horrible graphics that allows you to hone your objection skills.  It gets really tough after a while, so I thought it would be fun to inject a dll and dump the questions and make a simple bot. If anything, it would be a good exercise in reverse engineering.

Since it comes bundled in an exe, and it looks old as hell, I assumed the game was written in C and using the WinAPI.  But after popping up IDA and looking inside the exe, I quickly realized that it was nothing more than a JNI class loader, and the game itself came bundled in a jar file called tmgames.jar.  This changes everything, instead of injecting a dll to detour functions from the process, I can build a custom loader to load the jar, and instrument the client’s code at runtime.

The first step in this whole process is taking control of the loading process of the game.  After that we can instrument it.  And so this tutorial is born.

[>>>>>]

The process breaks down in six steps:

  1. Build a classloader from the gamejar.
  2. Load the class that has the game’s main method.
  3. Get the constructor that you want to call of that class.
  4. Instantiate the class with the constructor and parameter(s) you need.
  5. Find the game’s main method.
  6. Invoke the main method.
package runtime;
 
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.reflect.Method;
import java.io.*;
import java.lang.reflect.Constructor;
 
public class Main 
{
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		URL[] url = new URL[1];
		try
		{
			url[0] = new URL("file:////C://Users//emist//workspace//tmloader//bin//runtime//tmgames.jar");
			verifyValidPath(url[0]);
		}
		catch (Exception ex)
		{
			System.out.println("URL error");
		}
		Loader l = new Loader();
		l.loadobjection(url);
 
	}
 
	public static void verifyValidPath(URL url) throws FileNotFoundException
	{
		    File filePath = new File(url.getFile());
		    if (!filePath.exists()) 
		    {
		      throw new FileNotFoundException(filePath.getPath());
		    }
	}
 
}
 
class Loader
{
	public void loadobjection(URL[] myJar)
	{
		try 
		{
			//Create a classloader.  myJar holds the full path to the game's jar file. 
			URLClassLoader child = new URLClassLoader(myJar, this.getClass().getClassLoader());
 
			//tmcore.game is the class that holds the main method in the jar
			Class<?> classToLoad = Class.forName("tmcore.game", true, child);
			if(classToLoad == null)
			{
				System.out.println("No tmcore.game");
				return;
			}
 
			//game doesn't have a default constructor, so we need to get the reference to public game(String[] args)
			Constructor ctor = classToLoad.getDeclaredConstructor(String[].class);
			if(ctor == null)
			{
				System.out.println("can't find constructor");
				return;
			}
 
			//Instantiate the class by calling the constructor
			String[] args = {"tmgames.jar"};
			Object instance = ctor.newInstance(new Object[]{args});
			if(instance == null)
			{
				System.out.println("Can't instantiate constructor");
			}
 
			//get reference to main(String[] args)
			Method method = classToLoad.getDeclaredMethod("main", String[].class);
			//call the main method
			method.invoke(instance);
		}	
		catch (Exception ex)
		{
			System.out.println(ex.getMessage());
			ex.printStackTrace();
		}
	}
}

Something to note about this code is that there are many hidden pitfalls.  For example, if you call getDeclaredMethod(“main”) you will have a methodnotfoundexception.  The reason being that you have to match the method declaration.  getDeclaredMethod(“main”, String[].class) matches main(String[] args), while getDeclaredMethod(“main”) looks for main(), which doesn’t exist.

Another thing that can trip you up is that classToLoad.getDeclaredConstructor is required if the class doesn’t have a default constructor.  If you forget to do this, you will get an exception to the effect that the class cannot be instantiated.

[Epilogue]

If you’re wondering how you find out what methods you need to call and what parameters they take, there’s many ways of going about it.  Personally, since its java I extracted the jar and ran the classes through jad.  Once decompiled its a simple process to figure out what code you need to be calling.

[End]

So now you have a class loader to load your jar.  This is the first step in making a working bot.  In the next article I will show you how this fits into a working bot.