TclPKCS11

Check-in [504bf858f4]
Login

Check-in [504bf858f4]

Overview
Comment:Got tclpkcs11 into usable state
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: 504bf858f4c59564f42b1481fab99183928c4af19a25edb6981f9f14cfb4f02f
User & Date: rkeene on 2010-10-10 04:34:37
Other Links: manifest | tags
Context
2010-10-10
04:45
Added signing and verification to test Made test less verbose check-in: 0a81f17bc9 user: rkeene tags: trunk
04:34
Got tclpkcs11 into usable state check-in: 504bf858f4 user: rkeene tags: trunk
2010-10-09
21:04
Added tclpkcs11 check-in: 73118f183b user: rkeene tags: trunk
Changes

Modified Makefile from [5b44ffd369] to [ed33656445].

1
2
3
4
5
6
7
8
9
10
11
CC = gcc
CFLAGS = -fPIC -DPIC -Wall
CPPFLAGS = -DTCL_USE_STUBS
SHFLAGS = -rdynamic -shared
LIBS = -ldl -ltclstub8.5 

all: tclpkcs11.so

pkcs11.h: pkcs11f.h pkcs11t.h
tclpkcs11.o: tclpkcs11.c pkcs11.h
tclpkcs11.so: tclpkcs11.o

|

|







1
2
3
4
5
6
7
8
9
10
11
CC = gcc
CFLAGS = -g3 -ggdb3 -fPIC -DPIC -Wall
CPPFLAGS = -DTCL_USE_STUBS
SHFLAGS = -nostartfiles -rdynamic -shared
LIBS = -ldl -ltclstub8.5 

all: tclpkcs11.so

pkcs11.h: pkcs11f.h pkcs11t.h
tclpkcs11.o: tclpkcs11.c pkcs11.h
tclpkcs11.so: tclpkcs11.o

Modified pkcs11.h from [61c6152256] to [4b887d3c75].

Modified pkcs11f.h from [84cbda383c] to [9dbcabb35b].

Modified pkcs11t.h from [6d2b7ad611] to [def7d2f918].

1250
1251
1252
1253
1254
1255
1256

1257
1258
1259
1260
1261
1262
1263
 * C_Initialize */
typedef struct CK_C_INITIALIZE_ARGS {
  CK_CREATEMUTEX CreateMutex;
  CK_DESTROYMUTEX DestroyMutex;
  CK_LOCKMUTEX LockMutex;
  CK_UNLOCKMUTEX UnlockMutex;
  CK_FLAGS flags;

  CK_VOID_PTR pReserved;
} CK_C_INITIALIZE_ARGS;

/* flags: bit flags that provide capabilities of the slot
 *      Bit Flag                           Mask       Meaning
 */
#define CKF_LIBRARY_CANT_CREATE_OS_THREADS 0x00000001







>







1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
 * C_Initialize */
typedef struct CK_C_INITIALIZE_ARGS {
  CK_CREATEMUTEX CreateMutex;
  CK_DESTROYMUTEX DestroyMutex;
  CK_LOCKMUTEX LockMutex;
  CK_UNLOCKMUTEX UnlockMutex;
  CK_FLAGS flags;
  CK_VOID_PTR LibraryFlags;
  CK_VOID_PTR pReserved;
} CK_C_INITIALIZE_ARGS;

/* flags: bit flags that provide capabilities of the slot
 *      Bit Flag                           Mask       Meaning
 */
#define CKF_LIBRARY_CANT_CREATE_OS_THREADS 0x00000001

Modified tclpkcs11.c from [def012d324] to [eac26b71e7].

1
2

3
4
5
6
7
8
9
#include <unistd.h>
#include <stdlib.h>

#include <dlfcn.h>
#include <tcl.h>

/* PKCS#11 Definitions for the local platform */
#define CK_PTR *
#define CK_DECLARE_FUNCTION(rv, func) rv func
#define CK_DECLARE_FUNCTION_POINTER(rv, func) rv (CK_PTR func)


>







1
2
3
4
5
6
7
8
9
10
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
#include <tcl.h>

/* PKCS#11 Definitions for the local platform */
#define CK_PTR *
#define CK_DECLARE_FUNCTION(rv, func) rv func
#define CK_DECLARE_FUNCTION_POINTER(rv, func) rv (CK_PTR func)
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
struct tclpkcs11_interpdata {
	/* Handle Hash Table */
	Tcl_HashTable handles;
	unsigned long handles_idx;
};

struct tclpkcs11_handle {

	void *base;
	CK_FUNCTION_LIST_PTR pkcs11;




};






























































































































































































































































































































































static int tclpkcs11_load_module(ClientData cd, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) {
	CK_RV (*getFuncList)(CK_FUNCTION_LIST_PTR_PTR ppFunctionList);
	CK_FUNCTION_LIST_PTR pkcs11_function_list;
	struct tclpkcs11_interpdata *interpdata;
	struct tclpkcs11_handle *new_handle;
	const char *pathname;
	Tcl_HashEntry *tcl_handle_entry;
	Tcl_Obj *tcl_handle;
	void *handle;
	char handle_buf[32];
	int snprintf_ret;
	int is_new_entry;




	CK_RV getFuncList_ret;

	if (!cd) {
		Tcl_SetResult(interp, "invalid clientdata\n", TCL_STATIC);

		return(TCL_ERROR);
	}

	if (objc != 2) {
		Tcl_SetResult(interp, "wrong # args: should be \"pki::pkcs11::loadmodule filename\"", TCL_STATIC);

		return(TCL_ERROR);
	}

	pathname = Tcl_GetString(objv[1]);
	if (!pathname) {
		Tcl_SetResult(interp, "invalid pathname", TCL_STATIC);

		return(TCL_ERROR);
	}


	handle = dlopen(pathname, RTLD_LAZY | RTLD_LOCAL);
	if (!handle) {
		Tcl_SetResult(interp, "unable to load", TCL_STATIC);

		return(TCL_ERROR);
	}


	getFuncList = dlsym(handle, "C_GetFunctionList");
	if (!getFuncList) {
		Tcl_SetResult(interp, "unable to locate C_GetFunctionList symbol in PKCS#11 module", TCL_STATIC);

		return(TCL_ERROR);
	}

	getFuncList_ret = getFuncList(&pkcs11_function_list);
	if (getFuncList_ret != CKR_OK) {
		Tcl_SetResult(interp, "C_GetFunctionList returned in failure", TCL_STATIC);


		return(TCL_ERROR);
	}

	if (!pkcs11_function_list) {
		Tcl_SetResult(interp, "C_GetFunctionList returned invalid data", TCL_STATIC);

		return(TCL_ERROR);
	}

	if (!pkcs11_function_list->C_Initialize) {
		Tcl_SetResult(interp, "C_GetFunctionList returned incomplete data", TCL_STATIC);
















		return(TCL_ERROR);
	}

	interpdata = (struct tclpkcs11_interpdata *) cd;

	snprintf_ret = snprintf(handle_buf, sizeof(handle_buf), "pkcsmod%lu", interpdata->handles_idx);
	(interpdata->handles_idx)++;

	if (snprintf_ret >= sizeof(handle_buf)) {
		snprintf_ret = sizeof(handle_buf) - 1;
	}

	tcl_handle = Tcl_NewStringObj(handle_buf, snprintf_ret);
	if (!tcl_handle) {
		Tcl_SetResult(interp, "unable to create new string obj", TCL_STATIC);

		return(TCL_ERROR);
	}

	tcl_handle_entry = Tcl_CreateHashEntry(&interpdata->handles, (const char *) tcl_handle, &is_new_entry);
	if (!tcl_handle_entry) {
		Tcl_SetResult(interp, "unable to create new hash entry", TCL_STATIC);

		return(TCL_ERROR);
	}


	new_handle = malloc(sizeof(*new_handle));
	if (!new_handle) {
		Tcl_SetResult(interp, "unable to allocate internal handle structure", TCL_STATIC);
		return(TCL_ERROR);
	}

	new_handle->base = handle;
	new_handle->pkcs11 = pkcs11_function_list;



	Tcl_SetHashValue(tcl_handle_entry, (ClientData) new_handle);

	Tcl_SetObjResult(interp, tcl_handle);

	return(TCL_OK);
}


















































































































































































































































































































































































































































































































































































































































































































































































































































































































































int Tclpkcs11_Init(Tcl_Interp *interp) {
	struct tclpkcs11_interpdata *interpdata;
	Tcl_Command tclCreatComm_ret;

	int tclPkgProv_ret;

	interpdata = malloc(sizeof(*interpdata));
	if (!interpdata) {
		Tcl_SetResult(interp, "failed to allocate interpdata structure", TCL_STATIC);

		return(TCL_ERROR);
	}



	/* Initialize InterpData structure */
	Tcl_InitObjHashTable(&interpdata->handles);
	interpdata->handles_idx = 0;

	tclCreatComm_ret = Tcl_CreateObjCommand(interp, "pki::pkcs11::loadmodule", tclpkcs11_load_module, interpdata, NULL);
	if (!tclCreatComm_ret) {

		Tcl_SetResult(interp, "failed to create required commands", TCL_STATIC);





		return(TCL_ERROR);
	}







































	tclPkgProv_ret = Tcl_PkgProvide(interp, "pki::pkcs11", "1.0");
	if (tclPkgProv_ret != TCL_OK) {
		Tcl_SetResult(interp, "failed to provide package pki::pkcs11", TCL_STATIC);

		return(tclPkgProv_ret);
	}

	return(TCL_OK);
}







>


>
>
>
>


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

<
<









>
>
>
>
|


|





|






|




>


|




>


|




|
|
<
|





|





|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>














<
<
<
<
<



|




>
|
<
<
<
|
|


>
>








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



>


<
|
<
|


>
>







>
|
>
|
>
>
>


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



<
<





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
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421

1422

1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484


1485
1486
1487
1488
1489
struct tclpkcs11_interpdata {
	/* Handle Hash Table */
	Tcl_HashTable handles;
	unsigned long handles_idx;
};

struct tclpkcs11_handle {
	/* PKCS11 Module Pointers */
	void *base;
	CK_FUNCTION_LIST_PTR pkcs11;

	/* Session Management */
	CK_SLOT_ID session_slot;
	CK_SESSION_HANDLE session;
};

/*
 * Tcl <--> PKCS11 Bridge Functions
 */ 
static Tcl_Obj *tclpkcs11_pkcs11_error(CK_RV errorCode) {
	switch (errorCode) {
		case CKR_OK:
			return(Tcl_NewStringObj("PKCS11_OK OK", -1));
		case CKR_CANCEL:
			return(Tcl_NewStringObj("PKCS11_ERROR CANCEL", -1));
		case CKR_HOST_MEMORY:
			return(Tcl_NewStringObj("PKCS11_ERROR HOST_MEMORY", -1));
		case CKR_SLOT_ID_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR SLOT_ID_INVALID", -1));
		case CKR_GENERAL_ERROR:
			return(Tcl_NewStringObj("PKCS11_ERROR GENERAL_ERROR", -1));
		case CKR_FUNCTION_FAILED:
			return(Tcl_NewStringObj("PKCS11_ERROR FUNCTION_FAILED", -1));
		case CKR_ARGUMENTS_BAD:
			return(Tcl_NewStringObj("PKCS11_ERROR ARGUMENTS_BAD", -1));
		case CKR_NO_EVENT:
			return(Tcl_NewStringObj("PKCS11_ERROR NO_EVENT", -1));
		case CKR_NEED_TO_CREATE_THREADS:
			return(Tcl_NewStringObj("PKCS11_ERROR NEED_TO_CREATE_THREADS", -1));
		case CKR_CANT_LOCK:
			return(Tcl_NewStringObj("PKCS11_ERROR CANT_LOCK", -1));
		case CKR_ATTRIBUTE_READ_ONLY:
			return(Tcl_NewStringObj("PKCS11_ERROR ATTRIBUTE_READ_ONLY", -1));
		case CKR_ATTRIBUTE_SENSITIVE:
			return(Tcl_NewStringObj("PKCS11_ERROR ATTRIBUTE_SENSITIVE", -1));
		case CKR_ATTRIBUTE_TYPE_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR ATTRIBUTE_TYPE_INVALID", -1));
		case CKR_ATTRIBUTE_VALUE_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR ATTRIBUTE_VALUE_INVALID", -1));
		case CKR_DATA_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR DATA_INVALID", -1));
		case CKR_DATA_LEN_RANGE:
			return(Tcl_NewStringObj("PKCS11_ERROR DATA_LEN_RANGE", -1));
		case CKR_DEVICE_ERROR:
			return(Tcl_NewStringObj("PKCS11_ERROR DEVICE_ERROR", -1));
		case CKR_DEVICE_MEMORY:
			return(Tcl_NewStringObj("PKCS11_ERROR DEVICE_MEMORY", -1));
		case CKR_DEVICE_REMOVED:
			return(Tcl_NewStringObj("PKCS11_ERROR DEVICE_REMOVED", -1));
		case CKR_ENCRYPTED_DATA_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR ENCRYPTED_DATA_INVALID", -1));
		case CKR_ENCRYPTED_DATA_LEN_RANGE:
			return(Tcl_NewStringObj("PKCS11_ERROR ENCRYPTED_DATA_LEN_RANGE", -1));
		case CKR_FUNCTION_CANCELED:
			return(Tcl_NewStringObj("PKCS11_ERROR FUNCTION_CANCELED", -1));
		case CKR_FUNCTION_NOT_PARALLEL:
			return(Tcl_NewStringObj("PKCS11_ERROR FUNCTION_NOT_PARALLEL", -1));
		case CKR_FUNCTION_NOT_SUPPORTED:
			return(Tcl_NewStringObj("PKCS11_ERROR FUNCTION_NOT_SUPPORTED", -1));
		case CKR_KEY_HANDLE_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR KEY_HANDLE_INVALID", -1));
		case CKR_KEY_SIZE_RANGE:
			return(Tcl_NewStringObj("PKCS11_ERROR KEY_SIZE_RANGE", -1));
		case CKR_KEY_TYPE_INCONSISTENT:
			return(Tcl_NewStringObj("PKCS11_ERROR KEY_TYPE_INCONSISTENT", -1));
		case CKR_KEY_NOT_NEEDED:
			return(Tcl_NewStringObj("PKCS11_ERROR KEY_NOT_NEEDED", -1));
		case CKR_KEY_CHANGED:
			return(Tcl_NewStringObj("PKCS11_ERROR KEY_CHANGED", -1));
		case CKR_KEY_NEEDED:
			return(Tcl_NewStringObj("PKCS11_ERROR KEY_NEEDED", -1));
		case CKR_KEY_INDIGESTIBLE:
			return(Tcl_NewStringObj("PKCS11_ERROR KEY_INDIGESTIBLE", -1));
		case CKR_KEY_FUNCTION_NOT_PERMITTED:
			return(Tcl_NewStringObj("PKCS11_ERROR KEY_FUNCTION_NOT_PERMITTED", -1));
		case CKR_KEY_NOT_WRAPPABLE:
			return(Tcl_NewStringObj("PKCS11_ERROR KEY_NOT_WRAPPABLE", -1));
		case CKR_KEY_UNEXTRACTABLE:
			return(Tcl_NewStringObj("PKCS11_ERROR KEY_UNEXTRACTABLE", -1));
		case CKR_MECHANISM_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR MECHANISM_INVALID", -1));
		case CKR_MECHANISM_PARAM_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR MECHANISM_PARAM_INVALID", -1));
		case CKR_OBJECT_HANDLE_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR OBJECT_HANDLE_INVALID", -1));
		case CKR_OPERATION_ACTIVE:
			return(Tcl_NewStringObj("PKCS11_ERROR OPERATION_ACTIVE", -1));
		case CKR_OPERATION_NOT_INITIALIZED:
			return(Tcl_NewStringObj("PKCS11_ERROR OPERATION_NOT_INITIALIZED", -1));
		case CKR_PIN_INCORRECT:
			return(Tcl_NewStringObj("PKCS11_ERROR PIN_INCORRECT", -1));
		case CKR_PIN_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR PIN_INVALID", -1));
		case CKR_PIN_LEN_RANGE:
			return(Tcl_NewStringObj("PKCS11_ERROR PIN_LEN_RANGE", -1));
		case CKR_PIN_EXPIRED:
			return(Tcl_NewStringObj("PKCS11_ERROR PIN_EXPIRED", -1));
		case CKR_PIN_LOCKED:
			return(Tcl_NewStringObj("PKCS11_ERROR PIN_LOCKED", -1));
		case CKR_SESSION_CLOSED:
			return(Tcl_NewStringObj("PKCS11_ERROR SESSION_CLOSED", -1));
		case CKR_SESSION_COUNT:
			return(Tcl_NewStringObj("PKCS11_ERROR SESSION_COUNT", -1));
		case CKR_SESSION_HANDLE_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR SESSION_HANDLE_INVALID", -1));
		case CKR_SESSION_PARALLEL_NOT_SUPPORTED:
			return(Tcl_NewStringObj("PKCS11_ERROR SESSION_PARALLEL_NOT_SUPPORTED", -1));
		case CKR_SESSION_READ_ONLY:
			return(Tcl_NewStringObj("PKCS11_ERROR SESSION_READ_ONLY", -1));
		case CKR_SESSION_EXISTS:
			return(Tcl_NewStringObj("PKCS11_ERROR SESSION_EXISTS", -1));
		case CKR_SESSION_READ_ONLY_EXISTS:
			return(Tcl_NewStringObj("PKCS11_ERROR SESSION_READ_ONLY_EXISTS", -1));
		case CKR_SESSION_READ_WRITE_SO_EXISTS:
			return(Tcl_NewStringObj("PKCS11_ERROR SESSION_READ_WRITE_SO_EXISTS", -1));
		case CKR_SIGNATURE_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR SIGNATURE_INVALID", -1));
		case CKR_SIGNATURE_LEN_RANGE:
			return(Tcl_NewStringObj("PKCS11_ERROR SIGNATURE_LEN_RANGE", -1));
		case CKR_TEMPLATE_INCOMPLETE:
			return(Tcl_NewStringObj("PKCS11_ERROR TEMPLATE_INCOMPLETE", -1));
		case CKR_TEMPLATE_INCONSISTENT:
			return(Tcl_NewStringObj("PKCS11_ERROR TEMPLATE_INCONSISTENT", -1));
		case CKR_TOKEN_NOT_PRESENT:
			return(Tcl_NewStringObj("PKCS11_ERROR TOKEN_NOT_PRESENT", -1));
		case CKR_TOKEN_NOT_RECOGNIZED:
			return(Tcl_NewStringObj("PKCS11_ERROR TOKEN_NOT_RECOGNIZED", -1));
		case CKR_TOKEN_WRITE_PROTECTED:
			return(Tcl_NewStringObj("PKCS11_ERROR TOKEN_WRITE_PROTECTED", -1));
		case CKR_UNWRAPPING_KEY_HANDLE_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR UNWRAPPING_KEY_HANDLE_INVALID", -1));
		case CKR_UNWRAPPING_KEY_SIZE_RANGE:
			return(Tcl_NewStringObj("PKCS11_ERROR UNWRAPPING_KEY_SIZE_RANGE", -1));
		case CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT:
			return(Tcl_NewStringObj("PKCS11_ERROR UNWRAPPING_KEY_TYPE_INCONSISTENT", -1));
		case CKR_USER_ALREADY_LOGGED_IN:
			return(Tcl_NewStringObj("PKCS11_ERROR USER_ALREADY_LOGGED_IN", -1));
		case CKR_USER_NOT_LOGGED_IN:
			return(Tcl_NewStringObj("PKCS11_ERROR USER_NOT_LOGGED_IN", -1));
		case CKR_USER_PIN_NOT_INITIALIZED:
			return(Tcl_NewStringObj("PKCS11_ERROR USER_PIN_NOT_INITIALIZED", -1));
		case CKR_USER_TYPE_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR USER_TYPE_INVALID", -1));
		case CKR_USER_ANOTHER_ALREADY_LOGGED_IN:
			return(Tcl_NewStringObj("PKCS11_ERROR USER_ANOTHER_ALREADY_LOGGED_IN", -1));
		case CKR_USER_TOO_MANY_TYPES:
			return(Tcl_NewStringObj("PKCS11_ERROR USER_TOO_MANY_TYPES", -1));
		case CKR_WRAPPED_KEY_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR WRAPPED_KEY_INVALID", -1));
		case CKR_WRAPPED_KEY_LEN_RANGE:
			return(Tcl_NewStringObj("PKCS11_ERROR WRAPPED_KEY_LEN_RANGE", -1));
		case CKR_WRAPPING_KEY_HANDLE_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR WRAPPING_KEY_HANDLE_INVALID", -1));
		case CKR_WRAPPING_KEY_SIZE_RANGE:
			return(Tcl_NewStringObj("PKCS11_ERROR WRAPPING_KEY_SIZE_RANGE", -1));
		case CKR_WRAPPING_KEY_TYPE_INCONSISTENT:
			return(Tcl_NewStringObj("PKCS11_ERROR WRAPPING_KEY_TYPE_INCONSISTENT", -1));
		case CKR_RANDOM_SEED_NOT_SUPPORTED:
			return(Tcl_NewStringObj("PKCS11_ERROR RANDOM_SEED_NOT_SUPPORTED", -1));
		case CKR_RANDOM_NO_RNG:
			return(Tcl_NewStringObj("PKCS11_ERROR RANDOM_NO_RNG", -1));
		case CKR_DOMAIN_PARAMS_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR DOMAIN_PARAMS_INVALID", -1));
		case CKR_BUFFER_TOO_SMALL:
			return(Tcl_NewStringObj("PKCS11_ERROR BUFFER_TOO_SMALL", -1));
		case CKR_SAVED_STATE_INVALID:
			return(Tcl_NewStringObj("PKCS11_ERROR SAVED_STATE_INVALID", -1));
		case CKR_INFORMATION_SENSITIVE:
			return(Tcl_NewStringObj("PKCS11_ERROR INFORMATION_SENSITIVE", -1));
		case CKR_STATE_UNSAVEABLE:
			return(Tcl_NewStringObj("PKCS11_ERROR STATE_UNSAVEABLE", -1));
		case CKR_CRYPTOKI_NOT_INITIALIZED:
			return(Tcl_NewStringObj("PKCS11_ERROR CRYPTOKI_NOT_INITIALIZED", -1));
		case CKR_CRYPTOKI_ALREADY_INITIALIZED:
			return(Tcl_NewStringObj("PKCS11_ERROR CRYPTOKI_ALREADY_INITIALIZED", -1));
		case CKR_MUTEX_BAD:
			return(Tcl_NewStringObj("PKCS11_ERROR MUTEX_BAD", -1));
		case CKR_MUTEX_NOT_LOCKED:
			return(Tcl_NewStringObj("PKCS11_ERROR MUTEX_NOT_LOCKED", -1));
		case CKR_NEW_PIN_MODE:
			return(Tcl_NewStringObj("PKCS11_ERROR NEW_PIN_MODE", -1));
		case CKR_NEXT_OTP:
			return(Tcl_NewStringObj("PKCS11_ERROR NEXT_OTP", -1));
		case CKR_FUNCTION_REJECTED:
			return(Tcl_NewStringObj("PKCS11_ERROR FUNCTION_REJECTED", -1));
		case CKR_VENDOR_DEFINED:
			return(Tcl_NewStringObj("PKCS11_ERROR VENDOR_DEFINED", -1));
	}

	return(Tcl_NewStringObj("PKCS11_ERROR UNKNOWN", -1));
}

static Tcl_Obj *tclpkcs11_bytearray_to_string(const unsigned char *data, unsigned long datalen) {
	unsigned long idx;
	Tcl_Obj *retval;

	retval = Tcl_NewObj();

	if (data == NULL) {
		return(retval);
	}

	for (idx = 0; idx < datalen; idx++) {
		Tcl_AppendPrintfToObj(retval, "%02x", data[idx]);
	}

	return(retval);
}

static unsigned long tclpkcs11_string_to_bytearray(Tcl_Obj *data, unsigned char *outbuf, unsigned long outbuflen) {
	unsigned long outbufidx = 0;
	char tmpbuf[5];
	char *str;
	int tmpint;
	int tcl_rv;

	if (outbuf == NULL) {
		return(0);
	}

	str = Tcl_GetString(data);
	if (!str) {
		return(0);
	}

	tmpbuf[0] = '0';
	tmpbuf[1] = 'x';
	tmpbuf[4] = '\0';

	for (str = Tcl_GetString(data); *str; str++) {
		tmpbuf[2] = *str;

		str++;
		if (!*str) {
			break;
		}

		tmpbuf[3] = *str;

		tcl_rv = Tcl_GetInt(NULL, tmpbuf, &tmpint);
		if (tcl_rv != TCL_OK) {
			return(0);
		}

		outbuf[outbufidx] = tmpint;
		outbufidx++;

		if (outbufidx >= outbuflen) {
			break;
		}
	}

	return(outbufidx);
}

/* PKCS#11 CreateMutex implementation that use Tcl Mutexes */
static CK_RV tclpkcs11_create_mutex(void **mutex) {
	Tcl_Mutex *retval;

	if (!mutex) {
		return(CKR_GENERAL_ERROR);
	}

	retval = (Tcl_Mutex *) ckalloc(sizeof(*retval));
	memset(retval, 0, sizeof(*retval));

	*mutex = retval;

	return(CKR_OK);
}

static CK_RV tclpkcs11_lock_mutex(void *mutex) {
	if (!mutex) {
		return(CKR_GENERAL_ERROR);
	}

	Tcl_MutexLock(*mutex);

	return(CKR_OK);
}

static CK_RV tclpkcs11_unlock_mutex(void *mutex) {
	if (!mutex) {
		return(CKR_GENERAL_ERROR);
	}

	Tcl_MutexUnlock(*mutex);

	return(CKR_OK);
}

static CK_RV tclpkcs11_destroy_mutex(void *mutex) {
	if (!mutex) {
		return(CKR_GENERAL_ERROR);
	}

	Tcl_MutexFinalize(*mutex);
	free(mutex);

	return(CKR_OK);
}

/* Convience function to start a session if one is not already active */
static int tclpkcs11_start_session(struct tclpkcs11_handle *handle, CK_SLOT_ID slot) {
	CK_SESSION_HANDLE tmp_session;
	CK_RV chk_rv;

	if (handle->session != -1) {
		if (handle->session_slot == slot) {
			return(CKR_OK);
		}

		/* Close the existing session and create a new one */
		chk_rv = handle->pkcs11->C_CloseSession(handle->session);
		handle->session = -1;
		handle->session_slot = -1;
		if (chk_rv != CKR_OK) {
			return(chk_rv);
		}
	}

	chk_rv = handle->pkcs11->C_OpenSession(slot, CKF_SERIAL_SESSION, NULL, NULL, &tmp_session);
	if (chk_rv != CKR_OK) {
		handle->pkcs11->C_CloseSession(handle->session);
		handle->session = -1;
		handle->session_slot = -1;

		return(chk_rv);
	}

	handle->session = tmp_session;
	handle->session_slot = slot;

	return(CKR_OK);
}

static int tclpkcs11_close_session(struct tclpkcs11_handle *handle) {
	CK_RV chk_rv;

	if (handle->session != -1) {
		chk_rv = handle->pkcs11->C_CloseSession(handle->session);
		handle->session = -1;
		handle->session_slot = -1;

		if (chk_rv != CKR_OK) {
			return(chk_rv);
		}
	}

	return(CKR_OK);
}

/*
 * Tcl Commands
 */
static int tclpkcs11_load_module(ClientData cd, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) {


	struct tclpkcs11_interpdata *interpdata;
	struct tclpkcs11_handle *new_handle;
	const char *pathname;
	Tcl_HashEntry *tcl_handle_entry;
	Tcl_Obj *tcl_handle;
	void *handle;
	char handle_buf[32];
	int snprintf_ret;
	int is_new_entry;

	CK_C_INITIALIZE_ARGS initargs;
	CK_RV (*getFuncList)(CK_FUNCTION_LIST_PTR_PTR ppFunctionList);
	CK_FUNCTION_LIST_PTR pkcs11_function_list;
	CK_RV chk_rv;

	if (!cd) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid clientdata\n", -1));

		return(TCL_ERROR);
	}

	if (objc != 2) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("wrong # args: should be \"pki::pkcs11::loadmodule filename\"", -1));

		return(TCL_ERROR);
	}

	pathname = Tcl_GetString(objv[1]);
	if (!pathname) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid pathname", -1));

		return(TCL_ERROR);
	}

	/* XXX: TODO: Replace this with Tcl_Load() in 8.6 or otherwise a system-specific loading mechanism */
	handle = dlopen(pathname, RTLD_LAZY | RTLD_LOCAL);
	if (!handle) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("unable to load", -1));

		return(TCL_ERROR);
	}

	/* XXX: TODO: Replace this with ... ? in 8.6 or otherwise a system-specific symbol lookup mechanism */
	getFuncList = dlsym(handle, "C_GetFunctionList");
	if (!getFuncList) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("unable to locate C_GetFunctionList symbol in PKCS#11 module", -1));

		return(TCL_ERROR);
	}

	chk_rv = getFuncList(&pkcs11_function_list);
	if (chk_rv != CKR_OK) {

		Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

		return(TCL_ERROR);
	}

	if (!pkcs11_function_list) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("C_GetFunctionList returned invalid data", -1));

		return(TCL_ERROR);
	}

	if (!pkcs11_function_list->C_Initialize) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("C_GetFunctionList returned incomplete data", -1));

		return(TCL_ERROR);
	}

	initargs.CreateMutex = tclpkcs11_create_mutex;
	initargs.DestroyMutex = tclpkcs11_destroy_mutex;
	initargs.LockMutex = tclpkcs11_lock_mutex;
	initargs.UnlockMutex = tclpkcs11_unlock_mutex;
	initargs.flags = 0;
	initargs.LibraryFlags = NULL;
	initargs.pReserved = NULL;

	chk_rv = pkcs11_function_list->C_Initialize(&initargs);
	if (chk_rv != CKR_OK) {
		Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

		return(TCL_ERROR);
	}

	interpdata = (struct tclpkcs11_interpdata *) cd;

	snprintf_ret = snprintf(handle_buf, sizeof(handle_buf), "pkcsmod%lu", interpdata->handles_idx);
	(interpdata->handles_idx)++;

	if (snprintf_ret >= sizeof(handle_buf)) {
		snprintf_ret = sizeof(handle_buf) - 1;
	}

	tcl_handle = Tcl_NewStringObj(handle_buf, snprintf_ret);






	tcl_handle_entry = Tcl_CreateHashEntry(&interpdata->handles, (const char *) tcl_handle, &is_new_entry);
	if (!tcl_handle_entry) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("unable to create new hash entry", -1));

		return(TCL_ERROR);
	}

	/* Allocate the per-handle structure */
	new_handle = (struct tclpkcs11_handle *) ckalloc(sizeof(*new_handle));




	/* Initialize the per-handle structure */
	new_handle->base = handle;
	new_handle->pkcs11 = pkcs11_function_list;
	new_handle->session = -1;
	new_handle->session_slot = -1;

	Tcl_SetHashValue(tcl_handle_entry, (ClientData) new_handle);

	Tcl_SetObjResult(interp, tcl_handle);

	return(TCL_OK);
}

static int tclpkcs11_unload_module(ClientData cd, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) {
	struct tclpkcs11_interpdata *interpdata;
	struct tclpkcs11_handle *handle;
	Tcl_HashEntry *tcl_handle_entry;
	Tcl_Obj *tcl_handle;

	CK_RV chk_rv;

	if (!cd) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid clientdata", -1));

		return(TCL_ERROR);
	}

	if (objc != 2) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("wrong # args: should be \"pki::pkcs11::unloadmodule handle\"", -1));

		return(TCL_ERROR);
	}

	tcl_handle = objv[1];

	interpdata = (struct tclpkcs11_interpdata *) cd;

	tcl_handle_entry = Tcl_FindHashEntry(&interpdata->handles, (const char *) tcl_handle);
	if (!tcl_handle_entry) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid handle", -1));

		return(TCL_ERROR);
	}

	handle = (struct tclpkcs11_handle *) Tcl_GetHashValue(tcl_handle_entry);
	if (!handle) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid handle", -1));

		return(TCL_ERROR);
	}

	/* Log out of the PKCS11 module */
	chk_rv = handle->pkcs11->C_Logout(handle->session);
	if (chk_rv != CKR_OK) {
		Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

		return(TCL_ERROR);
	}

	/* Close the session, cleaning up all the session objects */
	chk_rv = tclpkcs11_close_session(handle);
	if (chk_rv != CKR_OK) {
		Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

		return(TCL_ERROR);
	}

	/* Ask the PKCS#11 Provider to terminate */
	chk_rv = handle->pkcs11->C_Finalize(NULL);
	if (chk_rv != CKR_OK) {
		Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

		return(TCL_ERROR);
	}

	/* Delete our hash entry */
	Tcl_DeleteHashEntry(tcl_handle_entry);

	/* Attempt to unload the module */
	dlclose(handle->base);

	/* Free our allocated handle */
	ckfree((char *) handle);

	Tcl_SetObjResult(interp, Tcl_NewBooleanObj(1));

	return(TCL_OK);
}

static int tclpkcs11_list_slots(ClientData cd, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) {
	struct tclpkcs11_interpdata *interpdata;
	struct tclpkcs11_handle *handle;
	Tcl_HashEntry *tcl_handle_entry;
	Tcl_Obj *tcl_handle;
	Tcl_Obj *ret_list, *curr_item_list, *flags_list, *slot_desc;

	CK_SLOT_ID_PTR slots;
	CK_SLOT_INFO slotInfo;
	CK_TOKEN_INFO tokenInfo;
	CK_ULONG numSlots, currSlot;
	CK_RV chk_rv;

	if (!cd) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid clientdata", -1));

		return(TCL_ERROR);
	}

	if (objc != 2) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("wrong # args: should be \"pki::pkcs11::listslots handle\"", -1));

		return(TCL_ERROR);
	}

	tcl_handle = objv[1];

	interpdata = (struct tclpkcs11_interpdata *) cd;

	tcl_handle_entry = Tcl_FindHashEntry(&interpdata->handles, (const char *) tcl_handle);
	if (!tcl_handle_entry) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid handle", -1));

		return(TCL_ERROR);
	}

	handle = (struct tclpkcs11_handle *) Tcl_GetHashValue(tcl_handle_entry);
	if (!handle) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid handle", -1));

		return(TCL_ERROR);
	}

	chk_rv = handle->pkcs11->C_GetSlotList(FALSE, NULL, &numSlots);
	if (chk_rv != CKR_OK) {
		Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

		return(TCL_ERROR);
	}

	slots = (CK_SLOT_ID_PTR) ckalloc(sizeof(*slots) * numSlots);

	chk_rv = handle->pkcs11->C_GetSlotList(FALSE, slots, &numSlots);
	if (chk_rv != CKR_OK) {
		Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

		return(TCL_ERROR);
	}

	ret_list = Tcl_NewObj();

	for (currSlot = 0; currSlot < numSlots; currSlot++) {
		chk_rv = handle->pkcs11->C_GetSlotInfo(slots[currSlot], &slotInfo);

		curr_item_list = Tcl_NewObj();
		Tcl_ListObjAppendElement(interp, curr_item_list, Tcl_NewLongObj(slots[currSlot]));

		flags_list = Tcl_NewObj();

		if (chk_rv != CKR_OK) {
			/* Add an empty string as the token label */
			Tcl_ListObjAppendElement(interp, curr_item_list, Tcl_NewStringObj("", 0));

			/* Add the list of existing flags (none) */
			Tcl_ListObjAppendElement(interp, curr_item_list, flags_list);

			/* Add this item to the list */
			Tcl_ListObjAppendElement(interp, ret_list, curr_item_list);

			continue;
		}

		slot_desc = NULL;

		if ((slotInfo.flags & CKF_TOKEN_PRESENT) == CKF_TOKEN_PRESENT) {
			Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("TOKEN_PRESENT", -1));

			chk_rv = handle->pkcs11->C_GetTokenInfo(slots[currSlot], &tokenInfo);

			if (chk_rv == CKR_OK) {
				/* Add the token label as the slot label */
				if (!slot_desc) {
					slot_desc = Tcl_NewStringObj((const char *) tokenInfo.label, 32);
				}

				if ((tokenInfo.flags & CKF_RNG) == CKF_RNG) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("RNG", -1));
				}
				if ((tokenInfo.flags & CKF_WRITE_PROTECTED) == CKF_WRITE_PROTECTED) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("WRITE_PROTECTED", -1));
				}
				if ((tokenInfo.flags & CKF_LOGIN_REQUIRED) == CKF_LOGIN_REQUIRED) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("LOGIN_REQUIRED", -1));
				}
				if ((tokenInfo.flags & CKF_USER_PIN_INITIALIZED) == CKF_USER_PIN_INITIALIZED) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("USER_PIN_INITIALIZED", -1));
				}
				if ((tokenInfo.flags & CKF_RESTORE_KEY_NOT_NEEDED) == CKF_RESTORE_KEY_NOT_NEEDED) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("RESTORE_KEY_NOT_NEEDED", -1));
				}
				if ((tokenInfo.flags & CKF_CLOCK_ON_TOKEN) == CKF_CLOCK_ON_TOKEN) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("CLOCK_ON_TOKEN", -1));
				}
				if ((tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) == CKF_PROTECTED_AUTHENTICATION_PATH) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("PROTECTED_AUTHENTICATION_PATH", -1));
				}
				if ((tokenInfo.flags & CKF_DUAL_CRYPTO_OPERATIONS) == CKF_DUAL_CRYPTO_OPERATIONS) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("DUAL_CRYPTO_OPERATIONS", -1));
				}
				if ((tokenInfo.flags & CKF_TOKEN_INITIALIZED) == CKF_TOKEN_INITIALIZED) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("TOKEN_INITIALIZED", -1));
				}
				if ((tokenInfo.flags & CKF_SECONDARY_AUTHENTICATION) == CKF_SECONDARY_AUTHENTICATION) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("SECONDARY_AUTHENTICATION", -1));
				}
				if ((tokenInfo.flags & CKF_USER_PIN_COUNT_LOW) == CKF_USER_PIN_COUNT_LOW) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("USER_PIN_COUNT_LOW", -1));
				}
				if ((tokenInfo.flags & CKF_USER_PIN_FINAL_TRY) == CKF_USER_PIN_FINAL_TRY) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("USER_PIN_FINAL_TRY", -1));
				}
				if ((tokenInfo.flags & CKF_USER_PIN_LOCKED) == CKF_USER_PIN_LOCKED) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("USER_PIN_LOCKED", -1));
				}
				if ((tokenInfo.flags & CKF_USER_PIN_TO_BE_CHANGED) == CKF_USER_PIN_TO_BE_CHANGED) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("USER_PIN_TO_BE_CHANGED", -1));
				}
				if ((tokenInfo.flags & CKF_SO_PIN_COUNT_LOW) == CKF_SO_PIN_COUNT_LOW) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("SO_PIN_COUNT_LOW", -1));
				}
				if ((tokenInfo.flags & CKF_SO_PIN_FINAL_TRY) == CKF_SO_PIN_FINAL_TRY) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("SO_PIN_FINAL_TRY", -1));
				}
				if ((tokenInfo.flags & CKF_SO_PIN_LOCKED) == CKF_SO_PIN_LOCKED) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("SO_PIN_LOCKED", -1));
				}
				if ((tokenInfo.flags & CKF_SO_PIN_TO_BE_CHANGED) == CKF_SO_PIN_TO_BE_CHANGED) {
					Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("SO_PIN_TO_BE_CHANGED", -1));
				}
			}
		}

		/* Add additional slot flags */
		if ((slotInfo.flags & CKF_REMOVABLE_DEVICE) == CKF_REMOVABLE_DEVICE) {
			Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("REMOVABLE_DEVICE", -1));
		}
		if ((slotInfo.flags & CKF_HW_SLOT) == CKF_HW_SLOT) {
			Tcl_ListObjAppendElement(interp, flags_list, Tcl_NewStringObj("HW_SLOT", -1));
		}

		if (slot_desc) {
			/* If we found a more descriptive slot description, use it */
			Tcl_ListObjAppendElement(interp, curr_item_list, slot_desc);
		} else {
			/* Add the slot description as the label for tokens with nothing in them */
			Tcl_ListObjAppendElement(interp, curr_item_list, Tcl_NewStringObj((const char *) slotInfo.slotDescription, 32));
		}

		Tcl_ListObjAppendElement(interp, curr_item_list, flags_list);

		Tcl_ListObjAppendElement(interp, ret_list, curr_item_list);
	}

	Tcl_SetObjResult(interp, ret_list);

	return(TCL_OK);
}

static int tclpkcs11_list_certs(ClientData cd, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) {
	struct tclpkcs11_interpdata *interpdata;
	struct tclpkcs11_handle *handle;
	Tcl_HashEntry *tcl_handle_entry;
	Tcl_Obj *tcl_handle, *tcl_slotid;
	long slotid_long;
	Tcl_Obj *obj_label, *obj_cert, *obj_id;
	Tcl_Obj *ret_list, *curr_item_list;
	Tcl_Obj *parse_cert_cmd;
	int tcl_rv;

	CK_SLOT_ID slotid;
	CK_OBJECT_HANDLE hObject;
	CK_ULONG ulObjectCount;
	CK_ATTRIBUTE template[] = {
	                           {CKA_CLASS, NULL, 0},
	                           {CKA_LABEL, NULL, 0},
	                           {CKA_ID, NULL, 0},
	                           {CKA_VALUE, NULL, 0}
	}, *curr_attr;
	CK_ULONG curr_attr_idx;
	CK_OBJECT_CLASS *objectclass;
	CK_RV chk_rv;

	if (!cd) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid clientdata", -1));

		return(TCL_ERROR);
	}

	if (objc != 3) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("wrong # args: should be \"pki::pkcs11::listcerts handle slot\"", -1));

		return(TCL_ERROR);
	}

	tcl_handle = objv[1];
	tcl_slotid = objv[2];

	interpdata = (struct tclpkcs11_interpdata *) cd;

	tcl_handle_entry = Tcl_FindHashEntry(&interpdata->handles, (const char *) tcl_handle);
	if (!tcl_handle_entry) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid handle", -1));

		return(TCL_ERROR);
	}

	handle = (struct tclpkcs11_handle *) Tcl_GetHashValue(tcl_handle_entry);
	if (!handle) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid handle", -1));

		return(TCL_ERROR);
	}

	tcl_rv = Tcl_GetLongFromObj(interp, tcl_slotid, &slotid_long);
	if (tcl_rv != TCL_OK) {
		return(tcl_rv);
	}

	slotid = slotid_long;

	chk_rv = tclpkcs11_start_session(handle, slotid);
	if (chk_rv != CKR_OK) {
		Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

		return(TCL_ERROR);
	}

	chk_rv = handle->pkcs11->C_FindObjectsInit(handle->session, NULL, 0);
	if (chk_rv != CKR_OK) {
		Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

		return(TCL_ERROR);
	}

	ret_list = Tcl_NewObj();
	while (1) {
		chk_rv = handle->pkcs11->C_FindObjects(handle->session, &hObject, 1, &ulObjectCount);
		if (chk_rv != CKR_OK) {
			Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

			handle->pkcs11->C_FindObjectsFinal(handle->session);

			return(TCL_ERROR);
		}

		if (ulObjectCount == 0) {
			break;
		}

		if (ulObjectCount != 1) {
			Tcl_SetObjResult(interp, Tcl_NewStringObj("FindObjects() returned a weird number of objects.", -1));

			handle->pkcs11->C_FindObjectsFinal(handle->session);

			return(TCL_ERROR);
		}

		for (curr_attr_idx = 0; curr_attr_idx < (sizeof(template) / sizeof(template[0])); curr_attr_idx++) {
			curr_attr = &template[curr_attr_idx];
			if (curr_attr->pValue) {
				ckfree(curr_attr->pValue);
			}

			curr_attr->pValue = NULL;
		}

		/* Determine size of values to allocate */
		chk_rv = handle->pkcs11->C_GetAttributeValue(handle->session, hObject, template, sizeof(template) / sizeof(template[0]));
		if (chk_rv == CKR_ATTRIBUTE_TYPE_INVALID || chk_rv == CKR_ATTRIBUTE_SENSITIVE || chk_rv == CKR_BUFFER_TOO_SMALL) {
			chk_rv = CKR_OK;
		}

		if (chk_rv != CKR_OK) {
			/* Skip this object if we are not able to process it */
			continue;
		}

		/* Allocate values */
		for (curr_attr_idx = 0; curr_attr_idx < (sizeof(template) / sizeof(template[0])); curr_attr_idx++) {
			curr_attr = &template[curr_attr_idx];

			if (((CK_LONG) curr_attr->ulValueLen) != ((CK_LONG) -1)) {
				curr_attr->pValue = (void *) ckalloc(curr_attr->ulValueLen);
			}
		}

		/* Populate template values */
		chk_rv = handle->pkcs11->C_GetAttributeValue(handle->session, hObject, template, sizeof(template) / sizeof(template[0]));
		if (chk_rv != CKR_OK && chk_rv != CKR_ATTRIBUTE_SENSITIVE && chk_rv != CKR_ATTRIBUTE_TYPE_INVALID && chk_rv != CKR_BUFFER_TOO_SMALL) {
			/* Return an error if we are unable to process this entry due to unexpected errors */
			for (curr_attr_idx = 0; curr_attr_idx < (sizeof(template) / sizeof(template[0])); curr_attr_idx++) {
				curr_attr = &template[curr_attr_idx];
				if (curr_attr->pValue) {
					ckfree(curr_attr->pValue);
				}
			}

			Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

			handle->pkcs11->C_FindObjectsFinal(handle->session);

			return(TCL_ERROR);
		}

		/* Extract certificate data */
		obj_label = NULL;
		obj_id = NULL;
		obj_cert = NULL;
		objectclass = NULL;
		for (curr_attr_idx = 0; curr_attr_idx < (sizeof(template) / sizeof(template[0])); curr_attr_idx++) {
			curr_attr = &template[curr_attr_idx];

			if (!curr_attr->pValue) {
				continue;
			}

			switch (curr_attr->type) {
				case CKA_CLASS:
					objectclass = (CK_OBJECT_CLASS *) curr_attr->pValue;

					if (*objectclass != CKO_CERTIFICATE) {
						continue;
					}

					break;
				case CKA_LABEL:
					obj_label = Tcl_NewStringObj(curr_attr->pValue, curr_attr->ulValueLen);
					break;
				case CKA_ID:
					/* Convert the ID into a readable string */
					obj_id = tclpkcs11_bytearray_to_string(curr_attr->pValue, curr_attr->ulValueLen);

					break;
				case CKA_VALUE:
					if (!objectclass) {
						break;
					}

					obj_cert = Tcl_NewByteArrayObj(curr_attr->pValue, curr_attr->ulValueLen);

					break;
			}

			ckfree(curr_attr->pValue);
			curr_attr->pValue = NULL;
		}

		/* Add this certificate data to return list, if all found */
		if (obj_label == NULL || obj_id == NULL || obj_cert == NULL) {
			continue;
		}

		/* Create the current item list */
		curr_item_list = Tcl_NewObj();
		Tcl_ListObjAppendElement(interp, curr_item_list, Tcl_NewStringObj("pkcs11_handle", -1));
		Tcl_ListObjAppendElement(interp, curr_item_list, tcl_handle);

		Tcl_ListObjAppendElement(interp, curr_item_list, Tcl_NewStringObj("pkcs11_slotid", -1));
		Tcl_ListObjAppendElement(interp, curr_item_list, tcl_slotid);

		Tcl_ListObjAppendElement(interp, curr_item_list, Tcl_NewStringObj("pkcs11_id", -1));
		Tcl_ListObjAppendElement(interp, curr_item_list, obj_id);

		Tcl_ListObjAppendElement(interp, curr_item_list, Tcl_NewStringObj("pkcs11_label", -1));
		Tcl_ListObjAppendElement(interp, curr_item_list, obj_label);

		/* Call "::pki::x509::parse_cert" to parse the cert */
		parse_cert_cmd = Tcl_NewObj();
		Tcl_ListObjAppendElement(interp, parse_cert_cmd, Tcl_NewStringObj("::pki::x509::parse_cert", -1));
		Tcl_ListObjAppendElement(interp, parse_cert_cmd, obj_cert);

		tcl_rv = Tcl_EvalObjEx(interp, parse_cert_cmd, 0);
		if (tcl_rv != TCL_OK) {
			continue;
		}

		/* Add results of [parse_cert] to our return value */
		Tcl_ListObjAppendList(interp, curr_item_list, Tcl_GetObjResult(interp));

		/*
		 * Override the "type" so that [array set] returns our new
		 * type, but we can still parse through the list and figure
		 * out the real subordinate type
		 */
		Tcl_ListObjAppendElement(interp, curr_item_list, Tcl_NewStringObj("type", -1));
		Tcl_ListObjAppendElement(interp, curr_item_list, Tcl_NewStringObj("pkcs11", -1));

		/* Add the current item to the return value list */
		Tcl_ListObjAppendElement(interp, ret_list, curr_item_list);
	}

	/* Terminate search */
	handle->pkcs11->C_FindObjectsFinal(handle->session);

	/* Return */
	Tcl_SetObjResult(interp, ret_list);

	return(TCL_OK);
}

static int tclpkcs11_login(ClientData cd, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) {
	struct tclpkcs11_interpdata *interpdata;
	struct tclpkcs11_handle *handle;
	Tcl_HashEntry *tcl_handle_entry;
	Tcl_Obj *tcl_handle, *tcl_slotid, *tcl_password;
	long slotid_long;
	char *password;
	int password_len;
	int tcl_rv;

	CK_SLOT_ID slotid;
	CK_RV chk_rv;

	if (!cd) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid clientdata", -1));

		return(TCL_ERROR);
	}

	if (objc != 4) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("wrong # args: should be \"pki::pkcs11::login handle slot password\"", -1));

		return(TCL_ERROR);
	}

	tcl_handle = objv[1];
	tcl_slotid = objv[2];
	tcl_password = objv[3];

	interpdata = (struct tclpkcs11_interpdata *) cd;

	tcl_handle_entry = Tcl_FindHashEntry(&interpdata->handles, (const char *) tcl_handle);
	if (!tcl_handle_entry) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid handle", -1));

		return(TCL_ERROR);
	}

	handle = (struct tclpkcs11_handle *) Tcl_GetHashValue(tcl_handle_entry);
	if (!handle) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid handle", -1));

		return(TCL_ERROR);
	}

	tcl_rv = Tcl_GetLongFromObj(interp, tcl_slotid, &slotid_long);
	if (tcl_rv != TCL_OK) {
		return(tcl_rv);
	}

	slotid = slotid_long;

	chk_rv = tclpkcs11_start_session(handle, slotid);
	if (chk_rv != CKR_OK) {
		Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

		return(TCL_ERROR);
	}

	password = Tcl_GetStringFromObj(tcl_password, &password_len);

	chk_rv = handle->pkcs11->C_Login(handle->session, CKU_USER, (CK_UTF8CHAR_PTR) password, password_len);
	switch (chk_rv) {
		case CKR_OK:
		case CKR_USER_ALREADY_LOGGED_IN:
			Tcl_SetObjResult(interp, Tcl_NewBooleanObj(1));

			break;
		case CKR_PIN_INCORRECT:
			Tcl_SetObjResult(interp, Tcl_NewBooleanObj(0));

			break;
		default:
			Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

			return(TCL_ERROR);
	}

	return(TCL_OK);
}

static int tclpkcs11_logout(ClientData cd, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) {
	struct tclpkcs11_interpdata *interpdata;
	struct tclpkcs11_handle *handle;
	Tcl_HashEntry *tcl_handle_entry;
	Tcl_Obj *tcl_handle, *tcl_slotid;
	long slotid_long;
	int tcl_rv;

	CK_SLOT_ID slotid;
	CK_RV chk_rv;

	if (!cd) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid clientdata", -1));

		return(TCL_ERROR);
	}

	if (objc != 3) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("wrong # args: should be \"pki::pkcs11::login handle slot\"", -1));

		return(TCL_ERROR);
	}

	tcl_handle = objv[1];
	tcl_slotid = objv[2];

	interpdata = (struct tclpkcs11_interpdata *) cd;

	tcl_handle_entry = Tcl_FindHashEntry(&interpdata->handles, (const char *) tcl_handle);
	if (!tcl_handle_entry) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid handle", -1));

		return(TCL_ERROR);
	}

	handle = (struct tclpkcs11_handle *) Tcl_GetHashValue(tcl_handle_entry);
	if (!handle) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid handle", -1));

		return(TCL_ERROR);
	}

	tcl_rv = Tcl_GetLongFromObj(interp, tcl_slotid, &slotid_long);
	if (tcl_rv != TCL_OK) {
		return(tcl_rv);
	}

	slotid = slotid_long;

	chk_rv = tclpkcs11_start_session(handle, slotid);
	if (chk_rv != CKR_OK) {
		Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

		return(TCL_ERROR);
	}

	chk_rv = handle->pkcs11->C_Logout(handle->session);
	if (chk_rv != CKR_OK) {
		Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

		return(TCL_ERROR);
	}

	Tcl_SetObjResult(interp, Tcl_NewBooleanObj(1));

	return(TCL_OK);
}

static int tclpkcs11_perform_pki(int encrypt, ClientData cd, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) {
	struct tclpkcs11_interpdata *interpdata;
	struct tclpkcs11_handle *handle;
	unsigned char *input, resultbuf[1024];
	unsigned long tcl_strtobytearray_rv;
	Tcl_HashEntry *tcl_handle_entry;
	Tcl_Obj *pki_real_cmd;
	Tcl_Obj *tcl_keylist, **tcl_keylist_values, *tcl_keylist_key, *tcl_keylist_val;
	Tcl_Obj *tcl_mode, *tcl_input;
	Tcl_Obj *tcl_handle = NULL, *tcl_slotid = NULL, *tcl_objid = NULL;
	Tcl_Obj *tcl_result;
	long slotid_long;
	int tcl_keylist_llength, idx;
	int input_len;
	CK_ULONG resultbuf_len;
	int tcl_rv;

	CK_SLOT_ID slotid;
	CK_OBJECT_HANDLE hObject;
	CK_ULONG foundObjs;
	CK_OBJECT_CLASS objectclass_pk;
	CK_ATTRIBUTE template[] = {
	                           {CKA_ID, NULL, 0},
	                           {CKA_CLASS, NULL, 0},
	};
	CK_MECHANISM mechanism = {CKM_RSA_PKCS, NULL, 0};
	CK_RV chk_rv;

	if (!cd) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid clientdata", -1));

		return(TCL_ERROR);
	}

	if (objc != 4) {
		if (encrypt) {
			Tcl_SetObjResult(interp, Tcl_NewStringObj("wrong # args: should be \"pki::pkcs11::encrypt mode input keylist\"", -1));
		} else {
			Tcl_SetObjResult(interp, Tcl_NewStringObj("wrong # args: should be \"pki::pkcs11::decrypt mode input keylist\"", -1));
		}

		return(TCL_ERROR);
	}

	tcl_mode = objv[1];
	tcl_input = objv[2];
	tcl_keylist = objv[3];

	/*
	 * Parse the "keylist" argument and remove the extraneous "type
	 * pkcs11" entry so we can pass it to around as needed
	 *
	 * Also, while we are here, pick out the elements we can
	 */
	/* Duplicate the object so we can modify it */
	if (Tcl_IsShared(tcl_keylist)) {
		tcl_keylist = Tcl_DuplicateObj(tcl_keylist);
	}

	tcl_rv = Tcl_ListObjGetElements(interp, tcl_keylist, &tcl_keylist_llength, &tcl_keylist_values);
	if (tcl_rv != TCL_OK) {
		return(tcl_rv);
	}

	if ((tcl_keylist_llength % 2) != 0) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("list must have an even number of elements", -1));

		return(TCL_ERROR);
	}

	for (idx = 0; idx < tcl_keylist_llength; idx += 2) {
		tcl_keylist_key = tcl_keylist_values[idx];
		tcl_keylist_val = tcl_keylist_values[idx + 1];

		if (strcmp(Tcl_GetString(tcl_keylist_key), "type") == 0) {
			if (strcmp(Tcl_GetString(tcl_keylist_val), "pkcs11") == 0) {
				/* Remove "type pkcs11" from list */
				tcl_rv = Tcl_ListObjReplace(interp, tcl_keylist, idx, 2, 0, NULL);
			}

			continue;
		}
		if (strcmp(Tcl_GetString(tcl_keylist_key), "pkcs11_handle") == 0) {
			tcl_handle = tcl_keylist_val;

			continue;
		}
		if (strcmp(Tcl_GetString(tcl_keylist_key), "pkcs11_slotid") == 0) {
			tcl_slotid = tcl_keylist_val;

			continue;
		}
		if (strcmp(Tcl_GetString(tcl_keylist_key), "pkcs11_id") == 0) {
			tcl_objid = tcl_keylist_val;

			continue;
		}
	}

	if (strcmp(Tcl_GetString(tcl_mode), "pub") == 0) {
		/* Public Key Operations can be performed by the Tcl PKI Module */
		pki_real_cmd = Tcl_NewObj();

		if (encrypt) {
			Tcl_ListObjAppendElement(interp, pki_real_cmd, Tcl_NewStringObj("::pki::encrypt", -1));
			Tcl_ListObjAppendElement(interp, pki_real_cmd, Tcl_NewStringObj("-nopad", -1));
		} else {
			Tcl_ListObjAppendElement(interp, pki_real_cmd, Tcl_NewStringObj("::pki::decrypt", -1));
			Tcl_ListObjAppendElement(interp, pki_real_cmd, Tcl_NewStringObj("-nounpad", -1));
		}

		Tcl_ListObjAppendElement(interp, pki_real_cmd, Tcl_NewStringObj("-pub", -1));
		Tcl_ListObjAppendElement(interp, pki_real_cmd, Tcl_NewStringObj("-binary", -1));
		Tcl_ListObjAppendElement(interp, pki_real_cmd, tcl_input);
		Tcl_ListObjAppendElement(interp, pki_real_cmd, tcl_keylist);

		return(Tcl_EvalObjEx(interp, pki_real_cmd, 0));
	}

	if (!tcl_handle) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("could not find element named \"pkcs11_handle\" in keylist", -1));

		return(TCL_ERROR);
	}

	if (!tcl_slotid) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("could not find element named \"pkcs11_slotid\" in keylist", -1));

		return(TCL_ERROR);
	}

	if (!tcl_objid) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("could not find element named \"pkcs11_id\" in keylist", -1));

		return(TCL_ERROR);
	}

	interpdata = (struct tclpkcs11_interpdata *) cd;

	tcl_handle_entry = Tcl_FindHashEntry(&interpdata->handles, (const char *) tcl_handle);
	if (!tcl_handle_entry) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid handle", -1));

		return(TCL_ERROR);
	}

	handle = (struct tclpkcs11_handle *) Tcl_GetHashValue(tcl_handle_entry);
	if (!handle) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("invalid handle", -1));

		return(TCL_ERROR);
	}

	/*
	 * Find the PKCS#11 object ID that cooresponds to this certificate's
	 * private key
	 */
	tcl_rv = Tcl_GetLongFromObj(interp, tcl_slotid, &slotid_long);
	if (tcl_rv != TCL_OK) {
		return(tcl_rv);
	}

	slotid = slotid_long;

	chk_rv = tclpkcs11_start_session(handle, slotid);
	if (chk_rv != CKR_OK) {
		Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

		return(TCL_ERROR);
	}

	/* CKA_ID */
	template[0].pValue = ckalloc(Tcl_GetCharLength(tcl_objid) / 2);
	tcl_strtobytearray_rv = tclpkcs11_string_to_bytearray(tcl_objid, template[0].pValue, Tcl_GetCharLength(tcl_objid) / 2);
	template[0].ulValueLen = tcl_strtobytearray_rv;

	/* CKA_CLASS */
	objectclass_pk = CKO_PRIVATE_KEY;
	template[1].pValue = &objectclass_pk;
	template[1].ulValueLen = sizeof(objectclass_pk);

	chk_rv = handle->pkcs11->C_FindObjectsInit(handle->session, template, sizeof(template) / sizeof(template[0]));
	if (chk_rv != CKR_OK) {
		Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

		return(TCL_ERROR);
	}

	chk_rv = handle->pkcs11->C_FindObjects(handle->session, &hObject, 1, &foundObjs);
	if (chk_rv != CKR_OK) {
		Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

		handle->pkcs11->C_FindObjectsFinal(handle->session);

		return(TCL_ERROR);
	}

	/* Terminate Search */
	handle->pkcs11->C_FindObjectsFinal(handle->session);

	if (foundObjs < 1) {
		Tcl_SetObjResult(interp, Tcl_NewStringObj("unable to find private key that cooresponds to this certificate", -1));

		return(TCL_ERROR);
	}

	/* Perform the PKI operation (encrypt/decrypt) */
	input = Tcl_GetByteArrayFromObj(tcl_input, &input_len);
	if (encrypt) {
		chk_rv = handle->pkcs11->C_SignInit(handle->session, &mechanism, hObject);
		if (chk_rv != CKR_OK) {
			Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

			return(TCL_ERROR);
		}

		resultbuf_len = sizeof(resultbuf);
		chk_rv = handle->pkcs11->C_Sign(handle->session, input, input_len, resultbuf, &resultbuf_len);
		if (chk_rv != CKR_OK) {
			if (chk_rv == CKR_BUFFER_TOO_SMALL) {
				/* Terminate decryption operation */
				handle->pkcs11->C_DecryptFinal(handle->session, NULL, 0);
			}

			Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

			return(TCL_ERROR);
		}
	} else {
		chk_rv = handle->pkcs11->C_DecryptInit(handle->session, &mechanism, hObject);
		if (chk_rv != CKR_OK) {
			Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

			return(TCL_ERROR);
		}

		resultbuf_len = sizeof(resultbuf);
		chk_rv = handle->pkcs11->C_Decrypt(handle->session, input, input_len, resultbuf, &resultbuf_len);
		if (chk_rv != CKR_OK) {
			if (chk_rv == CKR_BUFFER_TOO_SMALL) {
				/* Terminate decryption operation */
				handle->pkcs11->C_DecryptFinal(handle->session, NULL, 0);
			}

			Tcl_SetObjResult(interp, tclpkcs11_pkcs11_error(chk_rv));

			return(TCL_ERROR);
		}
	}

	tcl_result = Tcl_NewByteArrayObj(resultbuf, resultbuf_len);

	Tcl_SetObjResult(interp, tcl_result);

	return(TCL_OK);
}

static int tclpkcs11_encrypt(ClientData cd, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) {
	return(tclpkcs11_perform_pki(1, cd, interp, objc, objv));
}

static int tclpkcs11_decrypt(ClientData cd, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) {
	return(tclpkcs11_perform_pki(0, cd, interp, objc, objv));
}

/*
 * Tcl Loadable Module Initialization
 */
int Tclpkcs11_Init(Tcl_Interp *interp) {
	struct tclpkcs11_interpdata *interpdata;
	Tcl_Command tclCreatComm_ret;
	const char *tclPkgReq_ret;
	int tclPkgProv_ret;


	tclPkgReq_ret = Tcl_PkgRequire(interp, "pki", "0.1", 0);

	if (!tclPkgReq_ret) {
		return(TCL_ERROR);
	}

	interpdata = (struct tclpkcs11_interpdata *) ckalloc(sizeof(*interpdata));

	/* Initialize InterpData structure */
	Tcl_InitObjHashTable(&interpdata->handles);
	interpdata->handles_idx = 0;

	tclCreatComm_ret = Tcl_CreateObjCommand(interp, "pki::pkcs11::loadmodule", tclpkcs11_load_module, interpdata, NULL);
	if (!tclCreatComm_ret) {
		ckfree((char *) interpdata);

		return(TCL_ERROR);
	}

	tclCreatComm_ret = Tcl_CreateObjCommand(interp, "pki::pkcs11::unloadmodule", tclpkcs11_unload_module, interpdata, NULL);
	if (!tclCreatComm_ret) {
		return(TCL_ERROR);
	}

	tclCreatComm_ret = Tcl_CreateObjCommand(interp, "pki::pkcs11::listslots", tclpkcs11_list_slots, interpdata, NULL);
	if (!tclCreatComm_ret) {
		return(TCL_ERROR);
	}

	tclCreatComm_ret = Tcl_CreateObjCommand(interp, "pki::pkcs11::listcerts", tclpkcs11_list_certs, interpdata, NULL);
	if (!tclCreatComm_ret) {
		return(TCL_ERROR);
	}

	tclCreatComm_ret = Tcl_CreateObjCommand(interp, "pki::pkcs11::login", tclpkcs11_login, interpdata, NULL);
	if (!tclCreatComm_ret) {
		return(TCL_ERROR);
	}

	tclCreatComm_ret = Tcl_CreateObjCommand(interp, "pki::pkcs11::logout", tclpkcs11_logout, interpdata, NULL);
	if (!tclCreatComm_ret) {
		return(TCL_ERROR);
	}

	tclCreatComm_ret = Tcl_CreateObjCommand(interp, "pki::pkcs11::encrypt", tclpkcs11_encrypt, interpdata, NULL);
	if (!tclCreatComm_ret) {
		return(TCL_ERROR);
	}

	tclCreatComm_ret = Tcl_CreateObjCommand(interp, "pki::pkcs11::decrypt", tclpkcs11_decrypt, interpdata, NULL);
	if (!tclCreatComm_ret) {
		return(TCL_ERROR);
	}

	/* Register PKI handlers */
	Tcl_ObjSetVar2(interp,
	               Tcl_NewStringObj("pki::handlers", -1),
	               Tcl_NewStringObj("pkcs11", -1),
	               Tcl_NewStringObj("::pki::pkcs11::encrypt ::pki::pkcs11::decrypt", -1),
	               TCL_GLOBAL_ONLY
	              );

	tclPkgProv_ret = Tcl_PkgProvide(interp, "pki::pkcs11", "1.0");
	if (tclPkgProv_ret != TCL_OK) {


		return(tclPkgProv_ret);
	}

	return(TCL_OK);
}

Modified test.tcl from [35dd087458] to [5a54b809c1].

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
#! /usr/bin/env tclsh



set pkcs11_module "/usr/local/lib/libcackey_g.so"

load tclpkcs11.so Tclpkcs11

set handle [::pki::pkcs11::loadmodule $pkcs11_module]
puts "Handle: $handle"

set slots [::pki::pkcs11::listslots $handle]
puts "Slots: $slots"

foreach slotinfo $slots {
	set slotid [lindex $slotinfo 0]

	set slotflags [lindex $slotinfo 1]

	if {[lsearch -exact $slotflags TOKEN_PRESENT] != -1} {

		set token_slotid $slotid
	}
}

if {![info exists token_slotid]} {
	puts stderr "Found no slots with tokens, aborting."

	exit 1
}

set certs [::pki::pkcs11::listcerts $handle $token_slotid]


foreach certinfo $certs {
	set certid [lindex $certinfo 0]
	set cert [lindex $certinfo 1]

}









#::pki::pkcs11::login <handle> <slot> <password>            -> true/false
#::pki::pkcs11::logout <handle> <slot>                      -> true/false



#::pki::pkcs11::sign <handle> <slot> <certId> <data>        -> data


#::pki::pkcs11::decrypt <handle> <slot> <certId> <data>     -> data









#::pki::pkcs11::unloadmoule <handle>                        -> true/false

>
>













>
|


>











>
>

|
|
>
|
>
>
>
>
>
>
>

>
|
|
>
>
>
|
>
>
|
>
>
>
>
>
>
>
>
>
|
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
#! /usr/bin/env tclsh

lappend auto_path [file join [pwd] work lib]

set pkcs11_module "/usr/local/lib/libcackey_g.so"

load tclpkcs11.so Tclpkcs11

set handle [::pki::pkcs11::loadmodule $pkcs11_module]
puts "Handle: $handle"

set slots [::pki::pkcs11::listslots $handle]
puts "Slots: $slots"

foreach slotinfo $slots {
	set slotid [lindex $slotinfo 0]
	set slotlabel [lindex $slotinfo 1]
	set slotflags [lindex $slotinfo 2]

	if {[lsearch -exact $slotflags TOKEN_PRESENT] != -1} {
		set token_slotlabel $slotlabel
		set token_slotid $slotid
	}
}

if {![info exists token_slotid]} {
	puts stderr "Found no slots with tokens, aborting."

	exit 1
}

set certs [::pki::pkcs11::listcerts $handle $token_slotid]
puts "Found [llength $certs] certificates"
set orig "TestMsg"
foreach certinfo $certs {
	puts "Cert: $certinfo"

	set cipher [pki::encrypt -binary -pub $orig $certinfo]

	if {[catch {
		set plain  [pki::decrypt -binary -priv $cipher $certinfo]
	} err]} {
		if {$err == "PKCS11_ERROR USER_NOT_LOGGED_IN"} {
			# Login and try it again...
			puts -nonewline " *** ENTER PIN: "
			flush stdout

			gets stdin password
			::pki::pkcs11::login $handle $token_slotid $password

			set plain  [pki::decrypt -binary -priv $cipher $certinfo]
		}
	}

	if {$plain != $orig} {
		puts "Decryption error!  Expected \"$orig\", got \"$plain\""

		exit
	}

	set cipher [pki::encrypt -binary -priv $orig $certinfo]
	set plain  [pki::decrypt -binary -pub $cipher $certinfo]

	puts "Got Match!"
}

::pki::pkcs11::unloadmodule $handle

Modified usage.txt from [20bb7056fa] to [584fd1a98e].

1

2
3


4
5
6
7
8
::pki::pkcs11::loadmodule <filename>                       -> handle

::pki::pkcs11::listslots  <handle>                         -> list: slot flags
::pki::pkcs11::listcerts  <handle> <slot>                  -> list: certId cert 


::pki::pkcs11::login <handle> <slot> <password>            -> true/false
::pki::pkcs11::logout <handle> <slot>                      -> true/false
::pki::pkcs11::sign <handle> <slot> <certId> <data>        -> data
::pki::pkcs11::decrypt <handle> <slot> <certId> <data>     -> data
::pki::pkcs11::unloadmoule <handle>                        -> true/false

>
|
|
>
>
|
|
<
<
<
1
2
3
4
5
6
7
8



::pki::pkcs11::loadmodule <filename>                       -> handle
::pki::pkcs11::unloadmodule <handle>                       -> true/false
::pki::pkcs11::listslots  <handle>                         -> list: slotId label flags
::pki::pkcs11::listcerts  <handle> <slotId>                -> list: keylist
::pki::pkcs11::encrypt <mode> <input> <keylist>            -> data
::pki::pkcs11::decrypt <mode> <input> <keylist>            -> data
::pki::pkcs11::login <handle> <slotId> <password>          -> true/false
::pki::pkcs11::logout <handle> <slotId>                    -> true/false