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 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
|
// 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 <memory>
#include "base/files/file_path.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/stringprintf.h"
#include "base/test/bind.h"
#include "build/build_config.h"
#include "chrome/browser/chrome_content_browser_client.h"
#include "chrome/browser/extensions/api/messaging/native_messaging_test_util.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_client.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "extensions/browser/api/storage/storage_api.h"
#include "extensions/browser/background_script_executor.h"
#include "extensions/browser/bad_message.h"
#include "extensions/browser/browsertest_util.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_frame_host.h"
#include "extensions/browser/extension_web_contents_observer.h"
#include "extensions/browser/process_manager.h"
#include "extensions/browser/renderer_startup_helper.h"
#include "extensions/browser/script_executor.h"
#include "extensions/browser/service_worker/service_worker_host.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension_features.h"
#include "extensions/common/mojom/frame.mojom-test-utils.h"
#include "extensions/common/mojom/service_worker_host.mojom-test-utils.h"
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/test_extension_dir.h"
#include "ipc/ipc_security_test_util.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_database.mojom-forward.h"
#include "url/gurl.h"
namespace extensions {
// ExtensionFrameHostInterceptor is a helper for:
// - Intercepting mojom::LocalFrameHost method calls (e.g. methods
// that would normally be handled / implemented by ExtensionFrameHost).
// - Allowing the test to mutate the method arguments (e.g. to simulate a
// compromised renderer) before passing the method call to the usual handler.
class ExtensionFrameHostInterceptor
: mojom::LocalFrameHostInterceptorForTesting {
public:
// The caller needs to ensure that `frame` stays alive longer than the
// constructed ExtensionFrameHostInterceptor.
explicit ExtensionFrameHostInterceptor(content::RenderFrameHost* frame)
: frame_(frame),
extension_frame_host_(
ExtensionWebContentsObserver::GetForWebContents(
content::WebContents::FromRenderFrameHost(frame_))
->extension_frame_host_for_testing()),
scoped_swap_impl_(extension_frame_host_->receivers_for_testing(),
this) {}
~ExtensionFrameHostInterceptor() override = default;
using RequestMutator =
base::RepeatingCallback<void(mojom::RequestParams& request_params)>;
void SetRequestMutator(RequestMutator request_mutator) {
request_mutator_ = std::move(request_mutator);
}
using OpenChannelToExtensionMutator =
base::RepeatingCallback<void(mojom::ExternalConnectionInfo& info)>;
void SetOpenChannelToExtensionMutator(
OpenChannelToExtensionMutator open_extension_mutator) {
open_extension_mutator_ = std::move(open_extension_mutator);
}
private:
mojom::LocalFrameHost* GetForwardingInterface() override {
return scoped_swap_impl_.old_impl();
}
void Request(mojom::RequestParamsPtr params,
RequestCallback callback) override {
// `//extensions/common/mojom/frame.mojom` specifies that `params` is
// non-optional.
CHECK(params);
content::RenderFrameHost* current_target_frame =
extension_frame_host_->receivers_for_testing().GetCurrentTargetFrame();
if (request_mutator_ && frame_ == current_target_frame) {
request_mutator_.Run(*params);
}
GetForwardingInterface()->Request(std::move(params), std::move(callback));
}
void OpenChannelToExtension(
mojom::ExternalConnectionInfoPtr info,
mojom::ChannelType channel_type,
const std::string& channel_name,
const PortId& port_id,
mojo::PendingAssociatedRemote<mojom::MessagePort> port,
mojo::PendingAssociatedReceiver<mojom::MessagePortHost> port_host)
override {
CHECK(info);
content::RenderFrameHost* current_target_frame =
extension_frame_host_->receivers_for_testing().GetCurrentTargetFrame();
if (open_extension_mutator_ && frame_ == current_target_frame) {
open_extension_mutator_.Run(*info);
}
GetForwardingInterface()->OpenChannelToExtension(
std::move(info), channel_type, channel_name, port_id, std::move(port),
std::move(port_host));
}
const raw_ptr<content::RenderFrameHost> frame_ = nullptr;
RequestMutator request_mutator_;
OpenChannelToExtensionMutator open_extension_mutator_;
const raw_ptr<ExtensionFrameHost> extension_frame_host_ = nullptr;
const mojo::test::ScopedSwapImplForTesting<mojom::LocalFrameHost>
scoped_swap_impl_;
};
class ServiceWorkerHostInterceptorForProcessDeath
: public mojom::ServiceWorkerHostInterceptorForTesting {
public:
// We use `worker_id` to have an weak handle to the `ServiceWorkerHost`
// which will be destroyed when this object mutates the IPC to cause
// a bad message resulting in process death.
explicit ServiceWorkerHostInterceptorForProcessDeath(
const WorkerId& worker_id)
: worker_id_(worker_id) {
auto* host = extensions::ServiceWorkerHost::GetWorkerFor(worker_id_);
CHECK(host);
std::ignore = host->receiver_for_testing().SwapImplForTesting(this);
}
mojom::ServiceWorkerHost* GetForwardingInterface() override {
// This should be non-null if this interface is still receiving events.
auto* host = extensions::ServiceWorkerHost::GetWorkerFor(worker_id_);
CHECK(host);
return host;
}
void OpenChannelToExtension(
mojom::ExternalConnectionInfoPtr info,
mojom::ChannelType channel_type,
const std::string& channel_name,
const PortId& port_id,
mojo::PendingAssociatedRemote<mojom::MessagePort> port,
mojo::PendingAssociatedReceiver<mojom::MessagePortHost> port_host)
override {
CHECK(info);
if (open_extension_mutator_) {
open_extension_mutator_.Run(*info);
}
GetForwardingInterface()->OpenChannelToExtension(
std::move(info), channel_type, channel_name, port_id, std::move(port),
std::move(port_host));
}
using OpenChannelToExtensionMutator =
base::RepeatingCallback<void(mojom::ExternalConnectionInfo& info)>;
void SetOpenChannelToExtensionMutator(
OpenChannelToExtensionMutator open_extension_mutator) {
open_extension_mutator_ = std::move(open_extension_mutator);
}
private:
OpenChannelToExtensionMutator open_extension_mutator_;
const WorkerId worker_id_;
};
// Waits for a kill of the given RenderProcessHost and returns the
// BadMessageReason that caused an //extensions-triggerred kill.
//
// Example usage:
// RenderProcessHostBadIpcMessageWaiter kill_waiter(render_process_host);
// ... test code that triggers a renderer kill ...
// EXPECT_EQ(bad_message::EFD_BAD_MESSAGE_PROCESS, kill_waiter.Wait());
class RenderProcessHostBadIpcMessageWaiter {
public:
explicit RenderProcessHostBadIpcMessageWaiter(
content::RenderProcessHost* render_process_host)
: internal_waiter_(render_process_host,
"Stability.BadMessageTerminated.Extensions") {}
// Waits until the renderer process exits. Returns the bad message that made
// //extensions kill the renderer. `std::nullopt` is returned if the
// renderer was killed outside of //extensions or exited normally.
[[nodiscard]] std::optional<bad_message::BadMessageReason> Wait() {
std::optional<int> internal_result = internal_waiter_.Wait();
if (!internal_result.has_value())
return std::nullopt;
return static_cast<bad_message::BadMessageReason>(internal_result.value());
}
RenderProcessHostBadIpcMessageWaiter(
const RenderProcessHostBadIpcMessageWaiter&) = delete;
RenderProcessHostBadIpcMessageWaiter& operator=(
const RenderProcessHostBadIpcMessageWaiter&) = delete;
private:
content::RenderProcessHostKillWaiter internal_waiter_;
};
// Test suite covering how mojo/IPC messages are verified after being received
// from a (potentially compromised) renderer process.
class ExtensionSecurityExploitBrowserTest : public ExtensionBrowserTest {
public:
ExtensionSecurityExploitBrowserTest() = default;
void SetUpOnMainThread() override {
ExtensionBrowserTest::SetUpOnMainThread();
host_resolver()->AddRule("*", "127.0.0.1");
content::SetupCrossSiteRedirector(embedded_test_server());
ASSERT_TRUE(embedded_test_server()->Start());
}
content::WebContents* active_web_contents() {
return browser()->tab_strip_model()->GetActiveWebContents();
}
// Asks the `extension_id` to inject `content_script` into `web_contents`.
// Returns true if the content script execution started successfully.
bool ExecuteProgrammaticContentScript(content::WebContents* web_contents,
const ExtensionId& extension_id,
const std::string& content_script) {
DCHECK(web_contents);
int tab_id = ExtensionTabUtil::GetTabId(web_contents);
const char kScriptTemplate[] = R"(
chrome.scripting.executeScript({
target: {tabId: %d},
injectImmediately: true,
func: () => { %s }
});
)";
std::string background_script =
base::StringPrintf(kScriptTemplate, tab_id, content_script.c_str());
return BackgroundScriptExecutor::ExecuteScriptAsync(
browser()->profile(), extension_id, background_script);
}
// (Asynchronously) executes the given `script` in a user script world in
// `web_contents`, associated with the given `extension_id`
void ExecuteUserScript(content::WebContents& web_contents,
const ExtensionId& extension_id,
const std::string& script) {
ScriptExecutor script_executor(&web_contents);
std::vector<mojom::JSSourcePtr> sources;
sources.push_back(mojom::JSSource::New(script, GURL()));
script_executor.ExecuteScript(
mojom::HostID(mojom::HostID::HostType::kExtensions, extension_id),
mojom::CodeInjection::NewJs(mojom::JSInjection::New(
std::move(sources), mojom::ExecutionWorld::kUserScript,
/*world_id=*/std::nullopt,
blink::mojom::WantResultOption::kWantResult,
blink::mojom::UserActivationOption::kDoNotActivate,
blink::mojom::PromiseResultOption::kAwait)),
ScriptExecutor::SPECIFIED_FRAMES, {ExtensionApiFrameIdMap::kTopFrameId},
mojom::MatchOriginAsFallbackBehavior::kNever,
mojom::RunLocation::kDocumentIdle, ScriptExecutor::DEFAULT_PROCESS,
GURL() /* webview_src */, base::DoNothing());
}
// Allows messaging APIs for user scripts created by the given `extension`.
void AllowUserScriptMessaging(const Extension& extension) {
RendererStartupHelperFactory::GetForBrowserContext(profile())
->SetUserScriptWorldProperties(
extension, mojom::UserScriptWorldInfo::New(
extension.id(), /*world_id=*/std::nullopt,
/*csp=*/std::nullopt,
/*enable_messaging=*/true));
}
const Extension& active_extension() { return *active_extension_; }
const ExtensionId& active_extension_id() { return active_extension_->id(); }
const Extension& spoofed_extension() { return *spoofed_extension_; }
const ExtensionId& spoofed_extension_id() { return spoofed_extension_->id(); }
// Installs an `active_extension` and a separate, but otherwise identical
// `spoofed_extension` (the only difference will be the extension id).
void InstallTestExtensions() {
auto install_extension =
[this](TestExtensionDir& dir,
const char* extra_manifest_bits) -> const Extension* {
const char kManifestTemplate[] = R"(
{
%s
"name": "ScriptInjectionTrackerBrowserTest - Programmatic",
"version": "1.0",
"manifest_version": 3,
"host_permissions": ["http://foo.com/*"],
"permissions": [
"scripting",
"tabs",
"nativeMessaging",
"storage"
],
"background": {"service_worker": "background_script.js"}
} )";
dir.WriteManifest(
base::StringPrintf(kManifestTemplate, extra_manifest_bits));
dir.WriteFile(FILE_PATH_LITERAL("background_script.js"), "");
dir.WriteFile(FILE_PATH_LITERAL("page.html"), "<p>page</p>");
return LoadExtension(dir.UnpackedPath());
};
// The key below corresponds to the extension ID used by
// ScopedTestNativeMessagingHost::kExtensionId.
const char kActiveExtensionKey[] = R"(
"key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcBHwzDvyBQ6bDppkIs9MP4ksKqCMyXQ/A52JivHZKh4YO/9vJsT3oaYhSpDCE9RPocOEQvwsHsFReW2nUEc6OLLyoCFFxIb7KkLGsmfakkut/fFdNJYh0xOTbSN8YvLWcqph09XAY2Y/f0AL7vfO1cuCqtkMt8hFrBGWxDdf9CQIDAQAB",
)";
active_extension_ = install_extension(active_dir_, kActiveExtensionKey);
spoofed_extension_ = install_extension(spoofed_dir_, "");
ASSERT_TRUE(active_extension_);
ASSERT_TRUE(spoofed_extension_);
ASSERT_EQ(active_extension_id(),
ScopedTestNativeMessagingHost::kExtensionId);
ASSERT_NE(active_extension_id(), spoofed_extension_id());
}
private:
TestExtensionDir active_dir_;
TestExtensionDir spoofed_dir_;
raw_ptr<const Extension, DanglingUntriaged> active_extension_ = nullptr;
raw_ptr<const Extension, DanglingUntriaged> spoofed_extension_ = nullptr;
};
// Test suite for covering ExtensionHostMsg_OpenChannelToExtension IPC.
class OpenChannelToExtensionExploitTest
: public ExtensionSecurityExploitBrowserTest {
public:
OpenChannelToExtensionExploitTest() = default;
void SetUpOnMainThread() override {
ExtensionSecurityExploitBrowserTest::SetUpOnMainThread();
// Navigate to an arbitrary, mostly empty test page. Make sure that a new
// RenderProcessHost is created to make sure it is covered by the
// `ipc_message_waiter_`. (A WebUI -> http navigation should swap the
// RenderProcessHost on all platforms.)
GURL test_page_url =
embedded_test_server()->GetURL("foo.com", "/title1.html");
int old_process_id = active_web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetDeprecatedID();
EXPECT_TRUE(
ui_test_utils::NavigateToURL(browser(), GURL("chrome://version")));
EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), test_page_url));
int new_process_id = active_web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetDeprecatedID();
EXPECT_NE(old_process_id, new_process_id);
// Install the extensions (and potentially spawn new RenderProcessHosts)
// only *after* the `ipc_message_waiter_` has been constructed.
InstallTestExtensions();
}
};
IN_PROC_BROWSER_TEST_F(OpenChannelToExtensionExploitTest,
FromContentScript_BadExtensionIdInMessagingSource) {
// Trigger sending of a valid ExtensionHostMsg_OpenChannelToExtension IPC
// from a content script of an `active_extension_id`.
ASSERT_TRUE(ExecuteProgrammaticContentScript(
active_web_contents(), active_extension_id(),
"chrome.runtime.sendMessage({greeting: 'hello'}, (response) => {});"));
content::RenderProcessHost* main_frame_process =
active_web_contents()->GetPrimaryMainFrame()->GetProcess();
RenderProcessHostBadIpcMessageWaiter kill_waiter(main_frame_process);
auto interceptor = std::make_unique<ExtensionFrameHostInterceptor>(
active_web_contents()->GetPrimaryMainFrame());
interceptor->SetOpenChannelToExtensionMutator(
base::BindLambdaForTesting([this](mojom::ExternalConnectionInfo& info) {
EXPECT_EQ(MessagingEndpoint::Type::kContentScript,
info.source_endpoint.type);
EXPECT_EQ(active_extension_id(), info.source_endpoint.extension_id);
// Mutate the IPC payload.
info.source_endpoint.extension_id = spoofed_extension_id();
}));
EXPECT_EQ(bad_message::EMF_INVALID_EXTENSION_ID_FOR_CONTENT_SCRIPT,
kill_waiter.Wait());
}
IN_PROC_BROWSER_TEST_F(OpenChannelToExtensionExploitTest,
FromContentScript_UnexpectedNativeAppType) {
// Trigger sending of a valid ExtensionHostMsg_OpenChannelToExtension IPC
// from a content script of an `active_extension_id`.
ASSERT_TRUE(ExecuteProgrammaticContentScript(
active_web_contents(), active_extension_id(),
"chrome.runtime.sendMessage({greeting: 'hello'}, (response) => {});"));
content::RenderProcessHost* main_frame_process =
active_web_contents()->GetPrimaryMainFrame()->GetProcess();
RenderProcessHostBadIpcMessageWaiter kill_waiter(main_frame_process);
auto interceptor = std::make_unique<ExtensionFrameHostInterceptor>(
active_web_contents()->GetPrimaryMainFrame());
interceptor->SetOpenChannelToExtensionMutator(
base::BindLambdaForTesting([this](mojom::ExternalConnectionInfo& info) {
EXPECT_EQ(MessagingEndpoint::Type::kContentScript,
info.source_endpoint.type);
EXPECT_EQ(active_extension_id(), info.source_endpoint.extension_id);
// Mutate the IPC payload.
info.source_endpoint.type = MessagingEndpoint::Type::kNativeApp;
}));
EXPECT_EQ(bad_message::EMF_INVALID_CHANNEL_SOURCE_TYPE, kill_waiter.Wait());
}
IN_PROC_BROWSER_TEST_F(OpenChannelToExtensionExploitTest,
FromContentScript_UnexpectedExtensionType) {
// Trigger sending of a valid ExtensionHostMsg_OpenChannelToExtension IPC
// from a content script of an `active_extension_id`.
ASSERT_TRUE(ExecuteProgrammaticContentScript(
active_web_contents(), active_extension_id(),
"chrome.runtime.sendMessage({greeting: 'hello'}, (response) => {});"));
content::RenderProcessHost* main_frame_process =
active_web_contents()->GetPrimaryMainFrame()->GetProcess();
RenderProcessHostBadIpcMessageWaiter kill_waiter(main_frame_process);
auto interceptor = std::make_unique<ExtensionFrameHostInterceptor>(
active_web_contents()->GetPrimaryMainFrame());
interceptor->SetOpenChannelToExtensionMutator(
base::BindLambdaForTesting([this](mojom::ExternalConnectionInfo& info) {
EXPECT_EQ(MessagingEndpoint::Type::kContentScript,
info.source_endpoint.type);
EXPECT_EQ(active_extension_id(), info.source_endpoint.extension_id);
// Mutate the IPC payload.
info.source_endpoint.type = MessagingEndpoint::Type::kExtension;
}));
EXPECT_EQ(bad_message::EMF_INVALID_EXTENSION_ID_FOR_EXTENSION_SOURCE,
kill_waiter.Wait());
}
IN_PROC_BROWSER_TEST_F(OpenChannelToExtensionExploitTest,
FromContentScript_NoExtensionIdForExtensionType) {
// Trigger sending of a valid ExtensionHostMsg_OpenChannelToExtension IPC
// from a content script of an `active_extension_id`.
ASSERT_TRUE(ExecuteProgrammaticContentScript(
active_web_contents(), active_extension_id(),
"chrome.runtime.sendMessage({greeting: 'hello'}, (response) => {});"));
content::RenderProcessHost* main_frame_process =
active_web_contents()->GetPrimaryMainFrame()->GetProcess();
RenderProcessHostBadIpcMessageWaiter kill_waiter(main_frame_process);
auto interceptor = std::make_unique<ExtensionFrameHostInterceptor>(
active_web_contents()->GetPrimaryMainFrame());
interceptor->SetOpenChannelToExtensionMutator(
base::BindLambdaForTesting([this](mojom::ExternalConnectionInfo& info) {
EXPECT_EQ(MessagingEndpoint::Type::kContentScript,
info.source_endpoint.type);
EXPECT_EQ(active_extension_id(), info.source_endpoint.extension_id);
// Mutate the IPC payload.
info.source_endpoint.type = MessagingEndpoint::Type::kExtension;
info.source_endpoint.extension_id = std::nullopt;
}));
EXPECT_EQ(bad_message::EMF_NO_EXTENSION_ID_FOR_EXTENSION_SOURCE,
kill_waiter.Wait());
}
IN_PROC_BROWSER_TEST_F(OpenChannelToExtensionExploitTest,
FromContentScript_BadSourceUrl_FromFrame) {
// Trigger sending of a valid ExtensionHostMsg_OpenChannelToExtension IPC
// from a content script of an `active_extension_id`.
ASSERT_TRUE(ExecuteProgrammaticContentScript(
active_web_contents(), active_extension_id(),
"chrome.runtime.sendMessage({greeting: 'hello'}, (response) => {});"));
content::RenderProcessHost* main_frame_process =
active_web_contents()->GetPrimaryMainFrame()->GetProcess();
RenderProcessHostBadIpcMessageWaiter kill_waiter(main_frame_process);
auto interceptor = std::make_unique<ExtensionFrameHostInterceptor>(
active_web_contents()->GetPrimaryMainFrame());
interceptor->SetOpenChannelToExtensionMutator(
base::BindLambdaForTesting([this](mojom::ExternalConnectionInfo& info) {
EXPECT_EQ(MessagingEndpoint::Type::kContentScript,
info.source_endpoint.type);
EXPECT_EQ(active_extension_id(), info.source_endpoint.extension_id);
// Mutate `source_url` in the IPC payload.
GURL actual_url =
active_web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL();
ASSERT_EQ(actual_url, info.source_url);
GURL spoofed_url =
embedded_test_server()->GetURL("spoofed.com", "/title1.html");
ASSERT_NE(spoofed_url.host(), actual_url.host());
info.source_url = spoofed_url;
}));
EXPECT_EQ(bad_message::EMF_INVALID_SOURCE_URL, kill_waiter.Wait());
}
IN_PROC_BROWSER_TEST_F(OpenChannelToExtensionExploitTest,
FromServiceWorker_BadSourceUrl) {
// Navigate the test tab to an extension page.
// TODO(crbug.com/40874764): Remove this test step - it is only here as
// a workaround for the bug that impacts how renderer kills are detected when
// there are no frames in a given renderer process.
GURL test_page_url = active_extension().GetResourceURL("page.html");
EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), test_page_url));
// Trigger sending of a valid ExtensionHostMsg_OpenChannelToExtension IPC
// from the service worker of an `active_extension_id`.
ASSERT_TRUE(BackgroundScriptExecutor::ExecuteScriptAsync(
browser()->profile(), active_extension_id(),
"chrome.runtime.sendMessage({greeting: 'hello'});"));
std::vector<WorkerId> service_workers =
ProcessManager::Get(browser()->profile())
->GetServiceWorkersForExtension(active_extension_id());
ASSERT_EQ(1u, service_workers.size());
content::RenderProcessHost* service_worker_process =
content::RenderProcessHost::FromID(service_workers[0].render_process_id);
ASSERT_TRUE(service_worker_process);
RenderProcessHostBadIpcMessageWaiter kill_waiter(service_worker_process);
auto interceptor =
std::make_unique<ServiceWorkerHostInterceptorForProcessDeath>(
service_workers[0]);
interceptor->SetOpenChannelToExtensionMutator(
base::BindLambdaForTesting([this](mojom::ExternalConnectionInfo& info) {
EXPECT_EQ(MessagingEndpoint::Type::kExtension,
info.source_endpoint.type);
EXPECT_EQ(active_extension_id(), info.source_endpoint.extension_id);
EXPECT_EQ(info.source_url.host(), active_extension_id());
// Mutate `source_url` in the IPC payload.
info.source_url =
spoofed_extension().GetResourceURL("some_resource.html");
EXPECT_EQ(info.source_url.host(), spoofed_extension_id());
}));
EXPECT_EQ(bad_message::EMF_INVALID_SOURCE_URL, kill_waiter.Wait());
}
// This is a regression test for https://crbug.com/1379558.
IN_PROC_BROWSER_TEST_F(ExtensionSecurityExploitBrowserTest,
SendMessageFromContentScriptInDataUrlFrame) {
// Install a test extension that 1) declaratively injects content scripts into
// all frames (including data: frames thanks to `match_origin_as_fallback`),
// 2) sends a message from the content script to the extension, 3) echoes back
// the `source_url` of the message sender via `chrome.test.sendMessage`.
//
// Note that `chrome.scripting.executeScript` is unable to inject content
// scripts into data: frames (without additional permissions), because this
// API doesn't have a knob equivalent to `match_origin_as_fallback`. This is
// the primary reason for using manifest-declared content scripts in this
// test.
TestExtensionDir dir;
const char kManifestTemplate[] = R"(
{
"name": "source_url echo-er",
"version": "1.0",
"manifest_version": 3,
"content_scripts": [{
"all_frames": true,
"match_about_blank": true,
"match_origin_as_fallback": true,
"matches": ["*://foo.com/*"],
"js": ["content_script.js"]
}],
"background": {"service_worker": "background_script.js"}
} )";
dir.WriteManifest(kManifestTemplate);
const char kBackgroundScript[] = R"(
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
chrome.test.sendMessage(sender.url);
}
);
)";
dir.WriteFile(FILE_PATH_LITERAL("background_script.js"), kBackgroundScript);
const char kContentScript[] = R"(
chrome.runtime.sendMessage({greeting: 'hello'}, (response) => {});
)";
dir.WriteFile(FILE_PATH_LITERAL("content_script.js"), kContentScript);
const Extension* extension = LoadExtension(dir.UnpackedPath());
ASSERT_TRUE(extension);
// Navigate to foo.com (covered by `content_scripts.matches` above).
GURL http_url = embedded_test_server()->GetURL("foo.com", "/title1.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), http_url));
// Add a data: URL subframe and wait for its `source_url` to be echoed back.
// The data: URL encodes `<p>foo</p>` HTML doc.
const GURL kDataUrl("data:text/html;charset=utf-8;base64,PHA+Zm9vPC9wPg==");
ExtensionTestMessageListener listener(kDataUrl.spec());
const char kScriptTemplate[] = R"(
new Promise(function (resolve, reject) {
var iframe = document.createElement('iframe');
iframe.src = $1;
iframe.onload = () => {
resolve("onload");
};
document.body.appendChild(iframe);
});
)";
ASSERT_EQ("onload",
content::EvalJs(active_web_contents(),
content::JsReplace(kScriptTemplate, kDataUrl)));
ASSERT_TRUE(listener.WaitUntilSatisfied());
// The main verification here (against https://crbug.com/1379558) is that the
// renderer process wasn't terminated (because of incorrectly classifying IPC
// payload as spoofed / illegitimately claiming to come on behalf of the data
// URL). This verification happens at the test suite level (e.g. see
// `content::NoRendererCrashesAssertion` for more details).
}
IN_PROC_BROWSER_TEST_F(ExtensionSecurityExploitBrowserTest,
SpoofedExtensionId_ExtensionFunctionDispatcher) {
InstallTestExtensions();
// Navigate to a test page.
GURL test_page_url =
embedded_test_server()->GetURL("foo.com", "/title1.html");
ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_page_url));
content::RenderFrameHost* main_frame =
active_web_contents()->GetPrimaryMainFrame();
// Verify the test setup by checking if the non-intercepted `chrome.storage`
// API call will succeed.
{
ExtensionTestMessageListener listener("Got chrome.storage response");
ASSERT_TRUE(ExecuteProgrammaticContentScript(active_web_contents(),
active_extension_id(), R"(
chrome.storage.local.set(
{ test_key: 'test value'},
() => {
chrome.test.sendMessage('Got chrome.storage response');
}
); )"));
ASSERT_TRUE(listener.WaitUntilSatisfied());
}
// Prepare to mutate the extension id in the IPC associated with the
// `chrome.storage.local.set`.
auto interceptor =
std::make_unique<ExtensionFrameHostInterceptor>(main_frame);
interceptor->SetRequestMutator(
base::BindLambdaForTesting([this](mojom::RequestParams& request_params) {
if (request_params.name != "storage.set")
return;
EXPECT_EQ(active_extension_id(), request_params.extension_id);
request_params.extension_id = spoofed_extension_id();
}));
// Trigger an IPC associated with the `chrome.storage.local.set` API and
// verify that the mutated/spoofed extension id is detected and leads to
// terminating the misbehaving renderer process.
RenderProcessHostBadIpcMessageWaiter kill_waiter(main_frame->GetProcess());
ASSERT_TRUE(ExecuteProgrammaticContentScript(active_web_contents(),
active_extension_id(),
R"(
chrome.storage.local.set({ test_key: 'test value2'}, () => {}); )"));
EXPECT_EQ(bad_message::EFD_INVALID_EXTENSION_ID_FOR_PROCESS,
kill_waiter.Wait());
}
IN_PROC_BROWSER_TEST_F(OpenChannelToExtensionExploitTest,
FromUserScript_BadExtensionIdInMessagingSource) {
AllowUserScriptMessaging(active_extension());
// Trigger sending of a valid ExtensionHostMsg_OpenChannelToExtension IPC
// from a user script of an `active_extension_id`.
ExecuteUserScript(
*active_web_contents(), active_extension_id(),
"chrome.runtime.sendMessage({greeting: 'hello'}, (response) => {});");
content::RenderProcessHost* main_frame_process =
active_web_contents()->GetPrimaryMainFrame()->GetProcess();
RenderProcessHostBadIpcMessageWaiter kill_waiter(main_frame_process);
auto interceptor = std::make_unique<ExtensionFrameHostInterceptor>(
active_web_contents()->GetPrimaryMainFrame());
interceptor->SetOpenChannelToExtensionMutator(
base::BindLambdaForTesting([this](mojom::ExternalConnectionInfo& info) {
EXPECT_EQ(MessagingEndpoint::Type::kUserScript,
info.source_endpoint.type);
EXPECT_EQ(active_extension_id(), info.source_endpoint.extension_id);
// Mutate the IPC payload.
info.source_endpoint.extension_id.reset();
}));
EXPECT_EQ(bad_message::EMF_INVALID_EXTENSION_ID_FOR_USER_SCRIPT,
kill_waiter.Wait());
}
IN_PROC_BROWSER_TEST_F(OpenChannelToExtensionExploitTest,
FromUserScript_SpoofedExtensionIdInMessagingSource) {
AllowUserScriptMessaging(active_extension());
// Trigger sending of a valid ExtensionHostMsg_OpenChannelToExtension IPC
// from a user script of an `active_extension_id`.
ExecuteUserScript(
*active_web_contents(), active_extension_id(),
"chrome.runtime.sendMessage({greeting: 'hello'}, (response) => {});");
content::RenderProcessHost* main_frame_process =
active_web_contents()->GetPrimaryMainFrame()->GetProcess();
RenderProcessHostBadIpcMessageWaiter kill_waiter(main_frame_process);
auto interceptor = std::make_unique<ExtensionFrameHostInterceptor>(
active_web_contents()->GetPrimaryMainFrame());
interceptor->SetOpenChannelToExtensionMutator(
base::BindLambdaForTesting([this](mojom::ExternalConnectionInfo& info) {
EXPECT_EQ(MessagingEndpoint::Type::kUserScript,
info.source_endpoint.type);
EXPECT_EQ(active_extension_id(), info.source_endpoint.extension_id);
// Mutate the IPC payload.
info.source_endpoint.extension_id = spoofed_extension_id();
}));
EXPECT_EQ(bad_message::EMF_INVALID_EXTENSION_ID_FOR_USER_SCRIPT,
kill_waiter.Wait());
}
IN_PROC_BROWSER_TEST_F(OpenChannelToExtensionExploitTest,
FromUserScript_TargetingAnotherExtensionId) {
AllowUserScriptMessaging(active_extension());
// Trigger sending of a valid ExtensionHostMsg_OpenChannelToExtension IPC
// from a user script of an `active_extension_id`.
ExecuteUserScript(
*active_web_contents(), active_extension_id(),
"chrome.runtime.sendMessage({greeting: 'hello'}, (response) => {});");
content::RenderProcessHost* main_frame_process =
active_web_contents()->GetPrimaryMainFrame()->GetProcess();
RenderProcessHostBadIpcMessageWaiter kill_waiter(main_frame_process);
auto interceptor = std::make_unique<ExtensionFrameHostInterceptor>(
active_web_contents()->GetPrimaryMainFrame());
interceptor->SetOpenChannelToExtensionMutator(
base::BindLambdaForTesting([this](mojom::ExternalConnectionInfo& info) {
EXPECT_EQ(MessagingEndpoint::Type::kUserScript,
info.source_endpoint.type);
EXPECT_EQ(active_extension_id(), info.source_endpoint.extension_id);
// Mutate the IPC payload.
info.target_id = spoofed_extension_id();
}));
EXPECT_EQ(bad_message::EMF_INVALID_EXTERNAL_EXTENSION_ID_FOR_USER_SCRIPT,
kill_waiter.Wait());
}
} // namespace extensions
|