summaryrefslogtreecommitdiffstats
path: root/task1/security.cpp
blob: d092be04a56feb6ae62e96ad00dfed773fa17e2b (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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/**
 * Wrapper for OpenSSL cryptographic functions.
 * @author SE/Linux Team <se-linux@inso.tuwien.ac.at>
 */

#include "security.h"

#include <errno.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <sstream>

#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>

//! Implementation of the Security interface.
//! We didn't put this declaration into the public header, beacause it 
//! contains OpenSSL related IMPLEMENTATION DETAILS.
class SecurityImpl : public Security {

    public:

	virtual void sign(
		const std::string& privateKeyFile,
		const ByteStream& data,
		ByteStream& output
		);

	virtual void verifySignature(
		const std::string& certificateFile,
		const ByteStream& data,
		const ByteStream& signature
		);

	virtual void encryptPublic(
		const std::string& certificateFile,
		const ByteStream& data,
		ByteStream& iv,
		ByteStream& ek,
		ByteStream& output
		);

	virtual void decryptPrivate(
		const std::string& privateKeyFile,
		const ByteStream& data,
		const ByteStream& iv,
		const ByteStream& ek,
		ByteStream& output
		);

	virtual std::string getCommonName(
		const std::string& certificateFile
		);

    private:

	//! Opens the given file.
	//! @throws SecurityException on error.
	FILE *openFile(const std::string& file);

	//! Throws an SecurityException containing the last OpenSSL error.
	void throwSslError();

	//! Reads a private key from the given file.
	//! @throws SecurityException on error.
	EVP_PKEY* readPrivKey(const std::string& file);

	//! Reads a public key from the given certificate file.
	//! @throws SecurityException on error.
	EVP_PKEY* readPubKey(const std::string& file);

	//! Reads a X509 certificate from the given certificate file.
	//! @throws SecurityException on error.
	X509 *readX509(const std::string& file);
};

// -----------------------------------------------------------------------------
// SecurityException
// -----------------------------------------------------------------------------

SecurityException::SecurityException(const std::string& what) :
    _what(what)
{
}

// -----------------------------------------------------------------------------
// Security
// -----------------------------------------------------------------------------

Security& Security::instance() {
    if (_instance == 0) {
	_instance = new SecurityImpl();
    }
    return *_instance;
}

Security *Security::_instance = 0;

// -----------------------------------------------------------------------------
// SecurityImpl
// -----------------------------------------------------------------------------

FILE *SecurityImpl::openFile(const std::string& file) {
    FILE *ret = fopen(file.c_str(), "r");
    if (ret == NULL) {
	std::ostringstream os;
	os << "Could not open file " << file << ": " << strerror(errno);
	throw SecurityException(os.str());
    }
    return ret;
}

void SecurityImpl::throwSslError() {
    ERR_print_errors_fp(stderr);
    throw SecurityException("ssl error");
}

EVP_PKEY* SecurityImpl::readPrivKey(const std::string& file) {
    FILE *f = NULL;
    EVP_PKEY *ret = NULL;

    f = openFile(file);
    ret = PEM_read_PrivateKey(f, NULL, NULL, NULL);
    fclose(f);

    if (! ret) {
	throwSslError();
    }

    return ret;
}

X509 *SecurityImpl::readX509(const std::string& file) {
    FILE *f = openFile(file);
    X509 *ret = PEM_read_X509(f, NULL, NULL, NULL);
    fclose(f);

    if (!ret) {
	throwSslError();
    }
    return ret;
}

void SecurityImpl::sign(
	const std::string& privateKeyFile,
	const ByteStream& data,
	ByteStream& output
	) {
    EVP_PKEY *priv = readPrivKey(privateKeyFile);
    EVP_MD_CTX ctx;

    EVP_SignInit(&ctx, EVP_sha1()); 
    EVP_SignUpdate(&ctx, &data[0], data.size());
    output.resize(EVP_PKEY_size(priv));
    unsigned int len = output.size();
    int err = EVP_SignFinal(&ctx, &output[0], &len, priv);

    EVP_PKEY_free(priv);	
    EVP_MD_CTX_cleanup(&ctx);

    if (err == 1) {
	output.resize(len);
    } else {
	throwSslError();
    }
}

void SecurityImpl::verifySignature(
	const std::string& certificateFile,
	const ByteStream& data,
	const ByteStream& signature
	) {
    X509 *x509 = readX509(certificateFile);
    EVP_PKEY *pub = X509_get_pubkey(x509);
    bool ok = true;
    int err;

    if (pub == NULL) {
	ok = false;
	goto failout;
    }

    EVP_MD_CTX ctx;
    EVP_VerifyInit(&ctx, EVP_sha1());
    EVP_VerifyUpdate(&ctx, &data[0], data.size());
    err = EVP_VerifyFinal(&ctx, const_cast<unsigned char *>(&signature[0]), signature.size(), pub);

    if (err != 1) {
	ok = false;
	goto failout;
    }

failout:

    if (pub) EVP_PKEY_free(pub);
    if (x509) X509_free(x509);
    if (! ok) throwSslError();
}

void SecurityImpl::encryptPublic(
	const std::string& certificateFile,
	const ByteStream& data,
	ByteStream& iv,
	ByteStream& ek,
	ByteStream& output
	) {
    X509 *x509 = readX509(certificateFile);
    EVP_PKEY *pub = X509_get_pubkey(x509);
    bool ok = true;
    int len, len2;

    const EVP_CIPHER *cipher = EVP_aes_256_cbc();
    EVP_CIPHER_CTX ctx;

    ek.resize(EVP_PKEY_size(pub));
    int ekl = ek.size();
    Byte *ek2 = &ek[0];

    iv.resize(EVP_CIPHER_iv_length(cipher));

    if (! EVP_SealInit(&ctx, cipher, &ek2, &ekl, &iv[0], &pub, 1)) {
	ok = false;
	goto failout;
    }

    ek.resize(ekl);

    output.resize(
	    data.size() + EVP_CIPHER_block_size(cipher) - 1 + // for update
	    EVP_CIPHER_block_size(cipher) // for final
	    );
    len = output.size();

    if (! EVP_SealUpdate(&ctx, &output[0], &len, &data[0], data.size())) {
	ok = false;
	goto failout;
    }
    len2 = output.size() - len;

    if (! EVP_SealFinal(&ctx, &output[len], &len2)) {
	ok = false;
	goto failout;
    }
    output.resize(len + len2);

failout:

    if (pub) EVP_PKEY_free(pub);
    if (x509) X509_free(x509);
    if (! ok) throwSslError();
}

void SecurityImpl::decryptPrivate(
	const std::string& privateKeyFile,
	const ByteStream& data,
	const ByteStream& iv,
	const ByteStream& ek,
	ByteStream& output
	) {
    EVP_PKEY *priv = readPrivKey(privateKeyFile);

    const EVP_CIPHER *cipher = EVP_aes_256_cbc();
    EVP_CIPHER_CTX ctx;
    int len, len2;
    bool ok = true;

    output.resize(data.size() + EVP_CIPHER_block_size(cipher));

    if (!EVP_OpenInit(
		&ctx, cipher, 
		const_cast<unsigned char *>(&ek[0]), ek.size(), 
		const_cast<unsigned char *>(&iv[0]), 
		priv
		)) {
	ok = false;
	goto failout;
    }
    if (!EVP_OpenUpdate(&ctx, &output[0], &len, &data[0], data.size())) {
	ok = false;
	goto failout;
    }
    if (!EVP_OpenFinal(&ctx, &output[len], &len2)) {
	ok = false;
	goto failout;
    }

    output.resize(len + len2);

failout:

    if (priv) EVP_PKEY_free(priv);
    if (!ok) throwSslError();
}

std::string SecurityImpl::getCommonName(
	const std::string& certificateFile
	) {
    X509 *x509 = readX509(certificateFile);
    X509_NAME *subj = 0;
    char data[256];
    bool ok = true;

    subj = X509_get_subject_name(x509);

    if (subj == 0) {
	ok = false;
	goto failout;
    }

    if (! X509_NAME_get_text_by_NID(subj, NID_commonName, data, sizeof(data))) {
	ok = false;
	goto failout;
    }

failout:

    X509_free(x509);

    if (!ok) {
	throwSslError();
    }
    return data;

}