aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/gq/malwarefight/nosession/utils/Utils.java
blob: d26d6f2da2323212c0108c4e7d30673198ff6f0d (plain)
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
package gq.malwarefight.nosession.utils;

import com.google.common.annotations.Beta;
import com.google.common.collect.ForwardingMultimap;
import com.google.gson.Gson;
import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService;
import gq.malwarefight.nosession.linux.libc.Libc;
import gq.malwarefight.tokenapp.Main;
import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.lang3.CharEncoding;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.Validate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.Opcodes;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Scanner;
import java.util.UUID;

public class Utils {
    public static int PORT = -1;
    private static final int BASE_PORT = 47777;

    public static void copy(InputStream i, OutputStream o) throws IOException {
        byte[] buffer = new byte[16384];
        int read;
        while ((read = i.read(buffer)) > 0) {
            o.write(buffer, 0, read);
        }
        i.close();
        o.close();
    }

    public static byte[] read(InputStream i, Character delimiter) throws IOException {
        byte[] buffer = new byte[512];
        int index = 0;
        while (true) {
            int in = i.read();
            if (in == -1 || (delimiter != null && delimiter == in)) {
                return Arrays.copyOfRange(buffer, 0, index);
            }
            if (index == buffer.length) {
                // grow the buffer
                byte[] newBuffer = new byte[buffer.length * 2];
                System.arraycopy(
                        buffer, 0, newBuffer, 0, buffer.length
                );
                buffer = newBuffer;
            }
            buffer[index] = (byte) in;
            index++;
        }
    }

    public static String readString(InputStream i, Character delimiter) throws IOException {
        return new String(read(i, delimiter), StandardCharsets.UTF_8);
    }

    public static Socket getProperSocket(UUID id) {
        if (PORT == -1) {
            Socket socket = null;
            int port;
            for (int i = BASE_PORT; i < BASE_PORT + 10; i++) {
                try {
                    socket = new Socket();
                    socket.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), i));
                    socket.getOutputStream().write("uuid\n".getBytes(StandardCharsets.UTF_8));
                    String value = readString(socket.getInputStream(), '\n');
                    if (UUID.fromString(value).equals(id)) {
                        port = i;
                        PORT = port;
                        break;
                    }
                } catch (Exception exception) {
                    socket = null;
                }
            }
            return socket;
        } else {
            try {
                Socket socket = new Socket();
                socket.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), PORT));
                return socket;
            } catch (IOException e) {
                PORT = -1;
                return getProperSocket(id);
            }
        }
    }

    public static String normalizeUUID(String uuid) {
        return uuid.replaceFirst(
                "(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5"
        );
    }

    public static void setStaticValue(Class<?> cls, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
        Field f = cls.getDeclaredField(fieldName);
        f.setAccessible(true);
        if ((f.getModifiers() & Modifier.FINAL) != 0) { // if it is final
            Field modifiers = Field.class.getDeclaredField("modifiers");
            modifiers.setAccessible(true);
            int modifiersValue = modifiers.getInt(f);
            modifiersValue &= ~Modifier.FINAL;
            modifiers.setInt(f, modifiersValue);
        }
        f.set(null, value);
    }

    public static String processString(String uri) {
        try {
            return uri.substring(uri.indexOf(":") + 1, uri.lastIndexOf('!'));
        } catch (Exception e) {
            e.printStackTrace();
            return uri;
        }
    }

    public static File getLibraryPathAsFile(Class<?> c) throws URISyntaxException {
        String uri = c.getProtectionDomain().getCodeSource().getLocation().toURI().toString().replace("%20", " "); // code breakage in 3, 2, 1...
        if (uri.endsWith(".class")) {
            uri = processString(uri); // stupid reference to a class within a jar
        }
        return new File(new URI(uri));
    }

    public static String getLibraryPath(Class<?> c) throws URISyntaxException {
        return getLibraryPathAsFile(c).getAbsolutePath();
    }

    private static String getClasspath() throws URISyntaxException {
        return String.join(
                System.getProperty("path.separator"),
                getLibraryPath(Main.class),
                getLibraryPath(YggdrasilAuthenticationService.class),
                getLibraryPath(Gson.class),
                getLibraryPath(LogManager.class),
                getLibraryPath(Validate.class),
                getLibraryPath(ForwardingMultimap.class),
                getLibraryPath(Beta.class),
                getLibraryPath(CharEncoding.class),
                getLibraryPath(ByteOrderMark.class),
                getLibraryPath(Logger.class),
                getLibraryPath(Opcodes.class)
        );
    }

    /**
     * Gets the java exe path
     * @return the exe path
     */
    public static String getJavaExe() {
        try {
            return Paths.get(String.join(
                System.getProperty("file.separator"),
                System.getProperty("java.home"),
                "bin",
                "java" + (SystemUtils.IS_OS_WINDOWS ? ".exe" : "")
            )).toFile().getAbsolutePath();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void setToken(String token) throws IOException, URISyntaxException {
        ProcessBuilder processBuilder = new ProcessBuilder(
                getJavaExe(), "-cp", getClasspath(), Main.class.getName()
        );
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT).redirectError(ProcessBuilder.Redirect.INHERIT);
        Process c = processBuilder.start();
        c.getOutputStream().write((token + "\n").getBytes(StandardCharsets.UTF_8));
        c.getOutputStream().flush();
    }
    public static void shutdown() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class<?> shutdown = Class.forName("java.lang.Shutdown");
        Method m = shutdown.getDeclaredMethod("exit", int.class);
        m.setAccessible(true);
        m.invoke(null, 0);
    }

}