How to decompile jar

How to decompile jar

In the past few days, I had some fun trying to understand the inner workings of an APK file. Previously, I had only used the legendary JD-GUI as a decompiler for some CTF challenges. But when dealing with more complex code, I found that looking at the output of different decompilers can help. Hence, I did a little research to find more decompilers that use different approaches. This post serves as a little reference on how to build and use these tools.

Introduction

That means, to reconstruct the source code for an APK file, there are two approaches:

For the first approach, jadx is the way to go. If your target is an APK file, you should definitely give this tool a try. I saw that a lot of APK analyzers rely on it, which probably means that it does a good job.

It [dex2jar] works reasonably well most of the time, but a lot of obscure features or edge cases will cause it to fail or even silently produce incorrect results. By contrast, Enjarify is designed to work in as many cases as possible, even for code where Dex2jar would fail.

Enjarify outputs—as the name suggests—a JAR file. From there, several popular tools can be used to reconstruct Java source code.

To sum up, the following figure illustrates both options we have.

How to decompile jar. Смотреть фото How to decompile jar. Смотреть картинку How to decompile jar. Картинка про How to decompile jar. Фото How to decompile jar

We can either use jadx to directly decompile the APK, or we can use Enjarify which enables us to make use of more classical Java decompilers.

Decompilers

Next, let me show you which decompilers I was particularly interested in, and how to install them.

When I saw the homepage of CFR the first time, the project quickly gained my sympathy. No fancy JavaScript-based interface, just a plain HTML site. The first sentence on the page immediately caught my eye:

Releases can be found on GitHub and other places, although I’m not sure if it is entirely open-source. Being a Java project, it compiles conveniently into a single JAR file.

That JAR file can be used as follows:

For larger JAR files I found it to run out of memory. You can simply adapt the size of the memory allocation pool of the JVM if that happens to you, too.

This example will allow a maximum of 4GB to be allocated.

Fernflower

Next up is Fernflower, which is part of IntelliJ IDEA. Everyone mentions that it is an analytical decompiler (as stated in their project description), but nobody points out what this actually means. I only found this Stackoverflow question, which unfortunately remains unanswered as of today.

Anyway, since there are no self-contained releases, you need to build it yourself. As a Gradle-based project, you can clone it and then run the following command given that Gradle is installed on your machine.

The invocation of Fernflower is similar to that of CFR.

Krakatau

Remember Enjarify from above? The very same author is also the developer of a decompiler named Krakatau.

In contrast to the other projects, this one is written in Python. And I think this is the reason why it’s a bit different from the others.

Next, make sure you have jars containing defintions (sic!) for any external classes (i.e. libraries) that might be referenced by the jar you are trying to decompile. This includes the standard library classes (i.e. JRT).

So we download that tool and run the following commands.

This should have written a file rt.jar inside the directory.

Given this file, we can run Krakatau as follows.

Procyon

The final and fourth decompiler I looked at is Procyon.

Even though the project’s wiki links to the downloads over at Bitbucket, as of the time of writing there are no downloads available. That’s why I tried to compile it myself.

Oh no! This one doesn’t compile smoothly.

As a last resort of help I checked if there is anything in the repositories, and luckily—at least on Debian—it’s packaged and ready to use.

Once installed, the usage is straightforward.

But hold on, if Debian packages Procyon, there must be a way to build it.

A quick search in their bug tracker revealed bug #909259. The maintainers had the exact same issue!

So let’s see how they patched the source to fix it. The discussion in the bug report links to this commit diff. There we can see that a patch was added for compatibility with OpenJDK 11.

I had to tweak the patch as the upstream source has already diverged but finally managed to build it. If you want to build it yourself, here is the patch file I was successful with.

First, apply the patch, then invoke Gradle to build the project.

Decompilers to go

You might be wondering: Isn’t there an easier way? And I suppose it depends.

GUI tools like Bytecode Viewer also use multiple decompilers under the hood and allow you to see their output nicely side-by-side. But I prefer going the manual way to see what parameters I can adjust. You have more control over how you launch a decompiler, and you will probably learn new things.

To make it all a bit more accessible, I created a Docker image where all four decompilers are available out-of-the-box. Visit the GitHub page of the project to get an idea of how to use it.

Let me note that it also includes the capability to decompile APK files. As discussed early on, Enjarify is used to convert your APKs to JARs. It will also decompile your APK files via jadx.

Conclusion

I kept this post deliberately short and practical. The goal was to write down my steps for future reference, and I thought it could be useful for others.

If decompilation does not get you anywhere, other tools might be helpful. Instead of trying to reconstruct the source, maybe it’s enough to slightly adjust the behavior of your target. In that case, you should look into instrumentation as provided by Frida and Soot.

Декомпиляция Java приложений

Декомпиляция — процесс воссоздания исходного кода декомпилятором

Недавно я задался вопросом: Какой декомпилятор лучше?
Начал мучить Google, экспериментировать. В итоге нашел отличное решение. Как декомпильнуть любую программу и получить рабочие «исходники»? Об этом в сабже.

Краткий обзор популярных декомпиляторов

Mocha

Mocha (автор — Hanpeter van Vliet)— это, вероятно, один из первых выпущенных декомпиляторов Java. Предоставляет консольный пользовательский интерфейс. Его релиз состоялся в 1996-ом году, ещё до того, как появился Java Development Kit версии 1.1

JAva Decompiler
DJ Java Decompiler

DJ Java Decompiler (автор — Atanas Neshkov) — долгое время вопреки названию являлся лишь графической оболочкой для предыдущего декомпилятора, позволявшей легко и удобно выбрать аргументы командной строки для вызова JAD. В текущей версии добавлена поддержка аннотаций, но декомпилятор стал условно-бесплатным (необходима покупка после 10 пробных использований).

JD-Core
Fernflower

Мой выбор

Fernflower будет развиваться в сторону деобфускатора

Специальных функций деобфускации Fernflower сейчас не содержит, они будут подключаться в дальнейшем отдельными модулями

Не хватает еще модуля переименования

ProGuardDeobfuscator — небольшая модификация программы ProGuard, превращающая ее в квази-деобфускатор. В процессе обработки короткие обфусцированные имена пакетов, классов, полей и методов заменяются на более осмысленные и уникальные в пределах Jar файла.

Скачать исходники и сам деобфускатор: projectd8.org/Programs/Java/PGD

Инструменты все есть, но лично я, для облегчения воссоздания сорцов использую так же любимую Netbeans IDE — очень сильно помогает своими подсказками, особенно когда классов много.
Спасибо за внимание!

Ссылки

UPD:
Извиняюсь, в offline версии Fernflower присутствует модуль переименований и уйма других штук — Readme

How to decompile jar. Смотреть фото How to decompile jar. Смотреть картинку How to decompile jar. Картинка про How to decompile jar. Фото How to decompile jar

3 Answers 3

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

I found that jd-cmd does the job just fine, and works recursively in sub-folders for multiple files. To decompile a group of files on the command line, run the following commands:

in 2021, seems the command line is more simple:

decompile target.jar to jar_result folder, and output the log with ALL levels.

How to decompile jar. Смотреть фото How to decompile jar. Смотреть картинку How to decompile jar. Картинка про How to decompile jar. Фото How to decompile jar

The JD-CMD GitHub project claims to be able to do so. However, most people I know use JD-GUI.

JD-Core is a library that reconstructs Java source code from one or more “.class” files. JD-Core may be used to recover lost source code and explore the source of Java runtime libraries. New features of Java 5, such as annotations, generics or type “enum”, are supported. JD-GUI and JD-Eclipse include JD-Core library.

I should include that when a source file is compiled, things like the variable assignment and the names of those variables are changed. Similarly, syntactic sugar is changed into what it actually is (such as x += i turns into x = x + i ).

How to decompile a whole Jar file? [closed]

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Does anyone know of a free decompiler that can decompile an entire Jar file instead of a single class? I have a problem with sub classes like name$1.class name$2.class name.class

8 Answers 8

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Quiltflower is a modern, general purpose decompiler focused on improving code quality, speed, and usability.
Quiltflower is a fork of Fernflower and Forgeflower.

Originally intended just for use with the QuiltMC toolchain with Minecraft, Quiltflower quickly expanded to be a general purpose java decompiler aiming to create code that is as accurate and clean as possible.

If the name sounds familiar it’s because Quiltflower is a fork of Fernflower, the (in)famous decompiler that was developed by Stiver, maintained by Jetbrains, and became the default decompiler in Intellij IDEA.
Fernflower also quickly found its way into many other tools.

Over the past year, Quiltflower has added support for features such as modern string concatenation, a code formatter, sealed classes, pattern matching, switch expressions, try-with-resources, and more. Quiltflower also focuses on the code quality of the decompiled output, and takes readability very seriously.

2009: JavaDecompiler can do a good job with a jar: since 0.2.5, All files, in JAR files, are displayed.

How to decompile jar. Смотреть фото How to decompile jar. Смотреть картинку How to decompile jar. Картинка про How to decompile jar. Фото How to decompile jar

The JD-Eclipse doesn’t seem to have changed since late 2009 though (see Changes).
So its integration with latest Eclipse (3.8, 4.2+) might be problematic.

JD-Core is actively maintained.

Both are the result of the fantastic work of (SO user) Emmanuel Dupuy.

2018: A more modern option, mentioned in the comments by David Kennedy Araujo:

Fernflower is the first actually working analytical decompiler for Java and probably for a high-level programming language in general.

See also How to decompile to java files intellij idea for a command working with recent IntelliJ IDEA.

How do I «decompile» Java class files? [closed]

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

What program can I use to decompile a class file? Will I actually get Java code, or is it just JVM assembly code?

On Java performance questions on this site I often see responses from people who have «decompiled» the Java class file to see how the compiler optimizes certain things.

How to decompile jar. Смотреть фото How to decompile jar. Смотреть картинку How to decompile jar. Картинка про How to decompile jar. Фото How to decompile jar

19 Answers 19

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Update February 2016:

the most popular Java decompiler, but primarily of this age only. Written in C++, so very fast.
Outdated, unsupported and does not decompile correctly Java 5 and later

So your mileage may vary with recent jdk (7, 8).

The same site list other tools.

Original answer: Oct. 2008

Java Decompiler (Yet another Fast Java decompiler) has:

How to decompile jar. Смотреть фото How to decompile jar. Смотреть картинку How to decompile jar. Картинка про How to decompile jar. Фото How to decompile jar

It works with compilers from JDK 1.1.8 up to JDK 1.7.0, and others (Jikes, JRockit, etc.).

It features an online live demo version that is actually fully functional! You can just drop a jar file on the page and see the decompiled source code without installing anything.

How to decompile jar. Смотреть фото How to decompile jar. Смотреть картинку How to decompile jar. Картинка про How to decompile jar. Фото How to decompile jar

There are a few decompilers out there. A quick search yields:

These produce Java code. Java comes with something that lets you see JVM byte code (javap).

To see Java source code check some decompiler. Go search for jad.

If you want to see bytecodes, just use javap which comes with the JDK.

I tried several, and Procyon seemed to work the best for me. It’s under active development and supports many features of the latest versions of Java.

These are the others I tried:

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *