archive.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. // Copyright (c) 2014 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/common/asar/archive.h"
  5. #include <string>
  6. #include <utility>
  7. #include <vector>
  8. #include "base/check.h"
  9. #include "base/files/file.h"
  10. #include "base/files/file_util.h"
  11. #include "base/json/json_reader.h"
  12. #include "base/logging.h"
  13. #include "base/pickle.h"
  14. #include "base/strings/string_number_conversions.h"
  15. #include "base/task/post_task.h"
  16. #include "base/threading/thread_restrictions.h"
  17. #include "base/values.h"
  18. #include "electron/fuses.h"
  19. #include "shell/common/asar/asar_util.h"
  20. #include "shell/common/asar/scoped_temporary_file.h"
  21. #if defined(OS_WIN)
  22. #include <io.h>
  23. #endif
  24. namespace asar {
  25. namespace {
  26. #if defined(OS_WIN)
  27. const char kSeparators[] = "\\/";
  28. #else
  29. const char kSeparators[] = "/";
  30. #endif
  31. bool GetNodeFromPath(std::string path,
  32. const base::DictionaryValue* root,
  33. const base::DictionaryValue** out);
  34. // Gets the "files" from "dir".
  35. bool GetFilesNode(const base::DictionaryValue* root,
  36. const base::DictionaryValue* dir,
  37. const base::DictionaryValue** out) {
  38. // Test for symbol linked directory.
  39. const std::string* link = dir->FindStringKey("link");
  40. if (link != nullptr) {
  41. const base::DictionaryValue* linked_node = nullptr;
  42. if (!GetNodeFromPath(*link, root, &linked_node))
  43. return false;
  44. dir = linked_node;
  45. }
  46. return dir->GetDictionaryWithoutPathExpansion("files", out);
  47. }
  48. // Gets sub-file "name" from "dir".
  49. bool GetChildNode(const base::DictionaryValue* root,
  50. const std::string& name,
  51. const base::DictionaryValue* dir,
  52. const base::DictionaryValue** out) {
  53. if (name.empty()) {
  54. *out = root;
  55. return true;
  56. }
  57. const base::DictionaryValue* files = nullptr;
  58. return GetFilesNode(root, dir, &files) &&
  59. files->GetDictionaryWithoutPathExpansion(name, out);
  60. }
  61. // Gets the node of "path" from "root".
  62. bool GetNodeFromPath(std::string path,
  63. const base::DictionaryValue* root,
  64. const base::DictionaryValue** out) {
  65. if (path.empty()) {
  66. *out = root;
  67. return true;
  68. }
  69. const base::DictionaryValue* dir = root;
  70. for (size_t delimiter_position = path.find_first_of(kSeparators);
  71. delimiter_position != std::string::npos;
  72. delimiter_position = path.find_first_of(kSeparators)) {
  73. const base::DictionaryValue* child = nullptr;
  74. if (!GetChildNode(root, path.substr(0, delimiter_position), dir, &child))
  75. return false;
  76. dir = child;
  77. path.erase(0, delimiter_position + 1);
  78. }
  79. return GetChildNode(root, path, dir, out);
  80. }
  81. bool FillFileInfoWithNode(Archive::FileInfo* info,
  82. uint32_t header_size,
  83. bool load_integrity,
  84. const base::DictionaryValue* node) {
  85. int size;
  86. if (!node->GetInteger("size", &size))
  87. return false;
  88. info->size = static_cast<uint32_t>(size);
  89. if (node->GetBoolean("unpacked", &info->unpacked) && info->unpacked)
  90. return true;
  91. std::string offset;
  92. if (!node->GetString("offset", &offset))
  93. return false;
  94. if (!base::StringToUint64(offset, &info->offset))
  95. return false;
  96. info->offset += header_size;
  97. node->GetBoolean("executable", &info->executable);
  98. #if defined(OS_MAC)
  99. if (load_integrity &&
  100. electron::fuses::IsEmbeddedAsarIntegrityValidationEnabled()) {
  101. const base::DictionaryValue* integrity;
  102. if (node->GetDictionary("integrity", &integrity)) {
  103. IntegrityPayload integrity_payload;
  104. std::string algorithm;
  105. const base::ListValue* blocks;
  106. int block_size;
  107. if (integrity->GetString("algorithm", &algorithm) &&
  108. integrity->GetString("hash", &integrity_payload.hash) &&
  109. integrity->GetInteger("blockSize", &block_size) &&
  110. integrity->GetList("blocks", &blocks) && block_size > 0) {
  111. integrity_payload.block_size = static_cast<uint32_t>(block_size);
  112. for (size_t i = 0; i < blocks->GetSize(); i++) {
  113. std::string block;
  114. if (!blocks->GetString(i, &block)) {
  115. LOG(FATAL)
  116. << "Invalid block integrity value for file in ASAR archive";
  117. }
  118. integrity_payload.blocks.push_back(block);
  119. }
  120. if (algorithm == "SHA256") {
  121. integrity_payload.algorithm = HashAlgorithm::SHA256;
  122. info->integrity = std::move(integrity_payload);
  123. }
  124. }
  125. }
  126. if (!info->integrity.has_value()) {
  127. LOG(FATAL) << "Failed to read integrity for file in ASAR archive";
  128. return false;
  129. }
  130. }
  131. #endif
  132. return true;
  133. }
  134. } // namespace
  135. IntegrityPayload::IntegrityPayload()
  136. : algorithm(HashAlgorithm::NONE), block_size(0) {}
  137. IntegrityPayload::~IntegrityPayload() = default;
  138. IntegrityPayload::IntegrityPayload(const IntegrityPayload& other) = default;
  139. Archive::FileInfo::FileInfo()
  140. : unpacked(false), executable(false), size(0), offset(0) {}
  141. Archive::FileInfo::~FileInfo() = default;
  142. Archive::Archive(const base::FilePath& path)
  143. : initialized_(false), path_(path), file_(base::File::FILE_OK) {
  144. base::ThreadRestrictions::ScopedAllowIO allow_io;
  145. file_.Initialize(path_, base::File::FLAG_OPEN | base::File::FLAG_READ);
  146. #if defined(OS_WIN)
  147. fd_ = _open_osfhandle(reinterpret_cast<intptr_t>(file_.GetPlatformFile()), 0);
  148. #elif defined(OS_POSIX)
  149. fd_ = file_.GetPlatformFile();
  150. #endif
  151. }
  152. Archive::~Archive() {
  153. #if defined(OS_WIN)
  154. if (fd_ != -1) {
  155. _close(fd_);
  156. // Don't close the handle since we already closed the fd.
  157. file_.TakePlatformFile();
  158. }
  159. #endif
  160. base::ThreadRestrictions::ScopedAllowIO allow_io;
  161. file_.Close();
  162. }
  163. bool Archive::Init() {
  164. // Should only be initialized once
  165. CHECK(!initialized_);
  166. initialized_ = true;
  167. if (!file_.IsValid()) {
  168. if (file_.error_details() != base::File::FILE_ERROR_NOT_FOUND) {
  169. LOG(WARNING) << "Opening " << path_.value() << ": "
  170. << base::File::ErrorToString(file_.error_details());
  171. }
  172. return false;
  173. }
  174. std::vector<char> buf;
  175. int len;
  176. buf.resize(8);
  177. {
  178. base::ThreadRestrictions::ScopedAllowIO allow_io;
  179. len = file_.ReadAtCurrentPos(buf.data(), buf.size());
  180. }
  181. if (len != static_cast<int>(buf.size())) {
  182. PLOG(ERROR) << "Failed to read header size from " << path_.value();
  183. return false;
  184. }
  185. uint32_t size;
  186. if (!base::PickleIterator(base::Pickle(buf.data(), buf.size()))
  187. .ReadUInt32(&size)) {
  188. LOG(ERROR) << "Failed to parse header size from " << path_.value();
  189. return false;
  190. }
  191. buf.resize(size);
  192. {
  193. base::ThreadRestrictions::ScopedAllowIO allow_io;
  194. len = file_.ReadAtCurrentPos(buf.data(), buf.size());
  195. }
  196. if (len != static_cast<int>(buf.size())) {
  197. PLOG(ERROR) << "Failed to read header from " << path_.value();
  198. return false;
  199. }
  200. std::string header;
  201. if (!base::PickleIterator(base::Pickle(buf.data(), buf.size()))
  202. .ReadString(&header)) {
  203. LOG(ERROR) << "Failed to parse header from " << path_.value();
  204. return false;
  205. }
  206. #if defined(OS_MAC)
  207. // Validate header signature if required and possible
  208. if (electron::fuses::IsEmbeddedAsarIntegrityValidationEnabled() &&
  209. RelativePath().has_value()) {
  210. absl::optional<IntegrityPayload> integrity = HeaderIntegrity();
  211. if (!integrity.has_value()) {
  212. LOG(FATAL) << "Failed to get integrity for validatable asar archive: "
  213. << RelativePath().value();
  214. return false;
  215. }
  216. // Currently we only support the sha256 algorithm, we can add support for
  217. // more below ensure we read them in preference order from most secure to
  218. // least
  219. if (integrity.value().algorithm != HashAlgorithm::NONE) {
  220. ValidateIntegrityOrDie(header.c_str(), header.length(),
  221. integrity.value());
  222. } else {
  223. LOG(FATAL) << "No eligible hash for validatable asar archive: "
  224. << RelativePath().value();
  225. }
  226. header_validated_ = true;
  227. }
  228. #endif
  229. absl::optional<base::Value> value = base::JSONReader::Read(header);
  230. if (!value || !value->is_dict()) {
  231. LOG(ERROR) << "Failed to parse header";
  232. return false;
  233. }
  234. header_size_ = 8 + size;
  235. header_ = base::DictionaryValue::From(
  236. base::Value::ToUniquePtrValue(std::move(*value)));
  237. return true;
  238. }
  239. #if !defined(OS_MAC)
  240. absl::optional<IntegrityPayload> Archive::HeaderIntegrity() const {
  241. return absl::nullopt;
  242. }
  243. absl::optional<base::FilePath> Archive::RelativePath() const {
  244. return absl::nullopt;
  245. }
  246. #endif
  247. bool Archive::GetFileInfo(const base::FilePath& path, FileInfo* info) const {
  248. if (!header_)
  249. return false;
  250. const base::DictionaryValue* node;
  251. if (!GetNodeFromPath(path.AsUTF8Unsafe(), header_.get(), &node))
  252. return false;
  253. std::string link;
  254. if (node->GetString("link", &link))
  255. return GetFileInfo(base::FilePath::FromUTF8Unsafe(link), info);
  256. return FillFileInfoWithNode(info, header_size_, header_validated_, node);
  257. }
  258. bool Archive::Stat(const base::FilePath& path, Stats* stats) const {
  259. if (!header_)
  260. return false;
  261. const base::DictionaryValue* node;
  262. if (!GetNodeFromPath(path.AsUTF8Unsafe(), header_.get(), &node))
  263. return false;
  264. if (node->FindKey("link")) {
  265. stats->is_file = false;
  266. stats->is_link = true;
  267. return true;
  268. }
  269. if (node->FindKey("files")) {
  270. stats->is_file = false;
  271. stats->is_directory = true;
  272. return true;
  273. }
  274. return FillFileInfoWithNode(stats, header_size_, header_validated_, node);
  275. }
  276. bool Archive::Readdir(const base::FilePath& path,
  277. std::vector<base::FilePath>* files) const {
  278. if (!header_)
  279. return false;
  280. const base::DictionaryValue* node;
  281. if (!GetNodeFromPath(path.AsUTF8Unsafe(), header_.get(), &node))
  282. return false;
  283. const base::DictionaryValue* files_node;
  284. if (!GetFilesNode(header_.get(), node, &files_node))
  285. return false;
  286. base::DictionaryValue::Iterator iter(*files_node);
  287. while (!iter.IsAtEnd()) {
  288. files->push_back(base::FilePath::FromUTF8Unsafe(iter.key()));
  289. iter.Advance();
  290. }
  291. return true;
  292. }
  293. bool Archive::Realpath(const base::FilePath& path,
  294. base::FilePath* realpath) const {
  295. if (!header_)
  296. return false;
  297. const base::DictionaryValue* node;
  298. if (!GetNodeFromPath(path.AsUTF8Unsafe(), header_.get(), &node))
  299. return false;
  300. std::string link;
  301. if (node->GetString("link", &link)) {
  302. *realpath = base::FilePath::FromUTF8Unsafe(link);
  303. return true;
  304. }
  305. *realpath = path;
  306. return true;
  307. }
  308. bool Archive::CopyFileOut(const base::FilePath& path, base::FilePath* out) {
  309. if (!header_)
  310. return false;
  311. base::AutoLock auto_lock(external_files_lock_);
  312. auto it = external_files_.find(path.value());
  313. if (it != external_files_.end()) {
  314. *out = it->second->path();
  315. return true;
  316. }
  317. FileInfo info;
  318. if (!GetFileInfo(path, &info))
  319. return false;
  320. if (info.unpacked) {
  321. *out = path_.AddExtension(FILE_PATH_LITERAL("unpacked")).Append(path);
  322. return true;
  323. }
  324. auto temp_file = std::make_unique<ScopedTemporaryFile>();
  325. base::FilePath::StringType ext = path.Extension();
  326. if (!temp_file->InitFromFile(&file_, ext, info.offset, info.size,
  327. info.integrity))
  328. return false;
  329. #if defined(OS_POSIX)
  330. if (info.executable) {
  331. // chmod a+x temp_file;
  332. base::SetPosixFilePermissions(temp_file->path(), 0755);
  333. }
  334. #endif
  335. *out = temp_file->path();
  336. external_files_[path.value()] = std::move(temp_file);
  337. return true;
  338. }
  339. int Archive::GetUnsafeFD() const {
  340. return fd_;
  341. }
  342. } // namespace asar