summaryrefslogtreecommitdiff
path: root/src/windows/csp/State.cpp
blob: eba3e9a6a9234fb341b6a719a3877c26eb1d0ab4 (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
/** BEGIN COPYRIGHT BLOCK
* This Program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; version 2 of the License.
*
* This Program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this Program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA.
*
* Copyright (C) 2003-2004 Identity Alliance

* All rights reserved.
* END COPYRIGHT BLOCK **/

/*****************************************************************
/
/ File   :   State.cpp
/ Date   :   December 3, 2002
/ Purpose:   Crypto API CSP->PKCS#11 Module
/ License:   Copyright (C) 2003-2004 Identity Alliance
/
******************************************************************/

#include "csp.h"
#include "State.h"
#include <winscard.h>

using namespace std;

namespace MCSP {

State::State()
   : init_(false), logging_(false), logFilename_("C:\\CSPDEBUG.log"), slot_(0), keyGenHack_(false), pkcs11dllname_("PKCS11.dll")
{
   lock_ = ::CreateMutex(NULL, FALSE, NULL); 

   HKEY hKey = NULL;

   if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                    TEXT("SOFTWARE\\Microsoft\\Cryptography\\Defaults\\Provider\\"PROVIDER_NAME),
                    0,
                    KEY_READ,
                    &hKey) == ERROR_SUCCESS)
   {
      DWORD value = 0;
      DWORD size = sizeof(value);
      
      if (RegQueryValueEx(hKey, TEXT("Logging"), 0, 0, (LPBYTE)&value, &size) == ERROR_SUCCESS)
      {
         if (value)
            logging(true);
      }

      size = 0;
      if (RegQueryValueEx(hKey, TEXT("LogFilename"), 0, 0, 0, &size) == ERROR_SUCCESS)
      {
         LOG("LogFilename size is: %u\n", size);
         std::string value;
         value.resize(size);

         if (RegQueryValueEx(hKey, TEXT("LogFilename"), 0, 0, (LPBYTE)&value[0], &size) == ERROR_SUCCESS)
         {
            // Remove trailing null
            value.resize(value.size() - 1);
            logFilename_ = value;
         }
         LOG("LogFilename value is: %s\n", &value[0]);
      }

      size = sizeof(value);
      if (RegQueryValueEx(hKey, TEXT("KeyGenHack"), 0, 0, (LPBYTE)&value, &size) == ERROR_SUCCESS)
      {
         if (value)
            keyGenHack(true);
      }

      if (RegQueryValueEx(hKey, TEXT("PKCS11Module"), 0, 0, 0, &size) == ERROR_SUCCESS)
      {
         LOG("PKCS11Module size is: %u\n", size);
         std::string value;
         value.resize(size);

         if (RegQueryValueEx(hKey, TEXT("PKCS11Module"), 0, 0, (LPBYTE)&value[0], &size) == ERROR_SUCCESS)
         {
            // Remove trailing null
            value.resize(value.size() - 1);
            pkcs11dllname_ = value;
         }
         LOG("PKCS11Module value is: %s\n", &value[0]);
      }

      RegCloseKey(hKey);
   }
}

State::~State()
{
   shutdown();
   ::CloseHandle(lock_);
}

bool State::sessionExists(Session* session)
{
   bool rv = false;

   lock();
   set<Session*>::iterator itr = sessions_.find(session);
   if (itr != sessions_.end())
      rv = true;

   unlock();
   return rv;
}

void State::removeSession(Session* session)
{
   lock();
   sessions_.erase(session); 
   delete session; 

   if (sessions_.empty()) 
      shutdown();
   unlock();
}

Session* State::checkValidSession(HCRYPTPROV hProv)
{
   //LOG("Checking 0x%X as a valid session handle\n", hProv);

   if (!sessionExists(reinterpret_cast<Session*>(hProv)))
      Throw(NTE_BAD_UID);

   return reinterpret_cast<Session*>(hProv);
}

bool State::keyExists(Key* key)
{
   bool rv = false;

   lock();
   set<Key*>::iterator itr = keys_.find(key);
   if (itr != keys_.end())
      rv = true;

   unlock();
   return rv;
}

Key* State::checkValidKey(HCRYPTKEY hKey)
{
   //LOG("Checking 0x%X as a valid key handle\n", hKey);

   if (!keyExists(reinterpret_cast<Key*>(hKey)))
      Throw(NTE_BAD_UID);

   return reinterpret_cast<Key*>(hKey);
}

bool State::shutdown()
{
   if (init())
   {
      lock();

      LOG("Shutting down CSP\n");
      
      { 
         set<Session*>::iterator itr = sessions_.begin();
         for (; itr != sessions_.end(); itr++)
            delete *itr;

         sessions_.clear();
      }

      {
         set<Key*>::iterator itr = keys_.begin();
         for (; itr != keys_.end(); itr++)
         {
            LOG("Destroying key: 0x%X\n", *itr);
            delete *itr;
         }

         keys_.clear();
      }

      g_state.p11->C_Finalize(0);
      init(false);

      unlock();
   }

   return true;
}

bool State::initP11(const BinStr& reader_name0, DWORD dwFlags)
{
   bool rv = true;
   CK_RV ck_rv;
   CK_SLOT_ID slot = 0;
   BinStr reader_name = reader_name0; // We may need to modify the value
   bool silent = false;

   lock();

   if ((dwFlags & CRYPT_SILENT) || (dwFlags & CRYPT_VERIFYCONTEXT))
      silent = true;

   try
   {
      HMODULE p11lib = LoadLibrary(pkcs11dllname_.c_str());
      if (p11lib == NULL)
      {
         LOG("Failed to load PKCS11 library \"%s\"\n", pkcs11dllname_.c_str());
         SetLastError(NTE_FAIL);
         throw(false);
      }

      CK_RV (*getfunc)(CK_FUNCTION_LIST_PTR_PTR ppFunctionList);
      getfunc = (CK_RV (*)(CK_FUNCTION_LIST_PTR_PTR ppFunctionList))GetProcAddress(p11lib, "C_GetFunctionList");
      if (getfunc == NULL)
      {
         LOG("Failed to find C_GetFunctionList\n");
         SetLastError(NTE_FAIL);
         throw(false);
      }

      CK_RV rv = getfunc(&p11);
      if (rv != CKR_OK)
      {
         LOG("Failed to get PKCS11 function list\n");
         SetLastError(NTE_FAIL);
         throw(false);
      }

      ck_rv = p11->C_Initialize(0); 

      LOG("C_Initialize: 0x%X\n", ck_rv);
      if (ck_rv != CKR_OK && ck_rv != CKR_CRYPTOKI_ALREADY_INITIALIZED)
      {
         LOG("C_Initialize() failed: 0x%X (%u)\n", ck_rv, ck_rv);
         SetLastError(NTE_FAIL);
         throw(false);
      }

      CK_ULONG ulSlotCount;
      if (p11->C_GetSlotList(FALSE, 0, &ulSlotCount) != CKR_OK)
      {
         LOG("C_GetSlotList() failed\n");
         SetLastError(NTE_FAIL);
         throw(false);
      }

      LOG("There are %d slots on this machine\n", ulSlotCount);

      if (ulSlotCount < 1)
      {
         LOG("No slots detected\n");
         SetLastError(NTE_FAIL);
         throw(false);
      }

      vector<CK_SLOT_ID> slotList(ulSlotCount);

      if (p11->C_GetSlotList(FALSE, &slotList[0], &ulSlotCount) != CKR_OK)
      {
         LOG("C_GetSlotList() failed (second call)\n");
         SetLastError(NTE_FAIL);
         throw(false);
      }

      CK_SLOT_INFO slotInfo;
      BinStr current_reader;
      vector<CK_SLOT_ID>::iterator itr;
      bool found_slot = false;

      // FIXME: Look for the specified reader or if not specified then
      //        the first reader with a card present.  Should probably
      //        search for first valid token and use MS smartcard select
      //        dialog.
      while (!found_slot)
      {
         LOG("Looking for a valid token\n");

         CK_ULONG token_count = 0;
         itr = slotList.begin();
         for (; itr != slotList.end(); itr++)
         {
            p11->C_GetSlotInfo(*itr, &slotInfo);

            CK_TOKEN_INFO tokenInfo;
            CK_RV ck_rv = p11->C_GetTokenInfo(*itr, &tokenInfo);

            // Chop off trailing spaces in P11 slot name
            current_reader.assign(slotInfo.slotDescription, sizeof(slotInfo.slotDescription));
            while (current_reader[current_reader.size()-1] == 0x20)
               current_reader.resize(current_reader.size() - 1);
            current_reader.push_back(0);

            LOG("Slot %d: %s (looking for reader: %s)\n", *itr, &current_reader[0], reader_name.empty() ? "" : (char*)&reader_name[0]);

            if (!(slotInfo.flags & CKF_TOKEN_PRESENT))
            {
               LOG("^^^^^ (No card present)\n");

               if (reader_name == current_reader)
                  break;
            }
            else
            {
               string infoString((char*)tokenInfo.label, sizeof(tokenInfo.label));
               LOG("^^^^^ (%s)\n", infoString.c_str());

               token_count++;

               if (reader_name.empty())
               {
                  // If multiple tokens, ask user
                  if (token_count > 1 && !silent)
                     break;

                  found_slot = true;
                  slot = *itr;
               }
               else if (reader_name == current_reader)
               {
                  found_slot = true;
                  slot = *itr;
                  break;
               }
            }
         }

         if (token_count > 1 && !silent)
         {
            SCARDCONTEXT hSC;
            OPENCARDNAME_EX dlgStruct;
            char szReader[256];
            char szCard[256];

            if (SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &hSC) != SCARD_S_SUCCESS)
            {
               LOG("Failed SCardEstablishContext\n");
               SetLastError(NTE_FAIL);
               throw(false);
            }

            memset(&dlgStruct, 0, sizeof(dlgStruct));
            dlgStruct.dwStructSize = sizeof(dlgStruct);
            dlgStruct.hSCardContext = hSC;
            dlgStruct.dwFlags = SC_DLG_FORCE_UI;
            dlgStruct.lpstrRdr = szReader;
            dlgStruct.nMaxRdr = 256;
            dlgStruct.lpstrCard = szCard;
            dlgStruct.nMaxCard = 256;
            //dlgStruct.lpstrTitle = "Select Card:";

            // FIXME: Will this work during login?
            if (SCardUIDlgSelectCard(&dlgStruct) != SCARD_S_SUCCESS)
            {
               SCardReleaseContext(hSC);
               LOG("Failed SCardUIDlgSelectCard\n");
               SetLastError(NTE_FAIL);
               throw(false);
            }
            else
            {
               SCardReleaseContext(hSC);
               LOG("User selected reader: %s card: %s\n", szReader, szCard);
               reader_name = (char*)szReader;
               slot = 0;
               continue; // This will restart the search loop to find the selected reader
            }
         }

         if (!found_slot)
         {
            if (silent)
            {
               LOG("ERROR: Can't find a card in any reader and silent mode is set");
               SetLastError(NTE_FAIL);
               throw(false);
            }

            // FIXME: will this work during login?
            int result = MessageBox(NULL, "Please insert a supported smartcard",
               "Insert Card", MB_ICONEXCLAMATION | MB_RETRYCANCEL);

            if (result == IDCANCEL)
            {
               SetLastError(NTE_FAIL);
               throw(false);
            }
         }
      }

      LOG("Using slot %d\n", slot);

      g_state.slot(slot);
   }
   catch (bool rv0)
   {
      rv = rv0;
   }

   unlock();

   return rv;
}

} // namespace MCSP