1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "extensions/browser/sandboxed_unpacker.h"
9 #include "base/base64.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/files/file_util.h"
13 #include "base/files/file_util_proxy.h"
14 #include "base/files/scoped_file.h"
15 #include "base/json/json_string_value_serializer.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/metrics/histogram.h"
18 #include "base/numerics/safe_conversions.h"
19 #include "base/path_service.h"
20 #include "base/sequenced_task_runner.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/threading/sequenced_worker_pool.h"
24 #include "components/crx_file/constants.h"
25 #include "components/crx_file/crx_file.h"
26 #include "components/crx_file/id_util.h"
27 #include "content/public/browser/browser_thread.h"
28 #include "content/public/browser/utility_process_host.h"
29 #include "content/public/common/common_param_traits.h"
30 #include "crypto/secure_hash.h"
31 #include "crypto/sha2.h"
32 #include "crypto/signature_verifier.h"
33 #include "extensions/common/constants.h"
34 #include "extensions/common/extension.h"
35 #include "extensions/common/extension_l10n_util.h"
36 #include "extensions/common/extension_utility_messages.h"
37 #include "extensions/common/extensions_client.h"
38 #include "extensions/common/file_util.h"
39 #include "extensions/common/manifest_constants.h"
40 #include "extensions/common/manifest_handlers/icons_handler.h"
41 #include "extensions/common/switches.h"
42 #include "grit/extensions_strings.h"
43 #include "third_party/skia/include/core/SkBitmap.h"
44 #include "ui/base/l10n/l10n_util.h"
45 #include "ui/gfx/codec/png_codec.h"
47 using base::ASCIIToUTF16
;
48 using content::BrowserThread
;
49 using content::UtilityProcessHost
;
50 using crx_file::CrxFile
;
52 // The following macro makes histograms that record the length of paths
53 // in this file much easier to read.
54 // Windows has a short max path length. If the path length to a
55 // file being unpacked from a CRX exceeds the max length, we might
56 // fail to install. To see if this is happening, see how long the
57 // path to the temp unpack directory is. See crbug.com/69693 .
58 #define PATH_LENGTH_HISTOGRAM(name, path) \
59 UMA_HISTOGRAM_CUSTOM_COUNTS(name, path.value().length(), 0, 500, 100)
61 // Record a rate (kB per second) at which extensions are unpacked.
62 // Range from 1kB/s to 100mB/s.
63 #define UNPACK_RATE_HISTOGRAM(name, rate) \
64 UMA_HISTOGRAM_CUSTOM_COUNTS(name, rate, 1, 100000, 100);
66 namespace extensions
{
69 void RecordSuccessfulUnpackTimeHistograms(const base::FilePath
& crx_path
,
70 const base::TimeDelta unpack_time
) {
71 const int64 kBytesPerKb
= 1024;
72 const int64 kBytesPerMb
= 1024 * 1024;
74 UMA_HISTOGRAM_TIMES("Extensions.SandboxUnpackSuccessTime", unpack_time
);
76 // To get a sense of how CRX size impacts unpack time, record unpack
77 // time for several increments of CRX size.
79 if (!base::GetFileSize(crx_path
, &crx_file_size
)) {
80 UMA_HISTOGRAM_COUNTS("Extensions.SandboxUnpackSuccessCantGetCrxSize", 1);
84 // Cast is safe as long as the number of bytes in the CRX is less than
86 int crx_file_size_kb
= static_cast<int>(crx_file_size
/ kBytesPerKb
);
87 UMA_HISTOGRAM_COUNTS("Extensions.SandboxUnpackSuccessCrxSize",
90 // We have time in seconds and file size in bytes. We want the rate bytes are
93 static_cast<double>(crx_file_size
) / static_cast<double>(kBytesPerKb
);
94 int unpack_rate_kb_per_s
=
95 static_cast<int>(file_size_kb
/ unpack_time
.InSecondsF());
96 UNPACK_RATE_HISTOGRAM("Extensions.SandboxUnpackRate", unpack_rate_kb_per_s
);
98 if (crx_file_size
< 50.0 * kBytesPerKb
) {
99 UNPACK_RATE_HISTOGRAM("Extensions.SandboxUnpackRateUnder50kB",
100 unpack_rate_kb_per_s
);
102 } else if (crx_file_size
< 1 * kBytesPerMb
) {
103 UNPACK_RATE_HISTOGRAM("Extensions.SandboxUnpackRate50kBTo1mB",
104 unpack_rate_kb_per_s
);
106 } else if (crx_file_size
< 2 * kBytesPerMb
) {
107 UNPACK_RATE_HISTOGRAM("Extensions.SandboxUnpackRate1To2mB",
108 unpack_rate_kb_per_s
);
110 } else if (crx_file_size
< 5 * kBytesPerMb
) {
111 UNPACK_RATE_HISTOGRAM("Extensions.SandboxUnpackRate2To5mB",
112 unpack_rate_kb_per_s
);
114 } else if (crx_file_size
< 10 * kBytesPerMb
) {
115 UNPACK_RATE_HISTOGRAM("Extensions.SandboxUnpackRate5To10mB",
116 unpack_rate_kb_per_s
);
119 UNPACK_RATE_HISTOGRAM("Extensions.SandboxUnpackRateOver10mB",
120 unpack_rate_kb_per_s
);
124 // Work horse for FindWritableTempLocation. Creates a temp file in the folder
125 // and uses NormalizeFilePath to check if the path is junction free.
126 bool VerifyJunctionFreeLocation(base::FilePath
* temp_dir
) {
127 if (temp_dir
->empty())
130 base::FilePath temp_file
;
131 if (!base::CreateTemporaryFileInDir(*temp_dir
, &temp_file
)) {
132 LOG(ERROR
) << temp_dir
->value() << " is not writable";
135 // NormalizeFilePath requires a non-empty file, so write some data.
136 // If you change the exit points of this function please make sure all
137 // exit points delete this temp file!
138 if (base::WriteFile(temp_file
, ".", 1) != 1)
141 base::FilePath normalized_temp_file
;
142 bool normalized
= base::NormalizeFilePath(temp_file
, &normalized_temp_file
);
144 // If |temp_file| contains a link, the sandbox will block al file system
145 // operations, and the install will fail.
146 LOG(ERROR
) << temp_dir
->value() << " seem to be on remote drive.";
148 *temp_dir
= normalized_temp_file
.DirName();
150 // Clean up the temp file.
151 base::DeleteFile(temp_file
, false);
156 // This function tries to find a location for unpacking the extension archive
157 // that is writable and does not lie on a shared drive so that the sandboxed
158 // unpacking process can write there. If no such location exists we can not
159 // proceed and should fail.
160 // The result will be written to |temp_dir|. The function will write to this
161 // parameter even if it returns false.
162 bool FindWritableTempLocation(const base::FilePath
& extensions_dir
,
163 base::FilePath
* temp_dir
) {
164 // On ChromeOS, we will only attempt to unpack extension in cryptohome (profile)
165 // directory to provide additional security/privacy and speed up the rest of
166 // the extension install process.
167 #if !defined(OS_CHROMEOS)
168 PathService::Get(base::DIR_TEMP
, temp_dir
);
169 if (VerifyJunctionFreeLocation(temp_dir
))
173 *temp_dir
= file_util::GetInstallTempDir(extensions_dir
);
174 if (VerifyJunctionFreeLocation(temp_dir
))
176 // Neither paths is link free chances are good installation will fail.
177 LOG(ERROR
) << "Both the %TEMP% folder and the profile seem to be on "
178 << "remote drives or read-only. Installation can not complete!";
182 // Read the decoded images back from the file we saved them to.
183 // |extension_path| is the path to the extension we unpacked that wrote the
184 // data. Returns true on success.
185 bool ReadImagesFromFile(const base::FilePath
& extension_path
,
186 DecodedImages
* images
) {
187 base::FilePath path
= extension_path
.AppendASCII(kDecodedImagesFilename
);
188 std::string file_str
;
189 if (!base::ReadFileToString(path
, &file_str
))
192 IPC::Message
pickle(file_str
.data(), file_str
.size());
193 PickleIterator
iter(pickle
);
194 return IPC::ReadParam(&pickle
, &iter
, images
);
197 // Read the decoded message catalogs back from the file we saved them to.
198 // |extension_path| is the path to the extension we unpacked that wrote the
199 // data. Returns true on success.
200 bool ReadMessageCatalogsFromFile(const base::FilePath
& extension_path
,
201 base::DictionaryValue
* catalogs
) {
202 base::FilePath path
=
203 extension_path
.AppendASCII(kDecodedMessageCatalogsFilename
);
204 std::string file_str
;
205 if (!base::ReadFileToString(path
, &file_str
))
208 IPC::Message
pickle(file_str
.data(), file_str
.size());
209 PickleIterator
iter(pickle
);
210 return IPC::ReadParam(&pickle
, &iter
, catalogs
);
215 SandboxedUnpacker::SandboxedUnpacker(
216 const CRXFileInfo
& file
,
217 Manifest::Location location
,
219 const base::FilePath
& extensions_dir
,
220 const scoped_refptr
<base::SequencedTaskRunner
>& unpacker_io_task_runner
,
221 SandboxedUnpackerClient
* client
)
222 : crx_path_(file
.path
),
223 package_hash_(file
.expected_hash
),
224 check_crx_hash_(false),
226 extensions_dir_(extensions_dir
),
227 got_response_(false),
229 creation_flags_(creation_flags
),
230 unpacker_io_task_runner_(unpacker_io_task_runner
) {
231 if (!package_hash_
.empty()) {
232 check_crx_hash_
= base::CommandLine::ForCurrentProcess()->HasSwitch(
233 extensions::switches::kEnableCrxHashCheck
);
237 bool SandboxedUnpacker::CreateTempDirectory() {
238 CHECK(unpacker_io_task_runner_
->RunsTasksOnCurrentThread());
240 base::FilePath temp_dir
;
241 if (!FindWritableTempLocation(extensions_dir_
, &temp_dir
)) {
242 ReportFailure(COULD_NOT_GET_TEMP_DIRECTORY
,
243 l10n_util::GetStringFUTF16(
244 IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
245 ASCIIToUTF16("COULD_NOT_GET_TEMP_DIRECTORY")));
249 if (!temp_dir_
.CreateUniqueTempDirUnderPath(temp_dir
)) {
250 ReportFailure(COULD_NOT_CREATE_TEMP_DIRECTORY
,
251 l10n_util::GetStringFUTF16(
252 IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
253 ASCIIToUTF16("COULD_NOT_CREATE_TEMP_DIRECTORY")));
260 void SandboxedUnpacker::Start() {
261 // We assume that we are started on the thread that the client wants us to do
263 CHECK(unpacker_io_task_runner_
->RunsTasksOnCurrentThread());
265 unpack_start_time_
= base::TimeTicks::Now();
267 PATH_LENGTH_HISTOGRAM("Extensions.SandboxUnpackInitialCrxPathLength",
269 if (!CreateTempDirectory())
270 return; // ReportFailure() already called.
272 // Initialize the path that will eventually contain the unpacked extension.
273 extension_root_
= temp_dir_
.path().AppendASCII(kTempExtensionName
);
274 PATH_LENGTH_HISTOGRAM("Extensions.SandboxUnpackUnpackedCrxPathLength",
277 // Extract the public key and validate the package.
278 if (!ValidateSignature())
279 return; // ValidateSignature() already reported the error.
281 // Copy the crx file into our working directory.
282 base::FilePath temp_crx_path
= temp_dir_
.path().Append(crx_path_
.BaseName());
283 PATH_LENGTH_HISTOGRAM("Extensions.SandboxUnpackTempCrxPathLength",
286 if (!base::CopyFile(crx_path_
, temp_crx_path
)) {
287 // Failed to copy extension file to temporary directory.
289 FAILED_TO_COPY_EXTENSION_FILE_TO_TEMP_DIRECTORY
,
290 l10n_util::GetStringFUTF16(
291 IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
292 ASCIIToUTF16("FAILED_TO_COPY_EXTENSION_FILE_TO_TEMP_DIRECTORY")));
296 // The utility process will have access to the directory passed to
297 // SandboxedUnpacker. That directory should not contain a symlink or NTFS
298 // reparse point. When the path is used, following the link/reparse point
299 // will cause file system access outside the sandbox path, and the sandbox
300 // will deny the operation.
301 base::FilePath link_free_crx_path
;
302 if (!base::NormalizeFilePath(temp_crx_path
, &link_free_crx_path
)) {
303 LOG(ERROR
) << "Could not get the normalized path of "
304 << temp_crx_path
.value();
305 ReportFailure(COULD_NOT_GET_SANDBOX_FRIENDLY_PATH
,
306 l10n_util::GetStringUTF16(IDS_EXTENSION_UNPACK_FAILED
));
309 PATH_LENGTH_HISTOGRAM("Extensions.SandboxUnpackLinkFreeCrxPathLength",
312 BrowserThread::PostTask(BrowserThread::IO
, FROM_HERE
,
313 base::Bind(&SandboxedUnpacker::StartProcessOnIOThread
,
314 this, link_free_crx_path
));
317 SandboxedUnpacker::~SandboxedUnpacker() {
320 bool SandboxedUnpacker::OnMessageReceived(const IPC::Message
& message
) {
322 IPC_BEGIN_MESSAGE_MAP(SandboxedUnpacker
, message
)
323 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_UnpackExtension_Succeeded
,
324 OnUnpackExtensionSucceeded
)
325 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_UnpackExtension_Failed
,
326 OnUnpackExtensionFailed
)
327 IPC_MESSAGE_UNHANDLED(handled
= false)
328 IPC_END_MESSAGE_MAP()
332 void SandboxedUnpacker::OnProcessCrashed(int exit_code
) {
333 // Don't report crashes if they happen after we got a response.
337 // Utility process crashed while trying to install.
339 UTILITY_PROCESS_CRASHED_WHILE_TRYING_TO_INSTALL
,
340 l10n_util::GetStringFUTF16(
341 IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
342 ASCIIToUTF16("UTILITY_PROCESS_CRASHED_WHILE_TRYING_TO_INSTALL")) +
344 l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALL_PROCESS_CRASHED
));
347 void SandboxedUnpacker::StartProcessOnIOThread(
348 const base::FilePath
& temp_crx_path
) {
349 UtilityProcessHost
* host
=
350 UtilityProcessHost::Create(this, unpacker_io_task_runner_
.get());
351 // Grant the subprocess access to the entire subdir the extension file is
352 // in, so that it can unpack to that dir.
353 host
->SetExposedDir(temp_crx_path
.DirName());
354 host
->Send(new ChromeUtilityMsg_UnpackExtension(temp_crx_path
, extension_id_
,
355 location_
, creation_flags_
));
358 void SandboxedUnpacker::OnUnpackExtensionSucceeded(
359 const base::DictionaryValue
& manifest
) {
360 CHECK(unpacker_io_task_runner_
->RunsTasksOnCurrentThread());
361 got_response_
= true;
363 scoped_ptr
<base::DictionaryValue
> final_manifest(
364 RewriteManifestFile(manifest
));
368 // Create an extension object that refers to the temporary location the
369 // extension was unpacked to. We use this until the extension is finally
370 // installed. For example, the install UI shows images from inside the
373 // Localize manifest now, so confirm UI gets correct extension name.
375 // TODO(rdevlin.cronin): Continue removing std::string errors and replacing
376 // with base::string16
377 std::string utf8_error
;
378 if (!extension_l10n_util::LocalizeExtension(
379 extension_root_
, final_manifest
.get(), &utf8_error
)) {
381 COULD_NOT_LOCALIZE_EXTENSION
,
382 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_ERROR_MESSAGE
,
383 base::UTF8ToUTF16(utf8_error
)));
388 Extension::Create(extension_root_
, location_
, *final_manifest
,
389 Extension::REQUIRE_KEY
| creation_flags_
, &utf8_error
);
391 if (!extension_
.get()) {
392 ReportFailure(INVALID_MANIFEST
,
393 ASCIIToUTF16("Manifest is invalid: " + utf8_error
));
397 SkBitmap install_icon
;
398 if (!RewriteImageFiles(&install_icon
))
401 if (!RewriteCatalogFiles())
404 ReportSuccess(manifest
, install_icon
);
407 void SandboxedUnpacker::OnUnpackExtensionFailed(const base::string16
& error
) {
408 CHECK(unpacker_io_task_runner_
->RunsTasksOnCurrentThread());
409 got_response_
= true;
411 UNPACKER_CLIENT_FAILED
,
412 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_ERROR_MESSAGE
, error
));
415 static size_t ReadAndHash(void* ptr
,
419 scoped_ptr
<crypto::SecureHash
>& hash
) {
420 size_t len
= fread(ptr
, size
, nmemb
, stream
);
421 if (len
> 0 && hash
) {
422 hash
->Update(ptr
, len
* size
);
427 bool SandboxedUnpacker::FinalizeHash(scoped_ptr
<crypto::SecureHash
>& hash
) {
429 uint8 output
[crypto::kSHA256Length
];
430 hash
->Finish(output
, sizeof(output
));
431 bool result
= (base::StringToLowerASCII(base::HexEncode(
432 output
, sizeof(output
))) == package_hash_
);
433 UMA_HISTOGRAM_BOOLEAN("Extensions.SandboxUnpackHashCheck", result
);
434 if (!result
&& check_crx_hash_
) {
435 // Package hash verification failed
436 std::string name
= crx_path_
.BaseName().AsUTF8Unsafe();
437 LOG(ERROR
) << "Hash check failed for extension: " << name
;
438 ReportFailure(CRX_HASH_VERIFICATION_FAILED
,
439 l10n_util::GetStringFUTF16(
440 IDS_EXTENSION_PACKAGE_ERROR_CODE
,
441 ASCIIToUTF16("CRX_HASH_VERIFICATION_FAILED")));
449 bool SandboxedUnpacker::ValidateSignature() {
450 base::ScopedFILE
file(base::OpenFile(crx_path_
, "rb"));
452 scoped_ptr
<crypto::SecureHash
> hash
;
454 if (!package_hash_
.empty()) {
455 hash
.reset(crypto::SecureHash::Create(crypto::SecureHash::SHA256
));
459 // Could not open crx file for reading.
461 // On windows, get the error code.
462 uint32 error_code
= ::GetLastError();
463 // TODO(skerner): Use this histogram to understand why so many
464 // windows users hit this error. crbug.com/69693
466 // Windows errors are unit32s, but all of likely errors are in
467 // [1, 1000]. See winerror.h for the meaning of specific values.
468 // Clip errors outside the expected range to a single extra value.
469 // If there are errors in that extra bucket, we will know to expand
471 const uint32 kMaxErrorToSend
= 1001;
472 error_code
= std::min(error_code
, kMaxErrorToSend
);
473 UMA_HISTOGRAM_ENUMERATION("Extensions.ErrorCodeFromCrxOpen", error_code
,
478 CRX_FILE_NOT_READABLE
,
479 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_ERROR_CODE
,
480 ASCIIToUTF16("CRX_FILE_NOT_READABLE")));
484 // Read and verify the header.
485 // TODO(erikkay): Yuck. I'm not a big fan of this kind of code, but it
486 // appears that we don't have any endian/alignment aware serialization
487 // code in the code base. So for now, this assumes that we're running
488 // on a little endian machine with 4 byte alignment.
489 CrxFile::Header header
;
490 size_t len
= ReadAndHash(&header
, 1, sizeof(header
), file
.get(), hash
);
491 if (len
< sizeof(header
)) {
492 // Invalid crx header
493 ReportFailure(CRX_HEADER_INVALID
, l10n_util::GetStringFUTF16(
494 IDS_EXTENSION_PACKAGE_ERROR_CODE
,
495 ASCIIToUTF16("CRX_HEADER_INVALID")));
499 CrxFile::Error error
;
500 scoped_ptr
<CrxFile
> crx(CrxFile::Parse(header
, &error
));
503 case CrxFile::kWrongMagic
:
504 ReportFailure(CRX_MAGIC_NUMBER_INVALID
,
505 l10n_util::GetStringFUTF16(
506 IDS_EXTENSION_PACKAGE_ERROR_CODE
,
507 ASCIIToUTF16("CRX_MAGIC_NUMBER_INVALID")));
509 case CrxFile::kInvalidVersion
:
511 ReportFailure(CRX_VERSION_NUMBER_INVALID
,
512 l10n_util::GetStringFUTF16(
513 IDS_EXTENSION_PACKAGE_ERROR_CODE
,
514 ASCIIToUTF16("CRX_VERSION_NUMBER_INVALID")));
516 case CrxFile::kInvalidKeyTooLarge
:
517 case CrxFile::kInvalidSignatureTooLarge
:
518 // Excessively large key or signature
520 CRX_EXCESSIVELY_LARGE_KEY_OR_SIGNATURE
,
521 l10n_util::GetStringFUTF16(
522 IDS_EXTENSION_PACKAGE_ERROR_CODE
,
523 ASCIIToUTF16("CRX_EXCESSIVELY_LARGE_KEY_OR_SIGNATURE")));
525 case CrxFile::kInvalidKeyTooSmall
:
526 // Key length is zero
529 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_ERROR_CODE
,
530 ASCIIToUTF16("CRX_ZERO_KEY_LENGTH")));
532 case CrxFile::kInvalidSignatureTooSmall
:
533 // Signature length is zero
534 ReportFailure(CRX_ZERO_SIGNATURE_LENGTH
,
535 l10n_util::GetStringFUTF16(
536 IDS_EXTENSION_PACKAGE_ERROR_CODE
,
537 ASCIIToUTF16("CRX_ZERO_SIGNATURE_LENGTH")));
543 std::vector
<uint8
> key
;
544 key
.resize(header
.key_size
);
545 len
= ReadAndHash(&key
.front(), sizeof(uint8
), header
.key_size
, file
.get(),
547 if (len
< header
.key_size
) {
548 // Invalid public key
550 CRX_PUBLIC_KEY_INVALID
,
551 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_ERROR_CODE
,
552 ASCIIToUTF16("CRX_PUBLIC_KEY_INVALID")));
556 std::vector
<uint8
> signature
;
557 signature
.resize(header
.signature_size
);
558 len
= ReadAndHash(&signature
.front(), sizeof(uint8
), header
.signature_size
,
560 if (len
< header
.signature_size
) {
563 CRX_SIGNATURE_INVALID
,
564 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_ERROR_CODE
,
565 ASCIIToUTF16("CRX_SIGNATURE_INVALID")));
569 crypto::SignatureVerifier verifier
;
570 if (!verifier
.VerifyInit(
571 crx_file::kSignatureAlgorithm
, sizeof(crx_file::kSignatureAlgorithm
),
572 &signature
.front(), signature
.size(), &key
.front(), key
.size())) {
573 // Signature verification initialization failed. This is most likely
574 // caused by a public key in the wrong format (should encode algorithm).
576 CRX_SIGNATURE_VERIFICATION_INITIALIZATION_FAILED
,
577 l10n_util::GetStringFUTF16(
578 IDS_EXTENSION_PACKAGE_ERROR_CODE
,
579 ASCIIToUTF16("CRX_SIGNATURE_VERIFICATION_INITIALIZATION_FAILED")));
583 unsigned char buf
[1 << 12];
584 while ((len
= ReadAndHash(buf
, 1, sizeof(buf
), file
.get(), hash
)) > 0)
585 verifier
.VerifyUpdate(buf
, len
);
587 if (!verifier
.VerifyFinal()) {
588 // Signature verification failed
589 ReportFailure(CRX_SIGNATURE_VERIFICATION_FAILED
,
590 l10n_util::GetStringFUTF16(
591 IDS_EXTENSION_PACKAGE_ERROR_CODE
,
592 ASCIIToUTF16("CRX_SIGNATURE_VERIFICATION_FAILED")));
596 if (!FinalizeHash(hash
)) {
600 std::string public_key
=
601 std::string(reinterpret_cast<char*>(&key
.front()), key
.size());
602 base::Base64Encode(public_key
, &public_key_
);
604 extension_id_
= crx_file::id_util::GenerateId(public_key
);
609 void SandboxedUnpacker::ReportFailure(FailureReason reason
,
610 const base::string16
& error
) {
611 UMA_HISTOGRAM_ENUMERATION("Extensions.SandboxUnpackFailureReason", reason
,
612 NUM_FAILURE_REASONS
);
613 UMA_HISTOGRAM_TIMES("Extensions.SandboxUnpackFailureTime",
614 base::TimeTicks::Now() - unpack_start_time_
);
616 client_
->OnUnpackFailure(error
);
619 void SandboxedUnpacker::ReportSuccess(
620 const base::DictionaryValue
& original_manifest
,
621 const SkBitmap
& install_icon
) {
622 UMA_HISTOGRAM_COUNTS("Extensions.SandboxUnpackSuccess", 1);
624 RecordSuccessfulUnpackTimeHistograms(
625 crx_path_
, base::TimeTicks::Now() - unpack_start_time_
);
627 // Client takes ownership of temporary directory and extension.
628 client_
->OnUnpackSuccess(temp_dir_
.Take(), extension_root_
,
629 &original_manifest
, extension_
.get(), install_icon
);
633 base::DictionaryValue
* SandboxedUnpacker::RewriteManifestFile(
634 const base::DictionaryValue
& manifest
) {
635 // Add the public key extracted earlier to the parsed manifest and overwrite
636 // the original manifest. We do this to ensure the manifest doesn't contain an
637 // exploitable bug that could be used to compromise the browser.
638 scoped_ptr
<base::DictionaryValue
> final_manifest(manifest
.DeepCopy());
639 final_manifest
->SetString(manifest_keys::kPublicKey
, public_key_
);
641 std::string manifest_json
;
642 JSONStringValueSerializer
serializer(&manifest_json
);
643 serializer
.set_pretty_print(true);
644 if (!serializer
.Serialize(*final_manifest
)) {
645 // Error serializing manifest.json.
646 ReportFailure(ERROR_SERIALIZING_MANIFEST_JSON
,
647 l10n_util::GetStringFUTF16(
648 IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
649 ASCIIToUTF16("ERROR_SERIALIZING_MANIFEST_JSON")));
653 base::FilePath manifest_path
= extension_root_
.Append(kManifestFilename
);
654 int size
= base::checked_cast
<int>(manifest_json
.size());
655 if (base::WriteFile(manifest_path
, manifest_json
.data(), size
) != size
) {
656 // Error saving manifest.json.
658 ERROR_SAVING_MANIFEST_JSON
,
659 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
660 ASCIIToUTF16("ERROR_SAVING_MANIFEST_JSON")));
664 return final_manifest
.release();
667 bool SandboxedUnpacker::RewriteImageFiles(SkBitmap
* install_icon
) {
668 DecodedImages images
;
669 if (!ReadImagesFromFile(temp_dir_
.path(), &images
)) {
670 // Couldn't read image data from disk.
671 ReportFailure(COULD_NOT_READ_IMAGE_DATA_FROM_DISK
,
672 l10n_util::GetStringFUTF16(
673 IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
674 ASCIIToUTF16("COULD_NOT_READ_IMAGE_DATA_FROM_DISK")));
678 // Delete any images that may be used by the browser. We're going to write
679 // out our own versions of the parsed images, and we want to make sure the
680 // originals are gone for good.
681 std::set
<base::FilePath
> image_paths
=
682 ExtensionsClient::Get()->GetBrowserImagePaths(extension_
.get());
683 if (image_paths
.size() != images
.size()) {
684 // Decoded images don't match what's in the manifest.
686 DECODED_IMAGES_DO_NOT_MATCH_THE_MANIFEST
,
687 l10n_util::GetStringFUTF16(
688 IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
689 ASCIIToUTF16("DECODED_IMAGES_DO_NOT_MATCH_THE_MANIFEST")));
693 for (std::set
<base::FilePath
>::iterator it
= image_paths
.begin();
694 it
!= image_paths
.end(); ++it
) {
695 base::FilePath path
= *it
;
696 if (path
.IsAbsolute() || path
.ReferencesParent()) {
697 // Invalid path for browser image.
698 ReportFailure(INVALID_PATH_FOR_BROWSER_IMAGE
,
699 l10n_util::GetStringFUTF16(
700 IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
701 ASCIIToUTF16("INVALID_PATH_FOR_BROWSER_IMAGE")));
704 if (!base::DeleteFile(extension_root_
.Append(path
), false)) {
705 // Error removing old image file.
706 ReportFailure(ERROR_REMOVING_OLD_IMAGE_FILE
,
707 l10n_util::GetStringFUTF16(
708 IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
709 ASCIIToUTF16("ERROR_REMOVING_OLD_IMAGE_FILE")));
714 const std::string
& install_icon_path
=
715 IconsInfo::GetIcons(extension_
.get())
716 .Get(extension_misc::EXTENSION_ICON_LARGE
,
717 ExtensionIconSet::MATCH_BIGGER
);
719 // Write our parsed images back to disk as well.
720 for (size_t i
= 0; i
< images
.size(); ++i
) {
721 if (BrowserThread::GetBlockingPool()->IsShutdownInProgress()) {
722 // Abort package installation if shutdown was initiated, crbug.com/235525
724 ABORTED_DUE_TO_SHUTDOWN
,
725 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
726 ASCIIToUTF16("ABORTED_DUE_TO_SHUTDOWN")));
730 const SkBitmap
& image
= get
<0>(images
[i
]);
731 base::FilePath path_suffix
= get
<1>(images
[i
]);
732 if (path_suffix
.MaybeAsASCII() == install_icon_path
)
733 *install_icon
= image
;
735 if (path_suffix
.IsAbsolute() || path_suffix
.ReferencesParent()) {
736 // Invalid path for bitmap image.
737 ReportFailure(INVALID_PATH_FOR_BITMAP_IMAGE
,
738 l10n_util::GetStringFUTF16(
739 IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
740 ASCIIToUTF16("INVALID_PATH_FOR_BITMAP_IMAGE")));
743 base::FilePath path
= extension_root_
.Append(path_suffix
);
745 std::vector
<unsigned char> image_data
;
746 // TODO(mpcomplete): It's lame that we're encoding all images as PNG, even
747 // though they may originally be .jpg, etc. Figure something out.
748 // http://code.google.com/p/chromium/issues/detail?id=12459
749 if (!gfx::PNGCodec::EncodeBGRASkBitmap(image
, false, &image_data
)) {
750 // Error re-encoding theme image.
751 ReportFailure(ERROR_RE_ENCODING_THEME_IMAGE
,
752 l10n_util::GetStringFUTF16(
753 IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
754 ASCIIToUTF16("ERROR_RE_ENCODING_THEME_IMAGE")));
758 // Note: we're overwriting existing files that the utility process wrote,
759 // so we can be sure the directory exists.
760 const char* image_data_ptr
= reinterpret_cast<const char*>(&image_data
[0]);
761 int size
= base::checked_cast
<int>(image_data
.size());
762 if (base::WriteFile(path
, image_data_ptr
, size
) != size
) {
763 // Error saving theme image.
765 ERROR_SAVING_THEME_IMAGE
,
766 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
767 ASCIIToUTF16("ERROR_SAVING_THEME_IMAGE")));
775 bool SandboxedUnpacker::RewriteCatalogFiles() {
776 base::DictionaryValue catalogs
;
777 if (!ReadMessageCatalogsFromFile(temp_dir_
.path(), &catalogs
)) {
778 // Could not read catalog data from disk.
779 ReportFailure(COULD_NOT_READ_CATALOG_DATA_FROM_DISK
,
780 l10n_util::GetStringFUTF16(
781 IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
782 ASCIIToUTF16("COULD_NOT_READ_CATALOG_DATA_FROM_DISK")));
786 // Write our parsed catalogs back to disk.
787 for (base::DictionaryValue::Iterator
it(catalogs
); !it
.IsAtEnd();
789 const base::DictionaryValue
* catalog
= NULL
;
790 if (!it
.value().GetAsDictionary(&catalog
)) {
791 // Invalid catalog data.
793 INVALID_CATALOG_DATA
,
794 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
795 ASCIIToUTF16("INVALID_CATALOG_DATA")));
799 base::FilePath relative_path
= base::FilePath::FromUTF8Unsafe(it
.key());
800 relative_path
= relative_path
.Append(kMessagesFilename
);
801 if (relative_path
.IsAbsolute() || relative_path
.ReferencesParent()) {
802 // Invalid path for catalog.
804 INVALID_PATH_FOR_CATALOG
,
805 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
806 ASCIIToUTF16("INVALID_PATH_FOR_CATALOG")));
809 base::FilePath path
= extension_root_
.Append(relative_path
);
811 std::string catalog_json
;
812 JSONStringValueSerializer
serializer(&catalog_json
);
813 serializer
.set_pretty_print(true);
814 if (!serializer
.Serialize(*catalog
)) {
815 // Error serializing catalog.
816 ReportFailure(ERROR_SERIALIZING_CATALOG
,
817 l10n_util::GetStringFUTF16(
818 IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
819 ASCIIToUTF16("ERROR_SERIALIZING_CATALOG")));
823 // Note: we're overwriting existing files that the utility process read,
824 // so we can be sure the directory exists.
825 int size
= base::checked_cast
<int>(catalog_json
.size());
826 if (base::WriteFile(path
, catalog_json
.c_str(), size
) != size
) {
827 // Error saving catalog.
829 ERROR_SAVING_CATALOG
,
830 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_INSTALL_ERROR
,
831 ASCIIToUTF16("ERROR_SAVING_CATALOG")));
839 void SandboxedUnpacker::Cleanup() {
840 DCHECK(unpacker_io_task_runner_
->RunsTasksOnCurrentThread());
841 if (!temp_dir_
.Delete()) {
842 LOG(WARNING
) << "Can not delete temp directory at "
843 << temp_dir_
.path().value();
847 } // namespace extensions