Skip to content

Commit 344aa70

Browse files
committed
Guard against dangling ADB connections
1 parent 54efdf7 commit 344aa70

3 files changed

Lines changed: 245 additions & 33 deletions

File tree

‎src/interceptors/android/adb-commands.ts‎

Lines changed: 74 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@ import * as stream from 'stream';
22
import * as path from 'path';
33

44
import adb, * as Adb from '@devicefarmer/adbkit';
5+
import HostTransportCommand from '@devicefarmer/adbkit/dist/src/adb/command/host/transport';
6+
import TcpCommand from '@devicefarmer/adbkit/dist/src/adb/command/host-transport/tcp';
57
import { delay, isErrorLike } from '@httptoolkit/util';
68

79
import { logError } from '../../error-tracking';
8-
import { waitUntil } from '../../util/promise';
10+
import { waitUntil, withTimeout } from '../../util/promise';
911
import { getCertificateFingerprint, parseCert } from '../../certificates';
1012
import { streamToBuffer } from '../../util/stream';
1113

@@ -162,7 +164,10 @@ const getDeviceName = async (adbClient: Adb.Client, deviceId: string) => {
162164
deviceName = avdName || `Android ${osVersion} emulator`;
163165
} else {
164166
const name = (
165-
await run(device, ['settings', 'get', 'global', 'device_name'])
167+
await run(device, ['settings', 'get', 'global', 'device_name'], {
168+
timeout: 10000,
169+
abortOnTimeout: true
170+
})
166171
.catch(() => {})
167172
)?.trim();
168173

@@ -203,34 +208,81 @@ function bufferAsStream(input: Buffer) {
203208
return stream.Readable.from([input], { objectMode: false });
204209
}
205210

206-
async function run(
211+
type AdbConnection = Awaited<ReturnType<Adb.DeviceClient['transport']>>;
212+
213+
// How long we let timed-out commands keep running before force-closing their connection
214+
const ABANDONED_COMMAND_LIMIT_MS = 1_000 * 60 * 10;
215+
216+
// Adbkit commands can't be cancelled, and their connection stays open until the ADB
217+
// server or device responds, which might be never. Commands we stop waiting for would
218+
// leak sockets, so we hold the connection ourselves and always close it eventually.
219+
//
220+
// On timeout, read-only probes can be aborted immediately. Other commands might have side
221+
// effects that shouldn't be interrupted halfway (closing the connection may kill the
222+
// process on the device) so they're left to complete, up to a much longer hard limit.
223+
async function withDeviceConnection<T>(
224+
deviceClient: Adb.DeviceClient,
225+
options: { timeout: number | undefined, abortOnTimeout: boolean },
226+
command: (connection: AdbConnection) => PromiseLike<T>
227+
): Promise<T> {
228+
const connection = Promise.resolve(deviceClient.client.connection());
229+
const result = connection
230+
.then((conn) => new HostTransportCommand(conn).execute(deviceClient.serial).then(() => conn))
231+
.then(command);
232+
233+
const closeConnection = () => connection.then((conn) => conn.socket.destroy()).catch(() => {});
234+
235+
try {
236+
return await (options.timeout
237+
? withTimeout(options.timeout, result)
238+
: result
239+
);
240+
} finally {
241+
if (options.abortOnTimeout) {
242+
closeConnection();
243+
} else {
244+
Promise.race([
245+
result.catch(() => {}),
246+
delay(ABANDONED_COMMAND_LIMIT_MS, { unref: true })
247+
]).then(closeConnection);
248+
}
249+
}
250+
}
251+
252+
export async function isDevicePortOpen(deviceClient: Adb.DeviceClient, port: number) {
253+
return withDeviceConnection(deviceClient, { timeout: 1000, abortOnTimeout: true }, (conn) =>
254+
new TcpCommand(conn).execute(port)
255+
).then(
256+
// If the connection opened at all, then something is listening:
257+
() => true,
258+
() => false
259+
);
260+
}
261+
262+
export async function run(
207263
adbClient: Adb.DeviceClient,
208264
command: string[],
209265
options: {
210266
timeout?: number,
267+
abortOnTimeout?: boolean,
211268
skipLogging?: boolean
212269
} = {
213270
timeout: 10000
214271
}
215272
): Promise<string> {
216-
return Promise.race([
217-
adbClient.shell(command)
273+
return withDeviceConnection(adbClient, {
274+
timeout: options.timeout,
275+
abortOnTimeout: options.abortOnTimeout ?? false
276+
}, (conn) =>
277+
new Adb.ShellCommand(conn).execute(command)
218278
.then(adb.util.readAll)
219-
.then((buffer: Buffer) => buffer.toString('utf8'))
220-
.then((result) => {
221-
if (!options.skipLogging) {
222-
console.debug("Android command", command, "returned", `\`${result.trimEnd()}\``);
223-
}
224-
return result;
225-
}),
226-
...(options.timeout
227-
? [
228-
delay(options.timeout)
229-
.then(() => { throw new Error(`Timeout for ADB command ${command}`) })
230-
]
231-
: []
232-
)
233-
]).catch((e) => {
279+
).then((buffer: Buffer) => {
280+
const result = buffer.toString('utf8');
281+
if (!options.skipLogging) {
282+
console.debug("Android command", command, "returned", `\`${result.trimEnd()}\``);
283+
}
284+
return result;
285+
}).catch((e) => {
234286
if (!options.skipLogging) {
235287
console.debug("Android command", command, "threw", e.message);
236288
}
@@ -255,6 +307,7 @@ export async function pushFile(
255307
export async function isProbablyRooted(deviceClient: Adb.DeviceClient) {
256308
let hasSu = await run(deviceClient, ['command', '-v', 'su'], {
257309
timeout: 500,
310+
abortOnTimeout: true,
258311
skipLogging: true
259312
})
260313
.then((result) => result.includes('/su'))
@@ -266,6 +319,7 @@ export async function isProbablyRooted(deviceClient: Adb.DeviceClient) {
266319
// Requires the user to have run `adb root` beforehand
267320
return run(deviceClient, ['id'], {
268321
timeout: 500,
322+
abortOnTimeout: true,
269323
skipLogging: true
270324
})
271325
.then((result) => result.includes('uid=0(root)'))

‎src/interceptors/frida/frida-android-integration.ts‎

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@ import { CustomError } from '@httptoolkit/util';
22
import { Client as AdbClient, DeviceClient } from '@devicefarmer/adbkit';
33
import * as FridaJs from 'frida-js';
44

5-
import { waitUntil, withTimeout } from '../../util/promise';
5+
import { waitUntil } from '../../util/promise';
66
import { HtkConfig } from '../../config';
77
import {
88
EMULATOR_HOST_IPS,
99
createPersistentReverseTunnel,
1010
getConnectedDevices,
1111
getRootCommand,
12+
isDevicePortOpen,
1213
isProbablyRooted
1314
} from '../android/adb-commands';
1415
import { buildAndroidFridaScript } from './frida-scripts';
@@ -40,18 +41,6 @@ const isFridaInstalled = (deviceClient: DeviceClient) =>
4041
))
4142
.catch(() => false);
4243

43-
const isDevicePortOpen = (deviceClient: DeviceClient, port: number) =>
44-
withTimeout(1000, deviceClient.openTcp(port))
45-
.then((conn) => {
46-
// If the connection opened at all, then something is listening...
47-
conn.on('error', () => {});
48-
conn.end();
49-
return true;
50-
}).catch(() => {
51-
// If the port is closed, we jump straight to the error state instead
52-
return false
53-
});
54-
5544
export async function getAndroidFridaHosts(adbClient: AdbClient): Promise<Record<string, FridaHost>> {
5645
const devices = await getConnectedDevices(adbClient);
5746

‎test/unit/adb-connections.spec.ts‎

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
import * as net from 'net';
2+
import { expect } from 'chai';
3+
import adb from '@devicefarmer/adbkit';
4+
import { delay } from '@httptoolkit/util';
5+
6+
import {
7+
isDevicePortOpen,
8+
isProbablyRooted,
9+
run
10+
} from '../../src/interceptors/android/adb-commands';
11+
12+
type ServiceHandler = (service: string, socket: net.Socket) => void;
13+
14+
// A fake ADB server, which accepts transport requests for any device, and then
15+
// passes each device service request to the current test's handler.
16+
async function startFakeAdbServer(
17+
handler: ServiceHandler,
18+
options: { answerTransport: () => boolean }
19+
) {
20+
const openSockets = new Set<net.Socket>();
21+
22+
const server = net.createServer((socket) => {
23+
openSockets.add(socket);
24+
socket.on('close', () => openSockets.delete(socket));
25+
socket.on('error', () => {});
26+
27+
let buffer = Buffer.alloc(0);
28+
socket.on('data', (data) => {
29+
buffer = Buffer.concat([buffer, data]);
30+
while (buffer.length >= 4) {
31+
const length = parseInt(buffer.subarray(0, 4).toString('ascii'), 16);
32+
if (buffer.length < 4 + length) break;
33+
const request = buffer.subarray(4, 4 + length).toString('utf8');
34+
buffer = buffer.subarray(4 + length);
35+
36+
if (request.startsWith('host:transport:')) {
37+
if (options.answerTransport()) socket.write('OKAY');
38+
} else {
39+
handler(request, socket);
40+
}
41+
}
42+
});
43+
});
44+
45+
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
46+
47+
return {
48+
client: adb.createClient({ port: (server.address() as net.AddressInfo).port }),
49+
openSockets,
50+
stop: async () => {
51+
openSockets.forEach((socket) => socket.destroy());
52+
await new Promise((resolve) => server.close(resolve));
53+
}
54+
};
55+
}
56+
57+
async function expectAllClosed(openSockets: Set<net.Socket>) {
58+
for (let i = 0; i < 20 && openSockets.size > 0; i++) await delay(10);
59+
expect(openSockets.size).to.equal(0);
60+
}
61+
62+
describe("ADB connection management", function () {
63+
this.timeout(5000);
64+
65+
let fakeAdb: Awaited<ReturnType<typeof startFakeAdbServer>> | undefined;
66+
let handler: ServiceHandler;
67+
let answerTransport: boolean;
68+
69+
beforeEach(async () => {
70+
handler = () => {};
71+
answerTransport = true;
72+
fakeAdb = await startFakeAdbServer(
73+
(service, socket) => handler(service, socket),
74+
{ answerTransport: () => answerTransport }
75+
);
76+
});
77+
78+
afterEach(async () => {
79+
await fakeAdb?.stop();
80+
fakeAdb = undefined;
81+
});
82+
83+
it("detects an open device port, and closes the connection", async () => {
84+
handler = (_service, socket) => socket.write('OKAY');
85+
const device = fakeAdb!.client.getDevice('test-device');
86+
87+
expect(await isDevicePortOpen(device, 1234)).to.equal(true);
88+
await expectAllClosed(fakeAdb!.openSockets);
89+
});
90+
91+
it("detects a closed device port, and closes the connection", async () => {
92+
handler = (_service, socket) => socket.write('FAIL0006closed');
93+
const device = fakeAdb!.client.getDevice('test-device');
94+
95+
expect(await isDevicePortOpen(device, 1234)).to.equal(false);
96+
await expectAllClosed(fakeAdb!.openSockets);
97+
});
98+
99+
it("closes port checks that never respond", async () => {
100+
const device = fakeAdb!.client.getDevice('test-device');
101+
102+
expect(await isDevicePortOpen(device, 1234)).to.equal(false);
103+
await expectAllClosed(fakeAdb!.openSockets);
104+
});
105+
106+
it("closes port checks that respond after timing out", async () => {
107+
const services: string[] = [];
108+
handler = (service, socket) => {
109+
services.push(service);
110+
setTimeout(() => socket.write('OKAY'), 1200);
111+
};
112+
const device = fakeAdb!.client.getDevice('test-device');
113+
114+
expect(await isDevicePortOpen(device, 1234)).to.equal(false);
115+
expect(services).to.deep.equal(['tcp:1234']);
116+
await expectAllClosed(fakeAdb!.openSockets);
117+
});
118+
119+
it("reads shell command results, and closes the connection", async () => {
120+
handler = (_service, socket) => socket.end('OKAYuid=0(root) gid=0(root)\n');
121+
const device = fakeAdb!.client.getDevice('test-device');
122+
123+
expect(await isProbablyRooted(device)).to.equal(true);
124+
await expectAllClosed(fakeAdb!.openSockets);
125+
});
126+
127+
it("closes shell commands that time out", async () => {
128+
const services: string[] = [];
129+
handler = (service, socket) => {
130+
services.push(service);
131+
socket.write('OKAY'); // Started, but never completes
132+
};
133+
const device = fakeAdb!.client.getDevice('test-device');
134+
135+
expect(await isProbablyRooted(device)).to.equal(false);
136+
expect(services).to.deep.equal([
137+
"shell:'command' '-v' 'su'",
138+
"shell:'id'"
139+
]);
140+
await expectAllClosed(fakeAdb!.openSockets);
141+
});
142+
143+
it("closes probes whose device transport is never connected", async () => {
144+
answerTransport = false;
145+
const device = fakeAdb!.client.getDevice('test-device');
146+
147+
expect(await isDevicePortOpen(device, 1234)).to.equal(false);
148+
await expectAllClosed(fakeAdb!.openSockets);
149+
});
150+
151+
it("lets other timed-out commands run to completion", async () => {
152+
let completeCommand: (() => void) | undefined;
153+
handler = (_service, socket) => {
154+
socket.write('OKAY');
155+
completeCommand = () => socket.end('done\n');
156+
};
157+
const device = fakeAdb!.client.getDevice('test-device');
158+
159+
const result = await run(device, ['some-command'], { timeout: 100, skipLogging: true })
160+
.catch((e) => e);
161+
expect(result).to.be.instanceOf(Error);
162+
163+
await delay(200);
164+
expect(fakeAdb!.openSockets.size).to.equal(1);
165+
166+
completeCommand!();
167+
await expectAllClosed(fakeAdb!.openSockets);
168+
});
169+
});

0 commit comments

Comments
 (0)