-
Notifications
You must be signed in to change notification settings - Fork 1
/
CardService.cpp
355 lines (300 loc) · 9.94 KB
/
CardService.cpp
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
/*
* esteid-browser-plugin - a browser plugin for Estonian EID card
*
* Copyright (C) 2010 Estonian Informatics Centre
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "CardService.h"
#include "converter.h"
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <smartcardpp/PCSCManager.h>
using namespace Converter;
/* Singleton instance variable */
boost::weak_ptr<CardService> CardService::sCardService;
/**
* Class constructor.
* Right now we are making this a singleton.
* It's generally a good idea to have only a single connection
* to SmartCard manager service.
* We might reconsider when times change :P
*/
CardService::CardService()
: m_thread(boost::bind(&CardService::monitor, this))
{
}
CardService::~CardService()
{
m_thread.interrupt();
m_thread.join();
m_signThread.join();
}
/**
* Singleton "constructor". Will return an existing instance
* or create a new one if none exists.
*/
boost::shared_ptr<CardService> CardService::getInstance()
{
boost::shared_ptr<CardService> p = sCardService.lock();
if (!p) {
p.reset(new CardService());
sCardService = p;
}
return p;
}
void CardService::findEstEid(vector<ReaderID>& readers)
{
boost::mutex::scoped_lock l(m_cardMutex);
readers.clear();
for (ReaderID i = 0; i < m_cache.size(); i++ ) {
if (m_cache[i].cardPresent)
readers.push_back(i);
}
}
ReaderID CardService::findFirstEstEid()
{
vector<ReaderID> readers;
findEstEid(readers);
// FIXME: Define a more sane exception to throw from here
if (readers.size() <= 0)
throw std::runtime_error("No cards found");
else
return readers[0];
}
/* Card monitor thread */
void CardService::monitor()
{
while (!boost::this_thread::interruption_requested()) {
try {
poll();
} catch(const std::runtime_error&) { }
boost::this_thread::sleep(boost::posix_time::milliseconds(500));
}
}
/*
* PCSCManager constructor throws if the pcsc daemon isn't running.
* CardService class however needs to start polling even if the pcsc daemon
* isn't currently running. As a workaround, all calls to PCSCManager are
* proxied through cardManager() which attempts to start PCSCManager if
* needed.
*/
ManagerInterface& CardService::cardManager()
{
if (!m_manager)
m_manager.reset(new PCSCManager());
return *m_manager;
}
void CardService::addObserver(MessageObserver *obs)
{
boost::mutex::scoped_lock l(m_messageMutex);
m_observers.push_back(obs);
}
void CardService::removeObserver(MessageObserver *obs)
{
boost::mutex::scoped_lock l(m_messageMutex);
vector<MessageObserver *>::iterator i;
for (i = m_observers.begin(); i != m_observers.end(); i++) {
if (*i == obs) {
m_observers.erase(i);
break;
}
}
}
void CardService::postMessage(MsgType m, ReaderID r)
{
boost::mutex::scoped_lock l(m_messageMutex);
vector<MessageObserver *>::iterator i;
for (i = m_observers.begin(); i != m_observers.end(); i++)
(*i)->onMessage(m, r);
}
void CardService::poll()
{
boost::mutex::scoped_lock l(m_cardMutex);
/* See if the list of readers has been changed */
size_t nReaders = cardManager().getReaderCount();
if (m_cache.size() != nReaders) {
/* We have no way of knowing which reader was
removed, so it's safe to send card removed event to
all readers and purge all cached data */
for (unsigned int i = 0; i < m_cache.size(); i++ ) {
if (m_cache[i].cardPresent) {
m_cache[i].purge();
postMessage(CARD_REMOVED, i);
}
}
m_cache.resize(nReaders);
postMessage(READERS_CHANGED, nReaders);
}
/* Check for card status changes */
EstEidCard card(cardManager());
for (unsigned int i = 0; i < m_cache.size(); i++ ) {
bool inReader = readerHasCard(card, i);
if (inReader && !m_cache[i].cardPresent) {
m_cache[i].cardPresent = true;
postMessage(CARD_INSERTED, i);
} else if (!inReader && m_cache[i].cardPresent) {
m_cache[i].purge();
postMessage(CARD_REMOVED, i);
}
}
}
bool CardService::readerHasCard(EstEidCard& card, ReaderID i)
{
/* Ask manager if a token is inserted into that slot */
std::string state = cardManager().getReaderState(i);
if (state.find("PRESENT") == std::string::npos)
return false;
/* TODO: Investigate if this caching is actually needed */
if (m_cache[i].cardPresent)
return true;
/* See if it's EstEID */
return card.isInReader(i);
}
void CardService::readPersonalData(vector<std::string>& data)
{
readPersonalData(data, findFirstEstEid());
}
void CardService::readPersonalData(vector<std::string>& data,
ReaderID reader)
{
boost::mutex::scoped_lock l(m_cardMutex);
/* Populate cache if needed */
if (m_cache[reader].m_pData.size() <= 0) {
EstEidCard card(cardManager(), reader);
card.readPersonalData(m_cache[reader].m_pData, PDATA_MIN, PDATA_MAX);
}
data = m_cache[reader].m_pData;
}
ByteVec CardService::getAuthCert()
{
return getAuthCert(findFirstEstEid());
}
ByteVec CardService::getAuthCert(ReaderID reader)
{
boost::mutex::scoped_lock l(m_cardMutex);
/* Populate cache if needed */
if (m_cache[reader].m_authCert.size() <= 0) {
EstEidCard card(cardManager(), reader);
m_cache[reader].m_authCert = card.getAuthCert();
}
return m_cache[reader].m_authCert;
}
ByteVec CardService::getSignCert()
{
return getSignCert(findFirstEstEid());
}
ByteVec CardService::getSignCert(ReaderID reader)
{
boost::mutex::scoped_lock l(m_cardMutex);
/* Populate cache if needed */
if (m_cache[reader].m_signCert.size() <= 0) {
EstEidCard card(cardManager(), reader);
m_cache[reader].m_signCert = card.getSignCert();
}
return m_cache[reader].m_signCert;
}
std::string CardService::signSHA1(const std::string& hash,
EstEidCard::KeyType keyId,
const std::string& pin)
{
return signSHA1(hash, keyId, pin, findFirstEstEid());
}
std::string CardService::signSHA1(const std::string& hash,
EstEidCard::KeyType keyId,
const std::string& pin,
ReaderID reader)
{
ByteVec bhash = hex_to_bytes(hash);
if (bhash.size() != 20) {
throw std::runtime_error("Invalid SHA1 hash");
}
boost::mutex::scoped_lock l(m_cardMutex);
EstEidCard card(cardManager(), reader);
// FIXME: Ugly, ugly hack! This needs to be implemented correctly
// in order to protect PIN codes in program memory.
return bytes_to_hex(card.calcSignSHA1(bhash, keyId, PinString(pin.c_str())));
}
void CardService::setSignCompletedCallback(SignCompletedFunc f)
{
signCompletedFunc = f;
}
void CardService::setSignFailedCallback(SignFailedFunc f)
{
signFailedFunc = f;
}
SignError CardService::decodeAuthError(const AuthError& e)
{
SignError ret;
if (e.m_blocked)
ret = SIGN_ERROR_BLOCKED;
else if (e.m_aborted)
ret = SIGN_ERROR_ABORTED;
else
ret = SIGN_ERROR_WRONG_PIN;
return ret;
}
void CardService::runSignSHA1(const std::string& hash,
EstEidCard::KeyType keyId,
const std::string& pin,
ReaderID reader)
{
try {
boost::mutex::scoped_lock l(m_cardMutex);
boost::scoped_ptr<ManagerInterface> manager(new PCSCManager());
EstEidCard card(*manager, reader);
std::string ret = bytes_to_hex(card.calcSignSHA1(hex_to_bytes(hash), keyId, PinString(pin.c_str())));
signCompletedFunc(ret);
} catch(const AuthError& e) {
signFailedFunc(decodeAuthError(e), e.what());
} catch (const std::exception& e) {
signFailedFunc(SIGN_ERROR_CARD_ERROR, e.what());
}
}
void CardService::signSHA1Async(const std::string& hash,
EstEidCard::KeyType keyId,
const std::string& pin)
{
signSHA1Async(hash, keyId, pin, findFirstEstEid());
}
void CardService::signSHA1Async(const std::string& hash,
EstEidCard::KeyType keyId,
const std::string& pin,
ReaderID reader)
{
// Run signing operation in a thread
m_signThread = boost::thread(boost::bind(&CardService::runSignSHA1, this, hash, keyId, pin, reader));
}
bool CardService::getRetryCounts(byte& puk, byte& pinAuth, byte& pinSign)
{
return getRetryCounts(puk, pinAuth, pinSign, findFirstEstEid());
}
bool CardService::getRetryCounts(byte& puk, byte& pinAuth, byte& pinSign, ReaderID reader)
{
boost::mutex::scoped_lock l(m_cardMutex);
EstEidCard card(cardManager(), reader);
return card.getRetryCounts(puk, pinAuth, pinSign);
}
bool CardService::hasSecurePinEntry()
{
return hasSecurePinEntry(findFirstEstEid());
}
bool CardService::hasSecurePinEntry(ReaderID reader)
{
boost::mutex::scoped_lock l(m_cardMutex);
EstEidCard card(cardManager(), reader);
return card.hasSecurePinEntry();
}