Update app.py
Browse files
app.py
CHANGED
@@ -1,35 +1,35 @@
|
|
1 |
import os
|
2 |
-
import tempfile
|
3 |
import subprocess
|
|
|
4 |
from androguard.misc import AnalyzeAPK
|
5 |
from transformers import pipeline
|
6 |
from sentence_transformers import SentenceTransformer, util
|
7 |
import gradio as gr
|
8 |
|
9 |
-
#
|
10 |
apk_context = {"smali": {}, "java": {}, "info": ""}
|
11 |
|
12 |
def check_java():
|
13 |
-
"""
|
14 |
try:
|
15 |
result = subprocess.run(["java", "-version"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
16 |
-
print("Java
|
17 |
except FileNotFoundError:
|
18 |
-
raise EnvironmentError("Java
|
19 |
except Exception as e:
|
20 |
-
raise EnvironmentError(f"
|
21 |
|
22 |
def install_tools():
|
23 |
-
"""
|
24 |
baksmali_path = "/usr/local/bin/baksmali.jar"
|
25 |
jadx_path = "/usr/local/bin/jadx/bin/jadx"
|
26 |
|
27 |
-
#
|
28 |
check_java()
|
29 |
|
30 |
-
#
|
31 |
if not os.path.exists(baksmali_path):
|
32 |
-
print("
|
33 |
subprocess.run(
|
34 |
[
|
35 |
"curl",
|
@@ -41,10 +41,10 @@ def install_tools():
|
|
41 |
check=True,
|
42 |
)
|
43 |
|
44 |
-
#
|
45 |
jadx_zip_path = "/usr/local/bin/jadx.zip"
|
46 |
if not os.path.exists(jadx_path):
|
47 |
-
print("
|
48 |
subprocess.run(
|
49 |
[
|
50 |
"curl",
|
@@ -59,32 +59,32 @@ def install_tools():
|
|
59 |
if os.path.exists(jadx_path):
|
60 |
subprocess.run(["chmod", "+x", jadx_path], check=True)
|
61 |
else:
|
62 |
-
raise FileNotFoundError("
|
63 |
|
64 |
install_tools()
|
65 |
|
66 |
def decompile_apk(apk_file):
|
67 |
if apk_file is None:
|
68 |
-
return "
|
69 |
-
|
70 |
-
temp_apk_path = apk_file.name #
|
71 |
output_dir = tempfile.mkdtemp()
|
72 |
try:
|
73 |
-
#
|
74 |
smali_output = os.path.join(output_dir, "smali")
|
75 |
subprocess.run(
|
76 |
["java", "-jar", "/usr/local/bin/baksmali.jar", "d", temp_apk_path, "-o", smali_output],
|
77 |
check=True
|
78 |
)
|
79 |
|
80 |
-
#
|
81 |
java_output = os.path.join(output_dir, "java")
|
82 |
subprocess.run(
|
83 |
["/usr/local/bin/jadx/bin/jadx", "-d", java_output, temp_apk_path],
|
84 |
check=True
|
85 |
)
|
86 |
|
87 |
-
#
|
88 |
smali_files = {}
|
89 |
for root, _, files in os.walk(smali_output):
|
90 |
for file in files:
|
@@ -92,7 +92,7 @@ def decompile_apk(apk_file):
|
|
92 |
with open(os.path.join(root, file), "r") as f:
|
93 |
smali_files[file] = f.read()
|
94 |
|
95 |
-
#
|
96 |
java_files = {}
|
97 |
for root, _, files in os.walk(java_output):
|
98 |
for file in files:
|
@@ -100,16 +100,16 @@ def decompile_apk(apk_file):
|
|
100 |
with open(os.path.join(root, file), "r") as f:
|
101 |
java_files[file] = f.read()
|
102 |
|
103 |
-
#
|
104 |
apk_context["smali"] = smali_files
|
105 |
apk_context["java"] = java_files
|
106 |
|
107 |
-
return f"
|
108 |
|
109 |
except subprocess.CalledProcessError as e:
|
110 |
-
return f"
|
111 |
except Exception as e:
|
112 |
-
return f"
|
113 |
|
114 |
def build_search_index():
|
115 |
smali_texts = [f"{k}\n{v}" for k, v in apk_context["smali"].items()]
|
@@ -121,7 +121,7 @@ def build_search_index():
|
|
121 |
|
122 |
def query_apk_chat(user_message):
|
123 |
if not apk_context["smali"] and not apk_context["java"]:
|
124 |
-
return "
|
125 |
|
126 |
try:
|
127 |
model, smali_texts, smali_embeddings, java_texts, java_embeddings = build_search_index()
|
@@ -130,28 +130,28 @@ def query_apk_chat(user_message):
|
|
130 |
java_scores = util.pytorch_cos_sim(query_embedding, java_embeddings).squeeze(0)
|
131 |
smali_result = smali_texts[smali_scores.argmax().item()]
|
132 |
java_result = java_texts[java_scores.argmax().item()]
|
133 |
-
response = f"**
|
134 |
-
response += f"**
|
135 |
return response
|
136 |
|
137 |
except Exception as e:
|
138 |
-
return f"
|
139 |
|
140 |
apk_upload_interface = gr.Interface(
|
141 |
fn=decompile_apk,
|
142 |
-
inputs=gr.File(label="
|
143 |
outputs="text",
|
144 |
-
title="APK
|
145 |
-
description="
|
146 |
)
|
147 |
|
148 |
chat_interface = gr.Interface(
|
149 |
fn=query_apk_chat,
|
150 |
-
inputs=gr.Textbox(lines=3, placeholder="
|
151 |
-
outputs=gr.Textbox(lines=10, label="
|
152 |
-
title="APK
|
153 |
-
description="
|
154 |
)
|
155 |
|
156 |
-
iface = gr.TabbedInterface([apk_upload_interface, chat_interface], ["
|
157 |
iface.launch()
|
|
|
1 |
import os
|
|
|
2 |
import subprocess
|
3 |
+
import tempfile
|
4 |
from androguard.misc import AnalyzeAPK
|
5 |
from transformers import pipeline
|
6 |
from sentence_transformers import SentenceTransformer, util
|
7 |
import gradio as gr
|
8 |
|
9 |
+
# Contexto global para armazenar dados do APK
|
10 |
apk_context = {"smali": {}, "java": {}, "info": ""}
|
11 |
|
12 |
def check_java():
|
13 |
+
"""Função para verificar se o Java está instalado e acessível."""
|
14 |
try:
|
15 |
result = subprocess.run(["java", "-version"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
16 |
+
print("Java está disponível:", result.stderr.decode()) # Exibe informações sobre a versão do Java
|
17 |
except FileNotFoundError:
|
18 |
+
raise EnvironmentError("Java não está instalado ou não foi encontrado no PATH.")
|
19 |
except Exception as e:
|
20 |
+
raise EnvironmentError(f"Erro inesperado ao verificar a instalação do Java: {str(e)}")
|
21 |
|
22 |
def install_tools():
|
23 |
+
"""Instalar ferramentas como Baksmali e JADX."""
|
24 |
baksmali_path = "/usr/local/bin/baksmali.jar"
|
25 |
jadx_path = "/usr/local/bin/jadx/bin/jadx"
|
26 |
|
27 |
+
# Verificar se o Java está disponível
|
28 |
check_java()
|
29 |
|
30 |
+
# Instalar o Baksmali caso não esteja presente
|
31 |
if not os.path.exists(baksmali_path):
|
32 |
+
print("Instalando o Baksmali...")
|
33 |
subprocess.run(
|
34 |
[
|
35 |
"curl",
|
|
|
41 |
check=True,
|
42 |
)
|
43 |
|
44 |
+
# Instalar o JADX caso não esteja presente
|
45 |
jadx_zip_path = "/usr/local/bin/jadx.zip"
|
46 |
if not os.path.exists(jadx_path):
|
47 |
+
print("Instalando o JADX...")
|
48 |
subprocess.run(
|
49 |
[
|
50 |
"curl",
|
|
|
59 |
if os.path.exists(jadx_path):
|
60 |
subprocess.run(["chmod", "+x", jadx_path], check=True)
|
61 |
else:
|
62 |
+
raise FileNotFoundError("Executável do JADX não encontrado no caminho esperado.")
|
63 |
|
64 |
install_tools()
|
65 |
|
66 |
def decompile_apk(apk_file):
|
67 |
if apk_file is None:
|
68 |
+
return "Nenhum arquivo enviado. Por favor, envie um arquivo APK."
|
69 |
+
|
70 |
+
temp_apk_path = apk_file.name # Usar o caminho do arquivo diretamente
|
71 |
output_dir = tempfile.mkdtemp()
|
72 |
try:
|
73 |
+
# Decompilar usando o Baksmali
|
74 |
smali_output = os.path.join(output_dir, "smali")
|
75 |
subprocess.run(
|
76 |
["java", "-jar", "/usr/local/bin/baksmali.jar", "d", temp_apk_path, "-o", smali_output],
|
77 |
check=True
|
78 |
)
|
79 |
|
80 |
+
# Decompilar usando o JADX
|
81 |
java_output = os.path.join(output_dir, "java")
|
82 |
subprocess.run(
|
83 |
["/usr/local/bin/jadx/bin/jadx", "-d", java_output, temp_apk_path],
|
84 |
check=True
|
85 |
)
|
86 |
|
87 |
+
# Coletar arquivos Smali decompilados
|
88 |
smali_files = {}
|
89 |
for root, _, files in os.walk(smali_output):
|
90 |
for file in files:
|
|
|
92 |
with open(os.path.join(root, file), "r") as f:
|
93 |
smali_files[file] = f.read()
|
94 |
|
95 |
+
# Coletar arquivos Java decompilados
|
96 |
java_files = {}
|
97 |
for root, _, files in os.walk(java_output):
|
98 |
for file in files:
|
|
|
100 |
with open(os.path.join(root, file), "r") as f:
|
101 |
java_files[file] = f.read()
|
102 |
|
103 |
+
# Armazenar resultados no contexto global
|
104 |
apk_context["smali"] = smali_files
|
105 |
apk_context["java"] = java_files
|
106 |
|
107 |
+
return f"Decompilação bem-sucedida. Extraídos {len(smali_files)} arquivos Smali e {len(java_files)} arquivos Java."
|
108 |
|
109 |
except subprocess.CalledProcessError as e:
|
110 |
+
return f"Erro durante a decompilação: {e.stderr.decode('utf-8') if e.stderr else str(e)}"
|
111 |
except Exception as e:
|
112 |
+
return f"Erro durante a decompilação: {str(e)}"
|
113 |
|
114 |
def build_search_index():
|
115 |
smali_texts = [f"{k}\n{v}" for k, v in apk_context["smali"].items()]
|
|
|
121 |
|
122 |
def query_apk_chat(user_message):
|
123 |
if not apk_context["smali"] and not apk_context["java"]:
|
124 |
+
return "Nenhum APK decompilado disponível. Por favor, envie e decompile um APK primeiro."
|
125 |
|
126 |
try:
|
127 |
model, smali_texts, smali_embeddings, java_texts, java_embeddings = build_search_index()
|
|
|
130 |
java_scores = util.pytorch_cos_sim(query_embedding, java_embeddings).squeeze(0)
|
131 |
smali_result = smali_texts[smali_scores.argmax().item()]
|
132 |
java_result = java_texts[java_scores.argmax().item()]
|
133 |
+
response = f"**Código Smali relevante:**\n\n{smali_result[:1000]}\n\n"
|
134 |
+
response += f"**Código Java relevante:**\n\n{java_result[:1000]}"
|
135 |
return response
|
136 |
|
137 |
except Exception as e:
|
138 |
+
return f"Erro durante a busca: {str(e)}"
|
139 |
|
140 |
apk_upload_interface = gr.Interface(
|
141 |
fn=decompile_apk,
|
142 |
+
inputs=gr.File(label="Enviar arquivo APK", file_types=[".apk"]),
|
143 |
outputs="text",
|
144 |
+
title="Analisador de APK",
|
145 |
+
description="Envie um arquivo APK para decompilá-lo em código Smali e Java.",
|
146 |
)
|
147 |
|
148 |
chat_interface = gr.Interface(
|
149 |
fn=query_apk_chat,
|
150 |
+
inputs=gr.Textbox(lines=3, placeholder="Faça uma pergunta sobre o código do APK..."),
|
151 |
+
outputs=gr.Textbox(lines=10, label="Resposta do AI"),
|
152 |
+
title="Chat com APK",
|
153 |
+
description="Faça perguntas sobre o código-fonte do APK em Smali ou Java.",
|
154 |
)
|
155 |
|
156 |
+
iface = gr.TabbedInterface([apk_upload_interface, chat_interface], ["Enviar & Analisar", "Conversar com AI"])
|
157 |
iface.launch()
|