extension.h 21 KB

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