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 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/safe_browsing/download_protection/download_protection_service.h"
#include <memory>
#include <optional>
#include <utility>
#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/download/chrome_download_manager_delegate.h"
#include "chrome/browser/download/download_core_service.h"
#include "chrome/browser/download/download_core_service_factory.h"
#include "chrome/browser/download/download_item_warning_data.h"
#include "chrome/browser/enterprise/connectors/connectors_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/safe_browsing/advanced_protection_status_manager.h"
#include "chrome/browser/safe_browsing/advanced_protection_status_manager_factory.h"
#include "chrome/browser/safe_browsing/download_protection/check_client_download_request.h"
#include "chrome/browser/safe_browsing/download_protection/check_file_system_access_write_request.h"
#include "chrome/browser/safe_browsing/download_protection/download_item_metadata.h"
#include "chrome/browser/safe_browsing/download_protection/download_protection_util.h"
#include "chrome/browser/safe_browsing/download_protection/download_request_maker.h"
#include "chrome/browser/safe_browsing/download_protection/download_url_sb_client.h"
#include "chrome/browser/safe_browsing/download_protection/ppapi_download_request.h"
#include "chrome/browser/safe_browsing/safe_browsing_metrics_collector_factory.h"
#include "chrome/browser/safe_browsing/safe_browsing_navigation_observer_manager_factory.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/safe_browsing/services_delegate.h"
#include "chrome/common/safe_browsing/binary_feature_extractor.h"
#include "chrome/common/safe_browsing/download_type_util.h"
#include "chrome/common/url_constants.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/download/public/common/download_item.h"
#include "components/enterprise/connectors/core/reporting_utils.h"
#include "components/google/core/common/google_util.h"
#include "components/prefs/pref_service.h"
#include "components/safe_browsing/content/browser/safe_browsing_navigation_observer_manager.h"
#include "components/safe_browsing/content/browser/web_ui/safe_browsing_ui.h"
#include "components/safe_browsing/core/common/features.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/safe_browsing/core/common/safebrowsing_switches.h"
#include "components/sessions/content/session_tab_helper.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_item_utils.h"
#include "content/public/browser/global_routing_id.h"
#include "content/public/browser/web_contents.h"
#include "net/base/url_util.h"
#include "net/cert/x509_util.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h"
#include "chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.h"
#endif
#if !BUILDFLAG(IS_ANDROID)
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "chrome/browser/safe_browsing/download_protection/download_feedback_service.h"
#endif
using content::BrowserThread;
using ReportThreatDetailsResult =
safe_browsing::PingManager::ReportThreatDetailsResult;
namespace safe_browsing {
namespace {
inline constexpr int kDownloadAttributionUserGestureLimit = 2;
inline constexpr int kDownloadAttributionUserGestureLimitForExtendedReporting =
5;
const int64_t kDownloadRequestTimeoutMs = 7000;
bool IsDownloadSecuritySensitive(safe_browsing::DownloadCheckResult result) {
using Result = safe_browsing::DownloadCheckResult;
switch (result) {
case Result::UNKNOWN:
case Result::DANGEROUS:
case Result::UNCOMMON:
case Result::DANGEROUS_HOST:
case Result::POTENTIALLY_UNWANTED:
case Result::DANGEROUS_ACCOUNT_COMPROMISE:
case Result::DEEP_SCANNED_FAILED:
return true;
case Result::SAFE:
case Result::ALLOWLISTED_BY_POLICY:
case Result::ASYNC_SCANNING:
case Result::ASYNC_LOCAL_PASSWORD_SCANNING:
case Result::BLOCKED_PASSWORD_PROTECTED:
case Result::BLOCKED_TOO_LARGE:
case Result::SENSITIVE_CONTENT_BLOCK:
case Result::SENSITIVE_CONTENT_WARNING:
case Result::DEEP_SCANNED_SAFE:
case Result::PROMPT_FOR_SCANNING:
case Result::PROMPT_FOR_LOCAL_PASSWORD_SCANNING:
case Result::BLOCKED_SCAN_FAILED:
case Result::IMMEDIATE_DEEP_SCAN:
return false;
}
NOTREACHED();
}
void MaybeLogSecuritySensitiveDownloadEvent(
content::BrowserContext* browser_context,
DownloadCheckResult result) {
if (browser_context) {
SafeBrowsingMetricsCollector* metrics_collector =
SafeBrowsingMetricsCollectorFactory::GetForProfile(
Profile::FromBrowserContext(browser_context));
if (metrics_collector && IsDownloadSecuritySensitive(result)) {
metrics_collector->AddSafeBrowsingEventToPref(
safe_browsing::SafeBrowsingMetricsCollector::EventType::
SECURITY_SENSITIVE_DOWNLOAD);
}
}
}
} // namespace
const void* const DownloadProtectionService::kDownloadProtectionDataKey =
&kDownloadProtectionDataKey;
DownloadProtectionService::DownloadProtectionService(
SafeBrowsingServiceImpl* sb_service,
std::unique_ptr<DownloadProtectionDelegate> delegate)
: sb_service_(sb_service),
delegate_(std::move(delegate)),
binary_feature_extractor_(new BinaryFeatureExtractor()),
download_request_timeout_ms_(kDownloadRequestTimeoutMs),
#if !BUILDFLAG(IS_ANDROID)
feedback_service_(new DownloadFeedbackService(
this,
base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::TaskPriority::BEST_EFFORT})
.get())),
#endif
weak_ptr_factory_(this) {
CHECK(delegate_);
if (sb_service) {
ui_manager_ = sb_service->ui_manager();
database_manager_ = sb_service->database_manager();
ParseManualBlocklistFlag();
}
}
DownloadProtectionService::DownloadProtectionService(
SafeBrowsingServiceImpl* sb_service)
: DownloadProtectionService(
sb_service,
DownloadProtectionDelegate::CreateForPlatform()) {}
DownloadProtectionService::~DownloadProtectionService() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
CancelPendingRequests();
}
void DownloadProtectionService::SetEnabled(bool enabled) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (enabled == enabled_) {
return;
}
enabled_ = enabled;
if (!enabled_) {
CancelPendingRequests();
}
}
void DownloadProtectionService::ParseManualBlocklistFlag() {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (!command_line->HasSwitch(
safe_browsing::switches::kSbManualDownloadBlocklist))
return;
std::string flag_val = command_line->GetSwitchValueASCII(
safe_browsing::switches::kSbManualDownloadBlocklist);
for (const std::string& hash_hex : base::SplitString(
flag_val, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
std::string bytes;
if (base::HexStringToString(hash_hex, &bytes) && bytes.size() == 32) {
manual_blocklist_hashes_.insert(std::move(bytes));
} else {
LOG(FATAL) << "Bad sha256 hex value '" << hash_hex << "' found in --"
<< safe_browsing::switches::kSbManualDownloadBlocklist;
}
}
}
bool DownloadProtectionService::IsHashManuallyBlocklisted(
const std::string& sha256_hash) const {
return manual_blocklist_hashes_.count(sha256_hash) > 0;
}
void DownloadProtectionService::CheckClientDownload(
download::DownloadItem* item,
CheckDownloadRepeatingCallback callback,
base::optional_ref<const std::string> password) {
auto request = std::make_unique<CheckClientDownloadRequest>(
item, std::move(callback), this, database_manager_,
binary_feature_extractor_, password);
CheckClientDownloadRequest* request_copy = request.get();
context_download_requests_[content::DownloadItemUtils::GetBrowserContext(
item)][request_copy] = std::move(request);
request_copy->Start();
}
bool DownloadProtectionService::MaybeCheckClientDownload(
download::DownloadItem* item,
CheckDownloadRepeatingCallback callback) {
auto settings = ShouldUploadBinaryForDeepScanning(item);
#if !BUILDFLAG(IS_ANDROID)
bool report_only_scan =
settings.has_value() &&
settings.value().block_until_verdict ==
enterprise_connectors::BlockUntilVerdict::kNoBlock;
if (settings.has_value() && !report_only_scan) {
// Since this branch implies that the CSD check is done through the deep
// scanning request and not with a consumer check, the pre-deep scanning
// DownloadCheckResult is considered UNKNOWN. This shouldn't trigger on
// report-only scans to avoid skipping the consumer check.
UploadForDeepScanning(
std::make_unique<DownloadItemMetadata>(item),
base::BindRepeating(
&DownloadProtectionService::MaybeCheckMetadataAfterDeepScanning,
weak_ptr_factory_.GetWeakPtr(), item, std::move(callback)),
DownloadItemWarningData::DeepScanTrigger::TRIGGER_POLICY,
DownloadCheckResult::UNKNOWN, std::move(settings.value()),
/*password=*/std::nullopt);
return true;
}
#else
CHECK(!settings.has_value());
#endif
if (delegate_->MayCheckClientDownload(item)) {
CheckClientDownload(item, std::move(callback), /*password=*/std::nullopt);
return true;
}
#if !BUILDFLAG(IS_ANDROID)
if (settings.has_value()) {
DCHECK(report_only_scan);
// Since this branch implies that CheckClientDownload was not called, the
// pre-deep scanning DownloadCheckResult is considered UNKNOWN.
UploadForDeepScanning(
std::make_unique<DownloadItemMetadata>(item), std::move(callback),
DownloadItemWarningData::DeepScanTrigger::TRIGGER_POLICY,
DownloadCheckResult::UNKNOWN, std::move(settings.value()),
/*password=*/std::nullopt);
return true;
}
#endif
return false;
}
void DownloadProtectionService::CancelChecksForDownload(
download::DownloadItem* item) {
if (!item) {
return;
}
content::BrowserContext* context =
content::DownloadItemUtils::GetBrowserContext(item);
for (auto it = context_download_requests_[context].begin();
it != context_download_requests_[context].end(); ++it) {
if (it->first->item() == item) {
context_download_requests_[context].erase(it);
break;
}
}
}
bool DownloadProtectionService::ShouldCheckDownloadUrl(
download::DownloadItem* item) {
return delegate_->ShouldCheckDownloadUrl(item);
}
void DownloadProtectionService::CheckDownloadUrl(
download::DownloadItem* item,
CheckDownloadCallback callback) {
DCHECK(!item->GetUrlChain().empty());
content::WebContents* web_contents =
content::DownloadItemUtils::GetWebContents(item);
// |web_contents| can be null in tests.
// Checks if this download is allowlisted by enterprise policy.
if (web_contents) {
Profile* profile =
Profile::FromBrowserContext(web_contents->GetBrowserContext());
if (profile &&
MatchesEnterpriseAllowlist(*profile->GetPrefs(), item->GetUrlChain())) {
// We don't return ALLOWLISTED_BY_POLICY yet, because future deep scanning
// operations may indicate the file is unsafe.
std::move(callback).Run(DownloadCheckResult::SAFE);
return;
}
}
scoped_refptr<DownloadUrlSBClient> client(new DownloadUrlSBClient(
item, this, std::move(callback), ui_manager_, database_manager_));
// The client will release itself once it is done.
client->StartCheck();
}
bool DownloadProtectionService::IsSupportedDownload(
download::DownloadItem& item,
const base::FilePath& target_path) const {
return delegate_->IsSupportedDownload(item, target_path) !=
MayCheckDownloadResult::kMayNotCheckDownload;
}
void DownloadProtectionService::CheckPPAPIDownloadRequest(
const GURL& requestor_url,
content::RenderFrameHost* initiating_frame,
const base::FilePath& default_file_path,
const std::vector<base::FilePath::StringType>& alternate_extensions,
Profile* profile,
CheckDownloadCallback callback) {
DVLOG(1) << __func__ << " url:" << requestor_url
<< " default_file_path:" << default_file_path.value();
if (profile &&
MatchesEnterpriseAllowlist(
*profile->GetPrefs(),
{requestor_url,
(initiating_frame ? initiating_frame->GetLastCommittedURL()
: GURL())})) {
std::move(callback).Run(DownloadCheckResult::ALLOWLISTED_BY_POLICY);
return;
}
std::unique_ptr<PPAPIDownloadRequest> request(new PPAPIDownloadRequest(
requestor_url, initiating_frame, default_file_path, alternate_extensions,
profile, std::move(callback), this, database_manager_));
PPAPIDownloadRequest* request_copy = request.get();
auto insertion_result = ppapi_download_requests_.insert(
std::make_pair(request_copy, std::move(request)));
DCHECK(insertion_result.second);
insertion_result.first->second->Start();
}
void DownloadProtectionService::CheckFileSystemAccessWrite(
std::unique_ptr<content::FileSystemAccessWriteItem> item,
CheckDownloadCallback callback) {
if (!delegate_->MayCheckFileSystemAccessWrite(item.get())) {
std::move(callback).Run(DownloadCheckResult::UNKNOWN);
return;
}
content::BrowserContext* browser_context = item->browser_context;
auto request = std::make_unique<CheckFileSystemAccessWriteRequest>(
std::move(item), std::move(callback), this, database_manager_,
binary_feature_extractor_);
CheckClientDownloadRequestBase* request_copy = request.get();
context_download_requests_[browser_context][request_copy] =
std::move(request);
request_copy->Start();
}
base::CallbackListSubscription
DownloadProtectionService::RegisterClientDownloadRequestCallback(
const ClientDownloadRequestCallback& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return client_download_request_callbacks_.Add(callback);
}
base::CallbackListSubscription
DownloadProtectionService::RegisterFileSystemAccessWriteRequestCallback(
const FileSystemAccessWriteRequestCallback& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return file_system_access_write_request_callbacks_.Add(callback);
}
base::CallbackListSubscription
DownloadProtectionService::RegisterPPAPIDownloadRequestCallback(
const PPAPIDownloadRequestCallback& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return ppapi_download_request_callbacks_.Add(callback);
}
void DownloadProtectionService::CancelPendingRequests() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// It is sufficient to delete the list of CheckClientDownloadRequests.
context_download_requests_.clear();
// It is sufficient to delete the list of PPAPI download requests.
ppapi_download_requests_.clear();
}
void DownloadProtectionService::RequestFinished(
CheckClientDownloadRequestBase* request,
content::BrowserContext* browser_context,
DownloadCheckResult result) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
MaybeLogSecuritySensitiveDownloadEvent(browser_context, result);
DCHECK(context_download_requests_.contains(browser_context));
DCHECK(context_download_requests_[browser_context].contains(request));
context_download_requests_[browser_context].erase(request);
}
void DownloadProtectionService::PPAPIDownloadCheckRequestFinished(
PPAPIDownloadRequest* request) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
auto it = ppapi_download_requests_.find(request);
CHECK(it != ppapi_download_requests_.end());
ppapi_download_requests_.erase(it);
}
void DownloadProtectionService::ShowDetailsForDownload(
const download::DownloadItem* item,
content::PageNavigator* navigator) {
GURL learn_more_url(chrome::kDownloadScanningLearnMoreURL);
learn_more_url = google_util::AppendGoogleLocaleParam(
learn_more_url, g_browser_process->GetApplicationLocale());
learn_more_url = net::AppendQueryParameter(
learn_more_url, "ctx",
base::NumberToString(static_cast<int>(item->GetDangerType())));
Profile* profile = Profile::FromBrowserContext(
content::DownloadItemUtils::GetBrowserContext(item));
if (profile &&
AdvancedProtectionStatusManagerFactory::GetForProfile(profile)
->IsUnderAdvancedProtection() &&
item->GetDangerType() ==
download::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT) {
learn_more_url = GURL(chrome::kAdvancedProtectionDownloadLearnMoreURL);
learn_more_url = google_util::AppendGoogleLocaleParam(
learn_more_url, g_browser_process->GetApplicationLocale());
}
navigator->OpenURL(
content::OpenURLParams(learn_more_url, content::Referrer(),
WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui::PAGE_TRANSITION_LINK, false),
/*navigation_handle_callback=*/{});
}
double DownloadProtectionService::allowlist_sample_rate() const {
return allowlist_sample_rate_.value_or(
delegate()->GetAllowlistedDownloadSampleRate());
}
// static
void DownloadProtectionService::SetDownloadProtectionData(
download::DownloadItem* item,
const std::string& token,
const ClientDownloadResponse::Verdict& verdict,
const ClientDownloadResponse::TailoredVerdict& tailored_verdict) {
if (item) {
item->SetUserData(kDownloadProtectionDataKey,
std::make_unique<DownloadProtectionData>(
token, verdict, tailored_verdict));
}
}
// static
std::string DownloadProtectionService::GetDownloadPingToken(
const download::DownloadItem* item) {
base::SupportsUserData::Data* protection_data =
item->GetUserData(kDownloadProtectionDataKey);
if (protection_data)
return static_cast<DownloadProtectionData*>(protection_data)
->token_string();
else
return std::string();
}
// static
bool DownloadProtectionService::HasDownloadProtectionVerdict(
const download::DownloadItem* item) {
return item->GetUserData(kDownloadProtectionDataKey) != nullptr;
}
// static
ClientDownloadResponse::Verdict
DownloadProtectionService::GetDownloadProtectionVerdict(
const download::DownloadItem* item) {
base::SupportsUserData::Data* protection_data =
item->GetUserData(kDownloadProtectionDataKey);
if (protection_data)
return static_cast<DownloadProtectionData*>(protection_data)->verdict();
else
return ClientDownloadResponse::SAFE;
}
// static
ClientDownloadResponse::TailoredVerdict
DownloadProtectionService::GetDownloadProtectionTailoredVerdict(
const download::DownloadItem* item) {
base::SupportsUserData::Data* protection_data =
item->GetUserData(kDownloadProtectionDataKey);
if (protection_data)
return static_cast<DownloadProtectionData*>(protection_data)
->tailored_verdict();
else
return ClientDownloadResponse::TailoredVerdict();
}
void DownloadProtectionService::MaybeSendDangerousDownloadOpenedReport(
download::DownloadItem* item,
bool show_download_in_folder) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
content::BrowserContext* browser_context =
content::DownloadItemUtils::GetBrowserContext(item);
Profile* profile = Profile::FromBrowserContext(browser_context);
if (!profile || !IsSafeBrowsingEnabled(*profile->GetPrefs()))
return;
// When users are in incognito mode, no report will be sent and no
// |onDangerousDownloadOpened| extension API will be called.
if (browser_context->IsOffTheRecord())
return;
// Only report downloads that are known to be dangerous or was dangerous but
// was validated by the user.
if (!item->IsDangerous() &&
item->GetDangerType() != download::DOWNLOAD_DANGER_TYPE_USER_VALIDATED)
return;
OnDangerousDownloadOpened(item, profile);
if (sb_service_) {
// If the download is opened, it indicates the user has bypassed the warning
// and decided to proceed, so setting did_proceed to true.
sb_service_->SendDownloadReport(
item, ClientSafeBrowsingReportRequest::DANGEROUS_DOWNLOAD_OPENED,
/*did_proceed=*/true, show_download_in_folder);
}
}
void DownloadProtectionService::ReportDelayedBypassEvent(
download::DownloadItem* download,
download::DownloadDangerType danger_type) {
download_protection_observer_.ReportDelayedBypassEvent(download, danger_type);
}
void DownloadProtectionService::AddReferrerChainToPPAPIClientDownloadRequest(
content::WebContents* web_contents,
const GURL& initiating_frame_url,
const content::GlobalRenderFrameHostId& initiating_outermost_main_frame_id,
const GURL& initiating_main_frame_url,
SessionID tab_id,
bool has_user_gesture,
ClientDownloadRequest* out_request) {
// If web_contents is null, return immediately. This could happen in tests.
if (!web_contents) {
return;
}
SafeBrowsingNavigationObserverManager::AttributionResult result =
GetNavigationObserverManager(web_contents)
->IdentifyReferrerChainByHostingPage(
initiating_frame_url, initiating_main_frame_url,
initiating_outermost_main_frame_id, tab_id, has_user_gesture,
GetDownloadAttributionUserGestureLimit(),
out_request->mutable_referrer_chain());
UMA_HISTOGRAM_COUNTS_100(
"SafeBrowsing.ReferrerURLChainSize.PPAPIDownloadAttribution",
out_request->referrer_chain_size());
UMA_HISTOGRAM_ENUMERATION(
"SafeBrowsing.ReferrerAttributionResult.PPAPIDownloadAttribution", result,
SafeBrowsingNavigationObserverManager::ATTRIBUTION_FAILURE_TYPE_MAX);
}
void DownloadProtectionService::OnDangerousDownloadOpened(
download::DownloadItem* item,
Profile* profile) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
std::string raw_digest_sha256 = item->GetHash();
auto* router =
extensions::SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile);
if (!router)
return;
auto* scan_result = static_cast<enterprise_connectors::ScanResult*>(
item->GetUserData(enterprise_connectors::ScanResult::kKey));
google::protobuf::RepeatedPtrField<safe_browsing::ReferrerChainEntry>
referrer_chain;
if (base::FeatureList::IsEnabled(safe_browsing::kEnhancedFieldsForSecOps)) {
referrer_chain =
safe_browsing::GetOrIdentifyReferrerChainForEnterprise(*item);
}
// A download with a verdict of "sensitive data warning" can be opened and
// |item->IsDangerous()| will return |true| for it but the reported event
// should be a "sensitive file bypass" event rather than a "dangerous file
// bypass" event.
if (scan_result &&
item->GetDangerType() ==
download::DOWNLOAD_DANGER_TYPE_SENSITIVE_CONTENT_WARNING) {
for (const auto& metadata : scan_result->file_metadata) {
for (const auto& result : metadata.scan_response.results()) {
if (result.tag() != "dlp")
continue;
router->OnAnalysisConnectorWarningBypassed(
item->GetURL(), item->GetTabUrl(), "", "", metadata.filename,
metadata.sha256, metadata.mime_type,
extensions::SafeBrowsingPrivateEventRouter::kTriggerFileDownload,
metadata.scan_response.request_token(), "",
DeepScanAccessPoint::DOWNLOAD, referrer_chain, result,
metadata.size,
/*user_justification=*/std::nullopt);
// There won't be multiple DLP verdicts in the same response, so no need
// to keep iterating.
break;
}
}
} else if (scan_result) {
for (const auto& metadata : scan_result->file_metadata) {
router->OnDangerousDownloadOpened(
item->GetURL(), item->GetTabUrl(), metadata.filename, metadata.sha256,
metadata.mime_type, metadata.scan_response.request_token(),
item->GetDangerType(), metadata.size, referrer_chain);
}
} else {
router->OnDangerousDownloadOpened(
item->GetURL(), item->GetTabUrl(),
item->GetTargetFilePath().AsUTF8Unsafe(),
base::HexEncode(raw_digest_sha256), item->GetMimeType(), /*scan_id*/ "",
item->GetDangerType(), item->GetTotalBytes(), referrer_chain);
}
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
}
const GURL& DownloadProtectionService::GetDownloadRequestUrl() const {
return delegate_->GetDownloadRequestUrl();
}
base::TimeDelta DownloadProtectionService::GetDownloadRequestTimeout() const {
return base::Milliseconds(download_request_timeout_ms_);
}
bool DownloadProtectionService::MaybeBeginFeedbackForDownload(
Profile* profile,
download::DownloadItem* download,
const std::string& ping_request,
const std::string& ping_response) {
#if !BUILDFLAG(IS_ANDROID)
PrefService* prefs = profile->GetPrefs();
bool is_extended_reporting = IsExtendedReportingEnabled(*prefs);
if (!profile->IsOffTheRecord() && is_extended_reporting) {
feedback_service_->BeginFeedbackForDownload(profile, download, ping_request,
ping_response);
return true;
}
#endif
return false;
}
#if !BUILDFLAG(IS_ANDROID)
void DownloadProtectionService::UploadForDeepScanning(
std::unique_ptr<DeepScanningMetadata> metadata,
CheckDownloadRepeatingCallback callback,
DownloadItemWarningData::DeepScanTrigger trigger,
DownloadCheckResult download_check_result,
enterprise_connectors::AnalysisSettings analysis_settings,
base::optional_ref<const std::string> password) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
content::BrowserContext* browser_context = metadata->GetBrowserContext();
auto request = std::make_unique<DeepScanningRequest>(
std::move(metadata), trigger, download_check_result, callback, this,
std::move(analysis_settings), password);
DeepScanningRequest* request_raw = request.get();
auto insertion_result = deep_scanning_requests_.insert(
std::make_pair(request_raw, std::move(request)));
DCHECK(insertion_result.second);
insertion_result.first->second->Start();
Profile* profile = Profile::FromBrowserContext(browser_context);
SafeBrowsingMetricsCollector* metrics_collector =
SafeBrowsingMetricsCollectorFactory::GetForProfile(profile);
if (metrics_collector) {
metrics_collector->AddSafeBrowsingEventToPref(
safe_browsing::SafeBrowsingMetricsCollector::EventType::
DOWNLOAD_DEEP_SCAN);
}
}
// static
void DownloadProtectionService::UploadForConsumerDeepScanning(
download::DownloadItem* item,
DownloadItemWarningData::DeepScanTrigger trigger,
base::optional_ref<const std::string> password) {
if (!item) {
return;
}
safe_browsing::SafeBrowsingService* sb_service =
g_browser_process->safe_browsing_service();
if (!sb_service) {
return;
}
safe_browsing::DownloadProtectionService* protection_service =
sb_service->download_protection_service();
if (!protection_service) {
return;
}
DownloadCoreService* download_core_service =
DownloadCoreServiceFactory::GetForBrowserContext(
content::DownloadItemUtils::GetBrowserContext(item));
DCHECK(download_core_service);
ChromeDownloadManagerDelegate* delegate =
download_core_service->GetDownloadManagerDelegate();
DCHECK(delegate);
// Create an analysis settings object for UploadForDeepScanning().
// Make sure it specifies a cloud analysis is required and does not
// specify a DM token, which is what triggers an APP scan.
enterprise_connectors::AnalysisSettings settings;
settings.cloud_or_local_settings =
enterprise_connectors::CloudOrLocalAnalysisSettings(
enterprise_connectors::CloudAnalysisSettings());
settings.tags = {{"malware", enterprise_connectors::TagSettings()}};
protection_service->UploadForDeepScanning(
std::make_unique<DownloadItemMetadata>(item),
base::BindRepeating(
&ChromeDownloadManagerDelegate::CheckClientDownloadDone,
delegate->GetWeakPtr(), item->GetId()),
trigger, safe_browsing::DownloadCheckResult::UNKNOWN, std::move(settings),
password);
}
// static
void DownloadProtectionService::CheckDownloadWithLocalDecryption(
download::DownloadItem* item,
base::optional_ref<const std::string> password) {
if (!item) {
return;
}
safe_browsing::SafeBrowsingService* sb_service =
g_browser_process->safe_browsing_service();
if (!sb_service) {
return;
}
safe_browsing::DownloadProtectionService* protection_service =
sb_service->download_protection_service();
if (!protection_service) {
return;
}
DownloadCoreService* download_core_service =
DownloadCoreServiceFactory::GetForBrowserContext(
content::DownloadItemUtils::GetBrowserContext(item));
DCHECK(download_core_service);
ChromeDownloadManagerDelegate* delegate =
download_core_service->GetDownloadManagerDelegate();
DCHECK(delegate);
DownloadItemWarningData::SetHasShownLocalDecryptionPrompt(item, true);
delegate->CheckClientDownloadDone(
item->GetId(),
safe_browsing::DownloadCheckResult::ASYNC_LOCAL_PASSWORD_SCANNING);
protection_service->CheckClientDownload(
item,
base::BindRepeating(
&ChromeDownloadManagerDelegate::CheckClientDownloadDone,
delegate->GetWeakPtr(), item->GetId()),
password);
}
void DownloadProtectionService::UploadSavePackageForDeepScanning(
download::DownloadItem* item,
base::flat_map<base::FilePath, base::FilePath> save_package_files,
CheckDownloadRepeatingCallback callback,
enterprise_connectors::AnalysisSettings analysis_settings) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
auto request = std::make_unique<DeepScanningRequest>(
std::make_unique<DownloadItemMetadata>(item),
DownloadCheckResult::UNKNOWN, callback, this,
std::move(analysis_settings), std::move(save_package_files));
DeepScanningRequest* request_raw = request.get();
auto insertion_result = deep_scanning_requests_.insert(
std::make_pair(request_raw, std::move(request)));
DCHECK(insertion_result.second);
insertion_result.first->second->Start();
}
std::vector<DeepScanningRequest*>
DownloadProtectionService::GetDeepScanningRequests() {
std::vector<DeepScanningRequest*> requests;
for (const auto& pair : deep_scanning_requests_) {
requests.push_back(pair.first);
}
return requests;
}
#endif // !BUILDFLAG(IS_ANDROID)
scoped_refptr<network::SharedURLLoaderFactory>
DownloadProtectionService::GetURLLoaderFactory(
content::BrowserContext* browser_context) {
return sb_service_->GetURLLoaderFactory(
Profile::FromBrowserContext(browser_context));
}
void DownloadProtectionService::RemovePendingDownloadRequests(
content::BrowserContext* browser_context) {
context_download_requests_.erase(browser_context);
}
// static
int DownloadProtectionService::GetDownloadAttributionUserGestureLimit(
download::DownloadItem* item) {
if (!item) {
return kDownloadAttributionUserGestureLimit;
}
content::WebContents* web_contents =
content::DownloadItemUtils::GetWebContents(item);
if (!web_contents) {
return kDownloadAttributionUserGestureLimit;
}
if (Profile* profile =
Profile::FromBrowserContext(web_contents->GetBrowserContext());
profile && profile->GetPrefs() &&
IsExtendedReportingEnabled(*profile->GetPrefs())) {
return kDownloadAttributionUserGestureLimitForExtendedReporting;
}
return kDownloadAttributionUserGestureLimit;
}
#if !BUILDFLAG(IS_ANDROID)
void DownloadProtectionService::RequestFinished(DeepScanningRequest* request) {
auto it = deep_scanning_requests_.find(request);
CHECK(it != deep_scanning_requests_.end());
deep_scanning_requests_.erase(it);
}
BinaryUploadService* DownloadProtectionService::GetBinaryUploadService(
Profile* profile,
const enterprise_connectors::AnalysisSettings& settings) {
return BinaryUploadService::GetForProfile(profile, settings);
}
#endif
SafeBrowsingNavigationObserverManager*
DownloadProtectionService::GetNavigationObserverManager(
content::WebContents* web_contents) {
return SafeBrowsingNavigationObserverManagerFactory::GetForBrowserContext(
web_contents->GetBrowserContext());
}
void DownloadProtectionService::MaybeCheckMetadataAfterDeepScanning(
download::DownloadItem* item,
CheckDownloadRepeatingCallback callback,
DownloadCheckResult result) {
if (result == DownloadCheckResult::UNKNOWN) {
CheckClientDownload(item, callback, /*password=*/std::nullopt);
} else {
std::move(callback).Run(result);
}
}
} // namespace safe_browsing
|