1 /*
2  * card-coolkey.c: Support for Coolkey
3  *
4  * Copyright (C) 2001, 2002  Juha Yrjölä <juha.yrjola@iki.fi>
5  * Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov>
6  * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com>
7  * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com>
8  * Copyright (C) 2016, Red Hat, Inc.
9  *
10  * Coolkey driver author: Robert Relyea <rrelyea@redhat.com>
11  *
12  * This library is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with this library; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25  */
26 
27 #if HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30 
31 #include <ctype.h>
32 #include <fcntl.h>
33 #include <limits.h>
34 #include <stdlib.h>
35 #include <string.h>
36 
37 #ifdef _WIN32
38 #include <io.h>
39 #else
40 #include <unistd.h>
41 #endif
42 
43 #include <sys/types.h>
44 
45 #ifdef ENABLE_OPENSSL
46 	/* openssl only needed for card administration */
47 #include <openssl/evp.h>
48 #include <openssl/bio.h>
49 #include <openssl/pem.h>
50 #include <openssl/rand.h>
51 #include <openssl/rsa.h>
52 #endif /* ENABLE_OPENSSL */
53 
54 #include "internal.h"
55 #include "asn1.h"
56 #include "cardctl.h"
57 #ifdef ENABLE_ZLIB
58 #include "compression.h"
59 #endif
60 #include "iso7816.h"
61 #include "gp.h"
62 #include "../pkcs11/pkcs11.h"
63 
64 
65 
66 #define COOLKEY_MAX_SIZE 4096		/* arbitrary, just needs to be 'large enough' */
67 
68 /*
69  *  COOLKEY hardware and APDU constants
70  */
71 #define COOLKEY_MAX_CHUNK_SIZE 240 /* must be less than 255-8 */
72 
73 /* ISO 7816 CLA values used by COOLKEY */
74 #define ISO7816_CLASS           0x00
75 #define COOLKEY_CLASS           0xb0
76 
77 /* ISO 71816 INS values used by COOLKEY */
78 #define ISO7816_INS_SELECT_FILE 0xa4
79 
80 /* COOLKEY specific INS values (public) */
81 #define COOLKEY_INS_GET_LIFE_CYCLE             0xf2
82 #define COOLKEY_INS_GET_STATUS                 0x3c
83 #define COOLKEY_INS_VERIFY_PIN                 0x42
84 #define COOLKEY_INS_LIST_OBJECTS               0x58
85 
86 /* COOLKEY specific INS values (require nonce) */
87 #define COOLKEY_INS_COMPUTE_CRYPT              0x36
88 #define COOLKEY_INS_COMPUTE_ECC_KEY_AGREEMENT  0x37
89 #define COOLKEY_INS_COMPUTE_ECC_SIGNATURE      0x38
90 #define COOLKEY_INS_GET_RANDOM                 0x72
91 #define COOLKEY_INS_READ_OBJECT                0x56
92 #define COOLKEY_INS_WRITE_OBJECT               0x54
93 #define COOLKEY_INS_LOGOUT                     0x61
94 
95 /* COMPUTE_CRYPT and COMPUT_ECC parameters */
96 #define COOLKEY_CRYPT_INIT     1
97 #define COOLKEY_CRYPT_PROCESS  2
98 #define COOLKEY_CRYPT_FINAL    3
99 #define COOLKEY_CRYPT_ONE_STEP 4
100 
101 #define COOLKEY_CRYPT_MODE_RSA_NO_PAD    0x00
102 #define COOLKEY_CRYPT_LOCATION_APDU      0x01
103 #define COOLKEY_CRYPT_LOCATION_DL_OBJECT 0x02
104 #define COOLKEY_CRYPT_DIRECTION_ENCRYPT  0x03
105 
106 /* List Objects parameters */
107 #define COOLKEY_LIST_RESET 0x00
108 #define COOLKEY_LIST_NEXT  0x01
109 
110 /* Special object identifiers */
111 #define COOLKEY_DL_OBJECT_ID       0xffffffff
112 #define COOLKEY_COMBINED_OBJECT_ID 0x7a300000 /* 'z0\0\0' */
113 #define COOLKEY_INVALID_KEY        0xff00
114 #define COOLKEY_KEY_CLASS			'k'
115 #define COOLKEY_NONCE_SIZE  8
116 
117 /* returned from the coolkey extended life cycle apdu */
118 typedef struct coolkey_life_cycle {
119 	u8 life_cycle;
120 	u8 pin_count;
121 	u8 protocol_version_major;
122 	u8 protocol_version_minor;
123 } coolkey_life_cycle_t;
124 
125 /* return by the coolkey status apdu */
126 typedef struct coolkey_status {
127 	u8 protocol_version_major;
128 	u8 protocol_version_minor;
129 	u8 applet_major_version;
130 	u8 applet_minor_version;
131 	u8 total_object_memory[4];
132 	u8 free_object_memory[4];
133 	u8 pin_count;
134 	u8 key_count;
135 	u8 logged_in_identities[2];
136 } coolkey_status_t;
137 
138 /* format of the coolkey_cuid, either constructed from cplc data or read from the combined object */
139 typedef struct coolkey_cuid {
140 	u8 ic_fabricator[2];
141 	u8 ic_type[2];
142 	u8 ic_batch[2];
143 	u8 ic_serial_number[4];
144 } coolkey_cuid_t;
145 
146 /* parameter for list objects apdu */
147 typedef struct coolkey_object_info {
148 	u8 object_id[4];
149 	u8 object_length[4];
150 	u8 read_acl[2];
151 	u8 write_acl[2];
152 	u8 delete_acl[2];
153 } coolkey_object_info_t;
154 
155 /* parameter for the read object apdu */
156 typedef struct coolkey_read_object_param {
157 	u8 object_id[4];
158 	u8 offset[4];
159 	u8 length;
160 } coolkey_read_object_param_t;
161 
162 /* parameter for the write object apdu */
163 typedef struct coolkey_write_object_param {
164 	coolkey_read_object_param_t head;
165 	u8 buf[COOLKEY_MAX_CHUNK_SIZE];
166 } coolkey_write_object_param_t;
167 
168 /* coolkey uses muscle like objects, but when coolkey is managed by the TPS system
169  * it creates a single object and encodes the individual objects inside the
170  * common single object. This allows more efficient reading of all the objects
171  * (because we can use a single apdu call and we can compress all the objects
172  * together and take advantage of the fact that many of the certs share the same subject and issue). */
173 typedef struct coolkey_combined_header {
174 	u8	format_version[2];
175 	u8	object_version[2];
176 	coolkey_cuid_t cuid;
177 	u8	compression_type[2];
178 	u8	compression_length[2];
179 	u8	compression_offset[2];
180 } coolkey_combined_header_t;
181 
182 #define COOLKEY_COMPRESSION_NONE 0
183 #define COOLKEY_COMPRESSION_ZLIB 1
184 
185 /*
186  * This is the header of the decompressed portion of the combined object
187  */
188 typedef struct coolkey_decompressed_header {
189 	u8 object_offset[2];
190 	u8 object_count[2];
191 	u8 token_name_length;
192 	u8 token_name[255];      /* arbitrary size up to token_name_length */
193 } coolkey_decompressed_header_t;
194 
195 /*
196  * header for an object. There are 2 types of object headers, v1 and v0.
197  * v1 is the most common, and is always found in a combined object, so
198  * we only specify the v0 in the name of the structure.
199  */
200 
201 typedef struct coolkey_v0_object_header {
202 	u8 record_type;				 /* version 0 or version 1 */
203 	u8 object_id[4]; 			 /*  coolkey object id  */
204 	u8 attribute_data_len[2];    /* the length in bytes of the next block of
205 								  * attribute records */
206 	/* followed by the first attribute record */
207 } coolkey_v0_object_header_t;
208 
209 typedef struct coolkey_v0_attribute_header {
210 	u8 attribute_attr_type[4];	/* CKA_ATTRIBUTE_TYPE */
211 	u8 attribute_data_len[2];	/* Length of the attribute */
212 	/* followed by the actual attribute data */
213 } coolkey_v0_attribute_header_t;
214 
215 /* combined objects are v1 objects without the record_type indicator */
216 typedef struct coolkey_combined_object_header {
217 	u8 object_id[4]; 			 /*  coolkey object id  */
218 	u8 fixed_attributes_values[4]; /* compressed fixed attributes */
219 	u8 attribute_count[2];		/* the number of attribute records that follow */
220 	/* followed by the first attribute */
221 } coolkey_combined_object_header_t;
222 
223 typedef struct coolkey_object_header {
224 	u8 record_type;				/* version 0 or version 1 */
225 	u8 object_id[4]; 			 /*  coolkey object id  */
226 	u8 fixed_attributes_values[4]; /* compressed fixed attributes */
227 	u8 attribute_count[2];		/* the number of attribute records that follow */
228 	/* followed by the first attribute */
229 } coolkey_object_header_t;
230 
231 #define COOLKEY_V0_OBJECT 0
232 #define COOLKEY_V1_OBJECT 1
233 
234 /* vi attribute header */
235 typedef struct coolkey_attribute_header {
236 	u8 attribute_attr_type[4]; /* CKA_ATTRIBUTE_TYPE */
237 	u8 attribute_data_type;    /* the Type of data stored */
238 	/* optional attribute data, or attribute len+data, depending on the value of data_type */
239 } coolkey_attribute_header_t;
240 
241 /* values for attribute_data_type */
242 #define COOLKEY_ATTR_TYPE_STRING      0
243 #define COOLKEY_ATTR_TYPE_INTEGER     1
244 #define COOLKEY_ATTR_TYPE_BOOL_FALSE  2
245 #define COOLKEY_ATTR_TYPE_BOOL_TRUE   3
246 
247 /*
248  * format of the fix_attribute values. These are stored as a big endian uint32_t with the below bit field
249  * Definitions:
250  *
251 struct coolkey_fixed_attributes_values {
252 	uint32_t  cka_id:4;
253 	uint32_t  cka_class:3;
254 	uint32_t  cka_token:1;
255 	uint32_t  cka_private:1;
256 	uint32_t  cka_modifiable:1;
257 	uint32_t  cka_derive:1;
258 	uint32_t  cka_local:1;
259 	uint32_t  cka_encrypt:1;
260 	uint32_t  cka_decrypt:1;
261 	uint32_t  cka_wrap:1;
262 	uint32_t  cka_unwrap:1;
263 	uint32_t  cka_sign:1;
264 	uint32_t  cka_sign_recover:1;
265 	uint32_t  cka_verify:1;
266 	uint32_t  cka_verify_recover:1;
267 	uint32_t  cka_sensitive:1;
268 	uint32_t  cka_always_sensitive:1;
269 	uint32_t  cka_extractable:1;
270 	uint32_t  cka_never_extractable:1;
271 	uint32_t  reserved:8;
272 };
273 
274  *  cka_class is used to determine which booleans are valid. Any attributes in the full attribute list
275  *  takes precedence over the fixed attributes. That is if there is a CKA_ID in the full attribute list,
276  *  The cka_id in the fixed_attributes is ignored. When determining which boolean attribute is valid, the
277  *  cka_class in the fixed attributes are used, even if it is overridden by the  full attribute list.
278  * valid cka_class values and their corresponding valid bools are as follows:
279  *
280  *     0 CKO_DATA                          cka_private, cka_modifiable, cka_token
281  *     1 CKO_CERTIFICATE                   cka_private, cka_modifiable, cka_token
282  *     2 CKO_PUBLIC_KEY                    cka_private, cka_modifiable, cka_token
283  *                                         cka_derive, cka_local, cka_encrypt, cka_wrap
284  *                                         cka_verify, cka_verify_recover
285  *     3 CKO_PRIVATE_KEY                   cka_private, cka_modifiable, cka_token
286  *                                         cka_derive, cka_local, cka_decrypt, cka_unwrap
287  *                                         cka_sign, cka_sign_recover, cka_sensitive,
288  *                                         cka_always_sensitive, cka_extractable,
289  *                                         cka_never_extractable
290  *     4 CKO_SECRET_KEY                    cka_private, cka_modifiable, cka_token
291  *                                         cka_derive, cka_local, cka_encrypt, cka_decrypt,
292  *                                         cka_wrap, cka_unwrap, cka_sign, cka_verify,
293  *                                         cka_sensitive, cka_always_sensitive,
294  *                                         cka_extractable, cka_never_extractable
295  *     5-7 RESERVED                        none
296  *
297  */
298 
299 /*
300  * Coolkey attribute record handling functions.
301  */
302 
303 /* get the length of the attribute from a V1 attribute header. If encoded_len == true, then return the length of
304  * the attribute data field (including any explicit length values, If encoded_len = false return the length of
305  * the actual attribute data.
306  */
307 static int
coolkey_v1_get_attribute_len(const u8 * attr,size_t buf_len,size_t * len,int encoded_len)308 coolkey_v1_get_attribute_len(const u8 *attr, size_t buf_len, size_t *len, int encoded_len)
309 {
310 	coolkey_attribute_header_t *attribute_head = (coolkey_attribute_header_t *)attr;
311 
312 	*len = 0;
313 	/* don't reference beyond our buffer */
314 	if (buf_len < sizeof(coolkey_attribute_header_t)) {
315 		return SC_ERROR_CORRUPTED_DATA;
316 	}
317 	switch (attribute_head->attribute_data_type) {
318 	case COOLKEY_ATTR_TYPE_STRING:
319 		if (buf_len < (sizeof(coolkey_attribute_header_t) +2)) {
320 			break;
321 		}
322 		*len = bebytes2ushort(attr + sizeof(coolkey_attribute_header_t));
323 		if (encoded_len) {
324 			*len += 2;
325 		}
326 		return SC_SUCCESS;
327 	case COOLKEY_ATTR_TYPE_BOOL_FALSE:
328 	case COOLKEY_ATTR_TYPE_BOOL_TRUE:
329 		/* NOTE: there is no encoded data from TYPE_BOOL_XXX, so we return length 0, but the length
330 		 * of the attribute is actually 1 byte, so if encoded_len == false, return 1 */
331 		*len = encoded_len ? 0: 1;
332 		return SC_SUCCESS;
333 		break;
334 	case COOLKEY_ATTR_TYPE_INTEGER:
335 		*len = 4; /* length is 4 in both encoded length and attribute length */
336 		return SC_SUCCESS;
337 	default:
338 		break;
339 	}
340 	return SC_ERROR_CORRUPTED_DATA;
341 }
342 
343 /* length of the attribute data is stored in the header of the v0 record */
344 static int
coolkey_v0_get_attribute_len(const u8 * attr,size_t buf_len,size_t * len)345 coolkey_v0_get_attribute_len(const u8 *attr, size_t buf_len, size_t *len)
346 {
347 	coolkey_v0_attribute_header_t *attribute_head = (coolkey_v0_attribute_header_t *)attr;
348 	/* don't reference beyond our buffer */
349 	if (buf_len < sizeof(coolkey_v0_attribute_header_t)) {
350 		return SC_ERROR_CORRUPTED_DATA;
351 	}
352 	*len = bebytes2ushort(attribute_head->attribute_data_len);
353 	return SC_SUCCESS;
354 }
355 
356 /* these next 3 functions gets the length of the full attribute record, including
357  * the attribute header */
358 static size_t
coolkey_v1_get_attribute_record_len(const u8 * attr,size_t buf_len)359 coolkey_v1_get_attribute_record_len(const u8 *attr, size_t buf_len)
360 {
361 	size_t attribute_len = sizeof(coolkey_attribute_header_t);
362 	size_t len = 0;
363 	int r;
364 
365 	r = coolkey_v1_get_attribute_len(attr, buf_len, &len, 1);
366 	if (r < 0) {
367 		return buf_len; /* skip to the end, ignore the rest of the record */
368 	}
369 
370 	return MIN(buf_len,attribute_len+len);
371 }
372 
373 
374 static size_t
coolkey_v0_get_attribute_record_len(const u8 * attr,size_t buf_len)375 coolkey_v0_get_attribute_record_len(const u8 *attr, size_t buf_len)
376 {
377 	size_t attribute_len = sizeof(coolkey_v0_attribute_header_t);
378 	size_t len;
379 	int r;
380 
381 	r = coolkey_v0_get_attribute_len(attr, buf_len, &len);
382 	if (r < 0) {
383 		return buf_len; /* skip to the end, ignore the rest of the record */
384 	}
385 	return MIN(buf_len,attribute_len+len);
386 }
387 
388 static size_t
coolkey_get_attribute_record_len(const u8 * attr,u8 obj_record_type,size_t buf_len)389 coolkey_get_attribute_record_len(const u8 *attr, u8 obj_record_type, size_t buf_len)
390 {
391 	if (obj_record_type ==  COOLKEY_V0_OBJECT) {
392 		return coolkey_v0_get_attribute_record_len(attr, buf_len);
393 	}
394 	if (obj_record_type != COOLKEY_V1_OBJECT) {
395 		return buf_len; /* skip to the end */
396 	}
397 	return coolkey_v1_get_attribute_record_len(attr, buf_len);
398 }
399 
400 /*
401  * Attribute type shows up in the same place in all attribute record types. Carry record_type in case
402  * this changes in the future.
403  */
404 static CK_ATTRIBUTE_TYPE
coolkey_get_attribute_type(const u8 * attr,u8 obj_record_type,size_t buf_len)405 coolkey_get_attribute_type(const u8 *attr, u8 obj_record_type, size_t buf_len)
406 {
407 	coolkey_attribute_header_t *attribute_header = (coolkey_attribute_header_t *) attr;
408 
409 	return bebytes2ulong(attribute_header->attribute_attr_type);
410 }
411 
412 /*
413  * return the start of the attribute section based on the record type
414  */
415 static const u8 *
coolkey_attribute_start(const u8 * obj,u8 object_record_type,size_t buf_len)416 coolkey_attribute_start(const u8 *obj, u8 object_record_type, size_t buf_len)
417 {
418 	size_t offset = object_record_type == COOLKEY_V1_OBJECT ? sizeof(coolkey_object_header_t) :
419 			sizeof(coolkey_v0_object_header_t);
420 
421 	if ((object_record_type != COOLKEY_V1_OBJECT) && (object_record_type != COOLKEY_V0_OBJECT)) {
422 		return NULL;
423 	}
424 	if (offset > buf_len) {
425 		return NULL;
426 	}
427 	return obj + offset;
428 }
429 
430 /*
431  * We don't have the count in the header for v0 attributes,
432  * Count them.
433  */
434 static int
coolkey_v0_get_attribute_count(const u8 * obj,size_t buf_len)435 coolkey_v0_get_attribute_count(const u8 *obj, size_t buf_len)
436 {
437 	coolkey_v0_object_header_t *object_head = (coolkey_v0_object_header_t *)obj;
438 	const u8 *attr;
439 	int count = 0;
440 	size_t attribute_data_len;
441 
442 	/* make sure we have enough of the object to read the record_type */
443 	if (buf_len <= sizeof(coolkey_v0_object_header_t)) {
444 		return 0;
445 	}
446 	/*
447 	 * now loop through all the attributes in the list. first find the start of the list
448 	 */
449 	attr = coolkey_attribute_start(obj, COOLKEY_V0_OBJECT, buf_len);
450 	if (attr == NULL) {
451 		return 0;
452 	}
453 
454 	buf_len -= (attr-obj);
455 	attribute_data_len = bebytes2ushort(object_head->attribute_data_len);
456 	if (buf_len < attribute_data_len) {
457 		return 0;
458 	}
459 
460 	while (attribute_data_len) {
461 		size_t len = coolkey_v0_get_attribute_record_len(attr, buf_len);
462 
463 		if (len == 0) {
464 			break;
465 		}
466 		/*  This is an error in the token data, don't parse the last attribute */
467 		if (len > attribute_data_len) {
468 			break;
469 		}
470 		/* we know that coolkey_v0_get_attribute_record_len never
471 		 * 	returns more than buf_len, so we can safely assert that.
472 		 * 	If the assert is true, you can easily see that the loop
473 		 * 	will eventually break with len == 0, even if attribute_data_len
474 		 * 	was invalid */
475 		assert(len <= buf_len);
476 		count++;
477 		attr += len;
478 		buf_len -= len;
479 		attribute_data_len -= len;
480 	}
481 	return count;
482 }
483 
484 static int
coolkey_v1_get_attribute_count(const u8 * obj,size_t buf_len)485 coolkey_v1_get_attribute_count(const u8 *obj, size_t buf_len)
486 {
487 	coolkey_object_header_t *object_head = (coolkey_object_header_t *)obj;
488 
489 	if (buf_len <= sizeof(coolkey_object_header_t)) {
490 		return 0;
491 	}
492 	return bebytes2ushort(object_head->attribute_count);
493 }
494 
495 static int
coolkey_get_attribute_count(const u8 * obj,u8 object_record_type,size_t buf_len)496 coolkey_get_attribute_count(const u8 *obj, u8 object_record_type, size_t buf_len)
497 {
498 	if (object_record_type == COOLKEY_V0_OBJECT) {
499 		return coolkey_v0_get_attribute_count(obj, buf_len);
500 	}
501 	if (object_record_type != COOLKEY_V1_OBJECT) {
502 		return 0;
503 	}
504 	return coolkey_v1_get_attribute_count(obj, buf_len);
505 }
506 
507 /*
508  * The next three functions return a parsed attribute value from an attribute record.
509  */
510 static int
coolkey_v0_get_attribute_data(const u8 * attr,size_t buf_len,sc_cardctl_coolkey_attribute_t * attr_out)511 coolkey_v0_get_attribute_data(const u8 *attr, size_t buf_len, sc_cardctl_coolkey_attribute_t *attr_out)
512 {
513 	/* we need to manually detect types CK_ULONG */
514 	CK_ATTRIBUTE_TYPE attr_type = coolkey_get_attribute_type(attr, COOLKEY_V0_OBJECT, buf_len);
515 	int r;
516 	size_t len;
517 
518 	attr_out->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_STRING;
519 	attr_out->attribute_length = 0;
520 	attr_out->attribute_value = NULL;
521 
522 	r = coolkey_v0_get_attribute_len(attr, buf_len, &len);
523 	if (r < 0) {
524 		return r;
525 	}
526 	if (len + sizeof(coolkey_v0_attribute_header_t) > buf_len) {
527 		return SC_ERROR_CORRUPTED_DATA;
528 	}
529 	if ((attr_type == CKA_CLASS) || (attr_type == CKA_CERTIFICATE_TYPE)
530 									 || (attr_type == CKA_KEY_TYPE)) {
531 		if (len != 4) {
532 			return SC_ERROR_CORRUPTED_DATA;
533 		}
534 		attr_out->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_ULONG;
535 	}
536 	/* return the length and the data */
537 	attr_out->attribute_length = len;
538 	attr_out->attribute_value = attr + sizeof(coolkey_v0_attribute_header_t);
539 	return SC_SUCCESS;
540 }
541 
542 static u8 coolkey_static_false = CK_FALSE;
543 static u8 coolkey_static_true = CK_TRUE;
544 
545 static int
coolkey_v1_get_attribute_data(const u8 * attr,size_t buf_len,sc_cardctl_coolkey_attribute_t * attr_out)546 coolkey_v1_get_attribute_data(const u8 *attr, size_t buf_len, sc_cardctl_coolkey_attribute_t *attr_out)
547 {
548 	int r;
549 	size_t len;
550 	coolkey_attribute_header_t *attribute_head = (coolkey_attribute_header_t *)attr;
551 
552 	if (buf_len < sizeof(coolkey_attribute_header_t)) {
553 		return SC_ERROR_CORRUPTED_DATA;
554 	}
555 
556 	/* we must have type V1. Process according to data type */
557 	switch (attribute_head->attribute_data_type) {
558 	/* ULONG has implied length of 4 */
559 	case COOLKEY_ATTR_TYPE_INTEGER:
560 		if (buf_len < (sizeof(coolkey_attribute_header_t) + 4)) {
561 			return SC_ERROR_CORRUPTED_DATA;
562 		}
563 		attr_out->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_ULONG;
564 		attr_out->attribute_length = 4;
565 		attr_out->attribute_value = attr + sizeof(coolkey_attribute_header_t);
566 		return SC_SUCCESS;
567 	/* BOOL_FALSE and BOOL_TRUE have implied length and data */
568 	/* return type STRING for BOOLS */
569 	case COOLKEY_ATTR_TYPE_BOOL_FALSE:
570 		attr_out->attribute_length = 1;
571 		attr_out->attribute_value =  &coolkey_static_false;
572 		return SC_SUCCESS;
573 	case COOLKEY_ATTR_TYPE_BOOL_TRUE:
574 		attr_out->attribute_length = 1;
575 		attr_out->attribute_value =  &coolkey_static_true;
576 		return SC_SUCCESS;
577 	/* string type has encoded length */
578 	case COOLKEY_ATTR_TYPE_STRING:
579 		r = coolkey_v1_get_attribute_len(attr, buf_len, &len, 0);
580 		if (r < SC_SUCCESS) {
581 			return r;
582 		}
583 		if (buf_len < (len + sizeof(coolkey_attribute_header_t) + 2)) {
584 			return SC_ERROR_CORRUPTED_DATA;
585 		}
586 		attr_out->attribute_value = attr+sizeof(coolkey_attribute_header_t)+2;
587 		attr_out->attribute_length = len;
588 		return SC_SUCCESS;
589 	default:
590 		break;
591 	}
592 	return SC_ERROR_CORRUPTED_DATA;
593 }
594 
595 int
coolkey_get_attribute_data(const u8 * attr,u8 object_record_type,size_t buf_len,sc_cardctl_coolkey_attribute_t * attr_out)596 coolkey_get_attribute_data(const u8 *attr, u8 object_record_type, size_t buf_len, sc_cardctl_coolkey_attribute_t *attr_out)
597 {
598 	/* handle the V0 objects first */
599 	if (object_record_type == COOLKEY_V0_OBJECT) {
600 		return coolkey_v0_get_attribute_data(attr, buf_len, attr_out);
601 	}
602 
603 	/* don't crash if we encounter some new or corrupted coolkey device */
604 	if (object_record_type != COOLKEY_V1_OBJECT) {
605 		return SC_ERROR_NO_CARD_SUPPORT;
606 	}
607 
608 	return coolkey_v1_get_attribute_data(attr, buf_len, attr_out);
609 
610 }
611 
612 /* convert an attribute type into a  bit in the fixed attribute uint32_t  */
613 static unsigned long
coolkey_get_fixed_boolean_bit(CK_ATTRIBUTE_TYPE type)614 coolkey_get_fixed_boolean_bit(CK_ATTRIBUTE_TYPE type)
615 {
616 	switch(type) {
617 	case CKA_TOKEN:               return 0x00000080;
618 	case CKA_PRIVATE:             return 0x00000100;
619 	case CKA_MODIFIABLE:          return 0x00000200;
620 	case CKA_DERIVE:              return 0x00000400;
621 	case CKA_LOCAL:               return 0x00000800;
622 	case CKA_ENCRYPT:             return 0x00001000;
623 	case CKA_DECRYPT:             return 0x00002000;
624 	case CKA_WRAP:                return 0x00004000;
625 	case CKA_UNWRAP:              return 0x00008000;
626 	case CKA_SIGN:                return 0x00010000;
627 	case CKA_SIGN_RECOVER:        return 0x00020000;
628 	case CKA_VERIFY:              return 0x00040000;
629 	case CKA_VERIFY_RECOVER:      return 0x00080000;
630 	case CKA_SENSITIVE:           return 0x00100000;
631 	case CKA_ALWAYS_SENSITIVE:    return 0x00200000;
632 	case CKA_EXTRACTABLE:         return 0x00400000;
633 	case CKA_NEVER_EXTRACTABLE:   return 0x00800000;
634 	default: break;
635 	}
636 	return 0; /* return no bits */
637 }
638 /* This table lets us return a pointer to the CKA_ID value without allocating data or
639  * creating a changeable static that could cause thread issues */
640 static const u8 coolkey_static_cka_id[16] = {
641 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
642 };
643 
644 /* This table provides the following:
645  *     1) a mapping from a 3 bit cka_class to a full 32 bit CKA_CLASS_TYPE value we can return.
646  *     2) the mask of valid boolean attributes in the fixed attributes.
647  */
648 struct coolkey_fixed_class {
649 	u8 class_value[4];
650 	unsigned long boolean_mask;
651 };
652 
653 static const struct coolkey_fixed_class coolkey_static_cka_class[8] = {
654 	{ { 0, 0, 0, 0}, 0x00000380 }, /* DATA */
655 	{ { 0, 0, 0, 1}, 0x00000380 }, /* CERTIFICATE */
656 	{ { 0, 0, 0, 2}, 0x000c5f80 }, /* PUBLIC_KEY */
657 	{ { 0, 0, 0, 3}, 0x00f3af80 }, /* PRIVATE_KEY */
658 	{ { 0, 0, 0, 4}, 0x00f5ff80 }, /* SECRET_KEY */
659 	{ { 0, 0, 0, 5}, 0x00000000 },
660 	{ { 0, 0, 0, 6}, 0x00000000 },
661 	{ { 0, 0, 0, 7}, 0x00000000 }
662 };
663 
664 /*
665  * handle fixed attributes (V1 only)
666  */
667 static int
coolkey_get_attribute_data_fixed(CK_ATTRIBUTE_TYPE attr_type,unsigned long fixed_attributes,sc_cardctl_coolkey_attribute_t * attr_out)668 coolkey_get_attribute_data_fixed(CK_ATTRIBUTE_TYPE attr_type, unsigned long fixed_attributes,
669 																sc_cardctl_coolkey_attribute_t *attr_out) {
670 	unsigned long cka_id = fixed_attributes & 0xf;
671 	unsigned long cka_class = ((fixed_attributes) >> 4) & 0x7;
672 	unsigned long mask, bit;
673 
674 	if (attr_type == CKA_ID) {
675 		attr_out->attribute_length = 1;
676 		attr_out->attribute_value= &coolkey_static_cka_id[cka_id];
677 		return SC_SUCCESS;
678 	}
679 	if (attr_type == CKA_CLASS) {
680 		attr_out->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_ULONG;
681 		attr_out->attribute_length = 4;
682 		attr_out->attribute_value = coolkey_static_cka_class[cka_class].class_value;
683 		return SC_SUCCESS;
684 	}
685 	/* If it matched, it must be one of the booleans */
686 	mask = coolkey_static_cka_class[cka_class].boolean_mask;
687 	bit = coolkey_get_fixed_boolean_bit(attr_type);
688 	/* attribute isn't in the list */
689 	if ((bit & mask) == 0) {
690 		return SC_ERROR_DATA_OBJECT_NOT_FOUND;
691 	}
692 	attr_out->attribute_length = 1;
693 	attr_out->attribute_value = bit & fixed_attributes ? &coolkey_static_true : &coolkey_static_false;
694 	return SC_SUCCESS;
695 }
696 
697 
698 
699 static int
coolkey_v1_get_object_length(u8 * obj,size_t buf_len)700 coolkey_v1_get_object_length(u8 *obj, size_t buf_len)
701 {
702 	coolkey_combined_object_header_t *object_head = (coolkey_combined_object_header_t *) obj;
703 	int attribute_count;
704 	u8 *current_attribute;
705 	int j;
706 	size_t len;
707 
708 	len = sizeof(coolkey_combined_object_header_t);
709 	if (buf_len <= len) {
710 		return buf_len;
711 	}
712 	attribute_count = bebytes2ushort(object_head->attribute_count);
713 	buf_len -= len;
714 
715 	for (current_attribute = obj + len, j = 0; j < attribute_count; j++) {
716 		size_t attribute_len = coolkey_v1_get_attribute_record_len(current_attribute, buf_len);
717 
718 		len += attribute_len;
719 		current_attribute += attribute_len;
720 		buf_len -= attribute_len;
721 	}
722 	return len;
723 }
724 
725 /*
726  * COOLKEY private data per card state
727  */
728 typedef struct coolkey_private_data {
729 	u8 protocol_version_major;
730 	u8 protocol_version_minor;
731 	u8 format_version_major;
732 	u8 format_version_minor;
733 	unsigned short object_version;
734 	u8 life_cycle;
735 	u8 pin_count;
736 	u8 *token_name;				/* our token name read from the token */
737 	size_t token_name_length;		/* length of our token name */
738 	u8 nonce[COOLKEY_NONCE_SIZE];		/* nonce returned from login */
739 	int nonce_valid;
740 	coolkey_cuid_t cuid;			/* card unique ID from the CCC */
741 	sc_cardctl_coolkey_object_t *obj;	/* pointer to the current selected object */
742 	list_t objects_list;			/* list of objects on the token */
743 	unsigned short key_id;			/* key id set by select */
744 	int	algorithm;			/* saved from set_security_env */
745 	int operation;				/* saved from set_security_env */
746 } coolkey_private_data_t;
747 
748 #define COOLKEY_DATA(card) ((coolkey_private_data_t*)card->drv_data)
749 
750 int
coolkey_compare_id(const void * a,const void * b)751 coolkey_compare_id(const void * a, const void *b)
752 {
753 	if (a == NULL || b == NULL)
754 		return 1;
755 	return ((sc_cardctl_coolkey_object_t *)a)->id
756 	    != ((sc_cardctl_coolkey_object_t *)b)->id;
757 }
758 
759 /* For SimCList autocopy, we need to know the size of the data elements */
coolkey_list_meter(const void * el)760 size_t coolkey_list_meter(const void *el) {
761 	return sizeof(sc_cardctl_coolkey_object_t);
762 }
763 
764 static void coolkey_free_private_data(coolkey_private_data_t *priv);
765 
coolkey_new_private_data(void)766 static coolkey_private_data_t *coolkey_new_private_data(void)
767 {
768 	coolkey_private_data_t *priv;
769 
770 	/* allocate priv and zero all the fields */
771 	priv = calloc(1, sizeof(coolkey_private_data_t));
772 	if (!priv)
773 		return NULL;
774 
775 	/* set other fields as appropriate */
776 	priv->key_id = COOLKEY_INVALID_KEY;
777 	if (list_init(&priv->objects_list) != 0 ||
778 	    list_attributes_comparator(&priv->objects_list, coolkey_compare_id) != 0 ||
779 	    list_attributes_copy(&priv->objects_list, coolkey_list_meter, 1) != 0) {
780 		coolkey_free_private_data(priv);
781 		return NULL;
782 	}
783 
784 	return priv;
785 }
786 
coolkey_free_private_data(coolkey_private_data_t * priv)787 static void coolkey_free_private_data(coolkey_private_data_t *priv)
788 {
789 	list_t *l = &priv->objects_list;
790 	sc_cardctl_coolkey_object_t *o;
791 
792 	/* Clean up the allocated memory in the items */
793 	list_iterator_start(l);
794 	while (list_iterator_hasnext(l)) {
795 		o = (sc_cardctl_coolkey_object_t *)list_iterator_next(l);
796 		free(o->data);
797 		o->data = NULL;
798 	}
799 	list_iterator_stop(l);
800 
801 	list_destroy(&priv->objects_list);
802 	free(priv->token_name);
803 	free(priv);
804 	return;
805 }
806 
807 /*
808  * Object list operations
809  */
coolkey_add_object_to_list(list_t * list,const sc_cardctl_coolkey_object_t * object)810 static int coolkey_add_object_to_list(list_t *list, const sc_cardctl_coolkey_object_t *object)
811 {
812 	if (list_append(list, object) < 0)
813 		return SC_ERROR_UNKNOWN;
814 	return SC_SUCCESS;
815 }
816 
817 #define COOLKEY_AID "\xA0\x00\x00\x01\x16"
818 static sc_cardctl_coolkey_object_t *
coolkey_find_object_by_id(list_t * list,unsigned long object_id)819 coolkey_find_object_by_id(list_t *list, unsigned long object_id)
820 {
821 	int pos;
822 	static sc_cardctl_coolkey_object_t cmp = {{
823 		"", 0, 0, 0, SC_PATH_TYPE_DF_NAME,
824 		{ COOLKEY_AID, sizeof(COOLKEY_AID)-1 }
825 	}, 0, 0, NULL};
826 
827 	cmp.id = object_id;
828 	if ((pos = list_locate(list, &cmp)) < 0)
829 		return NULL;
830 
831 	return list_get_at(list, pos);
832 }
833 
834 
835 static const sc_path_t coolkey_template_path = {
836 	"", 0, 0, 0, SC_PATH_TYPE_DF_NAME,
837 	{ COOLKEY_AID, sizeof(COOLKEY_AID)-1 }
838 };
839 
840 struct coolkey_error_codes_st {
841 	int sc_error;
842 	char *description;
843 };
844 
845 static const struct coolkey_error_codes_st coolkey_error_codes[]= {
846 	{SC_ERROR_UNKNOWN,                       "Reserved 0x9c00" },
847 	{SC_ERROR_NOT_ENOUGH_MEMORY,             "No memory left on card" },
848 	{SC_ERROR_PIN_CODE_INCORRECT,            "Authentication failed" },
849 	{SC_ERROR_NOT_ALLOWED,                   "Operation not allowed" },
850 	{SC_ERROR_UNKNOWN,                       "Reserved 0x9c04" },
851 	{SC_ERROR_NO_CARD_SUPPORT,               "Unsupported feature" },
852 	{SC_ERROR_SECURITY_STATUS_NOT_SATISFIED, "Not authorized" },
853 	{SC_ERROR_DATA_OBJECT_NOT_FOUND,         "Object not found" },
854 	{SC_ERROR_FILE_ALREADY_EXISTS,           "Object exists" },
855 	{SC_ERROR_NO_CARD_SUPPORT,               "Incorrect Algorithm" },
856 	{SC_ERROR_UNKNOWN,                       "Reserved 0x9c0a" },
857 	{SC_ERROR_SM_INVALID_CHECKSUM,           "Signature invalid" },
858 	{SC_ERROR_AUTH_METHOD_BLOCKED,           "Identity blocked" },
859 	{SC_ERROR_UNKNOWN,                       "Reserved 0x9c0d" },
860 	{SC_ERROR_UNKNOWN,                       "Reserved 0x9c0e" },
861 	{SC_ERROR_INCORRECT_PARAMETERS,          "Invalid parameter" },
862 	{SC_ERROR_INCORRECT_PARAMETERS,          "Incorrect P1" },
863 	{SC_ERROR_INCORRECT_PARAMETERS,          "Incorrect P2" },
864 	{SC_ERROR_FILE_END_REACHED,              "Sequence End" },
865 };
866 
867 static const unsigned int
868 coolkey_number_of_error_codes = sizeof(coolkey_error_codes)/sizeof(coolkey_error_codes[0]);
869 
coolkey_check_sw(sc_card_t * card,unsigned int sw1,unsigned int sw2)870 static int coolkey_check_sw(sc_card_t *card, unsigned int sw1, unsigned int sw2)
871 {
872 	sc_log(card->ctx,
873 		"sw1 = 0x%02x, sw2 = 0x%02x\n", sw1, sw2);
874 
875 	if (sw1 == 0x90 && sw2 == 0x00)
876 		return SC_SUCCESS;
877 
878 	if (sw1 == 0x9c) {
879 		if (sw2 == 0xff) {
880 			/* shouldn't happen on a production applet, 0x9cff is a debugging error code */
881 			return SC_ERROR_INTERNAL;
882 		}
883 		if (sw2 >= coolkey_number_of_error_codes) {
884 			return SC_ERROR_UNKNOWN;
885 		}
886 		return coolkey_error_codes[sw2].sc_error;
887 	}
888 
889 	/* iso error */
890         return sc_get_iso7816_driver()->ops->check_sw(card, sw1, sw2);
891 }
892 
893 /*
894  * Send a command and receive data.
895  *
896  * A caller may provide a buffer, and length to read. If not provided,
897  * an internal 4096 byte buffer is used, and a copy is returned to the
898  * caller. that need to be freed by the caller.
899  *
900  * modelled after a similar function in card-piv.c. The coolkey version
901  * adds the coolkey nonce to user authenticated operations.
902  */
903 
coolkey_apdu_io(sc_card_t * card,int cla,int ins,int p1,int p2,const u8 * sendbuf,size_t sendbuflen,u8 ** recvbuf,size_t * recvbuflen,const u8 * nonce,size_t nonce_len)904 static int coolkey_apdu_io(sc_card_t *card, int cla, int ins, int p1, int p2,
905 	const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf, size_t * recvbuflen,
906 	const u8 *nonce, size_t nonce_len)
907 {
908 	int r;
909 	sc_apdu_t apdu;
910 	u8 rbufinitbuf[COOLKEY_MAX_SIZE];
911 	u8 rsendbuf[COOLKEY_MAX_SIZE];
912 	u8 *rbuf;
913 	size_t rbuflen;
914 	int cse = 0;
915 
916 
917 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
918 
919 	sc_log(card->ctx,
920 		 "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n",
921 		 ins, p1, p2, sendbuflen, card->max_send_size,
922 		 card->max_recv_size);
923 
924 	rbuf = rbufinitbuf;
925 	rbuflen = sizeof(rbufinitbuf);
926 
927 	/* if caller provided a buffer and length */
928 	if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) {
929 		rbuf = *recvbuf;
930 		rbuflen = *recvbuflen;
931 	}
932 
933 	if (sendbuf || nonce) {
934 		if (recvbuf) {
935 			cse = SC_APDU_CASE_4_SHORT;
936 		} else {
937 			cse = SC_APDU_CASE_3_SHORT;
938 		}
939 	} else {
940 		if (recvbuf) {
941 			cse = SC_APDU_CASE_2_SHORT;
942 		} else {
943 			cse = SC_APDU_CASE_1;
944 		}
945 	}
946 
947 	/* append the nonce if we have it. Coolkey just blindly puts this at the end
948 	 * of the APDU (while adjusting lc). This converts case 1 to case 3. coolkey
949 	 * also always drops le in case 4 (which happens when proto = T0). nonces are
950 	 * never used on case 2 commands, so we can simply append the nonce to the data
951 	 * and we should be fine */
952 	if (nonce) {
953 		u8 *buf = rsendbuf;
954 		if (sendbuf) {
955 			sendbuflen = MIN(sendbuflen,sizeof(rsendbuf)-nonce_len);
956 			memcpy(rsendbuf, sendbuf, sendbuflen);
957 			buf += sendbuflen;
958 		}
959 		memcpy(buf, nonce, nonce_len);
960 		sendbuflen += nonce_len;
961 		sendbuf =rsendbuf;
962 	}
963 
964 	sc_format_apdu(card, &apdu, cse, ins, p1, p2);
965 
966 	apdu.lc = sendbuflen;
967 	apdu.datalen = sendbuflen;
968 	apdu.data = sendbuf;
969 
970 
971 	/* coolkey uses non-standard classes */
972 	apdu.cla = cla;
973 
974 	if (recvbuf) {
975 		apdu.resp = rbuf;
976 		apdu.le = (rbuflen > 255) ? 255 : rbuflen;
977 		apdu.resplen = rbuflen;
978 	} else {
979 		 apdu.resp =  rbuf;
980 		 apdu.le = 0;
981 		 apdu.resplen = 0;
982 	}
983 
984 	sc_log(card->ctx,
985 		 "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p",
986 		 apdu.flags, apdu.le, apdu.resplen, apdu.resp);
987 
988 	/* with new adpu.c and chaining, this actually reads the whole object */
989 	r = sc_transmit_apdu(card, &apdu);
990 
991 	sc_log(card->ctx,
992 		 "result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x",
993 		 r, apdu.resplen, apdu.sw1, apdu.sw2);
994 
995 	if (r < 0) {
996 		sc_log(card->ctx, "Transmit failed");
997 		goto err;
998 	}
999 	r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1000 	if (r < 0) {
1001 		sc_log(card->ctx, "Transmit failed");
1002 		goto err;
1003 	}
1004 
1005 	if (recvbuflen) {
1006 		if (recvbuf && *recvbuf == NULL) {
1007 			*recvbuf =  malloc(apdu.resplen);
1008 			if (*recvbuf == NULL) {
1009 				r = SC_ERROR_OUT_OF_MEMORY;
1010 				goto err;
1011 			}
1012 			memcpy(*recvbuf, rbuf, apdu.resplen);
1013 		}
1014 		*recvbuflen =  apdu.resplen;
1015 		r = *recvbuflen;
1016 	}
1017 
1018 err:
1019 	LOG_FUNC_RETURN(card->ctx, r);
1020 }
1021 
1022 /*
1023  * Helpers to handle coolkey commands
1024  */
1025 static int
coolkey_get_life_cycle(sc_card_t * card,coolkey_life_cycle_t * life_cycle)1026 coolkey_get_life_cycle(sc_card_t *card, coolkey_life_cycle_t *life_cycle)
1027 {
1028 	coolkey_status_t status;
1029 	u8 *receive_buf;
1030 	size_t receive_len;
1031 	int len;
1032 
1033 	receive_len = sizeof(*life_cycle);
1034 	receive_buf = (u8 *)life_cycle;
1035 	len = coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_GET_LIFE_CYCLE, 0, 0,
1036 			NULL, 0, &receive_buf, &receive_len, NULL, 0);
1037 	if (len == sizeof(*life_cycle)) {
1038 		return SC_SUCCESS;
1039 	}
1040 
1041 	receive_len = 1;
1042 	receive_buf = &life_cycle->life_cycle;
1043 	len = coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_GET_LIFE_CYCLE, 0, 0,
1044 			NULL, 0, &receive_buf, &receive_len, NULL, 0);
1045 	if (len < 0) { /* Error from the trasmittion */
1046 		return len;
1047 	}
1048 	if (len != 1) { /* The returned data is invalid */
1049 		return SC_ERROR_INTERNAL;
1050 	}
1051 	receive_len = sizeof(status);
1052 	receive_buf = (u8 *)&status;
1053 	len = coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_GET_STATUS, 0, 0,
1054 			NULL, 0, &receive_buf, &receive_len, NULL, 0);
1055 	if (len < 0) { /* Error from the trasmittion */
1056 		return len;
1057 	}
1058 	if (len != sizeof(status)) { /* The returned data is invalid */
1059 		return SC_ERROR_INTERNAL;
1060 	}
1061 	life_cycle->protocol_version_major = status.protocol_version_major;
1062 	life_cycle->protocol_version_minor = status.protocol_version_minor;
1063 	life_cycle->pin_count = status.pin_count;
1064 	return SC_SUCCESS;
1065 }
1066 
1067 /* select the coolkey applet */
coolkey_select_applet(sc_card_t * card)1068 static int coolkey_select_applet(sc_card_t *card)
1069 {
1070 	u8 aid[] = { 0x62, 0x76, 0x01, 0xff, 0x00, 0x00, 0x00 };
1071 	return coolkey_apdu_io(card, ISO7816_CLASS, ISO7816_INS_SELECT_FILE, 4, 0,
1072 			&aid[0], sizeof(aid), NULL, NULL,  NULL, 0);
1073 }
1074 
1075 static void
coolkey_make_cuid_from_cplc(coolkey_cuid_t * cuid,global_platform_cplc_data_t * cplc_data)1076 coolkey_make_cuid_from_cplc(coolkey_cuid_t *cuid, global_platform_cplc_data_t *cplc_data)
1077 {
1078 	cuid->ic_fabricator[0]    = cplc_data->ic_fabricator[0];
1079 	cuid->ic_fabricator[1]    = cplc_data->ic_fabricator[1];
1080 	cuid->ic_type[0]          = cplc_data->ic_type[0];
1081 	cuid->ic_type[1]          = cplc_data->ic_type[1];
1082 	cuid->ic_batch[0]         = cplc_data->ic_batch[0];
1083 	cuid->ic_batch[1]         = cplc_data->ic_batch[1];
1084 	cuid->ic_serial_number[0] = cplc_data->ic_serial_number[0];
1085 	cuid->ic_serial_number[1] = cplc_data->ic_serial_number[1];
1086 	cuid->ic_serial_number[2] = cplc_data->ic_serial_number[2];
1087 	cuid->ic_serial_number[3] = cplc_data->ic_serial_number[3];
1088 }
1089 
1090 /*
1091  * Read a COOLKEY coolkey object.
1092  */
coolkey_read_object(sc_card_t * card,unsigned long object_id,size_t offset,u8 * out_buf,size_t out_len,u8 * nonce,size_t nonce_size)1093 static int coolkey_read_object(sc_card_t *card, unsigned long object_id, size_t offset,
1094 			u8 *out_buf, size_t out_len, u8 *nonce, size_t nonce_size)
1095 {
1096 	coolkey_read_object_param_t params;
1097 	u8 *out_ptr;
1098 	size_t left = 0;
1099 	size_t len;
1100 	int r;
1101 
1102 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1103 
1104 	ulong2bebytes(&params.object_id[0], object_id);
1105 
1106 	out_ptr = out_buf;
1107 	left = out_len;
1108 	do {
1109 		ulong2bebytes(&params.offset[0], offset);
1110 		params.length = MIN(left, COOLKEY_MAX_CHUNK_SIZE);
1111 		len = left;
1112 		r = coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_READ_OBJECT, 0, 0,
1113 			(u8 *)&params, sizeof(params), &out_ptr, &len, nonce, nonce_size);
1114 		if (r < 0) {
1115 			goto fail;
1116 		}
1117 		/* sanity check to make sure we don't overflow left */
1118 		if ((left < len) || (len == 0)) {
1119 			r = SC_ERROR_INTERNAL;
1120 			goto fail;
1121 		}
1122 		out_ptr += len;
1123 		offset += len;
1124 		left -= len;
1125 	} while (left != 0);
1126 
1127 	return out_len;
1128 
1129 fail:
1130 	LOG_FUNC_RETURN(card->ctx, r);
1131 }
1132 
1133 /*
1134  * Write a COOLKEY coolkey object.
1135  */
coolkey_write_object(sc_card_t * card,unsigned long object_id,size_t offset,const u8 * buf,size_t buf_len,const u8 * nonce,size_t nonce_size)1136 static int coolkey_write_object(sc_card_t *card, unsigned long object_id,
1137 			size_t offset, const u8 *buf, size_t buf_len, const u8 *nonce, size_t nonce_size)
1138 {
1139 	coolkey_write_object_param_t params;
1140 	size_t operation_len;
1141 	size_t left = buf_len;
1142 	int r;
1143 	size_t max_operation_len;
1144 
1145 	/* set limit for the card's maximum send size and short write */
1146 	max_operation_len = MIN(COOLKEY_MAX_CHUNK_SIZE, (card->max_send_size - sizeof(coolkey_read_object_param_t) - nonce_size));
1147 
1148 	ulong2bebytes(&params.head.object_id[0], object_id);
1149 
1150 	do {
1151 		ulong2bebytes(&params.head.offset[0], offset);
1152 		operation_len = MIN(left, max_operation_len);
1153 		params.head.length = operation_len;
1154 		memcpy(params.buf, buf, operation_len);
1155 		r = coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_WRITE_OBJECT, 0, 0,
1156 			(u8 *)&params, sizeof(params.head)+operation_len, NULL, 0, nonce, nonce_size);
1157 		if (r < 0) {
1158 			goto fail;
1159 		}
1160 		buf += operation_len;
1161 		offset += operation_len;
1162 		left -= operation_len;
1163 	} while (left != 0);
1164 
1165 	return buf_len - left;
1166 
1167 fail:
1168 	return r;
1169 }
1170 
1171 /*
1172  * coolkey_read_binary will read a coolkey object off the card. That object is selected
1173  * by select file. If we've already read the object, we'll return the data from the cache.
1174  * coolkey objects are encoded PKCS #11 entries, not pkcs #15 data. pkcs15-coolkey will
1175  * translate the objects into their PKCS #15 equivalent data structures.
1176  */
coolkey_read_binary(sc_card_t * card,unsigned int idx,u8 * buf,size_t count,unsigned long flags)1177 static int coolkey_read_binary(sc_card_t *card, unsigned int idx,
1178 		u8 *buf, size_t count, unsigned long flags)
1179 {
1180 	coolkey_private_data_t * priv = COOLKEY_DATA(card);
1181 	int r = 0, len;
1182 	u8 *data = NULL;
1183 
1184 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1185 	if (idx > priv->obj->length) {
1186 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_END_REACHED);
1187 	}
1188 
1189 	/* if we've already read the data, just return it */
1190 	if (priv->obj->data) {
1191 		sc_log(card->ctx,
1192 			 "returning cached value idx=%u count=%"SC_FORMAT_LEN_SIZE_T"u",
1193 			 idx, count);
1194 		len = MIN(count, priv->obj->length-idx);
1195 		memcpy(buf, &priv->obj->data[idx], len);
1196 		LOG_FUNC_RETURN(card->ctx, len);
1197 	}
1198 
1199 	sc_log(card->ctx,
1200 		 "clearing cache idx=%u count=%"SC_FORMAT_LEN_SIZE_T"u",
1201 		 idx, count);
1202 
1203 	data = malloc(priv->obj->length);
1204 	if (data == NULL) {
1205 		r = SC_ERROR_OUT_OF_MEMORY;
1206 		goto done;
1207 	}
1208 
1209 
1210 	r = coolkey_read_object(card, priv->obj->id, 0, data, priv->obj->length,
1211 		priv->nonce, sizeof(priv->nonce));
1212 	if (r < 0)
1213 		goto done;
1214 
1215 	if ((size_t) r != priv->obj->length) {
1216 		priv->obj->length = r;
1217 	}
1218 
1219 
1220 	/* OK we've read the data, now copy the required portion out to the callers buffer */
1221 	len = MIN(count, priv->obj->length-idx);
1222 	memcpy(buf, &data[idx], len);
1223 	r = len;
1224 	/* cache the data in the object */
1225 	priv->obj->data=data;
1226 	data = NULL;
1227 
1228 done:
1229 	if (data)
1230 		free(data);
1231 	LOG_FUNC_RETURN(card->ctx, r);
1232 }
1233 
1234 /* COOLKEY driver is read only. NOTE: The applet supports w/r operations, so it's perfectly
1235  * reasonable to try to create new objects, but currently TPS does not create applets
1236  * That allow user created objects, so this is a nice 2.0 feature. */
coolkey_write_binary(sc_card_t * card,unsigned int idx,const u8 * buf,size_t count,unsigned long flags)1237 static int coolkey_write_binary(sc_card_t *card, unsigned int idx,
1238 		const u8 *buf, size_t count, unsigned long flags)
1239 {
1240 
1241 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1242 	LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
1243 }
1244 
1245 /* initialize getting a list and return the number of elements in the list */
coolkey_get_init_and_get_count(list_t * list,int * countp)1246 static int coolkey_get_init_and_get_count(list_t *list, int *countp)
1247 {
1248 	*countp = list_size(list);
1249 	list_iterator_start(list);
1250 	return SC_SUCCESS;
1251 }
1252 
1253 /* fill in the obj_info for the current object on the list and advance to the next object */
coolkey_fetch_object(list_t * list,sc_cardctl_coolkey_object_t * coolkey_obj)1254 static int coolkey_fetch_object(list_t *list, sc_cardctl_coolkey_object_t *coolkey_obj)
1255 {
1256 	sc_cardctl_coolkey_object_t *ptr;
1257 	if (!list_iterator_hasnext(list)) {
1258 		return SC_ERROR_FILE_END_REACHED;
1259 	}
1260 
1261 	ptr = list_iterator_next(list);
1262 	*coolkey_obj = *ptr;
1263 	return SC_SUCCESS;
1264 }
1265 
1266 /* Finalize iterator */
coolkey_final_iterator(list_t * list)1267 static int coolkey_final_iterator(list_t *list)
1268 {
1269 	list_iterator_stop(list);
1270 	return SC_SUCCESS;
1271 }
1272 
coolkey_cuid_to_string(coolkey_cuid_t * cuid)1273 static char * coolkey_cuid_to_string(coolkey_cuid_t *cuid)
1274 {
1275 	char *buf;
1276 	size_t len = sizeof(coolkey_cuid_t)*2 + 1;
1277 	buf = malloc(len);
1278 	if (buf == NULL) {
1279 		return NULL;
1280 	}
1281 	sc_bin_to_hex((u8 *)cuid, sizeof(*cuid), buf, len, 0);
1282 	return buf;
1283 }
1284 
1285 static const struct manufacturer_list_st {
1286 	unsigned short id;
1287 	char *string;
1288 } manufacturer_list[] = {
1289 	{ 0x2050, "%04x Oberthur" },
1290 	{ 0x4090, "%04x GemAlto (Infineon)" },
1291 	{ 0x4780, "%04x STMicroElectronics" },
1292 	{ 0x4780, "%04x RSA" },
1293 	{ 0x534e, "%04x SafeNet" },
1294 };
1295 
1296 int manufacturer_list_count = sizeof(manufacturer_list)/sizeof(manufacturer_list[0]);
1297 
coolkey_get_manufacturer(coolkey_cuid_t * cuid)1298 static char * coolkey_get_manufacturer(coolkey_cuid_t *cuid)
1299 {
1300 	unsigned short fabricator = bebytes2ushort(cuid->ic_fabricator);
1301 	int i;
1302 	char *buf;
1303 	const char *manufacturer_string = "%04x Unknown";
1304 	size_t len;
1305 	int r;
1306 
1307 	for (i=0; i < manufacturer_list_count; i++) {
1308 		if (manufacturer_list[i].id == fabricator) {
1309 			manufacturer_string = manufacturer_list[i].string;
1310 			break;
1311 		}
1312 	}
1313 	len = strlen(manufacturer_string)+1;
1314 	buf= malloc(len);
1315 	if (buf == NULL) {
1316 		return NULL;
1317 	}
1318 	r = snprintf(buf, len, manufacturer_string, fabricator);
1319 	if (r < 0) {
1320 		free(buf);
1321 		return NULL;
1322 	}
1323 	return buf;
1324 }
1325 
1326 
coolkey_get_token_info(sc_card_t * card,sc_pkcs15_tokeninfo_t * token_info)1327 static int coolkey_get_token_info(sc_card_t *card, sc_pkcs15_tokeninfo_t * token_info)
1328 {
1329 	coolkey_private_data_t * priv = COOLKEY_DATA(card);
1330 	char *label = NULL;
1331 	char *manufacturer_id = NULL;
1332 	char *serial_number = NULL;
1333 
1334 	LOG_FUNC_CALLED(card->ctx);
1335 	label = strdup((char *)priv->token_name);
1336 	manufacturer_id = coolkey_get_manufacturer(&priv->cuid);
1337 	serial_number = coolkey_cuid_to_string(&priv->cuid);
1338 
1339 	if (label && manufacturer_id && serial_number) {
1340 		free(token_info->label);
1341 		token_info->label = label;
1342 		free(token_info->manufacturer_id);
1343 		token_info->manufacturer_id = manufacturer_id;
1344 		free(token_info->serial_number);
1345 		token_info->serial_number = serial_number;
1346 		return SC_SUCCESS;
1347 	}
1348 	free(label);
1349 	free(manufacturer_id);
1350 	free(serial_number);
1351 	return SC_ERROR_OUT_OF_MEMORY;
1352 }
1353 
coolkey_get_serial_nr_from_CUID(sc_card_t * card,sc_serial_number_t * serial)1354 static int coolkey_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial)
1355 {
1356 	coolkey_private_data_t * priv = COOLKEY_DATA(card);
1357 
1358 	LOG_FUNC_CALLED(card->ctx);
1359 	memcpy(serial->value, &priv->cuid, sizeof(priv->cuid));
1360 	serial->len = sizeof(priv->cuid);
1361 	LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
1362 }
1363 
1364 int
coolkey_fill_object(sc_card_t * card,sc_cardctl_coolkey_object_t * obj)1365 coolkey_fill_object(sc_card_t *card, sc_cardctl_coolkey_object_t *obj)
1366 {
1367 	int r;
1368 	size_t buf_len = obj->length;
1369 	u8 *new_obj_data = NULL;
1370 	sc_cardctl_coolkey_object_t *obj_entry;
1371 	coolkey_private_data_t * priv = COOLKEY_DATA(card);
1372 
1373 	LOG_FUNC_CALLED(card->ctx);
1374 
1375 	if (obj->data != NULL) {
1376 		return SC_SUCCESS;
1377 	}
1378 	new_obj_data = malloc(buf_len);
1379 	if (new_obj_data == NULL) {
1380 		return SC_ERROR_OUT_OF_MEMORY;
1381 	}
1382 	r = coolkey_read_object(card, obj->id, 0, new_obj_data, buf_len,
1383 				priv->nonce, sizeof(priv->nonce));
1384 	if (r != (int)buf_len) {
1385 		free(new_obj_data);
1386 		if (r < 0) {
1387 			LOG_FUNC_RETURN(card->ctx, r);
1388 		}
1389 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_CORRUPTED_DATA);
1390 	}
1391 	obj_entry = coolkey_find_object_by_id(&priv->objects_list, obj->id);
1392 	if (obj_entry == NULL) {
1393 		free(new_obj_data);
1394 		return SC_ERROR_INTERNAL; /* shouldn't happen */
1395 	}
1396 	if (obj_entry->data != NULL) {
1397 		free(new_obj_data);
1398 		return SC_ERROR_INTERNAL; /* shouldn't happen */
1399 	}
1400 	/* Make sure we will not go over the allocated limits in the other
1401 	 * objects if they somehow got different lengths in matching objects */
1402 	if (obj_entry->length != obj->length) {
1403 		free(new_obj_data);
1404 		return SC_ERROR_INTERNAL; /* shouldn't happen */
1405 	}
1406 	obj_entry->data = new_obj_data;
1407 	obj->data = new_obj_data;
1408 	LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
1409 }
1410 
1411 /*
1412  * return a parsed record for the attribute which includes value, type, and length.
1413  * Handled both v1 and v0 record types. determine record type from the object.
1414  *  make sure we don't overrun the buffer if the token gives us bad data.
1415  */
1416 static int
coolkey_find_attribute(sc_card_t * card,sc_cardctl_coolkey_attribute_t * attribute)1417 coolkey_find_attribute(sc_card_t *card, sc_cardctl_coolkey_attribute_t *attribute)
1418 {
1419 	u8 object_record_type;
1420 	CK_ATTRIBUTE_TYPE attr_type = attribute->attribute_type;
1421 	const u8 *obj = attribute->object->data;
1422 	const u8 *attr = NULL;
1423 	size_t buf_len = attribute->object->length;
1424 	coolkey_object_header_t *object_head;
1425 	int attribute_count,i;
1426 	attribute->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_STRING;
1427 	attribute->attribute_length = 0;
1428 	attribute->attribute_value = NULL;
1429 
1430 	LOG_FUNC_CALLED(card->ctx);
1431 
1432 	if (obj == NULL) {
1433 		/* cast away const so we can cache the data value */
1434 		int r = coolkey_fill_object(card, (sc_cardctl_coolkey_object_t *)attribute->object);
1435 		if (r < 0) {
1436 			return r;
1437 		}
1438 		obj = attribute->object->data;
1439 		if (obj == NULL) {
1440 			return SC_ERROR_INTERNAL;
1441 		}
1442 	}
1443 
1444 	/* should be a static assert so we catch this at compile time */
1445 	assert(sizeof(coolkey_object_header_t) >= sizeof(coolkey_v0_object_header_t));
1446 	/* make sure we have enough of the object to read the record_type */
1447 	if (buf_len <= sizeof(coolkey_v0_object_header_t)) {
1448 		return SC_ERROR_CORRUPTED_DATA;
1449 	}
1450 	object_head = (coolkey_object_header_t *)obj;
1451 	object_record_type = object_head->record_type;
1452 	/* make sure it's a type we recognize */
1453 	if ((object_record_type != COOLKEY_V1_OBJECT) && (object_record_type != COOLKEY_V0_OBJECT)) {
1454 		return SC_ERROR_CORRUPTED_DATA;
1455 	}
1456 
1457 	/*
1458 	 * now loop through all the attributes in the list. first find the start of the list
1459 	 */
1460 	attr = coolkey_attribute_start(obj, object_record_type, buf_len);
1461 	if (attr == NULL) {
1462 		return SC_ERROR_CORRUPTED_DATA;
1463 	}
1464 	buf_len -= (attr-obj);
1465 
1466 	/* now get the count */
1467 	attribute_count = coolkey_get_attribute_count(obj, object_record_type, buf_len);
1468 	for (i=0; i < attribute_count; i++) {
1469 		size_t record_len = coolkey_get_attribute_record_len(attr, object_record_type, buf_len);
1470 		/* make sure we have the complete record */
1471 		if (buf_len < record_len || record_len < 4) {
1472 			return SC_ERROR_CORRUPTED_DATA;
1473 		}
1474 		/* does the attribute match the one we are looking for */
1475 		if (attr_type == coolkey_get_attribute_type(attr, object_record_type, record_len)) {
1476 			/* yup, return it */
1477 			return coolkey_get_attribute_data(attr, object_record_type, record_len, attribute);
1478 		}
1479 		/* go to the next attribute on the list */
1480 		buf_len -= record_len;
1481 		attr += record_len;
1482 	}
1483 	/* not find in attribute list, check the fixed attribute record */
1484 	if (object_record_type == COOLKEY_V1_OBJECT) {
1485 		unsigned long fixed_attributes = bebytes2ulong(object_head->fixed_attributes_values);
1486 
1487 		return coolkey_get_attribute_data_fixed(attr_type, fixed_attributes, attribute);
1488 	}
1489 	LOG_FUNC_RETURN(card->ctx, SC_ERROR_DATA_OBJECT_NOT_FOUND);
1490 }
1491 
1492 /*
1493  * pkcs 15 needs to find the cert matching the keys to fill in some of the fields that wasn't stored
1494  * with the key. To do this we need to look for the cert matching the key's CKA_ID. For flexibility,
1495  * We simply search using a pkcs #11 style template using the cardctl_coolkey_attribute_t structure */
1496 sc_cardctl_coolkey_object_t *
coolkey_find_object_by_template(sc_card_t * card,sc_cardctl_coolkey_attribute_t * template,int count)1497 coolkey_find_object_by_template(sc_card_t *card, sc_cardctl_coolkey_attribute_t *template, int count)
1498 {
1499 	list_t *list;
1500 	sc_cardctl_coolkey_object_t *current, *rv = NULL;
1501 	coolkey_private_data_t * priv = COOLKEY_DATA(card);
1502 	int i, r;
1503 	unsigned int tmp_pos = (unsigned int) -1;
1504 
1505 	list = &priv->objects_list;
1506 	if (list->iter_active) {
1507 		/* workaround missing functionality of second iterator */
1508 		tmp_pos = list->iter_pos;
1509 		list_iterator_stop(list);
1510 	}
1511 
1512 	list_iterator_start(list);
1513 	while (list_iterator_hasnext(list)) {
1514 		sc_cardctl_coolkey_attribute_t attribute;
1515 		current = list_iterator_next(list);
1516 		attribute.object = current;
1517 
1518 		for (i=0; i < count; i++) {
1519 			attribute.attribute_type = template[i].attribute_type;
1520 			r = coolkey_find_attribute(card, &attribute);
1521 			if (r < 0) {
1522 				break;
1523 			}
1524 			if (template[i].attribute_data_type != attribute.attribute_data_type) {
1525 				break;
1526 			}
1527 			if (template[i].attribute_length != attribute.attribute_length) {
1528 				break;
1529 			}
1530 			if (memcmp(attribute.attribute_value, template[i].attribute_value,
1531 							attribute.attribute_length) != 0) {
1532 				break;
1533 			}
1534 		}
1535 		/* just return the first one */
1536 		if (i == count) {
1537 			rv = current;
1538 			break;
1539 		}
1540 	}
1541 
1542 	list_iterator_stop(list);
1543 	if (tmp_pos != (unsigned int)-1) {
1544 		/* workaround missing functionality of second iterator */
1545 		list_iterator_start(list);
1546 		while (list_iterator_hasnext(list) && list->iter_pos < tmp_pos)
1547 			(void) list_iterator_next(list);
1548 	}
1549 	return rv;
1550 }
1551 
1552 static int
coolkey_find_object(sc_card_t * card,sc_cardctl_coolkey_find_object_t * fobj)1553 coolkey_find_object(sc_card_t *card, sc_cardctl_coolkey_find_object_t *fobj)
1554 {
1555 	sc_cardctl_coolkey_object_t *obj = NULL;
1556 	coolkey_private_data_t * priv = COOLKEY_DATA(card);
1557 	int r;
1558 
1559 	switch (fobj->type) {
1560 	case SC_CARDCTL_COOLKEY_FIND_BY_ID:
1561 		obj = coolkey_find_object_by_id(&priv->objects_list, fobj->find_id);
1562 		break;
1563 	case SC_CARDCTL_COOLKEY_FIND_BY_TEMPLATE:
1564 		obj = coolkey_find_object_by_template(card, fobj->coolkey_template, fobj->template_count);
1565 		break;
1566 	default:
1567 		break;
1568 	}
1569 	if (obj == NULL) {
1570 		return SC_ERROR_DATA_OBJECT_NOT_FOUND;
1571 	}
1572 	if (obj->data == NULL) {
1573 		r = coolkey_fill_object(card, obj);
1574 		if (r < 0) {
1575 			return r;
1576 		}
1577 	}
1578 	fobj->obj = obj;
1579 	return SC_SUCCESS;
1580 }
1581 
coolkey_card_ctl(sc_card_t * card,unsigned long cmd,void * ptr)1582 static int coolkey_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
1583 {
1584 	coolkey_private_data_t * priv = COOLKEY_DATA(card);
1585 
1586 	LOG_FUNC_CALLED(card->ctx);
1587 	sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr);
1588 
1589 	if (priv == NULL) {
1590 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
1591 	}
1592 	switch(cmd) {
1593 		case SC_CARDCTL_GET_SERIALNR:
1594 			return coolkey_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr);
1595 		case SC_CARDCTL_COOLKEY_GET_TOKEN_INFO:
1596 			return coolkey_get_token_info(card, (sc_pkcs15_tokeninfo_t *) ptr);
1597 		case SC_CARDCTL_COOLKEY_FIND_OBJECT:
1598 			return coolkey_find_object(card, (sc_cardctl_coolkey_find_object_t *)ptr);
1599 		case SC_CARDCTL_COOLKEY_INIT_GET_OBJECTS:
1600 			return coolkey_get_init_and_get_count(&priv->objects_list, (int *)ptr);
1601 		case SC_CARDCTL_COOLKEY_GET_NEXT_OBJECT:
1602 			return coolkey_fetch_object(&priv->objects_list, (sc_cardctl_coolkey_object_t *)ptr);
1603 		case SC_CARDCTL_COOLKEY_FINAL_GET_OBJECTS:
1604 			return coolkey_final_iterator(&priv->objects_list);
1605 		case SC_CARDCTL_COOLKEY_GET_ATTRIBUTE:
1606 			return coolkey_find_attribute(card,(sc_cardctl_coolkey_attribute_t *)ptr);
1607 	}
1608 
1609 	LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
1610 }
1611 
coolkey_get_challenge(sc_card_t * card,u8 * rnd,size_t len)1612 static int coolkey_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
1613 {
1614 	LOG_FUNC_CALLED(card->ctx);
1615 
1616 	if (len > COOLKEY_MAX_CHUNK_SIZE)
1617 		len = COOLKEY_MAX_CHUNK_SIZE;
1618 
1619 	LOG_TEST_RET(card->ctx,
1620 			coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_GET_RANDOM, 0, 0,
1621 				NULL, 0, &rnd, &len,  NULL, 0),
1622 			"Could not get challenge");
1623 
1624 	LOG_FUNC_RETURN(card->ctx, (int) len);
1625 }
1626 
coolkey_set_security_env(sc_card_t * card,const sc_security_env_t * env,int se_num)1627 static int coolkey_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
1628 {
1629 	int r = SC_SUCCESS;
1630 	coolkey_private_data_t * priv = COOLKEY_DATA(card);
1631 
1632 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1633 
1634 	sc_log(card->ctx,
1635 		 "flags=%08lx op=%d alg=%d algf=%08x algr=%08x kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n",
1636 		 env->flags, env->operation, env->algorithm,
1637 		 env->algorithm_flags, env->algorithm_ref, env->key_ref[0],
1638 		 env->key_ref_len);
1639 
1640 	if ((env->algorithm != SC_ALGORITHM_RSA) && (env->algorithm != SC_ALGORITHM_EC)) {
1641 		 r = SC_ERROR_NO_CARD_SUPPORT;
1642 	}
1643 	priv->algorithm = env->algorithm;
1644 	priv->operation = env->operation;
1645 
1646 	SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
1647 }
1648 
1649 
coolkey_restore_security_env(sc_card_t * card,int se_num)1650 static int coolkey_restore_security_env(sc_card_t *card, int se_num)
1651 {
1652 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1653 
1654 	LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
1655 }
1656 
1657 #define MAX_COMPUTE_BUF 200
1658 typedef struct coolkey_compute_crypt_init_params {
1659 	u8 mode;
1660 	u8 direction;
1661 	u8 location;
1662 	u8 buf_len[2];
1663 } coolkey_compute_crypt_init_params_t;
1664 
1665 typedef struct coolkey_compute_crypt_params {
1666     coolkey_compute_crypt_init_params_t init;
1667 	u8 buf[MAX_COMPUTE_BUF];
1668 } coolkey_compute_crypt_params_t;
1669 
1670 typedef struct coolkey_compute_ecc_params {
1671 	u8 location;
1672 	u8 buf_len[2];
1673 	u8 buf[MAX_COMPUTE_BUF];
1674 } coolkey_compute_ecc_params_t;
1675 
coolkey_rsa_op(sc_card_t * card,const u8 * data,size_t datalen,u8 * out,size_t max_out_len)1676 static int coolkey_rsa_op(sc_card_t *card, const u8 * data, size_t datalen,
1677 	u8 * out, size_t max_out_len)
1678 {
1679 	int r;
1680 	u8 **crypt_out_p = NULL;
1681 	size_t crypt_out_len_p = 0;
1682 	coolkey_private_data_t *priv = COOLKEY_DATA(card);
1683 	coolkey_compute_crypt_params_t params;
1684 	u8 key_number;
1685 	size_t params_len;
1686 	u8 buf[MAX_COMPUTE_BUF + 2];
1687 	u8 *buf_out;
1688 
1689 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1690 	sc_log(card->ctx, "datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n",
1691 		datalen, max_out_len);
1692 
1693 	if (priv->key_id > 0xff) {
1694 		r = SC_ERROR_NO_DEFAULT_KEY;
1695 		goto done;
1696 	}
1697 	key_number = priv->key_id;
1698 
1699 	memset(&params, 0, sizeof(params));
1700 	params.init.mode = COOLKEY_CRYPT_MODE_RSA_NO_PAD;
1701 	params.init.direction = COOLKEY_CRYPT_DIRECTION_ENCRYPT; /* for no pad, direction is irrelevant */
1702 
1703 	/* send the data to the card if necessary */
1704 	if (datalen > MAX_COMPUTE_BUF) {
1705 		/* We need to write data to special object on the card as it does not safely fit APDU */
1706 		u8 len_buf[2];
1707 
1708 		params.init.location = COOLKEY_CRYPT_LOCATION_DL_OBJECT;
1709 
1710 		params_len = sizeof(params.init);
1711 
1712 		ushort2bebytes(len_buf, datalen);
1713 
1714 		r = coolkey_write_object(card, COOLKEY_DL_OBJECT_ID, 0, len_buf, sizeof(len_buf),
1715 					priv->nonce, sizeof(priv->nonce));
1716 		if (r < 0) {
1717 			goto done;
1718 		}
1719 
1720 		r = coolkey_write_object(card, COOLKEY_DL_OBJECT_ID, 2, data, datalen, priv->nonce, sizeof(priv->nonce));
1721 		if (r < 0) {
1722 			goto done;
1723 		}
1724 		ushort2bebytes(params.init.buf_len, 0);
1725 	} else {
1726 		/* The data fits in APDU. Copy it to the params object */
1727 		size_t buf_len;
1728 
1729 		params.init.location = COOLKEY_CRYPT_LOCATION_APDU;
1730 
1731 		params_len = sizeof(params.init) + datalen;
1732 
1733 		buf_out = &buf[0];
1734 		crypt_out_p = &buf_out;
1735 		buf_len = sizeof(buf);
1736 		crypt_out_len_p = buf_len;
1737 
1738 		ushort2bebytes(params.init.buf_len, datalen);
1739 		memcpy(params.buf, data, datalen);
1740 	}
1741 
1742 	r = coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_COMPUTE_CRYPT,
1743 			key_number, COOLKEY_CRYPT_ONE_STEP, (u8 *)&params, params_len,
1744 			crypt_out_p, &crypt_out_len_p, priv->nonce, sizeof(priv->nonce));
1745 	if (r < 0) {
1746 		goto done;
1747 	}
1748 
1749 	if (datalen > MAX_COMPUTE_BUF) {
1750 		u8 len_buf[2];
1751 		size_t out_length;
1752 
1753 		r = coolkey_read_object(card, COOLKEY_DL_OBJECT_ID, 0, len_buf, sizeof(len_buf),
1754 					priv->nonce, sizeof(priv->nonce));
1755 		if (r < 0) {
1756 			goto done;
1757 		}
1758 
1759 		out_length = bebytes2ushort(len_buf);
1760 		out_length = MIN(out_length,max_out_len);
1761 
1762 		r = coolkey_read_object(card, COOLKEY_DL_OBJECT_ID, sizeof(len_buf), out, out_length,
1763 					priv->nonce, sizeof(priv->nonce));
1764 
1765 	} else {
1766 		size_t out_length = bebytes2ushort(buf);
1767 		if (out_length > sizeof buf - 2) {
1768 			r = SC_ERROR_WRONG_LENGTH;
1769 			goto done;
1770 		}
1771 		out_length = MIN(out_length, max_out_len);
1772 		memcpy(out, buf + 2, out_length);
1773 		r = out_length;
1774 	}
1775 
1776 done:
1777 	return r;
1778 }
1779 
coolkey_ecc_op(sc_card_t * card,const u8 * data,size_t datalen,u8 * out,size_t outlen)1780 static int coolkey_ecc_op(sc_card_t *card,
1781 					const u8 * data, size_t datalen,
1782 					u8 * out, size_t outlen)
1783 {
1784 	int r;
1785 	const u8 *crypt_in;
1786 	u8  **crypt_out_p;
1787 	u8  ins = 0;
1788 	size_t crypt_in_len, *crypt_out_len_p;
1789 	coolkey_private_data_t * priv = COOLKEY_DATA(card);
1790 	coolkey_compute_ecc_params_t params;
1791 	size_t params_len;
1792 	u8 key_number;
1793 
1794 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1795 	sc_log(card->ctx,
1796 		 "datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n",
1797 		 datalen, outlen);
1798 
1799 	crypt_in = data;
1800 	crypt_in_len = datalen;
1801 
1802 	crypt_out_p = &out;
1803 	crypt_out_len_p = &outlen;
1804 	key_number = priv->key_id;
1805 	params.location = COOLKEY_CRYPT_LOCATION_APDU;
1806 
1807 	if (priv->key_id > 0xff) {
1808 		r = SC_ERROR_NO_DEFAULT_KEY;
1809 		goto done;
1810 	}
1811 
1812 	switch (priv->operation) {
1813 	case SC_SEC_OPERATION_DERIVE:
1814 		ins = COOLKEY_INS_COMPUTE_ECC_KEY_AGREEMENT;
1815 		break;
1816 	case SC_SEC_OPERATION_SIGN:
1817 		ins = COOLKEY_INS_COMPUTE_ECC_SIGNATURE;
1818 		break;
1819 	default:
1820 		r = SC_ERROR_NOT_SUPPORTED;
1821 		goto done;
1822 	}
1823 
1824 	params_len = (sizeof(params) - sizeof(params.buf))  + crypt_in_len;
1825 
1826 	ushort2bebytes(params.buf_len, crypt_in_len);
1827 	if (crypt_in_len) {
1828 		memcpy(params.buf, crypt_in, crypt_in_len);
1829 	}
1830 
1831 
1832 	r = coolkey_apdu_io(card, COOLKEY_CLASS, ins,
1833 			key_number, COOLKEY_CRYPT_ONE_STEP, (u8 *)&params, params_len,
1834 			crypt_out_p, crypt_out_len_p, priv->nonce, sizeof(priv->nonce));
1835 
1836 done:
1837 	return r;
1838 }
1839 
1840 
coolkey_compute_crypt(sc_card_t * card,const u8 * data,size_t datalen,u8 * out,size_t outlen)1841 static int coolkey_compute_crypt(sc_card_t *card,
1842 					const u8 * data, size_t datalen,
1843 					u8 * out, size_t outlen)
1844 {
1845 	coolkey_private_data_t * priv = COOLKEY_DATA(card);
1846 	int r;
1847 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1848 
1849 	switch (priv->algorithm) {
1850 	case SC_ALGORITHM_RSA:
1851 		r = coolkey_rsa_op(card, data, datalen, out, outlen);
1852 		break;
1853 	case SC_ALGORITHM_EC:
1854 		r = coolkey_ecc_op(card, data, datalen, out, outlen);
1855 		break;
1856 	default:
1857 		r = SC_ERROR_NO_CARD_SUPPORT;
1858 		break;
1859 	}
1860 
1861 	SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
1862 }
1863 
1864 
coolkey_class(unsigned long object_id)1865 static u8 coolkey_class(unsigned long object_id) {
1866 	return (object_id >> 24) & 0xff;
1867 }
1868 
coolkey_get_key_id(unsigned long object_id)1869 static unsigned short coolkey_get_key_id(unsigned long object_id) {
1870 	char char_index = (object_id >> 16) & 0xff;
1871 	if (char_index >= '0' && char_index <= '9') {
1872 		return (u8)(char_index - '0');
1873 	}
1874 	if (char_index >= 'A' && char_index <= 'Z') {
1875 		return (u8)(char_index - 'A' + 10);
1876 	}
1877 	if (char_index >= 'a' && char_index <= 'z') {
1878 		return (u8)(char_index - 'a' + 26 + 10);
1879 	}
1880 	return COOLKEY_INVALID_KEY;
1881 }
1882 
1883 /*
1884  * COOLKEY cards don't select objects in the applet, objects are selected by a parameter
1885  * to the APDU. We create paths for the object in which the path value is the object_id
1886  * and the path type is SC_PATH_SELECT_FILE_ID (so we could cache at the PKCS #15 level if
1887  * we wanted to.
1888  *
1889  * This select simply records what object was selected so that read knows how to access it.
1890  */
coolkey_select_file(sc_card_t * card,const sc_path_t * in_path,sc_file_t ** file_out)1891 static int coolkey_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out)
1892 {
1893 	int r;
1894 	struct sc_file *file = NULL;
1895 	coolkey_private_data_t * priv = COOLKEY_DATA(card);
1896 	unsigned long object_id;
1897 
1898 	assert(card != NULL && in_path != NULL);
1899 
1900 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1901 
1902 	if (in_path->len != 4) {
1903 		return SC_ERROR_OBJECT_NOT_FOUND;
1904 	}
1905 	r = coolkey_select_applet(card);
1906 	if (r != SC_SUCCESS) {
1907 		return r;
1908 	}
1909 	object_id = bebytes2ulong(in_path->value);
1910 	priv->obj = coolkey_find_object_by_id(&priv->objects_list, object_id);
1911 	if (priv->obj == NULL) {
1912 		return SC_ERROR_OBJECT_NOT_FOUND;
1913 	}
1914 
1915 	priv->key_id = COOLKEY_INVALID_KEY;
1916 	if (coolkey_class(object_id) == COOLKEY_KEY_CLASS) {
1917 		priv->key_id = coolkey_get_key_id(object_id);
1918 	}
1919 	if (file_out) {
1920 		file = sc_file_new();
1921 		if (file == NULL)
1922 			LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
1923 		file->path = *in_path;
1924 		/* this could be like the FCI */
1925 		file->type =  SC_PATH_TYPE_FILE_ID;
1926 		file->shareable = 0;
1927 		file->ef_structure = 0;
1928 		file->size = priv->obj->length;
1929 		*file_out = file;
1930 	}
1931 
1932 	return SC_SUCCESS;
1933 }
1934 
coolkey_finish(sc_card_t * card)1935 static int coolkey_finish(sc_card_t *card)
1936 {
1937 	coolkey_private_data_t * priv = COOLKEY_DATA(card);
1938 
1939 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1940 	if (priv) {
1941 		coolkey_free_private_data(priv);
1942 	}
1943 	return SC_SUCCESS;
1944 }
1945 
1946 static int
coolkey_add_object(coolkey_private_data_t * priv,unsigned long object_id,const u8 * object_data,size_t object_length,int add_v1_record)1947 coolkey_add_object(coolkey_private_data_t *priv, unsigned long object_id, const u8 *object_data, size_t object_length, int add_v1_record)
1948 {
1949 	sc_cardctl_coolkey_object_t new_object;
1950 	int r;
1951 
1952 	memset(&new_object, 0, sizeof(new_object));
1953 	new_object.path = coolkey_template_path;
1954 	new_object.path.len = 4;
1955 	ulong2bebytes(new_object.path.value, object_id);
1956 	new_object.id = object_id;
1957 	new_object.length = object_length;
1958 
1959 	/* The object ID needs to be unique */
1960 	if (coolkey_find_object_by_id(&priv->objects_list, object_id) != NULL) {
1961 		return SC_ERROR_INTERNAL;
1962 	}
1963 
1964 	if (object_data) {
1965 		new_object.data = malloc(object_length + add_v1_record);
1966 		if (new_object.data == NULL) {
1967 			return SC_ERROR_OUT_OF_MEMORY;
1968 		}
1969 		if (add_v1_record) {
1970 			new_object.data[0] = COOLKEY_V1_OBJECT;
1971 			new_object.length++;
1972 		}
1973 		memcpy(&new_object.data[add_v1_record], object_data, object_length);
1974 	}
1975 
1976 	r = coolkey_add_object_to_list(&priv->objects_list, &new_object);
1977 	if (r != SC_SUCCESS) {
1978 		/* if we didn't successfully put the object on the list,
1979 		 * the data space didn't get adopted. free it before we return */
1980 		free(new_object.data);
1981 		new_object.data = NULL;
1982 	}
1983 	return r;
1984 }
1985 
1986 
1987 static int
coolkey_process_combined_object(sc_card_t * card,coolkey_private_data_t * priv,u8 * object,size_t object_length)1988 coolkey_process_combined_object(sc_card_t *card, coolkey_private_data_t *priv, u8 *object, size_t object_length)
1989 {
1990 	coolkey_combined_header_t *header = (coolkey_combined_header_t *)object;
1991 	unsigned short compressed_offset;
1992 	unsigned short compressed_length;
1993 	unsigned short compressed_type;
1994 	unsigned short object_offset;
1995 	unsigned short object_count;
1996 	coolkey_decompressed_header_t *decompressed_header;
1997 	u8 *decompressed_object = NULL;
1998 	size_t decompressed_object_len = 0;
1999 	int free_decompressed = 0;
2000 	int i, r;
2001 
2002 	if (object_length < sizeof(coolkey_combined_header_t)) {
2003 		return SC_ERROR_CORRUPTED_DATA;
2004 	}
2005 	compressed_offset = bebytes2ushort(header->compression_offset);
2006 	compressed_length = bebytes2ushort(header->compression_length);
2007 	compressed_type   = bebytes2ushort(header->compression_type);
2008 
2009 	if ((((size_t)compressed_offset) + (size_t)compressed_length) >  object_length) {
2010 		return SC_ERROR_CORRUPTED_DATA;
2011 	}
2012 
2013 	/* store the CUID */
2014 	memcpy(&priv->cuid, &header->cuid, sizeof(priv->cuid));
2015 
2016 	if (compressed_type == COOLKEY_COMPRESSION_ZLIB) {
2017 #ifdef ENABLE_ZLIB
2018 		r = sc_decompress_alloc(&decompressed_object, &decompressed_object_len, &object[compressed_offset], compressed_length, COMPRESSION_AUTO);
2019 		if (r)
2020 			goto done;
2021 		free_decompressed = 1;
2022 #else
2023 		sc_log(card->ctx, "Coolkey compression not supported, no zlib");
2024 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
2025 #endif
2026 	}  else {
2027 		decompressed_object =&object[compressed_offset];
2028 		decompressed_object_len = (size_t) compressed_length;
2029 	}
2030 
2031 	decompressed_header = (coolkey_decompressed_header_t *)decompressed_object;
2032 
2033 	if (decompressed_object_len < sizeof(coolkey_decompressed_header_t)) {
2034 		return SC_ERROR_CORRUPTED_DATA;
2035 	}
2036 	object_offset = bebytes2ushort(decompressed_header->object_offset);
2037 	object_count = bebytes2ushort(decompressed_header->object_count);
2038 
2039 
2040 	/*
2041 	 * using 2 different tests here so we can log different errors if logging is
2042 	 * turned on.
2043 	 */
2044 	/* make sure token_name doesn't overrun the buffer */
2045 	if (decompressed_header->token_name_length +
2046 		offsetof(coolkey_decompressed_header_t,token_name) > decompressed_object_len) {
2047 		r = SC_ERROR_CORRUPTED_DATA;
2048 		goto done;
2049 	}
2050 	/* make sure it doesn't overlap the object space */
2051 	if (decompressed_header->token_name_length +
2052 		offsetof(coolkey_decompressed_header_t,token_name) > object_offset) {
2053 		r = SC_ERROR_CORRUPTED_DATA;
2054 		goto done;
2055 	}
2056 
2057 	/* store the token name in the priv structure so the emulator can set it */
2058 	free(priv->token_name);
2059 	priv->token_name = malloc(decompressed_header->token_name_length+1);
2060 	if (priv->token_name == NULL) {
2061 		r = SC_ERROR_OUT_OF_MEMORY;
2062 		goto done;
2063 	}
2064 	memcpy(priv->token_name, &decompressed_header->token_name[0],
2065 							decompressed_header->token_name_length);
2066 	priv->token_name[decompressed_header->token_name_length] = '\0';
2067 	priv->token_name_length = decompressed_header->token_name_length;
2068 
2069 
2070 	for (i=0; i < object_count; i++) {
2071 		u8 *current_object = NULL;
2072 		coolkey_combined_object_header_t *object_header = NULL;
2073 		unsigned long object_id;
2074 		int current_object_len;
2075 
2076 		/* Can we read the object header at all? */
2077 		if ((object_offset + sizeof(coolkey_combined_object_header_t)) > decompressed_object_len) {
2078 			r = SC_ERROR_CORRUPTED_DATA;
2079 			goto done;
2080 		}
2081 
2082 		current_object = &decompressed_object[object_offset];
2083 		object_header = (coolkey_combined_object_header_t *)current_object;
2084 
2085 		/* Parse object ID */
2086 		object_id = bebytes2ulong(object_header->object_id);
2087 
2088 		/* figure out how big it is */
2089 		r = coolkey_v1_get_object_length(current_object, decompressed_object_len-object_offset);
2090 		if (r < 0) {
2091 			goto done;
2092 		}
2093 		if ((size_t)r + object_offset > decompressed_object_len) {
2094 			r = SC_ERROR_CORRUPTED_DATA;
2095 			goto done;
2096 		}
2097 		current_object_len = r;
2098 		object_offset += current_object_len;
2099 
2100 		/* record this object */
2101 		sc_log(card->ctx, "Add new object id=%ld", object_id);
2102 		r = coolkey_add_object(priv, object_id, current_object, current_object_len, 1);
2103 		if (r) {
2104 			goto done;
2105 		}
2106 
2107 	}
2108 	r = SC_SUCCESS;
2109 
2110 done:
2111 	if (free_decompressed) {
2112 		free(decompressed_object);
2113 	}
2114 	return r;
2115 }
2116 
2117 static int
coolkey_list_object(sc_card_t * card,u8 seq,coolkey_object_info_t * object_info)2118 coolkey_list_object(sc_card_t *card, u8 seq, coolkey_object_info_t *object_info)
2119 {
2120 	u8 *rbuf = (u8 *) object_info;
2121 	size_t rbuflen = sizeof(*object_info);
2122 
2123 	return coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_LIST_OBJECTS, seq, 0,
2124 			NULL, 0, &rbuf, &rbuflen, NULL, 0);
2125 
2126 }
2127 
2128 /*
2129  * Initialize the Coolkey data structures.
2130  */
coolkey_initialize(sc_card_t * card)2131 static int coolkey_initialize(sc_card_t *card)
2132 {
2133 	int r;
2134 	coolkey_private_data_t *priv = NULL;
2135 	coolkey_life_cycle_t life_cycle;
2136 	coolkey_object_info_t object_info;
2137 	int combined_processed = 0;
2138 
2139 	/* already found? */
2140 	if (card->drv_data) {
2141 		return SC_SUCCESS;
2142 	}
2143 	sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"Coolkey Applet found");
2144 
2145 	priv = coolkey_new_private_data();
2146 	if (priv == NULL) {
2147 		r = SC_ERROR_OUT_OF_MEMORY;
2148 		goto cleanup;
2149 	}
2150 	r = coolkey_get_life_cycle(card, &life_cycle);
2151 	if (r < 0) {
2152 		goto cleanup;
2153 	}
2154 
2155 	/* Select a coolkey read the coolkey objects out */
2156 	r = coolkey_select_applet(card);
2157 	if (r < 0) {
2158 		goto cleanup;
2159 	}
2160 
2161 	priv->protocol_version_major = life_cycle.protocol_version_major;
2162 	priv->protocol_version_minor = life_cycle.protocol_version_minor;
2163 	priv->pin_count = life_cycle.pin_count;
2164 	priv->life_cycle = life_cycle.life_cycle;
2165 
2166 	/* walk down the list of objects and read them off the token */
2167 	r = coolkey_list_object(card, COOLKEY_LIST_RESET, &object_info);
2168 	while (r >= 0) {
2169 		unsigned long object_id;
2170 		unsigned long object_len;
2171 
2172 		/* The card did not return what we expected: Lets try other objects */
2173 		if ((size_t)r < (sizeof(object_info)))
2174 			break;
2175 
2176 		/* TODO also look at the ACL... */
2177 
2178 		object_id = bebytes2ulong(object_info.object_id);
2179 		object_len = bebytes2ulong(object_info.object_length);
2180 		/* Avoid insanely large data */
2181 		if (object_len > MAX_FILE_SIZE) {
2182 			r = SC_ERROR_CORRUPTED_DATA;
2183 			goto cleanup;
2184 		}
2185 
2186 		/* the combined object is a single object that can store the other objects.
2187 		 * most coolkeys provisioned by TPS has a single combined object that is
2188 		 * compressed greatly increasing the effectiveness of compress (since lots
2189 		 * of certs on the token share the same Subject and Issuer DN's). We now
2190 		 * process it separately so that we can have both combined objects managed
2191 		 * by TPS and user managed certs on the same token */
2192 		if (object_id == COOLKEY_COMBINED_OBJECT_ID) {
2193 			u8 *object = malloc(object_len);
2194 			if (object == NULL) {
2195 				r = SC_ERROR_OUT_OF_MEMORY;
2196 				break;
2197 			}
2198 			r = coolkey_read_object(card, COOLKEY_COMBINED_OBJECT_ID, 0, object, object_len,
2199 				priv->nonce, sizeof(priv->nonce));
2200 			if (r < 0) {
2201 				free(object);
2202 				break;
2203 			}
2204 			r = coolkey_process_combined_object(card, priv, object, r);
2205 			free(object);
2206 			if (r != SC_SUCCESS) {
2207 				break;
2208 			}
2209 			combined_processed = 1;
2210 		} else {
2211 			sc_log(card->ctx, "Add new object id=%ld, len=%lu", object_id, object_len);
2212 			r = coolkey_add_object(priv, object_id, NULL, object_len, 0);
2213 			if (r != SC_SUCCESS)
2214 				sc_log(card->ctx, "coolkey_add_object() returned %d", r);
2215 		}
2216 
2217 		/* Read next object: error is handled on the cycle condition and below after cycle */
2218 		r = coolkey_list_object(card, COOLKEY_LIST_NEXT, &object_info);
2219 	}
2220 	if (r != SC_ERROR_FILE_END_REACHED) {
2221 		/* This means the card does not cooperate at all: bail out */
2222 		if (r >= 0) {
2223 			r = SC_ERROR_INVALID_CARD;
2224 		}
2225 		goto cleanup;
2226 	}
2227 	/* if we didn't pull the cuid from the combined object, then grab it now */
2228 	if (!combined_processed) {
2229 		global_platform_cplc_data_t cplc_data;
2230 		/* select the card manager, because a card with applet only will have
2231 		   already selected the coolkey applet */
2232 
2233 		r = gp_select_card_manager(card);
2234 		if (r < 0) {
2235 			goto cleanup;
2236 		}
2237 
2238 		r = gp_get_cplc_data(card, &cplc_data);
2239 		if (r < 0) {
2240 			goto cleanup;
2241 		}
2242 		coolkey_make_cuid_from_cplc(&priv->cuid, &cplc_data);
2243 		priv->token_name = (u8 *)strdup("COOLKEY");
2244 		if (priv->token_name == NULL) {
2245 			r = SC_ERROR_OUT_OF_MEMORY;
2246 			goto cleanup;
2247 		}
2248 		priv->token_name_length = sizeof("COOLKEY")-1;
2249 	}
2250 	card->drv_data = priv;
2251 	LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
2252 
2253 cleanup:
2254 	if (priv) {
2255 		coolkey_free_private_data(priv);
2256 	}
2257 	LOG_FUNC_RETURN(card->ctx, r);
2258 }
2259 
2260 
2261 /* NOTE: returns a bool, 1 card matches, 0 it does not */
coolkey_match_card(sc_card_t * card)2262 static int coolkey_match_card(sc_card_t *card)
2263 {
2264 	int r;
2265 
2266 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
2267 	/* Since we send an APDU, the card's logout function may be called...
2268 	 * however it may be in dirty memory */
2269 	card->ops->logout = NULL;
2270 
2271 	r = coolkey_select_applet(card);
2272 	if (r == SC_SUCCESS) {
2273 		sc_apdu_t apdu;
2274 
2275 		/* The GET STATUS INS with P1 = 1 returns invalid instruction (0x6D00)
2276 		 * on Coolkey applet (reserved for GetMemory function),
2277 		 * while incorrect P1 (0x9C10) on Muscle applets
2278 		 */
2279 		sc_format_apdu(card, &apdu, SC_APDU_CASE_1, COOLKEY_INS_GET_STATUS, 0x01, 0x00);
2280 		apdu.cla = COOLKEY_CLASS;
2281 		apdu.le = 0x00;
2282 		apdu.resplen = 0;
2283 		apdu.resp = NULL;
2284 		r = sc_transmit_apdu(card, &apdu);
2285 		if (r == SC_SUCCESS && apdu.sw1 == 0x6d && apdu.sw2 == 0x00) {
2286 			return 1;
2287 		}
2288 		return 0;
2289 	}
2290 	return 0;
2291 }
2292 
2293 
coolkey_init(sc_card_t * card)2294 static int coolkey_init(sc_card_t *card)
2295 {
2296 	int r;
2297 	unsigned long flags;
2298 	unsigned long ext_flags;
2299 	coolkey_private_data_t * priv;
2300 
2301 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
2302 
2303 	r = coolkey_initialize(card);
2304 	if (r < 0) {
2305 		LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD);
2306 	}
2307 
2308 	card->type = SC_CARD_TYPE_COOLKEY_GENERIC;
2309 
2310 	/* set Token Major/minor version */
2311 	flags = SC_ALGORITHM_RSA_RAW;
2312 
2313 	_sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */
2314 	_sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */
2315 	_sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */
2316 
2317 	flags = SC_ALGORITHM_ECDSA_RAW | SC_ALGORITHM_ECDH_CDH_RAW | SC_ALGORITHM_ECDSA_HASH_NONE;
2318 	ext_flags = SC_ALGORITHM_EXT_EC_NAMEDCURVE | SC_ALGORITHM_EXT_EC_UNCOMPRESES;
2319 
2320 	_sc_card_add_ec_alg(card, 256, flags, ext_flags, NULL);
2321 	_sc_card_add_ec_alg(card, 384, flags, ext_flags, NULL);
2322 	_sc_card_add_ec_alg(card, 521, flags, ext_flags, NULL);
2323 
2324 
2325 	priv = COOLKEY_DATA(card);
2326 	if (priv->pin_count != 0) {
2327 		card->caps |= SC_CARD_CAP_ISO7816_PIN_INFO;
2328 	}
2329 
2330 	LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
2331 }
2332 
2333 
2334 static int
coolkey_pin_cmd(sc_card_t * card,struct sc_pin_cmd_data * data,int * tries_left)2335 coolkey_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left)
2336 {
2337 	int r;
2338 	coolkey_private_data_t * priv = COOLKEY_DATA(card);
2339 	size_t rbuflen;
2340 	u8 *rbuf;
2341 
2342 	/* COOLKEY uses a separate pin from the card pin, managed by the applet.
2343 	 * if we successfully log into coolkey, we will get a nonce, which we append
2344 	 * to our APDUs to authenticate the apdu to the card. This allows coolkey to
2345 	 * maintain separate per application login states without the application
2346 	 * having to cache the pin */
2347 	switch (data->cmd) {
2348 	case SC_PIN_CMD_GET_INFO:
2349 		if (priv->nonce_valid) {
2350 			data->pin1.logged_in = SC_PIN_STATE_LOGGED_IN;
2351 		} else {
2352 			data->pin1.logged_in = SC_PIN_STATE_LOGGED_OUT;
2353 			/* coolkey retries is 100. It's unlikely the pin is block.
2354 			 * instead, coolkey slows down the login command exponentially
2355 			 */
2356 			data->pin1.tries_left = 0xf;
2357 		}
2358 		if (tries_left) {
2359 			*tries_left = data->pin1.tries_left;
2360 		}
2361 		r = SC_SUCCESS;
2362 		break;
2363 
2364 	case SC_PIN_CMD_UNBLOCK:
2365 	case SC_PIN_CMD_CHANGE:
2366 		/* these 2 commands are currently reserved for TPS */
2367 	default:
2368 		r = SC_ERROR_NOT_SUPPORTED;
2369 		break;
2370 	case SC_PIN_CMD_VERIFY:
2371 		/* coolkey applet supports multiple pins, but TPS currently only uses one.
2372 		 * just support the one pin for now (we need an array of nonces to handle
2373 		 * multiple pins) */
2374 		/* coolkey only supports unpadded ascii pins, so no need to format the pin */
2375 		rbuflen = sizeof(priv->nonce);
2376 		rbuf = &priv->nonce[0];
2377 		r = coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_VERIFY_PIN,
2378 			data->pin_reference, 0, data->pin1.data, data->pin1.len,
2379 			&rbuf, &rbuflen, NULL, 0);
2380 		if (r < 0) {
2381 			break;
2382 		}
2383 		priv->nonce_valid = 1;
2384 		r = SC_SUCCESS;
2385 	}
2386 	return r;
2387 }
2388 
2389 
2390 static int
coolkey_logout(sc_card_t * card)2391 coolkey_logout(sc_card_t *card)
2392 {
2393 	/* when we add multi pin support here, how do we know which pin to logout? */
2394 	coolkey_private_data_t * priv = COOLKEY_DATA(card);
2395 	u8 pin_ref = 0;
2396 
2397 	(void) coolkey_apdu_io(card, COOLKEY_CLASS, COOLKEY_INS_LOGOUT, pin_ref, 0, NULL, 0, NULL, NULL,
2398 		priv->nonce, sizeof(priv->nonce));
2399 	/* even if logout failed on the card, flush the nonce and clear the nonce_valid and we are effectively
2400 	 * logged out... needing to login again to get a nonce back */
2401 	memset(priv->nonce, 0, sizeof(priv->nonce));
2402 	priv->nonce_valid = 0;
2403 	return SC_SUCCESS;
2404 }
2405 
2406 
coolkey_card_reader_lock_obtained(sc_card_t * card,int was_reset)2407 static int coolkey_card_reader_lock_obtained(sc_card_t *card, int was_reset)
2408 {
2409 	int r = SC_SUCCESS;
2410 
2411 	SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
2412 
2413 	if (was_reset > 0) {
2414 		r = coolkey_select_applet(card);
2415 	}
2416 
2417 	LOG_FUNC_RETURN(card->ctx, r);
2418 }
2419 
2420 static struct sc_card_operations coolkey_ops;
2421 
2422 static struct sc_card_driver coolkey_drv = {
2423 	"COOLKEY",
2424 	"coolkey",
2425 	&coolkey_ops,
2426 	NULL, 0, NULL
2427 };
2428 
sc_get_driver(void)2429 static struct sc_card_driver * sc_get_driver(void)
2430 {
2431 	struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
2432 
2433 	coolkey_ops = *iso_drv->ops;
2434 	coolkey_ops.match_card = coolkey_match_card;
2435 	coolkey_ops.init = coolkey_init;
2436 	coolkey_ops.finish = coolkey_finish;
2437 
2438 	coolkey_ops.select_file =  coolkey_select_file; /* need to record object type */
2439 	coolkey_ops.get_challenge = coolkey_get_challenge;
2440 	coolkey_ops.read_binary = coolkey_read_binary;
2441 	coolkey_ops.write_binary = coolkey_write_binary;
2442 	coolkey_ops.set_security_env = coolkey_set_security_env;
2443 	coolkey_ops.restore_security_env = coolkey_restore_security_env;
2444 	coolkey_ops.compute_signature = coolkey_compute_crypt;
2445 	coolkey_ops.decipher =  coolkey_compute_crypt;
2446 	coolkey_ops.card_ctl = coolkey_card_ctl;
2447 	coolkey_ops.check_sw = coolkey_check_sw;
2448 	coolkey_ops.pin_cmd = coolkey_pin_cmd;
2449 	coolkey_ops.logout = coolkey_logout;
2450 	coolkey_ops.card_reader_lock_obtained = coolkey_card_reader_lock_obtained;
2451 
2452 	return &coolkey_drv;
2453 }
2454 
2455 
sc_get_coolkey_driver(void)2456 struct sc_card_driver * sc_get_coolkey_driver(void)
2457 {
2458 	return sc_get_driver();
2459 }
2460 
2461