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
|
package com.wireguard.android.util;
import android.content.Context;
import android.system.ErrnoException;
import android.system.OsConstants;
import android.util.Log;
import com.wireguard.android.Application.ApplicationContext;
import com.wireguard.android.Application.ApplicationScope;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
/**
* Helper class for running commands as root.
*/
@ApplicationScope
public class RootShell {
private static final Pattern ERRNO_EXTRACTOR = Pattern.compile("error=(\\d+)");
private static final String TAG = "WireGuard/" + RootShell.class.getSimpleName();
private static final String[][] libraryNamedExecutables = {
{"libwg.so", "wg"},
{"libwg-quick.so", "wg-quick"}
};
private final String preamble;
private BufferedWriter stdin;
private BufferedReader stdout;
private BufferedReader stderr;
private Process process;
@Inject
public RootShell(@ApplicationContext final Context context) {
final String binDir = context.getCacheDir().getPath() + "/bin";
final String tmpDir = context.getCacheDir().getPath() + "/tmp";
final String libDir = context.getApplicationInfo().nativeLibraryDir;
new File(binDir).mkdirs();
new File(tmpDir).mkdirs();
StringBuilder builder = new StringBuilder();
for (final String[] libraryNamedExecutable : libraryNamedExecutables) {
final String arg1 = "'" + libDir + "/" + libraryNamedExecutable[0] + "'";
final String arg2 = "'" + binDir + "/" + libraryNamedExecutable[1] + "'";
builder.append(String.format("[ %s -ef %s ] || ln -sf %s %s || exit 31;", arg1, arg2, arg1, arg2));
}
builder.append(String.format("export PATH=\"%s:$PATH\" TMPDIR=\"%s\";", binDir, tmpDir));
builder.append("id;\n");
preamble = builder.toString();
}
private static boolean isExecutable(final String name) {
final String path = System.getenv("PATH");
if (path == null)
return false;
for (final String dir : path.split(":"))
if (new File(dir, name).canExecute())
return true;
return false;
}
private void ensureRoot() throws Exception {
try {
if (process != null) {
process.exitValue();
process = null;
}
} catch (IllegalThreadStateException e) {
return;
}
if (!isExecutable("su"))
throw new NoRootException();
try {
final ProcessBuilder builder = new ProcessBuilder();
builder.environment().put("LANG", "C");
builder.command("su");
process = builder.start();
stdin = new BufferedWriter(new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8));
stdout = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
stderr = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8));
Log.d(TAG, "New root shell, sending preamble: " + preamble);
stdin.write(preamble);
stdin.flush();
final String id = stdout.readLine();
try {
int errno = process.exitValue();
String line;
while ((line = stderr.readLine()) != null) {
if (line.contains("Permission denied"))
throw new NoRootException();
}
throw new ErrnoException("Unknown error when obtaining root access", errno);
} catch (IllegalThreadStateException e) {
// We're alive, so keep executing.
}
if (id == null || !id.contains("uid=0"))
throw new NoRootException();
} catch (Exception e) {
Log.w(TAG, "Session failed with exception", e);
process.destroy();
process = null;
final Matcher match = ERRNO_EXTRACTOR.matcher(e.toString());
if (match.find()) {
final int errno = Integer.valueOf(match.group(1));
if (errno == OsConstants.EACCES)
throw new NoRootException();
else
throw new ErrnoException("Unknown error when obtaining root access", errno);
}
throw e;
}
}
/**
* Run a command in a root shell.
*
* @param output Lines read from stdout are appended to this list. Pass null if the
* output from the shell is not important.
* @param command Command to run as root.
* @return The exit value of the last command run, or -1 if there was an internal error.
*/
public int run(final List<String> output, final String command) throws Exception {
ensureRoot();
StringBuilder builder = new StringBuilder();
final String marker = UUID.randomUUID().toString();
final String begin = marker + " begin";
final String end = marker + " end";
builder.append(String.format("echo '%s';", begin));
builder.append(String.format("echo '%s' >&2;", begin));
builder.append('(');
builder.append(command);
builder.append(");");
builder.append("ret=$?;");
builder.append(String.format("echo '%s' $ret;", end));
builder.append(String.format("echo '%s' $ret >&2;", end));
builder.append('\n');
Log.v(TAG, "executing: " + command);
stdin.write(builder.toString());
stdin.flush();
String line;
boolean first = true;
int errnoStdout = -1, errnoStderr = -2;
int beginEnds = 0;
while ((line = stdout.readLine()) != null) {
if (first) {
first = false;
if (!line.startsWith(begin))
throw new ErrnoException("Could not find begin marker", OsConstants.EBADMSG);
++beginEnds;
continue;
}
if (line.startsWith(end) && line.length() > end.length() + 1) {
errnoStdout = Integer.valueOf(line.substring(end.length() + 1));
++beginEnds;
break;
}
if (output != null)
output.add(line);
Log.v(TAG, "stdout: " + line);
}
first = true;
while ((line = stderr.readLine()) != null) {
if (first) {
first = false;
if (!line.startsWith(begin))
throw new ErrnoException("Could not find begin marker", OsConstants.EBADMSG);
++beginEnds;
continue;
}
if (line.startsWith(end) && line.length() > end.length() + 1) {
errnoStderr = Integer.valueOf(line.substring(end.length() + 1));
++beginEnds;
break;
}
Log.v(TAG, "stderr: " + line);
}
if (errnoStderr != errnoStdout || beginEnds != 4)
throw new ErrnoException("Incorrect errno reporting", OsConstants.EBADMSG);
return errnoStdout;
}
public class NoRootException extends Exception {
}
}
|