Patch class file java

Патчим байт-код Java на лету

В то время, пока dx занимается поддержкой своего нового обфускатора и разработкой улучшенной версии класса для работы с HTTP на PHP, я подготовил небольшую статью, чтобы разбавить пустоту, царящую в блоге.

Речь пойдет о правке байт-кода Java, как видно из названия статьи. Когда-то давно я уже писал подобную статью про модификацию официального приложения VK под Android, но там я просто патчил байт-код, содержащийся в .class-файле. Теперь мы сделаем примерно то же самое, но на лету, без внесения изменений в файлы.

Начну с небольшой предыстории, зачем мне это вообще понадобилось (многие из моих статей все-таки связаны с какой-то реальной проблемой, которая у меня внезапно возникла). Итак: мне написал человек и попросил «помочь» с программой Lazy SSH. На первый взгляд программа ничем не выделялась, обычный .exe, определяемый PEiD, как: Microsoft Visual C++ 6.0 [Overlay]. Однако, наличие секции экспортов у исполняемого файла меня насторожило, а ее содержимое подсказало, с чем я имею дело: все экспортируемые функции обладали префиксом _Java_com_regexlab_j2e_, который недвусмысленно намекает, что программа на Java была чем-то преобразована в .exe. Google подсказал, что для этого был использован Jar2Exe от RegExLab. Также Google подсказал способ получения .jar-файла из исполняемого файла, по крайней мере для этого случая. Перейдем к делу.

Поместим файл e2j-agent.jar в директорию с Lazy SSH и установим переменную окружения в соответствии с мануалом:

Источник

Didier Stevens

010 Editor is one of few commercial applications that I use daily. It’s a powerful binary editor with scripting and templates.

I recently had to patch a Java .class file: extend a string inside that class. Before going the route of decompiling / editing / recompiling, I tried with 010 Editor.

Here is the file opened inside the editor:

When opening the file, 010 Editor recognized the .class extension and installed and ran the template for .class files. That’s what I wanted to know: is there a template for .class files? Yes, there is!

Here is how you can apply a template manually, in case the file extension is not the original extension:

And this is how the template results look like:

Under the hex/ascii dump, the template results are displayed: a set of nested fields that match the internal structure of .class file. For example, the first field I selected here, u4 magic, is the magic header of a .class file: CAFEBABE.

The string I want to extend is this one:

I need to extend string “1.2 (20210922)”. Into something like “1.2 (20210922a)”.

Doing so will make the string longer, thus I need to add a byte to the file (trivial), but I also need to make sure that the binary structure of .java files remain valid: for example, if there is something in that structure like a field length, I need to change the field length too.

Читайте также:  Php pdo user class

I’m not familiar with the internal structure of .class files, that why I’m using 010 Editor’s .class template, hoping that the template will make it clear to me what needs to be changed.

To find the template result field I need to modify, I position my cursor on the string I want to modify inside the ASCII dump, I right-click and select “Jump To Template Variable”:

Which selects the corresponding template variable:

So my cursor was on the 10th byte (bytes[9]) of the string, which is part of template variable cp_info constant_pool[27]. From that I gather that the string I want to modify is inside a pool of constants.

I can select that template variable:

And here I can see which bytes inside the .class file were selected. It’s not only the string, but also bytes that represent the tag and length. The length is 14, that’s indeed the length of the string I want to extend. Since I want to add 1 character, I change the length from 14 to 15: I can do that inside the template results by double-clicking the value 14, I don’t need to make that change inside the hexdump:

Next I need to add a character to the string. I can do that in the ASCII dump:

I have to make sure that the editor is in insert mode (INS), so that when I type characters, they are inserted at the cursor, in stead of overwriting existing bytes:

And then I can type my extra character:

So I have changed the constant string I wanted to change. Maybe there are more changes to make to the internal structure of this .class file, like other length fields … I don’t know. But what I do as an extra check is: save the modified file and run the template again. It runs without errors, and the result looks good.

So I guess there are no more changes to make, and I decide to tryout my modified .class file and see what happens: it works, so there are no other changes to make.

Источник

Patching Java Executables – The Easy Way

The process of patching a Java executable (.jar files) without the original source code has been known for a while. As I know of, currently there are two ways of doing it:

  1. Decompile the executable > Import decompiled classes to an IDE (Eclipse, NetBeans, etc.) > Modify source code > Recompile > Repack
  2. Extract Java classes from executable > Modify Java Bytecode > Verify > Repack

Method (1) has big advantage if you are already familiar Java or similar OO-styled languages. However, in practice it has two main drawbacks:

  1. Typically, the targeted jar file has dependencies to other libraries. You should be familiar with linking those dependencies to your project
  2. The decompilation process is not an exact science, so expect to fix syntactical errors before getting it to recompile

On one project after importing a decompiled jar file into Eclipse there are nearly 1000 syntactical errors. Going through and fixing all of it would be a pain, especially what you want to do is just edit a few lines of code.

Читайте также:  Php spawn child process

In this blog post, I want to introduce to you a method (2) of patching Java. It is faster, less error-prone and quite simple to execute. I hope it will be useful for developers that are in need of patching Java. Some potential use cases are:

  • Bypass software restrictions (license, signature, hash, etc.)
  • Patch security issues without original source code
  • Inject custom code to application

In the example below, I will show you how to patch the JBoss encrypting library to use custom private key to encrypt data source strings.

Background

JBoss has a SecureIdentityLoginModule utility to encrypt data source password in XML configuration files. More info can be found at the JBoss Community Site. In JBoss 7, the module is located in picketbox-4.0.7.Final.jar

The actual command to encrypt the password is:

java -cp modulesorgJBossloggingmainJBoss-logging-3.1.0.GA.jar;modulesorgpicketboxmainpicketbox-4.0.7.Final.jar  org.picketbox.datasource.security.SecureIdentityLoginModule password
Encoded password: 5dfc52b51bd35553df8592078de921bc

Problem

If you peek into the source code, the utility is using Blowfish encryption algorithm with a fixed key set to: “jaas is the way”. There is already a tool to decrypt it located at https://usefulfor.com/security/2009/09/24/beware-of-JBoss-secureidentityloginmodule/.

Objective

The objective is to modify default private key. The key is still in the jar file and you can call the corresponding decode() function of the jar file to decrypt it anyway. Hence for a production system I would recommend switching to use the keystore-based JaasSecurityDomainIdentityLoginModule instead. More information could be found at https://community.JBoss.org/wiki/EncryptingDataSourcePasswords.

High-level steps:

  1. Setup the environment
  2. Use JD-GUI to peek into the jar file
  3. Unpack the jar file
  4. Modify the .class file with a Java Bytecode Editor
  5. Repack the modified classes into new archive file
  6. Verify it with JD-GUI

Step 1: Setup the Java environment

Most computers should have the JRE installed by default. For this tutorial, you will need to download and install the latest version of JDK. For this example, I am using JDK 6 update 35.

You may also need to add the JDK bin folder to your PATH environment variable. Upon completion, open up a command line console and type:

The result should look something like this:

java version “1.6.0_35″
Java(TM) SE Runtime Environment (build 1.6.0_35-b10)
Java HotSpot(TM) 64-Bit Server VM (build 20.10-b01, mixed mode)

Step 2: Use JD-GUI to peek into the jar file

Bytecode editors typically do not support decompiling Java executables. For that reason, I prefer to use a standalone decompiler to quickly browse decompiled classes and identify potential classes/methods. My favorite tool for this task is JD-GUI (we also need it later on to verify the modified bytecode):

Img E E Aed

As shown in the picture above, browsing to SecurityIdentityLoginModule reveals the default secret key used to encrypt string.

Step 3: Unpack the jar file

The below commands will create new directory > Copy jar file > Extract all the classes (note that in Windows you can use 7zip to extract them as well)

cd modulesorgpicketboxmain
mkdir picketbox
cp picketbox-4.0.7.Final.jar picketbox
cd picketbox
jar -xf picketbox-4.0.7.Final.jar

Step 4: Modify the .class file with a Java Bytecode Editor

In this example we need to modify two methods of SecureIdentityLoginModule class: encode() and decode(). Note that the original encryption/decryption methods only work with 16-character key. To keep it simple, I will modify default key “jaas is the way” to “java is the way” to keep the length intact.

Читайте также:  Jframe java на весь экран

Img E Edf D

Step 5: Repack the jar file

Take the changed class file and repack the jar file

cd picketbox
jar -cvf picketbox.jar *.*

Step 6: Verify the changes with JD-GUI

JBE tool has Code Verification feature, but in practice, I found it complains too much . Hence, I use JD-GUI again to verify correctness of the modified jar file.

If there’s any error in the modified class file, JD-GUI will not able to render the new jar file. If things go well, you should see your changes reflected in the patched jar file:

Img E Ded E

Final test:

java -cp modulesorgJBossloggingmainJBoss-logging-3.1.0.GA.jar;modulesorgpicketboxmainpicketbox.jar org.picketbox.datasource.security.SecureIdentityLoginModule password
Encoded password: 3f8c894b05a5462a4a06c734ae626874

The last step would be overwriting the patched file to the original one.

I hope you had fun. Thanks Steve for helping me proofread this and happy hacking!

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Library for easy patching of arbitrary java classes using mainly XML or other configuration files.

License

LunNova/JavaPatcher

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A library which allows flexible patching of java bytecode using javassist and config files.

Copyright © 2014, nallar rallan.pcl+gt@gmail.com JavaPatcher is licensed under the MIT license.

Including JavaPatcher in your project

JavaPatcher is available from the maven repo http://repo.nallar.me/ under the group «me.nallar», artifact «javapatcher» and version «1.0».

If you include JavaPatcher in your project, you must also bundle Javassist version 3.17 or later.

Download the latest builds from Jenkins.

JavaPatcher is built using Gradle.

Coding and Pull Request Formatting

  • Generally follows the Oracle coding standards.
  • Tabs, no spaces.
  • Pull requests must compile and work.
  • Pull requests must be formatted properly.

Please follow the above conventions if you want your pull requests accepted.

YourKit is kindly supporting open source projects with its full-featured Java Profiler. YourKit, LLC is the creator of innovative and intelligent tools for profiling Java and .NET applications. Take a look at YourKit’s leading software products: YourKit Java Profiler and YourKit .NET Profiler.

About

Library for easy patching of arbitrary java classes using mainly XML or other configuration files.

Источник

Оцените статью