nsv2042 commited on
Commit
3c561f4
1 Parent(s): 9da3b6e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -36
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
- # Global storage for APK data
10
  apk_context = {"smali": {}, "java": {}, "info": ""}
11
 
12
  def check_java():
13
- """Function to check if Java is installed and accessible."""
14
  try:
15
  result = subprocess.run(["java", "-version"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
16
- print("Java is available:", result.stderr.decode()) # Java version information
17
  except FileNotFoundError:
18
- raise EnvironmentError("Java is not installed or not found in the PATH.")
19
  except Exception as e:
20
- raise EnvironmentError(f"Unexpected error checking Java installation: {str(e)}")
21
 
22
  def install_tools():
23
- """Install Baksmali and JADX tools."""
24
  baksmali_path = "/usr/local/bin/baksmali.jar"
25
  jadx_path = "/usr/local/bin/jadx/bin/jadx"
26
 
27
- # Check for Java availability
28
  check_java()
29
 
30
- # Install Baksmali if not present
31
  if not os.path.exists(baksmali_path):
32
- print("Installing Baksmali...")
33
  subprocess.run(
34
  [
35
  "curl",
@@ -41,10 +41,10 @@ def install_tools():
41
  check=True,
42
  )
43
 
44
- # Install JADX if not present
45
  jadx_zip_path = "/usr/local/bin/jadx.zip"
46
  if not os.path.exists(jadx_path):
47
- print("Installing JADX...")
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("JADX executable not found in the expected path.")
63
 
64
  install_tools()
65
 
66
  def decompile_apk(apk_file):
67
  if apk_file is None:
68
- return "No file uploaded. Please upload an APK file."
69
-
70
- temp_apk_path = apk_file.name # Use the file path directly
71
  output_dir = tempfile.mkdtemp()
72
  try:
73
- # Decompile using 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
- # Decompile using 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
- # Collect decompiled Smali files
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
- # Collect decompiled Java files
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
- # Store results in global context
104
  apk_context["smali"] = smali_files
105
  apk_context["java"] = java_files
106
 
107
- return f"Decompilation successful. Extracted {len(smali_files)} Smali files and {len(java_files)} Java files."
108
 
109
  except subprocess.CalledProcessError as e:
110
- return f"Error during decompilation: {e.stderr.decode('utf-8') if e.stderr else str(e)}"
111
  except Exception as e:
112
- return f"Error during decompilation: {str(e)}"
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 "No decompiled APK available. Please upload and decompile an APK first."
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"**Relevant Smali Code:**\n\n{smali_result[:1000]}\n\n"
134
- response += f"**Relevant Java Code:**\n\n{java_result[:1000]}"
135
  return response
136
 
137
  except Exception as e:
138
- return f"Error during search: {str(e)}"
139
 
140
  apk_upload_interface = gr.Interface(
141
  fn=decompile_apk,
142
- inputs=gr.File(label="Upload APK File", file_types=[".apk"]),
143
  outputs="text",
144
- title="APK Analyzer",
145
- description="Upload an APK file to decompile it into Smali and Java source code.",
146
  )
147
 
148
  chat_interface = gr.Interface(
149
  fn=query_apk_chat,
150
- inputs=gr.Textbox(lines=3, placeholder="Ask a question about the APK code..."),
151
- outputs=gr.Textbox(lines=10, label="Response from AI"),
152
- title="APK Chatbot",
153
- description="Ask questions about the APK's source code in Smali or Java.",
154
  )
155
 
156
- iface = gr.TabbedInterface([apk_upload_interface, chat_interface], ["Upload & Analyze", "Chat with AI"])
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()