yubioath-flutter/lib/desktop/rpc.dart

354 lines
9.2 KiB
Dart
Raw Normal View History

2021-11-19 13:10:00 +03:00
import 'dart:async';
import 'dart:convert';
import 'dart:io';
2022-03-30 17:45:47 +03:00
import 'dart:math';
2021-11-19 13:10:00 +03:00
import 'package:logging/logging.dart';
2021-11-22 14:01:51 +03:00
import 'package:async/async.dart';
import 'package:yubico_authenticator/app/logging.dart';
2021-11-22 14:01:51 +03:00
import '../app/models.dart';
2021-11-19 13:10:00 +03:00
import 'models.dart';
final _log = Logger('helper');
2021-11-19 13:10:00 +03:00
class Signaler {
2021-11-22 15:59:52 +03:00
final _send = StreamController<String>();
final _recv = StreamController<Signal>();
2021-11-19 13:10:00 +03:00
2021-11-22 15:59:52 +03:00
Stream<Signal> get signals => _recv.stream;
2021-11-19 13:10:00 +03:00
2022-03-23 19:50:14 +03:00
Stream<String> get _sendStream => _send.stream;
2021-11-19 13:10:00 +03:00
void cancel() {
2021-11-22 15:59:52 +03:00
_send.add('cancel');
}
void _close() {
_send.close();
_recv.close();
2021-11-19 13:10:00 +03:00
}
}
class _Request {
final String action;
final List<String> target;
final Map body;
final Signaler? signal;
2021-11-22 14:49:23 +03:00
final Completer<Map<String, dynamic>> completer = Completer();
2021-11-19 13:10:00 +03:00
2021-11-22 15:59:52 +03:00
_Request(this.action, this.target, this.body, this.signal);
2021-11-19 13:10:00 +03:00
Map<String, dynamic> toJson() => {
'kind': 'command',
'action': action,
'target': target,
'body': body,
2021-11-19 13:10:00 +03:00
};
}
2021-11-24 13:36:59 +03:00
const _py2level = {
'TRAFFIC': Level.FINE,
2021-11-24 13:36:59 +03:00
'DEBUG': Level.CONFIG,
'INFO': Level.INFO,
'WARNING': Level.WARNING,
'ERROR': Level.SEVERE,
'CRITICAL': Level.SHOUT,
};
2022-03-30 17:45:47 +03:00
class _RpcConnection {
final IOSink _sink;
2021-11-22 14:01:51 +03:00
final StreamQueue<RpcResponse> _responses;
2022-03-30 17:45:47 +03:00
_RpcConnection(this._sink, Stream<String> stream)
: _responses = StreamQueue(stream.map((event) {
try {
return RpcResponse.fromJson(jsonDecode(event));
} catch (e) {
2022-05-03 12:24:25 +03:00
_log.error('Response was not valid JSON', event);
return RpcResponse.error('invalid-response', e.toString(), {});
}
2022-03-30 17:45:47 +03:00
}));
void send(Map data) {
_sink.writeln(jsonEncode(data));
}
Future<RpcResponse> getResponse() => _responses.next;
2022-04-03 20:48:14 +03:00
Future<void> close() async {
2022-03-30 17:45:47 +03:00
_sink.writeln('');
2022-04-03 20:48:14 +03:00
await _responses.cancel();
await _sink.close();
2022-03-30 17:45:47 +03:00
}
}
class RpcSession {
final String executable;
late _RpcConnection _connection;
final StreamController<_Request> _requests = StreamController();
RpcSession(this.executable);
static void _logEntry(String entry) {
try {
final record = jsonDecode(entry);
var entryLevel = _py2level[record['level']];
if (entryLevel == null) {
Logger('helper.${record['name']}')
.log(Levels.ERROR, 'Invalid log level: ${record['level']}');
} else {
Logger('helper.${record['name']}').log(
entryLevel,
record['message'],
record['exc_text'],
//time: DateTime.fromMillisecondsSinceEpoch(event['time'] * 1000),
);
}
2022-03-30 17:45:47 +03:00
} catch (e) {
_log.error(e.toString(), entry);
}
}
Future<void> initialize() async {
final process = await Process.start(executable, []);
_log.debug('Helper process started');
2022-03-30 17:45:47 +03:00
process.stderr
.transform(const Utf8Decoder())
.transform(const LineSplitter())
2022-03-30 17:45:47 +03:00
.listen(_logEntry);
// Communicate with rpc over stdin/stdout.
_connection = _RpcConnection(
process.stdin,
process.stdout
.transform(const Utf8Decoder())
.transform(const LineSplitter()),
);
2022-02-22 15:26:28 +03:00
2021-11-22 14:01:51 +03:00
_pump();
2021-11-19 13:10:00 +03:00
}
2022-03-30 17:45:47 +03:00
Future<bool> elevate() async {
if (!Platform.isWindows) {
throw Exception('Elevate is only available for Windows');
}
final random = Random.secure();
final nonce = base64Encode(List.generate(32, (_) => random.nextInt(256)));
// Bind to random port
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = server.port;
_log.debug('Listening for Helper connection on $port');
2022-03-30 17:45:47 +03:00
// Launch the elevated process
final process =
await Process.start('powershell.exe', ['-NoProfile', '-Command', '-']);
_log.info('Attempting to elevate $executable');
2022-03-30 17:45:47 +03:00
process.stdin.writeln(
'Start-Process "$executable" -Verb runAs -WindowStyle hidden -ArgumentList "--tcp $port $nonce"');
2022-03-30 17:45:47 +03:00
await process.stdin.flush();
await process.stdin.close();
if (await process.exitCode != 0) {
await server.close();
final error = await process.stderr
.transform(const Utf8Decoder())
.transform(const LineSplitter())
.join('\n');
_log.warning('Failed to elevate the Helper process', error);
2022-03-30 17:45:47 +03:00
return false;
}
_log.debug('Elevated Helper process started');
2022-03-30 17:45:47 +03:00
// Accept only a single connection
final client = await server.first;
await server.close();
_log.debug('Helper connected: $client');
2022-03-30 17:45:47 +03:00
// Stop the old subprocess.
try {
2022-04-03 20:48:14 +03:00
await command('quit', []);
} catch (error) {
_log.warning('Failed to dispose existing process', error);
}
2022-03-30 17:45:47 +03:00
bool authenticated = false;
final completer = Completer<void>();
final read =
utf8.decoder.bind(client).transform(const LineSplitter()).map((line) {
// The nonce needs to be received first.
if (!authenticated) {
if (nonce == line) {
_log.debug('Helper authenticated with correct nonce');
2022-03-30 17:45:47 +03:00
authenticated = true;
completer.complete();
return '';
} else {
_log.warning('Helper used WRONG NONCE: $line');
2022-03-30 17:45:47 +03:00
client.close();
completer.completeError(Exception('Invalid nonce'));
throw Exception('Invalid nonce');
}
} else {
// Filter out (and log) log messages
final type = line[0];
final message = line.substring(1);
switch (type) {
case 'O':
return message;
case 'E':
_logEntry(message);
return '';
default:
_log.error('Invalid message: $line');
throw Exception('Invalid message type: $type');
}
}
}).where((line) => line.isNotEmpty);
_connection = _RpcConnection(client, read);
await completer.future;
return true;
2021-11-19 13:10:00 +03:00
}
Future<Map<String, dynamic>> command(String action, List<String>? target,
{Map? params, Signaler? signal}) {
var request = _Request(action, target ?? [], params ?? {}, signal);
_requests.add(request);
return request.completer.future;
}
2022-05-03 12:24:25 +03:00
void setLogLevel(Level level) async {
final name = Levels.LEVELS
.firstWhere((e) => level.value <= e.value, orElse: () => Level.OFF)
.name
.toLowerCase();
await command('logging', [], params: {'level': name});
}
2021-11-19 13:10:00 +03:00
void _send(Map data) {
_log.traffic('SEND', jsonEncode(data));
2022-03-30 17:45:47 +03:00
_connection.send(data);
2021-11-19 13:10:00 +03:00
}
2021-11-22 14:01:51 +03:00
void _pump() async {
await for (final request in _requests.stream) {
2022-04-03 20:48:14 +03:00
if (request.action == 'quit') {
await _connection.close();
request.completer.complete({});
continue;
}
2021-11-22 14:01:51 +03:00
_send(request.toJson());
2022-03-23 19:50:14 +03:00
final signalSubscription = request.signal?._sendStream.listen((status) {
2021-11-22 14:49:23 +03:00
_send({'kind': 'signal', 'status': status});
2021-11-22 15:59:52 +03:00
});
2021-11-22 14:49:23 +03:00
2021-11-22 15:59:52 +03:00
bool completed = false;
while (!completed) {
2022-03-30 17:45:47 +03:00
final response = await _connection.getResponse();
_log.traffic('RECV', jsonEncode(response));
2021-11-22 14:01:51 +03:00
response.map(
signal: (signal) {
2022-03-17 22:10:10 +03:00
final signaler = request.signal;
if (signaler != null) {
signaler._recv.sink.add(signal);
} else {
_log.warning('Received unhandled signal: $signal');
}
2021-11-22 14:01:51 +03:00
},
success: (success) {
request.completer.complete(success.body);
2021-11-22 15:59:52 +03:00
completed = true;
2021-11-22 14:01:51 +03:00
},
error: (error) {
request.completer.completeError(error);
2021-11-22 15:59:52 +03:00
completed = true;
2021-11-22 14:01:51 +03:00
},
);
}
2022-03-23 19:50:14 +03:00
await signalSubscription?.cancel();
2021-11-22 15:59:52 +03:00
request.signal?._close();
2021-11-22 14:01:51 +03:00
}
}
2021-11-19 13:10:00 +03:00
}
typedef ErrorHandler = Future<void> Function(RpcError e);
2022-03-23 19:50:14 +03:00
class _MultiSignaler extends Signaler {
final Signaler delegate;
@override
final Stream<String> _sendStream;
_MultiSignaler(this.delegate)
: _sendStream = delegate._send.stream.asBroadcastStream() {
signals.listen(delegate._recv.sink.add);
}
@override
void _close() {}
void _reallyClose() {
super._close();
}
}
class RpcNodeSession {
final RpcSession _rpc;
final DevicePath devicePath;
final List<String> subPath;
final Map<String, ErrorHandler> _errorHandlers = {};
RpcNodeSession(this._rpc, this.devicePath, this.subPath);
void setErrorHandler(String status, ErrorHandler handler) {
_errorHandlers[status] = handler;
}
2022-03-15 19:16:14 +03:00
void unsetErrorHandler(String status) {
_errorHandlers.remove(status);
}
Future<Map<String, dynamic>> command(
String action, {
List<String> target = const [],
Map<dynamic, dynamic>? params,
Signaler? signal,
}) async {
2022-03-23 19:50:14 +03:00
bool wrapped = false;
try {
2022-03-23 19:50:14 +03:00
if (signal != null && signal is! _MultiSignaler) {
signal = _MultiSignaler(signal);
wrapped = true;
}
return await _rpc.command(
action,
devicePath.segments + subPath + target,
params: params,
signal: signal,
);
} on RpcError catch (e) {
final handler = _errorHandlers[e.status];
if (handler != null) {
_log.info('Attempting recovery on "${e.status}"');
await handler(e);
2022-03-23 19:50:14 +03:00
return await command(
action,
target: target,
params: params,
signal: signal,
);
}
rethrow;
2022-03-23 19:50:14 +03:00
} finally {
if (wrapped) {
(signal as _MultiSignaler)._reallyClose();
}
}
}
}