summaryrefslogtreecommitdiff
path: root/src/manager/crypto/sw-backend/store.cpp
blob: b4fd718aaf9c94c01e23eea9a5454afe5f40c9f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/*
 *  Copyright (c) 2015 - 2018 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 */
/*
 * @file       store.cpp
 * @author     Bartłomiej Grzelewski (b.grzelewski@samsung.com)
 * @version    1.0
 */
#include <memory>

#include <openssl/rand.h>
#include <openssl/evp.h>

#include <generic-backend/exception.h>
#include <generic-backend/crypto-params.h>
#include <sw-backend/obj.h>
#include <sw-backend/store.h>
#include <sw-backend/internals.h>
#include <SWKeyFile.h>
#include <dpl/log/log.h>

#include <message-buffer.h>

namespace CKM {
namespace Crypto {
namespace SW {

namespace {

// internal SW encryption scheme flags
enum EncryptionScheme {
	NONE = 0,
	PASSWORD = 1 << 0
};

template <typename T, typename ...Args>
std::unique_ptr<T> make_unique(Args &&...args)
{
	return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

RawBuffer generateRandIV()
{
	RawBuffer civ(EVP_MAX_IV_LENGTH);

	if (1 != RAND_bytes(civ.data(), civ.size()))
		ThrowErr(Exc::Crypto::InternalError, "RAND_bytes failed to generate IV.");

	return civ;
}

RawBuffer passwordToKey(const Password &password, const RawBuffer &salt,
						size_t keySize)
{
	RawBuffer result(keySize);

	if (1 != PKCS5_PBKDF2_HMAC_SHA1(
				password.c_str(),
				password.size(),
				salt.data(),
				salt.size(),
				Params::DERIVED_KEY_ITERATIONS,
				result.size(),
				result.data()))
		ThrowErr(Exc::InternalError, "PCKS5_PKKDF2_HMAC_SHA1 failed.");

	return result;
}

RawBuffer unpack(const RawBuffer &packed, const Password &pass)
{
	MessageBuffer buffer;
	buffer.Push(packed);
	int encryptionScheme = 0;
	RawBuffer data;
	buffer.Deserialize(encryptionScheme, data);

	if (encryptionScheme == 0)
		return data;

	MessageBuffer internalBuffer;
	internalBuffer.Push(data);
	RawBuffer encrypted;
	RawBuffer iv;
	RawBuffer tag;

	// serialization exceptions will be catched as CKM::Exception and will cause
	// CKM_API_ERROR_SERVER_ERROR
	internalBuffer.Deserialize(encrypted, iv, tag);

	/*
	 * AES GCM will check data integrity and handle cases where:
	 * - wrong password is used
	 * - password is empty when it shouldn't be
	 * - password is not empty when it should be
	 */
	RawBuffer key = passwordToKey(pass, iv, Params::DERIVED_KEY_LENGTH);

	RawBuffer ret;

	try {
		ret = Crypto::SW::Internals::decryptDataAesGcm(key, encrypted, iv, tag);
	} catch (const Exc::Crypto::InputParam &e) {
		ThrowErr(Exc::AuthenticationFailed, "Decryption with custom password failed, authentication failed");
	} catch (const Exc::Exception &e) {
		ThrowErr(Exc::InternalError, "Decryption with custom password failed, internal error");
	}

	return ret;
}

RawBuffer pack(const RawBuffer &data, const Password &pass)
{
	int scheme = EncryptionScheme::NONE;
	RawBuffer packed = data;

	if (!pass.empty()) {
		RawBuffer iv = generateRandIV();
		RawBuffer key = passwordToKey(pass, iv, Params::DERIVED_KEY_LENGTH);

		std::pair<RawBuffer, RawBuffer> ret;

		try {
			ret = Crypto::SW::Internals::encryptDataAesGcm(key, data, iv,
					Params::DEFAULT_AES_GCM_TAG_LEN_BYTES);
		} catch (const Exc::Exception &e) {
			ThrowErr(Exc::InternalError, "Encryption with custom password failed, internal error");
		}

		scheme |= EncryptionScheme::PASSWORD;

		// serialization exceptions will be catched as CKM::Exception and will cause
		// CKM_API_ERROR_SERVER_ERROR
		packed = MessageBuffer::Serialize(ret.first, iv, ret.second).Pop();
	}

	// encryption scheme + internal buffer
	return MessageBuffer::Serialize(scheme, packed).Pop();
}

} // namespace anonymous

namespace {
const char *const DEVICE_KEY_XSD = RO_DATA_DIR "/sw_key.xsd";
const char *const DEVICE_KEY_SW_FILE = RW_DATA_DIR "/device_key.xml";
}

Store::Store(CryptoBackend backendId)
	: GStore(backendId)
{
	// get the device key if present
	InitialValues::SWKeyFile keyFile(DEVICE_KEY_SW_FILE);
	int rc = keyFile.Validate(DEVICE_KEY_XSD);

	if (rc == XML::Parser::PARSE_SUCCESS) {
		rc = keyFile.Parse();

		if (rc == XML::Parser::PARSE_SUCCESS)
			m_deviceKey = keyFile.getPrivKey();
		else
			// do nothing, bypass encrypted elements
			LogWarning("invalid SW key file: " << DEVICE_KEY_SW_FILE << ", parsing code: "
					   << rc);
	} else {
		LogWarning("invalid SW key file: " << DEVICE_KEY_SW_FILE <<
				   ", validation code: " << rc);
	}
}

GObjUPtr Store::getObject(const Token &token, const Password &pass)
{
	if (token.backendId != m_backendId)
		ThrowErr(Exc::Crypto::WrongBackend, "Decider choose wrong backend!");

	RawBuffer data = unpack(token.data, pass);

	if (token.dataType.isKeyPrivate() || token.dataType.isKeyPublic())
		return make_unique<AKey>(data, token.dataType);

	if (token.dataType == DataType(DataType::KEY_AES))
		return make_unique<SKey>(data, token.dataType);

	if (token.dataType.isCertificate() || token.dataType.isChainCert())
		return make_unique<Cert>(data, token.dataType);

	if (token.dataType.isBinaryData())
		return make_unique<BData>(data, token.dataType);

	ThrowErr(Exc::Crypto::DataTypeNotSupported,
			 "This type of data is not supported by openssl backend: ", (int)token.dataType);
}

TokenPair Store::generateAKey(const CryptoAlgorithm &algorithm,
							  const Password &prvPass,
							  const Password &pubPass)
{
	Internals::DataPair ret = Internals::generateAKey(algorithm);
	return std::make_pair<Token, Token>(
			   Token(m_backendId, ret.first.type, pack(ret.first.buffer, prvPass)),
			   Token(m_backendId, ret.second.type, pack(ret.second.buffer, pubPass)));
}

Token Store::generateSKey(const CryptoAlgorithm &algorithm,
						  const Password &pass)
{
	Internals::Data ret = Internals::generateSKey(algorithm);
	return Token(m_backendId, ret.type, pack(ret.buffer, pass));
}

Token Store::import(const Data &data, const Password &pass, const EncryptionParams &e)
{
	if (!e.iv.empty())
		ThrowErr(Exc::Crypto::OperationNotSupported,
			"Encrypted import is not yet supported on software backend!");

	return Token(m_backendId, data.type, pack(data.data, pass));
}

} // namespace SW
} // namespace Crypto
} // namespace CKM