opensc-sys 0.1.1

FFI bindings to OpenSC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
/*
 * Generic handling of PKCS11 mechanisms
 *
 * Copyright (C) 2002 Olaf Kirch <okir@suse.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "config.h"

#include <stdlib.h>
#include <string.h>

#include "sc-pkcs11.h"

/* Also used for verification data */
struct hash_signature_info {
	CK_MECHANISM_TYPE	mech;
	CK_MECHANISM_TYPE	hash_mech;
	CK_MECHANISM_TYPE	sign_mech;
	sc_pkcs11_mechanism_type_t *hash_type;
	sc_pkcs11_mechanism_type_t *sign_type;
};

/* Also used for verification and decryption data */
struct signature_data {
	struct sc_pkcs11_object *key;
	struct hash_signature_info *info;
	sc_pkcs11_operation_t *	md;
	CK_BYTE			buffer[4096/8];
	unsigned int	buffer_len;
};

/*
 * Register a mechanism
 */
CK_RV
sc_pkcs11_register_mechanism(struct sc_pkcs11_card *p11card,
				sc_pkcs11_mechanism_type_t *mt)
{
	sc_pkcs11_mechanism_type_t **p;

	if (mt == NULL)
		return CKR_HOST_MEMORY;

	p = (sc_pkcs11_mechanism_type_t **) realloc(p11card->mechanisms,
			(p11card->nmechanisms + 2) * sizeof(*p));
	if (p == NULL)
		return CKR_HOST_MEMORY;
	p11card->mechanisms = p;
	p[p11card->nmechanisms++] = mt;
	p[p11card->nmechanisms] = NULL;
	return CKR_OK;
}

/*
 * Look up a mechanism
 */
sc_pkcs11_mechanism_type_t *
sc_pkcs11_find_mechanism(struct sc_pkcs11_card *p11card, CK_MECHANISM_TYPE mech, unsigned int flags)
{
	sc_pkcs11_mechanism_type_t *mt;
	unsigned int n;

	for (n = 0; n < p11card->nmechanisms; n++) {
		mt = p11card->mechanisms[n];
		if (mt && mt->mech == mech && ((mt->mech_info.flags & flags) == flags))
			return mt;
	}
	return NULL;
}

/*
 * Query mechanisms.
 * All of this is greatly simplified by having the framework
 * register all supported mechanisms at initialization
 * time.
 */
CK_RV
sc_pkcs11_get_mechanism_list(struct sc_pkcs11_card *p11card,
				CK_MECHANISM_TYPE_PTR pList,
				CK_ULONG_PTR pulCount)
{
	sc_pkcs11_mechanism_type_t *mt;
	unsigned int n, count = 0;
	CK_RV rv;

	if (!p11card)
		return CKR_TOKEN_NOT_PRESENT;

	for (n = 0; n < p11card->nmechanisms; n++) {
		if (!(mt = p11card->mechanisms[n]))
			continue;
		if (pList && count < *pulCount)
			pList[count] = mt->mech;
		count++;
	}

	rv = CKR_OK;
	if (pList && count > *pulCount)
		rv = CKR_BUFFER_TOO_SMALL;
	*pulCount = count;
	return rv;
}

CK_RV
sc_pkcs11_get_mechanism_info(struct sc_pkcs11_card *p11card,
			CK_MECHANISM_TYPE mechanism,
			CK_MECHANISM_INFO_PTR pInfo)
{
	sc_pkcs11_mechanism_type_t *mt;

	if (!(mt = sc_pkcs11_find_mechanism(p11card, mechanism, 0)))
		return CKR_MECHANISM_INVALID;
	memcpy(pInfo, &mt->mech_info, sizeof(*pInfo));
	return CKR_OK;
}

/*
 * Create/destroy operation handle
 */
sc_pkcs11_operation_t *
sc_pkcs11_new_operation(sc_pkcs11_session_t *session,
			sc_pkcs11_mechanism_type_t *type)
{
	sc_pkcs11_operation_t *res;

	res = calloc(1, type->obj_size);
	if (res) {
		res->session = session;
		res->type = type;
	}
	return res;
}

void
sc_pkcs11_release_operation(sc_pkcs11_operation_t **ptr)
{
	sc_pkcs11_operation_t *operation = *ptr;

	if (!operation)
		return;
	if (operation->type && operation->type->release)
		operation->type->release(operation);
	memset(operation, 0, sizeof(*operation));
	free(operation);
	*ptr = NULL;
}

CK_RV
sc_pkcs11_md_init(struct sc_pkcs11_session *session,
			CK_MECHANISM_PTR pMechanism)
{
	struct sc_pkcs11_card *p11card;
	sc_pkcs11_operation_t *operation;
	sc_pkcs11_mechanism_type_t *mt;
	CK_RV rv;

	LOG_FUNC_CALLED(context);
	if (!session || !session->slot || !(p11card = session->slot->p11card))
		LOG_FUNC_RETURN(context, CKR_ARGUMENTS_BAD);

	/* See if we support this mechanism type */
	mt = sc_pkcs11_find_mechanism(p11card, pMechanism->mechanism, CKF_DIGEST);
	if (mt == NULL)
		LOG_FUNC_RETURN(context, CKR_MECHANISM_INVALID);

	rv = session_start_operation(session, SC_PKCS11_OPERATION_DIGEST, mt, &operation);
	if (rv != CKR_OK)
		LOG_FUNC_RETURN(context, (int) rv);

	memcpy(&operation->mechanism, pMechanism, sizeof(CK_MECHANISM));

	rv = mt->md_init(operation);

	if (rv != CKR_OK)
		session_stop_operation(session, SC_PKCS11_OPERATION_DIGEST);

	LOG_FUNC_RETURN(context, (int) rv);
}

CK_RV
sc_pkcs11_md_update(struct sc_pkcs11_session *session,
			CK_BYTE_PTR pData, CK_ULONG ulDataLen)
{
	sc_pkcs11_operation_t *op;
	CK_RV rv;

	rv = session_get_operation(session, SC_PKCS11_OPERATION_DIGEST, &op);
	if (rv != CKR_OK)
		goto done;

	rv = op->type->md_update(op, pData, ulDataLen);

done:
	if (rv != CKR_OK)
		session_stop_operation(session, SC_PKCS11_OPERATION_DIGEST);

	LOG_FUNC_RETURN(context, (int) rv);
}

CK_RV
sc_pkcs11_md_final(struct sc_pkcs11_session *session,
			CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen)
{
	sc_pkcs11_operation_t *op;
	CK_RV rv;

	rv = session_get_operation(session, SC_PKCS11_OPERATION_DIGEST, &op);
	if (rv != CKR_OK)
		LOG_FUNC_RETURN(context, (int) rv);

	/* This is a request for the digest length */
	if (pData == NULL)
		*pulDataLen = 0;

	rv = op->type->md_final(op, pData, pulDataLen);
	if (rv == CKR_BUFFER_TOO_SMALL)
		LOG_FUNC_RETURN(context,  pData == NULL ? CKR_OK : CKR_BUFFER_TOO_SMALL);

	session_stop_operation(session, SC_PKCS11_OPERATION_DIGEST);
	LOG_FUNC_RETURN(context, (int) rv);
}

/*
 * Initialize a signing context. When we get here, we know
 * the key object is capable of signing _something_
 */
CK_RV
sc_pkcs11_sign_init(struct sc_pkcs11_session *session, CK_MECHANISM_PTR pMechanism,
		    struct sc_pkcs11_object *key, CK_MECHANISM_TYPE key_type)
{
	struct sc_pkcs11_card *p11card;
	sc_pkcs11_operation_t *operation;
	sc_pkcs11_mechanism_type_t *mt;
	CK_RV rv;

	LOG_FUNC_CALLED(context);
	if (!session || !session->slot || !(p11card = session->slot->p11card))
		LOG_FUNC_RETURN(context, CKR_ARGUMENTS_BAD);

	/* See if we support this mechanism type */
	sc_log(context, "mechanism 0x%lX, key-type 0x%lX",
	       pMechanism->mechanism, key_type);
	mt = sc_pkcs11_find_mechanism(p11card, pMechanism->mechanism, CKF_SIGN);
	if (mt == NULL)
		LOG_FUNC_RETURN(context, CKR_MECHANISM_INVALID);

	/* See if compatible with key type */
	if (mt->key_type != key_type)
		LOG_FUNC_RETURN(context, CKR_KEY_TYPE_INCONSISTENT);

	if (pMechanism->pParameter &&
	    pMechanism->ulParameterLen > sizeof(operation->mechanism_params))
		LOG_FUNC_RETURN(context, CKR_ARGUMENTS_BAD);

	rv = session_start_operation(session, SC_PKCS11_OPERATION_SIGN, mt, &operation);
	if (rv != CKR_OK)
		LOG_FUNC_RETURN(context, (int) rv);

	memcpy(&operation->mechanism, pMechanism, sizeof(CK_MECHANISM));
	if (pMechanism->pParameter) {
		memcpy(&operation->mechanism_params, pMechanism->pParameter,
		       pMechanism->ulParameterLen);
		operation->mechanism.pParameter = &operation->mechanism_params;
	}
	rv = mt->sign_init(operation, key);
	if (rv != CKR_OK)
		session_stop_operation(session, SC_PKCS11_OPERATION_SIGN);

	LOG_FUNC_RETURN(context, (int) rv);
}

CK_RV
sc_pkcs11_sign_update(struct sc_pkcs11_session *session,
		      CK_BYTE_PTR pData, CK_ULONG ulDataLen)
{
	sc_pkcs11_operation_t *op;
	CK_RV rv;

	LOG_FUNC_CALLED(context);
	rv = session_get_operation(session, SC_PKCS11_OPERATION_SIGN, &op);
	if (rv != CKR_OK)
		LOG_FUNC_RETURN(context, (int) rv);

	if (op->type->sign_update == NULL) {
		rv = CKR_KEY_TYPE_INCONSISTENT;
		goto done;
	}

	rv = op->type->sign_update(op, pData, ulDataLen);

done:
	if (rv != CKR_OK)
		session_stop_operation(session, SC_PKCS11_OPERATION_SIGN);

	LOG_FUNC_RETURN(context, (int) rv);
}

CK_RV
sc_pkcs11_sign_final(struct sc_pkcs11_session *session,
		     CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen)
{
	sc_pkcs11_operation_t *op;
	CK_RV rv;

	LOG_FUNC_CALLED(context);
	rv = session_get_operation(session, SC_PKCS11_OPERATION_SIGN, &op);
	if (rv != CKR_OK)
		LOG_FUNC_RETURN(context, (int) rv);

	/* Bail out for signature mechanisms that don't do hashing */
	if (op->type->sign_final == NULL) {
		rv = CKR_KEY_TYPE_INCONSISTENT;
		goto done;
	}

	rv = op->type->sign_final(op, pSignature, pulSignatureLen);

done:
	if (rv != CKR_BUFFER_TOO_SMALL && pSignature != NULL)
		session_stop_operation(session, SC_PKCS11_OPERATION_SIGN);

	LOG_FUNC_RETURN(context, (int) rv);
}

CK_RV
sc_pkcs11_sign_size(struct sc_pkcs11_session *session, CK_ULONG_PTR pLength)
{
	sc_pkcs11_operation_t *op;
	CK_RV rv;

	rv = session_get_operation(session, SC_PKCS11_OPERATION_SIGN, &op);
	if (rv != CKR_OK)
		LOG_FUNC_RETURN(context, (int) rv);

	/* Bail out for signature mechanisms that don't do hashing */
	if (op->type->sign_size == NULL) {
		rv = CKR_KEY_TYPE_INCONSISTENT;
		goto done;
	}

	rv = op->type->sign_size(op, pLength);

done:
	if (rv != CKR_OK)
		session_stop_operation(session, SC_PKCS11_OPERATION_SIGN);

	LOG_FUNC_RETURN(context, (int) rv);
}

/*
 * Initialize a signature operation
 */
static CK_RV
sc_pkcs11_signature_init(sc_pkcs11_operation_t *operation,
		struct sc_pkcs11_object *key)
{
	struct hash_signature_info *info;
	struct signature_data *data;
	CK_RV rv;
	int can_do_it = 0;

	LOG_FUNC_CALLED(context);
	if (!(data = calloc(1, sizeof(*data))))
		LOG_FUNC_RETURN(context, CKR_HOST_MEMORY);
	data->info = NULL;
	data->key = key;

	if (key->ops->can_do)   {
		rv = key->ops->can_do(operation->session, key, operation->type->mech, CKF_SIGN);
		if (rv == CKR_OK)   {
			/* Mechanism recognised and can be performed by pkcs#15 card */
			can_do_it = 1;
		}
		else if (rv == CKR_FUNCTION_NOT_SUPPORTED)   {
			/* Mechanism not recognised by pkcs#15 card */
			can_do_it = 0;
		}
		else  {
			/* Mechanism recognised but cannot be performed by pkcs#15 card, or some general error. */
			free(data);
			LOG_FUNC_RETURN(context, (int) rv);
		}
	}

	/* Validate the mechanism parameters */
	if (key->ops->init_params) {
		rv = key->ops->init_params(operation->session, &operation->mechanism);
		if (rv != CKR_OK) {
			/* Probably bad arguments */
			free(data);
			LOG_FUNC_RETURN(context, (int) rv);
		}
	}

	/* If this is a signature with hash operation,
	 * and card cannot perform itself signature with hash operation,
	 * set up the hash operation */
	info = (struct hash_signature_info *) operation->type->mech_data;
	if (info != NULL && !can_do_it) {
		/* Initialize hash operation */

		data->md = sc_pkcs11_new_operation(operation->session, info->hash_type);
		if (data->md == NULL)
			rv = CKR_HOST_MEMORY;
		else
			rv = info->hash_type->md_init(data->md);
		if (rv != CKR_OK) {
			sc_pkcs11_release_operation(&data->md);
			free(data);
			LOG_FUNC_RETURN(context, (int) rv);
		}
		data->info = info;
	}

	operation->priv_data = data;
	LOG_FUNC_RETURN(context, CKR_OK);
}

static CK_RV
sc_pkcs11_signature_update(sc_pkcs11_operation_t *operation,
		CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
{
	struct signature_data *data;

	LOG_FUNC_CALLED(context);
	sc_log(context, "data part length %li", ulPartLen);
	data = (struct signature_data *) operation->priv_data;
	if (data->md) {
		CK_RV rv = data->md->type->md_update(data->md, pPart, ulPartLen);
		LOG_FUNC_RETURN(context, (int) rv);
	}

	/* This signature mechanism operates on the raw data */
	if (data->buffer_len + ulPartLen > sizeof(data->buffer))
		LOG_FUNC_RETURN(context, CKR_DATA_LEN_RANGE);
	memcpy(data->buffer + data->buffer_len, pPart, ulPartLen);
	data->buffer_len += ulPartLen;
	LOG_FUNC_RETURN(context, CKR_OK);
}

static CK_RV
sc_pkcs11_signature_final(sc_pkcs11_operation_t *operation,
		CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen)
{
	struct signature_data *data;
	CK_RV rv;

	LOG_FUNC_CALLED(context);
	data = (struct signature_data *) operation->priv_data;
	if (data->md) {
		sc_pkcs11_operation_t	*md = data->md;
		CK_ULONG len = sizeof(data->buffer);

		rv = md->type->md_final(md, data->buffer, &len);
		if (rv == CKR_BUFFER_TOO_SMALL)
			rv = CKR_FUNCTION_FAILED;
		if (rv != CKR_OK)
			LOG_FUNC_RETURN(context, (int) rv);
		data->buffer_len = (unsigned int) len;
	}

	rv = data->key->ops->sign(operation->session, data->key, &operation->mechanism,
			data->buffer, data->buffer_len, pSignature, pulSignatureLen);
	LOG_FUNC_RETURN(context, (int) rv);
}

static CK_RV
sc_pkcs11_signature_size(sc_pkcs11_operation_t *operation, CK_ULONG_PTR pLength)
{
	struct sc_pkcs11_object *key;
	CK_ATTRIBUTE attr = { CKA_MODULUS_BITS, pLength, sizeof(*pLength) };
	CK_KEY_TYPE key_type;
	CK_ATTRIBUTE attr_key_type = { CKA_KEY_TYPE, &key_type, sizeof(key_type) };
	CK_RV rv;

	key = ((struct signature_data *) operation->priv_data)->key;
	/*
	 * EC and GOSTR do not have CKA_MODULUS_BITS attribute.
	 * But other code in framework treats them as if they do.
	 * So should do switch(key_type)
	 * and then get what ever attributes are needed.
	 */
	rv = key->ops->get_attribute(operation->session, key, &attr_key_type);
	if (rv == CKR_OK) {
		switch(key_type) {
			case CKK_RSA:
				rv = key->ops->get_attribute(operation->session, key, &attr);
				/* convert bits to bytes */
				if (rv == CKR_OK)
					*pLength = (*pLength + 7) / 8;
				break;
			case CKK_EC:
				/* TODO: -DEE we should use something other then CKA_MODULUS_BITS... */
				rv = key->ops->get_attribute(operation->session, key, &attr);
				*pLength = ((*pLength + 7)/8) * 2 ; /* 2*nLen in bytes */
				break;
			case CKK_GOSTR3410:
				rv = key->ops->get_attribute(operation->session, key, &attr);
				if (rv == CKR_OK)
					*pLength = (*pLength + 7) / 8 * 2;
				break;
			default:
				rv = CKR_MECHANISM_INVALID;
		}
	}

	LOG_FUNC_RETURN(context, (int) rv);
}

static void
sc_pkcs11_signature_release(sc_pkcs11_operation_t *operation)
{
	struct signature_data *data;

	data = (struct signature_data *) operation->priv_data;
	if (!data)
	    return;
	sc_pkcs11_release_operation(&data->md);
	memset(data, 0, sizeof(*data));
	free(data);
}

#ifdef ENABLE_OPENSSL
/*
 * Initialize a verify context. When we get here, we know
 * the key object is capable of verifying _something_
 */
CK_RV
sc_pkcs11_verif_init(struct sc_pkcs11_session *session, CK_MECHANISM_PTR pMechanism,
		struct sc_pkcs11_object *key, CK_MECHANISM_TYPE key_type)
{
	struct sc_pkcs11_card *p11card;
	sc_pkcs11_operation_t *operation;
	sc_pkcs11_mechanism_type_t *mt;
	CK_RV rv;

	if (!session || !session->slot
	 || !(p11card = session->slot->p11card))
		return CKR_ARGUMENTS_BAD;

	/* See if we support this mechanism type */
	mt = sc_pkcs11_find_mechanism(p11card, pMechanism->mechanism, CKF_VERIFY);
	if (mt == NULL)
		return CKR_MECHANISM_INVALID;

	/* See if compatible with key type */
	if (mt->key_type != key_type)
		return CKR_KEY_TYPE_INCONSISTENT;

	rv = session_start_operation(session, SC_PKCS11_OPERATION_VERIFY, mt, &operation);
	if (rv != CKR_OK)
		return rv;

	memcpy(&operation->mechanism, pMechanism, sizeof(CK_MECHANISM));
	if (pMechanism->pParameter) {
		memcpy(&operation->mechanism_params, pMechanism->pParameter,
			pMechanism->ulParameterLen);
		operation->mechanism.pParameter = &operation->mechanism_params;
	}

	rv = mt->verif_init(operation, key);

	if (rv != CKR_OK)
		session_stop_operation(session, SC_PKCS11_OPERATION_VERIFY);

	return rv;

}

CK_RV
sc_pkcs11_verif_update(struct sc_pkcs11_session *session,
		      CK_BYTE_PTR pData, CK_ULONG ulDataLen)
{
	sc_pkcs11_operation_t *op;
	CK_RV rv;

	rv = session_get_operation(session, SC_PKCS11_OPERATION_VERIFY, &op);
	if (rv != CKR_OK)
		return rv;

	if (op->type->verif_update == NULL) {
		rv = CKR_KEY_TYPE_INCONSISTENT;
		goto done;
	}

	rv = op->type->verif_update(op, pData, ulDataLen);

done:
	if (rv != CKR_OK)
		session_stop_operation(session, SC_PKCS11_OPERATION_VERIFY);

	return rv;
}

CK_RV
sc_pkcs11_verif_final(struct sc_pkcs11_session *session,
		     CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen)
{
	sc_pkcs11_operation_t *op;
	CK_RV rv;

	rv = session_get_operation(session, SC_PKCS11_OPERATION_VERIFY, &op);
	if (rv != CKR_OK)
		return rv;

	if (op->type->verif_final == NULL) {
		rv = CKR_KEY_TYPE_INCONSISTENT;
		goto done;
	}

	rv = op->type->verif_final(op, pSignature, ulSignatureLen);

done:
	session_stop_operation(session, SC_PKCS11_OPERATION_VERIFY);
	return rv;
}

/*
 * Initialize a verify operation
 */
static CK_RV
sc_pkcs11_verify_init(sc_pkcs11_operation_t *operation,
		    struct sc_pkcs11_object *key)
{
	struct hash_signature_info *info;
	struct signature_data *data;
	CK_RV rv;

	if (!(data = calloc(1, sizeof(*data))))
		return CKR_HOST_MEMORY;

	data->info = NULL;
	data->key = key;

	if (key->ops->can_do)   {
		rv = key->ops->can_do(operation->session, key, operation->type->mech, CKF_SIGN);
		if ((rv == CKR_OK) || (rv == CKR_FUNCTION_NOT_SUPPORTED))   {
			/* Mechanism recognized and can be performed by pkcs#15 card or algorithm references not supported */
		}
		else {
			/* Mechanism cannot be performed by pkcs#15 card, or some general error. */
			free(data);
			LOG_FUNC_RETURN(context, (int) rv);
		}
	}

	/* Validate the mechanism parameters */
	if (key->ops->init_params) {
		rv = key->ops->init_params(operation->session, &operation->mechanism);
		if (rv != CKR_OK) {
			/* Probably bad arguments */
			free(data);
			LOG_FUNC_RETURN(context, (int) rv);
		}
	}

	/* If this is a verify with hash operation, set up the
	 * hash operation */
	info = (struct hash_signature_info *) operation->type->mech_data;
	if (info != NULL) {
		/* Initialize hash operation */
		data->md = sc_pkcs11_new_operation(operation->session,
						   info->hash_type);
		if (data->md == NULL)
			rv = CKR_HOST_MEMORY;
		else
			rv = info->hash_type->md_init(data->md);
		if (rv != CKR_OK) {
			sc_pkcs11_release_operation(&data->md);
			free(data);
			return rv;
		}
		data->info = info;
	}

	operation->priv_data = data;
	return CKR_OK;
}

static CK_RV
sc_pkcs11_verify_update(sc_pkcs11_operation_t *operation,
		    CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
{
	struct signature_data *data;

	data = (struct signature_data *) operation->priv_data;
	if (data->md) {
		sc_pkcs11_operation_t	*md = data->md;

		return md->type->md_update(md, pPart, ulPartLen);
	}

	/* This verification mechanism operates on the raw data */
	if (data->buffer_len + ulPartLen > sizeof(data->buffer))
		return CKR_DATA_LEN_RANGE;
	memcpy(data->buffer + data->buffer_len, pPart, ulPartLen);
	data->buffer_len += ulPartLen;
	return CKR_OK;
}

static CK_RV
sc_pkcs11_verify_final(sc_pkcs11_operation_t *operation,
			CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen)
{
	struct signature_data *data;
	struct sc_pkcs11_object *key;
	unsigned char *pubkey_value = NULL;
	CK_KEY_TYPE key_type;
	CK_BYTE params[9 /* GOST_PARAMS_ENCODED_OID_SIZE */] = { 0 };
	CK_ATTRIBUTE attr = {CKA_VALUE, NULL, 0};
	CK_ATTRIBUTE attr_key_type = {CKA_KEY_TYPE, &key_type, sizeof(key_type)};
	CK_ATTRIBUTE attr_key_params = {CKA_GOSTR3410_PARAMS, &params, sizeof(params)};
	CK_RV rv;

	data = (struct signature_data *) operation->priv_data;

	if (pSignature == NULL)
		return CKR_ARGUMENTS_BAD;

	key = data->key;
	rv = key->ops->get_attribute(operation->session, key, &attr_key_type);
	if (rv != CKR_OK)
		return rv;

	if (key_type != CKK_GOSTR3410)
		attr.type = CKA_SPKI;
		

	rv = key->ops->get_attribute(operation->session, key, &attr);
	if (rv != CKR_OK)
		return rv;
	pubkey_value = calloc(1, attr.ulValueLen);
	if (!pubkey_value) {
		rv = CKR_HOST_MEMORY;
		goto done;
	}
	attr.pValue = pubkey_value;
	rv = key->ops->get_attribute(operation->session, key, &attr);
	if (rv != CKR_OK)
		goto done;

	if (key_type == CKK_GOSTR3410) {
		rv = key->ops->get_attribute(operation->session, key, &attr_key_params);
		if (rv != CKR_OK)
			goto done;
	}

	rv = sc_pkcs11_verify_data(pubkey_value, (unsigned int) attr.ulValueLen,
		params, sizeof(params),
		&operation->mechanism, data->md,
		data->buffer, data->buffer_len, pSignature, (unsigned int) ulSignatureLen);

done:
	free(pubkey_value);

	return rv;
}
#endif

/*
 * Initialize a decryption context. When we get here, we know
 * the key object is capable of decrypting _something_
 */
CK_RV
sc_pkcs11_decr_init(struct sc_pkcs11_session *session,
			CK_MECHANISM_PTR pMechanism,
			struct sc_pkcs11_object *key,
			CK_MECHANISM_TYPE key_type)
{
	struct sc_pkcs11_card *p11card;
	sc_pkcs11_operation_t *operation;
	sc_pkcs11_mechanism_type_t *mt;
	CK_RV rv;

	if (!session || !session->slot
	 || !(p11card = session->slot->p11card))
		return CKR_ARGUMENTS_BAD;

	/* See if we support this mechanism type */
	mt = sc_pkcs11_find_mechanism(p11card, pMechanism->mechanism, CKF_DECRYPT);
	if (mt == NULL)
		return CKR_MECHANISM_INVALID;

	/* See if compatible with key type */
	if (mt->key_type != key_type)
		return CKR_KEY_TYPE_INCONSISTENT;

	rv = session_start_operation(session, SC_PKCS11_OPERATION_DECRYPT, mt, &operation);
	if (rv != CKR_OK)
		return rv;

	memcpy(&operation->mechanism, pMechanism, sizeof(CK_MECHANISM));
	if (pMechanism->pParameter) {
		memcpy(&operation->mechanism_params, pMechanism->pParameter,
		       pMechanism->ulParameterLen);
		operation->mechanism.pParameter = &operation->mechanism_params;
	}
	rv = mt->decrypt_init(operation, key);

	if (rv != CKR_OK)
		session_stop_operation(session, SC_PKCS11_OPERATION_DECRYPT);

	return rv;
}

CK_RV
sc_pkcs11_decr(struct sc_pkcs11_session *session,
		CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen,
		CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen)
{
	sc_pkcs11_operation_t *op;
	CK_RV rv;

	rv = session_get_operation(session, SC_PKCS11_OPERATION_DECRYPT, &op);
	if (rv != CKR_OK)
		return rv;

	rv = op->type->decrypt(op, pEncryptedData, ulEncryptedDataLen,
	                       pData, pulDataLen);

	if (rv != CKR_BUFFER_TOO_SMALL && pData != NULL)
		session_stop_operation(session, SC_PKCS11_OPERATION_DECRYPT);

	return rv;
}

CK_RV
sc_pkcs11_wrap(struct sc_pkcs11_session *session,
	CK_MECHANISM_PTR pMechanism,
	struct sc_pkcs11_object *wrappingKey,	/* wrapping key */
	CK_KEY_TYPE key_type,			/* type of the wrapping key */
	struct sc_pkcs11_object *targetKey,	/* the key to be wrapped */
	CK_BYTE_PTR wrappedData,
	CK_ULONG_PTR wrappedDataLen)
{
	struct sc_pkcs11_card *p11card;
	sc_pkcs11_operation_t *operation;
	sc_pkcs11_mechanism_type_t *mt;
	CK_RV rv;

	if (!session || !session->slot || !(p11card = session->slot->p11card))
		return CKR_ARGUMENTS_BAD;

	/* See if we support this mechanism type */
	mt = sc_pkcs11_find_mechanism(p11card, pMechanism->mechanism, CKF_UNWRAP);
	if (mt == NULL)
		return CKR_MECHANISM_INVALID;

	/* See if compatible with key type */
	/* TODO: what if there are several mechanisms with different key types? Should we loop through them? */
	if (mt->key_type != key_type)
		return CKR_KEY_TYPE_INCONSISTENT;

	rv = session_start_operation(session, SC_PKCS11_OPERATION_WRAP, mt, &operation);
	if (rv != CKR_OK)
		return rv;

	memcpy(&operation->mechanism, pMechanism, sizeof(CK_MECHANISM));

	rv = operation->type->wrap(operation, wrappingKey,
			targetKey, wrappedData,
			wrappedDataLen);

	session_stop_operation(session, SC_PKCS11_OPERATION_WRAP);

	return rv;
}

/*
 * Unwrap a wrapped key into card. A new key object is created on card.
 */
CK_RV
sc_pkcs11_unwrap(struct sc_pkcs11_session *session,
	CK_MECHANISM_PTR pMechanism,
	struct sc_pkcs11_object *unwrappingKey,
	CK_KEY_TYPE key_type, /* type of the unwrapping key */
	CK_BYTE_PTR pWrappedKey,	/* the wrapped key */
	CK_ULONG ulWrappedKeyLen,	/* bytes length of wrapped key */
	struct sc_pkcs11_object *targetKey)
{
	struct sc_pkcs11_card *p11card;
	sc_pkcs11_operation_t *operation;
	sc_pkcs11_mechanism_type_t *mt;

	CK_RV rv;

	if (!session || !session->slot || !(p11card = session->slot->p11card))
		return CKR_ARGUMENTS_BAD;

	/* See if we support this mechanism type */
	mt = sc_pkcs11_find_mechanism(p11card, pMechanism->mechanism, CKF_UNWRAP);
	if (mt == NULL)
		return CKR_MECHANISM_INVALID;

	/* See if compatible with key type */
	/* TODO: what if there are several mechanisms with different key types? Should we loop through them? */
	if (mt->key_type != key_type)
		return CKR_KEY_TYPE_INCONSISTENT;

	rv = session_start_operation(session, SC_PKCS11_OPERATION_UNWRAP, mt, &operation);
	if (rv != CKR_OK)
		return rv;

	memcpy(&operation->mechanism, pMechanism, sizeof(CK_MECHANISM));


	/*
	 *  TODO: does it make sense to support unwrapping to an in memory key object?
	 *  This implementation assumes that the key should be unwrapped into a
	 *  key object on card, regardless whether CKA_TOKEN = FALSE
	 *  CKA_TOKEN = FALSE is considered an on card session object.
	 */

	rv = operation->type->unwrap(operation, unwrappingKey,
			pWrappedKey, ulWrappedKeyLen,
			targetKey);

	session_stop_operation(session, SC_PKCS11_OPERATION_UNWRAP);

	return rv;
}



/* Derive one key from another, and return results in created object */
CK_RV
sc_pkcs11_deri(struct sc_pkcs11_session *session,
	CK_MECHANISM_PTR pMechanism,
	struct sc_pkcs11_object * basekey,
	CK_KEY_TYPE key_type,
	CK_SESSION_HANDLE hSession,
	CK_OBJECT_HANDLE hdkey,
	struct sc_pkcs11_object * dkey)
{

	struct sc_pkcs11_card *p11card;
	sc_pkcs11_operation_t *operation;
	sc_pkcs11_mechanism_type_t *mt;
	CK_BYTE_PTR keybuf = NULL;
	CK_ULONG ulDataLen = 0;
	CK_ATTRIBUTE template[] = {
		{CKA_VALUE, keybuf, 0}
	};

	CK_RV rv;


	if (!session || !session->slot
	 || !(p11card = session->slot->p11card))
		return CKR_ARGUMENTS_BAD;

	/* See if we support this mechanism type */
	mt = sc_pkcs11_find_mechanism(p11card, pMechanism->mechanism, CKF_DERIVE);
	if (mt == NULL)
		return CKR_MECHANISM_INVALID;

	/* See if compatible with key type */
	if (mt->key_type != key_type)
		return CKR_KEY_TYPE_INCONSISTENT;


	rv = session_start_operation(session, SC_PKCS11_OPERATION_DERIVE, mt, &operation);
	if (rv != CKR_OK)
		return rv;

	memcpy(&operation->mechanism, pMechanism, sizeof(CK_MECHANISM));

	/* Get the size of the data to be returned
	 * If the card could derive a key an leave it on the card
	 * then no data is returned.
	 * If the card returns the data, we will store it in the secret key CKA_VALUE
	 */

	ulDataLen = 0;
	rv = operation->type->derive(operation, basekey,
			pMechanism->pParameter, pMechanism->ulParameterLen,
			NULL, &ulDataLen);
	if (rv != CKR_OK)
		goto out;

	if (ulDataLen > 0)
		keybuf = calloc(1,ulDataLen);
	else
		keybuf = calloc(1,8); /* pass in  dummy buffer */

	if (!keybuf) {
		rv = CKR_HOST_MEMORY;
		goto out;
	}

	/* Now do the actual derivation */

	rv = operation->type->derive(operation, basekey,
	    pMechanism->pParameter, pMechanism->ulParameterLen,
	    keybuf, &ulDataLen);
	if (rv != CKR_OK)
	    goto out;


/* add the CKA_VALUE attribute to the template if it was returned
 * if not assume it is on the card...
 * But for now PIV with ECDH returns the generic key data
 * TODO need to support truncation, if CKA_VALUE_LEN < ulDataLem
 */
	if (ulDataLen > 0) {
	    template[0].pValue = keybuf;
	    template[0].ulValueLen = ulDataLen;

	    dkey->ops->set_attribute(session, dkey, &template[0]);

	    memset(keybuf,0,ulDataLen);
	}

out:
	session_stop_operation(session, SC_PKCS11_OPERATION_DERIVE);

	if (keybuf)
	    free(keybuf);
	return rv;
}


/*
 * Initialize a decrypt operation
 */
static CK_RV
sc_pkcs11_decrypt_init(sc_pkcs11_operation_t *operation,
			struct sc_pkcs11_object *key)
{
	struct signature_data *data;
	CK_RV rv;

	if (!(data = calloc(1, sizeof(*data))))
		return CKR_HOST_MEMORY;

	data->key = key;

	if (key->ops->can_do)   {
		rv = key->ops->can_do(operation->session, key, operation->type->mech, CKF_DECRYPT);
		if ((rv == CKR_OK) || (rv == CKR_FUNCTION_NOT_SUPPORTED))   {
			/* Mechanism recognized and can be performed by pkcs#15 card or algorithm references not supported */
		}
		else {
			/* Mechanism cannot be performed by pkcs#15 card, or some general error. */
			free(data);
			LOG_FUNC_RETURN(context, (int) rv);
		}
	}

	operation->priv_data = data;
	return CKR_OK;
}

static CK_RV
sc_pkcs11_decrypt(sc_pkcs11_operation_t *operation,
		CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen,
		CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen)
{
	struct signature_data *data;
	struct sc_pkcs11_object *key;

	data = (struct signature_data*) operation->priv_data;

	key = data->key;
	return key->ops->decrypt(operation->session,
				key, &operation->mechanism,
				pEncryptedData, ulEncryptedDataLen,
				pData, pulDataLen);
}

static CK_RV
sc_pkcs11_derive(sc_pkcs11_operation_t *operation,
	    struct sc_pkcs11_object *basekey,
	    CK_BYTE_PTR pmechParam, CK_ULONG ulmechParamLen,
	    CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen)
{

	return basekey->ops->derive(operation->session,
		    basekey,
		    &operation->mechanism,
		    pmechParam, ulmechParamLen,
		    pData, pulDataLen);
}


static CK_RV
sc_pkcs11_wrap_operation(sc_pkcs11_operation_t *operation,
	    struct sc_pkcs11_object *wrappingKey,
	    struct sc_pkcs11_object *targetKey,
	    CK_BYTE_PTR pWrappedData, CK_ULONG_PTR ulWrappedDataLen)
{
	if (!operation || !wrappingKey || !wrappingKey->ops || !wrappingKey->ops->wrap_key)
		return CKR_ARGUMENTS_BAD;

    return wrappingKey->ops->wrap_key(operation->session,
		    wrappingKey,
		    &operation->mechanism,
		    targetKey, pWrappedData,
		    ulWrappedDataLen);
}

static CK_RV
sc_pkcs11_unwrap_operation(sc_pkcs11_operation_t *operation,
	    struct sc_pkcs11_object *unwrappingKey,
	    CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen,
	    struct sc_pkcs11_object *targetKey)
{
	if (!operation || !unwrappingKey || !unwrappingKey->ops || !unwrappingKey->ops->unwrap_key)
		return CKR_ARGUMENTS_BAD;

    return unwrappingKey->ops->unwrap_key(operation->session,
		    unwrappingKey,
		    &operation->mechanism,
		    pWrappedKey, ulWrappedKeyLen,
		    targetKey);
}

/*
 * Create new mechanism type for a mechanism supported by
 * the card
 */
sc_pkcs11_mechanism_type_t *
sc_pkcs11_new_fw_mechanism(CK_MECHANISM_TYPE mech,
				CK_MECHANISM_INFO_PTR pInfo,
				CK_KEY_TYPE key_type,
				const void *priv_data,
				void (*free_priv_data)(const void *priv_data))
{
	sc_pkcs11_mechanism_type_t *mt;

	mt = calloc(1, sizeof(*mt));
	if (mt == NULL)
		return mt;
	mt->mech = mech;
	mt->mech_info = *pInfo;
	mt->key_type = key_type;
	mt->mech_data = priv_data;
	mt->free_mech_data = free_priv_data;
	mt->obj_size = sizeof(sc_pkcs11_operation_t);

	mt->release = sc_pkcs11_signature_release;

	if (pInfo->flags & CKF_SIGN) {
		mt->sign_init = sc_pkcs11_signature_init;
		mt->sign_update = sc_pkcs11_signature_update;
		mt->sign_final = sc_pkcs11_signature_final;
		mt->sign_size = sc_pkcs11_signature_size;
#ifdef ENABLE_OPENSSL
		mt->verif_init = sc_pkcs11_verify_init;
		mt->verif_update = sc_pkcs11_verify_update;
		mt->verif_final = sc_pkcs11_verify_final;
#endif
	}
	if (pInfo->flags & CKF_WRAP) {
		mt->wrap = sc_pkcs11_wrap_operation;
	}
	if (pInfo->flags & CKF_UNWRAP) {
		mt->unwrap = sc_pkcs11_unwrap_operation;
	}
	if (pInfo->flags & CKF_DERIVE) {
		mt->derive = sc_pkcs11_derive;
	}
	if (pInfo->flags & CKF_DECRYPT) {
		mt->decrypt_init = sc_pkcs11_decrypt_init;
		mt->decrypt = sc_pkcs11_decrypt;
	}

	return mt;
}

/*
 * Register generic mechanisms
 */
CK_RV
sc_pkcs11_register_generic_mechanisms(struct sc_pkcs11_card *p11card)
{
#ifdef ENABLE_OPENSSL
	sc_pkcs11_register_openssl_mechanisms(p11card);
#endif
	return CKR_OK;
}

void free_info(const void *info)
{
	free((void *) info);
}

/*
 * Register a sign+hash algorithm derived from an algorithm supported
 * by the token + a software hash mechanism
 */
CK_RV
sc_pkcs11_register_sign_and_hash_mechanism(struct sc_pkcs11_card *p11card,
		CK_MECHANISM_TYPE mech,
		CK_MECHANISM_TYPE hash_mech,
		sc_pkcs11_mechanism_type_t *sign_type)
{
	sc_pkcs11_mechanism_type_t *hash_type, *new_type;
	struct hash_signature_info *info;
	CK_MECHANISM_INFO mech_info = sign_type->mech_info;
	CK_RV rv;

	if (!(hash_type = sc_pkcs11_find_mechanism(p11card, hash_mech, CKF_DIGEST)))
		return CKR_MECHANISM_INVALID;

	/* These hash-based mechs can only be used for sign/verify */
	mech_info.flags &= (CKF_SIGN | CKF_SIGN_RECOVER | CKF_VERIFY | CKF_VERIFY_RECOVER);

	info = calloc(1, sizeof(*info));
	if (!info)
		return CKR_HOST_MEMORY;

	info->mech = mech;
	info->sign_type = sign_type;
	info->hash_type = hash_type;
	info->sign_mech = sign_type->mech;
	info->hash_mech = hash_mech;

	new_type = sc_pkcs11_new_fw_mechanism(mech, &mech_info, sign_type->key_type, info, free_info);
	if (!new_type) {
		free_info(info);
		return CKR_HOST_MEMORY;
	}

	rv = sc_pkcs11_register_mechanism(p11card, new_type);
	if (CKR_OK != rv) {
		new_type->free_mech_data(new_type->mech_data);
		free(new_type);
	}

	return rv;
}