blob: e1e961d7bbe9ca989ab27754619be159ab291f5d [file] [log] [blame]
Jayanth Othayoth70804dc2018-03-20 06:31:59 -05001#include <set>
2#include <fstream>
3#include <sys/stat.h>
4#include <fcntl.h>
5#include <openssl/err.h>
6
7#include "image_verify.hpp"
8#include "config.h"
9#include "version.hpp"
10
11#include <phosphor-logging/log.hpp>
12#include <phosphor-logging/elog.hpp>
13#include <phosphor-logging/elog-errors.hpp>
14#include <xyz/openbmc_project/Common/error.hpp>
15
16namespace openpower
17{
18namespace software
19{
20namespace image
21{
22
23using namespace phosphor::logging;
24using namespace openpower::software::updater;
25using InternalFailure =
26 sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
27
28constexpr auto keyTypeTag = "KeyType";
29constexpr auto hashFunctionTag = "HashType";
30
31Signature::Signature(const fs::path& imageDirPath,
32 const fs::path& signedConfPath) :
33 imageDirPath(imageDirPath),
34 signedConfPath(signedConfPath)
35{
36 fs::path file(imageDirPath / MANIFEST_FILE);
37
38 auto keyValues =
39 Version::getValue(file, {{keyTypeTag, " "}, {hashFunctionTag, " "}});
40 keyType = keyValues.at(keyTypeTag);
41 hashType = keyValues.at(hashFunctionTag);
42}
43
44AvailableKeyTypes Signature::getAvailableKeyTypesFromSystem() const
45{
46 AvailableKeyTypes keyTypes{};
47
48 // Find the path of all the files
49 if (!fs::is_directory(signedConfPath))
50 {
51 log<level::ERR>("Signed configuration path not found in the system");
52 elog<InternalFailure>();
53 }
54
55 // Look for all the hash and public key file names get the key value
56 // For example:
57 // /etc/activationdata/OpenPOWER/publickey
58 // /etc/activationdata/OpenPOWER/hashfunc
59 // /etc/activationdata/GA/publickey
60 // /etc/activationdata/GA/hashfunc
61 // Set will have OpenPOWER, GA
62
63 for (const auto& p : fs::recursive_directory_iterator(signedConfPath))
64 {
65 if ((p.path().filename() == HASH_FILE_NAME) ||
66 (p.path().filename() == PUBLICKEY_FILE_NAME))
67 {
68 // extract the key types
69 // /etc/activationdata/GA/ -> get GA from the path
70 auto key = p.path().parent_path();
71 keyTypes.insert(key.filename());
72 }
73 }
74
75 return keyTypes;
76}
77
78inline KeyHashPathPair Signature::getKeyHashFileNames(const Key_t& key) const
79{
80 fs::path hashpath(signedConfPath / key / HASH_FILE_NAME);
81 fs::path keyPath(signedConfPath / key / PUBLICKEY_FILE_NAME);
82
83 return std::make_pair(std::move(hashpath), std::move(keyPath));
84}
85
86bool Signature::verify()
87{
88 try
89 {
90 // Verify the MANIFEST and publickey file using available
91 // public keys and hash on the system.
92 if (false == systemLevelVerify())
93 {
94 log<level::ERR>("System level Signature Validation failed");
95 return false;
96 }
97
Gunnar Mills4c7d2062018-03-23 12:12:20 -050098 // image specific publickey file name.
Jayanth Othayoth70804dc2018-03-20 06:31:59 -050099 fs::path publicKeyFile(imageDirPath / PUBLICKEY_FILE_NAME);
100
101 // Validate the PNOR image file.
102 // Build Image File name
103 fs::path file(imageDirPath);
104 file /= squashFSImage;
105
106 // Build Signature File name
107 std::string fileName = file.filename();
108 fs::path sigFile(imageDirPath);
109 sigFile /= fileName + SIGNATURE_FILE_EXT;
110
111 // Verify the signature.
112 auto valid = verifyFile(file, sigFile, publicKeyFile, hashType);
113 if (valid == false)
114 {
115 log<level::ERR>("Image file Signature Validation failed",
Jayanth Othayoth5248f3c2018-03-28 11:04:14 -0500116 entry("IMAGE=%s", squashFSImage));
Jayanth Othayoth70804dc2018-03-20 06:31:59 -0500117 return false;
118 }
119
Gunnar Mills4c7d2062018-03-23 12:12:20 -0500120 log<level::DEBUG>("Successfully completed Signature vaildation.");
Jayanth Othayoth70804dc2018-03-20 06:31:59 -0500121
122 return true;
123 }
124 catch (const InternalFailure& e)
125 {
126 return false;
127 }
128 catch (const std::exception& e)
129 {
130 log<level::ERR>(e.what());
131 return false;
132 }
133}
134
135bool Signature::systemLevelVerify()
136{
137 // Get available key types from the system.
138 auto keyTypes = getAvailableKeyTypesFromSystem();
139 if (keyTypes.empty())
140 {
141 log<level::ERR>("Missing Signature configuration data in system");
142 elog<InternalFailure>();
143 }
144
145 // Build publickey and its signature file name.
146 fs::path pkeyFile(imageDirPath / PUBLICKEY_FILE_NAME);
147 fs::path pkeyFileSig(pkeyFile);
148 pkeyFileSig.replace_extension(SIGNATURE_FILE_EXT);
149
150 // Build manifest and its signature file name.
151 fs::path manifestFile(imageDirPath / MANIFEST_FILE);
152 fs::path manifestFileSig(manifestFile);
153 manifestFileSig.replace_extension(SIGNATURE_FILE_EXT);
154
155 auto valid = false;
156
157 // Verify the file signature with available key types
158 // public keys and hash function.
159 // For any internal failure during the key/hash pair specific
160 // validation, should continue the validation with next
161 // available Key/hash pair.
162 for (const auto& keyType : keyTypes)
163 {
164 auto keyHashPair = getKeyHashFileNames(keyType);
165 auto keyValues =
166 Version::getValue(keyHashPair.first, {{hashFunctionTag, " "}});
167 auto hashFunc = keyValues.at(hashFunctionTag);
168
169 try
170 {
171 // Verify manifest file signature
172 valid = verifyFile(manifestFile, manifestFileSig,
173 keyHashPair.second, hashFunc);
174 if (valid)
175 {
176 // Verify publickey file signature.
177 valid = verifyFile(pkeyFile, pkeyFileSig, keyHashPair.second,
178 hashFunc);
179 if (valid)
180 {
181 break;
182 }
183 }
184 }
185 catch (const InternalFailure& e)
186 {
187 valid = false;
188 }
189 }
190 return valid;
191}
192
193bool Signature::verifyFile(const fs::path& file, const fs::path& sigFile,
194 const fs::path& publicKey,
195 const std::string& hashFunc)
196{
197
198 // Check existence of the files in the system.
199 if (!(fs::exists(file) && fs::exists(sigFile)))
200 {
201 log<level::ERR>("Failed to find the Data or signature file.",
202 entry("FILE=%s", file.c_str()));
203 elog<InternalFailure>();
204 }
205
206 // Create RSA.
207 auto publicRSA = createPublicRSA(publicKey);
208 if (publicRSA == nullptr)
209 {
210 log<level::ERR>("Failed to create RSA",
211 entry("FILE=%s", publicKey.c_str()));
212 elog<InternalFailure>();
213 }
214
215 // Assign key to RSA.
216 EVP_PKEY_Ptr pKeyPtr(EVP_PKEY_new(), ::EVP_PKEY_free);
217 EVP_PKEY_assign_RSA(pKeyPtr.get(), publicRSA);
218
219 // Initializes a digest context.
220 EVP_MD_CTX_Ptr rsaVerifyCtx(EVP_MD_CTX_create(), ::EVP_MD_CTX_destroy);
221
222 // Adds all digest algorithms to the internal table
223 OpenSSL_add_all_digests();
224
225 // Create Hash structre.
226 auto hashStruct = EVP_get_digestbyname(hashFunc.c_str());
227 if (!hashStruct)
228 {
229 log<level::ERR>("EVP_get_digestbynam: Unknown message digest",
230 entry("HASH=%s", hashFunc.c_str()));
231 elog<InternalFailure>();
232 }
233
234 auto result = EVP_DigestVerifyInit(rsaVerifyCtx.get(), nullptr, hashStruct,
235 nullptr, pKeyPtr.get());
236
237 if (result <= 0)
238 {
Gunnar Mills4c7d2062018-03-23 12:12:20 -0500239 log<level::ERR>("Error occurred during EVP_DigestVerifyInit",
Jayanth Othayoth70804dc2018-03-20 06:31:59 -0500240 entry("ERRCODE=%lu", ERR_get_error()));
241 elog<InternalFailure>();
242 }
243
244 // Hash the data file and update the verification context
245 auto size = fs::file_size(file);
246 auto dataPtr = mapFile(file, size);
247
248 result = EVP_DigestVerifyUpdate(rsaVerifyCtx.get(), dataPtr(), size);
249 if (result <= 0)
250 {
Gunnar Mills4c7d2062018-03-23 12:12:20 -0500251 log<level::ERR>("Error occurred during EVP_DigestVerifyUpdate",
Jayanth Othayoth70804dc2018-03-20 06:31:59 -0500252 entry("ERRCODE=%lu", ERR_get_error()));
253 elog<InternalFailure>();
254 }
255
256 // Verify the data with signature.
257 size = fs::file_size(sigFile);
258 auto signature = mapFile(sigFile, size);
259
260 result = EVP_DigestVerifyFinal(
261 rsaVerifyCtx.get(), reinterpret_cast<unsigned char*>(signature()),
262 size);
263
264 // Check the verification result.
265 if (result < 0)
266 {
Gunnar Mills4c7d2062018-03-23 12:12:20 -0500267 log<level::ERR>("Error occurred during EVP_DigestVerifyFinal",
Jayanth Othayoth70804dc2018-03-20 06:31:59 -0500268 entry("ERRCODE=%lu", ERR_get_error()));
269 elog<InternalFailure>();
270 }
271
272 if (result == 0)
273 {
274 log<level::ERR>("EVP_DigestVerifyFinal:Signature validation failed",
275 entry("PATH=%s", sigFile.c_str()));
276 return false;
277 }
278 return true;
279}
280
281inline RSA* Signature::createPublicRSA(const fs::path& publicKey)
282{
283 RSA* rsa = nullptr;
284 auto size = fs::file_size(publicKey);
285
286 // Read public key file
287 auto data = mapFile(publicKey, size);
288
289 BIO_MEM_Ptr keyBio(BIO_new_mem_buf(data(), -1), &::BIO_free);
290 if (keyBio.get() == nullptr)
291 {
292 log<level::ERR>("Failed to create new BIO Memory buffer");
293 elog<InternalFailure>();
294 }
295
296 rsa = PEM_read_bio_RSA_PUBKEY(keyBio.get(), &rsa, nullptr, nullptr);
297
298 return rsa;
299}
300
301CustomMap Signature::mapFile(const fs::path& path, size_t size)
302{
303
304 CustomFd fd(open(path.c_str(), O_RDONLY));
305
306 return CustomMap(mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd(), 0),
307 size);
308}
309
310} // namespace image
311} // namespace software
312} // namespace openpower