File: smart_card_service.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (316 lines) | stat: -rw-r--r-- 11,636 bytes parent folder | download | duplicates (5)
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
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/smart_card/smart_card_service.h"

#include "base/check_deref.h"
#include "base/containers/extend.h"
#include "base/containers/map_util.h"
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include "content/browser/smart_card/smart_card_histograms.h"
#include "content/public/browser/isolated_context_util.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/smart_card_delegate.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "services/device/public/mojom/smart_card.mojom.h"
#include "third_party/blink/public/common/features_generated.h"

namespace content {

using device::mojom::SmartCardConnectResult;
using device::mojom::SmartCardCreateContextResult;
using device::mojom::SmartCardError;

namespace {
SmartCardDelegate& GetSmartCardDelegate() {
  return CHECK_DEREF(GetContentClient()->browser()->GetSmartCardDelegate());
}
}  // namespace

SmartCardService::SmartCardService(
    RenderFrameHost& render_frame_host,
    mojo::PendingReceiver<blink::mojom::SmartCardService> receiver,
    mojo::PendingRemote<device::mojom::SmartCardContextFactory> context_factory)
    : DocumentService(render_frame_host, std::move(receiver)),
      context_factory_(std::move(context_factory)) {
  // base::Unretained is safe in below cases, as receiver sets, being members,
  // are bound to the lifetime of this object.
  context_wrapper_receivers_.set_disconnect_handler(
      base::BindRepeating(&SmartCardService::OnMojoWrapperContextDisconnected,
                          base::Unretained(this)));
  connection_watcher_receivers_.set_disconnect_handler(base::BindRepeating(
      &SmartCardService::OnMojoWatcherPipeClosed, base::Unretained(this)));
  GetSmartCardDelegate().AddObserver(render_frame_host, this);
}

SmartCardService::~SmartCardService() {
  GetSmartCardDelegate().RemoveObserver(render_frame_host(), this);
}

// static
void SmartCardService::Create(
    RenderFrameHost* render_frame_host,
    mojo::PendingReceiver<blink::mojom::SmartCardService> receiver) {
  BrowserContext* browser_context = render_frame_host->GetBrowserContext();
  DCHECK(browser_context);

  if (!base::FeatureList::IsEnabled(blink::features::kSmartCard)) {
    mojo::ReportBadMessage("The SmartCard feature is disabled.");
    return;
  }

  if (!render_frame_host->IsFeatureEnabled(
          network::mojom::PermissionsPolicyFeature::kSmartCard)) {
    mojo::ReportBadMessage(
        "Access to the feature \"smart-card\" is disallowed by permissions "
        "policy.");
    return;
  }

  if (!HasIsolatedContextCapability(render_frame_host)) {
    mojo::ReportBadMessage(
        "Frame is not sufficiently isolated to use the Smart Card API.");
    return;
  }

  SmartCardDelegate* delegate =
      GetContentClient()->browser()->GetSmartCardDelegate();
  if (!delegate) {
    mojo::ReportBadMessage("Browser has no Smart Card delegate.");
    return;
  }

  new SmartCardService(*render_frame_host, std::move(receiver),
                       delegate->GetSmartCardContextFactory(*browser_context));
}

void SmartCardService::CreateContext(CreateContextCallback callback) {
  if (GetSmartCardDelegate().IsPermissionBlocked(render_frame_host())) {
    std::move(callback).Run(SmartCardCreateContextResult::NewError(
        SmartCardError::kPermissionDenied));
    return;
  }

  context_factory_->CreateContext(
      base::BindOnce(&SmartCardService::OnContextCreated,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void SmartCardService::ListReaders(ListReadersCallback callback) {
  mojo::ReceiverId context_wrapper_id =
      context_wrapper_receivers_.current_receiver();

  mojo::Remote<SmartCardContext>& context_remote =
      CHECK_DEREF(base::FindOrNull(context_remotes_, context_wrapper_id));

  context_remote->ListReaders(
      base::BindOnce(&SmartCardService::OnListReadersResult,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void SmartCardService::GetStatusChange(
    base::TimeDelta timeout,
    std::vector<device::mojom::SmartCardReaderStateInPtr> reader_states,
    GetStatusChangeCallback callback) {
  mojo::ReceiverId context_wrapper_id =
      context_wrapper_receivers_.current_receiver();

  mojo::Remote<SmartCardContext>& context_remote =
      CHECK_DEREF(base::FindOrNull(context_remotes_, context_wrapper_id));

  context_remote->GetStatusChange(timeout, std::move(reader_states),
                                  std::move(callback));
}

void SmartCardService::Cancel(CancelCallback callback) {
  mojo::ReceiverId context_wrapper_id =
      context_wrapper_receivers_.current_receiver();

  mojo::Remote<SmartCardContext>& context_remote =
      CHECK_DEREF(base::FindOrNull(context_remotes_, context_wrapper_id));

  context_remote->Cancel(std::move(callback));
}

void SmartCardService::Connect(
    const std::string& reader,
    device::mojom::SmartCardShareMode share_mode,
    device::mojom::SmartCardProtocolsPtr preferred_protocols,
    mojo::PendingRemote<device::mojom::SmartCardConnectionWatcher>
        connection_watcher,
    ConnectCallback callback) {
  // This argument should be passed only from here to the platform-specific
  // component - not to here.
  CHECK(!mojo::Remote(std::move(connection_watcher)).is_bound());

  SmartCardDelegate& delegate = GetSmartCardDelegate();

  mojo::ReceiverId context_wrapper_id =
      context_wrapper_receivers_.current_receiver();

  if (delegate.HasReaderPermission(render_frame_host(), reader)) {
    mojo::Remote<SmartCardContext>& context_remote =
        CHECK_DEREF(base::FindOrNull(context_remotes_, context_wrapper_id));

    context_remote->Connect(reader, share_mode, std::move(preferred_protocols),
                            GetNewConnectionWatcher(reader),
                            std::move(callback));
    return;
  }

  if (!valid_reader_names_.contains(reader)) {
    // Avoid showing the user a string that comes directly from the application.
    //
    // This will also block the case where an application asks to connect to a
    // reader without first checking whether it exists in the system (via
    // ListReaders). But no sane application should be doing this anyway.  If
    // this turns out to be a problem we will have to do a ListReaders() here on
    // our own before coming to a decision.
    std::move(callback).Run(
        SmartCardConnectResult::NewError(SmartCardError::kPermissionDenied));
    return;
  }

  delegate.RequestReaderPermission(
      render_frame_host(), reader,
      base::BindOnce(&SmartCardService::OnReaderPermissionResult,
                     weak_ptr_factory_.GetWeakPtr(), context_wrapper_id, reader,
                     share_mode, std::move(preferred_protocols),
                     std::move(callback)));
}

void SmartCardService::NotifyConnectionUsed() {
  GetSmartCardDelegate().NotifyConnectionUsed(render_frame_host());
}

void SmartCardService::OnReaderPermissionResult(
    mojo::ReceiverId context_wrapper_id,
    const std::string& reader,
    device::mojom::SmartCardShareMode share_mode,
    device::mojom::SmartCardProtocolsPtr preferred_protocols,
    ConnectCallback callback,
    bool granted) {
  auto it = context_remotes_.find(context_wrapper_id);
  if (it == context_remotes_.end()) {
    // Can happen if the renderer has dropped the wrapper remote in the
    // meantime.
    std::move(callback).Run(
        SmartCardConnectResult::NewError(SmartCardError::kUnexpected));
    return;
  }

  if (!granted) {
    std::move(callback).Run(
        SmartCardConnectResult::NewError(SmartCardError::kPermissionDenied));
    return;
  }

  mojo::Remote<SmartCardContext>& context_remote = it->second;

  context_remote->Connect(reader, share_mode, std::move(preferred_protocols),
                          GetNewConnectionWatcher(reader), std::move(callback));
}

void SmartCardService::OnMojoWrapperContextDisconnected() {
  mojo::ReceiverId context_wrapper_id =
      context_wrapper_receivers_.current_receiver();

  context_remotes_.erase(context_wrapper_id);
}

void SmartCardService::OnListReadersResult(
    ListReadersCallback callback,
    device::mojom::SmartCardListReadersResultPtr result) {
  if (result->is_readers()) {
    // Update our set of valid reader names.
    // Note that this is larger than the set of "currently available readers".
    for (const auto& reader : result->get_readers()) {
      valid_reader_names_.insert(reader);
    }
  }

  // And finally forward the result to the original caller.
  std::move(callback).Run(std::move(result));
}

void SmartCardService::OnContextCreated(
    CreateContextCallback callback,
    ::device::mojom::SmartCardCreateContextResultPtr result) {
  if (result->is_error()) {
    std::move(callback).Run(std::move(result));
    return;
  }

  // Wrap the context so that we can do permission checking/prompting before
  // forwarding a call where appropriate.

  mojo::PendingRemote<device::mojom::SmartCardContext> wrapper_remote;

  mojo::ReceiverId context_wrapper_id = context_wrapper_receivers_.Add(
      this, wrapper_remote.InitWithNewPipeAndPassReceiver());

  context_remotes_[context_wrapper_id] =
      mojo::Remote<SmartCardContext>(std::move(result->get_context()));

  result->set_context(std::move(wrapper_remote));

  std::move(callback).Run(std::move(result));
}

mojo::PendingRemote<device::mojom::SmartCardConnectionWatcher>
SmartCardService::GetNewConnectionWatcher(const std::string& reader) {
  mojo::PendingRemote<device::mojom::SmartCardConnectionWatcher>
      ceaseless_watcher;
  auto receiver_id = connection_watcher_receivers_.Add(
      this, ceaseless_watcher.InitWithNewPipeAndPassReceiver());
  connection_watchers_per_reader_[reader].insert(receiver_id);
  reader_names_per_watcher_[receiver_id] = reader;
  return ceaseless_watcher;
}

void SmartCardService::OnMojoWatcherPipeClosed() {
  auto receiver_id = connection_watcher_receivers_.current_receiver();
  auto reader_it = reader_names_per_watcher_.find(receiver_id);
  if (reader_it == reader_names_per_watcher_.end()) {
    return;
  }
  const std::string& reader = reader_it->second;
  auto reader_ids_it = connection_watchers_per_reader_.find(reader);
  if (reader_ids_it == connection_watchers_per_reader_.end()) {
    return;
  }
  reader_ids_it->second.erase(receiver_id);
  reader_names_per_watcher_.erase(reader_it);

  if (reader_names_per_watcher_.empty()) {
    GetSmartCardDelegate().NotifyLastConnectionLost(render_frame_host());
  }
  RecordSmartCardConnectionClosedReason(
      SmartCardConnectionClosedReason::kSmartCardConnectionClosedDisconnect);
}

void SmartCardService::OnPermissionRevoked(const url::Origin& origin) {
  if (render_frame_host().GetLastCommittedOrigin() != origin) {
    return;
  }

  auto& delegate = GetSmartCardDelegate();

  std::vector<mojo::ReceiverId> watchers_of_connections_to_remove;
  for (const auto& [reader_name, receiver_ids] :
       connection_watchers_per_reader_) {
    if (delegate.HasReaderPermission(render_frame_host(), reader_name)) {
      continue;
    }
    base::Extend(watchers_of_connections_to_remove, receiver_ids);
  }
  for (const auto& receiver_id : watchers_of_connections_to_remove) {
    connection_watcher_receivers_.Remove(receiver_id);
    RecordSmartCardConnectionClosedReason(
        SmartCardConnectionClosedReason::
            kSmartCardConnectionClosedPermissionRevoked);
  }
}

}  // namespace content