winmm: dwBytesRecorded controls how much is played, not dwBufferLength.
[wine/hramrach.git] / dlls / cryptui / main.c
bloba95a7a487d3e38dec39d483ad7052e38ef723b33
1 /*
2 * Copyright 2008 Juan Lang
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 #include "config.h"
21 #include <stdarg.h>
23 #define COBJMACROS
24 #define NONAMELESSUNION
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winnls.h"
29 #include "winuser.h"
30 #include "softpub.h"
31 #include "wingdi.h"
32 #include "richedit.h"
33 #include "ole2.h"
34 #include "richole.h"
35 #include "commdlg.h"
36 #include "commctrl.h"
37 #include "cryptuiapi.h"
38 #include "cryptuires.h"
39 #include "urlmon.h"
40 #include "hlink.h"
41 #include "winreg.h"
42 #include "wine/debug.h"
43 #include "wine/unicode.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(cryptui);
47 static HINSTANCE hInstance;
49 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
51 TRACE("(0x%p, %d, %p)\n", hinstDLL, fdwReason, lpvReserved);
53 switch (fdwReason)
55 case DLL_WINE_PREATTACH:
56 return FALSE; /* prefer native version */
57 case DLL_PROCESS_ATTACH:
58 hInstance = hinstDLL;
59 DisableThreadLibraryCalls(hinstDLL);
60 break;
61 case DLL_PROCESS_DETACH:
62 break;
63 default:
64 break;
66 return TRUE;
69 #define MAX_STRING_LEN 512
71 static void add_cert_columns(HWND hwnd)
73 HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
74 RECT rc;
75 WCHAR buf[MAX_STRING_LEN];
76 LVCOLUMNW column;
78 SendMessageW(lv, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT);
79 GetWindowRect(lv, &rc);
80 LoadStringW(hInstance, IDS_SUBJECT_COLUMN, buf,
81 sizeof(buf) / sizeof(buf[0]));
82 column.mask = LVCF_WIDTH | LVCF_TEXT;
83 column.cx = (rc.right - rc.left) * 29 / 100 - 2;
84 column.pszText = buf;
85 SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
86 LoadStringW(hInstance, IDS_ISSUER_COLUMN, buf,
87 sizeof(buf) / sizeof(buf[0]));
88 SendMessageW(lv, LVM_INSERTCOLUMNW, 1, (LPARAM)&column);
89 column.cx = (rc.right - rc.left) * 16 / 100 - 2;
90 LoadStringW(hInstance, IDS_EXPIRATION_COLUMN, buf,
91 sizeof(buf) / sizeof(buf[0]));
92 SendMessageW(lv, LVM_INSERTCOLUMNW, 2, (LPARAM)&column);
93 column.cx = (rc.right - rc.left) * 23 / 100 - 1;
94 LoadStringW(hInstance, IDS_FRIENDLY_NAME_COLUMN, buf,
95 sizeof(buf) / sizeof(buf[0]));
96 SendMessageW(lv, LVM_INSERTCOLUMNW, 3, (LPARAM)&column);
99 static void add_cert_to_view(HWND lv, PCCERT_CONTEXT cert, DWORD *allocatedLen,
100 LPWSTR *str)
102 DWORD len;
103 LVITEMW item;
104 WCHAR dateFmt[80]; /* sufficient for LOCALE_SSHORTDATE */
105 WCHAR date[80];
106 SYSTEMTIME sysTime;
107 LPWSTR none;
109 item.mask = LVIF_IMAGE | LVIF_PARAM | LVIF_TEXT;
110 item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
111 item.iSubItem = 0;
112 item.iImage = 0;
113 item.lParam = (LPARAM)CertDuplicateCertificateContext(cert);
114 len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
115 NULL, 0);
116 if (len > *allocatedLen)
118 HeapFree(GetProcessHeap(), 0, *str);
119 *str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
120 if (*str)
121 *allocatedLen = len;
123 if (*str)
125 CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
126 *str, len);
127 item.pszText = *str;
128 SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
131 item.mask = LVIF_TEXT;
132 len = CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
133 CERT_NAME_ISSUER_FLAG, NULL, NULL, 0);
134 if (len > *allocatedLen)
136 HeapFree(GetProcessHeap(), 0, *str);
137 *str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
138 if (*str)
139 *allocatedLen = len;
141 if (*str)
143 CertGetNameStringW(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
144 CERT_NAME_ISSUER_FLAG, NULL, *str, len);
145 item.pszText = *str;
146 item.iSubItem = 1;
147 SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
150 GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, dateFmt,
151 sizeof(dateFmt) / sizeof(dateFmt[0]));
152 FileTimeToSystemTime(&cert->pCertInfo->NotAfter, &sysTime);
153 GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, date,
154 sizeof(date) / sizeof(date[0]));
155 item.pszText = date;
156 item.iSubItem = 2;
157 SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
159 if (!CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID,
160 NULL, &len))
161 len = LoadStringW(hInstance, IDS_FRIENDLY_NAME_NONE, (LPWSTR)&none, 0);
162 if (len > *allocatedLen)
164 HeapFree(GetProcessHeap(), 0, *str);
165 *str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
166 if (*str)
167 *allocatedLen = len;
169 if (*str)
171 if (!CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID,
172 *str, &len))
173 item.pszText = none;
174 else
175 item.pszText = *str;
176 item.iSubItem = 3;
177 SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
181 static LPSTR get_cert_mgr_usages(void)
183 static const WCHAR keyName[] = { 'S','o','f','t','w','a','r','e','\\','M',
184 'i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r','a',
185 'p','h','y','\\','U','I','\\','C','e','r','t','m','g','r','\\','P','u',
186 'r','p','o','s','e',0 };
187 LPSTR str = NULL;
188 HKEY key;
190 if (!RegCreateKeyExW(HKEY_CURRENT_USER, keyName, 0, NULL, 0, KEY_READ,
191 NULL, &key, NULL))
193 LONG rc;
194 DWORD type, size;
196 rc = RegQueryValueExA(key, "Purpose", NULL, &type, NULL, &size);
197 if ((!rc || rc == ERROR_MORE_DATA) && type == REG_SZ)
199 str = HeapAlloc(GetProcessHeap(), 0, size);
200 if (str)
202 rc = RegQueryValueExA(key, "Purpose", NULL, NULL, (LPBYTE)str,
203 &size);
204 if (rc)
206 HeapFree(GetProcessHeap(), 0, str);
207 str = NULL;
211 RegCloseKey(key);
213 return str;
216 typedef enum {
217 PurposeFilterShowAll = 0,
218 PurposeFilterShowAdvanced = 1,
219 PurposeFilterShowOID = 2
220 } PurposeFilter;
222 static void initialize_purpose_selection(HWND hwnd)
224 HWND cb = GetDlgItem(hwnd, IDC_MGR_PURPOSE_SELECTION);
225 WCHAR buf[MAX_STRING_LEN];
226 LPSTR usages;
227 int index;
229 LoadStringW(hInstance, IDS_PURPOSE_ALL, buf,
230 sizeof(buf) / sizeof(buf[0]));
231 index = SendMessageW(cb, CB_INSERTSTRING, -1, (LPARAM)buf);
232 SendMessageW(cb, CB_SETITEMDATA, index, (LPARAM)PurposeFilterShowAll);
233 LoadStringW(hInstance, IDS_PURPOSE_ADVANCED, buf,
234 sizeof(buf) / sizeof(buf[0]));
235 index = SendMessageW(cb, CB_INSERTSTRING, -1, (LPARAM)buf);
236 SendMessageW(cb, CB_SETITEMDATA, index, (LPARAM)PurposeFilterShowAdvanced);
237 SendMessageW(cb, CB_SETCURSEL, 0, 0);
238 if ((usages = get_cert_mgr_usages()))
240 LPSTR ptr, comma;
242 for (ptr = usages, comma = strchr(ptr, ','); ptr && *ptr;
243 ptr = comma ? comma + 1 : NULL,
244 comma = ptr ? strchr(ptr, ',') : NULL)
246 PCCRYPT_OID_INFO info;
248 if (comma)
249 *comma = 0;
250 if ((info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, ptr, 0)))
252 index = SendMessageW(cb, CB_INSERTSTRING, 0,
253 (LPARAM)info->pwszName);
254 SendMessageW(cb, CB_SETITEMDATA, index, (LPARAM)info);
257 HeapFree(GetProcessHeap(), 0, usages);
261 extern BOOL WINAPI WTHelperGetKnownUsages(DWORD action,
262 PCCRYPT_OID_INFO **usages);
264 static CERT_ENHKEY_USAGE *add_oid_to_usage(CERT_ENHKEY_USAGE *usage, LPSTR oid)
266 if (!usage->cUsageIdentifier)
267 usage->rgpszUsageIdentifier = HeapAlloc(GetProcessHeap(), 0,
268 sizeof(LPSTR));
269 else
270 usage->rgpszUsageIdentifier = HeapReAlloc(GetProcessHeap(), 0,
271 usage->rgpszUsageIdentifier,
272 (usage->cUsageIdentifier + 1) * sizeof(LPSTR));
273 if (usage->rgpszUsageIdentifier)
274 usage->rgpszUsageIdentifier[usage->cUsageIdentifier++] = oid;
275 else
277 HeapFree(GetProcessHeap(), 0, usage);
278 usage = NULL;
280 return usage;
283 static CERT_ENHKEY_USAGE *convert_usages_str_to_usage(LPSTR usageStr)
285 CERT_ENHKEY_USAGE *usage = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
286 sizeof(CERT_ENHKEY_USAGE));
288 if (usage)
290 LPSTR ptr, comma;
292 for (ptr = usageStr, comma = strchr(ptr, ','); usage && ptr && *ptr;
293 ptr = comma ? comma + 1 : NULL,
294 comma = ptr ? strchr(ptr, ',') : NULL)
296 if (comma)
297 *comma = 0;
298 add_oid_to_usage(usage, ptr);
301 return usage;
304 static CERT_ENHKEY_USAGE *create_advanced_filter(void)
306 CERT_ENHKEY_USAGE *advancedUsage = HeapAlloc(GetProcessHeap(),
307 HEAP_ZERO_MEMORY, sizeof(CERT_ENHKEY_USAGE));
309 if (advancedUsage)
311 PCCRYPT_OID_INFO *usages;
313 if (WTHelperGetKnownUsages(1, &usages))
315 LPSTR disabledUsagesStr;
317 if ((disabledUsagesStr = get_cert_mgr_usages()))
319 CERT_ENHKEY_USAGE *disabledUsages =
320 convert_usages_str_to_usage(disabledUsagesStr);
322 if (disabledUsages)
324 PCCRYPT_OID_INFO *ptr;
326 for (ptr = usages; *ptr; ptr++)
328 DWORD i;
329 BOOL disabled = FALSE;
331 for (i = 0; !disabled &&
332 i < disabledUsages->cUsageIdentifier; i++)
333 if (!strcmp(disabledUsages->rgpszUsageIdentifier[i],
334 (*ptr)->pszOID))
335 disabled = TRUE;
336 if (!disabled)
337 add_oid_to_usage(advancedUsage,
338 (LPSTR)(*ptr)->pszOID);
340 /* The individual strings are pointers to disabledUsagesStr,
341 * so they're freed when it is.
343 HeapFree(GetProcessHeap(), 0,
344 disabledUsages->rgpszUsageIdentifier);
345 HeapFree(GetProcessHeap(), 0, disabledUsages);
347 HeapFree(GetProcessHeap(), 0, disabledUsagesStr);
349 WTHelperGetKnownUsages(2, &usages);
352 return advancedUsage;
355 static int CALLBACK cert_mgr_sort_by_subject(LPARAM lp1, LPARAM lp2, LPARAM lp);
357 static void show_store_certs(HWND hwnd, HCERTSTORE store)
359 HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
360 HWND cb = GetDlgItem(hwnd, IDC_MGR_PURPOSE_SELECTION);
361 PCCERT_CONTEXT cert = NULL;
362 DWORD allocatedLen = 0;
363 LPWSTR str = NULL;
364 int index;
365 PurposeFilter filter = PurposeFilterShowAll;
366 LPCSTR oid = NULL;
367 CERT_ENHKEY_USAGE *advanced = NULL;
369 index = SendMessageW(cb, CB_GETCURSEL, 0, 0);
370 if (index >= 0)
372 INT_PTR data = SendMessageW(cb, CB_GETITEMDATA, index, 0);
374 if (!HIWORD(data))
375 filter = data;
376 else
378 PCCRYPT_OID_INFO info = (PCCRYPT_OID_INFO)data;
380 filter = PurposeFilterShowOID;
381 oid = info->pszOID;
384 if (filter == PurposeFilterShowAdvanced)
385 advanced = create_advanced_filter();
386 do {
387 cert = CertEnumCertificatesInStore(store, cert);
388 if (cert)
390 BOOL show = FALSE;
392 if (filter == PurposeFilterShowAll)
393 show = TRUE;
394 else
396 int numOIDs;
397 DWORD cbOIDs = 0;
399 if (CertGetValidUsages(1, &cert, &numOIDs, NULL, &cbOIDs))
401 if (numOIDs == -1)
403 /* -1 implies all usages are valid */
404 show = TRUE;
406 else
408 LPSTR *oids = HeapAlloc(GetProcessHeap(), 0, cbOIDs);
410 if (oids)
412 if (CertGetValidUsages(1, &cert, &numOIDs, oids,
413 &cbOIDs))
415 int i;
417 if (filter == PurposeFilterShowOID)
419 for (i = 0; !show && i < numOIDs; i++)
420 if (!strcmp(oids[i], oid))
421 show = TRUE;
423 else
425 for (i = 0; !show && i < numOIDs; i++)
427 DWORD j;
429 for (j = 0; !show &&
430 j < advanced->cUsageIdentifier; j++)
431 if (!strcmp(oids[i],
432 advanced->rgpszUsageIdentifier[j]))
433 show = TRUE;
437 HeapFree(GetProcessHeap(), 0, oids);
442 if (show)
443 add_cert_to_view(lv, cert, &allocatedLen, &str);
445 } while (cert);
446 HeapFree(GetProcessHeap(), 0, str);
447 if (advanced)
449 HeapFree(GetProcessHeap(), 0, advanced->rgpszUsageIdentifier);
450 HeapFree(GetProcessHeap(), 0, advanced);
452 SendMessageW(lv, LVM_SORTITEMSEX, (WPARAM)lv,
453 (LPARAM)cert_mgr_sort_by_subject);
456 static const WCHAR my[] = { 'M','y',0 };
457 static const WCHAR addressBook[] = {
458 'A','d','d','r','e','s','s','B','o','o','k',0 };
459 static const WCHAR ca[] = { 'C','A',0 };
460 static const WCHAR root[] = { 'R','o','o','t',0 };
461 static const WCHAR trustedPublisher[] = {
462 'T','r','u','s','t','e','d','P','u','b','l','i','s','h','e','r',0 };
463 static const WCHAR disallowed[] = { 'D','i','s','a','l','l','o','w','e','d',0 };
465 struct CertMgrStoreInfo
467 LPCWSTR name;
468 int removeWarning;
469 int removePluralWarning;
472 static const struct CertMgrStoreInfo defaultStoreList[] = {
473 { my, IDS_WARN_REMOVE_MY, IDS_WARN_REMOVE_PLURAL_MY },
474 { addressBook, IDS_WARN_REMOVE_ADDRESSBOOK,
475 IDS_WARN_REMOVE_PLURAL_ADDRESSBOOK },
476 { ca, IDS_WARN_REMOVE_CA, IDS_WARN_REMOVE_PLURAL_CA },
477 { root, IDS_WARN_REMOVE_ROOT, IDS_WARN_REMOVE_PLURAL_ROOT },
478 { trustedPublisher, IDS_WARN_REMOVE_TRUSTEDPUBLISHER,
479 IDS_WARN_REMOVE_PLURAL_TRUSTEDPUBLISHER },
480 { disallowed, IDS_WARN_REMOVE_DEFAULT },
483 static const struct CertMgrStoreInfo publisherStoreList[] = {
484 { root, IDS_WARN_REMOVE_ROOT, IDS_WARN_REMOVE_PLURAL_ROOT },
485 { trustedPublisher, IDS_WARN_REMOVE_TRUSTEDPUBLISHER,
486 IDS_WARN_REMOVE_PLURAL_TRUSTEDPUBLISHER },
487 { disallowed, IDS_WARN_REMOVE_PLURAL_DEFAULT },
490 struct CertMgrData
492 HIMAGELIST imageList;
493 LPCWSTR title;
494 DWORD nStores;
495 const struct CertMgrStoreInfo *stores;
498 static void show_cert_stores(HWND hwnd, DWORD dwFlags, struct CertMgrData *data)
500 const struct CertMgrStoreInfo *storeList;
501 int cStores, i;
502 HWND tab = GetDlgItem(hwnd, IDC_MGR_STORES);
504 if (dwFlags & CRYPTUI_CERT_MGR_PUBLISHER_TAB)
506 storeList = publisherStoreList;
507 cStores = sizeof(publisherStoreList) / sizeof(publisherStoreList[0]);
509 else
511 storeList = defaultStoreList;
512 cStores = sizeof(defaultStoreList) / sizeof(defaultStoreList[0]);
514 if (dwFlags & CRYPTUI_CERT_MGR_SINGLE_TAB_FLAG)
515 cStores = 1;
516 data->nStores = cStores;
517 data->stores = storeList;
518 for (i = 0; i < cStores; i++)
520 LPCWSTR name;
521 TCITEMW item;
522 HCERTSTORE store;
524 if (!(name = CryptFindLocalizedName(storeList[i].name)))
525 name = storeList[i].name;
526 store = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
527 CERT_SYSTEM_STORE_CURRENT_USER, storeList[i].name);
528 item.mask = TCIF_TEXT | TCIF_PARAM;
529 item.pszText = (LPWSTR)name;
530 item.lParam = (LPARAM)store;
531 SendMessageW(tab, TCM_INSERTITEMW, i, (LPARAM)&item);
535 static void free_certs(HWND lv)
537 LVITEMW item;
538 int items = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0), i;
540 for (i = 0; i < items; i++)
542 item.mask = LVIF_PARAM;
543 item.iItem = i;
544 item.iSubItem = 0;
545 SendMessageW(lv, LVM_GETITEMW, 0, (LPARAM)&item);
546 CertFreeCertificateContext((PCCERT_CONTEXT)item.lParam);
550 static HCERTSTORE cert_mgr_index_to_store(HWND tab, int index)
552 TCITEMW item;
554 item.mask = TCIF_PARAM;
555 SendMessageW(tab, TCM_GETITEMW, index, (LPARAM)&item);
556 return (HCERTSTORE)item.lParam;
559 static HCERTSTORE cert_mgr_current_store(HWND hwnd)
561 HWND tab = GetDlgItem(hwnd, IDC_MGR_STORES);
563 return cert_mgr_index_to_store(tab, SendMessageW(tab, TCM_GETCURSEL, 0, 0));
566 static void close_stores(HWND tab)
568 int i, tabs = SendMessageW(tab, TCM_GETITEMCOUNT, 0, 0);
570 for (i = 0; i < tabs; i++)
571 CertCloseStore(cert_mgr_index_to_store(tab, i), 0);
574 static void refresh_store_certs(HWND hwnd)
576 HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
578 free_certs(lv);
579 SendMessageW(lv, LVM_DELETEALLITEMS, 0, 0);
580 show_store_certs(hwnd, cert_mgr_current_store(hwnd));
583 typedef enum {
584 CheckBitmapIndexUnchecked = 1,
585 CheckBitmapIndexChecked = 2,
586 CheckBitmapIndexDisabledUnchecked = 3,
587 CheckBitmapIndexDisabledChecked = 4
588 } CheckBitmapIndex;
590 static void add_known_usage(HWND lv, PCCRYPT_OID_INFO info,
591 CheckBitmapIndex state)
593 LVITEMW item;
595 item.mask = LVIF_TEXT | LVIF_STATE | LVIF_PARAM;
596 item.state = INDEXTOSTATEIMAGEMASK(state);
597 item.stateMask = LVIS_STATEIMAGEMASK;
598 item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
599 item.iSubItem = 0;
600 item.lParam = (LPARAM)info;
601 item.pszText = (LPWSTR)info->pwszName;
602 SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
605 static void add_known_usages_to_list(HWND lv, CheckBitmapIndex state)
607 PCCRYPT_OID_INFO *usages;
609 if (WTHelperGetKnownUsages(1, &usages))
611 PCCRYPT_OID_INFO *ptr;
613 for (ptr = usages; *ptr; ptr++)
614 add_known_usage(lv, *ptr, state);
615 WTHelperGetKnownUsages(2, &usages);
619 static void toggle_usage(HWND hwnd, int iItem)
621 LVITEMW item;
622 int res;
623 HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
625 item.mask = LVIF_STATE;
626 item.iItem = iItem;
627 item.iSubItem = 0;
628 item.stateMask = LVIS_STATEIMAGEMASK;
629 res = SendMessageW(lv, LVM_GETITEMW, 0, (LPARAM)&item);
630 if (res)
632 int state = item.state >> 12;
634 item.state = INDEXTOSTATEIMAGEMASK(
635 state == CheckBitmapIndexChecked ? CheckBitmapIndexUnchecked :
636 CheckBitmapIndexChecked);
637 SendMessageW(lv, LVM_SETITEMSTATE, iItem, (LPARAM)&item);
641 static LONG_PTR find_oid_in_list(HWND lv, LPCSTR oid)
643 PCCRYPT_OID_INFO oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
644 (void *)oid, CRYPT_ENHKEY_USAGE_OID_GROUP_ID);
645 LONG_PTR ret;
647 if (oidInfo)
649 LVFINDINFOW findInfo;
651 findInfo.flags = LVFI_PARAM;
652 findInfo.lParam = (LPARAM)oidInfo;
653 ret = SendMessageW(lv, LVM_FINDITEMW, -1, (LPARAM)&findInfo);
655 else
657 LVFINDINFOA findInfo;
659 findInfo.flags = LVFI_STRING;
660 findInfo.psz = oid;
661 ret = SendMessageW(lv, LVM_FINDITEMA, -1, (LPARAM)&findInfo);
663 return ret;
666 static void save_cert_mgr_usages(HWND hwnd)
668 static const WCHAR keyName[] = { 'S','o','f','t','w','a','r','e','\\','M',
669 'i','c','r','o','s','o','f','t','\\','C','r','y','p','t','o','g','r','a',
670 'p','h','y','\\','U','I','\\','C','e','r','t','m','g','r','\\','P','u',
671 'r','p','o','s','e',0 };
672 HKEY key;
673 HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
674 int purposes = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0), i;
675 LVITEMW item;
676 LPSTR str = NULL;
678 item.mask = LVIF_STATE | LVIF_PARAM;
679 item.iSubItem = 0;
680 item.stateMask = LVIS_STATEIMAGEMASK;
681 for (i = 0; i < purposes; i++)
683 item.iItem = i;
684 if (SendMessageW(lv, LVM_GETITEMW, 0, (LPARAM)&item))
686 int state = item.state >> 12;
688 if (state == CheckBitmapIndexUnchecked)
690 CRYPT_OID_INFO *info = (CRYPT_OID_INFO *)item.lParam;
691 BOOL firstString = TRUE;
693 if (!str)
694 str = HeapAlloc(GetProcessHeap(), 0,
695 strlen(info->pszOID) + 1);
696 else
698 str = HeapReAlloc(GetProcessHeap(), 0, str,
699 strlen(str) + 1 + strlen(info->pszOID) + 1);
700 firstString = FALSE;
702 if (str)
704 LPSTR ptr = firstString ? str : str + strlen(str);
706 if (!firstString)
707 *ptr++ = ',';
708 strcpy(ptr, info->pszOID);
713 if (!RegCreateKeyExW(HKEY_CURRENT_USER, keyName, 0, NULL, 0, KEY_ALL_ACCESS,
714 NULL, &key, NULL))
716 if (str)
717 RegSetValueExA(key, "Purpose", 0, REG_SZ, (const BYTE *)str,
718 strlen(str) + 1);
719 else
720 RegDeleteValueA(key, "Purpose");
721 RegCloseKey(key);
723 HeapFree(GetProcessHeap(), 0, str);
726 static LRESULT CALLBACK cert_mgr_advanced_dlg_proc(HWND hwnd, UINT msg,
727 WPARAM wp, LPARAM lp)
729 switch (msg)
731 case WM_INITDIALOG:
733 RECT rc;
734 LVCOLUMNW column;
735 HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
736 HIMAGELIST imageList;
737 LPSTR disabledUsages;
739 GetWindowRect(lv, &rc);
740 column.mask = LVCF_WIDTH;
741 column.cx = rc.right - rc.left;
742 SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
743 imageList = ImageList_Create(16, 16, ILC_COLOR4 | ILC_MASK, 4, 0);
744 if (imageList)
746 HBITMAP bmp;
747 COLORREF backColor = RGB(255, 0, 255);
749 bmp = LoadBitmapW(hInstance, MAKEINTRESOURCEW(IDB_CHECKS));
750 ImageList_AddMasked(imageList, bmp, backColor);
751 DeleteObject(bmp);
752 ImageList_SetBkColor(imageList, CLR_NONE);
753 SendMessageW(lv, LVM_SETIMAGELIST, LVSIL_STATE, (LPARAM)imageList);
754 SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)imageList);
756 add_known_usages_to_list(lv, CheckBitmapIndexChecked);
757 if ((disabledUsages = get_cert_mgr_usages()))
759 LPSTR ptr, comma;
761 for (ptr = disabledUsages, comma = strchr(ptr, ','); ptr && *ptr;
762 ptr = comma ? comma + 1 : NULL,
763 comma = ptr ? strchr(ptr, ',') : NULL)
765 LONG_PTR index;
767 if (comma)
768 *comma = 0;
769 if ((index = find_oid_in_list(lv, ptr)) != -1)
770 toggle_usage(hwnd, index);
772 HeapFree(GetProcessHeap(), 0, disabledUsages);
774 break;
776 case WM_NOTIFY:
778 NMHDR *hdr = (NMHDR *)lp;
779 NMITEMACTIVATE *nm;
781 switch (hdr->code)
783 case NM_CLICK:
784 nm = (NMITEMACTIVATE *)lp;
785 toggle_usage(hwnd, nm->iItem);
786 SendMessageW(GetParent(hwnd), PSM_CHANGED, (WPARAM)hwnd, 0);
787 break;
789 break;
791 case WM_COMMAND:
792 switch (wp)
794 case IDOK:
795 save_cert_mgr_usages(hwnd);
796 ImageList_Destroy((HIMAGELIST)GetWindowLongPtrW(hwnd, DWLP_USER));
797 EndDialog(hwnd, IDOK);
798 break;
799 case IDCANCEL:
800 ImageList_Destroy((HIMAGELIST)GetWindowLongPtrW(hwnd, DWLP_USER));
801 EndDialog(hwnd, IDCANCEL);
802 break;
804 break;
806 return 0;
809 static void cert_mgr_clear_cert_selection(HWND hwnd)
811 WCHAR empty[] = { 0 };
813 EnableWindow(GetDlgItem(hwnd, IDC_MGR_EXPORT), FALSE);
814 EnableWindow(GetDlgItem(hwnd, IDC_MGR_REMOVE), FALSE);
815 EnableWindow(GetDlgItem(hwnd, IDC_MGR_VIEW), FALSE);
816 SendMessageW(GetDlgItem(hwnd, IDC_MGR_PURPOSES), WM_SETTEXT, 0,
817 (LPARAM)empty);
818 refresh_store_certs(hwnd);
821 static PCCERT_CONTEXT cert_mgr_index_to_cert(HWND hwnd, int index)
823 PCCERT_CONTEXT cert = NULL;
824 LVITEMW item;
826 item.mask = LVIF_PARAM;
827 item.iItem = index;
828 item.iSubItem = 0;
829 if (SendMessageW(GetDlgItem(hwnd, IDC_MGR_CERTS), LVM_GETITEMW, 0,
830 (LPARAM)&item))
831 cert = (PCCERT_CONTEXT)item.lParam;
832 return cert;
835 static void show_selected_cert(HWND hwnd, int index)
837 PCCERT_CONTEXT cert = cert_mgr_index_to_cert(hwnd, index);
839 if (cert)
841 CRYPTUI_VIEWCERTIFICATE_STRUCTW viewInfo;
843 memset(&viewInfo, 0, sizeof(viewInfo));
844 viewInfo.dwSize = sizeof(viewInfo);
845 viewInfo.hwndParent = hwnd;
846 viewInfo.pCertContext = cert;
847 /* FIXME: this should be modal */
848 CryptUIDlgViewCertificateW(&viewInfo, NULL);
852 static void cert_mgr_show_cert_usages(HWND hwnd, int index)
854 HWND text = GetDlgItem(hwnd, IDC_MGR_PURPOSES);
855 PCCERT_CONTEXT cert = cert_mgr_index_to_cert(hwnd, index);
856 PCERT_ENHKEY_USAGE usage;
857 DWORD size;
859 /* Get enhanced key usage. Have to check for a property and an extension
860 * separately, because CertGetEnhancedKeyUsage will succeed and return an
861 * empty usage if neither is set. Unfortunately an empty usage implies
862 * no usage is allowed, so we have to distinguish between the two cases.
864 if (CertGetEnhancedKeyUsage(cert, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG,
865 NULL, &size))
867 usage = HeapAlloc(GetProcessHeap(), 0, size);
868 if (!CertGetEnhancedKeyUsage(cert,
869 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, usage, &size))
871 HeapFree(GetProcessHeap(), 0, usage);
872 usage = NULL;
875 else if (CertGetEnhancedKeyUsage(cert, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG,
876 NULL, &size))
878 usage = HeapAlloc(GetProcessHeap(), 0, size);
879 if (!CertGetEnhancedKeyUsage(cert,
880 CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG, usage, &size))
882 HeapFree(GetProcessHeap(), 0, usage);
883 usage = NULL;
886 else
887 usage = NULL;
888 if (usage)
890 if (usage->cUsageIdentifier)
892 static const WCHAR commaSpace[] = { ',',' ',0 };
893 DWORD i, len = 1;
894 LPWSTR str, ptr;
896 for (i = 0; i < usage->cUsageIdentifier; i++)
898 PCCRYPT_OID_INFO info =
899 CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
900 usage->rgpszUsageIdentifier[i],
901 CRYPT_ENHKEY_USAGE_OID_GROUP_ID);
903 if (info)
904 len += strlenW(info->pwszName);
905 else
906 len += strlen(usage->rgpszUsageIdentifier[i]);
907 if (i < usage->cUsageIdentifier - 1)
908 len += strlenW(commaSpace);
910 str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
911 if (str)
913 for (i = 0, ptr = str; i < usage->cUsageIdentifier; i++)
915 PCCRYPT_OID_INFO info =
916 CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
917 usage->rgpszUsageIdentifier[i],
918 CRYPT_ENHKEY_USAGE_OID_GROUP_ID);
920 if (info)
922 strcpyW(ptr, info->pwszName);
923 ptr += strlenW(info->pwszName);
925 else
927 LPCSTR src = usage->rgpszUsageIdentifier[i];
929 for (; *src; ptr++, src++)
930 *ptr = *src;
931 *ptr = 0;
933 if (i < usage->cUsageIdentifier - 1)
935 strcpyW(ptr, commaSpace);
936 ptr += strlenW(commaSpace);
939 *ptr = 0;
940 SendMessageW(text, WM_SETTEXT, 0, (LPARAM)str);
941 HeapFree(GetProcessHeap(), 0, str);
943 HeapFree(GetProcessHeap(), 0, usage);
945 else
947 WCHAR buf[MAX_STRING_LEN];
949 LoadStringW(hInstance, IDS_ALLOWED_PURPOSE_NONE, buf,
950 sizeof(buf) / sizeof(buf[0]));
951 SendMessageW(text, WM_SETTEXT, 0, (LPARAM)buf);
954 else
956 WCHAR buf[MAX_STRING_LEN];
958 LoadStringW(hInstance, IDS_ALLOWED_PURPOSE_ALL, buf,
959 sizeof(buf) / sizeof(buf[0]));
960 SendMessageW(text, WM_SETTEXT, 0, (LPARAM)buf);
964 static void cert_mgr_do_remove(HWND hwnd)
966 int tabIndex = SendMessageW(GetDlgItem(hwnd, IDC_MGR_STORES),
967 TCM_GETCURSEL, 0, 0);
968 struct CertMgrData *data =
969 (struct CertMgrData *)GetWindowLongPtrW(hwnd, DWLP_USER);
971 if (tabIndex < data->nStores)
973 HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
974 WCHAR warning[MAX_STRING_LEN], title[MAX_STRING_LEN];
975 LPCWSTR pTitle;
976 int warningID;
978 if (SendMessageW(lv, LVM_GETSELECTEDCOUNT, 0, 0) > 1)
979 warningID = data->stores[tabIndex].removePluralWarning;
980 else
981 warningID = data->stores[tabIndex].removeWarning;
982 if (data->title)
983 pTitle = data->title;
984 else
986 LoadStringW(hInstance, IDS_CERT_MGR, title,
987 sizeof(title) / sizeof(title[0]));
988 pTitle = title;
990 LoadStringW(hInstance, warningID, warning,
991 sizeof(warning) / sizeof(warning[0]));
992 if (MessageBoxW(hwnd, warning, pTitle, MB_YESNO) == IDYES)
994 int selection = -1;
996 do {
997 selection = SendMessageW(lv, LVM_GETNEXTITEM, selection,
998 LVNI_SELECTED);
999 if (selection >= 0)
1001 PCCERT_CONTEXT cert = cert_mgr_index_to_cert(hwnd,
1002 selection);
1004 CertDeleteCertificateFromStore(cert);
1006 } while (selection >= 0);
1007 cert_mgr_clear_cert_selection(hwnd);
1012 static void cert_mgr_do_export(HWND hwnd)
1014 HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
1015 int selectionCount = SendMessageW(lv, LVM_GETSELECTEDCOUNT, 0, 0);
1017 if (selectionCount == 1)
1019 int selection = SendMessageW(lv, LVM_GETNEXTITEM, -1,
1020 LVNI_SELECTED);
1022 if (selection >= 0)
1024 PCCERT_CONTEXT cert = cert_mgr_index_to_cert(hwnd, selection);
1026 if (cert)
1028 CRYPTUI_WIZ_EXPORT_INFO info;
1030 info.dwSize = sizeof(info);
1031 info.pwszExportFileName = NULL;
1032 info.dwSubjectChoice = CRYPTUI_WIZ_EXPORT_CERT_CONTEXT;
1033 info.u.pCertContext = cert;
1034 info.cStores = 0;
1035 CryptUIWizExport(0, hwnd, NULL, &info, NULL);
1039 else if (selectionCount > 1)
1041 HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1042 CERT_STORE_CREATE_NEW_FLAG, NULL);
1044 if (store)
1046 CRYPTUI_WIZ_EXPORT_INFO info;
1047 int selection = -1;
1049 info.dwSize = sizeof(info);
1050 info.pwszExportFileName = NULL;
1051 info.dwSubjectChoice =
1052 CRYPTUI_WIZ_EXPORT_CERT_STORE_CERTIFICATES_ONLY;
1053 info.u.hCertStore = store;
1054 info.cStores = 0;
1055 do {
1056 selection = SendMessageW(lv, LVM_GETNEXTITEM, selection,
1057 LVNI_SELECTED);
1058 if (selection >= 0)
1060 PCCERT_CONTEXT cert = cert_mgr_index_to_cert(hwnd,
1061 selection);
1063 CertAddCertificateContextToStore(store, cert,
1064 CERT_STORE_ADD_ALWAYS, NULL);
1066 } while (selection >= 0);
1067 CryptUIWizExport(0, hwnd, NULL, &info, NULL);
1068 CertCloseStore(store, 0);
1073 static int cert_mgr_sort_by_text(HWND lv, int col, int index1, int index2)
1075 LVITEMW item;
1076 WCHAR buf1[MAX_STRING_LEN];
1077 WCHAR buf2[MAX_STRING_LEN];
1079 item.cchTextMax = sizeof(buf1) / sizeof(buf1[0]);
1080 item.mask = LVIF_TEXT;
1081 item.pszText = buf1;
1082 item.iItem = index1;
1083 item.iSubItem = col;
1084 SendMessageW(lv, LVM_GETITEMW, 0, (LPARAM)&item);
1085 item.pszText = buf2;
1086 item.iItem = index2;
1087 SendMessageW(lv, LVM_GETITEMW, 0, (LPARAM)&item);
1088 return strcmpW(buf1, buf2);
1091 static int CALLBACK cert_mgr_sort_by_subject(LPARAM lp1, LPARAM lp2, LPARAM lp)
1093 return cert_mgr_sort_by_text((HWND)lp, 0, lp1, lp2);
1096 static int CALLBACK cert_mgr_sort_by_issuer(LPARAM lp1, LPARAM lp2, LPARAM lp)
1098 return cert_mgr_sort_by_text((HWND)lp, 1, lp1, lp2);
1101 static int CALLBACK cert_mgr_sort_by_date(LPARAM lp1, LPARAM lp2, LPARAM lp)
1103 PCCERT_CONTEXT cert1 = (PCCERT_CONTEXT)lp1;
1104 PCCERT_CONTEXT cert2 = (PCCERT_CONTEXT)lp2;
1105 return CompareFileTime(&cert1->pCertInfo->NotAfter,
1106 &cert2->pCertInfo->NotAfter);
1109 static int CALLBACK cert_mgr_sort_by_friendly_name(LPARAM lp1, LPARAM lp2,
1110 LPARAM lp)
1112 return cert_mgr_sort_by_text((HWND)lp, 3, lp1, lp2);
1115 static LRESULT CALLBACK cert_mgr_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
1116 LPARAM lp)
1118 struct CertMgrData *data;
1120 switch (msg)
1122 case WM_INITDIALOG:
1124 PCCRYPTUI_CERT_MGR_STRUCT pCryptUICertMgr =
1125 (PCCRYPTUI_CERT_MGR_STRUCT)lp;
1126 HWND tab = GetDlgItem(hwnd, IDC_MGR_STORES);
1128 data = HeapAlloc(GetProcessHeap(), 0, sizeof(struct CertMgrData));
1129 if (!data)
1130 return 0;
1131 data->imageList = ImageList_Create(16, 16, ILC_COLOR4 | ILC_MASK, 2, 0);
1132 if (data->imageList)
1134 HBITMAP bmp;
1135 COLORREF backColor = RGB(255, 0, 255);
1137 bmp = LoadBitmapW(hInstance, MAKEINTRESOURCEW(IDB_SMALL_ICONS));
1138 ImageList_AddMasked(data->imageList, bmp, backColor);
1139 DeleteObject(bmp);
1140 ImageList_SetBkColor(data->imageList, CLR_NONE);
1141 SendMessageW(GetDlgItem(hwnd, IDC_MGR_CERTS), LVM_SETIMAGELIST,
1142 LVSIL_SMALL, (LPARAM)data->imageList);
1144 SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
1145 data->title = pCryptUICertMgr->pwszTitle;
1147 initialize_purpose_selection(hwnd);
1148 add_cert_columns(hwnd);
1149 if (pCryptUICertMgr->pwszTitle)
1150 SendMessageW(hwnd, WM_SETTEXT, 0,
1151 (LPARAM)pCryptUICertMgr->pwszTitle);
1152 show_cert_stores(hwnd, pCryptUICertMgr->dwFlags, data);
1153 show_store_certs(hwnd, cert_mgr_index_to_store(tab, 0));
1154 break;
1156 case WM_NOTIFY:
1158 NMHDR *hdr = (NMHDR *)lp;
1160 switch (hdr->code)
1162 case TCN_SELCHANGE:
1163 cert_mgr_clear_cert_selection(hwnd);
1164 break;
1165 case LVN_ITEMCHANGED:
1167 NMITEMACTIVATE *nm;
1168 HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
1170 nm = (NMITEMACTIVATE*)lp;
1171 if (nm->uNewState & LVN_ITEMACTIVATE)
1173 int numSelected = SendMessageW(lv, LVM_GETSELECTEDCOUNT, 0, 0);
1175 EnableWindow(GetDlgItem(hwnd, IDC_MGR_EXPORT), numSelected > 0);
1176 EnableWindow(GetDlgItem(hwnd, IDC_MGR_REMOVE), numSelected > 0);
1177 EnableWindow(GetDlgItem(hwnd, IDC_MGR_VIEW), numSelected == 1);
1178 if (numSelected == 1)
1179 cert_mgr_show_cert_usages(hwnd, nm->iItem);
1181 break;
1183 case NM_DBLCLK:
1184 show_selected_cert(hwnd, ((NMITEMACTIVATE *)lp)->iItem);
1185 break;
1186 case LVN_KEYDOWN:
1188 NMLVKEYDOWN *lvk = (NMLVKEYDOWN *)lp;
1190 if (lvk->wVKey == VK_DELETE)
1191 cert_mgr_do_remove(hwnd);
1192 break;
1194 case LVN_COLUMNCLICK:
1196 NMLISTVIEW *nmlv = (NMLISTVIEW *)lp;
1197 HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
1199 /* FIXME: doesn't support swapping sort order between ascending
1200 * and descending.
1202 switch (nmlv->iSubItem)
1204 case 0:
1205 SendMessageW(lv, LVM_SORTITEMSEX, (WPARAM)lv,
1206 (LPARAM)cert_mgr_sort_by_subject);
1207 break;
1208 case 1:
1209 SendMessageW(lv, LVM_SORTITEMSEX, (WPARAM)lv,
1210 (LPARAM)cert_mgr_sort_by_issuer);
1211 break;
1212 case 2:
1213 SendMessageW(lv, LVM_SORTITEMS, 0,
1214 (LPARAM)cert_mgr_sort_by_date);
1215 break;
1216 case 3:
1217 SendMessageW(lv, LVM_SORTITEMSEX, (WPARAM)lv,
1218 (LPARAM)cert_mgr_sort_by_friendly_name);
1219 break;
1221 break;
1224 break;
1226 case WM_COMMAND:
1227 switch (wp)
1229 case ((CBN_SELCHANGE << 16) | IDC_MGR_PURPOSE_SELECTION):
1230 cert_mgr_clear_cert_selection(hwnd);
1231 break;
1232 case IDC_MGR_IMPORT:
1233 if (CryptUIWizImport(0, hwnd, NULL, NULL,
1234 cert_mgr_current_store(hwnd)))
1235 refresh_store_certs(hwnd);
1236 break;
1237 case IDC_MGR_ADVANCED:
1238 if (DialogBoxW(hInstance, MAKEINTRESOURCEW(IDD_CERT_MGR_ADVANCED),
1239 hwnd, cert_mgr_advanced_dlg_proc) == IDOK)
1241 HWND cb = GetDlgItem(hwnd, IDC_MGR_PURPOSE_SELECTION);
1242 int index, len;
1243 LPWSTR curString = NULL;
1245 index = SendMessageW(cb, CB_GETCURSEL, 0, 0);
1246 if (index >= 0)
1248 len = SendMessageW(cb, CB_GETLBTEXTLEN, index, 0);
1249 curString = HeapAlloc(GetProcessHeap(), 0,
1250 (len + 1) * sizeof(WCHAR));
1251 SendMessageW(cb, CB_GETLBTEXT, index, (LPARAM)curString);
1253 SendMessageW(cb, CB_RESETCONTENT, 0, 0);
1254 initialize_purpose_selection(hwnd);
1255 if (curString)
1257 index = SendMessageW(cb, CB_FINDSTRINGEXACT, -1,
1258 (LPARAM)curString);
1259 if (index >= 0)
1260 SendMessageW(cb, CB_SETCURSEL, index, 0);
1261 HeapFree(GetProcessHeap(), 0, curString);
1263 refresh_store_certs(hwnd);
1265 break;
1266 case IDC_MGR_VIEW:
1268 HWND lv = GetDlgItem(hwnd, IDC_MGR_CERTS);
1269 int selection = SendMessageW(lv, LVM_GETNEXTITEM, -1,
1270 LVNI_SELECTED);
1272 if (selection >= 0)
1273 show_selected_cert(hwnd, selection);
1274 break;
1276 case IDC_MGR_EXPORT:
1277 cert_mgr_do_export(hwnd);
1278 break;
1279 case IDC_MGR_REMOVE:
1280 cert_mgr_do_remove(hwnd);
1281 break;
1282 case IDCANCEL:
1283 free_certs(GetDlgItem(hwnd, IDC_MGR_CERTS));
1284 close_stores(GetDlgItem(hwnd, IDC_MGR_STORES));
1285 close_stores(GetDlgItem(hwnd, IDC_MGR_STORES));
1286 data = (struct CertMgrData *)GetWindowLongPtrW(hwnd, DWLP_USER);
1287 ImageList_Destroy(data->imageList);
1288 HeapFree(GetProcessHeap(), 0, data);
1289 EndDialog(hwnd, IDCANCEL);
1290 break;
1292 break;
1294 return 0;
1297 /***********************************************************************
1298 * CryptUIDlgCertMgr (CRYPTUI.@)
1300 BOOL WINAPI CryptUIDlgCertMgr(PCCRYPTUI_CERT_MGR_STRUCT pCryptUICertMgr)
1302 TRACE("(%p)\n", pCryptUICertMgr);
1304 if (pCryptUICertMgr->dwSize != sizeof(CRYPTUI_CERT_MGR_STRUCT))
1306 WARN("unexpected size %d\n", pCryptUICertMgr->dwSize);
1307 SetLastError(E_INVALIDARG);
1308 return FALSE;
1310 DialogBoxParamW(hInstance, MAKEINTRESOURCEW(IDD_CERT_MGR),
1311 pCryptUICertMgr->hwndParent, cert_mgr_dlg_proc, (LPARAM)pCryptUICertMgr);
1312 return TRUE;
1315 /* FIXME: real names are unknown, functions are undocumented */
1316 typedef struct _CRYPTUI_ENUM_SYSTEM_STORE_ARGS
1318 DWORD dwFlags;
1319 void *pvSystemStoreLocationPara;
1320 } CRYPTUI_ENUM_SYSTEM_STORE_ARGS, *PCRYPTUI_ENUM_SYSTEM_STORE_ARGS;
1322 typedef struct _CRYPTUI_ENUM_DATA
1324 DWORD cStores;
1325 HCERTSTORE *rghStore;
1326 DWORD cEnumArgs;
1327 PCRYPTUI_ENUM_SYSTEM_STORE_ARGS rgEnumArgs;
1328 } CRYPTUI_ENUM_DATA, *PCRYPTUI_ENUM_DATA;
1330 typedef BOOL (WINAPI *PFN_SELECTED_STORE_CB)(HCERTSTORE store, HWND hwnd,
1331 void *pvArg);
1333 /* Values for dwFlags */
1334 #define CRYPTUI_ENABLE_SHOW_PHYSICAL_STORE 0x00000001
1336 typedef struct _CRYPTUI_SELECTSTORE_INFO_A
1338 DWORD dwSize;
1339 HWND parent;
1340 DWORD dwFlags;
1341 LPSTR pszTitle;
1342 LPSTR pszText;
1343 CRYPTUI_ENUM_DATA *pEnumData;
1344 PFN_SELECTED_STORE_CB pfnSelectedStoreCallback;
1345 void *pvArg;
1346 } CRYPTUI_SELECTSTORE_INFO_A, *PCRYPTUI_SELECTSTORE_INFO_A;
1348 typedef struct _CRYPTUI_SELECTSTORE_INFO_W
1350 DWORD dwSize;
1351 HWND parent;
1352 DWORD dwFlags;
1353 LPWSTR pwszTitle;
1354 LPWSTR pwszText;
1355 CRYPTUI_ENUM_DATA *pEnumData;
1356 PFN_SELECTED_STORE_CB pfnSelectedStoreCallback;
1357 void *pvArg;
1358 } CRYPTUI_SELECTSTORE_INFO_W, *PCRYPTUI_SELECTSTORE_INFO_W;
1360 struct StoreInfo
1362 enum {
1363 StoreHandle,
1364 SystemStore
1365 } type;
1366 union {
1367 HCERTSTORE store;
1368 LPWSTR name;
1369 } DUMMYUNIONNAME;
1372 static BOOL WINAPI enum_store_callback(const void *pvSystemStore,
1373 DWORD dwFlags, PCERT_SYSTEM_STORE_INFO pStoreInfo, void *pvReserved,
1374 void *pvArg)
1376 HWND tree = GetDlgItem(pvArg, IDC_STORE_LIST);
1377 TVINSERTSTRUCTW tvis;
1378 LPCWSTR localizedName;
1379 BOOL ret = TRUE;
1381 tvis.hParent = NULL;
1382 tvis.hInsertAfter = TVI_LAST;
1383 tvis.u.item.mask = TVIF_TEXT;
1384 if ((localizedName = CryptFindLocalizedName(pvSystemStore)))
1386 struct StoreInfo *storeInfo = HeapAlloc(GetProcessHeap(), 0,
1387 sizeof(struct StoreInfo));
1389 if (storeInfo)
1391 storeInfo->type = SystemStore;
1392 storeInfo->u.name = HeapAlloc(GetProcessHeap(), 0,
1393 (strlenW(pvSystemStore) + 1) * sizeof(WCHAR));
1394 if (storeInfo->u.name)
1396 tvis.u.item.mask |= TVIF_PARAM;
1397 tvis.u.item.lParam = (LPARAM)storeInfo;
1398 strcpyW(storeInfo->u.name, pvSystemStore);
1400 else
1402 HeapFree(GetProcessHeap(), 0, storeInfo);
1403 ret = FALSE;
1406 else
1407 ret = FALSE;
1408 tvis.u.item.pszText = (LPWSTR)localizedName;
1410 else
1411 tvis.u.item.pszText = (LPWSTR)pvSystemStore;
1412 /* FIXME: need a folder icon for the store too */
1413 if (ret)
1414 SendMessageW(tree, TVM_INSERTITEMW, 0, (LPARAM)&tvis);
1415 return ret;
1418 static void enumerate_stores(HWND hwnd, CRYPTUI_ENUM_DATA *pEnumData)
1420 DWORD i;
1421 HWND tree = GetDlgItem(hwnd, IDC_STORE_LIST);
1423 for (i = 0; i < pEnumData->cEnumArgs; i++)
1424 CertEnumSystemStore(pEnumData->rgEnumArgs[i].dwFlags,
1425 pEnumData->rgEnumArgs[i].pvSystemStoreLocationPara,
1426 hwnd, enum_store_callback);
1427 for (i = 0; i < pEnumData->cStores; i++)
1429 DWORD size;
1431 if (CertGetStoreProperty(pEnumData->rghStore[i],
1432 CERT_STORE_LOCALIZED_NAME_PROP_ID, NULL, &size))
1434 LPWSTR name = HeapAlloc(GetProcessHeap(), 0, size);
1436 if (name)
1438 if (CertGetStoreProperty(pEnumData->rghStore[i],
1439 CERT_STORE_LOCALIZED_NAME_PROP_ID, name, &size))
1441 struct StoreInfo *storeInfo = HeapAlloc(GetProcessHeap(),
1442 0, sizeof(struct StoreInfo));
1444 if (storeInfo)
1446 TVINSERTSTRUCTW tvis;
1448 storeInfo->type = StoreHandle;
1449 storeInfo->u.store = pEnumData->rghStore[i];
1450 tvis.hParent = NULL;
1451 tvis.hInsertAfter = TVI_LAST;
1452 tvis.u.item.mask = TVIF_TEXT | TVIF_PARAM;
1453 tvis.u.item.pszText = name;
1454 tvis.u.item.lParam = (LPARAM)storeInfo;
1455 SendMessageW(tree, TVM_INSERTITEMW, 0, (LPARAM)&tvis);
1458 HeapFree(GetProcessHeap(), 0, name);
1464 static void free_store_info(HWND tree)
1466 HTREEITEM next = (HTREEITEM)SendMessageW(tree, TVM_GETNEXTITEM, TVGN_CHILD,
1469 while (next)
1471 TVITEMW item;
1473 memset(&item, 0, sizeof(item));
1474 item.mask = TVIF_HANDLE | TVIF_PARAM;
1475 item.hItem = next;
1476 SendMessageW(tree, TVM_GETITEMW, 0, (LPARAM)&item);
1477 if (item.lParam)
1479 struct StoreInfo *storeInfo = (struct StoreInfo *)item.lParam;
1481 if (storeInfo->type == SystemStore)
1482 HeapFree(GetProcessHeap(), 0, storeInfo->u.name);
1483 HeapFree(GetProcessHeap(), 0, storeInfo);
1485 next = (HTREEITEM)SendMessageW(tree, TVM_GETNEXTITEM, TVGN_NEXT,
1486 (LPARAM)next);
1490 static HCERTSTORE selected_item_to_store(HWND tree, HTREEITEM hItem)
1492 WCHAR buf[MAX_STRING_LEN];
1493 TVITEMW item;
1494 HCERTSTORE store;
1496 memset(&item, 0, sizeof(item));
1497 item.mask = TVIF_HANDLE | TVIF_PARAM | TVIF_TEXT;
1498 item.hItem = hItem;
1499 item.cchTextMax = sizeof(buf) / sizeof(buf[0]);
1500 item.pszText = buf;
1501 SendMessageW(tree, TVM_GETITEMW, 0, (LPARAM)&item);
1502 if (item.lParam)
1504 struct StoreInfo *storeInfo = (struct StoreInfo *)item.lParam;
1506 if (storeInfo->type == StoreHandle)
1507 store = storeInfo->u.store;
1508 else
1509 store = CertOpenSystemStoreW(0, storeInfo->u.name);
1511 else
1513 /* It's implicitly a system store */
1514 store = CertOpenSystemStoreW(0, buf);
1516 return store;
1519 struct SelectStoreInfo
1521 PCRYPTUI_SELECTSTORE_INFO_W info;
1522 HCERTSTORE store;
1525 static LRESULT CALLBACK select_store_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
1526 LPARAM lp)
1528 struct SelectStoreInfo *selectInfo;
1529 LRESULT ret = 0;
1531 switch (msg)
1533 case WM_INITDIALOG:
1535 selectInfo = (struct SelectStoreInfo *)lp;
1536 SetWindowLongPtrW(hwnd, DWLP_USER, lp);
1537 if (selectInfo->info->pwszTitle)
1538 SendMessageW(hwnd, WM_SETTEXT, 0,
1539 (LPARAM)selectInfo->info->pwszTitle);
1540 if (selectInfo->info->pwszText)
1541 SendMessageW(GetDlgItem(hwnd, IDC_STORE_TEXT), WM_SETTEXT, 0,
1542 (LPARAM)selectInfo->info->pwszText);
1543 if (!(selectInfo->info->dwFlags & CRYPTUI_ENABLE_SHOW_PHYSICAL_STORE))
1544 ShowWindow(GetDlgItem(hwnd, IDC_SHOW_PHYSICAL_STORES), FALSE);
1545 enumerate_stores(hwnd, selectInfo->info->pEnumData);
1546 break;
1548 case WM_COMMAND:
1549 switch (wp)
1551 case IDOK:
1553 HWND tree = GetDlgItem(hwnd, IDC_STORE_LIST);
1554 HTREEITEM selection = (HTREEITEM)SendMessageW(tree,
1555 TVM_GETNEXTITEM, TVGN_CARET, 0);
1557 selectInfo = (struct SelectStoreInfo *)GetWindowLongPtrW(hwnd,
1558 DWLP_USER);
1559 if (!selection)
1561 WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN], *pTitle;
1563 if (selectInfo->info->pwszTitle)
1564 pTitle = selectInfo->info->pwszTitle;
1565 else
1567 LoadStringW(hInstance, IDS_SELECT_STORE_TITLE, title,
1568 sizeof(title) / sizeof(title[0]));
1569 pTitle = title;
1571 LoadStringW(hInstance, IDS_SELECT_STORE, error,
1572 sizeof(error) / sizeof(error[0]));
1573 MessageBoxW(hwnd, error, pTitle, MB_ICONEXCLAMATION | MB_OK);
1575 else
1577 HCERTSTORE store = selected_item_to_store(tree, selection);
1579 if (!selectInfo->info->pfnSelectedStoreCallback ||
1580 selectInfo->info->pfnSelectedStoreCallback(store, hwnd,
1581 selectInfo->info->pvArg))
1583 selectInfo->store = store;
1584 free_store_info(tree);
1585 EndDialog(hwnd, IDOK);
1587 else
1588 CertCloseStore(store, 0);
1590 ret = TRUE;
1591 break;
1593 case IDCANCEL:
1594 free_store_info(GetDlgItem(hwnd, IDC_STORE_LIST));
1595 EndDialog(hwnd, IDCANCEL);
1596 ret = TRUE;
1597 break;
1599 break;
1601 return ret;
1604 /***********************************************************************
1605 * CryptUIDlgSelectStoreW (CRYPTUI.@)
1607 HCERTSTORE WINAPI CryptUIDlgSelectStoreW(PCRYPTUI_SELECTSTORE_INFO_W info)
1609 struct SelectStoreInfo selectInfo = { info, NULL };
1611 TRACE("(%p)\n", info);
1613 if (info->dwSize != sizeof(CRYPTUI_SELECTSTORE_INFO_W))
1615 WARN("unexpected size %d\n", info->dwSize);
1616 SetLastError(E_INVALIDARG);
1617 return NULL;
1619 DialogBoxParamW(hInstance, MAKEINTRESOURCEW(IDD_SELECT_STORE), info->parent,
1620 select_store_dlg_proc, (LPARAM)&selectInfo);
1621 return selectInfo.store;
1624 /***********************************************************************
1625 * CryptUIDlgSelectStoreA (CRYPTUI.@)
1627 HCERTSTORE WINAPI CryptUIDlgSelectStoreA(PCRYPTUI_SELECTSTORE_INFO_A info)
1629 CRYPTUI_SELECTSTORE_INFO_W infoW;
1630 HCERTSTORE ret;
1631 int len;
1633 TRACE("(%p)\n", info);
1635 if (info->dwSize != sizeof(CRYPTUI_SELECTSTORE_INFO_A))
1637 WARN("unexpected size %d\n", info->dwSize);
1638 SetLastError(E_INVALIDARG);
1639 return NULL;
1641 memcpy(&infoW, &info, sizeof(info));
1642 if (info->pszTitle)
1644 len = MultiByteToWideChar(CP_ACP, 0, info->pszTitle, -1, NULL, 0);
1645 infoW.pwszTitle = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1646 MultiByteToWideChar(CP_ACP, 0, info->pszTitle, -1, infoW.pwszTitle,
1647 len);
1649 if (info->pszText)
1651 len = MultiByteToWideChar(CP_ACP, 0, info->pszText, -1, NULL, 0);
1652 infoW.pwszText = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1653 MultiByteToWideChar(CP_ACP, 0, info->pszText, -1, infoW.pwszText, len);
1655 ret = CryptUIDlgSelectStoreW(&infoW);
1656 HeapFree(GetProcessHeap(), 0, infoW.pwszText);
1657 HeapFree(GetProcessHeap(), 0, infoW.pwszTitle);
1658 return ret;
1661 /***********************************************************************
1662 * CryptUIDlgViewCertificateA (CRYPTUI.@)
1664 BOOL WINAPI CryptUIDlgViewCertificateA(
1665 PCCRYPTUI_VIEWCERTIFICATE_STRUCTA pCertViewInfo, BOOL *pfPropertiesChanged)
1667 CRYPTUI_VIEWCERTIFICATE_STRUCTW viewInfo;
1668 LPWSTR title = NULL;
1669 BOOL ret;
1671 TRACE("(%p, %p)\n", pCertViewInfo, pfPropertiesChanged);
1673 memcpy(&viewInfo, pCertViewInfo, sizeof(viewInfo));
1674 if (pCertViewInfo->szTitle)
1676 int len = MultiByteToWideChar(CP_ACP, 0, pCertViewInfo->szTitle, -1,
1677 NULL, 0);
1679 title = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1680 if (title)
1682 MultiByteToWideChar(CP_ACP, 0, pCertViewInfo->szTitle, -1, title,
1683 len);
1684 viewInfo.szTitle = title;
1686 else
1688 ret = FALSE;
1689 goto error;
1692 if (pCertViewInfo->cPropSheetPages)
1694 FIXME("ignoring additional prop sheet pages\n");
1695 viewInfo.cPropSheetPages = 0;
1697 ret = CryptUIDlgViewCertificateW(&viewInfo, pfPropertiesChanged);
1698 HeapFree(GetProcessHeap(), 0, title);
1699 error:
1700 return ret;
1703 struct ReadStringStruct
1705 LPCWSTR buf;
1706 LONG pos;
1707 LONG len;
1710 static DWORD CALLBACK read_text_callback(DWORD_PTR dwCookie, LPBYTE buf,
1711 LONG cb, LONG *pcb)
1713 struct ReadStringStruct *string = (struct ReadStringStruct *)dwCookie;
1714 LONG cch = min(cb / sizeof(WCHAR), string->len - string->pos);
1716 TRACE("(%p, %p, %d, %p)\n", string, buf, cb, pcb);
1718 memmove(buf, string->buf + string->pos, cch * sizeof(WCHAR));
1719 string->pos += cch;
1720 *pcb = cch * sizeof(WCHAR);
1721 return 0;
1724 static void add_unformatted_text_to_control(HWND hwnd, LPCWSTR text, LONG len)
1726 struct ReadStringStruct string;
1727 EDITSTREAM editstream;
1729 TRACE("(%p, %s)\n", hwnd, debugstr_wn(text, len));
1731 string.buf = text;
1732 string.pos = 0;
1733 string.len = len;
1734 editstream.dwCookie = (DWORD_PTR)&string;
1735 editstream.dwError = 0;
1736 editstream.pfnCallback = read_text_callback;
1737 SendMessageW(hwnd, EM_STREAMIN, SF_TEXT | SFF_SELECTION | SF_UNICODE,
1738 (LPARAM)&editstream);
1741 static void add_string_resource_to_control(HWND hwnd, int id)
1743 LPWSTR str;
1744 LONG len;
1746 len = LoadStringW(hInstance, id, (LPWSTR)&str, 0);
1747 add_unformatted_text_to_control(hwnd, str, len);
1750 static void add_text_with_paraformat_to_control(HWND hwnd, LPCWSTR text,
1751 LONG len, const PARAFORMAT2 *fmt)
1753 add_unformatted_text_to_control(hwnd, text, len);
1754 SendMessageW(hwnd, EM_SETPARAFORMAT, 0, (LPARAM)fmt);
1757 static void add_string_resource_with_paraformat_to_control(HWND hwnd, int id,
1758 const PARAFORMAT2 *fmt)
1760 LPWSTR str;
1761 LONG len;
1763 len = LoadStringW(hInstance, id, (LPWSTR)&str, 0);
1764 add_text_with_paraformat_to_control(hwnd, str, len, fmt);
1767 static LPWSTR get_cert_name_string(PCCERT_CONTEXT pCertContext, DWORD dwType,
1768 DWORD dwFlags)
1770 LPWSTR buf = NULL;
1771 DWORD len;
1773 len = CertGetNameStringW(pCertContext, dwType, dwFlags, NULL, NULL, 0);
1774 if (len)
1776 buf = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1777 if (buf)
1778 CertGetNameStringW(pCertContext, dwType, dwFlags, NULL, buf, len);
1780 return buf;
1783 static void add_cert_string_to_control(HWND hwnd, PCCERT_CONTEXT pCertContext,
1784 DWORD dwType, DWORD dwFlags)
1786 LPWSTR name = get_cert_name_string(pCertContext, dwType, dwFlags);
1788 if (name)
1790 /* Don't include NULL-terminator in output */
1791 DWORD len = lstrlenW(name);
1793 add_unformatted_text_to_control(hwnd, name, len);
1794 HeapFree(GetProcessHeap(), 0, name);
1798 static void add_icon_to_control(HWND hwnd, int id)
1800 HRESULT hr;
1801 LPRICHEDITOLE richEditOle = NULL;
1802 LPOLEOBJECT object = NULL;
1803 CLSID clsid;
1804 LPOLECACHE oleCache = NULL;
1805 FORMATETC formatEtc;
1806 DWORD conn;
1807 LPDATAOBJECT dataObject = NULL;
1808 HBITMAP bitmap = NULL;
1809 RECT rect;
1810 STGMEDIUM stgm;
1811 LPOLECLIENTSITE clientSite = NULL;
1812 REOBJECT reObject;
1814 TRACE("(%p, %d)\n", hwnd, id);
1816 SendMessageW(hwnd, EM_GETOLEINTERFACE, 0, (LPARAM)&richEditOle);
1817 if (!richEditOle)
1818 goto end;
1819 hr = OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject,
1820 (void**)&object);
1821 if (FAILED(hr))
1822 goto end;
1823 hr = IOleObject_GetUserClassID(object, &clsid);
1824 if (FAILED(hr))
1825 goto end;
1826 hr = IOleObject_QueryInterface(object, &IID_IOleCache, (void**)&oleCache);
1827 if (FAILED(hr))
1828 goto end;
1829 formatEtc.cfFormat = CF_BITMAP;
1830 formatEtc.ptd = NULL;
1831 formatEtc.dwAspect = DVASPECT_CONTENT;
1832 formatEtc.lindex = -1;
1833 formatEtc.tymed = TYMED_GDI;
1834 hr = IOleCache_Cache(oleCache, &formatEtc, 0, &conn);
1835 if (FAILED(hr))
1836 goto end;
1837 hr = IOleObject_QueryInterface(object, &IID_IDataObject,
1838 (void**)&dataObject);
1839 if (FAILED(hr))
1840 goto end;
1841 hr = IRichEditOle_GetClientSite(richEditOle, &clientSite);
1842 if (FAILED(hr))
1843 goto end;
1844 bitmap = LoadImageW(hInstance, MAKEINTRESOURCEW(id), IMAGE_BITMAP, 0, 0,
1845 LR_DEFAULTSIZE | LR_LOADTRANSPARENT);
1846 if (!bitmap)
1847 goto end;
1848 rect.left = rect.top = 0;
1849 rect.right = GetSystemMetrics(SM_CXICON);
1850 rect.bottom = GetSystemMetrics(SM_CYICON);
1851 stgm.tymed = TYMED_GDI;
1852 stgm.u.hBitmap = bitmap;
1853 stgm.pUnkForRelease = NULL;
1854 hr = IDataObject_SetData(dataObject, &formatEtc, &stgm, TRUE);
1855 if (FAILED(hr))
1856 goto end;
1858 reObject.cbStruct = sizeof(reObject);
1859 reObject.cp = REO_CP_SELECTION;
1860 reObject.clsid = clsid;
1861 reObject.poleobj = object;
1862 reObject.pstg = NULL;
1863 reObject.polesite = clientSite;
1864 reObject.sizel.cx = reObject.sizel.cy = 0;
1865 reObject.dvaspect = DVASPECT_CONTENT;
1866 reObject.dwFlags = 0;
1867 reObject.dwUser = 0;
1869 IRichEditOle_InsertObject(richEditOle, &reObject);
1871 end:
1872 if (clientSite)
1873 IOleClientSite_Release(clientSite);
1874 if (dataObject)
1875 IDataObject_Release(dataObject);
1876 if (oleCache)
1877 IOleCache_Release(oleCache);
1878 if (object)
1879 IOleObject_Release(object);
1880 if (richEditOle)
1881 IRichEditOle_Release(richEditOle);
1884 #define MY_INDENT 200
1886 static void add_oid_text_to_control(HWND hwnd, char *oid)
1888 WCHAR nl = '\n';
1889 PCCRYPT_OID_INFO oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, oid, 0);
1890 PARAFORMAT2 parFmt;
1892 parFmt.cbSize = sizeof(parFmt);
1893 parFmt.dwMask = PFM_STARTINDENT;
1894 parFmt.dxStartIndent = MY_INDENT * 3;
1895 if (oidInfo)
1897 add_text_with_paraformat_to_control(hwnd, oidInfo->pwszName,
1898 lstrlenW(oidInfo->pwszName), &parFmt);
1899 add_unformatted_text_to_control(hwnd, &nl, 1);
1903 struct OIDToString
1905 LPCSTR oid;
1906 int id;
1909 /* The following list MUST be lexicographically sorted by OID */
1910 static struct OIDToString oidMap[] = {
1911 /* 1.3.6.1.4.1.311.10.3.1 */
1912 { szOID_KP_CTL_USAGE_SIGNING, IDS_PURPOSE_CTL_USAGE_SIGNING },
1913 /* 1.3.6.1.4.1.311.10.3.4 */
1914 { szOID_KP_EFS, IDS_PURPOSE_EFS },
1915 /* 1.3.6.1.4.1.311.10.3.4.1 */
1916 { szOID_EFS_RECOVERY, IDS_PURPOSE_EFS_RECOVERY },
1917 /* 1.3.6.1.4.1.311.10.3.5 */
1918 { szOID_WHQL_CRYPTO, IDS_PURPOSE_WHQL },
1919 /* 1.3.6.1.4.1.311.10.3.6 */
1920 { szOID_NT5_CRYPTO, IDS_PURPOSE_NT5 },
1921 /* 1.3.6.1.4.1.311.10.3.7 */
1922 { szOID_OEM_WHQL_CRYPTO, IDS_PURPOSE_OEM_WHQL },
1923 /* 1.3.6.1.4.1.311.10.3.8 */
1924 { szOID_EMBEDDED_NT_CRYPTO, IDS_PURPOSE_EMBEDDED_NT },
1925 /* 1.3.6.1.4.1.311.10.3.9 */
1926 { szOID_ROOT_LIST_SIGNER, IDS_PURPOSE_ROOT_LIST_SIGNER },
1927 /* 1.3.6.1.4.1.311.10.3.10 */
1928 { szOID_KP_QUALIFIED_SUBORDINATION, IDS_PURPOSE_QUALIFIED_SUBORDINATION },
1929 /* 1.3.6.1.4.1.311.10.3.11 */
1930 { szOID_KP_KEY_RECOVERY, IDS_PURPOSE_KEY_RECOVERY },
1931 /* 1.3.6.1.4.1.311.10.3.12 */
1932 { szOID_KP_DOCUMENT_SIGNING, IDS_PURPOSE_DOCUMENT_SIGNING },
1933 /* 1.3.6.1.4.1.311.10.3.13 */
1934 { szOID_KP_LIFETIME_SIGNING, IDS_PURPOSE_LIFETIME_SIGNING },
1935 /* 1.3.6.1.4.1.311.10.5.1 */
1936 { szOID_DRM, IDS_PURPOSE_DRM },
1937 /* 1.3.6.1.4.1.311.10.6.1 */
1938 { szOID_LICENSES, IDS_PURPOSE_LICENSES },
1939 /* 1.3.6.1.4.1.311.10.6.2 */
1940 { szOID_LICENSE_SERVER, IDS_PURPOSE_LICENSE_SERVER },
1941 /* 1.3.6.1.4.1.311.20.2.1 */
1942 { szOID_ENROLLMENT_AGENT, IDS_PURPOSE_ENROLLMENT_AGENT },
1943 /* 1.3.6.1.4.1.311.20.2.2 */
1944 { szOID_KP_SMARTCARD_LOGON, IDS_PURPOSE_SMARTCARD_LOGON },
1945 /* 1.3.6.1.4.1.311.21.5 */
1946 { szOID_KP_CA_EXCHANGE, IDS_PURPOSE_CA_EXCHANGE },
1947 /* 1.3.6.1.4.1.311.21.6 */
1948 { szOID_KP_KEY_RECOVERY_AGENT, IDS_PURPOSE_KEY_RECOVERY_AGENT },
1949 /* 1.3.6.1.4.1.311.21.19 */
1950 { szOID_DS_EMAIL_REPLICATION, IDS_PURPOSE_DS_EMAIL_REPLICATION },
1951 /* 1.3.6.1.5.5.7.3.1 */
1952 { szOID_PKIX_KP_SERVER_AUTH, IDS_PURPOSE_SERVER_AUTH },
1953 /* 1.3.6.1.5.5.7.3.2 */
1954 { szOID_PKIX_KP_CLIENT_AUTH, IDS_PURPOSE_CLIENT_AUTH },
1955 /* 1.3.6.1.5.5.7.3.3 */
1956 { szOID_PKIX_KP_CODE_SIGNING, IDS_PURPOSE_CODE_SIGNING },
1957 /* 1.3.6.1.5.5.7.3.4 */
1958 { szOID_PKIX_KP_EMAIL_PROTECTION, IDS_PURPOSE_EMAIL_PROTECTION },
1959 /* 1.3.6.1.5.5.7.3.5 */
1960 { szOID_PKIX_KP_IPSEC_END_SYSTEM, IDS_PURPOSE_IPSEC },
1961 /* 1.3.6.1.5.5.7.3.6 */
1962 { szOID_PKIX_KP_IPSEC_TUNNEL, IDS_PURPOSE_IPSEC },
1963 /* 1.3.6.1.5.5.7.3.7 */
1964 { szOID_PKIX_KP_IPSEC_USER, IDS_PURPOSE_IPSEC },
1965 /* 1.3.6.1.5.5.7.3.8 */
1966 { szOID_PKIX_KP_TIMESTAMP_SIGNING, IDS_PURPOSE_TIMESTAMP_SIGNING },
1969 static struct OIDToString *findSupportedOID(LPCSTR oid)
1971 int indexHigh = sizeof(oidMap) / sizeof(oidMap[0]) - 1, indexLow = 0, i;
1972 struct OIDToString *ret = NULL;
1974 for (i = (indexLow + indexHigh) / 2; !ret && indexLow <= indexHigh;
1975 i = (indexLow + indexHigh) / 2)
1977 int cmp;
1979 cmp = strcmp(oid, oidMap[i].oid);
1980 if (!cmp)
1981 ret = &oidMap[i];
1982 else if (cmp > 0)
1983 indexLow = i + 1;
1984 else
1985 indexHigh = i - 1;
1987 return ret;
1990 static void add_local_oid_text_to_control(HWND text, LPCSTR oid)
1992 struct OIDToString *entry;
1993 WCHAR nl = '\n';
1994 PARAFORMAT2 parFmt;
1996 parFmt.cbSize = sizeof(parFmt);
1997 parFmt.dwMask = PFM_STARTINDENT;
1998 parFmt.dxStartIndent = MY_INDENT * 3;
1999 if ((entry = findSupportedOID(oid)))
2001 WCHAR *str, *linebreak, *ptr;
2002 BOOL multiline = FALSE;
2003 int len;
2005 len = LoadStringW(hInstance, entry->id, (LPWSTR)&str, 0);
2006 ptr = str;
2007 do {
2008 if ((linebreak = memchrW(ptr, '\n', len)))
2010 WCHAR copy[MAX_STRING_LEN];
2012 multiline = TRUE;
2013 /* The source string contains a newline, which the richedit
2014 * control won't find since it's interpreted as a paragraph
2015 * break. Therefore copy up to the newline. lstrcpynW always
2016 * NULL-terminates, so pass one more than the length of the
2017 * source line so the copy includes the entire line and the
2018 * NULL-terminator.
2020 lstrcpynW(copy, ptr, linebreak - ptr + 1);
2021 add_text_with_paraformat_to_control(text, copy,
2022 linebreak - ptr, &parFmt);
2023 ptr = linebreak + 1;
2024 add_unformatted_text_to_control(text, &nl, 1);
2026 else if (multiline && *ptr)
2028 /* Add the last line */
2029 add_text_with_paraformat_to_control(text, ptr,
2030 len - (ptr - str), &parFmt);
2031 add_unformatted_text_to_control(text, &nl, 1);
2033 } while (linebreak);
2034 if (!multiline)
2036 add_text_with_paraformat_to_control(text, str, len, &parFmt);
2037 add_unformatted_text_to_control(text, &nl, 1);
2040 else
2042 WCHAR *oidW = HeapAlloc(GetProcessHeap(), 0,
2043 (strlen(oid) + 1) * sizeof(WCHAR));
2045 if (oidW)
2047 LPCSTR src;
2048 WCHAR *dst;
2050 for (src = oid, dst = oidW; *src; src++, dst++)
2051 *dst = *src;
2052 *dst = 0;
2053 add_text_with_paraformat_to_control(text, oidW, lstrlenW(oidW),
2054 &parFmt);
2055 add_unformatted_text_to_control(text, &nl, 1);
2056 HeapFree(GetProcessHeap(), 0, oidW);
2061 static void display_app_usages(HWND text, PCCERT_CONTEXT cert,
2062 BOOL *anyUsageAdded)
2064 static char any_app_policy[] = szOID_ANY_APPLICATION_POLICY;
2065 WCHAR nl = '\n';
2066 CHARFORMATW charFmt;
2067 PCERT_EXTENSION policyExt;
2068 if (!*anyUsageAdded)
2070 PARAFORMAT2 parFmt;
2072 parFmt.cbSize = sizeof(parFmt);
2073 parFmt.dwMask = PFM_STARTINDENT;
2074 parFmt.dxStartIndent = MY_INDENT;
2075 add_string_resource_with_paraformat_to_control(text,
2076 IDS_CERT_INFO_PURPOSES, &parFmt);
2077 add_unformatted_text_to_control(text, &nl, 1);
2078 *anyUsageAdded = TRUE;
2080 memset(&charFmt, 0, sizeof(charFmt));
2081 charFmt.cbSize = sizeof(charFmt);
2082 charFmt.dwMask = CFM_BOLD;
2083 charFmt.dwEffects = 0;
2084 SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2085 if ((policyExt = CertFindExtension(szOID_APPLICATION_CERT_POLICIES,
2086 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension)))
2088 CERT_POLICIES_INFO *policies;
2089 DWORD size;
2091 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_CERT_POLICIES,
2092 policyExt->Value.pbData, policyExt->Value.cbData,
2093 CRYPT_DECODE_ALLOC_FLAG, NULL, &policies, &size))
2095 DWORD i;
2097 for (i = 0; i < policies->cPolicyInfo; i++)
2099 DWORD j;
2101 for (j = 0; j < policies->rgPolicyInfo[i].cPolicyQualifier; j++)
2102 add_local_oid_text_to_control(text,
2103 policies->rgPolicyInfo[i].rgPolicyQualifier[j].
2104 pszPolicyQualifierId);
2106 LocalFree(policies);
2109 else
2110 add_oid_text_to_control(text, any_app_policy);
2113 static BOOL display_cert_usages(HWND text, PCCERT_CONTEXT cert,
2114 BOOL *anyUsageAdded)
2116 WCHAR nl = '\n';
2117 DWORD size;
2118 BOOL badUsages = FALSE;
2120 if (CertGetEnhancedKeyUsage(cert, 0, NULL, &size))
2122 CHARFORMATW charFmt;
2123 static char any_cert_policy[] = szOID_ANY_CERT_POLICY;
2124 PCERT_ENHKEY_USAGE usage = HeapAlloc(GetProcessHeap(), 0, size);
2126 if (usage)
2128 if (CertGetEnhancedKeyUsage(cert, 0, usage, &size))
2130 DWORD i;
2132 if (!*anyUsageAdded)
2134 PARAFORMAT2 parFmt;
2136 parFmt.cbSize = sizeof(parFmt);
2137 parFmt.dwMask = PFM_STARTINDENT;
2138 parFmt.dxStartIndent = MY_INDENT;
2139 add_string_resource_with_paraformat_to_control(text,
2140 IDS_CERT_INFO_PURPOSES, &parFmt);
2141 add_unformatted_text_to_control(text, &nl, 1);
2142 *anyUsageAdded = TRUE;
2144 memset(&charFmt, 0, sizeof(charFmt));
2145 charFmt.cbSize = sizeof(charFmt);
2146 charFmt.dwMask = CFM_BOLD;
2147 charFmt.dwEffects = 0;
2148 SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION,
2149 (LPARAM)&charFmt);
2150 if (!usage->cUsageIdentifier)
2151 add_oid_text_to_control(text, any_cert_policy);
2152 else
2153 for (i = 0; i < usage->cUsageIdentifier; i++)
2154 add_local_oid_text_to_control(text,
2155 usage->rgpszUsageIdentifier[i]);
2157 else
2158 badUsages = TRUE;
2159 HeapFree(GetProcessHeap(), 0, usage);
2161 else
2162 badUsages = TRUE;
2164 else
2165 badUsages = TRUE;
2166 return badUsages;
2169 static void set_policy_text(HWND text,
2170 PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo)
2172 BOOL includeCertUsages = FALSE, includeAppUsages = FALSE;
2173 BOOL badUsages = FALSE, anyUsageAdded = FALSE;
2175 if (pCertViewInfo->cPurposes)
2177 DWORD i;
2179 for (i = 0; i < pCertViewInfo->cPurposes; i++)
2181 if (!strcmp(pCertViewInfo->rgszPurposes[i], szOID_ANY_CERT_POLICY))
2182 includeCertUsages = TRUE;
2183 else if (!strcmp(pCertViewInfo->rgszPurposes[i],
2184 szOID_ANY_APPLICATION_POLICY))
2185 includeAppUsages = TRUE;
2186 else
2187 badUsages = TRUE;
2190 else
2191 includeAppUsages = includeCertUsages = TRUE;
2192 if (includeAppUsages)
2193 display_app_usages(text, pCertViewInfo->pCertContext, &anyUsageAdded);
2194 if (includeCertUsages)
2195 badUsages = display_cert_usages(text, pCertViewInfo->pCertContext,
2196 &anyUsageAdded);
2197 if (badUsages)
2199 PARAFORMAT2 parFmt;
2201 parFmt.cbSize = sizeof(parFmt);
2202 parFmt.dwMask = PFM_STARTINDENT;
2203 parFmt.dxStartIndent = MY_INDENT;
2204 add_string_resource_with_paraformat_to_control(text,
2205 IDS_CERT_INFO_BAD_PURPOSES, &parFmt);
2209 static CRYPT_OBJID_BLOB *find_policy_qualifier(CERT_POLICIES_INFO *policies,
2210 LPCSTR policyOid)
2212 CRYPT_OBJID_BLOB *ret = NULL;
2213 DWORD i;
2215 for (i = 0; !ret && i < policies->cPolicyInfo; i++)
2217 DWORD j;
2219 for (j = 0; !ret && j < policies->rgPolicyInfo[i].cPolicyQualifier; j++)
2220 if (!strcmp(policies->rgPolicyInfo[i].rgPolicyQualifier[j].
2221 pszPolicyQualifierId, policyOid))
2222 ret = &policies->rgPolicyInfo[i].rgPolicyQualifier[j].
2223 Qualifier;
2225 return ret;
2228 static WCHAR *get_cps_str_from_qualifier(const CRYPT_OBJID_BLOB *qualifier)
2230 LPWSTR qualifierStr = NULL;
2231 CERT_NAME_VALUE *qualifierValue;
2232 DWORD size;
2234 if (CryptDecodeObjectEx(X509_ASN_ENCODING, X509_NAME_VALUE,
2235 qualifier->pbData, qualifier->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
2236 &qualifierValue, &size))
2238 size = CertRDNValueToStrW(qualifierValue->dwValueType,
2239 &qualifierValue->Value, NULL, 0);
2240 qualifierStr = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
2241 if (qualifierStr)
2242 CertRDNValueToStrW(qualifierValue->dwValueType,
2243 &qualifierValue->Value, qualifierStr, size);
2244 LocalFree(qualifierValue);
2246 return qualifierStr;
2249 static WCHAR *get_user_notice_from_qualifier(const CRYPT_OBJID_BLOB *qualifier)
2251 LPWSTR str = NULL;
2252 CERT_POLICY_QUALIFIER_USER_NOTICE *qualifierValue;
2253 DWORD size;
2255 if (CryptDecodeObjectEx(X509_ASN_ENCODING,
2256 X509_PKIX_POLICY_QUALIFIER_USERNOTICE,
2257 qualifier->pbData, qualifier->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
2258 &qualifierValue, &size))
2260 str = HeapAlloc(GetProcessHeap(), 0,
2261 (strlenW(qualifierValue->pszDisplayText) + 1) * sizeof(WCHAR));
2262 if (str)
2263 strcpyW(str, qualifierValue->pszDisplayText);
2264 LocalFree(qualifierValue);
2266 return str;
2269 struct IssuerStatement
2271 LPWSTR cps;
2272 LPWSTR userNotice;
2275 static void set_issuer_statement(HWND hwnd,
2276 PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo)
2278 PCERT_EXTENSION policyExt;
2280 if (!(pCertViewInfo->dwFlags & CRYPTUI_DISABLE_ISSUERSTATEMENT) &&
2281 (policyExt = CertFindExtension(szOID_CERT_POLICIES,
2282 pCertViewInfo->pCertContext->pCertInfo->cExtension,
2283 pCertViewInfo->pCertContext->pCertInfo->rgExtension)))
2285 CERT_POLICIES_INFO *policies;
2286 DWORD size;
2288 if (CryptDecodeObjectEx(X509_ASN_ENCODING, policyExt->pszObjId,
2289 policyExt->Value.pbData, policyExt->Value.cbData,
2290 CRYPT_DECODE_ALLOC_FLAG, NULL, &policies, &size))
2292 CRYPT_OBJID_BLOB *qualifier;
2293 LPWSTR cps = NULL, userNotice = NULL;
2295 if ((qualifier = find_policy_qualifier(policies,
2296 szOID_PKIX_POLICY_QUALIFIER_CPS)))
2297 cps = get_cps_str_from_qualifier(qualifier);
2298 if ((qualifier = find_policy_qualifier(policies,
2299 szOID_PKIX_POLICY_QUALIFIER_USERNOTICE)))
2300 userNotice = get_user_notice_from_qualifier(qualifier);
2301 if (cps || userNotice)
2303 struct IssuerStatement *issuerStatement =
2304 HeapAlloc(GetProcessHeap(), 0, sizeof(struct IssuerStatement));
2306 if (issuerStatement)
2308 issuerStatement->cps = cps;
2309 issuerStatement->userNotice = userNotice;
2310 EnableWindow(GetDlgItem(hwnd, IDC_ISSUERSTATEMENT), TRUE);
2311 SetWindowLongPtrW(hwnd, DWLP_USER,
2312 (ULONG_PTR)issuerStatement);
2315 LocalFree(policies);
2320 static void set_cert_info(HWND hwnd,
2321 PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo)
2323 CHARFORMATW charFmt;
2324 PARAFORMAT2 parFmt;
2325 HWND icon = GetDlgItem(hwnd, IDC_CERTIFICATE_ICON);
2326 HWND text = GetDlgItem(hwnd, IDC_CERTIFICATE_INFO);
2327 CRYPT_PROVIDER_SGNR *provSigner = WTHelperGetProvSignerFromChain(
2328 (CRYPT_PROVIDER_DATA *)pCertViewInfo->u.pCryptProviderData,
2329 pCertViewInfo->idxSigner, pCertViewInfo->fCounterSigner,
2330 pCertViewInfo->idxCounterSigner);
2331 CRYPT_PROVIDER_CERT *root =
2332 &provSigner->pasCertChain[provSigner->csCertChain - 1];
2334 if (!provSigner->pChainContext ||
2335 (provSigner->pChainContext->TrustStatus.dwErrorStatus &
2336 CERT_TRUST_IS_PARTIAL_CHAIN))
2337 add_icon_to_control(icon, IDB_CERT_WARNING);
2338 else if (!root->fTrustedRoot)
2339 add_icon_to_control(icon, IDB_CERT_ERROR);
2340 else
2341 add_icon_to_control(icon, IDB_CERT);
2343 memset(&charFmt, 0, sizeof(charFmt));
2344 charFmt.cbSize = sizeof(charFmt);
2345 charFmt.dwMask = CFM_BOLD;
2346 charFmt.dwEffects = CFE_BOLD;
2347 SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2348 /* FIXME: vertically center text */
2349 parFmt.cbSize = sizeof(parFmt);
2350 parFmt.dwMask = PFM_STARTINDENT;
2351 parFmt.dxStartIndent = MY_INDENT;
2352 add_string_resource_with_paraformat_to_control(text,
2353 IDS_CERTIFICATEINFORMATION, &parFmt);
2355 text = GetDlgItem(hwnd, IDC_CERTIFICATE_STATUS);
2356 SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2357 if (provSigner->dwError == TRUST_E_CERT_SIGNATURE)
2358 add_string_resource_with_paraformat_to_control(text,
2359 IDS_CERT_INFO_BAD_SIG, &parFmt);
2360 else if (!provSigner->pChainContext ||
2361 (provSigner->pChainContext->TrustStatus.dwErrorStatus &
2362 CERT_TRUST_IS_PARTIAL_CHAIN))
2363 add_string_resource_with_paraformat_to_control(text,
2364 IDS_CERT_INFO_PARTIAL_CHAIN, &parFmt);
2365 else if (!root->fTrustedRoot)
2367 if (provSigner->csCertChain == 1 && root->fSelfSigned)
2368 add_string_resource_with_paraformat_to_control(text,
2369 IDS_CERT_INFO_UNTRUSTED_CA, &parFmt);
2370 else
2371 add_string_resource_with_paraformat_to_control(text,
2372 IDS_CERT_INFO_UNTRUSTED_ROOT, &parFmt);
2374 else
2376 set_policy_text(text, pCertViewInfo);
2377 set_issuer_statement(hwnd, pCertViewInfo);
2381 static void set_cert_name_string(HWND hwnd, PCCERT_CONTEXT cert,
2382 DWORD nameFlags, int heading)
2384 WCHAR nl = '\n';
2385 HWND text = GetDlgItem(hwnd, IDC_CERTIFICATE_NAMES);
2386 CHARFORMATW charFmt;
2387 PARAFORMAT2 parFmt;
2389 memset(&charFmt, 0, sizeof(charFmt));
2390 charFmt.cbSize = sizeof(charFmt);
2391 charFmt.dwMask = CFM_BOLD;
2392 charFmt.dwEffects = CFE_BOLD;
2393 SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2394 parFmt.cbSize = sizeof(parFmt);
2395 parFmt.dwMask = PFM_STARTINDENT;
2396 parFmt.dxStartIndent = MY_INDENT * 3;
2397 add_string_resource_with_paraformat_to_control(text, heading, &parFmt);
2398 charFmt.dwEffects = 0;
2399 SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2400 add_cert_string_to_control(text, cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
2401 nameFlags);
2402 add_unformatted_text_to_control(text, &nl, 1);
2403 add_unformatted_text_to_control(text, &nl, 1);
2404 add_unformatted_text_to_control(text, &nl, 1);
2408 static void add_date_string_to_control(HWND hwnd, const FILETIME *fileTime)
2410 WCHAR dateFmt[80]; /* sufficient for all versions of LOCALE_SSHORTDATE */
2411 WCHAR date[80];
2412 SYSTEMTIME sysTime;
2414 GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SSHORTDATE, dateFmt,
2415 sizeof(dateFmt) / sizeof(dateFmt[0]));
2416 FileTimeToSystemTime(fileTime, &sysTime);
2417 GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, date,
2418 sizeof(date) / sizeof(date[0]));
2419 add_unformatted_text_to_control(hwnd, date, lstrlenW(date));
2422 static void set_cert_validity_period(HWND hwnd, PCCERT_CONTEXT cert)
2424 WCHAR nl = '\n';
2425 HWND text = GetDlgItem(hwnd, IDC_CERTIFICATE_NAMES);
2426 CHARFORMATW charFmt;
2427 PARAFORMAT2 parFmt;
2429 memset(&charFmt, 0, sizeof(charFmt));
2430 charFmt.cbSize = sizeof(charFmt);
2431 charFmt.dwMask = CFM_BOLD;
2432 charFmt.dwEffects = CFE_BOLD;
2433 SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2434 parFmt.cbSize = sizeof(parFmt);
2435 parFmt.dwMask = PFM_STARTINDENT;
2436 parFmt.dxStartIndent = MY_INDENT * 3;
2437 add_string_resource_with_paraformat_to_control(text, IDS_VALID_FROM,
2438 &parFmt);
2439 charFmt.dwEffects = 0;
2440 SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2441 add_date_string_to_control(text, &cert->pCertInfo->NotBefore);
2442 charFmt.dwEffects = CFE_BOLD;
2443 SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2444 add_string_resource_to_control(text, IDS_VALID_TO);
2445 charFmt.dwEffects = 0;
2446 SendMessageW(text, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&charFmt);
2447 add_date_string_to_control(text, &cert->pCertInfo->NotAfter);
2448 add_unformatted_text_to_control(text, &nl, 1);
2451 static void set_general_info(HWND hwnd,
2452 PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo)
2454 set_cert_info(hwnd, pCertViewInfo);
2455 set_cert_name_string(hwnd, pCertViewInfo->pCertContext, 0,
2456 IDS_SUBJECT_HEADING);
2457 set_cert_name_string(hwnd, pCertViewInfo->pCertContext,
2458 CERT_NAME_ISSUER_FLAG, IDS_ISSUER_HEADING);
2459 set_cert_validity_period(hwnd, pCertViewInfo->pCertContext);
2462 static LRESULT CALLBACK user_notice_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
2463 LPARAM lp)
2465 LRESULT ret = 0;
2466 HWND text;
2467 struct IssuerStatement *issuerStatement;
2469 switch (msg)
2471 case WM_INITDIALOG:
2472 text = GetDlgItem(hwnd, IDC_USERNOTICE);
2473 issuerStatement = (struct IssuerStatement *)lp;
2474 add_unformatted_text_to_control(text, issuerStatement->userNotice,
2475 strlenW(issuerStatement->userNotice));
2476 if (issuerStatement->cps)
2477 SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)issuerStatement->cps);
2478 else
2479 EnableWindow(GetDlgItem(hwnd, IDC_CPS), FALSE);
2480 break;
2481 case WM_COMMAND:
2482 switch (wp)
2484 case IDOK:
2485 EndDialog(hwnd, IDOK);
2486 ret = TRUE;
2487 break;
2488 case IDC_CPS:
2490 IBindCtx *bctx = NULL;
2491 LPWSTR cps;
2493 CreateBindCtx(0, &bctx);
2494 cps = (LPWSTR)GetWindowLongPtrW(hwnd, DWLP_USER);
2495 HlinkSimpleNavigateToString(cps, NULL, NULL, NULL, bctx, NULL,
2496 HLNF_OPENINNEWWINDOW, 0);
2497 IBindCtx_Release(bctx);
2498 break;
2502 return ret;
2505 static void show_user_notice(HWND hwnd, struct IssuerStatement *issuerStatement)
2507 DialogBoxParamW(hInstance, MAKEINTRESOURCEW(IDD_USERNOTICE), hwnd,
2508 user_notice_dlg_proc, (LPARAM)issuerStatement);
2511 static LRESULT CALLBACK general_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
2512 LPARAM lp)
2514 PROPSHEETPAGEW *page;
2515 PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo;
2517 TRACE("(%p, %08x, %08lx, %08lx)\n", hwnd, msg, wp, lp);
2519 switch (msg)
2521 case WM_INITDIALOG:
2522 page = (PROPSHEETPAGEW *)lp;
2523 pCertViewInfo = (PCCRYPTUI_VIEWCERTIFICATE_STRUCTW)page->lParam;
2524 if (pCertViewInfo->dwFlags & CRYPTUI_DISABLE_ADDTOSTORE)
2525 ShowWindow(GetDlgItem(hwnd, IDC_ADDTOSTORE), FALSE);
2526 EnableWindow(GetDlgItem(hwnd, IDC_ISSUERSTATEMENT), FALSE);
2527 set_general_info(hwnd, pCertViewInfo);
2528 break;
2529 case WM_COMMAND:
2530 switch (wp)
2532 case IDC_ADDTOSTORE:
2533 CryptUIWizImport(0, hwnd, NULL, NULL, NULL);
2534 break;
2535 case IDC_ISSUERSTATEMENT:
2537 struct IssuerStatement *issuerStatement =
2538 (struct IssuerStatement *)GetWindowLongPtrW(hwnd, DWLP_USER);
2540 if (issuerStatement)
2542 if (issuerStatement->userNotice)
2543 show_user_notice(hwnd, issuerStatement);
2544 else if (issuerStatement->cps)
2546 IBindCtx *bctx = NULL;
2548 CreateBindCtx(0, &bctx);
2549 HlinkSimpleNavigateToString(issuerStatement->cps, NULL,
2550 NULL, NULL, bctx, NULL, HLNF_OPENINNEWWINDOW, 0);
2551 IBindCtx_Release(bctx);
2554 break;
2557 break;
2559 return 0;
2562 static UINT CALLBACK general_callback_proc(HWND hwnd, UINT msg,
2563 PROPSHEETPAGEW *page)
2565 struct IssuerStatement *issuerStatement;
2567 switch (msg)
2569 case PSPCB_RELEASE:
2570 issuerStatement =
2571 (struct IssuerStatement *)GetWindowLongPtrW(hwnd, DWLP_USER);
2572 if (issuerStatement)
2574 HeapFree(GetProcessHeap(), 0, issuerStatement->cps);
2575 HeapFree(GetProcessHeap(), 0, issuerStatement->userNotice);
2576 HeapFree(GetProcessHeap(), 0, issuerStatement);
2578 break;
2580 return 1;
2583 static void init_general_page(PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo,
2584 PROPSHEETPAGEW *page)
2586 memset(page, 0, sizeof(PROPSHEETPAGEW));
2587 page->dwSize = sizeof(PROPSHEETPAGEW);
2588 page->dwFlags = PSP_USECALLBACK;
2589 page->pfnCallback = general_callback_proc;
2590 page->hInstance = hInstance;
2591 page->u.pszTemplate = MAKEINTRESOURCEW(IDD_GENERAL);
2592 page->pfnDlgProc = general_dlg_proc;
2593 page->lParam = (LPARAM)pCertViewInfo;
2596 typedef WCHAR * (*field_format_func)(PCCERT_CONTEXT cert);
2598 static WCHAR *field_format_version(PCCERT_CONTEXT cert)
2600 static const WCHAR fmt[] = { 'V','%','d',0 };
2601 WCHAR *buf = HeapAlloc(GetProcessHeap(), 0, 12 * sizeof(WCHAR));
2603 if (buf)
2604 sprintfW(buf, fmt, cert->pCertInfo->dwVersion);
2605 return buf;
2608 static WCHAR *format_hex_string(void *pb, DWORD cb)
2610 WCHAR *buf = HeapAlloc(GetProcessHeap(), 0, (cb * 3 + 1) * sizeof(WCHAR));
2612 if (buf)
2614 static const WCHAR fmt[] = { '%','0','2','x',' ',0 };
2615 DWORD i;
2616 WCHAR *ptr;
2618 for (i = 0, ptr = buf; i < cb; i++, ptr += 3)
2619 sprintfW(ptr, fmt, ((BYTE *)pb)[i]);
2621 return buf;
2624 static WCHAR *field_format_serial_number(PCCERT_CONTEXT cert)
2626 return format_hex_string(cert->pCertInfo->SerialNumber.pbData,
2627 cert->pCertInfo->SerialNumber.cbData);
2630 static WCHAR *field_format_issuer(PCCERT_CONTEXT cert)
2632 return get_cert_name_string(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE,
2633 CERT_NAME_ISSUER_FLAG);
2636 static WCHAR *field_format_detailed_cert_name(PCERT_NAME_BLOB name)
2638 WCHAR *str = NULL;
2639 DWORD len = CertNameToStrW(X509_ASN_ENCODING, name,
2640 CERT_X500_NAME_STR | CERT_NAME_STR_CRLF_FLAG, NULL, 0);
2642 if (len)
2644 str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
2645 if (str)
2646 CertNameToStrW(X509_ASN_ENCODING, name,
2647 CERT_X500_NAME_STR | CERT_NAME_STR_CRLF_FLAG, str, len);
2649 return str;
2652 static WCHAR *field_format_detailed_issuer(PCCERT_CONTEXT cert, void *param)
2654 return field_format_detailed_cert_name(&cert->pCertInfo->Issuer);
2657 static WCHAR *field_format_subject(PCCERT_CONTEXT cert)
2659 return get_cert_name_string(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0);
2662 static WCHAR *field_format_detailed_subject(PCCERT_CONTEXT cert, void *param)
2664 return field_format_detailed_cert_name(&cert->pCertInfo->Subject);
2667 static WCHAR *format_long_date(const FILETIME *fileTime)
2669 WCHAR dateFmt[80]; /* long enough for LOCALE_SLONGDATE */
2670 DWORD len;
2671 WCHAR *buf = NULL;
2672 SYSTEMTIME sysTime;
2674 /* FIXME: format isn't quite right, want time too */
2675 GetLocaleInfoW(LOCALE_SYSTEM_DEFAULT, LOCALE_SLONGDATE, dateFmt,
2676 sizeof(dateFmt) / sizeof(dateFmt[0]));
2677 FileTimeToSystemTime(fileTime, &sysTime);
2678 len = GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, NULL, 0);
2679 if (len)
2681 buf = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
2682 if (buf)
2683 GetDateFormatW(LOCALE_SYSTEM_DEFAULT, 0, &sysTime, dateFmt, buf,
2684 len);
2686 return buf;
2689 static WCHAR *field_format_from_date(PCCERT_CONTEXT cert)
2691 return format_long_date(&cert->pCertInfo->NotBefore);
2694 static WCHAR *field_format_to_date(PCCERT_CONTEXT cert)
2696 return format_long_date(&cert->pCertInfo->NotAfter);
2699 static WCHAR *field_format_public_key(PCCERT_CONTEXT cert)
2701 PCCRYPT_OID_INFO oidInfo;
2702 WCHAR *buf = NULL;
2704 oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
2705 cert->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId, 0);
2706 if (oidInfo)
2708 WCHAR fmt[MAX_STRING_LEN];
2710 if (LoadStringW(hInstance, IDS_FIELD_PUBLIC_KEY_FORMAT, fmt,
2711 sizeof(fmt) / sizeof(fmt[0])))
2713 /* Allocate the output buffer. Use the number of bytes in the
2714 * public key as a conservative (high) estimate for the number of
2715 * digits in its output.
2716 * The output is of the form (in English)
2717 * "<public key algorithm> (<public key bit length> bits)".
2718 * Ordinarily having two positional parameters in a string is not a
2719 * good idea, but as this isn't a sentence fragment, it shouldn't
2720 * be word-order dependent.
2722 buf = HeapAlloc(GetProcessHeap(), 0,
2723 (strlenW(fmt) + strlenW(oidInfo->pwszName) +
2724 cert->pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData * 8)
2725 * sizeof(WCHAR));
2726 if (buf)
2727 sprintfW(buf, fmt, oidInfo->pwszName,
2728 CertGetPublicKeyLength(X509_ASN_ENCODING,
2729 &cert->pCertInfo->SubjectPublicKeyInfo));
2732 return buf;
2735 static WCHAR *field_format_detailed_public_key(PCCERT_CONTEXT cert, void *param)
2737 return format_hex_string(
2738 cert->pCertInfo->SubjectPublicKeyInfo.PublicKey.pbData,
2739 cert->pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData);
2742 struct field_value_data;
2743 struct detail_data
2745 PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo;
2746 BOOL *pfPropertiesChanged;
2747 int cFields;
2748 struct field_value_data *fields;
2751 typedef void (*add_fields_func)(HWND hwnd, struct detail_data *data);
2753 typedef WCHAR *(*create_detailed_value_func)(PCCERT_CONTEXT cert, void *param);
2755 struct field_value_data
2757 create_detailed_value_func create;
2758 LPWSTR detailed_value;
2759 void *param;
2762 static void add_field_value_data(struct detail_data *data,
2763 create_detailed_value_func create, void *param)
2765 if (data->cFields)
2766 data->fields = HeapReAlloc(GetProcessHeap(), 0, data->fields,
2767 (data->cFields + 1) * sizeof(struct field_value_data));
2768 else
2769 data->fields = HeapAlloc(GetProcessHeap(), 0,
2770 sizeof(struct field_value_data));
2771 if (data->fields)
2773 data->fields[data->cFields].create = create;
2774 data->fields[data->cFields].detailed_value = NULL;
2775 data->fields[data->cFields].param = param;
2776 data->cFields++;
2780 static void add_field_and_value_to_list(HWND hwnd, struct detail_data *data,
2781 LPWSTR field, LPWSTR value, create_detailed_value_func create, void *param)
2783 LVITEMW item;
2784 int iItem = SendMessageW(hwnd, LVM_GETITEMCOUNT, 0, 0);
2786 item.mask = LVIF_TEXT | LVIF_PARAM;
2787 item.iItem = iItem;
2788 item.iSubItem = 0;
2789 item.pszText = field;
2790 item.lParam = (LPARAM)data;
2791 SendMessageW(hwnd, LVM_INSERTITEMW, 0, (LPARAM)&item);
2792 if (value)
2794 item.pszText = value;
2795 item.iSubItem = 1;
2796 SendMessageW(hwnd, LVM_SETITEMTEXTW, iItem, (LPARAM)&item);
2798 add_field_value_data(data, create, param);
2801 static void add_string_id_and_value_to_list(HWND hwnd, struct detail_data *data,
2802 int id, LPWSTR value, create_detailed_value_func create, void *param)
2804 WCHAR buf[MAX_STRING_LEN];
2806 LoadStringW(hInstance, id, buf, sizeof(buf) / sizeof(buf[0]));
2807 add_field_and_value_to_list(hwnd, data, buf, value, create, param);
2810 struct v1_field
2812 int id;
2813 field_format_func format;
2814 create_detailed_value_func create_detailed_value;
2817 static void add_v1_field(HWND hwnd, struct detail_data *data,
2818 const struct v1_field *field)
2820 WCHAR *val = field->format(data->pCertViewInfo->pCertContext);
2822 if (val)
2824 add_string_id_and_value_to_list(hwnd, data, field->id, val,
2825 field->create_detailed_value, NULL);
2826 HeapFree(GetProcessHeap(), 0, val);
2830 static const struct v1_field v1_fields[] = {
2831 { IDS_FIELD_VERSION, field_format_version, NULL },
2832 { IDS_FIELD_SERIAL_NUMBER, field_format_serial_number, NULL },
2833 { IDS_FIELD_ISSUER, field_format_issuer, field_format_detailed_issuer },
2834 { IDS_FIELD_VALID_FROM, field_format_from_date, NULL },
2835 { IDS_FIELD_VALID_TO, field_format_to_date, NULL },
2836 { IDS_FIELD_SUBJECT, field_format_subject, field_format_detailed_subject },
2837 { IDS_FIELD_PUBLIC_KEY, field_format_public_key,
2838 field_format_detailed_public_key }
2841 static void add_v1_fields(HWND hwnd, struct detail_data *data)
2843 int i;
2844 PCCERT_CONTEXT cert = data->pCertViewInfo->pCertContext;
2846 /* The last item in v1_fields is the public key, which is not in the loop
2847 * because it's a special case.
2849 for (i = 0; i < sizeof(v1_fields) / sizeof(v1_fields[0]) - 1; i++)
2850 add_v1_field(hwnd, data, &v1_fields[i]);
2851 if (cert->pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData)
2852 add_v1_field(hwnd, data, &v1_fields[i]);
2855 static WCHAR *crypt_format_extension(const CERT_EXTENSION *ext, DWORD formatStrType)
2857 WCHAR *str = NULL;
2858 DWORD size;
2860 if (CryptFormatObject(X509_ASN_ENCODING, 0, formatStrType, NULL,
2861 ext->pszObjId, ext->Value.pbData, ext->Value.cbData, NULL, &size))
2863 str = HeapAlloc(GetProcessHeap(), 0, size);
2864 CryptFormatObject(X509_ASN_ENCODING, 0, formatStrType, NULL,
2865 ext->pszObjId, ext->Value.pbData, ext->Value.cbData, str, &size);
2867 return str;
2870 static WCHAR *field_format_extension_hex_with_ascii(const CERT_EXTENSION *ext)
2872 WCHAR *str = NULL;
2874 if (ext->Value.cbData)
2876 /* The output is formatted as:
2877 * <hex bytes> <ascii bytes>\n
2878 * where <hex bytes> is a string of up to 8 bytes, output as %02x,
2879 * and <ascii bytes> is the ASCII equivalent of each byte, or '.' if
2880 * the byte is not printable.
2881 * So, for example, the extension value consisting of the following
2882 * bytes:
2883 * 0x30,0x14,0x31,0x12,0x30,0x10,0x06,0x03,0x55,0x04,0x03,
2884 * 0x13,0x09,0x4a,0x75,0x61,0x6e,0x20,0x4c,0x61,0x6e,0x67
2885 * is output as:
2886 * 30 14 31 12 30 10 06 03 0.1.0...
2887 * 55 04 03 13 09 4a 75 61 U....Jua
2888 * 6e 20 4c 61 6e 67 n Lang
2889 * The allocation size therefore requires:
2890 * - 4 characters per character in an 8-byte line
2891 * (2 for the hex format, one for the space, one for the ASCII value)
2892 * - 3 more characters per 8-byte line (two spaces and a newline)
2893 * - 1 character for the terminating nul
2894 * FIXME: should use a fixed-width font for this
2896 DWORD lines = (ext->Value.cbData + 7) / 8;
2898 str = HeapAlloc(GetProcessHeap(), 0,
2899 (lines * 8 * 4 + lines * 3 + 1) * sizeof(WCHAR));
2900 if (str)
2902 static const WCHAR fmt[] = { '%','0','2','x',' ',0 };
2903 DWORD i, j;
2904 WCHAR *ptr;
2906 for (i = 0, ptr = str; i < ext->Value.cbData; i += 8)
2908 /* Output as hex bytes first */
2909 for (j = i; j < min(i + 8, ext->Value.cbData); j++, ptr += 3)
2910 sprintfW(ptr, fmt, ext->Value.pbData[j]);
2911 /* Pad the hex output with spaces for alignment */
2912 if (j == ext->Value.cbData && j % 8)
2914 static const WCHAR pad[] = { ' ',' ',' ' };
2916 for (; j % 8; j++, ptr += sizeof(pad) / sizeof(pad[0]))
2917 memcpy(ptr, pad, sizeof(pad));
2919 /* The last sprintfW included a space, so just insert one
2920 * more space between the hex bytes and the ASCII output
2922 *ptr++ = ' ';
2923 /* Output as ASCII bytes */
2924 for (j = i; j < min(i + 8, ext->Value.cbData); j++, ptr++)
2926 if (isprintW(ext->Value.pbData[j]) &&
2927 !isspaceW(ext->Value.pbData[j]))
2928 *ptr = ext->Value.pbData[j];
2929 else
2930 *ptr = '.';
2932 *ptr++ = '\n';
2934 *ptr++ = '\0';
2937 return str;
2940 static WCHAR *field_format_detailed_extension(PCCERT_CONTEXT cert, void *param)
2942 PCERT_EXTENSION ext = param;
2943 LPWSTR str = crypt_format_extension(ext,
2944 CRYPT_FORMAT_STR_MULTI_LINE | CRYPT_FORMAT_STR_NO_HEX);
2946 if (!str)
2947 str = field_format_extension_hex_with_ascii(ext);
2948 return str;
2951 static void add_cert_extension_detail(HWND hwnd, struct detail_data *data,
2952 PCERT_EXTENSION ext)
2954 PCCRYPT_OID_INFO oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
2955 ext->pszObjId, 0);
2956 LPWSTR val = crypt_format_extension(ext, 0);
2958 if (oidInfo)
2959 add_field_and_value_to_list(hwnd, data, (LPWSTR)oidInfo->pwszName,
2960 val, field_format_detailed_extension, ext);
2961 else
2963 DWORD len = strlen(ext->pszObjId);
2964 LPWSTR oidW = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
2966 if (oidW)
2968 DWORD i;
2970 for (i = 0; i <= len; i++)
2971 oidW[i] = ext->pszObjId[i];
2972 add_field_and_value_to_list(hwnd, data, oidW, val,
2973 field_format_detailed_extension, ext);
2974 HeapFree(GetProcessHeap(), 0, oidW);
2977 HeapFree(GetProcessHeap(), 0, val);
2980 static void add_all_extensions(HWND hwnd, struct detail_data *data)
2982 DWORD i;
2983 PCCERT_CONTEXT cert = data->pCertViewInfo->pCertContext;
2985 for (i = 0; i < cert->pCertInfo->cExtension; i++)
2986 add_cert_extension_detail(hwnd, data, &cert->pCertInfo->rgExtension[i]);
2989 static void add_critical_extensions(HWND hwnd, struct detail_data *data)
2991 DWORD i;
2992 PCCERT_CONTEXT cert = data->pCertViewInfo->pCertContext;
2994 for (i = 0; i < cert->pCertInfo->cExtension; i++)
2995 if (cert->pCertInfo->rgExtension[i].fCritical)
2996 add_cert_extension_detail(hwnd, data,
2997 &cert->pCertInfo->rgExtension[i]);
3000 typedef WCHAR * (*prop_to_value_func)(void *pb, DWORD cb);
3002 struct prop_id_to_string_id
3004 DWORD prop;
3005 int id;
3006 BOOL prop_is_string;
3007 prop_to_value_func prop_to_value;
3010 static WCHAR *format_enhanced_key_usage_value(void *pb, DWORD cb)
3012 CERT_EXTENSION ext;
3014 ext.pszObjId = (LPSTR)X509_ENHANCED_KEY_USAGE;
3015 ext.fCritical = FALSE;
3016 ext.Value.pbData = pb;
3017 ext.Value.cbData = cb;
3018 return crypt_format_extension(&ext, 0);
3021 /* Logically the access state should also be checked, and IDC_EDITPROPERTIES
3022 * disabled for read-only certificates, but native doesn't appear to do that.
3024 static const struct prop_id_to_string_id prop_id_map[] = {
3025 { CERT_HASH_PROP_ID, IDS_PROP_HASH, FALSE, format_hex_string },
3026 { CERT_FRIENDLY_NAME_PROP_ID, IDS_PROP_FRIENDLY_NAME, TRUE, NULL },
3027 { CERT_DESCRIPTION_PROP_ID, IDS_PROP_DESCRIPTION, TRUE, NULL },
3028 { CERT_ENHKEY_USAGE_PROP_ID, IDS_PROP_ENHKEY_USAGE, FALSE,
3029 format_enhanced_key_usage_value },
3032 static void add_properties(HWND hwnd, struct detail_data *data)
3034 DWORD i;
3035 PCCERT_CONTEXT cert = data->pCertViewInfo->pCertContext;
3037 for (i = 0; i < sizeof(prop_id_map) / sizeof(prop_id_map[0]); i++)
3039 DWORD cb;
3041 if (CertGetCertificateContextProperty(cert, prop_id_map[i].prop, NULL,
3042 &cb))
3044 BYTE *pb;
3045 WCHAR *val = NULL;
3047 /* FIXME: MS adds a separate value for the signature hash
3048 * algorithm.
3050 pb = HeapAlloc(GetProcessHeap(), 0, cb);
3051 if (pb)
3053 if (CertGetCertificateContextProperty(cert,
3054 prop_id_map[i].prop, pb, &cb))
3056 if (prop_id_map[i].prop_is_string)
3058 val = (LPWSTR)pb;
3059 /* Don't double-free pb */
3060 pb = NULL;
3062 else
3063 val = prop_id_map[i].prop_to_value(pb, cb);
3065 HeapFree(GetProcessHeap(), 0, pb);
3067 add_string_id_and_value_to_list(hwnd, data, prop_id_map[i].id, val,
3068 NULL, NULL);
3073 static void add_all_fields(HWND hwnd, struct detail_data *data)
3075 add_v1_fields(hwnd, data);
3076 add_all_extensions(hwnd, data);
3077 add_properties(hwnd, data);
3080 struct selection_list_item
3082 int id;
3083 add_fields_func add;
3086 const struct selection_list_item listItems[] = {
3087 { IDS_FIELDS_ALL, add_all_fields },
3088 { IDS_FIELDS_V1, add_v1_fields },
3089 { IDS_FIELDS_EXTENSIONS, add_all_extensions },
3090 { IDS_FIELDS_CRITICAL_EXTENSIONS, add_critical_extensions },
3091 { IDS_FIELDS_PROPERTIES, add_properties },
3094 static void create_show_list(HWND hwnd, struct detail_data *data)
3096 HWND cb = GetDlgItem(hwnd, IDC_DETAIL_SELECT);
3097 WCHAR buf[MAX_STRING_LEN];
3098 int i;
3100 for (i = 0; i < sizeof(listItems) / sizeof(listItems[0]); i++)
3102 int index;
3104 LoadStringW(hInstance, listItems[i].id, buf,
3105 sizeof(buf) / sizeof(buf[0]));
3106 index = SendMessageW(cb, CB_INSERTSTRING, -1, (LPARAM)buf);
3107 SendMessageW(cb, CB_SETITEMDATA, index, (LPARAM)data);
3109 SendMessageW(cb, CB_SETCURSEL, 0, 0);
3112 static void create_listview_columns(HWND hwnd)
3114 HWND lv = GetDlgItem(hwnd, IDC_DETAIL_LIST);
3115 RECT rc;
3116 WCHAR buf[MAX_STRING_LEN];
3117 LVCOLUMNW column;
3119 SendMessageW(lv, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT);
3120 GetWindowRect(lv, &rc);
3121 LoadStringW(hInstance, IDS_FIELD, buf, sizeof(buf) / sizeof(buf[0]));
3122 column.mask = LVCF_WIDTH | LVCF_TEXT;
3123 column.cx = (rc.right - rc.left) / 2 - 2;
3124 column.pszText = buf;
3125 SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
3126 LoadStringW(hInstance, IDS_VALUE, buf, sizeof(buf) / sizeof(buf[0]));
3127 SendMessageW(lv, LVM_INSERTCOLUMNW, 1, (LPARAM)&column);
3130 static void set_fields_selection(HWND hwnd, struct detail_data *data, int sel)
3132 HWND list = GetDlgItem(hwnd, IDC_DETAIL_LIST);
3134 if (sel >= 0 && sel < sizeof(listItems) / sizeof(listItems[0]))
3136 SendMessageW(list, LVM_DELETEALLITEMS, 0, 0);
3137 listItems[sel].add(list, data);
3141 static void create_cert_details_list(HWND hwnd, struct detail_data *data)
3143 create_show_list(hwnd, data);
3144 create_listview_columns(hwnd);
3145 set_fields_selection(hwnd, data, 0);
3148 static void add_purpose(HWND hwnd, LPCSTR oid)
3150 HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
3151 PCRYPT_OID_INFO info = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
3152 sizeof(CRYPT_OID_INFO));
3154 if (info)
3156 char *oidCopy = HeapAlloc(GetProcessHeap(), 0, strlen(oid) + 1);
3158 if (oidCopy)
3160 LVITEMA item;
3162 strcpy(oidCopy, oid);
3163 info->cbSize = sizeof(CRYPT_OID_INFO);
3164 info->pszOID = oidCopy;
3165 item.mask = LVIF_TEXT | LVIF_STATE | LVIF_PARAM;
3166 item.state = INDEXTOSTATEIMAGEMASK(CheckBitmapIndexChecked);
3167 item.stateMask = LVIS_STATEIMAGEMASK;
3168 item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
3169 item.iSubItem = 0;
3170 item.lParam = (LPARAM)info;
3171 item.pszText = oidCopy;
3172 SendMessageA(lv, LVM_INSERTITEMA, 0, (LPARAM)&item);
3174 else
3175 HeapFree(GetProcessHeap(), 0, info);
3179 static BOOL is_valid_oid(LPCSTR oid)
3181 BOOL ret;
3183 if (oid[0] != '0' && oid[0] != '1' && oid[0] != '2')
3184 ret = FALSE;
3185 else if (oid[1] != '.')
3186 ret = FALSE;
3187 else if (!oid[2])
3188 ret = FALSE;
3189 else
3191 const char *ptr;
3192 BOOL expectNum = TRUE;
3194 for (ptr = oid + 2, ret = TRUE; ret && *ptr; ptr++)
3196 if (expectNum)
3198 if (!isdigit(*ptr))
3199 ret = FALSE;
3200 else if (*(ptr + 1) == '.')
3201 expectNum = FALSE;
3203 else
3205 if (*ptr != '.')
3206 ret = FALSE;
3207 else if (!(*(ptr + 1)))
3208 ret = FALSE;
3209 else
3210 expectNum = TRUE;
3214 return ret;
3217 static BOOL is_oid_in_list(HWND hwnd, LPCSTR oid)
3219 return find_oid_in_list(GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES), oid)
3220 != -1;
3223 #define MAX_PURPOSE 255
3225 static LRESULT CALLBACK add_purpose_dlg_proc(HWND hwnd, UINT msg,
3226 WPARAM wp, LPARAM lp)
3228 LRESULT ret = 0;
3229 char buf[MAX_PURPOSE + 1];
3231 switch (msg)
3233 case WM_INITDIALOG:
3234 SendMessageW(GetDlgItem(hwnd, IDC_NEW_PURPOSE), EM_SETLIMITTEXT,
3235 MAX_PURPOSE, 0);
3236 ShowScrollBar(GetDlgItem(hwnd, IDC_NEW_PURPOSE), SB_VERT, FALSE);
3237 SetWindowLongPtrW(hwnd, DWLP_USER, lp);
3238 break;
3239 case WM_COMMAND:
3240 switch (HIWORD(wp))
3242 case EN_CHANGE:
3243 if (LOWORD(wp) == IDC_NEW_PURPOSE)
3245 /* Show/hide scroll bar on description depending on how much
3246 * text it has.
3248 HWND description = GetDlgItem(hwnd, IDC_NEW_PURPOSE);
3249 int lines = SendMessageW(description, EM_GETLINECOUNT, 0, 0);
3251 ShowScrollBar(description, SB_VERT, lines > 1);
3253 break;
3254 case BN_CLICKED:
3255 switch (LOWORD(wp))
3257 case IDOK:
3258 SendMessageA(GetDlgItem(hwnd, IDC_NEW_PURPOSE), WM_GETTEXT,
3259 sizeof(buf) / sizeof(buf[0]), (LPARAM)buf);
3260 if (!buf[0])
3262 /* An empty purpose is the same as cancelling */
3263 EndDialog(hwnd, IDCANCEL);
3264 ret = TRUE;
3266 else if (!is_valid_oid(buf))
3268 WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
3270 LoadStringW(hInstance, IDS_CERTIFICATE_PURPOSE_ERROR, error,
3271 sizeof(error) / sizeof(error[0]));
3272 LoadStringW(hInstance, IDS_CERTIFICATE_PROPERTIES, title,
3273 sizeof(title) / sizeof(title[0]));
3274 MessageBoxW(hwnd, error, title, MB_ICONERROR | MB_OK);
3276 else if (is_oid_in_list(
3277 (HWND)GetWindowLongPtrW(hwnd, DWLP_USER), buf))
3279 WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
3281 LoadStringW(hInstance, IDS_CERTIFICATE_PURPOSE_EXISTS,
3282 error, sizeof(error) / sizeof(error[0]));
3283 LoadStringW(hInstance, IDS_CERTIFICATE_PROPERTIES, title,
3284 sizeof(title) / sizeof(title[0]));
3285 MessageBoxW(hwnd, error, title, MB_ICONEXCLAMATION | MB_OK);
3287 else
3289 HWND parent = (HWND)GetWindowLongPtrW(hwnd, DWLP_USER);
3291 add_purpose(parent, buf);
3292 EndDialog(hwnd, wp);
3293 ret = TRUE;
3295 break;
3296 case IDCANCEL:
3297 EndDialog(hwnd, wp);
3298 ret = TRUE;
3299 break;
3301 break;
3303 break;
3305 return ret;
3308 static WCHAR *get_cert_property_as_string(PCCERT_CONTEXT cert, DWORD prop)
3310 WCHAR *name = NULL;
3311 DWORD cb;
3313 if (CertGetCertificateContextProperty(cert, prop, NULL, &cb))
3315 name = HeapAlloc(GetProcessHeap(), 0, cb);
3316 if (name)
3318 if (!CertGetCertificateContextProperty(cert, prop, name, &cb))
3320 HeapFree(GetProcessHeap(), 0, name);
3321 name = NULL;
3325 return name;
3328 static void redraw_states(HWND list, BOOL enabled)
3330 int items = SendMessageW(list, LVM_GETITEMCOUNT, 0, 0), i;
3332 for (i = 0; i < items; i++)
3334 BOOL change = FALSE;
3335 int state;
3337 state = SendMessageW(list, LVM_GETITEMSTATE, i, LVIS_STATEIMAGEMASK);
3338 /* This reverses the INDEXTOSTATEIMAGEMASK shift. There doesn't appear
3339 * to be a handy macro for it.
3341 state >>= 12;
3342 if (enabled)
3344 if (state == CheckBitmapIndexDisabledChecked)
3346 state = CheckBitmapIndexChecked;
3347 change = TRUE;
3349 if (state == CheckBitmapIndexDisabledUnchecked)
3351 state = CheckBitmapIndexUnchecked;
3352 change = TRUE;
3355 else
3357 if (state == CheckBitmapIndexChecked)
3359 state = CheckBitmapIndexDisabledChecked;
3360 change = TRUE;
3362 if (state == CheckBitmapIndexUnchecked)
3364 state = CheckBitmapIndexDisabledUnchecked;
3365 change = TRUE;
3368 if (change)
3370 LVITEMW item;
3372 item.state = INDEXTOSTATEIMAGEMASK(state);
3373 item.stateMask = LVIS_STATEIMAGEMASK;
3374 SendMessageW(list, LVM_SETITEMSTATE, i, (LPARAM)&item);
3379 typedef enum {
3380 PurposeEnableAll = 0,
3381 PurposeDisableAll,
3382 PurposeEnableSelected
3383 } PurposeSelection;
3385 static void select_purposes(HWND hwnd, PurposeSelection selection)
3387 HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
3389 switch (selection)
3391 case PurposeEnableAll:
3392 case PurposeDisableAll:
3393 EnableWindow(lv, FALSE);
3394 redraw_states(lv, FALSE);
3395 EnableWindow(GetDlgItem(hwnd, IDC_ADD_PURPOSE), FALSE);
3396 break;
3397 case PurposeEnableSelected:
3398 EnableWindow(lv, TRUE);
3399 redraw_states(lv, TRUE);
3400 EnableWindow(GetDlgItem(hwnd, IDC_ADD_PURPOSE), TRUE);
3404 struct edit_cert_data
3406 PCCERT_CONTEXT cert;
3407 BOOL *pfPropertiesChanged;
3408 HIMAGELIST imageList;
3411 static void show_cert_usages(HWND hwnd, struct edit_cert_data *data)
3413 PCCERT_CONTEXT cert = data->cert;
3414 HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
3415 PCERT_ENHKEY_USAGE usage;
3416 DWORD size;
3417 RECT rc;
3418 LVCOLUMNW column;
3419 PurposeSelection purposeSelection = PurposeEnableAll;
3421 GetWindowRect(lv, &rc);
3422 column.mask = LVCF_WIDTH;
3423 column.cx = rc.right - rc.left;
3424 SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
3425 SendMessageW(lv, LVM_SETIMAGELIST, LVSIL_STATE, (LPARAM)data->imageList);
3427 /* Get enhanced key usage. Have to check for a property and an extension
3428 * separately, because CertGetEnhancedKeyUsage will succeed and return an
3429 * empty usage if neither is set. Unfortunately an empty usage implies
3430 * no usage is allowed, so we have to distinguish between the two cases.
3432 if (CertGetEnhancedKeyUsage(cert, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG,
3433 NULL, &size))
3435 usage = HeapAlloc(GetProcessHeap(), 0, size);
3436 if (!CertGetEnhancedKeyUsage(cert,
3437 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, usage, &size))
3439 HeapFree(GetProcessHeap(), 0, usage);
3440 usage = NULL;
3442 else if (usage->cUsageIdentifier)
3443 purposeSelection = PurposeEnableSelected;
3444 else
3445 purposeSelection = PurposeDisableAll;
3447 else if (CertGetEnhancedKeyUsage(cert, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG,
3448 NULL, &size))
3450 usage = HeapAlloc(GetProcessHeap(), 0, size);
3451 if (!CertGetEnhancedKeyUsage(cert,
3452 CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG, usage, &size))
3454 HeapFree(GetProcessHeap(), 0, usage);
3455 usage = NULL;
3457 else if (usage->cUsageIdentifier)
3458 purposeSelection = PurposeEnableAll;
3459 else
3460 purposeSelection = PurposeDisableAll;
3462 else
3464 purposeSelection = PurposeEnableAll;
3465 usage = NULL;
3467 if (usage)
3469 DWORD i;
3471 for (i = 0; i < usage->cUsageIdentifier; i++)
3473 PCCRYPT_OID_INFO info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
3474 usage->rgpszUsageIdentifier[i], CRYPT_ENHKEY_USAGE_OID_GROUP_ID);
3476 if (info)
3477 add_known_usage(lv, info, CheckBitmapIndexDisabledChecked);
3478 else
3479 add_purpose(hwnd, usage->rgpszUsageIdentifier[i]);
3481 HeapFree(GetProcessHeap(), 0, usage);
3483 else
3484 add_known_usages_to_list(lv, CheckBitmapIndexDisabledChecked);
3485 select_purposes(hwnd, purposeSelection);
3486 SendMessageW(GetDlgItem(hwnd, IDC_ENABLE_ALL_PURPOSES + purposeSelection),
3487 BM_CLICK, 0, 0);
3490 static void set_general_cert_properties(HWND hwnd, struct edit_cert_data *data)
3492 PCCERT_CONTEXT cert = data->cert;
3493 WCHAR *str;
3495 if ((str = get_cert_property_as_string(cert, CERT_FRIENDLY_NAME_PROP_ID)))
3497 SendMessageW(GetDlgItem(hwnd, IDC_FRIENDLY_NAME), WM_SETTEXT, 0,
3498 (LPARAM)str);
3499 HeapFree(GetProcessHeap(), 0, str);
3501 if ((str = get_cert_property_as_string(cert, CERT_DESCRIPTION_PROP_ID)))
3503 SendMessageW(GetDlgItem(hwnd, IDC_DESCRIPTION), WM_SETTEXT, 0,
3504 (LPARAM)str);
3505 HeapFree(GetProcessHeap(), 0, str);
3507 show_cert_usages(hwnd, data);
3510 static void set_cert_string_property(PCCERT_CONTEXT cert, DWORD prop,
3511 LPWSTR str)
3513 if (str && strlenW(str))
3515 CRYPT_DATA_BLOB blob;
3517 blob.pbData = (BYTE *)str;
3518 blob.cbData = (strlenW(str) + 1) * sizeof(WCHAR);
3519 CertSetCertificateContextProperty(cert, prop, 0, &blob);
3521 else
3522 CertSetCertificateContextProperty(cert, prop, 0, NULL);
3525 #define WM_REFRESH_VIEW WM_USER + 0
3527 static BOOL CALLBACK refresh_propsheet_pages(HWND hwnd, LPARAM lParam)
3529 if ((GetClassLongW(hwnd, GCW_ATOM) == WC_DIALOG))
3530 SendMessageW(hwnd, WM_REFRESH_VIEW, 0, 0);
3531 return TRUE;
3534 #define MAX_FRIENDLY_NAME 40
3535 #define MAX_DESCRIPTION 255
3537 static void apply_general_changes(HWND hwnd)
3539 WCHAR buf[MAX_DESCRIPTION + 1];
3540 struct edit_cert_data *data =
3541 (struct edit_cert_data *)GetWindowLongPtrW(hwnd, DWLP_USER);
3543 SendMessageW(GetDlgItem(hwnd, IDC_FRIENDLY_NAME), WM_GETTEXT,
3544 sizeof(buf) / sizeof(buf[0]), (LPARAM)buf);
3545 set_cert_string_property(data->cert, CERT_FRIENDLY_NAME_PROP_ID, buf);
3546 SendMessageW(GetDlgItem(hwnd, IDC_DESCRIPTION), WM_GETTEXT,
3547 sizeof(buf) / sizeof(buf[0]), (LPARAM)buf);
3548 set_cert_string_property(data->cert, CERT_DESCRIPTION_PROP_ID, buf);
3549 if (IsDlgButtonChecked(hwnd, IDC_ENABLE_ALL_PURPOSES))
3551 /* Setting a NULL usage removes the enhanced key usage property. */
3552 CertSetEnhancedKeyUsage(data->cert, NULL);
3554 else if (IsDlgButtonChecked(hwnd, IDC_DISABLE_ALL_PURPOSES))
3556 CERT_ENHKEY_USAGE usage = { 0, NULL };
3558 CertSetEnhancedKeyUsage(data->cert, &usage);
3560 else if (IsDlgButtonChecked(hwnd, IDC_ENABLE_SELECTED_PURPOSES))
3562 HWND lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
3563 CERT_ENHKEY_USAGE usage = { 0, NULL };
3564 int purposes = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0), i;
3565 LVITEMW item;
3567 item.mask = LVIF_STATE | LVIF_PARAM;
3568 item.iSubItem = 0;
3569 item.stateMask = LVIS_STATEIMAGEMASK;
3570 for (i = 0; i < purposes; i++)
3572 item.iItem = i;
3573 if (SendMessageW(lv, LVM_GETITEMW, 0, (LPARAM)&item))
3575 int state = item.state >> 12;
3577 if (state == CheckBitmapIndexChecked)
3579 CRYPT_OID_INFO *info = (CRYPT_OID_INFO *)item.lParam;
3581 if (usage.cUsageIdentifier)
3582 usage.rgpszUsageIdentifier =
3583 HeapReAlloc(GetProcessHeap(), 0,
3584 usage.rgpszUsageIdentifier,
3585 (usage.cUsageIdentifier + 1) * sizeof(LPSTR));
3586 else
3587 usage.rgpszUsageIdentifier =
3588 HeapAlloc(GetProcessHeap(), 0, sizeof(LPSTR));
3589 if (usage.rgpszUsageIdentifier)
3590 usage.rgpszUsageIdentifier[usage.cUsageIdentifier++] =
3591 (LPSTR)info->pszOID;
3595 CertSetEnhancedKeyUsage(data->cert, &usage);
3596 HeapFree(GetProcessHeap(), 0, usage.rgpszUsageIdentifier);
3598 EnumChildWindows(GetParent(GetParent(hwnd)), refresh_propsheet_pages, 0);
3599 if (data->pfPropertiesChanged)
3600 *data->pfPropertiesChanged = TRUE;
3603 static LRESULT CALLBACK cert_properties_general_dlg_proc(HWND hwnd, UINT msg,
3604 WPARAM wp, LPARAM lp)
3606 PROPSHEETPAGEW *page;
3608 TRACE("(%p, %08x, %08lx, %08lx)\n", hwnd, msg, wp, lp);
3610 switch (msg)
3612 case WM_INITDIALOG:
3614 HWND description = GetDlgItem(hwnd, IDC_DESCRIPTION);
3615 struct detail_data *detailData;
3616 struct edit_cert_data *editData;
3618 page = (PROPSHEETPAGEW *)lp;
3619 detailData = (struct detail_data *)page->lParam;
3620 SendMessageW(GetDlgItem(hwnd, IDC_FRIENDLY_NAME), EM_SETLIMITTEXT,
3621 MAX_FRIENDLY_NAME, 0);
3622 SendMessageW(description, EM_SETLIMITTEXT, MAX_DESCRIPTION, 0);
3623 ShowScrollBar(description, SB_VERT, FALSE);
3624 editData = HeapAlloc(GetProcessHeap(), 0,
3625 sizeof(struct edit_cert_data));
3626 if (editData)
3628 editData->imageList = ImageList_Create(16, 16,
3629 ILC_COLOR4 | ILC_MASK, 4, 0);
3630 if (editData->imageList)
3632 HBITMAP bmp;
3633 COLORREF backColor = RGB(255, 0, 255);
3635 bmp = LoadBitmapW(hInstance, MAKEINTRESOURCEW(IDB_CHECKS));
3636 ImageList_AddMasked(editData->imageList, bmp, backColor);
3637 DeleteObject(bmp);
3638 ImageList_SetBkColor(editData->imageList, CLR_NONE);
3640 editData->cert = detailData->pCertViewInfo->pCertContext;
3641 editData->pfPropertiesChanged = detailData->pfPropertiesChanged;
3642 SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)editData);
3643 set_general_cert_properties(hwnd, editData);
3645 break;
3647 case WM_NOTIFY:
3649 NMHDR *hdr = (NMHDR *)lp;
3650 NMITEMACTIVATE *nm;
3652 switch (hdr->code)
3654 case NM_CLICK:
3655 nm = (NMITEMACTIVATE *)lp;
3656 toggle_usage(hwnd, nm->iItem);
3657 SendMessageW(GetParent(hwnd), PSM_CHANGED, (WPARAM)hwnd, 0);
3658 break;
3659 case PSN_APPLY:
3660 apply_general_changes(hwnd);
3661 break;
3663 break;
3665 case WM_COMMAND:
3666 switch (HIWORD(wp))
3668 case EN_CHANGE:
3669 SendMessageW(GetParent(hwnd), PSM_CHANGED, (WPARAM)hwnd, 0);
3670 if (LOWORD(wp) == IDC_DESCRIPTION)
3672 /* Show/hide scroll bar on description depending on how much
3673 * text it has.
3675 HWND description = GetDlgItem(hwnd, IDC_DESCRIPTION);
3676 int lines = SendMessageW(description, EM_GETLINECOUNT, 0, 0);
3678 ShowScrollBar(description, SB_VERT, lines > 1);
3680 break;
3681 case BN_CLICKED:
3682 switch (LOWORD(wp))
3684 case IDC_ADD_PURPOSE:
3685 if (DialogBoxParamW(hInstance,
3686 MAKEINTRESOURCEW(IDD_ADD_CERT_PURPOSE), hwnd,
3687 add_purpose_dlg_proc, (LPARAM)hwnd) == IDOK)
3688 SendMessageW(GetParent(hwnd), PSM_CHANGED, (WPARAM)hwnd, 0);
3689 break;
3690 case IDC_ENABLE_ALL_PURPOSES:
3691 case IDC_DISABLE_ALL_PURPOSES:
3692 case IDC_ENABLE_SELECTED_PURPOSES:
3693 SendMessageW(GetParent(hwnd), PSM_CHANGED, (WPARAM)hwnd, 0);
3694 select_purposes(hwnd, LOWORD(wp) - IDC_ENABLE_ALL_PURPOSES);
3695 break;
3697 break;
3699 break;
3701 return 0;
3704 static UINT CALLBACK cert_properties_general_callback(HWND hwnd, UINT msg,
3705 PROPSHEETPAGEW *page)
3707 HWND lv;
3708 int cItem, i;
3709 struct edit_cert_data *data;
3711 switch (msg)
3713 case PSPCB_RELEASE:
3714 lv = GetDlgItem(hwnd, IDC_CERTIFICATE_USAGES);
3715 cItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
3716 for (i = 0; i < cItem; i++)
3718 LVITEMW item;
3720 item.mask = LVIF_PARAM;
3721 item.iItem = i;
3722 item.iSubItem = 0;
3723 if (SendMessageW(lv, LVM_GETITEMW, 0, (LPARAM)&item) && item.lParam)
3725 PCRYPT_OID_INFO info = (PCRYPT_OID_INFO)item.lParam;
3727 if (info->cbSize == sizeof(CRYPT_OID_INFO) && !info->dwGroupId)
3729 HeapFree(GetProcessHeap(), 0, (LPSTR)info->pszOID);
3730 HeapFree(GetProcessHeap(), 0, info);
3734 data = (struct edit_cert_data *)GetWindowLongPtrW(hwnd, DWLP_USER);
3735 if (data)
3737 ImageList_Destroy(data->imageList);
3738 HeapFree(GetProcessHeap(), 0, data);
3740 break;
3742 return 1;
3745 static void show_edit_cert_properties_dialog(HWND parent,
3746 struct detail_data *data)
3748 PROPSHEETHEADERW hdr;
3749 PROPSHEETPAGEW page; /* FIXME: need to add a cross-certificate page */
3751 TRACE("(%p)\n", data);
3753 memset(&page, 0, sizeof(PROPSHEETPAGEW));
3754 page.dwSize = sizeof(page);
3755 page.dwFlags = PSP_USECALLBACK;
3756 page.pfnCallback = cert_properties_general_callback;
3757 page.hInstance = hInstance;
3758 page.u.pszTemplate = MAKEINTRESOURCEW(IDD_CERT_PROPERTIES_GENERAL);
3759 page.pfnDlgProc = cert_properties_general_dlg_proc;
3760 page.lParam = (LPARAM)data;
3762 memset(&hdr, 0, sizeof(hdr));
3763 hdr.dwSize = sizeof(hdr);
3764 hdr.hwndParent = parent;
3765 hdr.dwFlags = PSH_PROPSHEETPAGE;
3766 hdr.hInstance = hInstance;
3767 hdr.pszCaption = MAKEINTRESOURCEW(IDS_CERTIFICATE_PROPERTIES);
3768 hdr.u3.ppsp = &page;
3769 hdr.nPages = 1;
3770 PropertySheetW(&hdr);
3773 static void free_detail_fields(struct detail_data *data)
3775 DWORD i;
3777 for (i = 0; i < data->cFields; i++)
3778 HeapFree(GetProcessHeap(), 0, data->fields[i].detailed_value);
3779 HeapFree(GetProcessHeap(), 0, data->fields);
3780 data->fields = NULL;
3781 data->cFields = 0;
3784 static void refresh_details_view(HWND hwnd)
3786 HWND cb = GetDlgItem(hwnd, IDC_DETAIL_SELECT);
3787 int curSel;
3788 struct detail_data *data;
3790 curSel = SendMessageW(cb, CB_GETCURSEL, 0, 0);
3791 /* Actually, any index will do, since they all store the same data value */
3792 data = (struct detail_data *)SendMessageW(cb, CB_GETITEMDATA, curSel, 0);
3793 free_detail_fields(data);
3794 set_fields_selection(hwnd, data, curSel);
3797 static LRESULT CALLBACK detail_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
3798 LPARAM lp)
3800 PROPSHEETPAGEW *page;
3801 struct detail_data *data;
3803 TRACE("(%p, %08x, %08lx, %08lx)\n", hwnd, msg, wp, lp);
3805 switch (msg)
3807 case WM_INITDIALOG:
3808 page = (PROPSHEETPAGEW *)lp;
3809 data = (struct detail_data *)page->lParam;
3810 create_cert_details_list(hwnd, data);
3811 if (!(data->pCertViewInfo->dwFlags & CRYPTUI_ENABLE_EDITPROPERTIES))
3812 EnableWindow(GetDlgItem(hwnd, IDC_EDITPROPERTIES), FALSE);
3813 if (data->pCertViewInfo->dwFlags & CRYPTUI_DISABLE_EXPORT)
3814 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT), FALSE);
3815 break;
3816 case WM_NOTIFY:
3818 NMITEMACTIVATE *nm;
3819 HWND list = GetDlgItem(hwnd, IDC_DETAIL_LIST);
3821 nm = (NMITEMACTIVATE*)lp;
3822 if (nm->hdr.hwndFrom == list && nm->uNewState & LVN_ITEMACTIVATE
3823 && nm->hdr.code == LVN_ITEMCHANGED)
3825 data = (struct detail_data *)nm->lParam;
3826 if (nm->iItem >= 0 && data && nm->iItem < data->cFields)
3828 WCHAR buf[MAX_STRING_LEN], *val = NULL;
3829 HWND valueCtl = GetDlgItem(hwnd, IDC_DETAIL_VALUE);
3831 if (data->fields[nm->iItem].create)
3832 val = data->fields[nm->iItem].create(
3833 data->pCertViewInfo->pCertContext,
3834 data->fields[nm->iItem].param);
3835 else
3837 LVITEMW item;
3838 int res;
3840 item.cchTextMax = sizeof(buf) / sizeof(buf[0]);
3841 item.mask = LVIF_TEXT;
3842 item.pszText = buf;
3843 item.iItem = nm->iItem;
3844 item.iSubItem = 1;
3845 res = SendMessageW(list, LVM_GETITEMW, 0, (LPARAM)&item);
3846 if (res)
3847 val = buf;
3849 /* Select all the text in the control, the next update will
3850 * replace it
3852 SendMessageW(valueCtl, EM_SETSEL, 0, -1);
3853 add_unformatted_text_to_control(valueCtl, val,
3854 val ? strlenW(val) : 0);
3855 if (val != buf)
3856 HeapFree(GetProcessHeap(), 0, val);
3859 break;
3861 case WM_COMMAND:
3862 switch (wp)
3864 case IDC_EXPORT:
3866 HWND cb = GetDlgItem(hwnd, IDC_DETAIL_SELECT);
3867 CRYPTUI_WIZ_EXPORT_INFO info;
3869 data = (struct detail_data *)SendMessageW(cb, CB_GETITEMDATA, 0, 0);
3870 info.dwSize = sizeof(info);
3871 info.pwszExportFileName = NULL;
3872 info.dwSubjectChoice = CRYPTUI_WIZ_EXPORT_CERT_CONTEXT;
3873 info.u.pCertContext = data->pCertViewInfo->pCertContext;
3874 info.cStores = 0;
3875 CryptUIWizExport(0, hwnd, NULL, &info, NULL);
3876 break;
3878 case IDC_EDITPROPERTIES:
3880 HWND cb = GetDlgItem(hwnd, IDC_DETAIL_SELECT);
3881 int curSel;
3883 curSel = SendMessageW(cb, CB_GETCURSEL, 0, 0);
3884 /* Actually, any index will do, since they all store the same
3885 * data value
3887 data = (struct detail_data *)SendMessageW(cb, CB_GETITEMDATA,
3888 curSel, 0);
3889 show_edit_cert_properties_dialog(GetParent(hwnd), data);
3890 break;
3892 case ((CBN_SELCHANGE << 16) | IDC_DETAIL_SELECT):
3893 refresh_details_view(hwnd);
3894 break;
3896 break;
3897 case WM_REFRESH_VIEW:
3898 refresh_details_view(hwnd);
3899 break;
3901 return 0;
3904 static UINT CALLBACK detail_callback(HWND hwnd, UINT msg,
3905 PROPSHEETPAGEW *page)
3907 struct detail_data *data;
3909 switch (msg)
3911 case PSPCB_RELEASE:
3912 data = (struct detail_data *)page->lParam;
3913 free_detail_fields(data);
3914 HeapFree(GetProcessHeap(), 0, data);
3915 break;
3917 return 0;
3920 static BOOL init_detail_page(PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo,
3921 BOOL *pfPropertiesChanged, PROPSHEETPAGEW *page)
3923 BOOL ret;
3924 struct detail_data *data = HeapAlloc(GetProcessHeap(), 0,
3925 sizeof(struct detail_data));
3927 if (data)
3929 data->pCertViewInfo = pCertViewInfo;
3930 data->pfPropertiesChanged = pfPropertiesChanged;
3931 data->cFields = 0;
3932 data->fields = NULL;
3933 memset(page, 0, sizeof(PROPSHEETPAGEW));
3934 page->dwSize = sizeof(PROPSHEETPAGEW);
3935 page->dwFlags = PSP_USECALLBACK;
3936 page->pfnCallback = detail_callback;
3937 page->hInstance = hInstance;
3938 page->u.pszTemplate = MAKEINTRESOURCEW(IDD_DETAIL);
3939 page->pfnDlgProc = detail_dlg_proc;
3940 page->lParam = (LPARAM)data;
3941 ret = TRUE;
3943 else
3944 ret = FALSE;
3945 return ret;
3948 struct hierarchy_data
3950 PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo;
3951 HIMAGELIST imageList;
3952 DWORD selectedCert;
3955 static LPARAM index_to_lparam(struct hierarchy_data *data, DWORD index)
3957 CRYPT_PROVIDER_SGNR *provSigner = WTHelperGetProvSignerFromChain(
3958 (CRYPT_PROVIDER_DATA *)data->pCertViewInfo->u.pCryptProviderData,
3959 data->pCertViewInfo->idxSigner, data->pCertViewInfo->fCounterSigner,
3960 data->pCertViewInfo->idxCounterSigner);
3962 /* Takes advantage of the fact that a pointer is 32-bit aligned, and
3963 * therefore always even.
3965 if (index == provSigner->csCertChain - 1)
3966 return (LPARAM)data;
3967 return index << 1 | 1;
3970 static inline DWORD lparam_to_index(struct hierarchy_data *data, LPARAM lp)
3972 CRYPT_PROVIDER_SGNR *provSigner = WTHelperGetProvSignerFromChain(
3973 (CRYPT_PROVIDER_DATA *)data->pCertViewInfo->u.pCryptProviderData,
3974 data->pCertViewInfo->idxSigner, data->pCertViewInfo->fCounterSigner,
3975 data->pCertViewInfo->idxCounterSigner);
3977 if (!(lp & 1))
3978 return provSigner->csCertChain - 1;
3979 return lp >> 1;
3982 static struct hierarchy_data *get_hierarchy_data_from_tree_item(HWND tree,
3983 HTREEITEM hItem)
3985 struct hierarchy_data *data = NULL;
3986 HTREEITEM root = NULL;
3988 do {
3989 HTREEITEM parent = (HTREEITEM)SendMessageW(tree, TVM_GETNEXTITEM,
3990 TVGN_PARENT, (LPARAM)hItem);
3992 if (!parent)
3993 root = hItem;
3994 hItem = parent;
3995 } while (hItem);
3996 if (root)
3998 TVITEMW item;
4000 item.mask = TVIF_PARAM;
4001 item.hItem = root;
4002 SendMessageW(tree, TVM_GETITEMW, 0, (LPARAM)&item);
4003 data = (struct hierarchy_data *)item.lParam;
4005 return data;
4008 static WCHAR *get_cert_display_name(PCCERT_CONTEXT cert)
4010 WCHAR *name = get_cert_property_as_string(cert, CERT_FRIENDLY_NAME_PROP_ID);
4012 if (!name)
4013 name = get_cert_name_string(cert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0);
4014 return name;
4017 static void show_cert_chain(HWND hwnd, struct hierarchy_data *data)
4019 HWND tree = GetDlgItem(hwnd, IDC_CERTPATH);
4020 CRYPT_PROVIDER_SGNR *provSigner = WTHelperGetProvSignerFromChain(
4021 (CRYPT_PROVIDER_DATA *)data->pCertViewInfo->u.pCryptProviderData,
4022 data->pCertViewInfo->idxSigner, data->pCertViewInfo->fCounterSigner,
4023 data->pCertViewInfo->idxCounterSigner);
4024 DWORD i;
4025 HTREEITEM parent = NULL;
4027 SendMessageW(tree, TVM_SETIMAGELIST, TVSIL_NORMAL, (LPARAM)data->imageList);
4028 for (i = provSigner->csCertChain; i; i--)
4030 LPWSTR name;
4032 name = get_cert_display_name(provSigner->pasCertChain[i - 1].pCert);
4033 if (name)
4035 TVINSERTSTRUCTW tvis;
4037 tvis.hParent = parent;
4038 tvis.hInsertAfter = TVI_LAST;
4039 tvis.u.item.mask = TVIF_TEXT | TVIF_STATE | TVIF_IMAGE |
4040 TVIF_SELECTEDIMAGE | TVIF_PARAM;
4041 tvis.u.item.pszText = name;
4042 tvis.u.item.state = TVIS_EXPANDED;
4043 tvis.u.item.stateMask = TVIS_EXPANDED;
4044 if (i == 1 &&
4045 (provSigner->pChainContext->TrustStatus.dwErrorStatus &
4046 CERT_TRUST_IS_PARTIAL_CHAIN))
4048 /* The root of the chain has a special case: if the chain is
4049 * a partial chain, the icon is a warning icon rather than an
4050 * error icon.
4052 tvis.u.item.iImage = 2;
4054 else if (provSigner->pasCertChain[i - 1].pChainElement->TrustStatus.
4055 dwErrorStatus == 0)
4056 tvis.u.item.iImage = 0;
4057 else
4058 tvis.u.item.iImage = 1;
4059 tvis.u.item.iSelectedImage = tvis.u.item.iImage;
4060 tvis.u.item.lParam = index_to_lparam(data, i - 1);
4061 parent = (HTREEITEM)SendMessageW(tree, TVM_INSERTITEMW, 0,
4062 (LPARAM)&tvis);
4063 HeapFree(GetProcessHeap(), 0, name);
4068 static void set_certificate_status(HWND hwnd, const CRYPT_PROVIDER_CERT *cert)
4070 /* Select all the text in the control, the next update will replace it */
4071 SendMessageW(hwnd, EM_SETSEL, 0, -1);
4072 /* Set the highest priority error messages first. */
4073 if (!(cert->dwConfidence & CERT_CONFIDENCE_SIG))
4074 add_string_resource_to_control(hwnd, IDS_CERTIFICATE_BAD_SIGNATURE);
4075 else if (!(cert->dwConfidence & CERT_CONFIDENCE_TIME))
4076 add_string_resource_to_control(hwnd, IDS_CERTIFICATE_BAD_TIME);
4077 else if (!(cert->dwConfidence & CERT_CONFIDENCE_TIMENEST))
4078 add_string_resource_to_control(hwnd, IDS_CERTIFICATE_BAD_TIMENEST);
4079 else if (cert->dwRevokedReason)
4080 add_string_resource_to_control(hwnd, IDS_CERTIFICATE_REVOKED);
4081 else
4082 add_string_resource_to_control(hwnd, IDS_CERTIFICATE_VALID);
4085 static void set_certificate_status_for_end_cert(HWND hwnd,
4086 PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo)
4088 HWND status = GetDlgItem(hwnd, IDC_CERTIFICATESTATUSTEXT);
4089 CRYPT_PROVIDER_SGNR *provSigner = WTHelperGetProvSignerFromChain(
4090 (CRYPT_PROVIDER_DATA *)pCertViewInfo->u.pCryptProviderData,
4091 pCertViewInfo->idxSigner, pCertViewInfo->fCounterSigner,
4092 pCertViewInfo->idxCounterSigner);
4093 CRYPT_PROVIDER_CERT *provCert = WTHelperGetProvCertFromChain(provSigner,
4094 pCertViewInfo->idxCert);
4096 set_certificate_status(status, provCert);
4099 static void show_cert_hierarchy(HWND hwnd, struct hierarchy_data *data)
4101 /* Disable view certificate button until a certificate is selected */
4102 EnableWindow(GetDlgItem(hwnd, IDC_VIEWCERTIFICATE), FALSE);
4103 show_cert_chain(hwnd, data);
4104 set_certificate_status_for_end_cert(hwnd, data->pCertViewInfo);
4107 static void show_dialog_for_selected_cert(HWND hwnd)
4109 HWND tree = GetDlgItem(hwnd, IDC_CERTPATH);
4110 TVITEMW item;
4111 struct hierarchy_data *data;
4112 DWORD selection;
4114 memset(&item, 0, sizeof(item));
4115 item.mask = TVIF_HANDLE | TVIF_PARAM;
4116 item.hItem = (HTREEITEM)SendMessageW(tree, TVM_GETNEXTITEM, TVGN_CARET, 0);
4117 SendMessageW(tree, TVM_GETITEMW, 0, (LPARAM)&item);
4118 data = get_hierarchy_data_from_tree_item(tree, item.hItem);
4119 selection = lparam_to_index(data, item.lParam);
4120 if (selection != 0)
4122 CRYPT_PROVIDER_SGNR *provSigner;
4123 CRYPTUI_VIEWCERTIFICATE_STRUCTW viewInfo;
4124 BOOL changed = FALSE;
4126 provSigner = WTHelperGetProvSignerFromChain(
4127 (CRYPT_PROVIDER_DATA *)data->pCertViewInfo->u.pCryptProviderData,
4128 data->pCertViewInfo->idxSigner,
4129 data->pCertViewInfo->fCounterSigner,
4130 data->pCertViewInfo->idxCounterSigner);
4131 memset(&viewInfo, 0, sizeof(viewInfo));
4132 viewInfo.dwSize = sizeof(viewInfo);
4133 viewInfo.dwFlags = data->pCertViewInfo->dwFlags;
4134 viewInfo.szTitle = data->pCertViewInfo->szTitle;
4135 viewInfo.pCertContext = provSigner->pasCertChain[selection].pCert;
4136 viewInfo.cStores = data->pCertViewInfo->cStores;
4137 viewInfo.rghStores = data->pCertViewInfo->rghStores;
4138 viewInfo.cPropSheetPages = data->pCertViewInfo->cPropSheetPages;
4139 viewInfo.rgPropSheetPages = data->pCertViewInfo->rgPropSheetPages;
4140 viewInfo.nStartPage = data->pCertViewInfo->nStartPage;
4141 CryptUIDlgViewCertificateW(&viewInfo, &changed);
4142 if (changed)
4144 /* Delete the contents of the tree */
4145 SendMessageW(tree, TVM_DELETEITEM, 0, (LPARAM)TVI_ROOT);
4146 /* Reinitialize the tree */
4147 show_cert_hierarchy(hwnd, data);
4152 static LRESULT CALLBACK hierarchy_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
4153 LPARAM lp)
4155 PROPSHEETPAGEW *page;
4156 struct hierarchy_data *data;
4157 LRESULT ret = 0;
4158 HWND tree = GetDlgItem(hwnd, IDC_CERTPATH);
4160 TRACE("(%p, %08x, %08lx, %08lx)\n", hwnd, msg, wp, lp);
4162 switch (msg)
4164 case WM_INITDIALOG:
4165 page = (PROPSHEETPAGEW *)lp;
4166 data = (struct hierarchy_data *)page->lParam;
4167 show_cert_hierarchy(hwnd, data);
4168 break;
4169 case WM_NOTIFY:
4171 NMHDR *hdr;
4173 hdr = (NMHDR *)lp;
4174 switch (hdr->code)
4176 case TVN_SELCHANGEDW:
4178 NMTREEVIEWW *nm = (NMTREEVIEWW*)lp;
4179 DWORD selection;
4180 CRYPT_PROVIDER_SGNR *provSigner;
4182 data = get_hierarchy_data_from_tree_item(tree, nm->itemNew.hItem);
4183 selection = lparam_to_index(data, nm->itemNew.lParam);
4184 provSigner = WTHelperGetProvSignerFromChain(
4185 (CRYPT_PROVIDER_DATA *)data->pCertViewInfo->u.pCryptProviderData,
4186 data->pCertViewInfo->idxSigner,
4187 data->pCertViewInfo->fCounterSigner,
4188 data->pCertViewInfo->idxCounterSigner);
4189 EnableWindow(GetDlgItem(hwnd, IDC_VIEWCERTIFICATE), selection != 0);
4190 set_certificate_status(GetDlgItem(hwnd, IDC_CERTIFICATESTATUSTEXT),
4191 &provSigner->pasCertChain[selection]);
4192 break;
4194 case NM_DBLCLK:
4195 show_dialog_for_selected_cert(hwnd);
4196 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
4197 ret = 1;
4198 break;
4200 break;
4202 case WM_COMMAND:
4203 switch (wp)
4205 case IDC_VIEWCERTIFICATE:
4206 show_dialog_for_selected_cert(hwnd);
4207 break;
4209 break;
4210 case WM_REFRESH_VIEW:
4212 TVITEMW item;
4214 /* Get hierarchy data */
4215 memset(&item, 0, sizeof(item));
4216 item.mask = TVIF_HANDLE | TVIF_PARAM;
4217 item.hItem = (HTREEITEM)SendMessageW(tree, TVM_GETNEXTITEM, TVGN_ROOT,
4219 data = get_hierarchy_data_from_tree_item(tree, item.hItem);
4220 /* Delete the contents of the tree */
4221 SendMessageW(tree, TVM_DELETEITEM, 0, (LPARAM)TVI_ROOT);
4222 /* Reinitialize the tree */
4223 show_cert_hierarchy(hwnd, data);
4224 break;
4227 return ret;
4230 static UINT CALLBACK hierarchy_callback(HWND hwnd, UINT msg,
4231 PROPSHEETPAGEW *page)
4233 struct hierarchy_data *data;
4235 switch (msg)
4237 case PSPCB_RELEASE:
4238 data = (struct hierarchy_data *)page->lParam;
4239 ImageList_Destroy(data->imageList);
4240 HeapFree(GetProcessHeap(), 0, data);
4241 break;
4243 return 0;
4246 static BOOL init_hierarchy_page(PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo,
4247 PROPSHEETPAGEW *page)
4249 struct hierarchy_data *data = HeapAlloc(GetProcessHeap(), 0,
4250 sizeof(struct hierarchy_data));
4251 BOOL ret = FALSE;
4253 if (data)
4255 data->imageList = ImageList_Create(16, 16, ILC_COLOR4 | ILC_MASK, 2, 0);
4256 if (data->imageList)
4258 HBITMAP bmp;
4259 COLORREF backColor = RGB(255, 0, 255);
4261 data->pCertViewInfo = pCertViewInfo;
4262 data->selectedCert = 0xffffffff;
4264 bmp = LoadBitmapW(hInstance, MAKEINTRESOURCEW(IDB_SMALL_ICONS));
4265 ImageList_AddMasked(data->imageList, bmp, backColor);
4266 DeleteObject(bmp);
4267 ImageList_SetBkColor(data->imageList, CLR_NONE);
4269 memset(page, 0, sizeof(PROPSHEETPAGEW));
4270 page->dwSize = sizeof(PROPSHEETPAGEW);
4271 page->dwFlags = PSP_USECALLBACK;
4272 page->hInstance = hInstance;
4273 page->u.pszTemplate = MAKEINTRESOURCEW(IDD_HIERARCHY);
4274 page->pfnDlgProc = hierarchy_dlg_proc;
4275 page->lParam = (LPARAM)data;
4276 page->pfnCallback = hierarchy_callback;
4277 ret = TRUE;
4279 else
4280 HeapFree(GetProcessHeap(), 0, data);
4282 return ret;
4285 static int CALLBACK cert_prop_sheet_proc(HWND hwnd, UINT msg, LPARAM lp)
4287 RECT rc;
4288 POINT topLeft;
4290 TRACE("(%p, %08x, %08lx)\n", hwnd, msg, lp);
4292 switch (msg)
4294 case PSCB_INITIALIZED:
4295 /* Get cancel button's position.. */
4296 GetWindowRect(GetDlgItem(hwnd, IDCANCEL), &rc);
4297 topLeft.x = rc.left;
4298 topLeft.y = rc.top;
4299 ScreenToClient(hwnd, &topLeft);
4300 /* hide the cancel button.. */
4301 ShowWindow(GetDlgItem(hwnd, IDCANCEL), FALSE);
4302 /* get the OK button's size.. */
4303 GetWindowRect(GetDlgItem(hwnd, IDOK), &rc);
4304 /* and move the OK button to the cancel button's original position. */
4305 MoveWindow(GetDlgItem(hwnd, IDOK), topLeft.x, topLeft.y,
4306 rc.right - rc.left, rc.bottom - rc.top, FALSE);
4307 GetWindowRect(GetDlgItem(hwnd, IDOK), &rc);
4308 break;
4310 return 0;
4313 static BOOL show_cert_dialog(PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo,
4314 CRYPT_PROVIDER_CERT *provCert, BOOL *pfPropertiesChanged)
4316 static const WCHAR riched[] = { 'r','i','c','h','e','d','2','0',0 };
4317 DWORD nPages;
4318 PROPSHEETPAGEW *pages;
4319 BOOL ret = FALSE;
4320 HMODULE lib = LoadLibraryW(riched);
4322 nPages = pCertViewInfo->cPropSheetPages + 1; /* one for the General tab */
4323 if (!(pCertViewInfo->dwFlags & CRYPTUI_HIDE_DETAILPAGE))
4324 nPages++;
4325 if (!(pCertViewInfo->dwFlags & CRYPTUI_HIDE_HIERARCHYPAGE))
4326 nPages++;
4327 pages = HeapAlloc(GetProcessHeap(), 0, nPages * sizeof(PROPSHEETPAGEW));
4328 if (pages)
4330 PROPSHEETHEADERW hdr;
4331 CRYPTUI_INITDIALOG_STRUCT *init = NULL;
4332 DWORD i;
4334 memset(&hdr, 0, sizeof(hdr));
4335 hdr.dwSize = sizeof(hdr);
4336 hdr.dwFlags = PSH_NOAPPLYNOW | PSH_PROPSHEETPAGE | PSH_USECALLBACK;
4337 hdr.hInstance = hInstance;
4338 if (pCertViewInfo->szTitle)
4339 hdr.pszCaption = pCertViewInfo->szTitle;
4340 else
4341 hdr.pszCaption = MAKEINTRESOURCEW(IDS_CERTIFICATE);
4342 init_general_page(pCertViewInfo, &pages[hdr.nPages++]);
4343 if (!(pCertViewInfo->dwFlags & CRYPTUI_HIDE_DETAILPAGE))
4345 if (init_detail_page(pCertViewInfo, pfPropertiesChanged,
4346 &pages[hdr.nPages]))
4347 hdr.nPages++;
4349 if (!(pCertViewInfo->dwFlags & CRYPTUI_HIDE_HIERARCHYPAGE))
4351 if (init_hierarchy_page(pCertViewInfo, &pages[hdr.nPages]))
4352 hdr.nPages++;
4354 /* Copy each additional page, and create the init dialog struct for it
4356 if (pCertViewInfo->cPropSheetPages)
4358 init = HeapAlloc(GetProcessHeap(), 0,
4359 pCertViewInfo->cPropSheetPages *
4360 sizeof(CRYPTUI_INITDIALOG_STRUCT));
4361 if (init)
4363 for (i = 0; i < pCertViewInfo->cPropSheetPages; i++)
4365 memcpy(&pages[hdr.nPages + i],
4366 &pCertViewInfo->rgPropSheetPages[i],
4367 sizeof(PROPSHEETPAGEW));
4368 init[i].lParam = pCertViewInfo->rgPropSheetPages[i].lParam;
4369 init[i].pCertContext = pCertViewInfo->pCertContext;
4370 pages[hdr.nPages + i].lParam = (LPARAM)&init[i];
4372 if (pCertViewInfo->nStartPage & 0x8000)
4374 /* Start page index is relative to the number of default
4375 * pages
4377 hdr.u2.nStartPage = pCertViewInfo->nStartPage + hdr.nPages;
4379 else
4380 hdr.u2.nStartPage = pCertViewInfo->nStartPage;
4381 hdr.nPages = nPages;
4382 ret = TRUE;
4384 else
4385 SetLastError(ERROR_OUTOFMEMORY);
4387 else
4389 /* Ignore the relative flag if there aren't any additional pages */
4390 hdr.u2.nStartPage = pCertViewInfo->nStartPage & 0x7fff;
4391 ret = TRUE;
4393 if (ret)
4395 INT_PTR l;
4397 hdr.u3.ppsp = pages;
4398 hdr.pfnCallback = cert_prop_sheet_proc;
4399 l = PropertySheetW(&hdr);
4400 if (l == 0)
4402 SetLastError(ERROR_CANCELLED);
4403 ret = FALSE;
4406 HeapFree(GetProcessHeap(), 0, init);
4407 HeapFree(GetProcessHeap(), 0, pages);
4409 else
4410 SetLastError(ERROR_OUTOFMEMORY);
4411 FreeLibrary(lib);
4412 return ret;
4415 /***********************************************************************
4416 * CryptUIDlgViewCertificateW (CRYPTUI.@)
4418 BOOL WINAPI CryptUIDlgViewCertificateW(
4419 PCCRYPTUI_VIEWCERTIFICATE_STRUCTW pCertViewInfo, BOOL *pfPropertiesChanged)
4421 static GUID generic_cert_verify = WINTRUST_ACTION_GENERIC_CERT_VERIFY;
4422 CRYPTUI_VIEWCERTIFICATE_STRUCTW viewInfo;
4423 WINTRUST_DATA wvt;
4424 WINTRUST_CERT_INFO cert;
4425 BOOL ret = FALSE;
4426 CRYPT_PROVIDER_SGNR *signer;
4427 CRYPT_PROVIDER_CERT *provCert = NULL;
4429 TRACE("(%p, %p)\n", pCertViewInfo, pfPropertiesChanged);
4431 if (pCertViewInfo->dwSize != sizeof(CRYPTUI_VIEWCERTIFICATE_STRUCTW))
4433 SetLastError(ERROR_INVALID_PARAMETER);
4434 return FALSE;
4436 /* Make a local copy in case we have to call WinVerifyTrust ourselves */
4437 memcpy(&viewInfo, pCertViewInfo, sizeof(viewInfo));
4438 if (!viewInfo.u.hWVTStateData)
4440 memset(&wvt, 0, sizeof(wvt));
4441 wvt.cbStruct = sizeof(wvt);
4442 wvt.dwUIChoice = WTD_UI_NONE;
4443 if (viewInfo.dwFlags &
4444 CRYPTUI_ENABLE_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT)
4445 wvt.fdwRevocationChecks |= WTD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
4446 if (viewInfo.dwFlags & CRYPTUI_ENABLE_REVOCATION_CHECK_END_CERT)
4447 wvt.fdwRevocationChecks |= WTD_REVOCATION_CHECK_END_CERT;
4448 if (viewInfo.dwFlags & CRYPTUI_ENABLE_REVOCATION_CHECK_CHAIN)
4449 wvt.fdwRevocationChecks |= WTD_REVOCATION_CHECK_CHAIN;
4450 wvt.dwUnionChoice = WTD_CHOICE_CERT;
4451 memset(&cert, 0, sizeof(cert));
4452 cert.cbStruct = sizeof(cert);
4453 cert.psCertContext = (CERT_CONTEXT *)viewInfo.pCertContext;
4454 cert.chStores = viewInfo.cStores;
4455 cert.pahStores = viewInfo.rghStores;
4456 wvt.u.pCert = &cert;
4457 wvt.dwStateAction = WTD_STATEACTION_VERIFY;
4458 WinVerifyTrust(NULL, &generic_cert_verify, &wvt);
4459 viewInfo.u.pCryptProviderData =
4460 WTHelperProvDataFromStateData(wvt.hWVTStateData);
4461 signer = WTHelperGetProvSignerFromChain(
4462 (CRYPT_PROVIDER_DATA *)viewInfo.u.pCryptProviderData, 0, FALSE, 0);
4463 provCert = WTHelperGetProvCertFromChain(signer, 0);
4464 ret = TRUE;
4466 else
4468 viewInfo.u.pCryptProviderData =
4469 WTHelperProvDataFromStateData(viewInfo.u.hWVTStateData);
4470 signer = WTHelperGetProvSignerFromChain(
4471 (CRYPT_PROVIDER_DATA *)viewInfo.u.pCryptProviderData,
4472 viewInfo.idxSigner, viewInfo.fCounterSigner,
4473 viewInfo.idxCounterSigner);
4474 provCert = WTHelperGetProvCertFromChain(signer, viewInfo.idxCert);
4475 ret = TRUE;
4477 if (ret)
4479 ret = show_cert_dialog(&viewInfo, provCert, pfPropertiesChanged);
4480 if (!viewInfo.u.hWVTStateData)
4482 wvt.dwStateAction = WTD_STATEACTION_CLOSE;
4483 WinVerifyTrust(NULL, &generic_cert_verify, &wvt);
4486 return ret;
4489 /***********************************************************************
4490 * CryptUIDlgViewContext (CRYPTUI.@)
4492 BOOL WINAPI CryptUIDlgViewContext(DWORD dwContextType, LPVOID pvContext,
4493 HWND hwnd, LPCWSTR pwszTitle, DWORD dwFlags, LPVOID pvReserved)
4495 BOOL ret;
4497 TRACE("(%d, %p, %p, %s, %08x, %p)\n", dwContextType, pvContext, hwnd,
4498 debugstr_w(pwszTitle), dwFlags, pvReserved);
4500 switch (dwContextType)
4502 case CERT_STORE_CERTIFICATE_CONTEXT:
4504 CRYPTUI_VIEWCERTIFICATE_STRUCTW viewInfo;
4506 memset(&viewInfo, 0, sizeof(viewInfo));
4507 viewInfo.dwSize = sizeof(viewInfo);
4508 viewInfo.hwndParent = hwnd;
4509 viewInfo.szTitle = pwszTitle;
4510 viewInfo.pCertContext = pvContext;
4511 ret = CryptUIDlgViewCertificateW(&viewInfo, NULL);
4512 break;
4514 default:
4515 FIXME("unimplemented for context type %d\n", dwContextType);
4516 SetLastError(E_INVALIDARG);
4517 ret = FALSE;
4519 return ret;
4522 /* Decodes a cert's basic constraints extension (either szOID_BASIC_CONSTRAINTS
4523 * or szOID_BASIC_CONSTRAINTS2, whichever is present) to determine if it
4524 * should be a CA. If neither extension is present, returns
4525 * defaultIfNotSpecified.
4527 static BOOL is_ca_cert(PCCERT_CONTEXT cert, BOOL defaultIfNotSpecified)
4529 BOOL isCA = defaultIfNotSpecified;
4530 PCERT_EXTENSION ext = CertFindExtension(szOID_BASIC_CONSTRAINTS,
4531 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
4533 if (ext)
4535 CERT_BASIC_CONSTRAINTS_INFO *info;
4536 DWORD size = 0;
4538 if (CryptDecodeObjectEx(X509_ASN_ENCODING, szOID_BASIC_CONSTRAINTS,
4539 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG,
4540 NULL, &info, &size))
4542 if (info->SubjectType.cbData == 1)
4543 isCA = info->SubjectType.pbData[0] & CERT_CA_SUBJECT_FLAG;
4544 LocalFree(info);
4547 else
4549 ext = CertFindExtension(szOID_BASIC_CONSTRAINTS2,
4550 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension);
4551 if (ext)
4553 CERT_BASIC_CONSTRAINTS2_INFO info;
4554 DWORD size = sizeof(CERT_BASIC_CONSTRAINTS2_INFO);
4556 if (CryptDecodeObjectEx(X509_ASN_ENCODING,
4557 szOID_BASIC_CONSTRAINTS2, ext->Value.pbData, ext->Value.cbData,
4558 0, NULL, &info, &size))
4559 isCA = info.fCA;
4562 return isCA;
4565 static HCERTSTORE choose_store_for_cert(PCCERT_CONTEXT cert)
4567 LPCWSTR storeName;
4569 if (is_ca_cert(cert, TRUE))
4570 storeName = ca;
4571 else
4572 storeName = addressBook;
4573 return CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
4574 CERT_SYSTEM_STORE_CURRENT_USER, storeName);
4577 static BOOL import_cert(PCCERT_CONTEXT cert, HCERTSTORE hDestCertStore)
4579 HCERTSTORE store;
4580 BOOL ret;
4582 if (!cert)
4584 SetLastError(E_INVALIDARG);
4585 return FALSE;
4587 if (hDestCertStore) store = hDestCertStore;
4588 else
4590 if (!(store = choose_store_for_cert(cert)))
4592 WARN("unable to open certificate store\n");
4593 return FALSE;
4596 ret = CertAddCertificateContextToStore(store, cert,
4597 CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES, NULL);
4598 if (!hDestCertStore) CertCloseStore(store, 0);
4599 return ret;
4602 static BOOL import_crl(PCCRL_CONTEXT crl, HCERTSTORE hDestCertStore)
4604 HCERTSTORE store;
4605 BOOL ret;
4607 if (!crl)
4609 SetLastError(E_INVALIDARG);
4610 return FALSE;
4612 if (hDestCertStore) store = hDestCertStore;
4613 else
4615 if (!(store = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
4616 CERT_SYSTEM_STORE_CURRENT_USER, ca)))
4618 WARN("unable to open certificate store\n");
4619 return FALSE;
4622 ret = CertAddCRLContextToStore(store, crl,
4623 CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES, NULL);
4624 if (!hDestCertStore) CertCloseStore(store, 0);
4625 return ret;
4628 static BOOL import_ctl(PCCTL_CONTEXT ctl, HCERTSTORE hDestCertStore)
4630 HCERTSTORE store;
4631 BOOL ret;
4633 if (!ctl)
4635 SetLastError(E_INVALIDARG);
4636 return FALSE;
4638 if (hDestCertStore) store = hDestCertStore;
4639 else
4641 static const WCHAR trust[] = { 'T','r','u','s','t',0 };
4643 if (!(store = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
4644 CERT_SYSTEM_STORE_CURRENT_USER, trust)))
4646 WARN("unable to open certificate store\n");
4647 return FALSE;
4650 ret = CertAddCTLContextToStore(store, ctl,
4651 CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES, NULL);
4652 if (!hDestCertStore) CertCloseStore(store, 0);
4653 return ret;
4656 /* Checks type, a type such as CERT_QUERY_CONTENT_CERT returned by
4657 * CryptQueryObject, against the allowed types. Returns TRUE if the
4658 * type is allowed, FALSE otherwise.
4660 static BOOL check_context_type(DWORD dwFlags, DWORD type)
4662 BOOL ret;
4664 if (dwFlags &
4665 (CRYPTUI_WIZ_IMPORT_ALLOW_CERT | CRYPTUI_WIZ_IMPORT_ALLOW_CRL |
4666 CRYPTUI_WIZ_IMPORT_ALLOW_CTL))
4668 switch (type)
4670 case CERT_QUERY_CONTENT_CERT:
4671 case CERT_QUERY_CONTENT_SERIALIZED_CERT:
4672 ret = dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CERT;
4673 break;
4674 case CERT_QUERY_CONTENT_CRL:
4675 case CERT_QUERY_CONTENT_SERIALIZED_CRL:
4676 ret = dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CRL;
4677 break;
4678 case CERT_QUERY_CONTENT_CTL:
4679 case CERT_QUERY_CONTENT_SERIALIZED_CTL:
4680 ret = dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CTL;
4681 break;
4682 default:
4683 /* The remaining types contain more than one type, so allow
4684 * any combination.
4686 ret = TRUE;
4689 else
4691 /* No allowed types specified, so any type is allowed */
4692 ret = TRUE;
4694 if (!ret)
4695 SetLastError(E_INVALIDARG);
4696 return ret;
4700 static void import_warning(DWORD dwFlags, HWND hwnd, LPCWSTR szTitle,
4701 int warningID)
4703 if (!(dwFlags & CRYPTUI_WIZ_NO_UI))
4705 WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
4706 LPCWSTR pTitle;
4708 if (szTitle)
4709 pTitle = szTitle;
4710 else
4712 LoadStringW(hInstance, IDS_IMPORT_WIZARD, title,
4713 sizeof(title) / sizeof(title[0]));
4714 pTitle = title;
4716 LoadStringW(hInstance, warningID, error,
4717 sizeof(error) / sizeof(error[0]));
4718 MessageBoxW(hwnd, error, pTitle, MB_ICONERROR | MB_OK);
4722 static void import_warn_type_mismatch(DWORD dwFlags, HWND hwnd, LPCWSTR szTitle)
4724 import_warning(dwFlags, hwnd, szTitle, IDS_IMPORT_TYPE_MISMATCH);
4727 static BOOL check_store_context_type(DWORD dwFlags, HCERTSTORE store)
4729 BOOL ret;
4731 if (dwFlags &
4732 (CRYPTUI_WIZ_IMPORT_ALLOW_CERT | CRYPTUI_WIZ_IMPORT_ALLOW_CRL |
4733 CRYPTUI_WIZ_IMPORT_ALLOW_CTL))
4735 PCCERT_CONTEXT cert;
4736 PCCRL_CONTEXT crl;
4737 PCCTL_CONTEXT ctl;
4739 ret = TRUE;
4740 if ((cert = CertEnumCertificatesInStore(store, NULL)))
4742 CertFreeCertificateContext(cert);
4743 if (!(dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CERT))
4744 ret = FALSE;
4746 if (ret && (crl = CertEnumCRLsInStore(store, NULL)))
4748 CertFreeCRLContext(crl);
4749 if (!(dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CRL))
4750 ret = FALSE;
4752 if (ret && (ctl = CertEnumCTLsInStore(store, NULL)))
4754 CertFreeCTLContext(ctl);
4755 if (!(dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CTL))
4756 ret = FALSE;
4759 else
4760 ret = TRUE;
4761 if (!ret)
4762 SetLastError(E_INVALIDARG);
4763 return ret;
4766 static BOOL import_store(DWORD dwFlags, HWND hwnd, LPCWSTR szTitle,
4767 HCERTSTORE source, HCERTSTORE dest)
4769 BOOL ret;
4771 if ((ret = check_store_context_type(dwFlags, source)))
4773 PCCERT_CONTEXT cert = NULL;
4774 PCCRL_CONTEXT crl = NULL;
4775 PCCTL_CONTEXT ctl = NULL;
4777 do {
4778 cert = CertEnumCertificatesInStore(source, cert);
4779 if (cert)
4780 ret = import_cert(cert, dest);
4781 } while (ret && cert);
4782 do {
4783 crl = CertEnumCRLsInStore(source, crl);
4784 if (crl)
4785 ret = import_crl(crl, dest);
4786 } while (ret && crl);
4787 do {
4788 ctl = CertEnumCTLsInStore(source, ctl);
4789 if (ctl)
4790 ret = import_ctl(ctl, dest);
4791 } while (ret && ctl);
4793 else
4794 import_warn_type_mismatch(dwFlags, hwnd, szTitle);
4795 return ret;
4798 static HCERTSTORE open_store_from_file(DWORD dwFlags, LPCWSTR fileName,
4799 DWORD *pContentType)
4801 HCERTSTORE store = NULL;
4802 DWORD contentType = 0, expectedContentTypeFlags;
4804 if (dwFlags &
4805 (CRYPTUI_WIZ_IMPORT_ALLOW_CERT | CRYPTUI_WIZ_IMPORT_ALLOW_CRL |
4806 CRYPTUI_WIZ_IMPORT_ALLOW_CTL))
4808 expectedContentTypeFlags =
4809 CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE |
4810 CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED |
4811 CERT_QUERY_CONTENT_FLAG_PFX;
4812 if (dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CERT)
4813 expectedContentTypeFlags |=
4814 CERT_QUERY_CONTENT_FLAG_CERT |
4815 CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT;
4816 if (dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CRL)
4817 expectedContentTypeFlags |=
4818 CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL |
4819 CERT_QUERY_CONTENT_FLAG_CRL;
4820 if (dwFlags & CRYPTUI_WIZ_IMPORT_ALLOW_CTL)
4821 expectedContentTypeFlags |=
4822 CERT_QUERY_CONTENT_FLAG_CTL |
4823 CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL;
4825 else
4826 expectedContentTypeFlags =
4827 CERT_QUERY_CONTENT_FLAG_CERT |
4828 CERT_QUERY_CONTENT_FLAG_CTL |
4829 CERT_QUERY_CONTENT_FLAG_CRL |
4830 CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE |
4831 CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT |
4832 CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL |
4833 CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL |
4834 CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED |
4835 CERT_QUERY_CONTENT_FLAG_PFX;
4837 CryptQueryObject(CERT_QUERY_OBJECT_FILE, fileName,
4838 expectedContentTypeFlags, CERT_QUERY_FORMAT_FLAG_ALL, 0, NULL,
4839 &contentType, NULL, &store, NULL, NULL);
4840 if (pContentType)
4841 *pContentType = contentType;
4842 return store;
4845 static BOOL import_file(DWORD dwFlags, HWND hwnd, LPCWSTR szTitle,
4846 LPCWSTR fileName, HCERTSTORE dest)
4848 HCERTSTORE source;
4849 BOOL ret;
4851 if ((source = open_store_from_file(dwFlags, fileName, NULL)))
4853 ret = import_store(dwFlags, hwnd, szTitle, source, dest);
4854 CertCloseStore(source, 0);
4856 else
4857 ret = FALSE;
4858 return ret;
4861 struct ImportWizData
4863 HFONT titleFont;
4864 DWORD dwFlags;
4865 LPCWSTR pwszWizardTitle;
4866 CRYPTUI_WIZ_IMPORT_SRC_INFO importSrc;
4867 LPWSTR fileName;
4868 DWORD contentType;
4869 BOOL freeSource;
4870 HCERTSTORE hDestCertStore;
4871 BOOL freeDest;
4872 BOOL autoDest;
4873 BOOL success;
4876 static LRESULT CALLBACK import_welcome_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
4877 LPARAM lp)
4879 LRESULT ret = 0;
4881 switch (msg)
4883 case WM_INITDIALOG:
4885 struct ImportWizData *data;
4886 PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
4887 WCHAR fontFace[MAX_STRING_LEN];
4888 HDC hDC = GetDC(hwnd);
4889 int height;
4891 data = (struct ImportWizData *)page->lParam;
4892 LoadStringW(hInstance, IDS_WIZARD_TITLE_FONT, fontFace,
4893 sizeof(fontFace) / sizeof(fontFace[0]));
4894 height = -MulDiv(12, GetDeviceCaps(hDC, LOGPIXELSY), 72);
4895 data->titleFont = CreateFontW(height, 0, 0, 0, FW_BOLD, 0, 0, 0,
4896 DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
4897 DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, fontFace);
4898 SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_TITLE), WM_SETFONT,
4899 (WPARAM)data->titleFont, TRUE);
4900 ReleaseDC(hwnd, hDC);
4901 break;
4903 case WM_NOTIFY:
4905 NMHDR *hdr = (NMHDR *)lp;
4907 switch (hdr->code)
4909 case PSN_SETACTIVE:
4910 PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0, PSWIZB_NEXT);
4911 ret = TRUE;
4912 break;
4914 break;
4917 return ret;
4920 static const WCHAR filter_cert[] = { '*','.','c','e','r',';','*','.',
4921 'c','r','t',0 };
4922 static const WCHAR filter_pfx[] = { '*','.','p','f','x',';','*','.',
4923 'p','1','2',0 };
4924 static const WCHAR filter_crl[] = { '*','.','c','r','l',0 };
4925 static const WCHAR filter_ctl[] = { '*','.','s','t','l',0 };
4926 static const WCHAR filter_serialized_store[] = { '*','.','s','s','t',0 };
4927 static const WCHAR filter_cms[] = { '*','.','s','p','c',';','*','.',
4928 'p','7','b',0 };
4929 static const WCHAR filter_all[] = { '*','.','*',0 };
4931 struct StringToFilter
4933 int id;
4934 DWORD allowFlags;
4935 LPCWSTR filter;
4936 } import_filters[] = {
4937 { IDS_IMPORT_FILTER_CERT, CRYPTUI_WIZ_IMPORT_ALLOW_CERT, filter_cert },
4938 { IDS_IMPORT_FILTER_PFX, 0, filter_pfx },
4939 { IDS_IMPORT_FILTER_CRL, CRYPTUI_WIZ_IMPORT_ALLOW_CRL, filter_crl },
4940 { IDS_IMPORT_FILTER_CTL, CRYPTUI_WIZ_IMPORT_ALLOW_CTL, filter_ctl },
4941 { IDS_IMPORT_FILTER_SERIALIZED_STORE, 0, filter_serialized_store },
4942 { IDS_IMPORT_FILTER_CMS, 0, filter_cms },
4943 { IDS_IMPORT_FILTER_ALL, 0, filter_all },
4946 static WCHAR *make_import_file_filter(DWORD dwFlags)
4948 DWORD i;
4949 int len, totalLen = 2;
4950 LPWSTR filter = NULL, str;
4952 for (i = 0; i < sizeof(import_filters) / sizeof(import_filters[0]); i++)
4954 if (!import_filters[i].allowFlags || !dwFlags ||
4955 (dwFlags & import_filters[i].allowFlags))
4957 len = LoadStringW(hInstance, import_filters[i].id, (LPWSTR)&str, 0);
4958 totalLen += len + strlenW(import_filters[i].filter) + 2;
4961 filter = HeapAlloc(GetProcessHeap(), 0, totalLen * sizeof(WCHAR));
4962 if (filter)
4964 LPWSTR ptr;
4966 ptr = filter;
4967 for (i = 0; i < sizeof(import_filters) / sizeof(import_filters[0]); i++)
4969 if (!import_filters[i].allowFlags || !dwFlags ||
4970 (dwFlags & import_filters[i].allowFlags))
4972 len = LoadStringW(hInstance, import_filters[i].id,
4973 (LPWSTR)&str, 0);
4974 memcpy(ptr, str, len * sizeof(WCHAR));
4975 ptr += len;
4976 *ptr++ = 0;
4977 strcpyW(ptr, import_filters[i].filter);
4978 ptr += strlenW(import_filters[i].filter) + 1;
4981 *ptr++ = 0;
4983 return filter;
4986 static BOOL import_validate_filename(HWND hwnd, struct ImportWizData *data,
4987 LPCWSTR fileName)
4989 HANDLE file;
4990 BOOL ret = FALSE;
4992 file = CreateFileW(fileName, GENERIC_READ, FILE_SHARE_READ, NULL,
4993 OPEN_EXISTING, 0, NULL);
4994 if (file != INVALID_HANDLE_VALUE)
4996 HCERTSTORE source = open_store_from_file(data->dwFlags, fileName,
4997 &data->contentType);
4998 int warningID = 0;
5000 if (!source)
5001 warningID = IDS_IMPORT_BAD_FORMAT;
5002 else if (!check_store_context_type(data->dwFlags, source))
5003 warningID = IDS_IMPORT_TYPE_MISMATCH;
5004 else
5006 data->importSrc.dwSubjectChoice =
5007 CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_STORE;
5008 data->importSrc.u.hCertStore = source;
5009 data->freeSource = TRUE;
5010 ret = TRUE;
5012 if (warningID)
5014 import_warning(data->dwFlags, hwnd, data->pwszWizardTitle,
5015 warningID);
5017 CloseHandle(file);
5019 else
5021 WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
5022 LPCWSTR pTitle;
5023 LPWSTR msgBuf, fullError;
5025 if (data->pwszWizardTitle)
5026 pTitle = data->pwszWizardTitle;
5027 else
5029 LoadStringW(hInstance, IDS_IMPORT_WIZARD, title,
5030 sizeof(title) / sizeof(title[0]));
5031 pTitle = title;
5033 LoadStringW(hInstance, IDS_IMPORT_OPEN_FAILED, error,
5034 sizeof(error) / sizeof(error[0]));
5035 FormatMessageW(
5036 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL,
5037 GetLastError(), 0, (LPWSTR) &msgBuf, 0, NULL);
5038 fullError = HeapAlloc(GetProcessHeap(), 0,
5039 (strlenW(error) + strlenW(fileName) + strlenW(msgBuf) + 3)
5040 * sizeof(WCHAR));
5041 if (fullError)
5043 LPWSTR ptr = fullError;
5045 strcpyW(ptr, error);
5046 ptr += strlenW(error);
5047 strcpyW(ptr, fileName);
5048 ptr += strlenW(fileName);
5049 *ptr++ = ':';
5050 *ptr++ = '\n';
5051 strcpyW(ptr, msgBuf);
5052 MessageBoxW(hwnd, fullError, pTitle, MB_ICONERROR | MB_OK);
5053 HeapFree(GetProcessHeap(), 0, fullError);
5055 LocalFree(msgBuf);
5057 return ret;
5060 static LRESULT CALLBACK import_file_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
5061 LPARAM lp)
5063 LRESULT ret = 0;
5064 struct ImportWizData *data;
5066 switch (msg)
5068 case WM_INITDIALOG:
5070 PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5072 data = (struct ImportWizData *)page->lParam;
5073 SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5074 if (data->fileName)
5076 HWND fileNameEdit = GetDlgItem(hwnd, IDC_IMPORT_FILENAME);
5078 SendMessageW(fileNameEdit, WM_SETTEXT, 0, (LPARAM)data->fileName);
5080 break;
5082 case WM_NOTIFY:
5084 NMHDR *hdr = (NMHDR *)lp;
5086 switch (hdr->code)
5088 case PSN_SETACTIVE:
5089 PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5090 PSWIZB_BACK | PSWIZB_NEXT);
5091 ret = TRUE;
5092 break;
5093 case PSN_WIZNEXT:
5095 HWND fileNameEdit = GetDlgItem(hwnd, IDC_IMPORT_FILENAME);
5096 DWORD len = SendMessageW(fileNameEdit, WM_GETTEXTLENGTH, 0, 0);
5098 data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5099 if (!len)
5101 import_warning(data->dwFlags, hwnd, data->pwszWizardTitle,
5102 IDS_IMPORT_EMPTY_FILE);
5103 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
5104 ret = 1;
5106 else
5108 LPWSTR fileName = HeapAlloc(GetProcessHeap(), 0,
5109 (len + 1) * sizeof(WCHAR));
5111 if (fileName)
5113 SendMessageW(fileNameEdit, WM_GETTEXT, len + 1,
5114 (LPARAM)fileName);
5115 if (!import_validate_filename(hwnd, data, fileName))
5117 HeapFree(GetProcessHeap(), 0, fileName);
5118 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
5119 ret = 1;
5121 else
5122 data->fileName = fileName;
5125 break;
5128 break;
5130 case WM_COMMAND:
5131 switch (wp)
5133 case IDC_IMPORT_BROWSE_FILE:
5135 OPENFILENAMEW ofn;
5136 WCHAR fileBuf[MAX_PATH];
5138 data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5139 memset(&ofn, 0, sizeof(ofn));
5140 ofn.lStructSize = sizeof(ofn);
5141 ofn.hwndOwner = hwnd;
5142 ofn.lpstrFilter = make_import_file_filter(data->dwFlags);
5143 ofn.lpstrFile = fileBuf;
5144 ofn.nMaxFile = sizeof(fileBuf) / sizeof(fileBuf[0]);
5145 fileBuf[0] = 0;
5146 if (GetOpenFileNameW(&ofn))
5147 SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_FILENAME), WM_SETTEXT,
5148 0, (LPARAM)ofn.lpstrFile);
5149 HeapFree(GetProcessHeap(), 0, (LPWSTR)ofn.lpstrFilter);
5150 break;
5153 break;
5155 return ret;
5158 static LRESULT CALLBACK import_store_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
5159 LPARAM lp)
5161 LRESULT ret = 0;
5162 struct ImportWizData *data;
5164 switch (msg)
5166 case WM_INITDIALOG:
5168 PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5170 data = (struct ImportWizData *)page->lParam;
5171 SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5172 if (!data->hDestCertStore)
5174 SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_AUTO_STORE), BM_CLICK,
5175 0, 0);
5176 EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_STORE), FALSE);
5177 EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_BROWSE_STORE), FALSE);
5178 EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_SPECIFY_STORE), FALSE);
5180 else
5182 WCHAR storeTitle[MAX_STRING_LEN];
5184 SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_SPECIFY_STORE), BM_CLICK,
5185 0, 0);
5186 EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_STORE), TRUE);
5187 EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_BROWSE_STORE), TRUE);
5188 EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_SPECIFY_STORE),
5189 !(data->dwFlags & CRYPTUI_WIZ_IMPORT_NO_CHANGE_DEST_STORE));
5190 LoadStringW(hInstance, IDS_IMPORT_DEST_DETERMINED,
5191 storeTitle, sizeof(storeTitle) / sizeof(storeTitle[0]));
5192 SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_STORE), WM_SETTEXT,
5193 0, (LPARAM)storeTitle);
5195 break;
5197 case WM_NOTIFY:
5199 NMHDR *hdr = (NMHDR *)lp;
5201 switch (hdr->code)
5203 case PSN_SETACTIVE:
5204 PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5205 PSWIZB_BACK | PSWIZB_NEXT);
5206 ret = TRUE;
5207 break;
5208 case PSN_WIZNEXT:
5210 data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5211 if (IsDlgButtonChecked(hwnd, IDC_IMPORT_SPECIFY_STORE) &&
5212 !data->hDestCertStore)
5214 import_warning(data->dwFlags, hwnd, data->pwszWizardTitle,
5215 IDS_IMPORT_SELECT_STORE);
5216 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
5217 ret = 1;
5219 break;
5222 break;
5224 case WM_COMMAND:
5225 switch (wp)
5227 case IDC_IMPORT_AUTO_STORE:
5228 data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5229 data->autoDest = TRUE;
5230 EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_STORE), FALSE);
5231 EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_BROWSE_STORE), FALSE);
5232 break;
5233 case IDC_IMPORT_SPECIFY_STORE:
5234 data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5235 data->autoDest = FALSE;
5236 EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_STORE), TRUE);
5237 EnableWindow(GetDlgItem(hwnd, IDC_IMPORT_BROWSE_STORE), TRUE);
5238 break;
5239 case IDC_IMPORT_BROWSE_STORE:
5241 CRYPTUI_ENUM_SYSTEM_STORE_ARGS enumArgs = {
5242 CERT_SYSTEM_STORE_CURRENT_USER, NULL };
5243 CRYPTUI_ENUM_DATA enumData = { 0, NULL, 1, &enumArgs };
5244 CRYPTUI_SELECTSTORE_INFO_W selectInfo;
5245 HCERTSTORE store;
5247 data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5248 selectInfo.dwSize = sizeof(selectInfo);
5249 selectInfo.parent = hwnd;
5250 selectInfo.dwFlags = CRYPTUI_ENABLE_SHOW_PHYSICAL_STORE;
5251 selectInfo.pwszTitle = NULL;
5252 selectInfo.pwszText = NULL;
5253 selectInfo.pEnumData = &enumData;
5254 selectInfo.pfnSelectedStoreCallback = NULL;
5255 if ((store = CryptUIDlgSelectStoreW(&selectInfo)))
5257 WCHAR storeTitle[MAX_STRING_LEN];
5259 LoadStringW(hInstance, IDS_IMPORT_DEST_DETERMINED,
5260 storeTitle, sizeof(storeTitle) / sizeof(storeTitle[0]));
5261 SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_STORE), WM_SETTEXT,
5262 0, (LPARAM)storeTitle);
5263 data->hDestCertStore = store;
5264 data->freeDest = TRUE;
5266 break;
5269 break;
5271 return ret;
5274 static void show_import_details(HWND lv, struct ImportWizData *data)
5276 WCHAR text[MAX_STRING_LEN];
5277 LVITEMW item;
5278 int contentID;
5280 item.mask = LVIF_TEXT;
5281 item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
5282 item.iSubItem = 0;
5283 LoadStringW(hInstance, IDS_IMPORT_STORE_SELECTION, text,
5284 sizeof(text)/ sizeof(text[0]));
5285 item.pszText = text;
5286 SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
5287 item.iSubItem = 1;
5288 if (data->autoDest)
5289 LoadStringW(hInstance, IDS_IMPORT_DEST_AUTOMATIC, text,
5290 sizeof(text)/ sizeof(text[0]));
5291 else
5292 LoadStringW(hInstance, IDS_IMPORT_DEST_DETERMINED, text,
5293 sizeof(text)/ sizeof(text[0]));
5294 SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
5295 item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
5296 item.iSubItem = 0;
5297 LoadStringW(hInstance, IDS_IMPORT_CONTENT, text,
5298 sizeof(text)/ sizeof(text[0]));
5299 SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
5300 switch (data->contentType)
5302 case CERT_QUERY_CONTENT_CERT:
5303 case CERT_QUERY_CONTENT_SERIALIZED_CERT:
5304 contentID = IDS_IMPORT_CONTENT_CERT;
5305 break;
5306 case CERT_QUERY_CONTENT_CRL:
5307 case CERT_QUERY_CONTENT_SERIALIZED_CRL:
5308 contentID = IDS_IMPORT_CONTENT_CRL;
5309 break;
5310 case CERT_QUERY_CONTENT_CTL:
5311 case CERT_QUERY_CONTENT_SERIALIZED_CTL:
5312 contentID = IDS_IMPORT_CONTENT_CTL;
5313 break;
5314 case CERT_QUERY_CONTENT_PKCS7_SIGNED:
5315 contentID = IDS_IMPORT_CONTENT_CMS;
5316 break;
5317 case CERT_QUERY_CONTENT_FLAG_PFX:
5318 contentID = IDS_IMPORT_CONTENT_PFX;
5319 break;
5320 default:
5321 contentID = IDS_IMPORT_CONTENT_STORE;
5322 break;
5324 LoadStringW(hInstance, contentID, text, sizeof(text)/ sizeof(text[0]));
5325 item.iSubItem = 1;
5326 SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
5327 if (data->fileName)
5329 item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
5330 item.iSubItem = 0;
5331 LoadStringW(hInstance, IDS_IMPORT_FILE, text,
5332 sizeof(text)/ sizeof(text[0]));
5333 SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
5334 item.iSubItem = 1;
5335 item.pszText = data->fileName;
5336 SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
5340 static BOOL do_import(DWORD dwFlags, HWND hwndParent, LPCWSTR pwszWizardTitle,
5341 PCCRYPTUI_WIZ_IMPORT_SRC_INFO pImportSrc, HCERTSTORE hDestCertStore)
5343 BOOL ret;
5345 switch (pImportSrc->dwSubjectChoice)
5347 case CRYPTUI_WIZ_IMPORT_SUBJECT_FILE:
5348 ret = import_file(dwFlags, hwndParent, pwszWizardTitle,
5349 pImportSrc->u.pwszFileName, hDestCertStore);
5350 break;
5351 case CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_CONTEXT:
5352 if ((ret = check_context_type(dwFlags, CERT_QUERY_CONTENT_CERT)))
5353 ret = import_cert(pImportSrc->u.pCertContext, hDestCertStore);
5354 else
5355 import_warn_type_mismatch(dwFlags, hwndParent, pwszWizardTitle);
5356 break;
5357 case CRYPTUI_WIZ_IMPORT_SUBJECT_CRL_CONTEXT:
5358 if ((ret = check_context_type(dwFlags, CERT_QUERY_CONTENT_CRL)))
5359 ret = import_crl(pImportSrc->u.pCRLContext, hDestCertStore);
5360 else
5361 import_warn_type_mismatch(dwFlags, hwndParent, pwszWizardTitle);
5362 break;
5363 case CRYPTUI_WIZ_IMPORT_SUBJECT_CTL_CONTEXT:
5364 if ((ret = check_context_type(dwFlags, CERT_QUERY_CONTENT_CTL)))
5365 ret = import_ctl(pImportSrc->u.pCTLContext, hDestCertStore);
5366 else
5367 import_warn_type_mismatch(dwFlags, hwndParent, pwszWizardTitle);
5368 break;
5369 case CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_STORE:
5370 ret = import_store(dwFlags, hwndParent, pwszWizardTitle,
5371 pImportSrc->u.hCertStore, hDestCertStore);
5372 break;
5373 default:
5374 WARN("unknown source type: %u\n", pImportSrc->dwSubjectChoice);
5375 SetLastError(E_INVALIDARG);
5376 ret = FALSE;
5378 return ret;
5381 static LRESULT CALLBACK import_finish_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
5382 LPARAM lp)
5384 LRESULT ret = 0;
5385 struct ImportWizData *data;
5387 switch (msg)
5389 case WM_INITDIALOG:
5391 PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5392 HWND lv = GetDlgItem(hwnd, IDC_IMPORT_SETTINGS);
5393 RECT rc;
5394 LVCOLUMNW column;
5396 data = (struct ImportWizData *)page->lParam;
5397 SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5398 SendMessageW(GetDlgItem(hwnd, IDC_IMPORT_TITLE), WM_SETFONT,
5399 (WPARAM)data->titleFont, TRUE);
5400 GetWindowRect(lv, &rc);
5401 column.mask = LVCF_WIDTH;
5402 column.cx = (rc.right - rc.left) / 2 - 2;
5403 SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
5404 SendMessageW(lv, LVM_INSERTCOLUMNW, 1, (LPARAM)&column);
5405 show_import_details(lv, data);
5406 break;
5408 case WM_NOTIFY:
5410 NMHDR *hdr = (NMHDR *)lp;
5412 switch (hdr->code)
5414 case PSN_SETACTIVE:
5416 HWND lv = GetDlgItem(hwnd, IDC_IMPORT_SETTINGS);
5418 data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5419 SendMessageW(lv, LVM_DELETEALLITEMS, 0, 0);
5420 show_import_details(lv, data);
5421 PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5422 PSWIZB_BACK | PSWIZB_FINISH);
5423 ret = TRUE;
5424 break;
5426 case PSN_WIZFINISH:
5428 data = (struct ImportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5429 if ((data->success = do_import(data->dwFlags, hwnd,
5430 data->pwszWizardTitle, &data->importSrc, data->hDestCertStore)))
5432 WCHAR title[MAX_STRING_LEN], message[MAX_STRING_LEN];
5433 LPCWSTR pTitle;
5435 if (data->pwszWizardTitle)
5436 pTitle = data->pwszWizardTitle;
5437 else
5439 LoadStringW(hInstance, IDS_IMPORT_WIZARD, title,
5440 sizeof(title) / sizeof(title[0]));
5441 pTitle = title;
5443 LoadStringW(hInstance, IDS_IMPORT_SUCCEEDED, message,
5444 sizeof(message) / sizeof(message[0]));
5445 MessageBoxW(hwnd, message, pTitle, MB_OK);
5447 else
5448 import_warning(data->dwFlags, hwnd, data->pwszWizardTitle,
5449 IDS_IMPORT_FAILED);
5450 break;
5453 break;
5456 return ret;
5459 static BOOL show_import_ui(DWORD dwFlags, HWND hwndParent,
5460 LPCWSTR pwszWizardTitle, PCCRYPTUI_WIZ_IMPORT_SRC_INFO pImportSrc,
5461 HCERTSTORE hDestCertStore)
5463 PROPSHEETHEADERW hdr;
5464 PROPSHEETPAGEW pages[4];
5465 struct ImportWizData data;
5466 int nPages = 0;
5468 data.dwFlags = dwFlags;
5469 data.pwszWizardTitle = pwszWizardTitle;
5470 if (pImportSrc)
5472 memcpy(&data.importSrc, pImportSrc, sizeof(data.importSrc));
5473 data.fileName = (LPWSTR)pImportSrc->u.pwszFileName;
5475 else
5477 memset(&data.importSrc, 0, sizeof(data.importSrc));
5478 data.fileName = NULL;
5480 data.freeSource = FALSE;
5481 data.hDestCertStore = hDestCertStore;
5482 data.freeDest = FALSE;
5483 data.autoDest = TRUE;
5484 data.success = TRUE;
5486 memset(&pages, 0, sizeof(pages));
5488 pages[nPages].dwSize = sizeof(pages[0]);
5489 pages[nPages].hInstance = hInstance;
5490 pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_IMPORT_WELCOME);
5491 pages[nPages].pfnDlgProc = import_welcome_dlg_proc;
5492 pages[nPages].dwFlags = PSP_HIDEHEADER;
5493 pages[nPages].lParam = (LPARAM)&data;
5494 nPages++;
5496 if (!pImportSrc ||
5497 pImportSrc->dwSubjectChoice == CRYPTUI_WIZ_IMPORT_SUBJECT_FILE)
5499 pages[nPages].dwSize = sizeof(pages[0]);
5500 pages[nPages].hInstance = hInstance;
5501 pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_IMPORT_FILE);
5502 pages[nPages].pfnDlgProc = import_file_dlg_proc;
5503 pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
5504 pages[nPages].pszHeaderTitle = MAKEINTRESOURCEW(IDS_IMPORT_FILE_TITLE);
5505 pages[nPages].pszHeaderSubTitle =
5506 MAKEINTRESOURCEW(IDS_IMPORT_FILE_SUBTITLE);
5507 pages[nPages].lParam = (LPARAM)&data;
5508 nPages++;
5510 else
5512 switch (pImportSrc->dwSubjectChoice)
5514 case CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_CONTEXT:
5515 data.contentType = CERT_QUERY_CONTENT_CERT;
5516 break;
5517 case CRYPTUI_WIZ_IMPORT_SUBJECT_CRL_CONTEXT:
5518 data.contentType = CERT_QUERY_CONTENT_CRL;
5519 break;
5520 case CRYPTUI_WIZ_IMPORT_SUBJECT_CTL_CONTEXT:
5521 data.contentType = CERT_QUERY_CONTENT_CTL;
5522 break;
5523 case CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_STORE:
5524 data.contentType = CERT_QUERY_CONTENT_SERIALIZED_STORE;
5525 break;
5529 pages[nPages].dwSize = sizeof(pages[0]);
5530 pages[nPages].hInstance = hInstance;
5531 pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_IMPORT_STORE);
5532 pages[nPages].pfnDlgProc = import_store_dlg_proc;
5533 pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
5534 pages[nPages].pszHeaderTitle = MAKEINTRESOURCEW(IDS_IMPORT_STORE_TITLE);
5535 pages[nPages].pszHeaderSubTitle =
5536 MAKEINTRESOURCEW(IDS_IMPORT_STORE_SUBTITLE);
5537 pages[nPages].lParam = (LPARAM)&data;
5538 nPages++;
5540 pages[nPages].dwSize = sizeof(pages[0]);
5541 pages[nPages].hInstance = hInstance;
5542 pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_IMPORT_FINISH);
5543 pages[nPages].pfnDlgProc = import_finish_dlg_proc;
5544 pages[nPages].dwFlags = PSP_HIDEHEADER;
5545 pages[nPages].lParam = (LPARAM)&data;
5546 nPages++;
5548 memset(&hdr, 0, sizeof(hdr));
5549 hdr.dwSize = sizeof(hdr);
5550 hdr.hwndParent = hwndParent;
5551 hdr.dwFlags = PSH_PROPSHEETPAGE | PSH_WIZARD97_NEW | PSH_HEADER |
5552 PSH_WATERMARK;
5553 hdr.hInstance = hInstance;
5554 if (pwszWizardTitle)
5555 hdr.pszCaption = pwszWizardTitle;
5556 else
5557 hdr.pszCaption = MAKEINTRESOURCEW(IDS_IMPORT_WIZARD);
5558 hdr.u3.ppsp = pages;
5559 hdr.nPages = nPages;
5560 hdr.u4.pszbmWatermark = MAKEINTRESOURCEW(IDB_CERT_WATERMARK);
5561 hdr.u5.pszbmHeader = MAKEINTRESOURCEW(IDB_CERT_HEADER);
5562 PropertySheetW(&hdr);
5563 if (data.fileName != data.importSrc.u.pwszFileName)
5564 HeapFree(GetProcessHeap(), 0, data.fileName);
5565 if (data.freeSource &&
5566 data.importSrc.dwSubjectChoice == CRYPTUI_WIZ_IMPORT_SUBJECT_CERT_STORE)
5567 CertCloseStore(data.importSrc.u.hCertStore, 0);
5568 DeleteObject(data.titleFont);
5569 return data.success;
5572 BOOL WINAPI CryptUIWizImport(DWORD dwFlags, HWND hwndParent, LPCWSTR pwszWizardTitle,
5573 PCCRYPTUI_WIZ_IMPORT_SRC_INFO pImportSrc, HCERTSTORE hDestCertStore)
5575 BOOL ret;
5577 TRACE("(0x%08x, %p, %s, %p, %p)\n", dwFlags, hwndParent, debugstr_w(pwszWizardTitle),
5578 pImportSrc, hDestCertStore);
5580 if (pImportSrc &&
5581 pImportSrc->dwSize != sizeof(CRYPTUI_WIZ_IMPORT_SRC_INFO))
5583 SetLastError(E_INVALIDARG);
5584 return FALSE;
5587 if (!(dwFlags & CRYPTUI_WIZ_NO_UI))
5588 ret = show_import_ui(dwFlags, hwndParent, pwszWizardTitle, pImportSrc,
5589 hDestCertStore);
5590 else if (pImportSrc)
5591 ret = do_import(dwFlags, hwndParent, pwszWizardTitle, pImportSrc,
5592 hDestCertStore);
5593 else
5595 /* Can't have no UI without specifying source */
5596 SetLastError(E_INVALIDARG);
5597 ret = FALSE;
5600 return ret;
5603 struct ExportWizData
5605 HFONT titleFont;
5606 DWORD dwFlags;
5607 LPCWSTR pwszWizardTitle;
5608 CRYPTUI_WIZ_EXPORT_INFO exportInfo;
5609 CRYPTUI_WIZ_EXPORT_CERTCONTEXT_INFO contextInfo;
5610 BOOL freePassword;
5611 PCRYPT_KEY_PROV_INFO keyProvInfo;
5612 BOOL deleteKeys;
5613 LPWSTR fileName;
5614 HANDLE file;
5615 BOOL success;
5618 static LRESULT CALLBACK export_welcome_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
5619 LPARAM lp)
5621 LRESULT ret = 0;
5623 switch (msg)
5625 case WM_INITDIALOG:
5627 struct ExportWizData *data;
5628 PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5629 WCHAR fontFace[MAX_STRING_LEN];
5630 HDC hDC = GetDC(hwnd);
5631 int height;
5633 data = (struct ExportWizData *)page->lParam;
5634 LoadStringW(hInstance, IDS_WIZARD_TITLE_FONT, fontFace,
5635 sizeof(fontFace) / sizeof(fontFace[0]));
5636 height = -MulDiv(12, GetDeviceCaps(hDC, LOGPIXELSY), 72);
5637 data->titleFont = CreateFontW(height, 0, 0, 0, FW_BOLD, 0, 0, 0,
5638 DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
5639 DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, fontFace);
5640 SendMessageW(GetDlgItem(hwnd, IDC_EXPORT_TITLE), WM_SETFONT,
5641 (WPARAM)data->titleFont, TRUE);
5642 ReleaseDC(hwnd, hDC);
5643 break;
5645 case WM_NOTIFY:
5647 NMHDR *hdr = (NMHDR *)lp;
5649 switch (hdr->code)
5651 case PSN_SETACTIVE:
5652 PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0, PSWIZB_NEXT);
5653 ret = TRUE;
5654 break;
5656 break;
5659 return ret;
5662 static PCRYPT_KEY_PROV_INFO export_get_private_key_info(PCCERT_CONTEXT cert)
5664 PCRYPT_KEY_PROV_INFO info = NULL;
5665 DWORD size;
5667 if (CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID,
5668 NULL, &size))
5670 info = HeapAlloc(GetProcessHeap(), 0, size);
5671 if (info)
5673 if (!CertGetCertificateContextProperty(cert,
5674 CERT_KEY_PROV_INFO_PROP_ID, info, &size))
5676 HeapFree(GetProcessHeap(), 0, info);
5677 info = NULL;
5681 return info;
5684 static BOOL export_acquire_private_key(const CRYPT_KEY_PROV_INFO *info,
5685 HCRYPTPROV *phProv)
5687 BOOL ret;
5689 ret = CryptAcquireContextW(phProv, info->pwszContainerName,
5690 info->pwszProvName, info->dwProvType, 0);
5691 if (ret)
5693 DWORD i;
5695 for (i = 0; i < info->cProvParam; i++)
5696 CryptSetProvParam(*phProv, info->rgProvParam[i].dwParam,
5697 info->rgProvParam[i].pbData, info->rgProvParam[i].dwFlags);
5699 return ret;
5702 static BOOL export_is_key_exportable(HCRYPTPROV hProv, DWORD keySpec)
5704 BOOL ret;
5705 HCRYPTKEY key;
5707 if ((ret = CryptGetUserKey(hProv, keySpec, &key)))
5709 DWORD permissions, size = sizeof(permissions);
5711 if ((ret = CryptGetKeyParam(key, KP_PERMISSIONS, (BYTE *)&permissions,
5712 &size, 0)) && !(permissions & CRYPT_EXPORT))
5713 ret = FALSE;
5714 CryptDestroyKey(key);
5716 return ret;
5719 static LRESULT CALLBACK export_private_key_dlg_proc(HWND hwnd, UINT msg,
5720 WPARAM wp, LPARAM lp)
5722 LRESULT ret = 0;
5723 struct ExportWizData *data;
5725 switch (msg)
5727 case WM_INITDIALOG:
5729 PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5730 PCRYPT_KEY_PROV_INFO info;
5731 HCRYPTPROV hProv = 0;
5732 int errorID = 0;
5734 data = (struct ExportWizData *)page->lParam;
5735 SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5736 /* Get enough information about a key to see whether it's exportable.
5738 if (!(info = export_get_private_key_info(
5739 data->exportInfo.u.pCertContext)))
5740 errorID = IDS_EXPORT_PRIVATE_KEY_UNAVAILABLE;
5741 else if (!export_acquire_private_key(info, &hProv))
5742 errorID = IDS_EXPORT_PRIVATE_KEY_UNAVAILABLE;
5743 else if (!export_is_key_exportable(hProv, info->dwKeySpec))
5744 errorID = IDS_EXPORT_PRIVATE_KEY_NON_EXPORTABLE;
5746 if (errorID)
5748 WCHAR error[MAX_STRING_LEN];
5750 LoadStringW(hInstance, errorID, error,
5751 sizeof(error) / sizeof(error[0]));
5752 SendMessageW(GetDlgItem(hwnd, IDC_EXPORT_PRIVATE_KEY_UNAVAILABLE),
5753 WM_SETTEXT, 0, (LPARAM)error);
5754 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_PRIVATE_KEY_YES), FALSE);
5756 else
5757 data->keyProvInfo = info;
5758 if (hProv)
5759 CryptReleaseContext(hProv, 0);
5760 SendMessageW(GetDlgItem(hwnd, IDC_EXPORT_PRIVATE_KEY_NO), BM_CLICK,
5761 0, 0);
5762 break;
5764 case WM_NOTIFY:
5766 NMHDR *hdr = (NMHDR *)lp;
5768 switch (hdr->code)
5770 case PSN_SETACTIVE:
5771 PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5772 PSWIZB_BACK | PSWIZB_NEXT);
5773 ret = TRUE;
5774 break;
5775 case PSN_WIZNEXT:
5776 data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5777 if (IsDlgButtonChecked(hwnd, IDC_EXPORT_PRIVATE_KEY_NO))
5779 data->contextInfo.dwExportFormat =
5780 CRYPTUI_WIZ_EXPORT_FORMAT_DER;
5781 data->contextInfo.fExportPrivateKeys = FALSE;
5783 else
5785 data->contextInfo.dwExportFormat =
5786 CRYPTUI_WIZ_EXPORT_FORMAT_PFX;
5787 data->contextInfo.fExportPrivateKeys = TRUE;
5789 break;
5791 break;
5794 return ret;
5797 static BOOL export_info_has_private_key(PCCRYPTUI_WIZ_EXPORT_INFO pExportInfo)
5799 BOOL ret = FALSE;
5801 if (pExportInfo->dwSubjectChoice == CRYPTUI_WIZ_EXPORT_CERT_CONTEXT)
5803 DWORD size;
5805 /* If there's a CRYPT_KEY_PROV_INFO set for this cert, assume the
5806 * cert has a private key.
5808 if (CertGetCertificateContextProperty(pExportInfo->u.pCertContext,
5809 CERT_KEY_PROV_INFO_PROP_ID, NULL, &size))
5810 ret = TRUE;
5812 return ret;
5815 static void export_format_enable_controls(HWND hwnd, const struct ExportWizData *data)
5817 int defaultFormatID;
5819 switch (data->contextInfo.dwExportFormat)
5821 case CRYPTUI_WIZ_EXPORT_FORMAT_BASE64:
5822 defaultFormatID = IDC_EXPORT_FORMAT_BASE64;
5823 break;
5824 case CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7:
5825 defaultFormatID = IDC_EXPORT_FORMAT_CMS;
5826 break;
5827 case CRYPTUI_WIZ_EXPORT_FORMAT_PFX:
5828 defaultFormatID = IDC_EXPORT_FORMAT_PFX;
5829 break;
5830 default:
5831 defaultFormatID = IDC_EXPORT_FORMAT_DER;
5833 SendMessageW(GetDlgItem(hwnd, defaultFormatID), BM_CLICK, 0, 0);
5834 if (defaultFormatID == IDC_EXPORT_FORMAT_PFX)
5836 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_DER), FALSE);
5837 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_BASE64), FALSE);
5838 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_CMS), FALSE);
5839 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_PFX), TRUE);
5841 else
5843 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_DER), TRUE);
5844 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_BASE64), TRUE);
5845 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_CMS), TRUE);
5846 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_FORMAT_PFX), FALSE);
5850 static LRESULT CALLBACK export_format_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
5851 LPARAM lp)
5853 LRESULT ret = 0;
5854 struct ExportWizData *data;
5856 switch (msg)
5858 case WM_INITDIALOG:
5860 PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5862 data = (struct ExportWizData *)page->lParam;
5863 SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5864 export_format_enable_controls(hwnd, data);
5865 break;
5867 case WM_NOTIFY:
5869 NMHDR *hdr = (NMHDR *)lp;
5871 switch (hdr->code)
5873 case PSN_SETACTIVE:
5874 PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5875 PSWIZB_BACK | PSWIZB_NEXT);
5876 data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5877 export_format_enable_controls(hwnd, data);
5878 ret = TRUE;
5879 break;
5880 case PSN_WIZNEXT:
5882 BOOL skipPasswordPage = TRUE;
5884 data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
5885 if (IsDlgButtonChecked(hwnd, IDC_EXPORT_FORMAT_DER))
5886 data->contextInfo.dwExportFormat =
5887 CRYPTUI_WIZ_EXPORT_FORMAT_DER;
5888 else if (IsDlgButtonChecked(hwnd, IDC_EXPORT_FORMAT_BASE64))
5889 data->contextInfo.dwExportFormat =
5890 CRYPTUI_WIZ_EXPORT_FORMAT_BASE64;
5891 else if (IsDlgButtonChecked(hwnd, IDC_EXPORT_FORMAT_CMS))
5893 data->contextInfo.dwExportFormat =
5894 CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7;
5895 if (IsDlgButtonChecked(hwnd, IDC_EXPORT_CMS_INCLUDE_CHAIN))
5896 data->contextInfo.fExportChain =
5897 CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7;
5899 else
5901 data->contextInfo.dwExportFormat =
5902 CRYPTUI_WIZ_EXPORT_FORMAT_PFX;
5903 if (IsDlgButtonChecked(hwnd, IDC_EXPORT_PFX_INCLUDE_CHAIN))
5904 data->contextInfo.fExportChain = TRUE;
5905 if (IsDlgButtonChecked(hwnd, IDC_EXPORT_PFX_STRONG_ENCRYPTION))
5906 data->contextInfo.fStrongEncryption = TRUE;
5907 if (IsDlgButtonChecked(hwnd, IDC_EXPORT_PFX_DELETE_PRIVATE_KEY))
5908 data->deleteKeys = TRUE;
5909 skipPasswordPage = FALSE;
5911 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT,
5912 skipPasswordPage ? IDD_EXPORT_FILE : 0);
5913 ret = 1;
5914 break;
5917 break;
5919 case WM_COMMAND:
5920 switch (HIWORD(wp))
5922 case BN_CLICKED:
5923 switch (LOWORD(wp))
5925 case IDC_EXPORT_FORMAT_DER:
5926 case IDC_EXPORT_FORMAT_BASE64:
5927 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_CMS_INCLUDE_CHAIN),
5928 FALSE);
5929 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_PFX_INCLUDE_CHAIN),
5930 FALSE);
5931 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_PFX_STRONG_ENCRYPTION),
5932 FALSE);
5933 EnableWindow(GetDlgItem(hwnd,
5934 IDC_EXPORT_PFX_DELETE_PRIVATE_KEY), FALSE);
5935 break;
5936 case IDC_EXPORT_FORMAT_CMS:
5937 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_CMS_INCLUDE_CHAIN),
5938 TRUE);
5939 break;
5940 case IDC_EXPORT_FORMAT_PFX:
5941 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_PFX_INCLUDE_CHAIN),
5942 TRUE);
5943 EnableWindow(GetDlgItem(hwnd, IDC_EXPORT_PFX_STRONG_ENCRYPTION),
5944 TRUE);
5945 EnableWindow(GetDlgItem(hwnd,
5946 IDC_EXPORT_PFX_DELETE_PRIVATE_KEY), TRUE);
5947 break;
5949 break;
5951 break;
5953 return ret;
5956 static void export_password_mismatch(HWND hwnd, const struct ExportWizData *data)
5958 WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
5959 LPCWSTR pTitle;
5961 if (data->pwszWizardTitle)
5962 pTitle = data->pwszWizardTitle;
5963 else
5965 LoadStringW(hInstance, IDS_EXPORT_WIZARD, title,
5966 sizeof(title) / sizeof(title[0]));
5967 pTitle = title;
5969 LoadStringW(hInstance, IDS_EXPORT_PASSWORD_MISMATCH, error,
5970 sizeof(error) / sizeof(error[0]));
5971 MessageBoxW(hwnd, error, pTitle, MB_ICONERROR | MB_OK);
5972 SetFocus(GetDlgItem(hwnd, IDC_EXPORT_PASSWORD));
5975 static LRESULT CALLBACK export_password_dlg_proc(HWND hwnd, UINT msg,
5976 WPARAM wp, LPARAM lp)
5978 LRESULT ret = 0;
5979 struct ExportWizData *data;
5981 switch (msg)
5983 case WM_INITDIALOG:
5985 PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
5987 data = (struct ExportWizData *)page->lParam;
5988 SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
5989 break;
5991 case WM_NOTIFY:
5993 NMHDR *hdr = (NMHDR *)lp;
5995 switch (hdr->code)
5997 case PSN_SETACTIVE:
5998 PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
5999 PSWIZB_BACK | PSWIZB_NEXT);
6000 ret = TRUE;
6001 break;
6002 case PSN_WIZNEXT:
6004 HWND passwordEdit = GetDlgItem(hwnd, IDC_EXPORT_PASSWORD);
6005 HWND passwordConfirmEdit = GetDlgItem(hwnd,
6006 IDC_EXPORT_PASSWORD_CONFIRM);
6007 DWORD passwordLen = SendMessageW(passwordEdit, WM_GETTEXTLENGTH,
6008 0, 0);
6009 DWORD passwordConfirmLen = SendMessageW(passwordConfirmEdit,
6010 WM_GETTEXTLENGTH, 0, 0);
6012 data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
6013 if (!passwordLen && !passwordConfirmLen)
6014 data->contextInfo.pwszPassword = NULL;
6015 else if (passwordLen != passwordConfirmLen)
6017 export_password_mismatch(hwnd, data);
6018 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
6019 ret = 1;
6021 else
6023 LPWSTR password = HeapAlloc(GetProcessHeap(), 0,
6024 (passwordLen + 1) * sizeof(WCHAR));
6025 LPWSTR passwordConfirm = HeapAlloc(GetProcessHeap(), 0,
6026 (passwordConfirmLen + 1) * sizeof(WCHAR));
6027 BOOL freePassword = TRUE;
6029 if (password && passwordConfirm)
6031 SendMessageW(passwordEdit, WM_GETTEXT, passwordLen + 1,
6032 (LPARAM)password);
6033 SendMessageW(passwordConfirmEdit, WM_GETTEXT,
6034 passwordConfirmLen + 1, (LPARAM)passwordConfirm);
6035 if (strcmpW(password, passwordConfirm))
6037 export_password_mismatch(hwnd, data);
6038 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
6039 ret = 1;
6041 else
6043 data->contextInfo.pwszPassword = password;
6044 freePassword = FALSE;
6045 data->freePassword = TRUE;
6048 if (freePassword)
6049 HeapFree(GetProcessHeap(), 0, password);
6050 HeapFree(GetProcessHeap(), 0, passwordConfirm);
6052 break;
6055 break;
6058 return ret;
6061 static LPWSTR export_append_extension(const struct ExportWizData *data,
6062 LPWSTR fileName)
6064 static const WCHAR cer[] = { '.','c','e','r',0 };
6065 static const WCHAR crl[] = { '.','c','r','l',0 };
6066 static const WCHAR ctl[] = { '.','c','t','l',0 };
6067 static const WCHAR p7b[] = { '.','p','7','b',0 };
6068 static const WCHAR pfx[] = { '.','p','f','x',0 };
6069 static const WCHAR sst[] = { '.','s','s','t',0 };
6070 LPCWSTR extension;
6071 LPWSTR dot;
6072 BOOL appendExtension;
6074 switch (data->contextInfo.dwExportFormat)
6076 case CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7:
6077 extension = p7b;
6078 break;
6079 case CRYPTUI_WIZ_EXPORT_FORMAT_PFX:
6080 extension = pfx;
6081 break;
6082 default:
6083 switch (data->exportInfo.dwSubjectChoice)
6085 case CRYPTUI_WIZ_EXPORT_CRL_CONTEXT:
6086 extension = crl;
6087 break;
6088 case CRYPTUI_WIZ_EXPORT_CTL_CONTEXT:
6089 extension = ctl;
6090 break;
6091 case CRYPTUI_WIZ_EXPORT_CERT_STORE:
6092 extension = sst;
6093 break;
6094 default:
6095 extension = cer;
6098 dot = strrchrW(fileName, '.');
6099 if (dot)
6100 appendExtension = strcmpiW(dot, extension) != 0;
6101 else
6102 appendExtension = TRUE;
6103 if (appendExtension)
6105 fileName = HeapReAlloc(GetProcessHeap(), 0, fileName,
6106 (strlenW(fileName) + strlenW(extension) + 1) * sizeof(WCHAR));
6107 if (fileName)
6108 strcatW(fileName, extension);
6110 return fileName;
6113 static BOOL export_validate_filename(HWND hwnd, struct ExportWizData *data,
6114 LPCWSTR fileName)
6116 HANDLE file;
6117 BOOL tryCreate = TRUE, forceCreate = FALSE, ret = FALSE;
6119 file = CreateFileW(fileName, GENERIC_WRITE,
6120 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
6121 if (file != INVALID_HANDLE_VALUE)
6123 WCHAR warning[MAX_STRING_LEN], title[MAX_STRING_LEN];
6124 LPCWSTR pTitle;
6126 if (data->pwszWizardTitle)
6127 pTitle = data->pwszWizardTitle;
6128 else
6130 LoadStringW(hInstance, IDS_EXPORT_WIZARD, title,
6131 sizeof(title) / sizeof(title[0]));
6132 pTitle = title;
6134 LoadStringW(hInstance, IDS_EXPORT_FILE_EXISTS, warning,
6135 sizeof(warning) / sizeof(warning[0]));
6136 if (MessageBoxW(hwnd, warning, pTitle, MB_YESNO) == IDYES)
6137 forceCreate = TRUE;
6138 else
6139 tryCreate = FALSE;
6140 CloseHandle(file);
6142 if (tryCreate)
6144 file = CreateFileW(fileName, GENERIC_WRITE,
6145 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
6146 forceCreate ? CREATE_ALWAYS : CREATE_NEW,
6147 0, NULL);
6148 if (file != INVALID_HANDLE_VALUE)
6150 data->file = file;
6151 ret = TRUE;
6153 else
6155 WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
6156 LPCWSTR pTitle;
6157 LPWSTR msgBuf, fullError;
6159 if (data->pwszWizardTitle)
6160 pTitle = data->pwszWizardTitle;
6161 else
6163 LoadStringW(hInstance, IDS_EXPORT_WIZARD, title,
6164 sizeof(title) / sizeof(title[0]));
6165 pTitle = title;
6167 LoadStringW(hInstance, IDS_IMPORT_OPEN_FAILED, error,
6168 sizeof(error) / sizeof(error[0]));
6169 FormatMessageW(
6170 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL,
6171 GetLastError(), 0, (LPWSTR) &msgBuf, 0, NULL);
6172 fullError = HeapAlloc(GetProcessHeap(), 0,
6173 (strlenW(error) + strlenW(fileName) + strlenW(msgBuf) + 3)
6174 * sizeof(WCHAR));
6175 if (fullError)
6177 LPWSTR ptr = fullError;
6179 strcpyW(ptr, error);
6180 ptr += strlenW(error);
6181 strcpyW(ptr, fileName);
6182 ptr += strlenW(fileName);
6183 *ptr++ = ':';
6184 *ptr++ = '\n';
6185 strcpyW(ptr, msgBuf);
6186 MessageBoxW(hwnd, fullError, pTitle, MB_ICONERROR | MB_OK);
6187 HeapFree(GetProcessHeap(), 0, fullError);
6189 LocalFree(msgBuf);
6192 return ret;
6195 static const WCHAR export_filter_cert[] = { '*','.','c','e','r',0 };
6196 static const WCHAR export_filter_crl[] = { '*','.','c','r','l',0 };
6197 static const WCHAR export_filter_ctl[] = { '*','.','s','t','l',0 };
6198 static const WCHAR export_filter_cms[] = { '*','.','p','7','b',0 };
6199 static const WCHAR export_filter_pfx[] = { '*','.','p','f','x',0 };
6200 static const WCHAR export_filter_sst[] = { '*','.','s','s','t',0 };
6202 static WCHAR *make_export_file_filter(DWORD exportFormat, DWORD subjectChoice)
6204 int baseLen, allLen, totalLen = 2, baseID;
6205 LPWSTR filter = NULL, baseFilter, all;
6206 LPCWSTR filterStr;
6208 switch (exportFormat)
6210 case CRYPTUI_WIZ_EXPORT_FORMAT_BASE64:
6211 baseID = IDS_EXPORT_FILTER_BASE64_CERT;
6212 filterStr = export_filter_cert;
6213 break;
6214 case CRYPTUI_WIZ_EXPORT_FORMAT_PFX:
6215 baseID = IDS_EXPORT_FILTER_PFX;
6216 filterStr = export_filter_pfx;
6217 break;
6218 case CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7:
6219 baseID = IDS_EXPORT_FILTER_CMS;
6220 filterStr = export_filter_cms;
6221 break;
6222 default:
6223 switch (subjectChoice)
6225 case CRYPTUI_WIZ_EXPORT_CRL_CONTEXT:
6226 baseID = IDS_EXPORT_FILTER_CRL;
6227 filterStr = export_filter_crl;
6228 break;
6229 case CRYPTUI_WIZ_EXPORT_CTL_CONTEXT:
6230 baseID = IDS_EXPORT_FILTER_CTL;
6231 filterStr = export_filter_ctl;
6232 break;
6233 case CRYPTUI_WIZ_EXPORT_CERT_STORE:
6234 baseID = IDS_EXPORT_FILTER_SERIALIZED_CERT_STORE;
6235 filterStr = export_filter_sst;
6236 break;
6237 default:
6238 baseID = IDS_EXPORT_FILTER_CERT;
6239 filterStr = export_filter_cert;
6240 break;
6243 baseLen = LoadStringW(hInstance, baseID, (LPWSTR)&baseFilter, 0);
6244 totalLen += baseLen + strlenW(filterStr) + 2;
6245 allLen = LoadStringW(hInstance, IDS_IMPORT_FILTER_ALL, (LPWSTR)&all, 0);
6246 totalLen += allLen + strlenW(filter_all) + 2;
6247 filter = HeapAlloc(GetProcessHeap(), 0, totalLen * sizeof(WCHAR));
6248 if (filter)
6250 LPWSTR ptr;
6252 ptr = filter;
6253 memcpy(ptr, baseFilter, baseLen * sizeof(WCHAR));
6254 ptr += baseLen;
6255 *ptr++ = 0;
6256 strcpyW(ptr, filterStr);
6257 ptr += strlenW(filterStr) + 1;
6258 memcpy(ptr, all, allLen * sizeof(WCHAR));
6259 ptr += allLen;
6260 *ptr++ = 0;
6261 strcpyW(ptr, filter_all);
6262 ptr += strlenW(filter_all) + 1;
6263 *ptr++ = 0;
6265 return filter;
6268 static LRESULT CALLBACK export_file_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
6269 LPARAM lp)
6271 LRESULT ret = 0;
6272 struct ExportWizData *data;
6274 switch (msg)
6276 case WM_INITDIALOG:
6278 PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
6280 data = (struct ExportWizData *)page->lParam;
6281 SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
6282 if (data->exportInfo.pwszExportFileName)
6283 SendMessageW(GetDlgItem(hwnd, IDC_EXPORT_FILENAME), WM_SETTEXT, 0,
6284 (LPARAM)data->exportInfo.pwszExportFileName);
6285 break;
6287 case WM_NOTIFY:
6289 NMHDR *hdr = (NMHDR *)lp;
6291 switch (hdr->code)
6293 case PSN_WIZBACK:
6294 data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
6295 if (data->contextInfo.dwExportFormat !=
6296 CRYPTUI_WIZ_EXPORT_FORMAT_PFX)
6298 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, IDD_EXPORT_FORMAT);
6299 ret = 1;
6301 break;
6302 case PSN_WIZNEXT:
6304 HWND fileNameEdit = GetDlgItem(hwnd, IDC_EXPORT_FILENAME);
6305 DWORD len = SendMessageW(fileNameEdit, WM_GETTEXTLENGTH, 0, 0);
6307 data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
6308 if (!len)
6310 WCHAR title[MAX_STRING_LEN], error[MAX_STRING_LEN];
6311 LPCWSTR pTitle;
6313 if (data->pwszWizardTitle)
6314 pTitle = data->pwszWizardTitle;
6315 else
6317 LoadStringW(hInstance, IDS_EXPORT_WIZARD, title,
6318 sizeof(title) / sizeof(title[0]));
6319 pTitle = title;
6321 LoadStringW(hInstance, IDS_IMPORT_EMPTY_FILE, error,
6322 sizeof(error) / sizeof(error[0]));
6323 MessageBoxW(hwnd, error, pTitle, MB_ICONERROR | MB_OK);
6324 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
6325 ret = 1;
6327 else
6329 LPWSTR fileName = HeapAlloc(GetProcessHeap(), 0,
6330 (len + 1) * sizeof(WCHAR));
6332 if (fileName)
6334 SendMessageW(fileNameEdit, WM_GETTEXT, len + 1,
6335 (LPARAM)fileName);
6336 fileName = export_append_extension(data, fileName);
6337 if (!export_validate_filename(hwnd, data, fileName))
6339 HeapFree(GetProcessHeap(), 0, fileName);
6340 SetWindowLongPtrW(hwnd, DWLP_MSGRESULT, 1);
6341 ret = 1;
6343 else
6344 data->fileName = fileName;
6347 break;
6349 case PSN_SETACTIVE:
6350 PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
6351 PSWIZB_BACK | PSWIZB_NEXT);
6352 ret = TRUE;
6353 break;
6355 break;
6357 case WM_COMMAND:
6358 switch (wp)
6360 case IDC_EXPORT_BROWSE_FILE:
6362 OPENFILENAMEW ofn;
6363 WCHAR fileBuf[MAX_PATH];
6365 data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
6366 memset(&ofn, 0, sizeof(ofn));
6367 ofn.lStructSize = sizeof(ofn);
6368 ofn.hwndOwner = hwnd;
6369 ofn.lpstrFilter = make_export_file_filter(
6370 data->contextInfo.dwExportFormat,
6371 data->exportInfo.dwSubjectChoice);
6372 ofn.lpstrFile = fileBuf;
6373 ofn.nMaxFile = sizeof(fileBuf) / sizeof(fileBuf[0]);
6374 fileBuf[0] = 0;
6375 if (GetSaveFileNameW(&ofn))
6376 SendMessageW(GetDlgItem(hwnd, IDC_EXPORT_FILENAME), WM_SETTEXT,
6377 0, (LPARAM)ofn.lpstrFile);
6378 HeapFree(GetProcessHeap(), 0, (LPWSTR)ofn.lpstrFilter);
6379 break;
6382 break;
6384 return ret;
6387 static void show_export_details(HWND lv, const struct ExportWizData *data)
6389 WCHAR text[MAX_STRING_LEN];
6390 LVITEMW item;
6391 int contentID;
6393 item.mask = LVIF_TEXT;
6394 if (data->fileName)
6396 item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
6397 item.iSubItem = 0;
6398 LoadStringW(hInstance, IDS_IMPORT_FILE, text,
6399 sizeof(text)/ sizeof(text[0]));
6400 item.pszText = text;
6401 SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
6402 item.iSubItem = 1;
6403 item.pszText = data->fileName;
6404 SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
6407 item.pszText = text;
6408 switch (data->exportInfo.dwSubjectChoice)
6410 case CRYPTUI_WIZ_EXPORT_CRL_CONTEXT:
6411 case CRYPTUI_WIZ_EXPORT_CTL_CONTEXT:
6412 case CRYPTUI_WIZ_EXPORT_CERT_STORE:
6413 case CRYPTUI_WIZ_EXPORT_CERT_STORE_CERTIFICATES_ONLY:
6414 /* do nothing */
6415 break;
6416 default:
6418 item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
6419 item.iSubItem = 0;
6420 LoadStringW(hInstance, IDS_EXPORT_INCLUDE_CHAIN, text,
6421 sizeof(text) / sizeof(text[0]));
6422 SendMessageW(lv, LVM_INSERTITEMW, item.iItem, (LPARAM)&item);
6423 item.iSubItem = 1;
6424 LoadStringW(hInstance,
6425 data->contextInfo.fExportChain ? IDS_YES : IDS_NO, text,
6426 sizeof(text) / sizeof(text[0]));
6427 SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
6429 item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
6430 item.iSubItem = 0;
6431 LoadStringW(hInstance, IDS_EXPORT_KEYS, text,
6432 sizeof(text) / sizeof(text[0]));
6433 SendMessageW(lv, LVM_INSERTITEMW, item.iItem, (LPARAM)&item);
6434 item.iSubItem = 1;
6435 LoadStringW(hInstance,
6436 data->contextInfo.fExportPrivateKeys ? IDS_YES : IDS_NO, text,
6437 sizeof(text) / sizeof(text[0]));
6438 SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
6442 item.iItem = SendMessageW(lv, LVM_GETITEMCOUNT, 0, 0);
6443 item.iSubItem = 0;
6444 LoadStringW(hInstance, IDS_EXPORT_FORMAT, text,
6445 sizeof(text)/ sizeof(text[0]));
6446 SendMessageW(lv, LVM_INSERTITEMW, 0, (LPARAM)&item);
6448 item.iSubItem = 1;
6449 switch (data->exportInfo.dwSubjectChoice)
6451 case CRYPTUI_WIZ_EXPORT_CRL_CONTEXT:
6452 contentID = IDS_EXPORT_FILTER_CRL;
6453 break;
6454 case CRYPTUI_WIZ_EXPORT_CTL_CONTEXT:
6455 contentID = IDS_EXPORT_FILTER_CTL;
6456 break;
6457 case CRYPTUI_WIZ_EXPORT_CERT_STORE:
6458 contentID = IDS_EXPORT_FILTER_SERIALIZED_CERT_STORE;
6459 break;
6460 default:
6461 switch (data->contextInfo.dwExportFormat)
6463 case CRYPTUI_WIZ_EXPORT_FORMAT_BASE64:
6464 contentID = IDS_EXPORT_FILTER_BASE64_CERT;
6465 break;
6466 case CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7:
6467 contentID = IDS_EXPORT_FILTER_CMS;
6468 break;
6469 case CRYPTUI_WIZ_EXPORT_FORMAT_PFX:
6470 contentID = IDS_EXPORT_FILTER_PFX;
6471 break;
6472 default:
6473 contentID = IDS_EXPORT_FILTER_CERT;
6476 LoadStringW(hInstance, contentID, text, sizeof(text) / sizeof(text[0]));
6477 SendMessageW(lv, LVM_SETITEMTEXTW, item.iItem, (LPARAM)&item);
6480 static inline BOOL save_der(HANDLE file, const BYTE *pb, DWORD cb)
6482 DWORD bytesWritten;
6484 return WriteFile(file, pb, cb, &bytesWritten, NULL);
6487 static BOOL save_base64(HANDLE file, const BYTE *pb, DWORD cb)
6489 BOOL ret;
6490 DWORD size = 0;
6492 if ((ret = CryptBinaryToStringA(pb, cb, CRYPT_STRING_BASE64, NULL, &size)))
6494 LPSTR buf = HeapAlloc(GetProcessHeap(), 0, size);
6496 if (buf)
6498 if ((ret = CryptBinaryToStringA(pb, cb, CRYPT_STRING_BASE64, buf,
6499 &size)))
6500 ret = WriteFile(file, buf, size, &size, NULL);
6501 HeapFree(GetProcessHeap(), 0, buf);
6503 else
6505 SetLastError(ERROR_OUTOFMEMORY);
6506 ret = FALSE;
6509 return ret;
6512 static inline BOOL save_store_as_cms(HANDLE file, HCERTSTORE store)
6514 return CertSaveStore(store, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
6515 CERT_STORE_SAVE_AS_PKCS7, CERT_STORE_SAVE_TO_FILE, file, 0);
6518 static BOOL save_cert_as_cms(HANDLE file, PCCRYPTUI_WIZ_EXPORT_INFO pExportInfo,
6519 BOOL includeChain)
6521 BOOL ret;
6522 HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
6523 CERT_STORE_CREATE_NEW_FLAG, NULL);
6525 if (store)
6527 if (includeChain)
6529 HCERTSTORE addlStore = CertOpenStore(CERT_STORE_PROV_COLLECTION,
6530 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL);
6532 if (addlStore)
6534 DWORD i;
6536 ret = TRUE;
6537 for (i = 0; ret && i < pExportInfo->cStores; i++)
6538 ret = CertAddStoreToCollection(addlStore,
6539 pExportInfo->rghStores, 0, 0);
6540 if (ret)
6542 PCCERT_CHAIN_CONTEXT chain;
6544 ret = CertGetCertificateChain(NULL,
6545 pExportInfo->u.pCertContext, NULL, addlStore, NULL, 0,
6546 NULL, &chain);
6547 if (ret)
6549 DWORD j;
6551 for (i = 0; ret && i < chain->cChain; i++)
6552 for (j = 0; ret && j < chain->rgpChain[i]->cElement;
6553 j++)
6554 ret = CertAddCertificateContextToStore(store,
6555 chain->rgpChain[i]->rgpElement[j]->pCertContext,
6556 CERT_STORE_ADD_ALWAYS, NULL);
6557 CertFreeCertificateChain(chain);
6559 else
6561 /* No chain could be created, just add the individual
6562 * cert to the message.
6564 ret = CertAddCertificateContextToStore(store,
6565 pExportInfo->u.pCertContext, CERT_STORE_ADD_ALWAYS,
6566 NULL);
6569 CertCloseStore(addlStore, 0);
6571 else
6572 ret = FALSE;
6574 else
6575 ret = CertAddCertificateContextToStore(store,
6576 pExportInfo->u.pCertContext, CERT_STORE_ADD_ALWAYS, NULL);
6577 if (ret)
6578 ret = save_store_as_cms(file, store);
6579 CertCloseStore(store, 0);
6581 else
6582 ret = FALSE;
6583 return ret;
6586 static BOOL save_serialized_store(HANDLE file, HCERTSTORE store)
6588 return CertSaveStore(store, PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
6589 CERT_STORE_SAVE_AS_STORE, CERT_STORE_SAVE_TO_FILE, file, 0);
6592 static BOOL save_pfx(HANDLE file, PCCRYPTUI_WIZ_EXPORT_INFO pExportInfo,
6593 PCCRYPTUI_WIZ_EXPORT_CERTCONTEXT_INFO pContextInfo,
6594 PCRYPT_KEY_PROV_INFO keyProvInfo, BOOL deleteKeys)
6596 HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, X509_ASN_ENCODING,
6597 0, CERT_STORE_CREATE_NEW_FLAG, NULL);
6598 BOOL ret = FALSE;
6600 if (store)
6602 CRYPT_DATA_BLOB pfxBlob = { 0, NULL };
6603 PCCERT_CONTEXT cert = NULL;
6604 BOOL freeKeyProvInfo = FALSE;
6606 if (pContextInfo->fExportChain)
6608 HCERTCHAINENGINE engine = NULL;
6610 if (pExportInfo->cStores)
6612 CERT_CHAIN_ENGINE_CONFIG config;
6614 memset(&config, 0, sizeof(config));
6615 config.cbSize = sizeof(config);
6616 config.cAdditionalStore = pExportInfo->cStores;
6617 config.rghAdditionalStore = pExportInfo->rghStores;
6618 ret = CertCreateCertificateChainEngine(&config, &engine);
6620 else
6621 ret = TRUE;
6622 if (ret)
6624 CERT_CHAIN_PARA chainPara;
6625 PCCERT_CHAIN_CONTEXT chain;
6627 memset(&chainPara, 0, sizeof(chainPara));
6628 chainPara.cbSize = sizeof(chainPara);
6629 ret = CertGetCertificateChain(engine,
6630 pExportInfo->u.pCertContext, NULL, NULL, &chainPara, 0, NULL,
6631 &chain);
6632 if (ret)
6634 DWORD i, j;
6636 for (i = 0; ret && i < chain->cChain; i++)
6637 for (j = 0; ret && j < chain->rgpChain[i]->cElement;
6638 j++)
6640 if (i == 0 && j == 0)
6641 ret = CertAddCertificateContextToStore(store,
6642 chain->rgpChain[i]->rgpElement[j]->pCertContext,
6643 CERT_STORE_ADD_ALWAYS, &cert);
6644 else
6645 ret = CertAddCertificateContextToStore(store,
6646 chain->rgpChain[i]->rgpElement[j]->pCertContext,
6647 CERT_STORE_ADD_ALWAYS, NULL);
6649 CertFreeCertificateChain(chain);
6652 if (engine)
6653 CertFreeCertificateChainEngine(engine);
6655 else
6656 ret = CertAddCertificateContextToStore(store,
6657 pExportInfo->u.pCertContext, CERT_STORE_ADD_ALWAYS, &cert);
6658 /* Copy private key info to newly created cert, so it'll get exported
6659 * along with the cert.
6661 if (ret && pContextInfo->fExportPrivateKeys)
6663 if (keyProvInfo)
6664 ret = CertSetCertificateContextProperty(cert,
6665 CERT_KEY_PROV_INFO_PROP_ID, 0, keyProvInfo);
6666 else
6668 if (!(keyProvInfo = export_get_private_key_info(cert)))
6669 ret = FALSE;
6670 else
6672 ret = CertSetCertificateContextProperty(cert,
6673 CERT_KEY_PROV_INFO_PROP_ID, 0, keyProvInfo);
6674 freeKeyProvInfo = TRUE;
6678 if (ret)
6680 DWORD exportFlags =
6681 REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY | EXPORT_PRIVATE_KEYS;
6683 ret = PFXExportCertStore(store, &pfxBlob,
6684 pContextInfo->pwszPassword, exportFlags);
6685 if (ret)
6687 pfxBlob.pbData = HeapAlloc(GetProcessHeap(), 0, pfxBlob.cbData);
6688 if (pfxBlob.pbData)
6690 ret = PFXExportCertStore(store, &pfxBlob,
6691 pContextInfo->pwszPassword, exportFlags);
6692 if (ret)
6694 DWORD bytesWritten;
6696 ret = WriteFile(file, pfxBlob.pbData, pfxBlob.cbData,
6697 &bytesWritten, NULL);
6700 else
6702 SetLastError(ERROR_OUTOFMEMORY);
6703 ret = FALSE;
6707 if (ret && deleteKeys)
6709 HCRYPTPROV prov;
6711 CryptAcquireContextW(&prov, keyProvInfo->pwszContainerName,
6712 keyProvInfo->pwszProvName, keyProvInfo->dwProvType,
6713 CRYPT_DELETEKEYSET);
6715 if (freeKeyProvInfo)
6716 HeapFree(GetProcessHeap(), 0, keyProvInfo);
6717 CertFreeCertificateContext(cert);
6718 CertCloseStore(store, 0);
6720 return ret;
6723 static BOOL do_export(HANDLE file, PCCRYPTUI_WIZ_EXPORT_INFO pExportInfo,
6724 PCCRYPTUI_WIZ_EXPORT_CERTCONTEXT_INFO pContextInfo,
6725 PCRYPT_KEY_PROV_INFO keyProvInfo, BOOL deleteKeys)
6727 BOOL ret;
6729 if (pContextInfo->dwSize != sizeof(CRYPTUI_WIZ_EXPORT_CERTCONTEXT_INFO))
6731 SetLastError(E_INVALIDARG);
6732 return FALSE;
6734 switch (pExportInfo->dwSubjectChoice)
6736 case CRYPTUI_WIZ_EXPORT_CRL_CONTEXT:
6737 ret = save_der(file,
6738 pExportInfo->u.pCRLContext->pbCrlEncoded,
6739 pExportInfo->u.pCRLContext->cbCrlEncoded);
6740 break;
6741 case CRYPTUI_WIZ_EXPORT_CTL_CONTEXT:
6742 ret = save_der(file,
6743 pExportInfo->u.pCTLContext->pbCtlEncoded,
6744 pExportInfo->u.pCTLContext->cbCtlEncoded);
6745 break;
6746 case CRYPTUI_WIZ_EXPORT_CERT_STORE:
6747 ret = save_serialized_store(file, pExportInfo->u.hCertStore);
6748 break;
6749 case CRYPTUI_WIZ_EXPORT_CERT_STORE_CERTIFICATES_ONLY:
6750 ret = save_store_as_cms(file, pExportInfo->u.hCertStore);
6751 break;
6752 default:
6753 switch (pContextInfo->dwExportFormat)
6755 case CRYPTUI_WIZ_EXPORT_FORMAT_DER:
6756 ret = save_der(file, pExportInfo->u.pCertContext->pbCertEncoded,
6757 pExportInfo->u.pCertContext->cbCertEncoded);
6758 break;
6759 case CRYPTUI_WIZ_EXPORT_FORMAT_BASE64:
6760 ret = save_base64(file,
6761 pExportInfo->u.pCertContext->pbCertEncoded,
6762 pExportInfo->u.pCertContext->cbCertEncoded);
6763 break;
6764 case CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7:
6765 ret = save_cert_as_cms(file, pExportInfo,
6766 pContextInfo->fExportChain);
6767 break;
6768 case CRYPTUI_WIZ_EXPORT_FORMAT_PFX:
6769 ret = save_pfx(file, pExportInfo, pContextInfo, keyProvInfo,
6770 deleteKeys);
6771 break;
6772 default:
6773 SetLastError(E_FAIL);
6774 ret = FALSE;
6777 return ret;
6780 static LRESULT CALLBACK export_finish_dlg_proc(HWND hwnd, UINT msg, WPARAM wp,
6781 LPARAM lp)
6783 LRESULT ret = 0;
6784 struct ExportWizData *data;
6786 switch (msg)
6788 case WM_INITDIALOG:
6790 PROPSHEETPAGEW *page = (PROPSHEETPAGEW *)lp;
6791 HWND lv = GetDlgItem(hwnd, IDC_EXPORT_SETTINGS);
6792 RECT rc;
6793 LVCOLUMNW column;
6795 data = (struct ExportWizData *)page->lParam;
6796 SetWindowLongPtrW(hwnd, DWLP_USER, (LPARAM)data);
6797 SendMessageW(GetDlgItem(hwnd, IDC_EXPORT_TITLE), WM_SETFONT,
6798 (WPARAM)data->titleFont, TRUE);
6799 GetWindowRect(lv, &rc);
6800 column.mask = LVCF_WIDTH;
6801 column.cx = (rc.right - rc.left) / 2 - 2;
6802 SendMessageW(lv, LVM_INSERTCOLUMNW, 0, (LPARAM)&column);
6803 SendMessageW(lv, LVM_INSERTCOLUMNW, 1, (LPARAM)&column);
6804 show_export_details(lv, data);
6805 break;
6807 case WM_NOTIFY:
6809 NMHDR *hdr = (NMHDR *)lp;
6811 switch (hdr->code)
6813 case PSN_SETACTIVE:
6815 HWND lv = GetDlgItem(hwnd, IDC_EXPORT_SETTINGS);
6817 data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
6818 SendMessageW(lv, LVM_DELETEALLITEMS, 0, 0);
6819 show_export_details(lv, data);
6820 PostMessageW(GetParent(hwnd), PSM_SETWIZBUTTONS, 0,
6821 PSWIZB_BACK | PSWIZB_FINISH);
6822 ret = TRUE;
6823 break;
6825 case PSN_WIZFINISH:
6827 int messageID;
6828 WCHAR title[MAX_STRING_LEN], message[MAX_STRING_LEN];
6829 LPCWSTR pTitle;
6830 DWORD mbFlags;
6832 data = (struct ExportWizData *)GetWindowLongPtrW(hwnd, DWLP_USER);
6833 if ((data->success = do_export(data->file, &data->exportInfo,
6834 &data->contextInfo, data->keyProvInfo, data->deleteKeys)))
6836 messageID = IDS_EXPORT_SUCCEEDED;
6837 mbFlags = MB_OK;
6839 else
6841 messageID = IDS_EXPORT_FAILED;
6842 mbFlags = MB_OK | MB_ICONERROR;
6844 if (data->pwszWizardTitle)
6845 pTitle = data->pwszWizardTitle;
6846 else
6848 LoadStringW(hInstance, IDS_EXPORT_WIZARD, title,
6849 sizeof(title) / sizeof(title[0]));
6850 pTitle = title;
6852 LoadStringW(hInstance, messageID, message,
6853 sizeof(message) / sizeof(message[0]));
6854 MessageBoxW(hwnd, message, pTitle, mbFlags);
6855 break;
6858 break;
6861 return ret;
6864 static BOOL show_export_ui(DWORD dwFlags, HWND hwndParent,
6865 LPCWSTR pwszWizardTitle, PCCRYPTUI_WIZ_EXPORT_INFO pExportInfo, const void *pvoid)
6867 PROPSHEETHEADERW hdr;
6868 PROPSHEETPAGEW pages[6];
6869 struct ExportWizData data;
6870 int nPages = 0;
6871 BOOL hasPrivateKey, showFormatPage = TRUE;
6872 INT_PTR l;
6874 data.dwFlags = dwFlags;
6875 data.pwszWizardTitle = pwszWizardTitle;
6876 memset(&data.exportInfo, 0, sizeof(data.exportInfo));
6877 memcpy(&data.exportInfo, pExportInfo,
6878 min(sizeof(data.exportInfo), pExportInfo->dwSize));
6879 if (pExportInfo->dwSize > sizeof(data.exportInfo))
6880 data.exportInfo.dwSize = sizeof(data.exportInfo);
6881 data.contextInfo.dwSize = sizeof(data.contextInfo);
6882 data.contextInfo.dwExportFormat = CRYPTUI_WIZ_EXPORT_FORMAT_DER;
6883 data.contextInfo.fExportChain = FALSE;
6884 data.contextInfo.fStrongEncryption = FALSE;
6885 data.contextInfo.fExportPrivateKeys = FALSE;
6886 data.contextInfo.pwszPassword = NULL;
6887 data.freePassword = FALSE;
6888 if (pExportInfo->dwSubjectChoice == CRYPTUI_WIZ_EXPORT_CERT_CONTEXT &&
6889 pvoid)
6890 memcpy(&data.contextInfo, pvoid,
6891 min(((PCCRYPTUI_WIZ_EXPORT_CERTCONTEXT_INFO)pvoid)->dwSize,
6892 sizeof(data.contextInfo)));
6893 data.keyProvInfo = NULL;
6894 data.deleteKeys = FALSE;
6895 data.fileName = NULL;
6896 data.file = INVALID_HANDLE_VALUE;
6897 data.success = FALSE;
6899 memset(&pages, 0, sizeof(pages));
6901 pages[nPages].dwSize = sizeof(pages[0]);
6902 pages[nPages].hInstance = hInstance;
6903 pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_WELCOME);
6904 pages[nPages].pfnDlgProc = export_welcome_dlg_proc;
6905 pages[nPages].dwFlags = PSP_HIDEHEADER;
6906 pages[nPages].lParam = (LPARAM)&data;
6907 nPages++;
6909 hasPrivateKey = export_info_has_private_key(pExportInfo);
6910 switch (pExportInfo->dwSubjectChoice)
6912 case CRYPTUI_WIZ_EXPORT_CRL_CONTEXT:
6913 case CRYPTUI_WIZ_EXPORT_CTL_CONTEXT:
6914 showFormatPage = FALSE;
6915 data.contextInfo.dwExportFormat = CRYPTUI_WIZ_EXPORT_FORMAT_DER;
6916 break;
6917 case CRYPTUI_WIZ_EXPORT_CERT_STORE:
6918 showFormatPage = FALSE;
6919 data.contextInfo.dwExportFormat =
6920 CRYPTUI_WIZ_EXPORT_FORMAT_SERIALIZED_CERT_STORE;
6921 break;
6922 case CRYPTUI_WIZ_EXPORT_CERT_STORE_CERTIFICATES_ONLY:
6923 showFormatPage = FALSE;
6924 data.contextInfo.dwExportFormat = CRYPTUI_WIZ_EXPORT_FORMAT_PKCS7;
6925 break;
6928 if (hasPrivateKey && showFormatPage)
6930 pages[nPages].dwSize = sizeof(pages[0]);
6931 pages[nPages].hInstance = hInstance;
6932 pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_PRIVATE_KEY);
6933 pages[nPages].pfnDlgProc = export_private_key_dlg_proc;
6934 pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
6935 pages[nPages].pszHeaderTitle =
6936 MAKEINTRESOURCEW(IDS_EXPORT_PRIVATE_KEY_TITLE);
6937 pages[nPages].pszHeaderSubTitle =
6938 MAKEINTRESOURCEW(IDS_EXPORT_PRIVATE_KEY_SUBTITLE);
6939 pages[nPages].lParam = (LPARAM)&data;
6940 nPages++;
6942 if (showFormatPage)
6944 pages[nPages].dwSize = sizeof(pages[0]);
6945 pages[nPages].hInstance = hInstance;
6946 pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_FORMAT);
6947 pages[nPages].pfnDlgProc = export_format_dlg_proc;
6948 pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
6949 pages[nPages].pszHeaderTitle =
6950 MAKEINTRESOURCEW(IDS_EXPORT_FORMAT_TITLE);
6951 pages[nPages].pszHeaderSubTitle =
6952 MAKEINTRESOURCEW(IDS_EXPORT_FORMAT_SUBTITLE);
6953 pages[nPages].lParam = (LPARAM)&data;
6954 nPages++;
6956 if (hasPrivateKey && showFormatPage)
6958 pages[nPages].dwSize = sizeof(pages[0]);
6959 pages[nPages].hInstance = hInstance;
6960 pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_PASSWORD);
6961 pages[nPages].pfnDlgProc = export_password_dlg_proc;
6962 pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
6963 pages[nPages].pszHeaderTitle =
6964 MAKEINTRESOURCEW(IDS_EXPORT_PASSWORD_TITLE);
6965 pages[nPages].pszHeaderSubTitle =
6966 MAKEINTRESOURCEW(IDS_EXPORT_PASSWORD_SUBTITLE);
6967 pages[nPages].lParam = (LPARAM)&data;
6968 nPages++;
6971 pages[nPages].dwSize = sizeof(pages[0]);
6972 pages[nPages].hInstance = hInstance;
6973 pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_FILE);
6974 pages[nPages].pfnDlgProc = export_file_dlg_proc;
6975 pages[nPages].dwFlags = PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
6976 pages[nPages].pszHeaderTitle = MAKEINTRESOURCEW(IDS_EXPORT_FILE_TITLE);
6977 pages[nPages].pszHeaderSubTitle =
6978 MAKEINTRESOURCEW(IDS_EXPORT_FILE_SUBTITLE);
6979 pages[nPages].lParam = (LPARAM)&data;
6980 nPages++;
6982 pages[nPages].dwSize = sizeof(pages[0]);
6983 pages[nPages].hInstance = hInstance;
6984 pages[nPages].u.pszTemplate = MAKEINTRESOURCEW(IDD_EXPORT_FINISH);
6985 pages[nPages].pfnDlgProc = export_finish_dlg_proc;
6986 pages[nPages].dwFlags = PSP_HIDEHEADER;
6987 pages[nPages].lParam = (LPARAM)&data;
6988 nPages++;
6990 memset(&hdr, 0, sizeof(hdr));
6991 hdr.dwSize = sizeof(hdr);
6992 hdr.hwndParent = hwndParent;
6993 hdr.dwFlags = PSH_PROPSHEETPAGE | PSH_WIZARD97_NEW | PSH_HEADER |
6994 PSH_WATERMARK;
6995 hdr.hInstance = hInstance;
6996 if (pwszWizardTitle)
6997 hdr.pszCaption = pwszWizardTitle;
6998 else
6999 hdr.pszCaption = MAKEINTRESOURCEW(IDS_EXPORT_WIZARD);
7000 hdr.u3.ppsp = pages;
7001 hdr.nPages = nPages;
7002 hdr.u4.pszbmWatermark = MAKEINTRESOURCEW(IDB_CERT_WATERMARK);
7003 hdr.u5.pszbmHeader = MAKEINTRESOURCEW(IDB_CERT_HEADER);
7004 l = PropertySheetW(&hdr);
7005 DeleteObject(data.titleFont);
7006 if (data.freePassword)
7007 HeapFree(GetProcessHeap(), 0,
7008 (LPWSTR)data.contextInfo.pwszPassword);
7009 HeapFree(GetProcessHeap(), 0, data.keyProvInfo);
7010 CloseHandle(data.file);
7011 HeapFree(GetProcessHeap(), 0, data.fileName);
7012 if (l == 0)
7014 SetLastError(ERROR_CANCELLED);
7015 return FALSE;
7017 else
7018 return data.success;
7021 BOOL WINAPI CryptUIWizExport(DWORD dwFlags, HWND hwndParent,
7022 LPCWSTR pwszWizardTitle, PCCRYPTUI_WIZ_EXPORT_INFO pExportInfo, void *pvoid)
7024 BOOL ret;
7026 TRACE("(%08x, %p, %s, %p, %p)\n", dwFlags, hwndParent,
7027 debugstr_w(pwszWizardTitle), pExportInfo, pvoid);
7029 if (!(dwFlags & CRYPTUI_WIZ_NO_UI))
7030 ret = show_export_ui(dwFlags, hwndParent, pwszWizardTitle, pExportInfo,
7031 pvoid);
7032 else
7034 HANDLE file = CreateFileW(pExportInfo->pwszExportFileName,
7035 GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
7036 CREATE_ALWAYS, 0, NULL);
7038 if (file != INVALID_HANDLE_VALUE)
7040 ret = do_export(file, pExportInfo, pvoid, NULL, FALSE);
7041 CloseHandle(file);
7043 else
7044 ret = FALSE;
7046 return ret;