File: remote_webauthn_native_messaging_host.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (541 lines) | stat: -rw-r--r-- 18,719 bytes parent folder | download | duplicates (3)
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/host/webauthn/remote_webauthn_native_messaging_host.h"

#include <algorithm>
#include <memory>

#include "base/functional/bind.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/task/single_thread_task_runner.h"
#include "base/values.h"
#include "build/build_config.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "remoting/base/logging.h"
#include "remoting/host/chromoting_host_services_client.h"
#include "remoting/host/mojom/webauthn_proxy.mojom.h"
#include "remoting/host/native_messaging/native_messaging_constants.h"
#include "remoting/host/native_messaging/native_messaging_helpers.h"
#include "remoting/host/webauthn/desktop_session_type_util.h"
#include "remoting/host/webauthn/remote_webauthn_constants.h"

namespace remoting {

namespace {

base::Value::Dict CreateWebAuthnExceptionDetailsDict(
    const std::string& name,
    const std::string& message) {
  return base::Value::Dict()
      .Set(kWebAuthnErrorNameKey, name)
      .Set(kWebAuthnErrorMessageKey, message);
}

base::Value::Dict MojoErrorToErrorDict(
    const mojom::WebAuthnExceptionDetailsPtr& mojo_error) {
  return CreateWebAuthnExceptionDetailsDict(mojo_error->name,
                                            mojo_error->message);
}

}  // namespace

RemoteWebAuthnNativeMessagingHost::RemoteWebAuthnNativeMessagingHost(
    scoped_refptr<base::SingleThreadTaskRunner> task_runner)
    : RemoteWebAuthnNativeMessagingHost(
          std::make_unique<ChromotingHostServicesClient>(),
          task_runner) {}

RemoteWebAuthnNativeMessagingHost::RemoteWebAuthnNativeMessagingHost(
    std::unique_ptr<ChromotingHostServicesProvider> host_service_api_client,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner)
    : task_runner_(task_runner),
      host_service_api_client_(std::move(host_service_api_client)) {
  request_cancellers_.set_disconnect_handler(base::BindRepeating(
      &RemoteWebAuthnNativeMessagingHost::OnRequestCancellerDisconnected,
      base::Unretained(this)));
}

RemoteWebAuthnNativeMessagingHost::~RemoteWebAuthnNativeMessagingHost() {
  DCHECK(task_runner_->BelongsToCurrentThread());

#if !BUILDFLAG(IS_CHROMEOS)
  // This makes sure the log messages below get sent to the extension before the
  // caller sequence gets terminated.
  log_message_handler_->set_log_synchronously_if_possible(true);
#endif  // !BUILDFLAG(IS_CHROMEOS)

  if (!id_to_request_canceller_.empty()) {
    LOG(WARNING) << id_to_request_canceller_.size()
                 << "Requests are still pending at destruction.";
  }
  HOST_LOG << "Remote WebAuthn native messaging host is being terminated";
}

void RemoteWebAuthnNativeMessagingHost::OnMessage(const std::string& message) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  std::string type;
  base::Value::Dict request;
  if (!ParseNativeMessageJson(message, type, request)) {
    return;
  }

  std::optional<base::Value::Dict> response =
      CreateNativeMessageResponse(request);
  if (!response.has_value()) {
    return;
  }

  if (type == kHelloMessage) {
    ProcessHello(std::move(*response));
  } else if (type == kIsUvpaaMessageType) {
    ProcessIsUvpaa(request, std::move(*response));
  } else if (type == kGetRemoteStateMessageType) {
    ProcessGetRemoteState(std::move(*response));
  } else if (type == kCreateMessageType) {
    ProcessCreate(request, std::move(*response));
  } else if (type == kGetMessageType) {
    ProcessGet(request, std::move(*response));
  } else if (type == kCancelMessageType) {
    ProcessCancel(request, std::move(*response));
  } else {
    LOG(ERROR) << "Unsupported request type: " << type;
  }
}

void RemoteWebAuthnNativeMessagingHost::Start(
    extensions::NativeMessageHost::Client* client) {
  DCHECK(task_runner_->BelongsToCurrentThread());
  client_ = client;
#if !BUILDFLAG(IS_CHROMEOS)
  log_message_handler_ =
      std::make_unique<LogMessageHandler>(base::BindRepeating(
          &RemoteWebAuthnNativeMessagingHost::SendMessageToClient,
          base::Unretained(this)));
#endif  // !BUILDFLAG(IS_CHROMEOS)
  HOST_LOG << "Remote WebAuthn native messaging host has started";
}

scoped_refptr<base::SingleThreadTaskRunner>
RemoteWebAuthnNativeMessagingHost::task_runner() const {
  return task_runner_;
}

void RemoteWebAuthnNativeMessagingHost::ProcessHello(
    base::Value::Dict response) {
  // Hello request: {id: string, type: 'hello'}
  // Hello response: {id: string, type: 'helloResponse', hostVersion: string}

  DCHECK(task_runner_->BelongsToCurrentThread());

  ProcessNativeMessageHelloResponse(response);
  SendMessageToClient(std::move(response));
}

void RemoteWebAuthnNativeMessagingHost::ProcessIsUvpaa(
    const base::Value::Dict& request,
    base::Value::Dict response) {
  // IsUvpaa request: {id: string, type: 'isUvpaa'}
  // IsUvpaa response:
  //   {id: string, type: 'isUvpaaResponse', isAvailable: boolean}

  DCHECK(task_runner_->BelongsToCurrentThread());

  if (!EnsureIpcConnection()) {
    SendClientDisconnectedMessage();
    return;
  }

  remote_->IsUserVerifyingPlatformAuthenticatorAvailable(
      base::BindOnce(&RemoteWebAuthnNativeMessagingHost::OnIsUvpaaResponse,
                     base::Unretained(this), std::move(response)));
}

void RemoteWebAuthnNativeMessagingHost::ProcessCreate(
    const base::Value::Dict& request,
    base::Value::Dict response) {
  // Create request: {id: string, type: 'create', requestData: string}
  // Create response: {
  //   id: string, type: 'createResponse', responseData?: string,
  //   error?: {name: string, message: string}}

  DCHECK(task_runner_->BelongsToCurrentThread());

  if (!EnsureIpcConnection()) {
    SendClientDisconnectedMessage();
    return;
  }
  const base::Value* message_id = FindMessageIdOrSendError(response);
  if (!message_id) {
    return;
  }
  const std::string* request_data =
      FindRequestDataOrSendError(request, kCreateRequestDataKey, response);
  if (!request_data) {
    return;
  }

  remote_->Create(
      *request_data, AddRequestCanceller(message_id->Clone()),
      base::BindOnce(&RemoteWebAuthnNativeMessagingHost::OnCreateResponse,
                     base::Unretained(this), std::move(response)));
}

void RemoteWebAuthnNativeMessagingHost::ProcessGet(
    const base::Value::Dict& request,
    base::Value::Dict response) {
  // Get request: {id: string, type: 'get', requestData: string}
  // Get response: {
  //   id: string, type: 'getResponse', responseData?: string,
  //   error?: {name: string, message: string}}

  DCHECK(task_runner_->BelongsToCurrentThread());

  if (!EnsureIpcConnection()) {
    SendClientDisconnectedMessage();
    return;
  }
  const base::Value* message_id = FindMessageIdOrSendError(response);
  if (!message_id) {
    return;
  }
  const std::string* request_data =
      FindRequestDataOrSendError(request, kGetRequestDataKey, response);
  if (!request_data) {
    return;
  }

  remote_->Get(*request_data, AddRequestCanceller(message_id->Clone()),
               base::BindOnce(&RemoteWebAuthnNativeMessagingHost::OnGetResponse,
                              base::Unretained(this), std::move(response)));
}

void RemoteWebAuthnNativeMessagingHost::ProcessCancel(
    const base::Value::Dict& request,
    base::Value::Dict response) {
  // Cancel request: {id: string, type: 'cancel'}
  // Cancel response:
  //   {id: string, type: 'cancelResponse', wasCanceled: boolean}

  if (!EnsureIpcConnection()) {
    SendClientDisconnectedMessage();
    return;
  }

  const base::Value* message_id = request.Find(kMessageId);
  if (!message_id) {
    LOG(ERROR) << "Message ID not found in cancel request.";
    response.Set(kCancelResponseWasCanceledKey, false);
    SendMessageToClient(std::move(response));
    return;
  }

  auto it = id_to_request_canceller_.find(*message_id);
  if (it == id_to_request_canceller_.end()) {
    LOG(ERROR) << "No cancelable request found for message ID " << *message_id;
    response.Set(kCancelResponseWasCanceledKey, false);
    SendMessageToClient(std::move(response));
    return;
  }

  auto* canceller = request_cancellers_.Get(it->second);
  CHECK(canceller);
  canceller->Cancel(
      base::BindOnce(&RemoteWebAuthnNativeMessagingHost::OnCancelResponse,
                     base::Unretained(this), std::move(response)));
}

void RemoteWebAuthnNativeMessagingHost::ProcessGetRemoteState(
    base::Value::Dict response) {
  // GetRemoteState request: {id: string, type: 'getRemoteState'}
  // GetRemoteState response:
  //   {id: string, type: 'getRemoteStateResponse', isRemoted: boolean,
  //    desktopSessionType: 'unspecified'|'remote-only'|'local-only'}

  DCHECK(task_runner_->BelongsToCurrentThread());

  // We query and report the remote state one at a time to prevent race
  // conditions caused by multiple requests coming in while there is already a
  // pending request (e.g. WebAuthn channel connected and AttachToDesktop on
  // Windows).
  get_remote_state_responses_.push(std::move(response));
  if (get_remote_state_responses_.size() == 1) {
    QueryNextRemoteState();
  }
  // Otherwise it means there is already a pending remote state request.
}

void RemoteWebAuthnNativeMessagingHost::OnQueryVersionResult(uint32_t version) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  SendNextRemoteState(true);
}

void RemoteWebAuthnNativeMessagingHost::OnIpcDisconnected() {
  DCHECK(task_runner_->BelongsToCurrentThread());

  remote_.reset();
  if (!get_remote_state_responses_.empty()) {
    SendNextRemoteState(false);
  } else {
    SendClientDisconnectedMessage();
  }
}

void RemoteWebAuthnNativeMessagingHost::OnIsUvpaaResponse(
    base::Value::Dict response,
    bool is_available) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  response.Set(kIsUvpaaResponseIsAvailableKey, is_available);
  SendMessageToClient(std::move(response));
}

void RemoteWebAuthnNativeMessagingHost::OnCreateResponse(
    base::Value::Dict response,
    mojom::WebAuthnCreateResponsePtr remote_response) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  // If |remote_response| is null, it means that the remote create() call has
  // yielded `null`, which is still a valid response according to the spec. In
  // this case we just send back an empty create response.
  if (!remote_response.is_null()) {
    switch (remote_response->which()) {
      case mojom::WebAuthnCreateResponse::Tag::kErrorDetails:
        response.Set(
            kWebAuthnErrorKey,
            MojoErrorToErrorDict(remote_response->get_error_details()));
        break;
      case mojom::WebAuthnCreateResponse::Tag::kResponseData:
        response.Set(kCreateResponseDataKey,
                     remote_response->get_response_data());
        break;
      default:
        NOTREACHED() << "Unexpected create response tag: "
                     << static_cast<uint32_t>(remote_response->which());
    }
  }

  const base::Value* message_id = response.Find(kMessageId);
  if (message_id) {
    RemoveRequestCancellerByMessageId(*message_id);
  }

  SendMessageToClient(std::move(response));
}

void RemoteWebAuthnNativeMessagingHost::OnGetResponse(
    base::Value::Dict response,
    mojom::WebAuthnGetResponsePtr remote_response) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  // If |remote_response| is null, it means that the remote get() call has
  // yielded `null`, which is still a valid response according to the spec. In
  // this case we just send back an empty get response.
  if (!remote_response.is_null()) {
    switch (remote_response->which()) {
      case mojom::WebAuthnGetResponse::Tag::kErrorDetails:
        response.Set(
            kWebAuthnErrorKey,
            MojoErrorToErrorDict(remote_response->get_error_details()));
        break;
      case mojom::WebAuthnGetResponse::Tag::kResponseData:
        response.Set(kGetResponseDataKey, remote_response->get_response_data());
        break;
      default:
        NOTREACHED() << "Unexpected get response tag: "
                     << static_cast<uint32_t>(remote_response->which());
    }
  }

  const base::Value* message_id = response.Find(kMessageId);
  if (message_id) {
    RemoveRequestCancellerByMessageId(*message_id);
  }

  SendMessageToClient(std::move(response));
}

void RemoteWebAuthnNativeMessagingHost::OnCancelResponse(
    base::Value::Dict response,
    bool was_canceled) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  const base::Value* message_id = response.Find(kMessageId);
  if (message_id) {
    RemoveRequestCancellerByMessageId(*message_id);
  }

  response.Set(kCancelResponseWasCanceledKey, was_canceled);
  SendMessageToClient(std::move(response));
}

void RemoteWebAuthnNativeMessagingHost::QueryNextRemoteState() {
  DCHECK(task_runner_->BelongsToCurrentThread());

  if (!EnsureIpcConnection()) {
    SendNextRemoteState(false);
    return;
  }

  // QueryVersion() is simply used to determine if the receiving end actually
  // accepts the connection. If it doesn't, then the callback will be silently
  // dropped, and OnIpcDisconnected() will be called instead.
  remote_.QueryVersion(
      base::BindOnce(&RemoteWebAuthnNativeMessagingHost::OnQueryVersionResult,
                     base::Unretained(this)));
}

void RemoteWebAuthnNativeMessagingHost::SendNextRemoteState(bool is_remoted) {
  DCHECK(task_runner_->BelongsToCurrentThread());
  DCHECK(!get_remote_state_responses_.empty());

  auto response = std::move(get_remote_state_responses_.front());
  get_remote_state_responses_.pop();

  response.Set(kGetRemoteStateResponseIsRemotedKey, is_remoted);
  std::string desktop_session_type;
  switch (GetDesktopSessionType()) {
    case DesktopSessionType::UNSPECIFIED:
      desktop_session_type = "unspecified";
      break;
    case DesktopSessionType::REMOTE_ONLY:
      desktop_session_type = "remote-only";
      break;
    case DesktopSessionType::LOCAL_ONLY:
      desktop_session_type = "local-only";
      break;
  }
  response.Set(kGetRemoteStateResponseDesktopSessionTypeKey,
               desktop_session_type);
  SendMessageToClient(std::move(response));
  if (!get_remote_state_responses_.empty()) {
    QueryNextRemoteState();
  }
}

bool RemoteWebAuthnNativeMessagingHost::EnsureIpcConnection() {
  DCHECK(task_runner_->BelongsToCurrentThread());

  if (remote_.is_bound()) {
    return true;
  }

  auto disconnect_handler =
      base::BindRepeating(&RemoteWebAuthnNativeMessagingHost::OnIpcDisconnected,
                          base::Unretained(this));
  // There is a bug in Mojo, such that if the host rejects binding of session
  // services, there is a chance that binding of WebAuthnProxy appears to be
  // successful and the disconnect handler of `remote_` is never called, so
  // `remote_` will remain invalid forever.
  // The disconnect handler of session services is still called, so we set a
  // disconnect handler on it.
  // See https://crbug.com/425759818#comment8 for more context.
  host_service_api_client_->set_disconnect_handler(disconnect_handler);
  auto* api = host_service_api_client_->GetSessionServices();
  if (!api) {
    return false;
  }
  api->BindWebAuthnProxy(remote_.BindNewPipeAndPassReceiver());
  remote_.set_disconnect_handler(disconnect_handler);
  return true;
}

void RemoteWebAuthnNativeMessagingHost::SendMessageToClient(
    base::Value::Dict message) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  std::string message_json;
  if (!base::JSONWriter::Write(message, &message_json)) {
    LOG(ERROR) << "Failed to write message to JSON";
    return;
  }
  client_->PostMessageFromNativeHost(message_json);
}

const base::Value* RemoteWebAuthnNativeMessagingHost::FindMessageIdOrSendError(
    base::Value::Dict& response) {
  const base::Value* message_id = response.Find(kMessageId);
  if (message_id) {
    return message_id;
  }
  response.Set(kWebAuthnErrorKey,
               CreateWebAuthnExceptionDetailsDict(
                   "NotSupportedError", "Message ID not found in request."));
  SendMessageToClient(std::move(response));
  return nullptr;
}

const std::string*
RemoteWebAuthnNativeMessagingHost::FindRequestDataOrSendError(
    const base::Value::Dict& request,
    const std::string& request_data_key,
    base::Value::Dict& response) {
  const std::string* request_data = request.FindString(request_data_key);
  if (request_data) {
    return request_data;
  }
  response.Set(
      kWebAuthnErrorKey,
      CreateWebAuthnExceptionDetailsDict(
          "NotSupportedError", "Request data not found in the request."));
  SendMessageToClient(std::move(response));
  return nullptr;
}

mojo::PendingReceiver<mojom::WebAuthnRequestCanceller>
RemoteWebAuthnNativeMessagingHost::AddRequestCanceller(base::Value message_id) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  mojo::PendingRemote<mojom::WebAuthnRequestCanceller>
      pending_request_canceller;
  auto request_canceller_receiver =
      pending_request_canceller.InitWithNewPipeAndPassReceiver();
  id_to_request_canceller_.emplace(
      std::move(message_id),
      request_cancellers_.Add(std::move(pending_request_canceller)));
  return request_canceller_receiver;
}

void RemoteWebAuthnNativeMessagingHost::RemoveRequestCancellerByMessageId(
    const base::Value& message_id) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  auto it = id_to_request_canceller_.find(message_id);
  if (it != id_to_request_canceller_.end()) {
    request_cancellers_.Remove(it->second);
    id_to_request_canceller_.erase(it);
  } else {
    // This may happen, say if the request canceller is disconnected before the
    // create/get response is received, so we just verbose-log it.
    VLOG(1) << "Cannot find receiver for message ID " << message_id;
  }
}

void RemoteWebAuthnNativeMessagingHost::OnRequestCancellerDisconnected(
    mojo::RemoteSetElementId disconnecting_canceller) {
  DCHECK(task_runner_->BelongsToCurrentThread());

  auto it = std::ranges::find(id_to_request_canceller_, disconnecting_canceller,
                              &IdToRequestMap::value_type::second);
  if (it != id_to_request_canceller_.end()) {
    id_to_request_canceller_.erase(it);
  }

  if (on_request_canceller_disconnected_for_testing_) {
    on_request_canceller_disconnected_for_testing_.Run();
  }
}

void RemoteWebAuthnNativeMessagingHost::SendClientDisconnectedMessage() {
  DCHECK(task_runner_->BelongsToCurrentThread());

  base::Value::Dict message;
  message.Set(kMessageType, kClientDisconnectedMessageType);
  SendMessageToClient(std::move(message));
}

}  // namespace remoting