1// Copyright (c) 2013 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.
4
5#ifndef EXTENSIONS_COMMON_EXTENSION_H_
6#define EXTENSIONS_COMMON_EXTENSION_H_
7
8#include <map>
9#include <memory>
10#include <set>
11#include <string>
12#include <vector>
13
14#include "base/auto_reset.h"
15#include "base/files/file_path.h"
16#include "base/macros.h"
17#include "base/memory/ref_counted.h"
18#include "base/threading/thread_checker.h"
19#include "base/version.h"
20#include "extensions/buildflags/buildflags.h"
21#include "extensions/common/extension_id.h"
22#include "extensions/common/extension_resource.h"
23#include "extensions/common/hashed_extension_id.h"
24#include "extensions/common/install_warning.h"
25#include "extensions/common/manifest.h"
26#include "extensions/common/url_pattern_set.h"
27#include "url/gurl.h"
28
29#if !BUILDFLAG(ENABLE_EXTENSIONS)
30#error "Extensions must be enabled"
31#endif
32
33namespace base {
34class DictionaryValue;
35class Version;
36}
37
38namespace extensions {
39class PermissionSet;
40class PermissionsData;
41class PermissionsParser;
42
43// Represents a Chrome extension.
44// Once created, an Extension object is immutable, with the exception of its
45// RuntimeData. This makes it safe to use on any thread, since access to the
46// RuntimeData is protected by a lock.
47class Extension : public base::RefCountedThreadSafe<Extension> {
48 public:
49 // Do not renumber or reorder these values, as they are stored on-disk in the
50 // user's preferences.
51 enum State {
52 DISABLED = 0,
53 ENABLED = 1,
54
55 // An external extension that the user uninstalled. We should not reinstall
56 // such extensions on startup.
57 EXTERNAL_EXTENSION_UNINSTALLED = 2,
58
59 // DEPRECATED: Special state for component extensions.
60 // ENABLED_COMPONENT_DEPRECATED = 3,
61
62 // Do not add more values. State is being removed.
63 // https://crbug.com/794205.
64 NUM_STATES = 4,
65 };
66
67 // A base class for parsed manifest data that APIs want to store on
68 // the extension. Related to base::SupportsUserData, but with an immutable
69 // thread-safe interface to match Extension.
70 struct ManifestData {
71 virtual ~ManifestData() {}
72 };
73
74 // Do not change the order of entries or remove entries in this list
75 // as this is used in UMA_HISTOGRAM_ENUMERATIONs about extensions.
76 enum InitFromValueFlags {
77 NO_FLAGS = 0,
78
79 // Usually, the id of an extension is generated by the "key" property of
80 // its manifest, but if |REQUIRE_KEY| is not set, a temporary ID will be
81 // generated based on the path.
82 REQUIRE_KEY = 1 << 0,
83
84 // Requires the extension to have an up-to-date manifest version.
85 // Typically, we'll support multiple manifest versions during a version
86 // transition. This flag signals that we want to require the most modern
87 // manifest version that Chrome understands.
88 REQUIRE_MODERN_MANIFEST_VERSION = 1 << 1,
89
90 // |ALLOW_FILE_ACCESS| indicates that the user is allowing this extension
91 // to have file access. If it's not present, then permissions and content
92 // scripts that match file:/// URLs will be filtered out.
93 ALLOW_FILE_ACCESS = 1 << 2,
94
95 // |FROM_WEBSTORE| indicates that the extension was installed from the
96 // Chrome Web Store.
97 FROM_WEBSTORE = 1 << 3,
98
99 // |FROM_BOOKMARK| indicates the extension is a bookmark app which has been
100 // generated from a web page. Bookmark apps have no permissions or extent
101 // and launch the web page they are created from when run.
102 FROM_BOOKMARK = 1 << 4,
103
104 // |FOLLOW_SYMLINKS_ANYWHERE| means that resources can be symlinks to
105 // anywhere in the filesystem, rather than being restricted to the
106 // extension directory.
107 FOLLOW_SYMLINKS_ANYWHERE = 1 << 5,
108
109 // |ERROR_ON_PRIVATE_KEY| means that private keys inside an
110 // extension should be errors rather than warnings.
111 ERROR_ON_PRIVATE_KEY = 1 << 6,
112
113 // |WAS_INSTALLED_BY_DEFAULT| installed by default when the profile was
114 // created.
115 WAS_INSTALLED_BY_DEFAULT = 1 << 7,
116
117 // Unused - was part of an abandoned experiment.
118 REQUIRE_PERMISSIONS_CONSENT = 1 << 8,
119
120 // Unused - this flag has been moved to ExtensionPrefs.
121 IS_EPHEMERAL = 1 << 9,
122
123 // |WAS_INSTALLED_BY_OEM| installed by an OEM (e.g on Chrome OS) and should
124 // be placed in a special OEM folder in the App Launcher. Note: OEM apps are
125 // also installed by Default (i.e. WAS_INSTALLED_BY_DEFAULT is also true).
126 WAS_INSTALLED_BY_OEM = 1 << 10,
127
128 // DEPRECATED: WAS_INSTALLED_BY_CUSTODIAN is now stored as a pref instead.
129 // WAS_INSTALLED_BY_CUSTODIAN = 1 << 11,
130
131 // |MAY_BE_UNTRUSTED| indicates that this extension came from a potentially
132 // unsafe source (e.g., sideloaded from a local CRX file via the Windows
133 // registry). Such extensions may be subjected to additional constraints
134 // before they are fully installed and enabled.
135 MAY_BE_UNTRUSTED = 1 << 12,
136
137 // When adding new flags, make sure to update kInitFromValueFlagBits.
138 };
139
140 // This is the highest bit index of the flags defined above.
141 static const int kInitFromValueFlagBits;
142
143 static scoped_refptr<Extension> Create(const base::FilePath& path,
144 Manifest::Location location,
145 const base::DictionaryValue& value,
146 int flags,
147 std::string* error);
148
149 // In a few special circumstances, we want to create an Extension and give it
150 // an explicit id. Most consumers should just use the other Create() method.
151 static scoped_refptr<Extension> Create(const base::FilePath& path,
152 Manifest::Location location,
153 const base::DictionaryValue& value,
154 int flags,
155 const ExtensionId& explicit_id,
156 std::string* error);
157
158 // Valid schemes for web extent URLPatterns.
159 static const int kValidWebExtentSchemes;
160
161 // Valid schemes for bookmark app installs by the user.
162 static const int kValidBookmarkAppSchemes;
163
164 // Valid schemes for host permission URLPatterns.
165 static const int kValidHostPermissionSchemes;
166
167 // The mimetype used for extensions.
168 static const char kMimeType[];
169
170 // See Type definition in Manifest.
171 Manifest::Type GetType() const;
172
173 // Returns an absolute url to a resource inside of an extension. The
174 // |extension_url| argument should be the url() from an Extension object. The
175 // |relative_path| can be untrusted user input. The returned URL will either
176 // be invalid() or a child of |extension_url|.
177 // NOTE: Static so that it can be used from multiple threads.
178 static GURL GetResourceURL(const GURL& extension_url,
179 const std::string& relative_path);
180 GURL GetResourceURL(const std::string& relative_path) const {
181 return GetResourceURL(url(), relative_path);
182 }
183
184 // Returns true if the resource matches a pattern in the pattern_set.
185 bool ResourceMatches(const URLPatternSet& pattern_set,
186 const std::string& resource) const;
187
188 // Returns an extension resource object. |relative_path| should be UTF8
189 // encoded.
190 ExtensionResource GetResource(const std::string& relative_path) const;
191
192 // As above, but with |relative_path| following the file system's encoding.
193 ExtensionResource GetResource(const base::FilePath& relative_path) const;
194
195 // |input| is expected to be the text of an rsa public or private key. It
196 // tolerates the presence or absence of bracking header/footer like this:
197 // -----(BEGIN|END) [RSA PUBLIC/PRIVATE] KEY-----
198 // and may contain newlines.
199 static bool ParsePEMKeyBytes(const std::string& input, std::string* output);
200
201 // Does a simple base64 encoding of |input| into |output|.
202 static bool ProducePEM(const std::string& input, std::string* output);
203
204 // Expects base64 encoded |input| and formats into |output| including
205 // the appropriate header & footer.
206 static bool FormatPEMForFileOutput(const std::string& input,
207 std::string* output,
208 bool is_public);
209
210 // Returns the base extension url for a given |extension_id|.
211 static GURL GetBaseURLFromExtensionId(const ExtensionId& extension_id);
212
213 // Returns true if this extension or app includes areas within |origin|.
214 bool OverlapsWithOrigin(const GURL& origin) const;
215
216 // Returns true if the extension requires a valid ordinal for sorting, e.g.,
217 // for displaying in a launcher or new tab page.
218 bool RequiresSortOrdinal() const;
219
220 // Returns true if the extension should be displayed in the app launcher.
221 bool ShouldDisplayInAppLauncher() const;
222
223 // Returns true if the extension should be displayed in the browser NTP.
224 bool ShouldDisplayInNewTabPage() const;
225
226 // Returns true if the extension should be displayed in the extension
227 // settings page (i.e. chrome://extensions).
228 bool ShouldDisplayInExtensionSettings() const;
229
230 // Returns true if the extension should be exposed via the chrome.management
231 // API.
232 bool ShouldExposeViaManagementAPI() const;
233
234 // Get the manifest data associated with the key, or NULL if there is none.
235 // Can only be called after InitValue is finished.
236 ManifestData* GetManifestData(const std::string& key) const;
237
238 // Sets |data| to be associated with the key.
239 // Can only be called before InitValue is finished. Not thread-safe;
240 // all SetManifestData calls should be on only one thread.
241 void SetManifestData(const std::string& key,
242 std::unique_ptr<ManifestData> data);
243
244 // Accessors:
245
246 const base::FilePath& path() const { return path_; }
247 const GURL& url() const { return extension_url_; }
248 Manifest::Location location() const;
249 const ExtensionId& id() const;
250 const HashedExtensionId& hashed_id() const;
251 const base::Version& version() const { return version_; }
252 const std::string& version_name() const { return version_name_; }
253 const std::string VersionString() const;
254 const std::string GetVersionForDisplay() const;
255 const std::string& name() const { return display_name_; }
256 const std::string& short_name() const { return short_name_; }
257 const std::string& non_localized_name() const { return non_localized_name_; }
258 // Base64-encoded version of the key used to sign this extension.
259 // In pseudocode, returns
260 // base::Base64Encode(RSAPrivateKey(pem_file).ExportPublicKey()).
261 const std::string& public_key() const { return public_key_; }
262 const std::string& description() const { return description_; }
263 int manifest_version() const { return manifest_version_; }
264 bool converted_from_user_script() const {
265 return converted_from_user_script_;
266 }
267 PermissionsParser* permissions_parser() { return permissions_parser_.get(); }
268 const PermissionsParser* permissions_parser() const {
269 return permissions_parser_.get();
270 }
271
272 const PermissionsData* permissions_data() const {
273 return permissions_data_.get();
274 }
275
276 // Appends |new_warning[s]| to install_warnings_.
277 void AddInstallWarning(InstallWarning new_warning);
278 void AddInstallWarnings(std::vector<InstallWarning> new_warnings);
279 const std::vector<InstallWarning>& install_warnings() const {
280 return install_warnings_;
281 }
282 const extensions::Manifest* manifest() const {
283 return manifest_.get();
284 }
285 bool wants_file_access() const { return wants_file_access_; }
286 // TODO(rdevlin.cronin): This is needed for ContentScriptsHandler, and should
287 // be moved out as part of crbug.com/159265. This should not be used anywhere
288 // else.
289 void set_wants_file_access(bool wants_file_access) {
290 wants_file_access_ = wants_file_access;
291 }
292 int creation_flags() const { return creation_flags_; }
293 bool from_webstore() const { return (creation_flags_ & FROM_WEBSTORE) != 0; }
294 bool from_bookmark() const { return (creation_flags_ & FROM_BOOKMARK) != 0; }
295 bool may_be_untrusted() const {
296 return (creation_flags_ & MAY_BE_UNTRUSTED) != 0;
297 }
298 bool was_installed_by_default() const {
299 return (creation_flags_ & WAS_INSTALLED_BY_DEFAULT) != 0;
300 }
301 bool was_installed_by_oem() const {
302 return (creation_flags_ & WAS_INSTALLED_BY_OEM) != 0;
303 }
304
305 // Type-related queries. These are all mutually exclusive.
306 //
307 // The differences between the types of Extension are documented here:
308 // https://chromium.googlesource.com/chromium/src/+/HEAD/extensions/docs/extension_and_app_types.md
309 bool is_platform_app() const; // aka "V2 app", "V2 packaged app"
310 bool is_hosted_app() const; // Hosted app (or bookmark app)
311 bool is_legacy_packaged_app() const; // aka "V1 packaged app"
312 bool is_extension() const; // Regular browser extension, not an app
313 bool is_shared_module() const; // Shared module
314 bool is_theme() const; // Theme
315
316 // True if this is a platform app, hosted app, or legacy packaged app.
317 bool is_app() const;
318
319 void AddWebExtentPattern(const URLPattern& pattern);
320 const URLPatternSet& web_extent() const { return extent_; }
321
322 private:
323 friend class base::RefCountedThreadSafe<Extension>;
324
325 // Chooses the extension ID for an extension based on a variety of criteria.
326 // The chosen ID will be set in |manifest|.
327 static bool InitExtensionID(extensions::Manifest* manifest,
328 const base::FilePath& path,
329 const ExtensionId& explicit_id,
330 int creation_flags,
331 base::string16* error);
332
333 Extension(const base::FilePath& path,
334 std::unique_ptr<extensions::Manifest> manifest);
335 virtual ~Extension();
336
337 // Initialize the extension from a parsed manifest.
338 // TODO(aa): Rename to just Init()? There's no Value here anymore.
339 // TODO(aa): It is really weird the way this class essentially contains a copy
340 // of the underlying DictionaryValue in its members. We should decide to
341 // either wrap the DictionaryValue and go with that only, or we should parse
342 // into strong types and discard the value. But doing both is bad.
343 bool InitFromValue(int flags, base::string16* error);
344
345 // The following are helpers for InitFromValue to load various features of the
346 // extension from the manifest.
347
348 bool LoadRequiredFeatures(base::string16* error);
349 bool LoadName(base::string16* error);
350 bool LoadVersion(base::string16* error);
351
352 bool LoadAppFeatures(base::string16* error);
353 bool LoadExtent(const char* key,
354 URLPatternSet* extent,
355 const char* list_error,
356 const char* value_error,
357 base::string16* error);
358
359 bool LoadSharedFeatures(base::string16* error);
360 bool LoadDescription(base::string16* error);
361 bool LoadManifestVersion(base::string16* error);
362 bool LoadShortName(base::string16* error);
363
364 bool CheckMinimumChromeVersion(base::string16* error) const;
365
366 // The extension's human-readable name. Name is used for display purpose. It
367 // might be wrapped with unicode bidi control characters so that it is
368 // displayed correctly in RTL context.
369 // NOTE: Name is UTF-8 and may contain non-ascii characters.
370 std::string display_name_;
371
372 // A non-localized version of the extension's name. This is useful for
373 // debug output.
374 std::string non_localized_name_;
375
376 // A short version of the extension's name. This can be used as an alternative
377 // to the name where there is insufficient space to display the full name. If
378 // an extension has not explicitly specified a short name, the value of this
379 // member variable will be the full name rather than an empty string.
380 std::string short_name_;
381
382 // The version of this extension's manifest. We increase the manifest
383 // version when making breaking changes to the extension system.
384 // Version 1 was the first manifest version (implied by a lack of a
385 // manifest_version attribute in the extension's manifest). We initialize
386 // this member variable to 0 to distinguish the "uninitialized" case from
387 // the case when we know the manifest version actually is 1.
388 int manifest_version_;
389
390 // The absolute path to the directory the extension is stored in.
391 base::FilePath path_;
392
393 // Defines the set of URLs in the extension's web content.
394 URLPatternSet extent_;
395
396 // The parser for the manifest's permissions. This is NULL anytime not during
397 // initialization.
398 // TODO(rdevlin.cronin): This doesn't really belong here.
399 std::unique_ptr<PermissionsParser> permissions_parser_;
400
401 // The active permissions for the extension.
402 std::unique_ptr<PermissionsData> permissions_data_;
403
404 // Any warnings that occurred when trying to create/parse the extension.
405 std::vector<InstallWarning> install_warnings_;
406
407 // The base extension url for the extension.
408 GURL extension_url_;
409
410 // The extension's version.
411 base::Version version_;
412
413 // The extension's user visible version name.
414 std::string version_name_;
415
416 // An optional longer description of the extension.
417 std::string description_;
418
419 // True if the extension was generated from a user script. (We show slightly
420 // different UI if so).
421 bool converted_from_user_script_;
422
423 // The public key used to sign the contents of the crx package.
424 std::string public_key_;
425
426 // The manifest from which this extension was created.
427 std::unique_ptr<Manifest> manifest_;
428
429 // Stored parsed manifest data.
430 using ManifestDataMap = std::map<std::string, std::unique_ptr<ManifestData>>;
431 ManifestDataMap manifest_data_;
432
433 // Set to true at the end of InitValue when initialization is finished.
434 bool finished_parsing_manifest_;
435
436 // Ensures that any call to GetManifestData() prior to finishing
437 // initialization happens from the same thread (this can happen when certain
438 // parts of the initialization process need information from previous parts).
439 base::ThreadChecker thread_checker_;
440
441 // Should this app be shown in the app launcher.
442 bool display_in_launcher_;
443
444 // Should this app be shown in the browser New Tab Page.
445 bool display_in_new_tab_page_;
446
447 // Whether the extension has host permissions or user script patterns that
448 // imply access to file:/// scheme URLs (the user may not have actually
449 // granted it that access).
450 bool wants_file_access_;
451
452 // The flags that were passed to InitFromValue.
453 int creation_flags_;
454
455 DISALLOW_COPY_AND_ASSIGN(Extension);
456};
457
458typedef std::vector<scoped_refptr<const Extension> > ExtensionList;
459typedef std::set<ExtensionId> ExtensionIdSet;
460typedef std::vector<ExtensionId> ExtensionIdList;
461
462// Handy struct to pass core extension info around.
463struct ExtensionInfo {
464 ExtensionInfo(const base::DictionaryValue* manifest,
465 const ExtensionId& id,
466 const base::FilePath& path,
467 Manifest::Location location);
468 ~ExtensionInfo();
469
470 // Note: This may be null (e.g. for unpacked extensions retrieved from the
471 // Preferences file).
472 std::unique_ptr<base::DictionaryValue> extension_manifest;
473
474 ExtensionId extension_id;
475 base::FilePath extension_path;
476 Manifest::Location extension_location;
477
478 private:
479 DISALLOW_COPY_AND_ASSIGN(ExtensionInfo);
480};
481
482// TODO(DHNishi): Move this enum to ExtensionRegistryObserver.
483enum class UnloadedExtensionReason {
484 UNDEFINED, // Undefined state used to initialize variables.
485 DISABLE, // Extension is being disabled.
486 UPDATE, // Extension is being updated to a newer version.
487 UNINSTALL, // Extension is being uninstalled.
488 TERMINATE, // Extension has terminated.
489 BLACKLIST, // Extension has been blacklisted.
490 PROFILE_SHUTDOWN, // Profile is being shut down.
491 LOCK_ALL, // All extensions for the profile are blocked.
492 MIGRATED_TO_COMPONENT, // Extension is being migrated to a component
493 // action.
494};
495
496// The details sent for EXTENSION_PERMISSIONS_UPDATED notifications.
497struct UpdatedExtensionPermissionsInfo {
498 enum Reason {
499 ADDED, // The permissions were added to the extension.
500 REMOVED, // The permissions were removed from the extension.
501 POLICY, // The policy that affects permissions was updated.
502 };
503
504 Reason reason;
505
506 // The extension who's permissions have changed.
507 const Extension* extension;
508
509 // The permissions that have changed. For Reason::ADDED, this would contain
510 // only the permissions that have added, and for Reason::REMOVED, this would
511 // only contain the removed permissions.
512 const PermissionSet& permissions;
513
514 UpdatedExtensionPermissionsInfo(const Extension* extension,
515 const PermissionSet& permissions,
516 Reason reason);
517};
518
519} // namespace extensions
520
521#endif // EXTENSIONS_COMMON_EXTENSION_H_
522