Friday, February 8, 2013

Android hacking: replacing system classes methods with your own

If you read my previous post you already know it is really easy to intercept libc functions used by Dalvik. However we can go a bit further and hack DVM from inside out. This time we will be replacing Android framework system classes in runtime, without rooting the device or recompilation of system class libs.

Sounds impossible? Yet, it can be done.
We will dive deeply into Dalvik internals, a bit in DEX bytecode and plain old hacking.

The challenge

It is pretty much impossible to replace a loaded system class on Android (unless you've got root).
  • When your app is started, most classes are already loaded/linked thanks to Zygote
  • Because of that, you can not override system class path
  • You may not load your custom classes with system class loader
  • In other words, you can not replace system java class from inside of java

DVM internals


Fortunately, many DVM methods and global variables are exported libdvm.so. In fact several libs like androidruntime.so and libbinder.so relay on that.


So even though we may not just link with -ldvm (at least it didn't work for me, so I gave up) it is still possible to dlopen() and dlsym() these functions/globals and hack our way into Dalvik.

On Dalvik all Java class/object mapping to native C structs is happening in vm/oo/* files.
Object instances are mirrored with ClassObject structs, and methods with Methods.
So each ClassObject comes with 2d vtable array, which simply contains pointers to Methods.

Now then, from JNI code we can issue following calls to get the ClassObjects we want:
We can easily invoke these to get class we need. Note however the class descriptor is different from traditional class name and dalvik.system.class would look like  "Ldalvik/system/class;"

So, what we could do is to dvmFindSystemClass() the target class and dvmFindClass() and swap Method's class bytecode pointers, right? Wrong.

Dalvik bytecode


On Android, compiled system classes bytecode sit in .dex file. They are "optimized". Normally it is a good thing, but makes injecting code harder. Why?
Because unlike traditional Java's invokevirtual, Android's invoke-virtual opcode takes method reference index as an argument. Lets disassemble some .dex and see how methods are invoked:


So this invoke-virtual opcode address println method by @001f index, rather than string. This index is specific to .dex file and is populated during its creation. So if we just copy new bytecode over original bytecode, DVM will end up calling wrong methods. Unless we want to manually patch bytecode or hack into Dalvik's method index tables, we better leave this approach. Another approach would be to write bytecode payload by hand, but it it is a tedious and the code will be extremely version-specific and probably break on different device/version.

What we could also do is to swap the  Method structure pointer in vtable[]. Since every Method contains reference to parent object pointer, the interpreter will be able to invoke referenced methods properly. However, access to local variables will not work, because DVM does not use any kind of indexing in such case. If we need to access some local variables, we will have to use a helper singleton class. On native side, replacing Method pointers in vtable[] is not enough, we would also need to update methodIndex. If we need to call original method, we will need to prefix it and rename it, and then we will be able to use Reflection API to call it.

Putting it all together

To summarize all we need to do is:

  • In your class, add a method with exactly the same signature as your target method
  • Write the method as you normally would, but
  • Avoid accessing class members
  • Local variables are fine
  • Use helper singleton if you need to speak to outside world
  • Use Reflection API to call original method, but add "_orig_" to your method name
Lets override ClipboardManager.setText() method so that we whatever something is send to clipboard, we add a custom string.


So the actual code to do swapping is trivially simple:

Now, once you do the following from your .so:
every time something is pasted in clipboard, the "pwned:" will be added to the clip :)

Congratulations! you've successfully overridden system class on Android.
compilable source

83 comments:

  1. compilable source cannt download
    can you send it to my email?
    wynney@gmail.com
    thx

    ReplyDelete
  2. How to compile this code ? Can you tell us the dependencies ?

    ReplyDelete
  3. how can i download complete source code?
    isn't it possible to download the source code?

    ReplyDelete
  4. can you share the code to readercn@gmail.com, thanks!

    ReplyDelete
  5. Which header file should i include to use ObjectClass.. its throwing exception ( unknown type name 'ClassObject') while creating .so file using ndk-build too

    ReplyDelete
  6. Can you reupload the compilable source? How do you load a method that has the same name but different signature? I would like to see the rest of the code to make sure I am understanding properly.

    Thank you.

    ReplyDelete
  7. Andrey, you are really cool!!!
    Can you reupload sources or mail them to andruwik777@ua.fm.
    Thank you one more time!

    ReplyDelete
  8. Awesome
    please share the code at djoshi@process9.com

    Thanks

    ReplyDelete
  9. Awesome
    please share the code at djoshi@process9.com

    Thanks

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. Download link dead :((
    Please send the sources to xottavych@yandex.ru

    ReplyDelete
  15. Hi, you have done great job! I can't download the source code because of dead link. Can you please send it to xardas01@gmail.com?

    Thanks and best regards

    ReplyDelete
  16. Download link dead :((
    Please send the sources to rayarasool@gmail.com

    ReplyDelete
  17. Stuck with the dead link too.
    If anyone have it, please comment with a link
    Thanks!

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. Awesome
    please share the code at emotian@gmail.com

    Thanks

    ReplyDelete
  20. This is great! Can you please send the code to arturs.ziborovs@gmail.com? Would really appreciate it! Also, does it work with ART nowadays?

    ReplyDelete
  21. can i get code for this at arsalanjibran5@gmail.com

    ReplyDelete
  22. That's great!! Can i do that to 'View' class and access its members via helper class? which is not a singleton class.

    ReplyDelete

  23. Buy Tramadol Online from the Leading online Tramadol dispensary. Buy Tramadol 50mg at cheap price Legally. Buying Tramadol Online is very simple and easy today. Shop Now.

    ReplyDelete
  24. Tramadol is a drug which is an opioid pain medication and you can buy Best Tramadol online from us. The Online Pain relief Pills tramadol pills has been categorized as depressant and analgesic. The active component of this drug is Tramadol Hydrochloride (HCL) and it could be combined with the acetaminophen and they can be prescribed in the type of tablets.

    ReplyDelete
  25. Buy Tramadol Online from the Leading online Tramadol dispensary. Buy Tramadol 100mg at cheap price Legally. Buying Tramadol Online is very simple and easy today. Shop Now.

    ReplyDelete

  26. We at Strive 2 drive,driving school In Melbourne.
    Driving School in Melbourne!
    is one of the best & safe driving school where you have an ease of access
    Driving School in Melbourne!

    to a wide array of special driving features. We are focused at your
    comfort and so we have put together facilities within the site to ensure
    that you get the very best.
    Driving School in Melbourne!

    ReplyDelete
  27. The high quality Organic T-shirts by Dezayno are made on some of the softest ringspun certified organic cotton available. Their shirts are built to last a long time and feel comfortable the entire life of the shirt. Organic T-shirts

    ReplyDelete
  28. If you are looking for your desired job So visit now our website Rozgar Ki Dunya . You can find all information about education and jobs on our website. If you want to start your business then Government announced Kamyab Jawan Program SchemeGet Loan and start your own business.
    PPSC announced 145 plus vacancies in different departments. click on PPSC jobs October 2019 Advertisement 36/2019 and download advertisement
    click on PPSC jobs October 2019 Advertisement 36/2019 and download advertisement
    You can also check CTI New 4500 Jobs In Punjab 2019-20 For Lecturer Male & Female
    For Free internship Check here: Pakistan Post Internship Program 2019-35000+ Interns

    ReplyDelete
  29. Hi Guys. We are a family-owned business started in 1971 in Sparks, Nevada. We have an automotive parts warehouse distribution system for automobiles and light and heavy-duty trucks with several shipping locations throughout the United States. We specialize in drivetrain-related areas and provide experience and expertise to assist you in getting the correct parts the first time. We offer free diagnostics and road testing as well as free troubleshooting support by telephone. We would be honored if We can help you. drivetrain

    ReplyDelete
  30. Great Article! Thanks for sharing this types of article is very helpful for us! If you have any type of pain like chronic pain, back pain etc.
    Best Pharmacy Shop

    ReplyDelete
  31. Very Nice Blog!!! Thanks for Sharing Awesome Blog!! Prescription medicines are now easy to purchase. You can order here.
    Buy Soma 350mg
    Order soma online
    buy Ambien 5 mg online
    buy Ambien online
    buying Gabapentin COD
    Buy Gabapentin cod online

    ReplyDelete
  32. Great Article! Thanks for sharing this types of article is very helpful for us! Prescription medicines are now easy to purchase. You can order here.

    Buy Gabapentin Cash on delivery
    Buy Gabapentin Online
    order Gabapentin 400mg online
    order Gabapentin 300mg online

    ReplyDelete

  33. Thanks for this informative blog.There are online pharmacies such as ours that can help you with medicines along with prescription
    buy Xanax 1mg pills online
    buy Alprazolam online

    order Xanax cash on delivery

    order Alprazolam cash on delivery

    ReplyDelete
  34. Thanks for sharing your innovative ideas to our vision. I have read your blog and I gathered some new information through your blog. Your blog is really very informative and unique. Keep posting like this. Awaiting for your further update.If you are looking for any Big Data related information, please visit our website Big Data training Certification Course in Bangalore.

    ReplyDelete
  35. Every person can apply indian visa application online from all over the world

    ReplyDelete
  36. Resurge is absolutely 100% natural, safe and effective. Many thousands of folks enjoy taking Resurge every day and there has been absolutely zero side effects reported. Every capsule of Resurge is manufactured here in the USA in our state of the art FDA approved and GMP (good manufacturing practices) certified facility under the most sterile, strict and precise standards. Resurge is 100% all natural, vegetarian and non-GMO. As always, if you have a medical condition it's recommended to consult with your doctor. Best natural foods for weight loss

    ReplyDelete
  37. A great website with interesting and unique material what else would you need.
    360digitmg data science courses online

    ReplyDelete
  38. I truly like your style of blogging. I added it to my preferred's blog webpage list and will return soon…

    https://360digitmg.com/course/artificial-intelligence-ai-and-deep-learning

    ReplyDelete
  39. Great to become visiting your weblog once more, it has been a very long time for me. Pleasantly this article i've been sat tight for such a long time. I will require this post to add up to my task in the school, and it has identical subject along with your review. Much appreciated, great offer.
    Data analytics course

    ReplyDelete
  40. This is my first time visit here. From the tremendous measures of comments on your articles.I deduce I am not only one having all the fulfillment legitimately here!
    hrdf contribution

    ReplyDelete
  41. You totally coordinate our desire and the assortment of our data.
    https://360digitmg.com/hrdf-training

    ReplyDelete
  42. To terminate an unwanted pregnancy at home order online MTP kit at a low price.

    ReplyDelete
  43. The writer is enthusiastic about purchasing wooden furniture on the web and his exploration about best wooden furniture has brought about the arrangement of this article.
    Best Data Science Courses in Hyderabad

    ReplyDelete
  44. Bayzat is redefining the work life experience,
    health insurance dubai
    medical insurance dubai
    making automated HR, payroll, employee benefits and insurance a possibility for all businesses

    ReplyDelete
  45. Thanks for sharing such a valuable information!

    We pride ourselves in offering you a wide array of good quality drugs that have been clinically tested as well as approved by the U.S. Food and Drug Administration (FDA).So, if you intend to order anti anxiety tablets,erectile dysfunction pills & Pain Relief Online USA, you may obtain the same from us in a hassle free manner.24-Hour Pharmacy USA. Fast Delivery. No prescription.

    Buy Xanax online USA
    Tapentadol tablet online USA
    Adderall 20mg tablets
    buy Jpdol online

    ReplyDelete
  46. Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog. ExcelR Data Analyst Course

    ReplyDelete
  47. buy tramadol 225mg online
    Buy Tramadol Online in USA. Tramadol 50mg,100mg,150mg,200mg,225mg. Brand Name: OL-TRAM / ULTRAM. Order Tramadol from our website with affordable price rates.

    ReplyDelete
  48. Talk to Best Astrologer
    AstrologyKart is the best astrology website for online astrology predictions from the best astrologers of India. Chat with an astrologer in India online & also talk to best experienced astrologers online anytime at AstrologyKart.

    ReplyDelete
  49. Talk to Astrologers Online
    If you want to talk to astrologers online in India, then Astrology Kart has the best astrologers to provide accurate astrology predictions online at a very affordable price rates.

    ReplyDelete
  50. Chat with Astrologer Online
    Chat with the best astrologer in India and get the best astrology advices and best accurate online astrology predictions only at Astrologykart.

    ReplyDelete
  51. Free Astrology Advice online
    AstrologyKart is the best astrology website for online astrology predictions from the best astrologers of India. Chat with an astrologer in India online & also talk to best experienced astrologers online anytime at AstrologyKart.

    ReplyDelete
  52. Mobile tower installation in West Bengal
    Being the largest Mobile Tower Installation service provider in West Bengal and Kolkata. We deliver the best Mobile Tower installation services in this area.

    ReplyDelete
  53. Mobile tower installation in Uttarakhand
    The Digital Groups is the best Mobile Tower Installation company in Uttarakhand. If you are looking for the tower installation services in Uttarakhand. Contact Us.

    ReplyDelete
  54. Mobile tower installation in Madhya Pradesh
    Looking for a Mobile Tower Installation company in Madhya Pradesh? Call now on 7864805461 for instant mobile tower installation any kind of queries.

    ReplyDelete
  55. Mobile tower installation in Gujarat
    Apply for mobile tower installation in Gujarat contact us on 7864805461. We are the best Mobile Tower Installation service provider in Gujarat and it's cities.

    ReplyDelete
  56. Best Ayurvedic Treatment
    Ayurvedic Hospital in Dhanbad
    Call Us at +91 9204900900, Kerala Ayurveda Dhanbad is one of the Best Ayurvedic Hospital, Providing Unbeatable Ayurvedic Treatments in Dhanbad.

    ReplyDelete

  57. Best Ayurvedic Treatment in Ashoknagar
    Ayurveda is the traditional method to cure different types of diseases, Kerala Ayurveda Ranchi is delivering the best Ayurvedic treatment in Ashoknagar.

    ReplyDelete
  58. Best Ayurvedic Treatment in Bariatu
    We provide the best Ayurvedic treatment in Bariatu, Kerala Ayurveda Ranchi is specialized in traditional ayurvedic treatment for diseases. Visit our website for more details.

    ReplyDelete
  59. Thanks! Very interesting to read. This is really very helpful. Best Data Science Course in Jaipur

    ReplyDelete