1 /*
2  * Copyright (C) 2011-2018 Frank Morgner
3  *
4  * This file is part of OpenSC.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23 
24 #include "sm/sm-iso.h"
25 #include "libopensc/asn1.h"
26 #include "libopensc/log.h"
27 #include "libopensc/opensc.h"
28 #include "sm-eac.h"
29 #include "sslutil.h"
30 #include <stdlib.h>
31 #include <string.h>
32 
33 #ifdef ENABLE_OPENSSL
34 #include <openssl/evp.h>
35 #else
36 #define ssl_error(a)
37 #endif
38 
39 char eac_default_flags = 0;
40 #define ISO_MSE 0x22
41 
42 #if defined(ENABLE_OPENPACE)
43 #include <openssl/asn1t.h>
44 
45 #define ASN1_APP_IMP_OPT(stname, field, type, tag) ASN1_EX_TYPE(ASN1_TFLG_IMPTAG|ASN1_TFLG_APPLICATION|ASN1_TFLG_OPTIONAL, tag, stname, field, type)
46 #define ASN1_APP_IMP(stname, field, type, tag) ASN1_EX_TYPE(ASN1_TFLG_IMPTAG|ASN1_TFLG_APPLICATION, tag, stname, field, type)
47 
48 /* 0x67
49  * Auxiliary authenticated data */
50 ASN1_ITEM_TEMPLATE(ASN1_AUXILIARY_DATA) =
51 	ASN1_EX_TEMPLATE_TYPE(
52 			ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_IMPTAG|ASN1_TFLG_APPLICATION,
53 			7, AuxiliaryAuthenticatedData, CVC_DISCRETIONARY_DATA_TEMPLATE)
54 ASN1_ITEM_TEMPLATE_END(ASN1_AUXILIARY_DATA)
55 IMPLEMENT_ASN1_FUNCTIONS(ASN1_AUXILIARY_DATA)
56 #endif
57 
58 #if defined(ENABLE_OPENPACE) && defined(ENABLE_SM)
59 #include <eac/ca.h>
60 #include <eac/cv_cert.h>
61 #include <eac/eac.h>
62 #include <eac/pace.h>
63 #include <eac/ta.h>
64 #include <openssl/bio.h>
65 #include <openssl/buffer.h>
66 #include <openssl/err.h>
67 #include <openssl/evp.h>
68 #include <openssl/objects.h>
69 
70 
71 /*
72  * MSE:Set AT
73  */
74 
75 typedef struct {
76 	ASN1_OBJECT *cryptographic_mechanism_reference;
77 	ASN1_OCTET_STRING *key_reference1;
78 	ASN1_OCTET_STRING *key_reference2;
79 	ASN1_OCTET_STRING *eph_pub_key;
80 	ASN1_AUXILIARY_DATA *auxiliary_data;
81 	CVC_CHAT *chat;
82 } EAC_MSE_C;
83 /* Note that we can not use ASN1_AUXILIARY_DATA for the auxiliary_data element
84  * here. Due to limitations of OpenSSL it is not possible to *encode* an
85  * optional item template (such as auxiliary_data) in an other item template
86  * (such as ASN1_AUXILIARY_DATA). However, we can do
87  *
88  * EAC_MSE_C->auxiliary_data = d2i_ASN1_AUXILIARY_DATA(...)
89  *
90  * because they both use the same underlying struct.
91  *
92  * See also openssl/crypto/asn1/tasn_dec.c:183
93  */
94 ASN1_SEQUENCE(EAC_MSE_C) = {
95 	/* 0x80
96 	 * Cryptographic mechanism reference */
97 	ASN1_IMP_OPT(EAC_MSE_C, cryptographic_mechanism_reference, ASN1_OBJECT, 0),
98 	/* 0x83
99 	 * Reference of a public key / secret key */
100 	ASN1_IMP_OPT(EAC_MSE_C, key_reference1, ASN1_OCTET_STRING, 3),
101 	/* 0x84
102 	 * Reference of a private key / Reference for computing a session key */
103 	ASN1_IMP_OPT(EAC_MSE_C, key_reference2, ASN1_OCTET_STRING, 4),
104 	/* 0x91
105 	 * Ephemeral Public Key */
106 	ASN1_IMP_OPT(EAC_MSE_C, eph_pub_key, ASN1_OCTET_STRING, 0x11),
107 	/* 0x67
108 	 * Auxiliary authenticated data. See note above. */
109 	ASN1_APP_IMP_SEQUENCE_OF_OPT(EAC_MSE_C, auxiliary_data, CVC_DISCRETIONARY_DATA_TEMPLATE, 7),
110 	/* Certificate Holder Authorization Template */
111 	ASN1_OPT(EAC_MSE_C, chat, CVC_CHAT),
112 } ASN1_SEQUENCE_END(EAC_MSE_C)
113 DECLARE_ASN1_FUNCTIONS(EAC_MSE_C)
114 IMPLEMENT_ASN1_FUNCTIONS(EAC_MSE_C)
115 
116 
117 /*
118  * General Authenticate for PACE
119  */
120 
121 /* Protocol Command Data */
122 typedef struct {
123 	ASN1_OCTET_STRING *mapping_data;
124 	ASN1_OCTET_STRING *eph_pub_key;
125 	ASN1_OCTET_STRING *auth_token;
126 } EAC_GEN_AUTH_PACE_C_BODY;
127 ASN1_SEQUENCE(EAC_GEN_AUTH_PACE_C_BODY) = {
128 	/* 0x81
129 	 * Mapping Data */
130 	ASN1_IMP_OPT(EAC_GEN_AUTH_PACE_C_BODY, mapping_data, ASN1_OCTET_STRING, 1),
131 	/* 0x83
132 	 * Ephemeral Public Key */
133 	ASN1_IMP_OPT(EAC_GEN_AUTH_PACE_C_BODY, eph_pub_key, ASN1_OCTET_STRING, 3),
134 	/* 0x85
135 	 * Authentication Token */
136 	ASN1_IMP_OPT(EAC_GEN_AUTH_PACE_C_BODY, auth_token, ASN1_OCTET_STRING, 5),
137 } ASN1_SEQUENCE_END(EAC_GEN_AUTH_PACE_C_BODY)
138 DECLARE_ASN1_FUNCTIONS(EAC_GEN_AUTH_PACE_C_BODY)
139 IMPLEMENT_ASN1_FUNCTIONS(EAC_GEN_AUTH_PACE_C_BODY)
140 
141 typedef EAC_GEN_AUTH_PACE_C_BODY EAC_GEN_AUTH_PACE_C;
142 /* 0x7C
143  * Dynamic Authentication Data */
144 ASN1_ITEM_TEMPLATE(EAC_GEN_AUTH_PACE_C) =
145 	ASN1_EX_TEMPLATE_TYPE(
146 			ASN1_TFLG_IMPTAG|ASN1_TFLG_APPLICATION,
147 			0x1c, EAC_GEN_AUTH_PACE_C, EAC_GEN_AUTH_PACE_C_BODY)
148 ASN1_ITEM_TEMPLATE_END(EAC_GEN_AUTH_PACE_C)
149 DECLARE_ASN1_FUNCTIONS(EAC_GEN_AUTH_PACE_C)
150 IMPLEMENT_ASN1_FUNCTIONS(EAC_GEN_AUTH_PACE_C)
151 
152 /* Protocol Response Data */
153 typedef struct {
154 	ASN1_OCTET_STRING *enc_nonce;
155 	ASN1_OCTET_STRING *mapping_data;
156 	ASN1_OCTET_STRING *eph_pub_key;
157 	ASN1_OCTET_STRING *auth_token;
158 	ASN1_OCTET_STRING *cur_car;
159 	ASN1_OCTET_STRING *prev_car;
160 } EAC_GEN_AUTH_PACE_R_BODY;
161 ASN1_SEQUENCE(EAC_GEN_AUTH_PACE_R_BODY) = {
162 	/* 0x80
163 	 * Encrypted Nonce */
164 	ASN1_IMP_OPT(EAC_GEN_AUTH_PACE_R_BODY, enc_nonce, ASN1_OCTET_STRING, 0),
165 	/* 0x82
166 	 * Mapping Data */
167 	ASN1_IMP_OPT(EAC_GEN_AUTH_PACE_R_BODY, mapping_data, ASN1_OCTET_STRING, 2),
168 	/* 0x84
169 	 * Ephemeral Public Key */
170 	ASN1_IMP_OPT(EAC_GEN_AUTH_PACE_R_BODY, eph_pub_key, ASN1_OCTET_STRING, 4),
171 	/* 0x86
172 	 * Authentication Token */
173 	ASN1_IMP_OPT(EAC_GEN_AUTH_PACE_R_BODY, auth_token, ASN1_OCTET_STRING, 6),
174 	/* 0x87
175 	 * Most recent Certification Authority Reference */
176 	ASN1_IMP_OPT(EAC_GEN_AUTH_PACE_R_BODY, cur_car, ASN1_OCTET_STRING, 7),
177 	/* 0x88
178 	 * Previous Certification Authority Reference */
179 	ASN1_IMP_OPT(EAC_GEN_AUTH_PACE_R_BODY, prev_car, ASN1_OCTET_STRING, 8),
180 } ASN1_SEQUENCE_END(EAC_GEN_AUTH_PACE_R_BODY)
181 DECLARE_ASN1_FUNCTIONS(EAC_GEN_AUTH_PACE_R_BODY)
182 IMPLEMENT_ASN1_FUNCTIONS(EAC_GEN_AUTH_PACE_R_BODY)
183 
184 typedef EAC_GEN_AUTH_PACE_R_BODY EAC_GEN_AUTH_PACE_R;
185 /* 0x7C
186  * Dynamic Authentication Data */
187 ASN1_ITEM_TEMPLATE(EAC_GEN_AUTH_PACE_R) =
188 	ASN1_EX_TEMPLATE_TYPE(
189 			ASN1_TFLG_IMPTAG|ASN1_TFLG_APPLICATION,
190 			0x1c, EAC_GEN_AUTH_PACE_R, EAC_GEN_AUTH_PACE_R_BODY)
191 ASN1_ITEM_TEMPLATE_END(EAC_GEN_AUTH_PACE_R)
192 DECLARE_ASN1_FUNCTIONS(EAC_GEN_AUTH_PACE_R)
193 IMPLEMENT_ASN1_FUNCTIONS(EAC_GEN_AUTH_PACE_R)
194 
195 
196 /*
197  * General Authenticate for CA
198  */
199 
200 /* Protocol Command Data */
201 typedef struct eac_gen_auth_ca_cd_st {
202 	ASN1_OCTET_STRING *eph_pub_key;
203 } EAC_GEN_AUTH_CA_C_BODY;
204 ASN1_SEQUENCE(EAC_GEN_AUTH_CA_C_BODY) = {
205 	/* 0x80
206 	 * Ephemeral Public Key */
207 	ASN1_IMP_OPT(EAC_GEN_AUTH_CA_C_BODY, eph_pub_key, ASN1_OCTET_STRING, 0),
208 } ASN1_SEQUENCE_END(EAC_GEN_AUTH_CA_C_BODY)
209 DECLARE_ASN1_FUNCTIONS(EAC_GEN_AUTH_CA_C_BODY)
210 IMPLEMENT_ASN1_FUNCTIONS(EAC_GEN_AUTH_CA_C_BODY)
211 
212 typedef EAC_GEN_AUTH_CA_C_BODY EAC_GEN_AUTH_CA_C;
213 /* 0x7C
214  * Dynamic Authentication Data */
215 ASN1_ITEM_TEMPLATE(EAC_GEN_AUTH_CA_C) =
216 	ASN1_EX_TEMPLATE_TYPE(
217 			ASN1_TFLG_IMPTAG|ASN1_TFLG_APPLICATION,
218 			0x1c, EAC_GEN_AUTH_CA_C, EAC_GEN_AUTH_CA_C_BODY)
219 ASN1_ITEM_TEMPLATE_END(EAC_GEN_AUTH_CA_C)
220 DECLARE_ASN1_FUNCTIONS(EAC_GEN_AUTH_CA_C)
221 IMPLEMENT_ASN1_FUNCTIONS(EAC_GEN_AUTH_CA_C)
222 
223 /* Protocol Response Data */
224 typedef struct eac_gen_auth_ca_rapdu_body_st {
225 	ASN1_OCTET_STRING *nonce;
226 	ASN1_OCTET_STRING *auth_token;
227 } EAC_GEN_AUTH_CA_R_BODY;
228 ASN1_SEQUENCE(EAC_GEN_AUTH_CA_R_BODY) = {
229 	/* 0x81
230 	 * Nonce */
231 	ASN1_IMP_OPT(EAC_GEN_AUTH_CA_R_BODY, nonce, ASN1_OCTET_STRING, 1),
232 	/* 0x82
233 	 * Authentication Token */
234 	ASN1_IMP_OPT(EAC_GEN_AUTH_CA_R_BODY, auth_token, ASN1_OCTET_STRING, 2),
235 } ASN1_SEQUENCE_END(EAC_GEN_AUTH_CA_R_BODY)
236 DECLARE_ASN1_FUNCTIONS(EAC_GEN_AUTH_CA_R_BODY)
237 IMPLEMENT_ASN1_FUNCTIONS(EAC_GEN_AUTH_CA_R_BODY)
238 
239 typedef EAC_GEN_AUTH_CA_R_BODY EAC_GEN_AUTH_CA_R;
240 /* 0x7C
241  * Dynamic Authentication Data */
242 ASN1_ITEM_TEMPLATE(EAC_GEN_AUTH_CA_R) =
243 	ASN1_EX_TEMPLATE_TYPE(
244 			ASN1_TFLG_IMPTAG|ASN1_TFLG_APPLICATION,
245 			0x1c, EAC_GEN_AUTH_CA_R, EAC_GEN_AUTH_CA_R_BODY)
246 ASN1_ITEM_TEMPLATE_END(EAC_GEN_AUTH_CA_R)
247 DECLARE_ASN1_FUNCTIONS(EAC_GEN_AUTH_CA_R)
248 IMPLEMENT_ASN1_FUNCTIONS(EAC_GEN_AUTH_CA_R)
249 
250 
251 
252 /** @brief NPA secure messaging context */
253 struct eac_sm_ctx {
254 	/** @brief EAC context */
255 	EAC_CTX *ctx;
256 	/** @brief Certificate Description given on initialization of PACE */
257 	BUF_MEM *certificate_description;
258 	/** @brief picc's compressed ephemeral public key of PACE */
259 	BUF_MEM *id_icc;
260 	/** @brief PCD's compressed ephemeral public key of CA */
261 	BUF_MEM *eph_pub_key;
262 	/** @brief Auxiliary Data */
263 	BUF_MEM *auxiliary_data;
264 	char flags;
265 };
266 
267 
268 /* included in OpenPACE, but not propagated */
269 extern BUF_MEM *BUF_MEM_create(size_t len);
270 extern BUF_MEM *BUF_MEM_create_init(const void *buf, size_t len);
271 
272 
273 static int eac_sm_encrypt(sc_card_t *card, const struct iso_sm_ctx *ctx,
274 		const u8 *data, size_t datalen, u8 **enc);
275 static int eac_sm_decrypt(sc_card_t *card, const struct iso_sm_ctx *ctx,
276 		const u8 *enc, size_t enclen, u8 **data);
277 static int eac_sm_authenticate(sc_card_t *card, const struct iso_sm_ctx *ctx,
278 		const u8 *data, size_t datalen, u8 **outdata);
279 static int eac_sm_verify_authentication(sc_card_t *card, const struct iso_sm_ctx *ctx,
280 		const u8 *mac, size_t maclen,
281 		const u8 *macdata, size_t macdatalen);
282 static int eac_sm_pre_transmit(sc_card_t *card, const struct iso_sm_ctx *ctx,
283 		sc_apdu_t *apdu);
284 static int eac_sm_post_transmit(sc_card_t *card, const struct iso_sm_ctx *ctx,
285 		sc_apdu_t *sm_apdu);
286 static int eac_sm_finish(sc_card_t *card, const struct iso_sm_ctx *ctx,
287 		sc_apdu_t *apdu);
288 static void eac_sm_clear_free(const struct iso_sm_ctx *ctx);
289 
290 
291 
292 
293 static struct eac_sm_ctx *
eac_sm_ctx_create(EAC_CTX * ctx,const unsigned char * certificate_description,size_t certificate_description_length,const unsigned char * id_icc,size_t id_icc_length)294 eac_sm_ctx_create(EAC_CTX *ctx, const unsigned char *certificate_description,
295 		size_t certificate_description_length,
296 		const unsigned char *id_icc, size_t id_icc_length)
297 {
298 	struct eac_sm_ctx *out = malloc(sizeof *out);
299 	if (!out)
300 		goto err;
301 
302 	out->ctx = ctx;
303 
304 	if (certificate_description && certificate_description_length) {
305 		out->certificate_description =
306 			BUF_MEM_create_init(certificate_description,
307 					certificate_description_length);
308 		if (!out->certificate_description)
309 			goto err;
310 	} else
311 		out->certificate_description = NULL;
312 
313 	if (id_icc && id_icc_length) {
314 		out->id_icc = BUF_MEM_create_init(id_icc, id_icc_length);
315 		if (!out->id_icc)
316 			goto err;
317 	} else
318 		out->id_icc = NULL;
319 
320 	out->eph_pub_key = NULL;
321 	out->auxiliary_data = NULL;
322 
323 	out->flags = eac_default_flags;
324 	if (out->flags & EAC_FLAG_DISABLE_CHECK_TA)
325 		TA_disable_checks(out->ctx);
326 	if (out->flags & EAC_FLAG_DISABLE_CHECK_CA)
327 		CA_disable_passive_authentication(out->ctx);
328 
329 	return out;
330 
331 err:
332 	free(out);
333 	return NULL;
334 }
335 
336 static int
eac_sm_start(sc_card_t * card,EAC_CTX * eac_ctx,const unsigned char * certificate_description,size_t certificate_description_length,const unsigned char * id_icc,size_t id_icc_length)337 eac_sm_start(sc_card_t *card, EAC_CTX *eac_ctx,
338 		const unsigned char *certificate_description,
339 		size_t certificate_description_length,
340 		const unsigned char *id_icc, size_t id_icc_length)
341 {
342 	int r;
343 	struct iso_sm_ctx *sctx = NULL;
344 
345 	if (!eac_ctx || !eac_ctx->key_ctx) {
346 		r = SC_ERROR_INVALID_ARGUMENTS;
347 		goto err;
348 	}
349 
350 	sctx = iso_sm_ctx_create();
351 	if (!sctx) {
352 		r = SC_ERROR_OUT_OF_MEMORY;
353 		goto err;
354 	}
355 
356 	sctx->priv_data = eac_sm_ctx_create(eac_ctx,
357 			certificate_description, certificate_description_length,
358 			id_icc, id_icc_length);
359 	if (!sctx->priv_data) {
360 		r = SC_ERROR_OUT_OF_MEMORY;
361 		goto err;
362 	}
363 
364 	sctx->authenticate = eac_sm_authenticate;
365 	sctx->encrypt = eac_sm_encrypt;
366 	sctx->decrypt = eac_sm_decrypt;
367 	sctx->verify_authentication = eac_sm_verify_authentication;
368 	sctx->pre_transmit = eac_sm_pre_transmit;
369 	sctx->post_transmit = eac_sm_post_transmit;
370 	sctx->finish = eac_sm_finish;
371 	sctx->clear_free = eac_sm_clear_free;
372 	sctx->padding_indicator = SM_ISO_PADDING;
373 	sctx->block_length = EVP_CIPHER_block_size(eac_ctx->key_ctx->cipher);
374 
375 	r = iso_sm_start(card, sctx);
376 
377 err:
378 	if (r < 0)
379 		iso_sm_ctx_clear_free(sctx);
380 
381 	return r;
382 }
383 
get_ef_card_access(sc_card_t * card,u8 ** ef_cardaccess,size_t * length_ef_cardaccess)384 static int get_ef_card_access(sc_card_t *card,
385 		u8 **ef_cardaccess, size_t *length_ef_cardaccess)
386 {
387 	return iso7816_read_binary_sfid(card, SFID_EF_CARDACCESS, ef_cardaccess, length_ef_cardaccess);
388 }
389 
format_mse_cdata(struct sc_context * ctx,int protocol,const unsigned char * key_reference1,size_t key_reference1_len,const unsigned char * key_reference2,size_t key_reference2_len,const unsigned char * eph_pub_key,size_t eph_pub_key_len,const unsigned char * auxiliary_data,size_t auxiliary_data_len,const CVC_CHAT * chat,unsigned char ** cdata)390 static int format_mse_cdata(struct sc_context *ctx, int protocol,
391 		const unsigned char *key_reference1, size_t key_reference1_len,
392 		const unsigned char *key_reference2, size_t key_reference2_len,
393 		const unsigned char *eph_pub_key, size_t eph_pub_key_len,
394 		const unsigned char *auxiliary_data, size_t auxiliary_data_len,
395 		const CVC_CHAT *chat, unsigned char **cdata)
396 {
397 	EAC_MSE_C *data = NULL;
398 	unsigned char *data_sequence = NULL;
399 	const unsigned char *data_no_sequence;
400 	unsigned char *p;
401 	long length;
402 	int r, class, tag;
403 
404 	if (!cdata) {
405 		r = SC_ERROR_INVALID_ARGUMENTS;
406 		goto err;
407 	}
408 
409 	data = EAC_MSE_C_new();
410 	if (!data) {
411 		ssl_error(ctx);
412 		r = SC_ERROR_INTERNAL;
413 		goto err;
414 	}
415 
416 	if (protocol) {
417 		data->cryptographic_mechanism_reference = OBJ_nid2obj(protocol);
418 		if (!data->cryptographic_mechanism_reference) {
419 			sc_debug(ctx, SC_LOG_DEBUG_VERBOSE, "Error setting Cryptographic mechanism reference of MSE:Set AT data");
420 			r = SC_ERROR_INTERNAL;
421 			goto err;
422 		}
423 	}
424 
425 	if (key_reference1 && key_reference1_len) {
426 		data->key_reference1 = ASN1_OCTET_STRING_new();
427 		if (!data->key_reference1
428 				|| !ASN1_OCTET_STRING_set(
429 					data->key_reference1, key_reference1, key_reference1_len)) {
430 			sc_debug(ctx, SC_LOG_DEBUG_VERBOSE, "Error setting key reference 1 of MSE:Set AT data");
431 			r = SC_ERROR_INTERNAL;
432 			goto err;
433 		}
434 	}
435 
436 	if (key_reference2 && key_reference2_len) {
437 		data->key_reference2 = ASN1_OCTET_STRING_new();
438 		if (!data->key_reference2
439 				|| !ASN1_OCTET_STRING_set(
440 					data->key_reference2, key_reference2, key_reference2_len)) {
441 			sc_debug(ctx, SC_LOG_DEBUG_VERBOSE, "Error setting key reference 2 of MSE:Set AT data");
442 			r = SC_ERROR_INTERNAL;
443 			goto err;
444 		}
445 	}
446 
447 	if (eph_pub_key && eph_pub_key_len) {
448 		data->eph_pub_key = ASN1_OCTET_STRING_new();
449 		if (!data->eph_pub_key
450 				|| !ASN1_OCTET_STRING_set(
451 					data->eph_pub_key, eph_pub_key, eph_pub_key_len)) {
452 			sc_debug(ctx, SC_LOG_DEBUG_VERBOSE, "Error setting ephemeral Public Key of MSE:Set AT data");
453 			r = SC_ERROR_INTERNAL;
454 			goto err;
455 		}
456 	}
457 
458 	if (auxiliary_data && auxiliary_data_len) {
459 		if (!d2i_ASN1_AUXILIARY_DATA(&data->auxiliary_data, &auxiliary_data, auxiliary_data_len)) {
460 			sc_debug(ctx, SC_LOG_DEBUG_VERBOSE, "Error setting authenticated auxiliary data of MSE:Set AT data");
461 			ssl_error(ctx);
462 			r = SC_ERROR_INTERNAL;
463 			goto err;
464 		}
465 	}
466 
467 	data->chat = (CVC_CHAT *) chat;
468 
469 
470 	length = i2d_EAC_MSE_C(data, &data_sequence);
471 	data_no_sequence = data_sequence;
472 	if (length < 0
473 			|| (0x80 & ASN1_get_object(&data_no_sequence, &length, &tag, &class, length))) {
474 		sc_debug(ctx, SC_LOG_DEBUG_VERBOSE, "Error encoding MSE:Set AT APDU data");
475 		ssl_error(ctx);
476 		r = SC_ERROR_INTERNAL;
477 		goto err;
478 	}
479 	if (length <= 0) {
480 		r = SC_ERROR_INTERNAL;
481 		goto err;
482 	}
483 	sc_debug_hex(ctx, SC_LOG_DEBUG_SM, "MSE command data", data_no_sequence, length);
484 
485 
486 	p = realloc(*cdata, length);
487 	if (!p) {
488 		r = SC_ERROR_OUT_OF_MEMORY;
489 		goto err;
490 	}
491 	memcpy(p, data_no_sequence, length);
492 	*cdata = p;
493 	r = length;
494 
495 err:
496 	if (data) {
497 		/* do not free the functions parameter chat */
498 		data->chat = NULL;
499 		EAC_MSE_C_free(data);
500 	}
501 	OPENSSL_free(data_sequence);
502 
503 	return r;
504 }
505 
eac_mse(sc_card_t * card,unsigned char p1,unsigned char p2,int protocol,const unsigned char * key_reference1,size_t key_reference1_len,const unsigned char * key_reference2,size_t key_reference2_len,const unsigned char * eph_pub_key,size_t eph_pub_key_len,const unsigned char * auxiliary_data,size_t auxiliary_data_len,const CVC_CHAT * chat,u8 * sw1,u8 * sw2)506 static int eac_mse(sc_card_t *card,
507 		unsigned char p1, unsigned char p2, int protocol,
508 		const unsigned char *key_reference1, size_t key_reference1_len,
509 		const unsigned char *key_reference2, size_t key_reference2_len,
510 		const unsigned char *eph_pub_key, size_t eph_pub_key_len,
511 		const unsigned char *auxiliary_data, size_t auxiliary_data_len,
512 		const CVC_CHAT *chat, u8 *sw1, u8 *sw2)
513 {
514 	sc_apdu_t apdu;
515 	unsigned char *d = NULL;
516 	int r;
517 
518 	if (!card) {
519 		r = SC_ERROR_INVALID_ARGUMENTS;
520 		goto err;
521 	}
522 
523 	r = format_mse_cdata(card->ctx, protocol, key_reference1,
524 			key_reference1_len, key_reference2, key_reference2_len,
525 			eph_pub_key, eph_pub_key_len, auxiliary_data, auxiliary_data_len,
526 			chat, &d);
527 	if (r < 0)
528 		goto err;
529 	sc_format_apdu_ex(&apdu, 0x00, ISO_MSE, p1, p2,
530 			d, r, NULL, 0);
531 
532 	r = sc_transmit_apdu(card, &apdu);
533 	if (r < 0)
534 		goto err;
535 
536 	if (apdu.resplen) {
537 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "MSE:Set AT response data should be empty "
538 				"(contains %"SC_FORMAT_LEN_SIZE_T"u bytes)", apdu.resplen);
539 		r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
540 		goto err;
541 	}
542 
543 	if (sw1)
544 		*sw1 = apdu.sw1;
545 	if (sw2)
546 		*sw2 = apdu.sw2;
547 
548 err:
549 	free(d);
550 
551 	return r;
552 }
553 
eac_mse_set_at(sc_card_t * card,unsigned char p1,int protocol,const unsigned char * key_reference1,size_t key_reference1_len,const unsigned char * key_reference2,size_t key_reference2_len,const unsigned char * eph_pub_key,size_t eph_pub_key_len,const unsigned char * auxiliary_data,size_t auxiliary_data_len,const CVC_CHAT * chat,u8 * sw1,u8 * sw2)554 static int eac_mse_set_at(sc_card_t *card, unsigned char p1, int protocol,
555 		const unsigned char *key_reference1, size_t key_reference1_len,
556 		const unsigned char *key_reference2, size_t key_reference2_len,
557 		const unsigned char *eph_pub_key, size_t eph_pub_key_len,
558 		const unsigned char *auxiliary_data, size_t auxiliary_data_len,
559 		const CVC_CHAT *chat, u8 *sw1, u8 *sw2)
560 {
561 	return eac_mse(card, p1, 0xA4, protocol, key_reference1,
562 			key_reference1_len, key_reference2, key_reference2_len,
563 			eph_pub_key, eph_pub_key_len, auxiliary_data, auxiliary_data_len,
564 			chat, sw1, sw2);
565 }
566 
eac_mse_set_at_pace(sc_card_t * card,int protocol,enum s_type secret_key,const CVC_CHAT * chat,u8 * sw1,u8 * sw2)567 static int eac_mse_set_at_pace(sc_card_t *card, int protocol,
568 		enum s_type secret_key, const CVC_CHAT *chat, u8 *sw1, u8 *sw2)
569 {
570 	int r, tries;
571 	unsigned char key = secret_key;
572 
573 	r = eac_mse_set_at(card, 0xC1, protocol, &key, sizeof key, NULL,
574 			0, NULL, 0, NULL, 0, chat, sw1, sw2);
575 	if (0 > r)
576 		goto err;
577 
578 	if (*sw1 == 0x63) {
579 		if ((*sw2 & 0xc0) == 0xc0) {
580 			tries = *sw2 & 0x0f;
581 			if (tries <= 1) {
582 				/* this is only a warning... */
583 				sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Remaining tries: %d (%s must be %s)\n",
584 						tries, eac_secret_name(secret_key),
585 						tries ? "resumed" : "unblocked");
586 			}
587 			r = SC_SUCCESS;
588 		} else {
589 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Unknown status bytes: SW1=%02X, SW2=%02X\n",
590 					*sw1, *sw2);
591 			r = SC_ERROR_CARD_CMD_FAILED;
592 		}
593 	} else if (*sw1 == 0x62 && *sw2 == 0x83) {
594 			 sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Password is deactivated\n");
595 			 r = SC_ERROR_AUTH_METHOD_BLOCKED;
596 	} else {
597 		r = sc_check_sw(card, *sw1, *sw2);
598 	}
599 
600 err:
601 	return r;
602 }
603 
604 
605 #define ISO_GENERAL_AUTHENTICATE 0x86
606 #define ISO_COMMAND_CHAINING 0x10
eac_gen_auth_1_encrypted_nonce(sc_card_t * card,u8 ** enc_nonce,size_t * enc_nonce_len)607 static int eac_gen_auth_1_encrypted_nonce(sc_card_t *card,
608 		u8 **enc_nonce, size_t *enc_nonce_len)
609 {
610 	sc_apdu_t apdu;
611 	EAC_GEN_AUTH_PACE_C *c_data = NULL;
612 	EAC_GEN_AUTH_PACE_R *r_data = NULL;
613 	unsigned char *d = NULL, *p;
614 	int r, l;
615 	unsigned char resp[SC_MAX_APDU_RESP_SIZE];
616 
617 	c_data = EAC_GEN_AUTH_PACE_C_new();
618 	if (!c_data) {
619 		r = SC_ERROR_OUT_OF_MEMORY;
620 		goto err;
621 	}
622 	r = i2d_EAC_GEN_AUTH_PACE_C(c_data, &d);
623 	if (r < 0) {
624 		ssl_error(card->ctx);
625 		r = SC_ERROR_INTERNAL;
626 		goto err;
627 	}
628 
629 	sc_format_apdu_ex(&apdu, 0x00, ISO_GENERAL_AUTHENTICATE, 0x00, 0x00,
630 			d, r, resp, sizeof resp);
631 	apdu.cla = ISO_COMMAND_CHAINING;
632 
633 	sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "General authenticate (Encrypted Nonce) command data", apdu.data, apdu.datalen);
634 
635 	r = sc_transmit_apdu(card, &apdu);
636 	if (r < 0)
637 		goto err;
638 
639 	r = sc_check_sw(card, apdu.sw1, apdu.sw2);
640 	if (r < 0)
641 		goto err;
642 
643 	sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "General authenticate (Encrypted Nonce) response data", apdu.resp, apdu.resplen);
644 
645 	if (!d2i_EAC_GEN_AUTH_PACE_R(&r_data,
646 				(const unsigned char **) &apdu.resp, apdu.resplen)) {
647 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not parse general authenticate response data.");
648 		ssl_error(card->ctx);
649 		r = SC_ERROR_INTERNAL;
650 		goto err;
651 	}
652 
653 	if (!r_data->enc_nonce
654 			|| r_data->mapping_data
655 			|| r_data->eph_pub_key
656 			|| r_data->auth_token
657 			|| r_data->cur_car
658 			|| r_data->prev_car) {
659 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Response data of general authenticate for "
660 				"step 1 should (only) contain the encrypted nonce.");
661 		r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
662 		goto err;
663 	}
664 	p = r_data->enc_nonce->data;
665 	l = r_data->enc_nonce->length;
666 
667 	*enc_nonce = malloc(l);
668 	if (!*enc_nonce) {
669 		r = SC_ERROR_OUT_OF_MEMORY;
670 		goto err;
671 	}
672 	/* Flawfinder: ignore */
673 	memcpy(*enc_nonce, p, l);
674 	*enc_nonce_len = l;
675 
676 err:
677 	if (c_data)
678 		EAC_GEN_AUTH_PACE_C_free(c_data);
679 	OPENSSL_free(d);
680 	if (r_data)
681 		EAC_GEN_AUTH_PACE_R_free(r_data);
682 
683 	return r;
684 }
eac_gen_auth_2_map_nonce(sc_card_t * card,const u8 * in,size_t in_len,u8 ** map_data_out,size_t * map_data_out_len)685 static int eac_gen_auth_2_map_nonce(sc_card_t *card,
686 		const u8 *in, size_t in_len,
687 		u8 **map_data_out, size_t *map_data_out_len)
688 {
689 	sc_apdu_t apdu;
690 	EAC_GEN_AUTH_PACE_C *c_data = NULL;
691 	EAC_GEN_AUTH_PACE_R *r_data = NULL;
692 	unsigned char *d = NULL, *p;
693 	int r, l;
694 	unsigned char resp[SC_MAX_APDU_RESP_SIZE];
695 
696 	c_data = EAC_GEN_AUTH_PACE_C_new();
697 	if (!c_data) {
698 		r = SC_ERROR_OUT_OF_MEMORY;
699 		goto err;
700 	}
701 	c_data->mapping_data = ASN1_OCTET_STRING_new();
702 	if (!c_data->mapping_data
703 			|| !ASN1_OCTET_STRING_set(
704 				c_data->mapping_data, in, in_len)) {
705 		ssl_error(card->ctx);
706 		r = SC_ERROR_INTERNAL;
707 		goto err;
708 	}
709 	r = i2d_EAC_GEN_AUTH_PACE_C(c_data, &d);
710 	if (r < 0) {
711 		ssl_error(card->ctx);
712 		r = SC_ERROR_INTERNAL;
713 		goto err;
714 	}
715 	sc_format_apdu_ex(&apdu, 0x00, ISO_GENERAL_AUTHENTICATE, 0x00, 0x00,
716 		   	d, r, resp, sizeof resp);
717 	apdu.cla = ISO_COMMAND_CHAINING;
718 
719 	sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "General authenticate (Map Nonce) command data", apdu.data, apdu.datalen);
720 
721 	r = sc_transmit_apdu(card, &apdu);
722 	if (r < 0)
723 		goto err;
724 
725 	r = sc_check_sw(card, apdu.sw1, apdu.sw2);
726 	if (r < 0)
727 		goto err;
728 
729 	sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "General authenticate (Map Nonce) response data", apdu.resp, apdu.resplen);
730 
731 	if (!d2i_EAC_GEN_AUTH_PACE_R(&r_data,
732 				(const unsigned char **) &apdu.resp, apdu.resplen)) {
733 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not parse general authenticate response data.");
734 		ssl_error(card->ctx);
735 		r = SC_ERROR_INTERNAL;
736 		goto err;
737 	}
738 
739 	if (r_data->enc_nonce
740 			|| !r_data->mapping_data
741 			|| r_data->eph_pub_key
742 			|| r_data->auth_token
743 			|| r_data->cur_car
744 			|| r_data->prev_car) {
745 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Response data of general authenticate for "
746 				"step 2 should (only) contain the mapping data.");
747 		r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
748 		goto err;
749 	}
750 	p = r_data->mapping_data->data;
751 	l = r_data->mapping_data->length;
752 
753 	*map_data_out = malloc(l);
754 	if (!*map_data_out) {
755 		r = SC_ERROR_OUT_OF_MEMORY;
756 		goto err;
757 	}
758 	/* Flawfinder: ignore */
759 	memcpy(*map_data_out, p, l);
760 	*map_data_out_len = l;
761 
762 err:
763 	if (c_data)
764 		EAC_GEN_AUTH_PACE_C_free(c_data);
765 	OPENSSL_free(d);
766 	if (r_data)
767 		EAC_GEN_AUTH_PACE_R_free(r_data);
768 
769 	return r;
770 }
eac_gen_auth_3_perform_key_agreement(sc_card_t * card,const u8 * in,size_t in_len,u8 ** eph_pub_key_out,size_t * eph_pub_key_out_len)771 static int eac_gen_auth_3_perform_key_agreement(sc_card_t *card,
772 		const u8 *in, size_t in_len,
773 		u8 **eph_pub_key_out, size_t *eph_pub_key_out_len)
774 {
775 	sc_apdu_t apdu;
776 	EAC_GEN_AUTH_PACE_C *c_data = NULL;
777 	EAC_GEN_AUTH_PACE_R *r_data = NULL;
778 	unsigned char *d = NULL, *p;
779 	int r, l;
780 	unsigned char resp[SC_MAX_APDU_RESP_SIZE];
781 
782 	c_data = EAC_GEN_AUTH_PACE_C_new();
783 	if (!c_data) {
784 		r = SC_ERROR_OUT_OF_MEMORY;
785 		goto err;
786 	}
787 	c_data->eph_pub_key = ASN1_OCTET_STRING_new();
788 	if (!c_data->eph_pub_key
789 			|| !ASN1_OCTET_STRING_set(
790 				c_data->eph_pub_key, in, in_len)) {
791 		ssl_error(card->ctx);
792 		r = SC_ERROR_INTERNAL;
793 		goto err;
794 	}
795 	r = i2d_EAC_GEN_AUTH_PACE_C(c_data, &d);
796 	if (r < 0) {
797 		ssl_error(card->ctx);
798 		r = SC_ERROR_INTERNAL;
799 		goto err;
800 	}
801 	sc_format_apdu_ex(&apdu, 0x00, ISO_GENERAL_AUTHENTICATE, 0x00, 0x00,
802 			d, r, resp, sizeof resp);
803 	apdu.cla = ISO_COMMAND_CHAINING;
804 
805 	sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "General authenticate (Perform Key Agreement) command data", apdu.data, apdu.datalen);
806 
807 	r = sc_transmit_apdu(card, &apdu);
808 	if (r < 0)
809 		goto err;
810 
811 	r = sc_check_sw(card, apdu.sw1, apdu.sw2);
812 	if (r < 0)
813 		goto err;
814 
815 	sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "General authenticate (Perform Key Agreement) response data", apdu.resp, apdu.resplen);
816 
817 	if (!d2i_EAC_GEN_AUTH_PACE_R(&r_data,
818 				(const unsigned char **) &apdu.resp, apdu.resplen)) {
819 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not parse general authenticate response data.");
820 		ssl_error(card->ctx);
821 		r = SC_ERROR_INTERNAL;
822 		goto err;
823 	}
824 
825 	if (r_data->enc_nonce
826 			|| r_data->mapping_data
827 			|| !r_data->eph_pub_key
828 			|| r_data->auth_token
829 			|| r_data->cur_car
830 			|| r_data->prev_car) {
831 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Response data of general authenticate for "
832 				"step 3 should (only) contain the ephemeral public key.");
833 		r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
834 		goto err;
835 	}
836 	p = r_data->eph_pub_key->data;
837 	l = r_data->eph_pub_key->length;
838 
839 	*eph_pub_key_out = malloc(l);
840 	if (!*eph_pub_key_out) {
841 		r = SC_ERROR_OUT_OF_MEMORY;
842 		goto err;
843 	}
844 	/* Flawfinder: ignore */
845 	memcpy(*eph_pub_key_out, p, l);
846 	*eph_pub_key_out_len = l;
847 
848 err:
849 	if (c_data)
850 		EAC_GEN_AUTH_PACE_C_free(c_data);
851 	OPENSSL_free(d);
852 	if (r_data)
853 		EAC_GEN_AUTH_PACE_R_free(r_data);
854 
855 	return r;
856 }
eac_gen_auth_4_mutual_authentication(sc_card_t * card,const u8 * in,size_t in_len,u8 ** auth_token_out,size_t * auth_token_out_len,u8 ** recent_car,size_t * recent_car_len,u8 ** prev_car,size_t * prev_car_len)857 static int eac_gen_auth_4_mutual_authentication(sc_card_t *card,
858 		const u8 *in, size_t in_len,
859 		u8 **auth_token_out, size_t *auth_token_out_len,
860 		u8 **recent_car, size_t *recent_car_len,
861 		u8 **prev_car, size_t *prev_car_len)
862 {
863 	sc_apdu_t apdu;
864 	EAC_GEN_AUTH_PACE_C *c_data = NULL;
865 	EAC_GEN_AUTH_PACE_R *r_data = NULL;
866 	unsigned char *d = NULL, *p;
867 	int r, l;
868 	unsigned char resp[SC_MAX_APDU_RESP_SIZE];
869 
870 	c_data = EAC_GEN_AUTH_PACE_C_new();
871 	if (!c_data) {
872 		r = SC_ERROR_OUT_OF_MEMORY;
873 		goto err;
874 	}
875 	c_data->auth_token = ASN1_OCTET_STRING_new();
876 	if (!c_data->auth_token
877 			|| !ASN1_OCTET_STRING_set(
878 				c_data->auth_token, in, in_len)) {
879 		ssl_error(card->ctx);
880 		r = SC_ERROR_INTERNAL;
881 		goto err;
882 	}
883 	r = i2d_EAC_GEN_AUTH_PACE_C(c_data, &d);
884 	if (r < 0) {
885 		ssl_error(card->ctx);
886 		r = SC_ERROR_INTERNAL;
887 		goto err;
888 	}
889 
890 	sc_format_apdu_ex(&apdu, 0x00, ISO_GENERAL_AUTHENTICATE, 0x00, 0x00,
891 			d, r, resp, sizeof resp);
892 
893 	sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "General authenticate (Perform Key Agreement) command data", apdu.data, apdu.datalen);
894 
895 	r = sc_transmit_apdu(card, &apdu);
896 	if (r < 0)
897 		goto err;
898 
899 	r = sc_check_sw(card, apdu.sw1, apdu.sw2);
900 	if (r < 0)
901 		goto err;
902 
903 	sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "General authenticate (Perform Key Agreement) response data", apdu.resp, apdu.resplen);
904 
905 	if (!d2i_EAC_GEN_AUTH_PACE_R(&r_data,
906 				(const unsigned char **) &apdu.resp, apdu.resplen)) {
907 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not parse general authenticate response data.");
908 		ssl_error(card->ctx);
909 		r = SC_ERROR_INTERNAL;
910 		goto err;
911 	}
912 
913 	if (r_data->enc_nonce
914 			|| r_data->mapping_data
915 			|| r_data->eph_pub_key
916 			|| !r_data->auth_token) {
917 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Response data of general authenticate for "
918 				"step 4 should (only) contain the authentication token.");
919 		r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
920 		goto err;
921 	}
922 	p = r_data->auth_token->data;
923 	l = r_data->auth_token->length;
924 	if (r_data->cur_car) {
925 		sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "Most recent Certificate Authority Reference",
926 				r_data->cur_car->data, r_data->cur_car->length);
927 		*recent_car = malloc(r_data->cur_car->length);
928 		if (!*recent_car) {
929 			r = SC_ERROR_OUT_OF_MEMORY;
930 			goto err;
931 		}
932 		/* Flawfinder: ignore */
933 		memcpy(*recent_car, r_data->cur_car->data, r_data->cur_car->length);
934 		*recent_car_len = r_data->cur_car->length;
935 	} else
936 		*recent_car_len = 0;
937 	if (r_data->prev_car) {
938 		sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "Previous Certificate Authority Reference",
939 				r_data->prev_car->data, r_data->prev_car->length);
940 		*prev_car = malloc(r_data->prev_car->length);
941 		if (!*prev_car) {
942 			r = SC_ERROR_OUT_OF_MEMORY;
943 			goto err;
944 		}
945 		/* Flawfinder: ignore */
946 		memcpy(*prev_car, r_data->prev_car->data, r_data->prev_car->length);
947 		*prev_car_len = r_data->prev_car->length;
948 	} else
949 		*prev_car_len = 0;
950 
951 	*auth_token_out = malloc(l);
952 	if (!*auth_token_out) {
953 		r = SC_ERROR_OUT_OF_MEMORY;
954 		goto err;
955 	}
956 	/* Flawfinder: ignore */
957 	memcpy(*auth_token_out, p, l);
958 	*auth_token_out_len = l;
959 
960 err:
961 	if (c_data)
962 		EAC_GEN_AUTH_PACE_C_free(c_data);
963 	OPENSSL_free(d);
964 	if (r_data)
965 		EAC_GEN_AUTH_PACE_R_free(r_data);
966 
967 	return r;
968 }
969 
970 static PACE_SEC *
get_psec(sc_card_t * card,const char * pin,size_t length_pin,enum s_type pin_id)971 get_psec(sc_card_t *card, const char *pin, size_t length_pin, enum s_type pin_id)
972 {
973 	char *p = NULL;
974 	PACE_SEC *r;
975 	/* Flawfinder: ignore */
976 	char buf[EAC_MAX_MRZ_LEN > 32 ? EAC_MAX_MRZ_LEN : 32];
977 
978 	if (!length_pin || !pin) {
979 		if (0 > snprintf(buf, sizeof buf, "Please enter your %s: ",
980 					eac_secret_name(pin_id))) {
981 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not create password prompt.\n");
982 			return NULL;
983 		}
984 		p = malloc(EAC_MAX_MRZ_LEN+1);
985 		if (!p) {
986 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Not enough memory for %s.\n",
987 					eac_secret_name(pin_id));
988 			return NULL;
989 		}
990 		if (0 > EVP_read_pw_string_min(p, 0, EAC_MAX_MRZ_LEN, buf, 0)) {
991 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not read %s.\n",
992 					eac_secret_name(pin_id));
993 			return NULL;
994 		}
995 		length_pin = strlen(p);
996 		if (length_pin > EAC_MAX_MRZ_LEN) {
997 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "MRZ too long");
998 			return NULL;
999 		}
1000 		pin = p;
1001 	}
1002 
1003 	r = PACE_SEC_new(pin, length_pin, pin_id);
1004 
1005 	if (p) {
1006 		OPENSSL_cleanse(p, length_pin);
1007 		free(p);
1008 	}
1009 
1010 	return r;
1011 }
1012 
1013 
perform_pace(sc_card_t * card,struct establish_pace_channel_input pace_input,struct establish_pace_channel_output * pace_output,enum eac_tr_version tr_version)1014 int perform_pace(sc_card_t *card,
1015 		struct establish_pace_channel_input pace_input,
1016 		struct establish_pace_channel_output *pace_output,
1017 		enum eac_tr_version tr_version)
1018 {
1019 	u8 *p = NULL;
1020 	EAC_CTX *eac_ctx = NULL;
1021 	BUF_MEM *enc_nonce = NULL, *mdata = NULL, *mdata_opp = NULL,
1022 			*token_opp = NULL, *token = NULL, *pub = NULL, *pub_opp = NULL,
1023 			*comp_pub = NULL, *comp_pub_opp = NULL;
1024 	PACE_SEC *sec = NULL;
1025 	CVC_CHAT *chat = NULL;
1026 	BIO *bio_stdout = NULL;
1027 	CVC_CERTIFICATE_DESCRIPTION *desc = NULL;
1028 	int r;
1029 	const unsigned char *pp;
1030 
1031 	if (!card || !card->reader || !card->reader->ops || !pace_output)
1032 		return SC_ERROR_INVALID_ARGUMENTS;
1033 
1034 	/* show description in advance to give the user more time to read it...
1035 	 * This behaviour differs from TR-03119 v1.1 p. 44. */
1036 	if (pace_input.certificate_description_length &&
1037 			pace_input.certificate_description) {
1038 
1039 		pp = pace_input.certificate_description;
1040 		if (!d2i_CVC_CERTIFICATE_DESCRIPTION(&desc,
1041 					&pp, pace_input.certificate_description_length)) {
1042 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not parse certificate description.");
1043 			ssl_error(card->ctx);
1044 			r = SC_ERROR_INTERNAL;
1045 			goto err;
1046 		}
1047 
1048 		if (!bio_stdout) {
1049 			bio_stdout = BIO_new_fp(stdout, BIO_NOCLOSE);
1050 			if (!bio_stdout) {
1051 				sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not create output buffer.");
1052 				ssl_error(card->ctx);
1053 				r = SC_ERROR_INTERNAL;
1054 				goto err;
1055 			}
1056 		}
1057 
1058 		printf("Certificate Description\n");
1059 		switch(certificate_description_print(bio_stdout, desc, 8)) {
1060 			case 0:
1061 				sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not print certificate description.");
1062 				ssl_error(card->ctx);
1063 				r = SC_ERROR_INTERNAL;
1064 				goto err;
1065 				break;
1066 			case 1:
1067 				/* text format */
1068 				break;
1069 			case 2:
1070 				sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Certificate description in "
1071 						"HTML format can not (yet) be handled.");
1072 				r = SC_ERROR_NOT_SUPPORTED;
1073 				goto err;
1074 				break;
1075 			case 3:
1076 				sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Certificate description in "
1077 						"PDF format can not (yet) be handled.");
1078 				r = SC_ERROR_NOT_SUPPORTED;
1079 				goto err;
1080 				break;
1081 			default:
1082 				sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Certificate description in "
1083 						"unknown format can not be handled.");
1084 				r = SC_ERROR_NOT_SUPPORTED;
1085 				goto err;
1086 				break;
1087 		}
1088 	}
1089 
1090 	/* show chat in advance to give the user more time to read it...
1091 	 * This behaviour differs from TR-03119 v1.1 p. 44. */
1092 	if (pace_input.chat_length && pace_input.chat) {
1093 
1094 		if (!bio_stdout) {
1095 			bio_stdout = BIO_new_fp(stdout, BIO_NOCLOSE);
1096 			if (!bio_stdout) {
1097 				sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not create output buffer.");
1098 				ssl_error(card->ctx);
1099 				r = SC_ERROR_INTERNAL;
1100 				goto err;
1101 			}
1102 		}
1103 
1104 		pp = pace_input.chat;
1105 		if (!d2i_CVC_CHAT(&chat, &pp, pace_input.chat_length)) {
1106 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not parse card holder authorization template (CHAT).");
1107 			ssl_error(card->ctx);
1108 			r = SC_ERROR_INTERNAL;
1109 			goto err;
1110 		}
1111 
1112 		printf("Card holder authorization template (CHAT)\n");
1113 		if (!cvc_chat_print(bio_stdout, chat, 8)) {
1114 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not print card holder authorization template (CHAT).");
1115 			ssl_error(card->ctx);
1116 			r = SC_ERROR_INTERNAL;
1117 			goto err;
1118 		}
1119 	}
1120 
1121 	if (card->reader->capabilities & SC_READER_CAP_PACE_GENERIC
1122 			&& card->reader->ops->perform_pace) {
1123 		r = card->reader->ops->perform_pace(card->reader, &pace_input, pace_output);
1124 		if (r < 0)
1125 			goto err;
1126 	} else {
1127 		if (!pace_output->ef_cardaccess_length || !pace_output->ef_cardaccess) {
1128 			r = get_ef_card_access(card, &pace_output->ef_cardaccess,
1129 					&pace_output->ef_cardaccess_length);
1130 			if (r < 0) {
1131 				sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not get EF.CardAccess.");
1132 				goto err;
1133 			}
1134 		}
1135 
1136 		sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "EF.CardAccess", pace_output->ef_cardaccess,
1137 				pace_output->ef_cardaccess_length);
1138 
1139 		eac_ctx = EAC_CTX_new();
1140 		if (!eac_ctx
1141 				|| !EAC_CTX_init_ef_cardaccess(pace_output->ef_cardaccess,
1142 					pace_output->ef_cardaccess_length, eac_ctx)
1143 				|| !eac_ctx->pace_ctx) {
1144 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not parse EF.CardAccess.");
1145 			ssl_error(card->ctx);
1146 			r = SC_ERROR_INTERNAL;
1147 			goto err;
1148 		}
1149 
1150 		eac_ctx->tr_version = tr_version;
1151 
1152 		r = eac_mse_set_at_pace(card, eac_ctx->pace_ctx->protocol,
1153 				pace_input.pin_id, chat, &pace_output->mse_set_at_sw1,
1154 				&pace_output->mse_set_at_sw2);
1155 		if (r < 0) {
1156 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not select protocol properties "
1157 					"(MSE: Set AT failed).");
1158 			goto err;
1159 		}
1160 
1161 		enc_nonce = BUF_MEM_new();
1162 		if (!enc_nonce) {
1163 			ssl_error(card->ctx);
1164 			r = SC_ERROR_OUT_OF_MEMORY;
1165 			goto err;
1166 		}
1167 		r = eac_gen_auth_1_encrypted_nonce(card, (u8 **) &enc_nonce->data,
1168 				&enc_nonce->length);
1169 		if (r < 0) {
1170 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not get encrypted nonce from card "
1171 					"(General Authenticate step 1 failed).");
1172 			goto err;
1173 		}
1174 		sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "Encrypted nonce from MRTD", (u8 *)enc_nonce->data, enc_nonce->length);
1175 		enc_nonce->max = enc_nonce->length;
1176 
1177 		sec = get_psec(card, (char *) pace_input.pin, pace_input.pin_length,
1178 				pace_input.pin_id);
1179 		if (!sec) {
1180 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not encode PACE secret.");
1181 			ssl_error(card->ctx);
1182 			r = SC_ERROR_INTERNAL;
1183 			goto err;
1184 		}
1185 
1186 		if (!PACE_STEP2_dec_nonce(eac_ctx, sec, enc_nonce)) {
1187 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not decrypt MRTD's nonce.");
1188 			ssl_error(card->ctx);
1189 			r = SC_ERROR_INTERNAL;
1190 			goto err;
1191 		}
1192 
1193 		mdata_opp = BUF_MEM_new();
1194 		mdata = PACE_STEP3A_generate_mapping_data(eac_ctx);
1195 		if (!mdata || !mdata_opp) {
1196 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not generate mapping data.");
1197 			ssl_error(card->ctx);
1198 			r = SC_ERROR_INTERNAL;
1199 			goto err;
1200 		}
1201 		r = eac_gen_auth_2_map_nonce(card, (u8 *) mdata->data, mdata->length,
1202 				(u8 **) &mdata_opp->data, &mdata_opp->length);
1203 		if (r < 0) {
1204 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not exchange mapping data with card "
1205 					"(General Authenticate step 2 failed).");
1206 			goto err;
1207 		}
1208 		mdata_opp->max = mdata_opp->length;
1209 		sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "Mapping data from MRTD", (u8 *) mdata_opp->data, mdata_opp->length);
1210 
1211 		if (!PACE_STEP3A_map_generator(eac_ctx, mdata_opp)) {
1212 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not map generator.");
1213 			ssl_error(card->ctx);
1214 			r = SC_ERROR_INTERNAL;
1215 			goto err;
1216 		}
1217 
1218 		pub = PACE_STEP3B_generate_ephemeral_key(eac_ctx);
1219 		pub_opp = BUF_MEM_new();
1220 		if (!pub || !pub_opp) {
1221 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not generate ephemeral domain parameter or "
1222 					"ephemeral key pair.");
1223 			ssl_error(card->ctx);
1224 			r = SC_ERROR_INTERNAL;
1225 			goto err;
1226 		}
1227 		r = eac_gen_auth_3_perform_key_agreement(card, (u8 *) pub->data, pub->length,
1228 				(u8 **) &pub_opp->data, &pub_opp->length);
1229 		if (r < 0) {
1230 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not exchange ephemeral public key with card "
1231 					"(General Authenticate step 3 failed).");
1232 			goto err;
1233 		}
1234 		pub_opp->max = pub_opp->length;
1235 		sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "Ephemeral public key from MRTD", (u8 *) pub_opp->data, pub_opp->length);
1236 
1237 
1238 		if (!PACE_STEP3B_compute_shared_secret(eac_ctx, pub_opp)
1239 				|| !PACE_STEP3C_derive_keys(eac_ctx)) {
1240 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not compute ephemeral shared secret or "
1241 					"derive keys for encryption and authentication.");
1242 			ssl_error(card->ctx);
1243 			r = SC_ERROR_INTERNAL;
1244 			goto err;
1245 		}
1246 		token = PACE_STEP3D_compute_authentication_token(eac_ctx, pub_opp);
1247 		token_opp = BUF_MEM_new();
1248 		if (!token || !token_opp) {
1249 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not compute authentication token.");
1250 			ssl_error(card->ctx);
1251 			r = SC_ERROR_INTERNAL;
1252 			goto err;
1253 		}
1254 		r = eac_gen_auth_4_mutual_authentication(card, (u8 *) token->data, token->length,
1255 				(u8 **) &token_opp->data, &token_opp->length,
1256 				&pace_output->recent_car, &pace_output->recent_car_length,
1257 				&pace_output->previous_car, &pace_output->previous_car_length);
1258 
1259 		if (r < 0) {
1260 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not exchange authentication token with card "
1261 					"(General Authenticate step 4 failed).");
1262 			goto err;
1263 		}
1264 		token_opp->max = token_opp->length;
1265 
1266 		if (!PACE_STEP3D_verify_authentication_token(eac_ctx, token_opp)) {
1267 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not verify authentication token.");
1268 			ssl_error(card->ctx);
1269 			r = SC_ERROR_INTERNAL;
1270 			goto err;
1271 		}
1272 
1273 		/* Initialize secure channel */
1274 		if (!EAC_CTX_set_encryption_ctx(eac_ctx, EAC_ID_PACE)) {
1275 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not initialize encryption.");
1276 			ssl_error(card->ctx);
1277 			r = SC_ERROR_INTERNAL;
1278 			goto err;
1279 		}
1280 
1281 		/* Identifier for ICC and PCD */
1282 		comp_pub = EAC_Comp(eac_ctx, EAC_ID_PACE, pub);
1283 		comp_pub_opp = EAC_Comp(eac_ctx, EAC_ID_PACE, pub_opp);
1284 		if (!comp_pub || !comp_pub_opp) {
1285 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not compress public keys for identification.");
1286 			ssl_error(card->ctx);
1287 			r = SC_ERROR_INTERNAL;
1288 			goto err;
1289 		}
1290 		if (comp_pub_opp->length == 0) {
1291 			r = SC_ERROR_INTERNAL;
1292 			goto err;
1293 		}
1294 		p = realloc(pace_output->id_icc, comp_pub_opp->length);
1295 		if (!p) {
1296 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Not enough memory for ID ICC.\n");
1297 			r = SC_ERROR_OUT_OF_MEMORY;
1298 			goto err;
1299 		}
1300 		pace_output->id_icc = p;
1301 		pace_output->id_icc_length = comp_pub_opp->length;
1302 		/* Flawfinder: ignore */
1303 		memcpy(pace_output->id_icc, comp_pub_opp->data, comp_pub_opp->length);
1304 		sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "ID ICC", pace_output->id_icc,
1305 				pace_output->id_icc_length);
1306 		if (comp_pub->length == 0) {
1307 			r = SC_ERROR_INTERNAL;
1308 			goto err;
1309 		}
1310 		p = realloc(pace_output->id_pcd, comp_pub->length);
1311 		if (!p) {
1312 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Not enough memory for ID PCD.\n");
1313 			r = SC_ERROR_OUT_OF_MEMORY;
1314 			goto err;
1315 		}
1316 		pace_output->id_pcd = p;
1317 		pace_output->id_pcd_length = comp_pub->length;
1318 		/* Flawfinder: ignore */
1319 		memcpy(pace_output->id_pcd, comp_pub->data, comp_pub->length);
1320 		sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "ID PCD", pace_output->id_pcd,
1321 				pace_output->id_pcd_length);
1322 
1323 		r = eac_sm_start(card, eac_ctx, pace_input.certificate_description,
1324 				pace_input.certificate_description_length, pace_output->id_icc,
1325 				pace_output->id_icc_length);
1326 	}
1327 
1328 err:
1329 	if (enc_nonce)
1330 		BUF_MEM_free(enc_nonce);
1331 	if (mdata)
1332 		BUF_MEM_free(mdata);
1333 	if (mdata_opp)
1334 		BUF_MEM_free(mdata_opp);
1335 	if (token_opp)
1336 		BUF_MEM_free(token_opp);
1337 	if (token)
1338 		BUF_MEM_free(token);
1339 	if (pub)
1340 		BUF_MEM_free(pub);
1341 	if (pub_opp)
1342 		BUF_MEM_free(pub_opp);
1343 	if (comp_pub_opp)
1344 		BUF_MEM_free(comp_pub_opp);
1345 	if (comp_pub)
1346 		BUF_MEM_free(comp_pub);
1347 	PACE_SEC_clear_free(sec);
1348 	if (bio_stdout)
1349 		BIO_free_all(bio_stdout);
1350 	if (desc)
1351 		CVC_CERTIFICATE_DESCRIPTION_free(desc);
1352 	if (chat)
1353 		CVC_CHAT_free(chat);
1354 
1355 	if (r < 0)
1356 		EAC_CTX_clear_free(eac_ctx);
1357 
1358 	SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_SM, r);
1359 }
1360 
eac_mse_set_at_ta(sc_card_t * card,int protocol,const unsigned char * chr,size_t chr_len,const unsigned char * eph_pub_key,size_t eph_pub_key_len,const unsigned char * auxiliary_data,size_t auxiliary_data_len)1361 static int eac_mse_set_at_ta(sc_card_t *card, int protocol,
1362 		const unsigned char *chr, size_t chr_len,
1363 		const unsigned char *eph_pub_key, size_t eph_pub_key_len,
1364 		const unsigned char *auxiliary_data, size_t auxiliary_data_len)
1365 {
1366 	return eac_mse_set_at(card, 0x81, protocol, chr, chr_len, NULL, 0,
1367 			eph_pub_key, eph_pub_key_len, auxiliary_data, auxiliary_data_len,
1368 			NULL, NULL, NULL);
1369 }
1370 
eac_mse_set_dst(sc_card_t * card,const unsigned char * chr,size_t chr_len)1371 static int eac_mse_set_dst(sc_card_t *card,
1372 		const unsigned char *chr, size_t chr_len)
1373 {
1374 	return eac_mse(card, 0x81, 0xb6, 0, chr, chr_len, NULL, 0, NULL, 0, NULL,
1375 			0, NULL, NULL, NULL);
1376 }
1377 
eac_get_challenge(sc_card_t * card,unsigned char * challenge,size_t len)1378 static int eac_get_challenge(sc_card_t *card,
1379 		unsigned char *challenge, size_t len)
1380 {
1381 	sc_apdu_t apdu;
1382 	int r;
1383 
1384 	if (!card) {
1385 		r = SC_ERROR_INVALID_ARGUMENTS;
1386 		goto err;
1387 	}
1388 
1389 	sc_format_apdu_ex(&apdu, 0x00, 0x84, 0x00, 0x00, NULL, 0, challenge, len);
1390 
1391 	r = sc_transmit_apdu(card, &apdu);
1392 	if (r < 0)
1393 		goto err;
1394 
1395 	r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1396 
1397 err:
1398 	return r;
1399 }
1400 
eac_verify(sc_card_t * card,const unsigned char * cert,size_t cert_len)1401 static int eac_verify(sc_card_t *card,
1402 		const unsigned char *cert, size_t cert_len)
1403 {
1404 	sc_apdu_t apdu;
1405 	int r, class, tag;
1406 	long int length;
1407 
1408 	memset(&apdu, 0, sizeof apdu);
1409 
1410 	if (!card) {
1411 		r = SC_ERROR_INVALID_ARGUMENTS;
1412 		goto err;
1413 	}
1414 
1415 	if (0x80 & ASN1_get_object(&cert, &length, &tag, &class, cert_len)) {
1416 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Error decoding Certificate");
1417 		ssl_error(card->ctx);
1418 		r = SC_ERROR_INTERNAL;
1419 		goto err;
1420 	}
1421 
1422 	sc_format_apdu_ex(&apdu, 0x00, 0x2A, 0x00, 0xbe, (unsigned char *) cert, length, NULL, 0);
1423 
1424 	r = sc_transmit_apdu(card, &apdu);
1425 	if (r < 0)
1426 		goto err;
1427 
1428 	r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1429 
1430 err:
1431 	return r;
1432 }
1433 
eac_external_authenticate(sc_card_t * card,unsigned char * signature,size_t signature_len)1434 static int eac_external_authenticate(sc_card_t *card,
1435 		unsigned char *signature, size_t signature_len)
1436 {
1437 	int r;
1438 	sc_apdu_t apdu;
1439 	memset(&apdu, 0, sizeof apdu);
1440 
1441 	if (!card) {
1442 		r = SC_ERROR_INVALID_ARGUMENTS;
1443 		goto err;
1444 	}
1445 
1446 	sc_format_apdu_ex(&apdu, 0x00, 0x82, 0x00, 0x00, signature, signature_len, NULL, 0);
1447 
1448 	r = sc_transmit_apdu(card, &apdu);
1449 	if (r < 0)
1450 		goto err;
1451 
1452 	r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1453 
1454 err:
1455 	return r;
1456 }
1457 
eac_sm_clear_free_without_ctx(const struct iso_sm_ctx * ctx)1458 static void eac_sm_clear_free_without_ctx(const struct iso_sm_ctx *ctx)
1459 {
1460 	if (ctx) {
1461 		struct eac_sm_ctx *eacsmctx = ctx->priv_data;
1462 		if (eacsmctx)
1463 			eacsmctx->ctx = NULL;
1464 		eac_sm_clear_free(ctx);
1465 	}
1466 }
1467 
1468 #define TA_NONCE_LENGTH 8
perform_terminal_authentication(sc_card_t * card,const unsigned char ** certs,const size_t * certs_lens,const unsigned char * privkey,size_t privkey_len,const unsigned char * auxiliary_data,size_t auxiliary_data_len)1469 int perform_terminal_authentication(sc_card_t *card,
1470 		const unsigned char **certs, const size_t *certs_lens,
1471 		const unsigned char *privkey, size_t privkey_len,
1472 		const unsigned char *auxiliary_data, size_t auxiliary_data_len)
1473 {
1474 	int r;
1475 	const unsigned char *cert = NULL;
1476 	size_t cert_len = 0, ef_cardaccess_length = 0;
1477 	CVC_CERT *cvc_cert = NULL;
1478 	BUF_MEM *nonce = NULL, *signature = NULL;
1479 	struct iso_sm_ctx *isosmctx = NULL;
1480 	struct eac_sm_ctx *eacsmctx = NULL;
1481 	unsigned char *ef_cardaccess = NULL;
1482 	EAC_CTX *eac_ctx = NULL;
1483 	const unsigned char *chr = NULL;
1484 	size_t chr_len = 0;
1485 
1486 	if (!card || !certs_lens || !certs) {
1487 		r = SC_ERROR_INVALID_ARGUMENTS;
1488 		goto err;
1489 	}
1490 	if (!card->sm_ctx.info.cmd_data) {
1491 		card->sm_ctx.info.cmd_data = iso_sm_ctx_create();
1492 		card->sm_ctx.ops.close = iso_sm_close;
1493 	}
1494 	if (!card->sm_ctx.info.cmd_data) {
1495 		r = SC_ERROR_INTERNAL;
1496 		goto err;
1497 	}
1498 
1499 	isosmctx = card->sm_ctx.info.cmd_data;
1500 	if (!isosmctx->priv_data) {
1501 		r = get_ef_card_access(card, &ef_cardaccess, &ef_cardaccess_length);
1502 		if (r < 0) {
1503 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not get EF.CardAccess.");
1504 			goto err;
1505 		}
1506 
1507 		sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "EF.CardAccess", ef_cardaccess,
1508 				ef_cardaccess_length);
1509 
1510 		/* XXX Card capabilities should be determined by the OpenSC card driver. We
1511 		 * set it here to be able to use the nPA without patching OpenSC. By
1512 		 * now we have read the EF.CardAccess so the assumption to have an nPA
1513 		 * seems valid. */
1514 		card->caps |= SC_CARD_CAP_APDU_EXT;
1515 
1516 		eac_ctx = EAC_CTX_new();
1517 		if (!eac_ctx
1518 				|| !EAC_CTX_init_ef_cardaccess(ef_cardaccess,
1519 					ef_cardaccess_length, eac_ctx)) {
1520 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not parse EF.CardAccess.");
1521 			ssl_error(card->ctx);
1522 			r = SC_ERROR_INTERNAL;
1523 			goto err;
1524 		}
1525 
1526 		isosmctx->priv_data = eac_sm_ctx_create(eac_ctx, NULL, 0, NULL, 0);
1527 		if (!isosmctx->priv_data) {
1528 			r = SC_ERROR_INTERNAL;
1529 			goto err;
1530 		}
1531 		/* when iso_sm_ctx_clear_free is called, we want everything to be freed
1532 		 * except the EAC_CTX, because it is needed for performing SM *after*
1533 		 * iso_sm_start was called. */
1534 		isosmctx->clear_free = eac_sm_clear_free_without_ctx;
1535 		eac_ctx = NULL;
1536 	}
1537 	eacsmctx = isosmctx->priv_data;
1538 
1539 
1540 	while (*certs && *certs_lens) {
1541 		cert = *certs;
1542 		cert_len = *certs_lens;
1543 		if (!CVC_d2i_CVC_CERT(&cvc_cert, &cert, cert_len) || !cvc_cert
1544 				|| !cvc_cert->body || !cvc_cert->body->certificate_authority_reference
1545 				|| !cvc_cert->body->certificate_holder_reference) {
1546 			ssl_error(card->ctx);
1547 			r = SC_ERROR_INVALID_DATA;
1548 			goto err;
1549 		}
1550 		cert = *certs;
1551 
1552 		r = eac_mse_set_dst(card,
1553 				cvc_cert->body->certificate_authority_reference->data,
1554 				cvc_cert->body->certificate_authority_reference->length);
1555 		if (r < 0) {
1556 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not select protocol properties "
1557 					"(MSE: Set AT failed).");
1558 			goto err;
1559 		}
1560 
1561 		r = eac_verify(card, cert, cert_len);
1562 		if (r < 0)
1563 			goto err;
1564 
1565 		chr = cvc_cert->body->certificate_holder_reference->data;
1566 		chr_len = cvc_cert->body->certificate_holder_reference->length;
1567 
1568 		certs++;
1569 		certs_lens++;
1570 	}
1571 
1572 
1573 	if (!EAC_CTX_init_ta(eacsmctx->ctx, privkey, privkey_len, cert, cert_len)) {
1574 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not initialize TA.");
1575 		ssl_error(card->ctx);
1576 		r = SC_ERROR_INTERNAL;
1577 		goto err;
1578 	}
1579 
1580 
1581 	if (eacsmctx->eph_pub_key)
1582 		BUF_MEM_free(eacsmctx->eph_pub_key);
1583 	eacsmctx->eph_pub_key = TA_STEP3_generate_ephemeral_key(eacsmctx->ctx);
1584 	if (!eacsmctx->eph_pub_key) {
1585 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not generate CA ephemeral key.");
1586 		ssl_error(card->ctx);
1587 		r = SC_ERROR_INTERNAL;
1588 		goto err;
1589 	}
1590 
1591 
1592 	r = eac_mse_set_at_ta(card, eacsmctx->ctx->ta_ctx->protocol, chr, chr_len,
1593 			(unsigned char *) eacsmctx->eph_pub_key->data, eacsmctx->eph_pub_key->length,
1594 			auxiliary_data, auxiliary_data_len);
1595 	if (r < 0) {
1596 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not select protocol properties "
1597 				"(MSE: Set AT failed).");
1598 		goto err;
1599 	}
1600 
1601 	nonce = BUF_MEM_create(TA_NONCE_LENGTH);
1602 	if (!nonce) {
1603 		ssl_error(card->ctx);
1604 		r = SC_ERROR_INTERNAL;
1605 		goto err;
1606 	}
1607 	r = eac_get_challenge(card, (unsigned char *) nonce->data, nonce->length);
1608 	if (r < 0) {
1609 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not get nonce for TA.");
1610 		goto err;
1611 	}
1612 	if (!TA_STEP4_set_nonce(eacsmctx->ctx, nonce)) {
1613 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not set nonce for TA.");
1614 		ssl_error(card->ctx);
1615 		r = SC_ERROR_INTERNAL;
1616 		goto err;
1617 	}
1618 
1619 	if (eacsmctx->auxiliary_data)
1620 		BUF_MEM_free(eacsmctx->auxiliary_data);
1621 	eacsmctx->auxiliary_data = BUF_MEM_create_init(auxiliary_data,
1622 			auxiliary_data_len);
1623 	if (!eacsmctx->id_icc)
1624 		eacsmctx->id_icc = BUF_MEM_new();
1625 	signature = TA_STEP5_sign(eacsmctx->ctx, eacsmctx->eph_pub_key,
1626 			eacsmctx->id_icc, eacsmctx->auxiliary_data);
1627 	if (!signature) {
1628 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not generate signature.");
1629 		ssl_error(card->ctx);
1630 		r = SC_ERROR_INTERNAL;
1631 		goto err;
1632 	}
1633 	r = eac_external_authenticate(card, (unsigned char *) signature->data,
1634 			signature->length);
1635 
1636 err:
1637 	if (cvc_cert)
1638 		CVC_CERT_free(cvc_cert);
1639 	free(ef_cardaccess);
1640 	EAC_CTX_clear_free(eac_ctx);
1641 	BUF_MEM_clear_free(nonce);
1642 	BUF_MEM_clear_free(signature);
1643 
1644 	if (card)
1645 		SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_SM, r);
1646 	else
1647 		return r;
1648 }
1649 
eac_mse_set_at_ca(sc_card_t * card,int protocol)1650 static int eac_mse_set_at_ca(sc_card_t *card, int protocol)
1651 {
1652 	return eac_mse_set_at(card, 0x41, protocol, NULL, 0, NULL, 0, NULL, 0,
1653 			NULL, 0, NULL, NULL, NULL);
1654 }
1655 
eac_gen_auth_ca(sc_card_t * card,const BUF_MEM * eph_pub_key,BUF_MEM ** nonce,BUF_MEM ** token)1656 static int eac_gen_auth_ca(sc_card_t *card, const BUF_MEM *eph_pub_key,
1657 		BUF_MEM **nonce, BUF_MEM **token)
1658 {
1659 	sc_apdu_t apdu;
1660 	EAC_GEN_AUTH_CA_C *c_data = NULL;
1661 	EAC_GEN_AUTH_CA_R *r_data = NULL;
1662 	unsigned char *d = NULL;
1663 	int r;
1664 	unsigned char resp[SC_MAX_APDU_RESP_SIZE];
1665 
1666 	c_data = EAC_GEN_AUTH_CA_C_new();
1667 	if (!c_data) {
1668 		r = SC_ERROR_OUT_OF_MEMORY;
1669 		goto err;
1670 	}
1671 	c_data->eph_pub_key = ASN1_OCTET_STRING_new();
1672 	if (!c_data->eph_pub_key
1673 			|| !ASN1_OCTET_STRING_set(c_data->eph_pub_key,
1674 				(const unsigned char *) eph_pub_key->data,
1675 				eph_pub_key->length)) {
1676 		ssl_error(card->ctx);
1677 		r = SC_ERROR_INTERNAL;
1678 		goto err;
1679 	}
1680 	r = i2d_EAC_GEN_AUTH_CA_C(c_data, &d);
1681 	if (r < 0) {
1682 		ssl_error(card->ctx);
1683 		r = SC_ERROR_INTERNAL;
1684 		goto err;
1685 	}
1686 	sc_format_apdu_ex(&apdu, 0x00, ISO_GENERAL_AUTHENTICATE, 0, 0, d, r, resp, sizeof resp);
1687 
1688 	sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "General authenticate (Perform Key Agreement) command data", apdu.data, apdu.datalen);
1689 
1690 	r = sc_transmit_apdu(card, &apdu);
1691 	if (r < 0)
1692 		goto err;
1693 
1694 	r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1695 	if (r < 0)
1696 		goto err;
1697 
1698 	sc_debug_hex(card->ctx, SC_LOG_DEBUG_SM, "General authenticate (Perform Key Agreement) response data", apdu.resp, apdu.resplen);
1699 
1700 	if (!d2i_EAC_GEN_AUTH_CA_R(&r_data,
1701 				(const unsigned char **) &apdu.resp, apdu.resplen)) {
1702 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not parse general authenticate response data.");
1703 		ssl_error(card->ctx);
1704 		r = SC_ERROR_INTERNAL;
1705 		goto err;
1706 	}
1707 
1708 	if (!r_data->nonce || !r_data->auth_token) {
1709 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Response data of general authenticate for CA"
1710 				"should contain the nonce and the authentication token.");
1711 		r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
1712 		goto err;
1713 	}
1714 
1715 	if (*nonce)
1716 		BUF_MEM_free(*nonce);
1717 	*nonce = BUF_MEM_create_init(r_data->nonce->data,
1718 			r_data->nonce->length);
1719 	if (*token)
1720 		BUF_MEM_free(*token);
1721 	*token = BUF_MEM_create_init(r_data->auth_token->data,
1722 			r_data->auth_token->length);
1723 	if (!*nonce || !*token) {
1724 		r = SC_ERROR_OUT_OF_MEMORY;
1725 		goto err;
1726 	}
1727 
1728 err:
1729 	if (c_data)
1730 		EAC_GEN_AUTH_CA_C_free(c_data);
1731 	if (r_data)
1732 		EAC_GEN_AUTH_CA_R_free(r_data);
1733 	OPENSSL_free(d);
1734 
1735 	return r;
1736 }
1737 
get_ef_card_security(sc_card_t * card,u8 ** ef_security,size_t * length_ef_security)1738 static int get_ef_card_security(sc_card_t *card,
1739 		u8 **ef_security, size_t *length_ef_security)
1740 {
1741 	return iso7816_read_binary_sfid(card, SFID_EF_CARDSECURITY, ef_security, length_ef_security);
1742 }
1743 
perform_chip_authentication(sc_card_t * card,unsigned char ** ef_cardsecurity,size_t * ef_cardsecurity_len)1744 int perform_chip_authentication(sc_card_t *card,
1745 		unsigned char **ef_cardsecurity, size_t *ef_cardsecurity_len)
1746 {
1747 	int r;
1748 	BUF_MEM *picc_pubkey = NULL;
1749 	struct iso_sm_ctx *isosmctx;
1750 	struct eac_sm_ctx *eacsmctx;
1751 
1752 	if (!card || !ef_cardsecurity || !ef_cardsecurity_len) {
1753 		r = SC_ERROR_INVALID_ARGUMENTS;
1754 		goto err;
1755 	}
1756 	isosmctx = card->sm_ctx.info.cmd_data;
1757 	if (!isosmctx->priv_data) {
1758 		r = SC_ERROR_INVALID_ARGUMENTS;
1759 		goto err;
1760 	}
1761 	eacsmctx = isosmctx->priv_data;
1762 
1763 	/* Passive Authentication */
1764 	if (!*ef_cardsecurity && !*ef_cardsecurity_len) {
1765 		r = get_ef_card_security(card, ef_cardsecurity, ef_cardsecurity_len);
1766 		if (r < 0 || !ef_cardsecurity || !ef_cardsecurity_len) {
1767 			sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not get EF.CardSecurity.");
1768 			goto err;
1769 		}
1770 	}
1771 	picc_pubkey = CA_get_pubkey(eacsmctx->ctx, *ef_cardsecurity, *ef_cardsecurity_len);
1772 	if (!picc_pubkey) {
1773 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not verify EF.CardSecurity.");
1774 		ssl_error(card->ctx);
1775 		r = SC_ERROR_INTERNAL;
1776 		goto err;
1777 	}
1778 
1779 	r = perform_chip_authentication_ex(card, eacsmctx->ctx,
1780 			(unsigned char *) picc_pubkey->data, picc_pubkey->length);
1781 
1782 err:
1783 	BUF_MEM_clear_free(picc_pubkey);
1784 
1785 	if (card)
1786 		SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_SM, r);
1787 	else
1788 		return r;
1789 }
1790 
perform_chip_authentication_ex(sc_card_t * card,void * eac_ctx,unsigned char * picc_pubkey,size_t picc_pubkey_len)1791 int perform_chip_authentication_ex(sc_card_t *card, void *eac_ctx,
1792 		unsigned char *picc_pubkey, size_t picc_pubkey_len)
1793 {
1794 	int r;
1795 	BUF_MEM *picc_pubkey_buf = NULL, *nonce = NULL, *token = NULL,
1796 			*eph_pub_key = NULL;
1797 	EAC_CTX *ctx = eac_ctx;
1798 
1799 	if (!card || !ctx) {
1800 		r = SC_ERROR_INVALID_ARGUMENTS;
1801 		goto err;
1802 	}
1803 
1804 
1805 	picc_pubkey_buf = BUF_MEM_create_init(picc_pubkey, picc_pubkey_len);
1806 	if (!picc_pubkey_buf) {
1807 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not verify EF.CardSecurity.");
1808 		ssl_error(card->ctx);
1809 		r = SC_ERROR_INTERNAL;
1810 		goto err;
1811 	}
1812 
1813 
1814 	r = eac_mse_set_at_ca(card, ctx->ca_ctx->protocol);
1815 	if (r < 0) {
1816 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not select protocol properties "
1817 				"(MSE: Set AT failed).");
1818 		goto err;
1819 	}
1820 
1821 
1822 	eph_pub_key = CA_STEP2_get_eph_pubkey(ctx);
1823 	if (!eph_pub_key) {
1824 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not derive keys.");
1825 		ssl_error(card->ctx);
1826 		r = SC_ERROR_INTERNAL;
1827 		goto err;
1828 	}
1829 	r = eac_gen_auth_ca(card, eph_pub_key, &nonce, &token);
1830 	if (r < 0) {
1831 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "(General Authenticate failed).");
1832 		goto err;
1833 	}
1834 
1835 
1836 	if (!CA_STEP4_compute_shared_secret(ctx, picc_pubkey_buf)) {
1837 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not compute shared secret.");
1838 		ssl_error(card->ctx);
1839 		r = SC_ERROR_INTERNAL;
1840 		goto err;
1841 	}
1842 
1843 
1844 	if (!CA_STEP6_derive_keys(ctx, nonce, token)) {
1845 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not derive keys.");
1846 		ssl_error(card->ctx);
1847 		r = SC_ERROR_INTERNAL;
1848 		goto err;
1849 	}
1850 
1851 
1852 	/* Initialize secure channel */
1853 	if (!EAC_CTX_set_encryption_ctx(ctx, EAC_ID_CA)) {
1854 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not initialize encryption.");
1855 		ssl_error(card->ctx);
1856 		r = SC_ERROR_INTERNAL;
1857 		goto err;
1858 	}
1859 
1860 	if (card->sm_ctx.sm_mode != SM_MODE_TRANSMIT) {
1861 		r = eac_sm_start(card, ctx, NULL, 0, NULL, 0);
1862 	}
1863 
1864 err:
1865 	BUF_MEM_clear_free(picc_pubkey_buf);
1866 	BUF_MEM_clear_free(nonce);
1867 	BUF_MEM_clear_free(token);
1868 	BUF_MEM_clear_free(eph_pub_key);
1869 
1870 	if (card)
1871 		SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_SM, r);
1872 	else
1873 		return r;
1874 }
1875 
1876 static int
increment_ssc(struct eac_sm_ctx * eacsmctx)1877 increment_ssc(struct eac_sm_ctx *eacsmctx)
1878 {
1879 	if (!eacsmctx)
1880 		return SC_ERROR_INVALID_ARGUMENTS;
1881 
1882 	if (!EAC_increment_ssc(eacsmctx->ctx))
1883 		return SC_ERROR_INTERNAL;
1884 
1885 	return SC_SUCCESS;
1886 }
1887 
1888 static int
eac_sm_encrypt(sc_card_t * card,const struct iso_sm_ctx * ctx,const u8 * data,size_t datalen,u8 ** enc)1889 eac_sm_encrypt(sc_card_t *card, const struct iso_sm_ctx *ctx,
1890 		const u8 *data, size_t datalen, u8 **enc)
1891 {
1892 	BUF_MEM *encbuf = NULL, *databuf = NULL;
1893 	u8 *p = NULL;
1894 	int r;
1895 	struct eac_sm_ctx *eacsmctx;
1896 
1897 	if (!card || !ctx || !enc || !ctx->priv_data) {
1898 		r = SC_ERROR_INVALID_ARGUMENTS;
1899 		goto err;
1900 	}
1901 	eacsmctx = ctx->priv_data;
1902 
1903 	databuf = BUF_MEM_create_init(data, datalen);
1904 	encbuf = EAC_encrypt(eacsmctx->ctx, databuf);
1905 	if (!databuf || !encbuf || !encbuf->length) {
1906 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not encrypt data.");
1907 		ssl_error(card->ctx);
1908 		r = SC_ERROR_INTERNAL;
1909 		goto err;
1910 	}
1911 
1912 	p = realloc(*enc, encbuf->length);
1913 	if (!p) {
1914 		r = SC_ERROR_OUT_OF_MEMORY;
1915 		goto err;
1916 	}
1917 	*enc = p;
1918 	/* Flawfinder: ignore */
1919 	memcpy(*enc, encbuf->data, encbuf->length);
1920 	r = encbuf->length;
1921 
1922 err:
1923 	BUF_MEM_clear_free(databuf);
1924 	if (encbuf)
1925 		BUF_MEM_free(encbuf);
1926 
1927 	return r;
1928 }
1929 
1930 static int
eac_sm_decrypt(sc_card_t * card,const struct iso_sm_ctx * ctx,const u8 * enc,size_t enclen,u8 ** data)1931 eac_sm_decrypt(sc_card_t *card, const struct iso_sm_ctx *ctx,
1932 		const u8 *enc, size_t enclen, u8 **data)
1933 {
1934 	BUF_MEM *encbuf = NULL, *databuf = NULL;
1935 	u8 *p = NULL;
1936 	int r;
1937 	struct eac_sm_ctx *eacsmctx;
1938 
1939 	if (!card || !ctx || !enc || !ctx->priv_data || !data) {
1940 		r = SC_ERROR_INVALID_ARGUMENTS;
1941 		goto err;
1942 	}
1943 	eacsmctx = ctx->priv_data;
1944 
1945 	encbuf = BUF_MEM_create_init(enc, enclen);
1946 	databuf = EAC_decrypt(eacsmctx->ctx, encbuf);
1947 	if (!encbuf || !databuf || !databuf->length) {
1948 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not decrypt data.");
1949 		ssl_error(card->ctx);
1950 		r = SC_ERROR_INTERNAL;
1951 		goto err;
1952 	}
1953 
1954 	p = realloc(*data, databuf->length);
1955 	if (!p) {
1956 		r = SC_ERROR_OUT_OF_MEMORY;
1957 		goto err;
1958 	}
1959 	*data = p;
1960 	/* Flawfinder: ignore */
1961 	memcpy(*data, databuf->data, databuf->length);
1962 	r = databuf->length;
1963 
1964 err:
1965 	BUF_MEM_clear_free(databuf);
1966 	if (encbuf)
1967 		BUF_MEM_free(encbuf);
1968 
1969 	return r;
1970 }
1971 
1972 static int
eac_sm_authenticate(sc_card_t * card,const struct iso_sm_ctx * ctx,const u8 * data,size_t datalen,u8 ** macdata)1973 eac_sm_authenticate(sc_card_t *card, const struct iso_sm_ctx *ctx,
1974 		const u8 *data, size_t datalen, u8 **macdata)
1975 {
1976 	BUF_MEM *inbuf = NULL, *macbuf = NULL;
1977 	u8 *p = NULL;
1978 	int r;
1979 	struct eac_sm_ctx *eacsmctx;
1980 
1981 	if (!card || !ctx || !ctx->priv_data || !macdata) {
1982 		r = SC_ERROR_INVALID_ARGUMENTS;
1983 		goto err;
1984 	}
1985 	eacsmctx = ctx->priv_data;
1986 
1987 	inbuf = BUF_MEM_create_init(data, datalen);
1988 	if (!inbuf) {
1989 		r = SC_ERROR_OUT_OF_MEMORY;
1990 		goto err;
1991 	}
1992 
1993 	macbuf = EAC_authenticate(eacsmctx->ctx, inbuf);
1994 	if (!macbuf || !macbuf->length) {
1995 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1996 				"Could not compute message authentication code (MAC).");
1997 		ssl_error(card->ctx);
1998 		r = SC_ERROR_INTERNAL;
1999 		goto err;
2000 	}
2001 
2002 	p = realloc(*macdata, macbuf->length);
2003 	if (!p) {
2004 		r = SC_ERROR_OUT_OF_MEMORY;
2005 		goto err;
2006 	}
2007 	*macdata = p;
2008 	/* Flawfinder: ignore */
2009 	memcpy(*macdata, macbuf->data, macbuf->length);
2010 	r = macbuf->length;
2011 
2012 err:
2013 	if (inbuf)
2014 		BUF_MEM_free(inbuf);
2015 	if (macbuf)
2016 		BUF_MEM_free(macbuf);
2017 
2018 	return r;
2019 }
2020 
2021 static int
eac_sm_verify_authentication(sc_card_t * card,const struct iso_sm_ctx * ctx,const u8 * mac,size_t maclen,const u8 * macdata,size_t macdatalen)2022 eac_sm_verify_authentication(sc_card_t *card, const struct iso_sm_ctx *ctx,
2023 		const u8 *mac, size_t maclen,
2024 		const u8 *macdata, size_t macdatalen)
2025 {
2026 	int r;
2027 	BUF_MEM *inbuf = NULL, *my_mac = NULL;
2028 	struct eac_sm_ctx *eacsmctx;
2029 
2030 	if (!card || !ctx || !ctx->priv_data) {
2031 		r = SC_ERROR_INVALID_ARGUMENTS;
2032 		goto err;
2033 	}
2034 	eacsmctx = ctx->priv_data;
2035 
2036 	inbuf = BUF_MEM_create_init(macdata, macdatalen);
2037 	if (!inbuf) {
2038 		r = SC_ERROR_OUT_OF_MEMORY;
2039 		goto err;
2040 	}
2041 
2042 	my_mac = EAC_authenticate(eacsmctx->ctx, inbuf);
2043 	if (!my_mac) {
2044 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
2045 				"Could not compute message authentication code (MAC) for verification.");
2046 		ssl_error(card->ctx);
2047 		r = SC_ERROR_INTERNAL;
2048 		goto err;
2049 	}
2050 
2051 	if (my_mac->length != maclen ||
2052 			memcmp(my_mac->data, mac, maclen) != 0) {
2053 		r = SC_ERROR_OBJECT_NOT_VALID;
2054 		sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
2055 				"Authentication data not verified");
2056 		goto err;
2057 	}
2058 
2059 	sc_debug(card->ctx, SC_LOG_DEBUG_SM, "Authentication data verified");
2060 
2061 	r = SC_SUCCESS;
2062 
2063 err:
2064 	if (inbuf)
2065 		BUF_MEM_free(inbuf);
2066 	if (my_mac)
2067 		BUF_MEM_free(my_mac);
2068 
2069 	return r;
2070 }
2071 
2072 static int
add_tag(unsigned char ** asn1new,int constructed,int tag,int xclass,const unsigned char * data,size_t len)2073 add_tag(unsigned char **asn1new, int constructed, int tag,
2074 		int xclass, const unsigned char *data, size_t len)
2075 {
2076 	unsigned char *p;
2077 	int newlen;
2078 
2079 	if (!asn1new || !data)
2080 		return -1;
2081 
2082 	newlen = ASN1_object_size(constructed, len, tag);
2083 	if (newlen <= 0)
2084 		return newlen;
2085 
2086 	p = OPENSSL_realloc(*asn1new, newlen);
2087 	if (!p)
2088 		return -1;
2089 	*asn1new = p;
2090 
2091 	ASN1_put_object(&p, constructed, len, tag, xclass);
2092 	memcpy(p, data, len);
2093 
2094 	return newlen;
2095 }
2096 static int
eac_sm_pre_transmit(sc_card_t * card,const struct iso_sm_ctx * ctx,sc_apdu_t * apdu)2097 eac_sm_pre_transmit(sc_card_t *card, const struct iso_sm_ctx *ctx,
2098 		sc_apdu_t *apdu)
2099 {
2100 	int r;
2101 	CVC_CERT *cvc_cert = NULL;
2102 	unsigned char *cert = NULL;
2103 	int len;
2104 	BUF_MEM *signature = NULL;
2105 	unsigned char *sequence = NULL;
2106 	EAC_MSE_C *msesetat = NULL;
2107 	const unsigned char *p;
2108 	struct eac_sm_ctx *eacsmctx;
2109 
2110 	if (!card)
2111 	   return SC_ERROR_INVALID_ARGUMENTS;
2112 	if(!ctx || !apdu || !ctx->priv_data) {
2113 		r = SC_ERROR_INVALID_ARGUMENTS;
2114 		goto err;
2115 	}
2116 	eacsmctx = ctx->priv_data;
2117 
2118 	if (!(eacsmctx->flags & EAC_FLAG_DISABLE_CHECK_ALL)) {
2119 		if (apdu->ins == 0x2a && apdu->p1 == 0x00 && apdu->p2 == 0xbe) {
2120 			/* PSO:Verify Certificate
2121 			 * check certificate description to match given certificate */
2122 
2123 			len = add_tag(&cert, 1, 0x21, V_ASN1_APPLICATION, apdu->data, apdu->datalen);
2124 			p = cert;
2125 			if (len < 0 || !CVC_d2i_CVC_CERT(&cvc_cert, &p, len)
2126 					|| !cvc_cert || !cvc_cert->body) {
2127 				r = SC_ERROR_INVALID_DATA;
2128 				goto err;
2129 			}
2130 
2131 			switch (CVC_get_role(cvc_cert->body->chat)) {
2132 				case CVC_CVCA:
2133 					sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Processing CVCA certificate");
2134 					break;
2135 
2136 				case CVC_DV:
2137 				case CVC_DocVer:
2138 					sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Processing DV certificate");
2139 					break;
2140 
2141 				case CVC_Terminal:
2142 					sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Processing Terminal certificate");
2143 
2144 					if (eacsmctx->certificate_description) {
2145 						switch (CVC_check_description(cvc_cert,
2146 									(unsigned char *) eacsmctx->certificate_description->data,
2147 									eacsmctx->certificate_description->length)) {
2148 							case 1:
2149 								sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
2150 										"Certificate Description matches Certificate");
2151 								break;
2152 							case 0:
2153 								sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
2154 										"Certificate Description doesn't match Certificate");
2155 								r = SC_ERROR_INVALID_DATA;
2156 								goto err;
2157 								break;
2158 							default:
2159 								sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
2160 										"Error verifying Certificate Description");
2161 								ssl_error(card->ctx);
2162 								r = SC_ERROR_INTERNAL;
2163 								goto err;
2164 								break;
2165 						}
2166 					} else {
2167 						sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
2168 								"Warning: Certificate Description missing");
2169 					}
2170 					break;
2171 
2172 				default:
2173 					sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Unknown type of certificate");
2174 					r = SC_ERROR_INVALID_DATA;
2175 					goto err;
2176 					break;
2177 			}
2178 
2179 			if (!TA_STEP2_import_certificate(eacsmctx->ctx, cert, len)) {
2180 				sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
2181 						"Error importing certificate");
2182 				ssl_error(card->ctx);
2183 				r = SC_ERROR_INTERNAL;
2184 				goto err;
2185 			}
2186 
2187 		} else if (apdu->ins == ISO_MSE && apdu->p2 == 0xa4) {
2188 			/* MSE:Set AT */
2189 
2190 			len = add_tag(&sequence, 1, V_ASN1_SEQUENCE, V_ASN1_UNIVERSAL, apdu->data, apdu->datalen);
2191 			p = sequence;
2192 			if (len < 0 || !d2i_EAC_MSE_C(&msesetat, &p, len)) {
2193 				sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Could not parse MSE:Set AT.");
2194 				ssl_error(card->ctx);
2195 				r = SC_ERROR_INTERNAL;
2196 				goto err;
2197 			}
2198 
2199 			if (apdu->p1 == 0x81) {
2200 				/* CA: fetch auxiliary data and terminal's compressed ephemeral
2201 				 * public key */
2202 
2203 				if (msesetat->auxiliary_data) {
2204 					sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Saving terminal's auxiliary data");
2205 					if (eacsmctx->auxiliary_data)
2206 						BUF_MEM_free(eacsmctx->auxiliary_data);
2207 					eacsmctx->auxiliary_data = BUF_MEM_new();
2208 					if (!eacsmctx->auxiliary_data) {
2209 						r = SC_ERROR_OUT_OF_MEMORY;
2210 						goto err;
2211 					}
2212 					eacsmctx->auxiliary_data->length = i2d_ASN1_AUXILIARY_DATA(
2213 							msesetat->auxiliary_data,
2214 							(unsigned char **) &eacsmctx->auxiliary_data->data);
2215 					if ((int) eacsmctx->auxiliary_data->length < 0) {
2216 						sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Error encoding auxiliary data.");
2217 						ssl_error(card->ctx);
2218 						r = SC_ERROR_INTERNAL;
2219 						goto err;
2220 					}
2221 					eacsmctx->auxiliary_data->max = eacsmctx->auxiliary_data->length;
2222 				}
2223 				if (msesetat->eph_pub_key) {
2224 					sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Saving terminal's compressed ephemeral public key");
2225 					if (eacsmctx->eph_pub_key)
2226 						BUF_MEM_free(eacsmctx->eph_pub_key);
2227 					eacsmctx->eph_pub_key =
2228 						BUF_MEM_create_init(msesetat->eph_pub_key->data,
2229 								msesetat->eph_pub_key->length);
2230 					if (!eacsmctx->eph_pub_key) {
2231 						r = SC_ERROR_OUT_OF_MEMORY;
2232 						goto err;
2233 					}
2234 				}
2235 			} else if (apdu->p1 == 0x41) {
2236 				/* TA: Set CAR */
2237 
2238 				if (msesetat->key_reference1 && msesetat->key_reference1->data &&
2239 						msesetat->key_reference1->length) {
2240 					/* do nothing. The trust anchor matching this CAR will be
2241 					 * looked up when the certificate chain is imported */
2242 				}
2243 			}
2244 		} else if (apdu->ins == 0x82 && apdu->p1 == 0x00 && apdu->p2 == 0x00) {
2245 			/* External Authenticate
2246 			 * check terminal's signature */
2247 
2248 			signature = BUF_MEM_create_init(apdu->data, apdu->datalen);
2249 			if (!signature) {
2250 				r = SC_ERROR_OUT_OF_MEMORY;
2251 				goto err;
2252 			}
2253 			switch (TA_STEP6_verify(eacsmctx->ctx, eacsmctx->eph_pub_key,
2254 						eacsmctx->id_icc, eacsmctx->auxiliary_data, signature)) {
2255 				case 1:
2256 					sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
2257 							"Verified Terminal's signature");
2258 					break;
2259 				case 0:
2260 					sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
2261 							"Terminal's signature not verified");
2262 					r = SC_ERROR_INVALID_DATA;
2263 					goto err;
2264 					break;
2265 				default:
2266 					sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
2267 							"Error verifying terminal's signature");
2268 					ssl_error(card->ctx);
2269 					r = SC_ERROR_INTERNAL;
2270 					goto err;
2271 					break;
2272 			}
2273 		}
2274 	}
2275 
2276 	r = increment_ssc(ctx->priv_data);
2277 
2278 err:
2279 	if (cvc_cert)
2280 		CVC_CERT_free(cvc_cert);
2281 	if (signature)
2282 		BUF_MEM_free(signature);
2283 	if (cert)
2284 		OPENSSL_free(cert);
2285 	if (sequence)
2286 		OPENSSL_free(sequence);
2287 	if (msesetat)
2288 		EAC_MSE_C_free(msesetat);
2289 
2290 	SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_SM, r);
2291 }
2292 
2293 static int
eac_sm_post_transmit(sc_card_t * card,const struct iso_sm_ctx * ctx,sc_apdu_t * sm_apdu)2294 eac_sm_post_transmit(sc_card_t *card, const struct iso_sm_ctx *ctx,
2295 		sc_apdu_t *sm_apdu)
2296 {
2297 	SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_SM,
2298 			increment_ssc(ctx->priv_data));
2299 }
2300 
2301 static int
eac_sm_finish(sc_card_t * card,const struct iso_sm_ctx * ctx,sc_apdu_t * apdu)2302 eac_sm_finish(sc_card_t *card, const struct iso_sm_ctx *ctx,
2303 		sc_apdu_t *apdu)
2304 {
2305 	struct eac_sm_ctx *eacsmctx;
2306 	if (!card)
2307 	   return SC_ERROR_INVALID_ARGUMENTS;
2308 	if(!ctx || !ctx->priv_data || !apdu)
2309 		SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_SM,
2310 				SC_ERROR_INVALID_ARGUMENTS);
2311 	eacsmctx = ctx->priv_data;
2312 
2313 	if (!(eacsmctx->flags & EAC_FLAG_DISABLE_CHECK_ALL)) {
2314 		if (apdu->sw1 == 0x90 && apdu->sw2 == 0x00) {
2315 			if (apdu->ins == 0x84 && apdu->p1 == 0x00 && apdu->p2 == 0x00
2316 					&& apdu->le == 8 && apdu->resplen == 8) {
2317 				BUF_MEM *nonce;
2318 				int r;
2319 				/* Get Challenge
2320 				 * copy challenge to EAC context */
2321 
2322 				sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "Saving MRTD's nonce to later verify Terminal's signature");
2323 
2324 				nonce = BUF_MEM_create_init(apdu->resp, apdu->resplen);
2325 				r = TA_STEP4_set_nonce(eacsmctx->ctx, nonce);
2326 				if (nonce)
2327 					BUF_MEM_free(nonce);
2328 
2329 				if (!r) {
2330 					ssl_error(card->ctx);
2331 					SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_SM,  SC_ERROR_INTERNAL);
2332 				}
2333 			}
2334 		}
2335 	}
2336 
2337 	SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_SM,  SC_SUCCESS);
2338 }
2339 
2340 static void
eac_sm_clear_free(const struct iso_sm_ctx * ctx)2341 eac_sm_clear_free(const struct iso_sm_ctx *ctx)
2342 {
2343 	if (ctx) {
2344 		struct eac_sm_ctx *eacsmctx = ctx->priv_data;
2345 		if (eacsmctx) {
2346 			EAC_CTX_clear_free(eacsmctx->ctx);
2347 			if (eacsmctx->certificate_description)
2348 				BUF_MEM_free(eacsmctx->certificate_description);
2349 			if (eacsmctx->id_icc)
2350 				BUF_MEM_free(eacsmctx->id_icc);
2351 			if (eacsmctx->eph_pub_key)
2352 				BUF_MEM_free(eacsmctx->eph_pub_key);
2353 			if (eacsmctx->auxiliary_data)
2354 				BUF_MEM_free(eacsmctx->auxiliary_data);
2355 			free(eacsmctx);
2356 		}
2357 	}
2358 }
2359 
2360 #else
2361 
2362 int perform_pace(sc_card_t *card,
2363 		struct establish_pace_channel_input pace_input,
2364 		struct establish_pace_channel_output *pace_output,
2365 		enum eac_tr_version tr_version)
2366 {
2367 	int r;
2368 
2369 	if (card && card->reader
2370 			&& card->reader->capabilities & SC_READER_CAP_PACE_GENERIC
2371 			&& card->reader->ops->perform_pace) {
2372 		r = card->reader->ops->perform_pace(card->reader, &pace_input, pace_output);
2373 	} else {
2374 		r = SC_ERROR_NOT_SUPPORTED;
2375 	}
2376 
2377 	return r;
2378 }
2379 
2380 int perform_terminal_authentication(sc_card_t *card,
2381 		const unsigned char **certs, const size_t *certs_lens,
2382 		const unsigned char *privkey, size_t privkey_len,
2383 		const unsigned char *auxiliary_data, size_t auxiliary_data_len)
2384 {
2385 	return SC_ERROR_NOT_SUPPORTED;
2386 }
2387 
2388 int perform_chip_authentication(sc_card_t *card,
2389 		unsigned char **ef_cardsecurity, size_t *ef_cardsecurity_len)
2390 {
2391 	return SC_ERROR_NOT_SUPPORTED;
2392 }
2393 
2394 int perform_chip_authentication_ex(sc_card_t *card, void *eac_ctx,
2395 		unsigned char *picc_pubkey, size_t picc_pubkey_len)
2396 {
2397 	return SC_ERROR_NOT_SUPPORTED;
2398 }
2399 
2400 #endif
2401 
2402 static const char *MRZ_name = "MRZ";
2403 static const char *PIN_name = "eID PIN";
2404 static const char *PUK_name = "PUK";
2405 static const char *CAN_name = "CAN";
2406 static const char *UNDEF_name = "UNDEF";
eac_secret_name(enum s_type pin_id)2407 const char *eac_secret_name(enum s_type pin_id) {
2408 	switch (pin_id) {
2409 		case PACE_MRZ:
2410 			return MRZ_name;
2411 		case PACE_PUK:
2412 			return PUK_name;
2413 		case PACE_PIN:
2414 			return PIN_name;
2415 		case PACE_CAN:
2416 			return CAN_name;
2417 		default:
2418 			return UNDEF_name;
2419 	}
2420 }
2421 
eac_pace_get_tries_left(sc_card_t * card,enum s_type pin_id,int * tries_left)2422 int eac_pace_get_tries_left(sc_card_t *card,
2423 		enum s_type pin_id, int *tries_left)
2424 {
2425 	int r;
2426 	u8 sw1, sw2;
2427 
2428 	if (tries_left) {
2429 #if defined(ENABLE_OPENPACE) && defined(ENABLE_SM)
2430 		r = eac_mse_set_at_pace(card, 0, pin_id, 0, &sw1, &sw2);
2431 #else
2432 		sc_apdu_t apdu;
2433 		sc_format_apdu_ex(&apdu, 0x00, ISO_MSE, 0xC1, 0xA4, NULL, 0, NULL, 0);
2434 		r = sc_transmit_apdu(card, &apdu);
2435 		sw1 = apdu.sw1;
2436 		sw2 = apdu.sw2;
2437 #endif
2438 
2439 		if (r > 0 && (sw1 == 0x63) && ((sw2 & 0xc0) == 0xc0)) {
2440 			*tries_left = sw2 & 0x0f;
2441 		} else {
2442 			*tries_left = -1;
2443 		}
2444 	} else {
2445 		r = SC_ERROR_INVALID_ARGUMENTS;
2446 	}
2447 
2448 	return r;
2449 }
2450