Aktualizr
C++ SOTA Client
bootstrap.cc
1 #include "bootstrap.h"
2 
3 #include <boost/algorithm/string.hpp>
4 
5 #include <stdio.h>
6 #include <fstream>
7 #include <sstream>
8 
9 #include "crypto/crypto.h"
10 #include "logging/logging.h"
11 #include "utilities/utils.h"
12 
13 Bootstrap::Bootstrap(const boost::filesystem::path& provision_path, const std::string& provision_password)
14  : ca(""), cert(""), pkey("") {
15  if (provision_path.empty()) {
16  LOG_ERROR << "Provision path is empty!";
17  throw std::runtime_error("Unable to parse bootstrap credentials");
18  }
19 
20  std::ifstream as(provision_path.c_str(), std::ios::in | std::ios::binary);
21  if (as.fail()) {
22  LOG_ERROR << "Unable to open provided provision archive " << provision_path << ": " << std::strerror(errno);
23  throw std::runtime_error("Unable to parse bootstrap credentials");
24  }
25 
26  std::string p12_str = Utils::readFileFromArchive(as, "autoprov_credentials.p12");
27  if (p12_str.empty()) {
28  throw std::runtime_error("Unable to parse bootstrap credentials");
29  }
30 
31  StructGuard<BIO> reg_p12(BIO_new_mem_buf(p12_str.c_str(), static_cast<int>(p12_str.size())), BIO_vfree);
32  if (reg_p12 == nullptr) {
33  LOG_ERROR << "Unable to open P12 archive: " << std::strerror(errno);
34  throw std::runtime_error("Unable to parse bootstrap credentials");
35  }
36 
37  if (!Crypto::parseP12(reg_p12.get(), provision_password, &pkey, &cert, &ca)) {
38  LOG_ERROR << "Unable to parse P12 archive";
39  throw std::runtime_error("Unable to parse bootstrap credentials");
40  }
41 }
42 
43 std::string Bootstrap::readServerUrl(const boost::filesystem::path& provision_path) {
44  std::string url;
45  try {
46  std::ifstream as(provision_path.c_str(), std::ios::in | std::ios::binary);
47  if (as.fail()) {
48  LOG_ERROR << "Unable to open provided provision archive " << provision_path << ": " << std::strerror(errno);
49  throw std::runtime_error("Unable to parse bootstrap credentials");
50  }
51  url = Utils::readFileFromArchive(as, "autoprov.url");
52  boost::trim(url);
53  } catch (std::runtime_error& exc) {
54  LOG_ERROR << "Unable to read server url from archive: " << exc.what();
55  url = "";
56  }
57 
58  return url;
59 }
60 
61 std::string Bootstrap::readServerCa(const boost::filesystem::path& provision_path) {
62  std::string server_ca;
63  try {
64  std::ifstream as(provision_path.c_str(), std::ios::in | std::ios::binary);
65  if (as.fail()) {
66  LOG_ERROR << "Unable to open provided provision archive " << provision_path << ": " << std::strerror(errno);
67  throw std::runtime_error("Unable to parse bootstrap credentials");
68  }
69  server_ca = Utils::readFileFromArchive(as, "server_ca.pem");
70  } catch (std::runtime_error& exc) {
71  LOG_ERROR << "Unable to read server ca from archive: " << exc.what();
72  return "";
73  }
74 
75  return server_ca;
76 }