보안 리뷰 반영: 봇 중계 유저별 서버 · 채널 권한, 인증서 검증 우회 차단
봇 중계 권한 (앱 유저의 디스코드 아이디 기준) - 서버 목록 · watch: 그 유저가 가입한 서버만. 아니면 watch_denied (명령 등록 · 멤버 목록도 거절) - 채널 · 음성 상태: 그 유저가 볼 수 있는(ViewChannel) 채널만. 볼 수 없는 채널로 옮기면 "나감"으로 가린다 - 음성 참여 op 4: 그 유저가 들어갈 수 있는(ViewChannel + Connect) 음성채널만 - /녹음시작 은 그 음성채널에 들어갈 수 있는 유저의 PC 로만, 다른 PC 로 가는 명령에는 볼 수 없는 채널 이름을 넣지 않는다 인증서 - 사이트 서버 https/wss(로그인 · 기기 등록 · 봇 중계 · 기기 중계)는 Node 내장 Mozilla 루트만 믿고 검증을 항상 켠다 (core/util/secure-http.ts) NODE_TLS_REJECT_UNAUTHORIZED=0 · 시스템 인증서 저장소의 가짜 루트로 엿볼 수 없다 - 시작할 때 NODE_TLS_REJECT_UNAUTHORIZED 를 지운다 (Electron main · 헤드리스 코어). fuses 로 막히지 않는 변수 - win smoke: 내장 루트만으로 실서버 https 가 검증되는지 확인 (siteTls) 테스트: 봇 중계 권한 1건(가입하지 않은 서버 · 비공개 채널 · 연결 권한 없는 채널 · 명령), 자체 서명 서버 + 검증 끄기 변수 1건(대조군 포함) login-e2e 친구 계정을 실제 F&L 멤버(테스트봇)로 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -22,6 +22,11 @@ const OTHER_G = '900000000000000002';
|
||||
const VC1 = '910000000000000001';
|
||||
const VC2 = '910000000000000002';
|
||||
const TEXT = '910000000000000009';
|
||||
/** 최고 관리자만 볼 수 있는 비공개 음성채널 */
|
||||
const PRIV = '910000000000000003';
|
||||
/** 모두 볼 수 있지만 최고 관리자만 들어갈 수 있는 음성채널 */
|
||||
const LOCKED = '910000000000000004';
|
||||
const OTHER_VC = '920000000000000001';
|
||||
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-botgw-'));
|
||||
delete process.env.GVR_BOT_TOKEN;
|
||||
|
||||
@@ -36,25 +41,48 @@ class FakeSource extends EventEmitter implements BotSource {
|
||||
me() {
|
||||
return ME;
|
||||
}
|
||||
guilds(): BotGwGuild[] {
|
||||
return [
|
||||
{ id: G, name: 'M&L', icon: null },
|
||||
{ id: OTHER_G, name: '다른 서버', icon: null },
|
||||
];
|
||||
private all: BotGwGuild[] = [
|
||||
{ id: G, name: 'M&L', icon: null },
|
||||
{ id: OTHER_G, name: '다른 서버', icon: null },
|
||||
];
|
||||
/** 서버별 멤버: 친구는 M&L 에만 가입 */
|
||||
private memberOf: Record<string, string[]> = { [G]: [SUPER, FRIEND], [OTHER_G]: [SUPER] };
|
||||
private channels: Record<string, { id: string; name: string; voice: boolean; view: string[]; connect: string[] }[]> = {
|
||||
[G]: [
|
||||
{ id: VC1, name: '일반', voice: true, view: [SUPER, FRIEND], connect: [SUPER, FRIEND] },
|
||||
{ id: VC2, name: '게임', voice: true, view: [SUPER, FRIEND], connect: [SUPER, FRIEND] },
|
||||
{ id: PRIV, name: '운영진', voice: true, view: [SUPER], connect: [SUPER] },
|
||||
{ id: LOCKED, name: '방송', voice: true, view: [SUPER, FRIEND], connect: [SUPER] },
|
||||
{ id: TEXT, name: '채팅', voice: false, view: [SUPER, FRIEND], connect: [] },
|
||||
],
|
||||
[OTHER_G]: [{ id: OTHER_VC, name: '다른 음성', voice: true, view: [SUPER], connect: [SUPER] }],
|
||||
};
|
||||
/** 지금 음성채널에 있는 사람 */
|
||||
voice: { member: BotGwMember; channelId: string; guildId: string }[] = [
|
||||
{ member: m(SUPER, '관리자'), channelId: VC1, guildId: G },
|
||||
{ member: m('300000000000000001', '운영진'), channelId: PRIV, guildId: G },
|
||||
];
|
||||
private ch(g: string, c: string) {
|
||||
return this.channels[g]?.find((x) => x.id === c);
|
||||
}
|
||||
snapshot(guildId: string) {
|
||||
const g = this.guilds().find((x) => x.id === guildId);
|
||||
if (!g) return null;
|
||||
const channels: BotGwChannel[] = [
|
||||
{ id: VC1, name: '일반' },
|
||||
{ id: VC2, name: '게임' },
|
||||
];
|
||||
return { guild: g, channels, voice: [{ member: m(SUPER, '관리자'), channelId: VC1 }] };
|
||||
async guildsFor(userId: string) {
|
||||
return this.all.filter((g) => this.memberOf[g.id]?.includes(userId));
|
||||
}
|
||||
isVoiceChannel(guildId: string, channelId: string) {
|
||||
return guildId === G && (channelId === VC1 || channelId === VC2);
|
||||
async snapshot(guildId: string, userId: string) {
|
||||
const g = this.all.find((x) => x.id === guildId);
|
||||
if (!g || !this.memberOf[guildId]?.includes(userId)) return null;
|
||||
const channels: BotGwChannel[] = this.channels[guildId]!.filter((c) => c.voice && c.view.includes(userId)).map((c) => ({ id: c.id, name: c.name }));
|
||||
return { guild: g, channels, voice: this.voice.filter((v) => v.guildId === guildId && channels.some((c) => c.id === v.channelId)).map(({ member, channelId }) => ({ member, channelId })) };
|
||||
}
|
||||
async members() {
|
||||
canView(guildId: string, userId: string, channelId: string) {
|
||||
return !!this.ch(guildId, channelId)?.view.includes(userId);
|
||||
}
|
||||
canConnect(guildId: string, userId: string, channelId: string) {
|
||||
const c = this.ch(guildId, channelId);
|
||||
return !!c?.voice && c.view.includes(userId) && c.connect.includes(userId);
|
||||
}
|
||||
async members(guildId: string, userId: string) {
|
||||
if (!this.memberOf[guildId]?.includes(userId)) throw new Error('forbidden');
|
||||
return [m(SUPER, '관리자'), m(FRIEND, '친구'), m('700000000000000001', '음악봇', true)];
|
||||
}
|
||||
async registerCommands(guildId: string) {
|
||||
@@ -312,3 +340,68 @@ test('봇 중계: 슬래시 명령은 그 서버를 지켜보는 앱으로 가
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('봇 중계 권한: 일반 유저는 가입한 서버 · 볼 수 있는 채널만 보이고, 들어갈 수 있는 음성채널에만 봇을 부른다', async () => {
|
||||
const s = await stack();
|
||||
const a = await s.pc(SUPER);
|
||||
const admin = new AppAuth(a.st, { version: 't', openUrl: () => undefined });
|
||||
await admin.adminAddUser(FRIEND, 'user');
|
||||
const b = await s.pc(FRIEND);
|
||||
try {
|
||||
await b.gw.start();
|
||||
// 서버 목록: 가입한 M&L 만
|
||||
assert.deepEqual(b.gw.guilds().map((g) => g.id), [G]);
|
||||
// 가입하지 않은 서버는 지켜볼 수 없다 (바로 거절)
|
||||
const t0 = Date.now();
|
||||
assert.equal(await b.gw.watch(OTHER_G, { commands: true }), null);
|
||||
assert.ok(Date.now() - t0 < 3000, '거절은 바로 온다');
|
||||
assert.ok(!s.source.commands.includes(OTHER_G), '가입하지 않은 서버에 명령을 등록하지 않는다');
|
||||
await assert.rejects(b.gw.members(OTHER_G), /forbidden/);
|
||||
|
||||
// M&L: 비공개 채널과 그 안의 사람은 안 보인다
|
||||
assert.ok(await b.gw.watch(G, { commands: false }));
|
||||
assert.deepEqual((b.gw as any).channels && [...(b.gw as any).channels.keys()].sort(), [VC1, VC2, LOCKED].sort());
|
||||
assert.equal(b.gw.voiceChannelOf(G, '300000000000000001'), null);
|
||||
assert.equal(b.gw.channel(G, PRIV), null);
|
||||
|
||||
// 비공개 채널 안의 움직임은 안 오고, 비공개 채널로 옮기면 "나감"으로만 보인다
|
||||
const evs: any[] = [];
|
||||
b.gw.on('voiceState', (e) => evs.push(e));
|
||||
s.source.emit('voiceState', { guildId: G, member: m('300000000000000002', '운영진2'), oldChannelId: null, newChannelId: PRIV, channel: { id: PRIV, name: '운영진' } });
|
||||
s.source.emit('voiceState', { guildId: G, member: m(SUPER, '관리자'), oldChannelId: VC1, newChannelId: PRIV, channel: { id: PRIV, name: '운영진' } });
|
||||
await until(() => evs.length === 1);
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
assert.equal(evs.length, 1);
|
||||
assert.deepEqual([evs[0].member.id, evs[0].oldChannelId, evs[0].newChannelId, evs[0].channel], [SUPER, VC1, null, null]);
|
||||
|
||||
// 음성 참여: 비공개 · 연결 권한 없는 채널 · 다른 서버는 거절, 들어갈 수 있는 채널만
|
||||
const ad = b.gw.adapterCreator(G)({ onVoiceServerUpdate: () => undefined, onVoiceStateUpdate: () => undefined, destroy: () => undefined });
|
||||
ad.sendPayload(op4(G, PRIV));
|
||||
ad.sendPayload(op4(G, LOCKED));
|
||||
ad.sendPayload(op4(G, OTHER_VC));
|
||||
ad.sendPayload(op4(G, VC2));
|
||||
await until(() => s.source.sent.length === 1);
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
assert.deepEqual(s.source.sent.map((x) => x.payload.d.channel_id), [VC2]);
|
||||
|
||||
// 슬래시 명령: 최고 관리자가 비공개 채널에서 /녹음시작 → 그 채널에 못 들어가는 친구 PC 로는 보내지 않는다
|
||||
const cmds: any[] = [];
|
||||
b.gw.on('command', (c, respond) => (cmds.push(c), respond('ok')));
|
||||
const cmd = (name: string) =>
|
||||
new Promise<string>((resolve) => s.source.emit('command', { name, guildId: G, user: m(SUPER, '관리자'), voiceChannel: { id: PRIV, name: '운영진' } } satisfies BotCommand, resolve));
|
||||
assert.equal(await cmd('녹음시작'), '이 음성채널에 들어갈 수 있는 겜녹이 앱이 없습니다.');
|
||||
// /녹음제외 는 친구 PC 기록에도 남기되 비공개 채널 이름은 보내지 않는다
|
||||
assert.equal(await cmd('녹음제외'), 'ok');
|
||||
assert.equal(cmds.length, 1);
|
||||
assert.equal(cmds[0].voiceChannel, null);
|
||||
|
||||
// 친구 PC 가 받은 메시지 어디에도 비공개 채널 · 그 안의 사람 정보가 없다
|
||||
const all = b.seen.join('\n');
|
||||
// (OTHER_G 는 친구가 직접 보낸 watch 의 거절 응답에만 나온다)
|
||||
for (const secret of [PRIV, '운영진', '300000000000000001', '300000000000000002', '다른 서버', OTHER_VC]) assert.ok(!all.includes(secret), secret);
|
||||
} finally {
|
||||
await a.gw.stop();
|
||||
await b.gw.stop();
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -46,3 +46,76 @@ test('암호화되지 않은 주소로는 로그인 토큰 · 기기 등록 코
|
||||
test('게임 연동: 인증서 검증을 끄는 건 이 PC 안 주소뿐 (local 을 잘못 넘겨도 바깥 주소는 거절)', async () => {
|
||||
await assert.rejects(request('https://pd.ap.a.pvp.net/x', { local: true }), /로컬 API 가 아닌 주소/);
|
||||
});
|
||||
|
||||
test('인증서: NODE_TLS_REJECT_UNAUTHORIZED=0 이어도 믿을 수 없는 인증서의 서버로는 토큰 · 기기 키를 보내지 않는다 (https · wss)', async () => {
|
||||
const { execFileSync } = await import('node:child_process');
|
||||
const https = await import('node:https');
|
||||
const { WebSocketServer } = await import('ws');
|
||||
const { RelayClient } = await import('../src/core/relay/client.ts');
|
||||
const { Bus } = await import('../src/core/util/events.ts');
|
||||
// 가짜 서버 (자체 서명 인증서): 받은 요청의 인증 헤더를 모두 기록한다
|
||||
const dir = tmp();
|
||||
execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-subj', '/CN=127.0.0.1', '-addext', 'subjectAltName=IP:127.0.0.1', '-days', '1', '-keyout', path.join(dir, 'k.pem'), '-out', path.join(dir, 'c.pem')], { stdio: 'ignore' });
|
||||
const got: string[] = [];
|
||||
const srv = https.createServer({ key: fs.readFileSync(path.join(dir, 'k.pem')), cert: fs.readFileSync(path.join(dir, 'c.pem')) }, (req, res) => {
|
||||
got.push(`${req.url} ${req.headers.authorization ?? ''}`);
|
||||
res.setHeader('content-type', 'application/json');
|
||||
res.end('{"state":"pending","user":{"id":"1","name":"x","avatar":null},"role":"user","serverTime":0}');
|
||||
});
|
||||
const wss = new WebSocketServer({ noServer: true });
|
||||
srv.on('upgrade', (req, socket, head) => {
|
||||
got.push(`WS ${req.url} ${req.headers.authorization ?? ''}`);
|
||||
wss.handleUpgrade(req, socket, head, (ws) => ws.close());
|
||||
});
|
||||
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
|
||||
const base = `https://127.0.0.1:${(srv.address() as any).port}`;
|
||||
const prev = process.env.NODE_TLS_REJECT_UNAUTHORIZED;
|
||||
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
|
||||
const origWarn = process.emitWarning;
|
||||
process.emitWarning = () => undefined;
|
||||
try {
|
||||
// 대조군: 기본 fetch 는 이 변수 때문에 실제로 토큰을 보낸다 (테스트가 우회를 잡아낼 수 있는지 확인)
|
||||
await fetch(`${base}/control`, { headers: { authorization: 'Bearer control' } });
|
||||
assert.deepEqual(got, ['/control Bearer control']);
|
||||
got.length = 0;
|
||||
|
||||
const st = new SettingsStore(tmp());
|
||||
st.update({ site: { serverUrl: base, deviceId: 'dev1' } });
|
||||
st.setSecret('appToken', 'secret-app-token');
|
||||
st.setSecret('deviceKey', 'secret-device-key');
|
||||
// 로그인 확인 (https)
|
||||
const auth = new AppAuth(st, { version: 't', openUrl: () => undefined });
|
||||
const a = await auth.check();
|
||||
assert.notEqual(a.status, 'ok');
|
||||
assert.match(a.error ?? '', /연결할 수 없습니다/);
|
||||
// 기기 등록 (https)
|
||||
await assert.rejects(registerDevice(base, 'ABCD-EFGH', 'pc'));
|
||||
// 겜녹이 봇 중계 (wss)
|
||||
const gw = new RemoteGateway({ serverUrl: () => base, appToken: () => 'secret-app-token', version: 't' });
|
||||
const started = gw.start().then(() => 'ready', () => 'failed');
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
await gw.stop();
|
||||
assert.equal(await Promise.race([started, new Promise((r) => setTimeout(() => r('pending'), 100))]) === 'ready', false);
|
||||
// 사이트 기기 중계 (wss)
|
||||
const relay = new RelayClient({} as any, new Bus(), () => ({ serverUrl: base, deviceId: 'dev1', deviceKey: 'secret-device-key', name: 'pc', version: 't', guildId: null }));
|
||||
relay.start();
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
assert.notEqual(relay.status.state, 'online');
|
||||
relay.stop();
|
||||
|
||||
assert.deepEqual(got, [], '믿을 수 없는 인증서의 서버에 요청 · 토큰이 가면 안 된다');
|
||||
|
||||
// 앱 시작 때 이 변수를 지우면 (main.ts · startCore) 사이트 밖 통신(일반 fetch: 다른 봇 · Riot 원격 API 등)도 다시 검증한다
|
||||
const { hardenTlsEnv } = await import('../src/core/util/secure-http.ts');
|
||||
hardenTlsEnv();
|
||||
assert.equal(process.env.NODE_TLS_REJECT_UNAUTHORIZED, undefined);
|
||||
await assert.rejects(fetch(`${base}/after-harden`, { headers: { authorization: 'Bearer x' } }));
|
||||
assert.deepEqual(got, []);
|
||||
} finally {
|
||||
if (prev === undefined) delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;
|
||||
else process.env.NODE_TLS_REJECT_UNAUTHORIZED = prev;
|
||||
process.emitWarning = origWarn;
|
||||
srv.closeAllConnections();
|
||||
srv.close();
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user