aboutsummaryrefslogtreecommitdiffstats
path: root/SoftHSMv2/src/bin/util/softhsm2-util.cpp
blob: 465df4a22205d44547b1aebd3381d42b0932f668 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
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
/*
 * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*****************************************************************************
 softhsm2-util.cpp

 This program can be used for interacting with HSMs using PKCS#11.
 The default library is the libsofthsm2.so
 *****************************************************************************/

#include <config.h>
#include "softhsm2-util.h"
#include "findslot.h"
#include "getpw.h"
#include "library.h"
#include "log.h"
#include "Configuration.h"
#include "SimpleConfigLoader.h"
#include "Directory.h"
#include "MutexFactory.h"
#include "ObjectStoreToken.h"
#include "OSPathSep.h"

#if defined(WITH_OPENSSL)
#include "OSSLCryptoFactory.h"
#else
#include "BotanCryptoFactory.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#ifndef _WIN32
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#else
#include <direct.h>
#include <io.h>
#endif
#include <iostream>
#include <fstream>

// Initialise the one-and-only instance

#ifdef HAVE_CXX11

std::unique_ptr<MutexFactory> MutexFactory::instance(nullptr);
std::unique_ptr<SecureMemoryRegistry> SecureMemoryRegistry::instance(nullptr);
#if defined(WITH_OPENSSL)
std::unique_ptr<OSSLCryptoFactory> OSSLCryptoFactory::instance(nullptr);
#else
std::unique_ptr<BotanCryptoFactory> BotanCryptoFactory::instance(nullptr);
#endif

#else

std::auto_ptr<MutexFactory> MutexFactory::instance(NULL);
std::auto_ptr<SecureMemoryRegistry> SecureMemoryRegistry::instance(NULL);
#if defined(WITH_OPENSSL)
std::auto_ptr<OSSLCryptoFactory> OSSLCryptoFactory::instance(NULL);
#else
std::auto_ptr<BotanCryptoFactory> BotanCryptoFactory::instance(NULL);
#endif

#endif

// Display the usage
void usage()
{
	printf("Support tool for PKCS#11\n");
	printf("Usage: softhsm2-util [ACTION] [OPTIONS]\n");
	printf("Action:\n");
	printf("  --delete-token    Delete the token at a given slot.\n");
	printf("                    Use with --token or --serial.\n");
	printf("                    WARNING: Any content in token will be erased.\n");
	printf("  -h                Shows this help screen.\n");
	printf("  --help            Shows this help screen.\n");
	printf("  --import <path>   Import a key pair from the given path.\n");
	printf("                    The file must be in PKCS#8-format.\n");
	printf("                    Use with --slot or --token or --serial, --file-pin,\n");
	printf("                    --label, --id, --no-public-key, and --pin.\n");
	printf("  --init-token      Initialize the token at a given slot.\n");
	printf("                    Use with --slot or --token or --serial or --free,\n");
	printf("                    --label, --so-pin, and --pin.\n");
	printf("                    WARNING: Any content in token will be erased.\n");
	printf("  --show-slots      Display all the available slots.\n");
	printf("  -v                Show version info.\n");
	printf("  --version         Show version info.\n");
	printf("Options:\n");
	printf("  --aes             Used to tell import to use file as is and import it as AES.\n");
	printf("  --file-pin <PIN>  Supply a PIN if the file is encrypted.\n");
	printf("  --force           Used to override a warning.\n");
	printf("  --free            Use the first free/uninitialized token.\n");
	printf("  --id <hex>        Defines the ID of the object. Hexadecimal characters.\n");
	printf("                    Use with --force if multiple key pairs may share\n");
	printf("                    the same ID.\n");
	printf("  --label <text>    Defines the label of the object or the token.\n");
	printf("  --module <path>   Use another PKCS#11 library than SoftHSM.\n");
	printf("  --no-public-key   Do not import the public key.\n");
	printf("  --pin <PIN>       The PIN for the normal user.\n");
	printf("  --serial <number> Will use the token with a matching serial number.\n");
	printf("  --slot <number>   The slot where the token is located.\n");
	printf("  --so-pin <PIN>    The PIN for the Security Officer (SO).\n");
	printf("  --token <label>   Will use the token with a matching token label.\n");
}

// Enumeration of the long options
enum {
	OPT_DELETE_TOKEN = 0x100,
	OPT_FILE_PIN,
	OPT_FORCE,
	OPT_FREE,
	OPT_HELP,
	OPT_ID,
	OPT_IMPORT,
	OPT_INIT_TOKEN,
	OPT_LABEL,
	OPT_MODULE,
	OPT_NO_PUBLIC_KEY,
	OPT_PIN,
	OPT_SERIAL,
	OPT_SHOW_SLOTS,
	OPT_SLOT,
	OPT_SO_PIN,
	OPT_TOKEN,
	OPT_VERSION,
	OPT_AES
};

// Text representation of the long options
static const struct option long_options[] = {
	{ "delete-token",    0, NULL, OPT_DELETE_TOKEN },
	{ "file-pin",        1, NULL, OPT_FILE_PIN },
	{ "force",           0, NULL, OPT_FORCE },
	{ "free",            0, NULL, OPT_FREE },
	{ "help",            0, NULL, OPT_HELP },
	{ "id",              1, NULL, OPT_ID },
	{ "import",          1, NULL, OPT_IMPORT },
	{ "init-token",      0, NULL, OPT_INIT_TOKEN },
	{ "label",           1, NULL, OPT_LABEL },
	{ "module",          1, NULL, OPT_MODULE },
	{ "no-public-key",   0, NULL, OPT_NO_PUBLIC_KEY },
	{ "pin",             1, NULL, OPT_PIN },
	{ "serial",          1, NULL, OPT_SERIAL },
	{ "show-slots",      0, NULL, OPT_SHOW_SLOTS },
	{ "slot",            1, NULL, OPT_SLOT },
	{ "so-pin",          1, NULL, OPT_SO_PIN },
	{ "token",           1, NULL, OPT_TOKEN },
	{ "version",         0, NULL, OPT_VERSION },
	{ "aes",             0, NULL, OPT_AES },
	{ NULL,              0, NULL, 0 }
};

CK_FUNCTION_LIST_PTR p11;

// The main function
int main(int argc, char* argv[])
{
	int option_index = 0;
	int opt;

	char* inPath = NULL;
	char* soPIN = NULL;
	char* userPIN = NULL;
	char* filePIN = NULL;
	char* label = NULL;
	char* module = NULL;
	char* objectID = NULL;
	char* slot = NULL;
	char* serial = NULL;
	char* token = NULL;
	char* errMsg = NULL;
	int forceExec = 0;
	bool freeToken = false;
	int noPublicKey = 0;
	bool importAES = false;

	int doInitToken = 0;
	int doShowSlots = 0;
	int doImport = 0;
	int doDeleteToken = 0;
	int action = 0;
	bool needP11 = false;
	int rv = 0;
	CK_SLOT_ID slotID = 0;

	moduleHandle = NULL;
	p11 = NULL;

	while ((opt = getopt_long(argc, argv, "hv", long_options, &option_index)) != -1)
	{
		switch (opt)
		{
			case OPT_SHOW_SLOTS:
				doShowSlots = 1;
				action++;
				needP11 = true;
				break;
			case OPT_INIT_TOKEN:
				doInitToken = 1;
				action++;
				needP11 = true;
				break;
			case OPT_IMPORT:
				doImport = 1;
				action++;
				inPath = optarg;
				needP11 = true;
				break;
			case OPT_AES:
				importAES = true;
				break;
			case OPT_DELETE_TOKEN:
				doDeleteToken = 1;
				action++;
				break;
			case OPT_SLOT:
				slot = optarg;
				break;
			case OPT_LABEL:
				label = optarg;
				break;
			case OPT_SERIAL:
				serial = optarg;
				break;
			case OPT_TOKEN:
				token = optarg;
				break;
			case OPT_MODULE:
				module = optarg;
				break;
			case OPT_NO_PUBLIC_KEY:
				noPublicKey = 1;
				break;
			case OPT_ID:
				objectID = optarg;
				break;
			case OPT_SO_PIN:
				soPIN = optarg;
				break;
			case OPT_PIN:
				userPIN = optarg;
				break;
			case OPT_FILE_PIN:
				filePIN = optarg;
				break;
			case OPT_FORCE:
				forceExec = 1;
				break;
			case OPT_FREE:
				freeToken = true;
				break;
			case OPT_VERSION:
			case 'v':
				printf("%s\n", PACKAGE_VERSION);
				exit(0);
				break;
			case OPT_HELP:
			case 'h':
			default:
				usage();
				exit(0);
				break;
		}
	}

	// No action given, display the usage.
	if (action != 1)
	{
		usage();
		exit(1);
	}

	if (needP11)
	{
		// Check the basic setup of SoftHSM
		if (!checkSetup())
		{
			fprintf(stderr, "ERROR: Please verify that the SoftHSM configuration is correct.\n");
			exit(1);
		}

		// Get a pointer to the function list for PKCS#11 library
		CK_C_GetFunctionList pGetFunctionList = loadLibrary(module, &moduleHandle, &errMsg);
		if (!pGetFunctionList)
		{
			fprintf(stderr, "ERROR: Could not load the PKCS#11 library/module: %s\n", errMsg);
			fprintf(stderr, "ERROR: Please check log files for additional information.\n");
			exit(1);
		}

		// Load the function list
		(*pGetFunctionList)(&p11);

		// Initialize the library
		CK_RV p11rv = p11->C_Initialize(NULL_PTR);
		if (p11rv != CKR_OK)
		{
			fprintf(stderr, "ERROR: Could not initialize the PKCS#11 library/module: %s\n", module ? module : DEFAULT_PKCS11_LIB);
			fprintf(stderr, "ERROR: Please check log files for additional information.\n");
			exit(1);
		}
	}

	// We should create the token.
	if (doInitToken)
	{
		// Get the slotID
		rv = findSlot(slot, serial, token, freeToken, slotID);
		if (!rv)
		{
			rv = initToken(slotID, label, soPIN, userPIN);
		}
	}

	// Show all available slots
	if (!rv && doShowSlots)
	{
		rv = showSlots();
	}

	// Import a key pair from the given path
	if (!rv && doImport)
	{
		// Get the slotID
		rv = findSlot(slot, serial, token, slotID);
		if (!rv)
		{
			rv = importAES ? importSecretKey(inPath, slotID, userPIN, label, objectID)
					: importKeyPair(inPath, filePIN, slotID, userPIN, label, objectID, forceExec, noPublicKey);
		}
	}

	// We should delete the token.
	if (!rv && doDeleteToken)
	{
		if (deleteToken(serial, token))
		{
			rv = 0;
		}
		else
		{
			rv = 1;
		}
	}

	// Finalize the library
	if (needP11)
	{
		p11->C_Finalize(NULL_PTR);
		unloadLibrary(moduleHandle);
	}

	return rv;
}

// Check the basic setup of SoftHSM
bool checkSetup()
{
	// Initialize the SoftHSM internal functions
	if (!initSoftHSM())
	{
		finalizeSoftHSM();
		return false;
	}

	std::string basedir = Configuration::i()->getString("directories.tokendir", DEFAULT_TOKENDIR);

	// Try open the token directory
	Directory storeDir(basedir);
	if (!storeDir.isValid())
	{
		fprintf(stderr, "ERROR: Failed to enumerate object store in %s\n", basedir.c_str());
		finalizeSoftHSM();
		return false;
	}

	finalizeSoftHSM();
	return true;
}

// Initialize the token
int initToken(CK_SLOT_ID slotID, char* label, char* soPIN, char* userPIN)
{
	char so_pin_copy[MAX_PIN_LEN+1];
	char user_pin_copy[MAX_PIN_LEN+1];

	if (label == NULL)
	{
		fprintf(stderr, "ERROR: A label for the token must be supplied. "
				"Use --label <text>\n");
		return 1;
	}

	if (strlen(label) > 32)
	{
		fprintf(stderr, "ERROR: The token label must not have a length "
				"greater than 32 chars.\n");
		return 1;
	}

	// Get the passwords
	if (getPW(soPIN, so_pin_copy, CKU_SO) != 0)
	{
		fprintf(stderr, "ERROR: Could not get SO PIN\n");
		return 1;
	}
	if (getPW(userPIN, user_pin_copy, CKU_USER) != 0)
	{
		fprintf(stderr, "ERROR: Could not get user PIN\n");
		return 1;
	}

	// Load the variables
	CK_UTF8CHAR paddedLabel[32];
	memset(paddedLabel, ' ', sizeof(paddedLabel));
	memcpy(paddedLabel, label, strlen(label));

	CK_RV rv = p11->C_InitToken(slotID, (CK_UTF8CHAR_PTR)so_pin_copy, strlen(so_pin_copy), paddedLabel);

	switch (rv)
	{
		case CKR_OK:
			break;
		case CKR_SLOT_ID_INVALID:
			fprintf(stderr, "CKR_SLOT_ID_INVALID: Slot %lu does not exist.\n", slotID);
			return 1;
			break;
		case CKR_PIN_INCORRECT:
			fprintf(stderr, "CKR_PIN_INCORRECT: The given SO PIN does not match the "
					"one in the token. Needed when reinitializing the token.\n");
			return 1;
			break;
		case CKR_TOKEN_NOT_PRESENT:
			fprintf(stderr, "CKR_TOKEN_NOT_PRESENT: The token is not present. "
					"Please read the HSM manual for further assistance.\n");
			return 1;
			break;
		default:
			fprintf(stderr, "ERROR rv=0x%08X: Could not initialize the token.\n", (unsigned int)rv);
			fprintf(stderr, "Please check log files for additional information.\n");
			return 1;
			break;
	}

	CK_SESSION_HANDLE hSession;
	rv = p11->C_OpenSession(slotID, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession);
	if (rv != CKR_OK)
	{
		fprintf(stderr, "ERROR: Could not open a session with the library.\n");
		return 1;
	}

	rv = p11->C_Login(hSession, CKU_SO, (CK_UTF8CHAR_PTR)so_pin_copy, strlen(so_pin_copy));
	if (rv != CKR_OK)
	{
		fprintf(stderr, "ERROR: Could not log in on the token.\n");
		return 1;
	}

	rv = p11->C_InitPIN(hSession, (CK_UTF8CHAR_PTR)user_pin_copy, strlen(user_pin_copy));
	if (rv != CKR_OK)
	{
		fprintf(stderr, "ERROR: Could not initialize the user PIN.\n");
		return 1;
	}

	// Get the token info
	CK_TOKEN_INFO tokenInfo;
	rv = p11->C_GetTokenInfo(slotID, &tokenInfo);
	if (rv != CKR_OK)
	{
		fprintf(stderr, "ERROR: Could not get info about the initialized token in slot %lu.\n", slotID);
		return 1;
	}

	// Reload the library
	p11->C_Finalize(NULL_PTR);
	rv = p11->C_Initialize(NULL_PTR);
	if (rv != CKR_OK)
	{
		fprintf(stderr, "ERROR: Could not initialize the library.\n");
		return 1;
	}

	// Get the slotID
	CK_SLOT_ID newSlotID;
	if (findSlot(tokenInfo, newSlotID))
	{
		return 1;
	}

	if (slotID == newSlotID)
	{
		printf("The token has been initialized on slot %lu\n", newSlotID);
	}
	else
	{
		printf("The token has been initialized and is reassigned to slot %lu\n", newSlotID);
	}

	return 0;
}

// Delete the token
bool deleteToken(char* serial, char* token)
{
	if (serial == NULL && token == NULL)
	{
		fprintf(stderr, "ERROR: A token must be supplied. "
				"Use --serial <serial> or --token <label>\n");
		return false;
	}

	// Initialize the SoftHSM internal functions
	if (!initSoftHSM())
	{
		finalizeSoftHSM();
		return false;
	}

	bool rv = true;
	std::string basedir = Configuration::i()->getString("directories.tokendir", DEFAULT_TOKENDIR);
	std::string tokendir;

	rv = findTokenDirectory(basedir, tokendir, serial, token);

	if (rv)
	{
		std::string fulldir = basedir;
		if (fulldir.find_last_of(OS_PATHSEP) != (fulldir.size()-1))
		{
			fulldir += OS_PATHSEP + tokendir;
		}
		else
		{
			fulldir += tokendir;
		}

		rv = rmdir(fulldir);
		if (rv)
		{
			printf("The token (%s) has been deleted.\n", fulldir.c_str());
		}
	}

	finalizeSoftHSM();

	return rv;
}

bool initSoftHSM()
{
	// Not using threading
	MutexFactory::i()->disable();

	// Initiate SecureMemoryRegistry
	if (SecureMemoryRegistry::i() == NULL)
	{
		fprintf(stderr, "ERROR: Could not initiate SecureMemoryRegistry.\n");
		return false;
	}

	// Build the CryptoFactory
	if (CryptoFactory::i() == NULL)
	{
		fprintf(stderr, "ERROR: Could not initiate CryptoFactory.\n");
		return false;
	}

#ifdef WITH_FIPS
	// Check the FIPS status
	if (!CryptoFactory::i()->getFipsSelfTestStatus())
	{
		fprintf(stderr, "ERROR: FIPS self test failed.\n");
		return false;
	}
#endif

	// Load the configuration
	if (!Configuration::i()->reload(SimpleConfigLoader::i()))
	{
		fprintf(stderr, "ERROR: Could not load the SoftHSM configuration.\n");
		return false;
	}

	// Configure the log level
	if (!setLogLevel(Configuration::i()->getString("log.level", DEFAULT_LOG_LEVEL)))
	{
		fprintf(stderr, "ERROR: Could not configure the log level.\n");
		return false;
	}

	// Configure object store storage backend used by all tokens.
	if (!ObjectStoreToken::selectBackend(Configuration::i()->getString("objectstore.backend", DEFAULT_OBJECTSTORE_BACKEND)))
	{
		fprintf(stderr, "ERROR: Could not select token backend.\n");
		return false;
	}

	return true;
}

void finalizeSoftHSM()
{
	CryptoFactory::reset();
	SecureMemoryRegistry::reset();
}

// Find the token directory
bool findTokenDirectory(std::string basedir, std::string& tokendir, char* serial, char* label)
{
	if (serial == NULL && label == NULL)
	{
		return false;
	}

	// Load the variables
	CK_UTF8CHAR paddedSerial[16];
	CK_UTF8CHAR paddedLabel[32];
	if (serial != NULL)
	{
		size_t inSize = strlen(serial);
		size_t outSize = sizeof(paddedSerial);
		if (inSize > outSize)
		{
			fprintf(stderr, "ERROR: --serial is too long.\n");
			return false;
		}
		memset(paddedSerial, ' ', outSize);
		memcpy(paddedSerial, serial, inSize);
	}
	if (label != NULL)
	{
		size_t inSize = strlen(label);
		size_t outSize = sizeof(paddedLabel);
		if (inSize > outSize)
		{
			fprintf(stderr, "ERROR: --token is too long.\n");
			return false;
		}
		memset(paddedLabel, ' ', outSize);
		memcpy(paddedLabel, label, inSize);
	}

	// Find all tokens in the specified path
	Directory storeDir(basedir);

	if (!storeDir.isValid())
	{
		fprintf(stderr, "Failed to enumerate object store in %s\n", basedir.c_str());

		return false;
	}

	// Assume that all subdirectories are tokens
	std::vector<std::string> dirs = storeDir.getSubDirs();

	ByteString tokenLabel;
	ByteString tokenSerial;
	CK_UTF8CHAR paddedTokenSerial[16];
	CK_UTF8CHAR paddedTokenLabel[32];
	size_t counter = 0;
	for (std::vector<std::string>::iterator i = dirs.begin(); i != dirs.end(); i++)
	{
		memset(paddedTokenSerial, ' ', sizeof(paddedTokenSerial));
		memset(paddedTokenLabel, ' ', sizeof(paddedTokenLabel));

		// Create a token instance
		ObjectStoreToken* token = ObjectStoreToken::accessToken(basedir, *i);

		if (!token->isValid())
		{
			delete token;
			continue;
		}

		if (token->getTokenLabel(tokenLabel) && tokenLabel.size() <= sizeof(paddedTokenLabel))
		{
			strncpy((char*) paddedTokenLabel, (char*) tokenLabel.byte_str(), tokenLabel.size());
		}
		if (token->getTokenSerial(tokenSerial) && tokenSerial.size() <= sizeof(paddedTokenSerial))
		{
			strncpy((char*) paddedTokenSerial, (char*) tokenSerial.byte_str(), tokenSerial.size());
		}

		if (serial != NULL && label == NULL &&
			memcmp(paddedTokenSerial, paddedSerial, sizeof(paddedSerial)) == 0)
		{
			printf("Found token (%s) with matching serial.\n", i->c_str());
			tokendir = i->c_str();
			counter++;
		}
		if (serial == NULL && label != NULL &&
			memcmp(paddedTokenLabel, paddedLabel, sizeof(paddedLabel)) == 0)
		{
			printf("Found token (%s) with matching token label.\n", i->c_str());
			tokendir = i->c_str();
			counter++;
		}
		if (serial != NULL && label != NULL &&
			memcmp(paddedTokenSerial, paddedSerial, sizeof(paddedSerial)) == 0 &&
			memcmp(paddedTokenLabel, paddedLabel, sizeof(paddedLabel)) == 0)
		{
			printf("Found token (%s) with matching serial and token label.\n", i->c_str());
			tokendir = i->c_str();
			counter++;
		}

		delete token;
	}

	if (counter == 1) return true;
	if (counter > 1)
	{
		fprintf(stderr, "ERROR: Found multiple matching tokens.\n");
		return false;
	}

	fprintf(stderr, "ERROR: Could not find a token using --serial or --token.\n");
	return false;
}


// Delete a directory
bool rmdir(std::string path)
{
	bool rv = true;

#ifndef _WIN32
	// Enumerate the directory
	DIR* dir = opendir(path.c_str());

	if (dir == NULL)
	{
		fprintf(stderr, "ERROR: Failed to open directory %s\n", path.c_str());
		return false;
	}

	// Enumerate the directory
	struct dirent* entry = NULL;

	while ((entry = readdir(dir)) != NULL)
	{
		bool handled = false;

		// Check if this is the . or .. entry
		if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
		{
			continue;
		}

		// Convert the name of the entry to a C++ string
		std::string name(entry->d_name);
		std::string fullPath = path + OS_PATHSEP + name;

#if defined(_DIRENT_HAVE_D_TYPE) && defined(_BSD_SOURCE)
		// Determine the type of the entry
		switch(entry->d_type)
		{
			case DT_DIR:
				// This is a directory
				rv = rmdir(fullPath);
				handled = true;
				break;
			case DT_REG:
				// This is a regular file
				rv = rm(fullPath);
				handled = true;
				break;
			default:
				break;
		}
#endif

		if (rv == false)
			break;

		if (!handled)
		{
			// The entry type has to be determined using lstat
			struct stat entryStatus;

			if (!lstat(fullPath.c_str(), &entryStatus))
			{
				if (S_ISDIR(entryStatus.st_mode))
				{
					// This is a directory
					rv = rmdir(fullPath);
				}
				else if (S_ISREG(entryStatus.st_mode))
				{
					// This is a regular file
					rv = rm(fullPath);
				}
			}

			if (rv == false)
				break;
		}
	}

	// Close the directory
	closedir(dir);
#else
	// Enumerate the directory
	std::string pattern;
	intptr_t h;
	struct _finddata_t fi;

	if ((path.back() == '/') || (path.back() == '\\'))
		pattern = path + "*";
	else
		pattern = path + "/*";
	memset(&fi, 0, sizeof(fi));
	h = _findfirst(pattern.c_str(), &fi);
	if (h == -1)
	{
		// empty directory
		if (errno == ENOENT)
			goto finished;

		fprintf(stderr, "ERROR: Failed to open directory %s\n", path.c_str());

		return false;
	}

	// scan files & subdirs
	do
	{
		// Check if this is the . or .. entry
		if (!strcmp(fi.name, ".") || !strcmp(fi.name, ".."))
			continue;

		std::string fullPath = path + OS_PATHSEP + fi.name;
		if ((fi.attrib & _A_SUBDIR) == 0)
		{
			// This is a regular file
			rv = rm(fullPath);
		}
		else
		{
			// This is a directory
			rv = rmdir(fullPath);
		}

		memset(&fi, 0, sizeof(fi));

		if (rv == false)
			break;
	} while (_findnext(h, &fi) == 0);

	(void) _findclose(h);

    finished:
#endif

	if (rv == false)
		return false;

	int result;
#ifndef _WIN32
	result = ::rmdir(path.c_str());
#else
	result = _rmdir(path.c_str());
#endif

	if (result != 0)
	{
		fprintf(stderr, "ERROR: Could not delete the directory: %s\n", path.c_str());
		return false;
	}

	return true;
}

// Delete a file
bool rm(std::string path)
{
	int result;

#ifndef _WIN32
	result = ::remove(path.c_str());
#else
	result = _unlink(path.c_str());
#endif

	if (result != 0)
	{
		fprintf(stderr, "ERROR: Could not delete the file: %s\n", path.c_str());
		return false;
	}

	return true;
}

// Show what slots are available
int showSlots()
{
	CK_ULONG ulSlotCount;
	CK_RV rv = p11->C_GetSlotList(CK_FALSE, NULL_PTR, &ulSlotCount);
	if (rv != CKR_OK)
	{
		fprintf(stderr, "ERROR: Could not get the number of slots.\n");
		return 1;
	}

	CK_SLOT_ID_PTR pSlotList = (CK_SLOT_ID_PTR) malloc(ulSlotCount*sizeof(CK_SLOT_ID));
	if (!pSlotList)
	{
		fprintf(stderr, "ERROR: Could not allocate memory.\n");
		return 1;
	}

	rv = p11->C_GetSlotList(CK_FALSE, pSlotList, &ulSlotCount);
	if (rv != CKR_OK)
	{
		fprintf(stderr, "ERROR: Could not get the slot list.\n");
		free(pSlotList);
		return 1;
	}

	printf("Available slots:\n");

	for (CK_ULONG i = 0; i < ulSlotCount; i++)
	{
		CK_SLOT_INFO slotInfo;
		CK_TOKEN_INFO tokenInfo;

		rv = p11->C_GetSlotInfo(pSlotList[i], &slotInfo);
		if (rv != CKR_OK)
		{
			fprintf(stderr, "ERROR: Could not get info about slot %lu.\n", pSlotList[i]);
			continue;
		}

		printf("Slot %lu\n", pSlotList[i]);
		printf("    Slot info:\n");
		printf("        Description:      %.*s\n", 64, slotInfo.slotDescription);
		printf("        Manufacturer ID:  %.*s\n", 32, slotInfo.manufacturerID);
		printf("        Hardware version: %i.%i\n", slotInfo.hardwareVersion.major,
							    slotInfo.hardwareVersion.minor);
		printf("        Firmware version: %i.%i\n", slotInfo.firmwareVersion.major,
							    slotInfo.firmwareVersion.minor);
		printf("        Token present:    ");
		if ((slotInfo.flags & CKF_TOKEN_PRESENT) == 0)
		{
			printf("no\n");
			continue;
		}

		printf("yes\n");
		printf("    Token info:\n");

		rv = p11->C_GetTokenInfo(pSlotList[i], &tokenInfo);
		if (rv != CKR_OK)
		{
			fprintf(stderr, "ERROR: Could not get info about the token in slot %lu.\n",
				pSlotList[i]);
			continue;
		}

		printf("        Manufacturer ID:  %.*s\n", 32, tokenInfo.manufacturerID);
		printf("        Model:            %.*s\n", 16, tokenInfo.model);
		printf("        Hardware version: %i.%i\n", tokenInfo.hardwareVersion.major,
							    tokenInfo.hardwareVersion.minor);
		printf("        Firmware version: %i.%i\n", tokenInfo.firmwareVersion.major,
							    tokenInfo.firmwareVersion.minor);
		printf("        Serial number:    %.*s\n", 16, tokenInfo.serialNumber);
		printf("        Initialized:      ");
		if ((tokenInfo.flags & CKF_TOKEN_INITIALIZED) == 0)
		{
			printf("no\n");
		}
		else
		{
			printf("yes\n");
		}

		printf("        User PIN init.:   ");
		if ((tokenInfo.flags & CKF_USER_PIN_INITIALIZED) == 0)
		{
			printf("no\n");
		}
		else
		{
			printf("yes\n");
		}

		printf("        Label:            %.*s\n", 32, tokenInfo.label);

	}

	free(pSlotList);

	return 0;
}

// Import a key pair from given path
int importKeyPair
(
	char* filePath,
	char* filePIN,
	CK_SLOT_ID slotID,
	char* userPIN,
	char* label,
	char* objectID,
	int forceExec,
	int noPublicKey
)
{
	char user_pin_copy[MAX_PIN_LEN+1];

	if (label == NULL)
	{
		fprintf(stderr, "ERROR: A label for the object must be supplied. "
				"Use --label <text>\n");
		return 1;
	}

	if (objectID == NULL)
	{
		fprintf(stderr, "ERROR: An ID for the object must be supplied. "
				"Use --id <hex>\n");
		return 1;
	}

	size_t objIDLen = 0;
	char* objID = hexStrToBin(objectID, strlen(objectID), &objIDLen);
	if (objID == NULL)
	{
		fprintf(stderr, "Please edit --id <hex> to correct error.\n");
		return 1;
	}

	CK_SESSION_HANDLE hSession;
	CK_RV rv = p11->C_OpenSession(slotID, CKF_SERIAL_SESSION | CKF_RW_SESSION,
					NULL_PTR, NULL_PTR, &hSession);
	if (rv != CKR_OK)
	{
		if (rv == CKR_SLOT_ID_INVALID)
		{
			fprintf(stderr, "ERROR: The given slot does not exist.\n");
		}
		else
		{
			fprintf(stderr, "ERROR: Could not open a session on the given slot.\n");
		}
		free(objID);
		return 1;
	}

	// Get the password
	if (getPW(userPIN, user_pin_copy, CKU_USER) != 0)
	{
		fprintf(stderr, "ERROR: Could not get user PIN\n");
		free(objID);
		return 1;
	}

	rv = p11->C_Login(hSession, CKU_USER, (CK_UTF8CHAR_PTR)user_pin_copy, strlen(user_pin_copy));
	if (rv != CKR_OK)
	{
		if (rv == CKR_PIN_INCORRECT) {
			fprintf(stderr, "ERROR: The given user PIN does not match the one in the token.\n");
		}
		else
		{
			fprintf(stderr, "ERROR: Could not log in on the token.\n");
		}
		free(objID);
		return 1;
	}

	CK_OBJECT_HANDLE oHandle = searchObject(hSession, objID, objIDLen);
	if (oHandle != CK_INVALID_HANDLE && forceExec == 0)
	{
		free(objID);
		fprintf(stderr, "ERROR: The ID is already assigned to another object. "
				"Use --force to override this message.\n");
		return 1;
	}

	crypto_init();
	int result = crypto_import_key_pair(hSession, filePath, filePIN, label, objID, objIDLen, noPublicKey);
	crypto_final();

	free(objID);

	return result;
}

// Import a secret key from given path
int importSecretKey(char* filePath, CK_SLOT_ID slotID, char* userPIN, char* label, char* objectID)
{
	char user_pin_copy[MAX_PIN_LEN+1];

	if (label == NULL)
	{
		fprintf(stderr, "ERROR: A label for the object must be supplied. "
				"Use --label <text>\n");
		return 1;
	}

	if (objectID == NULL)
	{
		fprintf(stderr, "ERROR: An ID for the object must be supplied. "
				"Use --id <hex>\n");
		return 1;
	}

	size_t objIDLen = 0;
	char* objID = hexStrToBin(objectID, strlen(objectID), &objIDLen);
	if (objID == NULL)
	{
		fprintf(stderr, "Please edit --id <hex> to correct error.\n");
		return 1;
	}

	// Get the password
	if (getPW(userPIN, user_pin_copy, CKU_USER) != 0)
	{
		fprintf(stderr, "ERROR: Could not get user PIN\n");
		return 1;
	}

	CK_SESSION_HANDLE hSession;
	CK_RV rv = p11->C_OpenSession(slotID, CKF_SERIAL_SESSION | CKF_RW_SESSION,
					NULL_PTR, NULL_PTR, &hSession);
	if (rv != CKR_OK)
	{
		if (rv == CKR_SLOT_ID_INVALID)
		{
			fprintf(stderr, "ERROR: The given slot does not exist.\n");
		}
		else
		{
			fprintf(stderr, "ERROR: Could not open a session on the given slot.\n");
		}
		return 1;
	}

	rv = p11->C_Login(hSession, CKU_USER, (CK_UTF8CHAR_PTR)user_pin_copy, strlen(user_pin_copy));
	if (rv != CKR_OK)
	{
		if (rv == CKR_PIN_INCORRECT) {
			fprintf(stderr, "ERROR: The given user PIN does not match the one in the token.\n");
		}
		else
		{
			fprintf(stderr, "ERROR: Could not log in on the token.\n");
		}
		return 1;
	}

	crypto_init();
	int result = crypto_import_aes_key(hSession, filePath, label, objID, objIDLen);
	crypto_final();

	return result;
}

// Convert a char array of hexadecimal characters into a binary representation
char* hexStrToBin(char* objectID, int idLength, size_t* newLen)
{
	char* bytes = NULL;

	if (idLength < 2 || idLength % 2 != 0)
	{
		fprintf(stderr, "ERROR: Invalid length on hex string.\n");
		return NULL;
	}

	for (int i = 0; i < idLength; i++)
	{
		if (hexdigit_to_int(objectID[i]) == -1)
		{
			fprintf(stderr, "ERROR: Invalid character in hex string.\n");
			return NULL;
		}
	}

	*newLen = idLength / 2;
	bytes = (char*) malloc(*newLen);
	if (bytes == NULL)
	{
		fprintf(stderr, "ERROR: Could not allocate memory.\n");
		return NULL;
	}

	for (size_t i = 0; i < *newLen; i++)
	{
		bytes[i] = hexdigit_to_int(objectID[2*i]) * 16 +
				hexdigit_to_int(objectID[2*i+1]);
	}

	return bytes;
}

// Return the integer value of a hexadecimal character
int hexdigit_to_int(char ch)
{
	switch (ch)
	{
		case '0':
			return 0;
		case '1':
			return 1;
		case '2':
			return 2;
		case '3':
			return 3;
		case '4':
			return 4;
		case '5':
			return 5;
		case '6':
			return 6;
		case '7':
			return 7;
		case '8':
			return 8;
		case '9':
			return 9;
		case 'a':
		case 'A':
			return 10;
		case 'b':
		case 'B':
			return 11;
		case 'c':
		case 'C':
			return 12;
		case 'd':
		case 'D':
			return 13;
		case 'e':
		case 'E':
			return 14;
		case 'f':
		case 'F':
			return 15;
		default:
			return -1;
	}
}

// Search for an object
CK_OBJECT_HANDLE searchObject(CK_SESSION_HANDLE hSession, char* objID, size_t objIDLen)
{
	if (objID == NULL)
	{
		return CK_INVALID_HANDLE;
	}

	CK_OBJECT_CLASS oClass = CKO_PRIVATE_KEY;
	CK_OBJECT_HANDLE hObject = CK_INVALID_HANDLE;
	CK_ULONG objectCount = 0;

	CK_ATTRIBUTE objTemplate[] = {
		{ CKA_CLASS, &oClass, sizeof(oClass) },
		{ CKA_ID,    objID,   objIDLen }
	};

	CK_RV rv = p11->C_FindObjectsInit(hSession, objTemplate, 2);
	if (rv != CKR_OK)
	{
		fprintf(stderr, "ERROR: Could not prepare the object search.\n");
		return CK_INVALID_HANDLE;
	}

	rv = p11->C_FindObjects(hSession, &hObject, 1, &objectCount);
	if (rv != CKR_OK)
	{
		fprintf(stderr, "ERROR: Could not get the search results.\n");
		return CK_INVALID_HANDLE;
	}

	rv = p11->C_FindObjectsFinal(hSession);
	if (rv != CKR_OK)
	{
		fprintf(stderr, "ERROR: Could not finalize the search.\n");
		return CK_INVALID_HANDLE;
	}

	if (objectCount == 0)
	{
		return CK_INVALID_HANDLE;
	}

	return hObject;
}