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
|
/*
* Copyright (c) 2015, NORDUnet A/S.
* See LICENSE for licensing information.
*/
#include <stdio.h>
#include <err.h>
#include <stdlib.h>
#include <string.h>
#include "hsmhelper.h"
#include "erlport.h"
static long
parseslot(char *slotstring)
{
char *endptr = NULL;
if (slotstring[0] == '\0') {
errx(1, "no slot given");
}
long slot = strtol(slotstring, &endptr, 10);
if (endptr[0] != '\0') {
errx(1, "not a valid slot number: %s", slotstring);
}
return slot;
}
static void
loop(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey,
CK_MECHANISM_TYPE mechanism)
{
unsigned char buf[10000];
unsigned char signature[2048];
ssize_t len;
while ((len = read_command(buf, sizeof(buf), 4)) > 0) {
unsigned long signatureLen = sizeof(signature);
sign(hSession, hKey, buf, len, signature, &signatureLen, mechanism);
write_reply(signature, signatureLen, 4);
}
}
#define MAX_PIN_SIZE 1000
char *
read_pin(char *filename)
{
FILE *pin_file;
char *result;
pin_file = fopen(filename, "r");
if (pin_file == NULL) {
return NULL;
}
char *pin = malloc(MAX_PIN_SIZE);
result = fgets(pin, MAX_PIN_SIZE, pin_file);
if (result == NULL) {
free(pin);
fclose(pin_file);
return NULL;
}
size_t newlinepos = strcspn(result, "\r\n");
pin[newlinepos] = '\0';
fclose(pin_file);
return pin;
}
int
main(int argc, char *argv[])
{
if (argc < 6) {
errx(1, "usage: %s <pkcs11library> <slot> rsa|ecdsa <keyname> <pin>", argv[0]);
}
char *library_path = argv[1];
char *slotstring = argv[2];
char *keytype = argv[3];
char *keyname = argv[4];
char *pin_or_file = argv[5];
char *pin;
if (pin_or_file[0] == '@') {
pin = read_pin(pin_or_file + 1);
} else {
pin = strdup(pin_or_file);
}
if (pin == NULL) {
errx(1, "Could not read pin");
}
init(library_path);
long slot = parseslot(slotstring);
CK_MECHANISM_TYPE mechanism;
if (strcmp(keytype, "ecdsa") == 0) {
mechanism = CKM_ECDSA;
} else if (strcmp(keytype, "rsa") == 0) {
mechanism = CKM_SHA256_RSA_PKCS;
} else {
errx(1, "invalid key type: %s", keytype);
}
CK_SESSION_HANDLE hSession = open_session(slot);
login(hSession, pin);
CK_OBJECT_HANDLE hKey = find_key(hSession, CKO_PRIVATE_KEY, keyname);
loop(hSession, hKey, mechanism);
free(pin);
return 0;
}
|