rasapi32: Update spec file.
[wine/zf.git] / dlls / cryptnet / cryptnet_main.c
blobefcb3dc9ba2393fdd14e3fb74f38c10e42e16a15
1 /*
2 * Copyright (C) 2006 Maarten Lankhorst
3 * Copyright 2007 Juan Lang
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #define NONAMELESSUNION
22 #define CERT_REVOCATION_PARA_HAS_EXTRA_FIELDS
24 #include <stdio.h>
25 #include <stdarg.h>
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winnt.h"
30 #include "winnls.h"
31 #include "wininet.h"
32 #include "objbase.h"
33 #include "wincrypt.h"
35 #include "wine/debug.h"
37 WINE_DEFAULT_DEBUG_CHANNEL(cryptnet);
39 #define IS_INTOID(x) (((ULONG_PTR)(x) >> 16) == 0)
42 /***********************************************************************
43 * DllRegisterServer (CRYPTNET.@)
45 HRESULT WINAPI DllRegisterServer(void)
47 TRACE("\n");
48 CryptRegisterDefaultOIDFunction(X509_ASN_ENCODING,
49 CRYPT_OID_VERIFY_REVOCATION_FUNC, 0, L"cryptnet.dll");
50 CryptRegisterOIDFunction(0, CRYPT_OID_OPEN_STORE_PROV_FUNC, "Ldap",
51 L"cryptnet.dll", "LdapProvOpenStore");
52 CryptRegisterOIDFunction(0, CRYPT_OID_OPEN_STORE_PROV_FUNC,
53 CERT_STORE_PROV_LDAP_W, L"cryptnet.dll", "LdapProvOpenStore");
54 return S_OK;
57 /***********************************************************************
58 * DllUnregisterServer (CRYPTNET.@)
60 HRESULT WINAPI DllUnregisterServer(void)
62 TRACE("\n");
63 CryptUnregisterDefaultOIDFunction(X509_ASN_ENCODING,
64 CRYPT_OID_VERIFY_REVOCATION_FUNC, L"cryptnet.dll");
65 CryptUnregisterOIDFunction(0, CRYPT_OID_OPEN_STORE_PROV_FUNC, "Ldap");
66 CryptUnregisterOIDFunction(0, CRYPT_OID_OPEN_STORE_PROV_FUNC,
67 CERT_STORE_PROV_LDAP_W);
68 return S_OK;
71 static const char *url_oid_to_str(LPCSTR oid)
73 if (IS_INTOID(oid))
75 static char buf[10];
77 switch (LOWORD(oid))
79 #define _x(oid) case LOWORD(oid): return #oid
80 _x(URL_OID_CERTIFICATE_ISSUER);
81 _x(URL_OID_CERTIFICATE_CRL_DIST_POINT);
82 _x(URL_OID_CTL_ISSUER);
83 _x(URL_OID_CTL_NEXT_UPDATE);
84 _x(URL_OID_CRL_ISSUER);
85 _x(URL_OID_CERTIFICATE_FRESHEST_CRL);
86 _x(URL_OID_CRL_FRESHEST_CRL);
87 _x(URL_OID_CROSS_CERT_DIST_POINT);
88 #undef _x
89 default:
90 snprintf(buf, sizeof(buf), "%d", LOWORD(oid));
91 return buf;
94 else
95 return oid;
98 typedef BOOL (WINAPI *UrlDllGetObjectUrlFunc)(LPCSTR, LPVOID, DWORD,
99 PCRYPT_URL_ARRAY, DWORD *, PCRYPT_URL_INFO, DWORD *, LPVOID);
101 static BOOL WINAPI CRYPT_GetUrlFromCertificateIssuer(LPCSTR pszUrlOid,
102 LPVOID pvPara, DWORD dwFlags, PCRYPT_URL_ARRAY pUrlArray, DWORD *pcbUrlArray,
103 PCRYPT_URL_INFO pUrlInfo, DWORD *pcbUrlInfo, LPVOID pvReserved)
105 PCCERT_CONTEXT cert = pvPara;
106 PCERT_EXTENSION ext;
107 BOOL ret = FALSE;
109 /* The only applicable flag is CRYPT_GET_URL_FROM_EXTENSION */
110 if (dwFlags && !(dwFlags & CRYPT_GET_URL_FROM_EXTENSION))
112 SetLastError(CRYPT_E_NOT_FOUND);
113 return FALSE;
115 if ((ext = CertFindExtension(szOID_AUTHORITY_INFO_ACCESS,
116 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension)))
118 CERT_AUTHORITY_INFO_ACCESS *aia;
119 DWORD size;
121 ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_AUTHORITY_INFO_ACCESS,
122 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL,
123 &aia, &size);
124 if (ret)
126 DWORD i, cUrl, bytesNeeded = sizeof(CRYPT_URL_ARRAY);
128 for (i = 0, cUrl = 0; i < aia->cAccDescr; i++)
129 if (!strcmp(aia->rgAccDescr[i].pszAccessMethod,
130 szOID_PKIX_CA_ISSUERS))
132 if (aia->rgAccDescr[i].AccessLocation.dwAltNameChoice ==
133 CERT_ALT_NAME_URL)
135 if (aia->rgAccDescr[i].AccessLocation.u.pwszURL)
137 cUrl++;
138 bytesNeeded += sizeof(LPWSTR) +
139 (lstrlenW(aia->rgAccDescr[i].AccessLocation.u.
140 pwszURL) + 1) * sizeof(WCHAR);
143 else
144 FIXME("unsupported alt name type %d\n",
145 aia->rgAccDescr[i].AccessLocation.dwAltNameChoice);
147 if (!pcbUrlArray)
149 SetLastError(E_INVALIDARG);
150 ret = FALSE;
152 else if (!pUrlArray)
153 *pcbUrlArray = bytesNeeded;
154 else if (*pcbUrlArray < bytesNeeded)
156 SetLastError(ERROR_MORE_DATA);
157 *pcbUrlArray = bytesNeeded;
158 ret = FALSE;
160 else
162 LPWSTR nextUrl;
164 *pcbUrlArray = bytesNeeded;
165 pUrlArray->cUrl = 0;
166 pUrlArray->rgwszUrl =
167 (LPWSTR *)((BYTE *)pUrlArray + sizeof(CRYPT_URL_ARRAY));
168 nextUrl = (LPWSTR)((BYTE *)pUrlArray + sizeof(CRYPT_URL_ARRAY)
169 + cUrl * sizeof(LPWSTR));
170 for (i = 0; i < aia->cAccDescr; i++)
171 if (!strcmp(aia->rgAccDescr[i].pszAccessMethod,
172 szOID_PKIX_CA_ISSUERS))
174 if (aia->rgAccDescr[i].AccessLocation.dwAltNameChoice
175 == CERT_ALT_NAME_URL)
177 if (aia->rgAccDescr[i].AccessLocation.u.pwszURL)
179 lstrcpyW(nextUrl,
180 aia->rgAccDescr[i].AccessLocation.u.pwszURL);
181 pUrlArray->rgwszUrl[pUrlArray->cUrl++] =
182 nextUrl;
183 nextUrl += (lstrlenW(nextUrl) + 1);
188 if (ret)
190 if (pcbUrlInfo)
192 FIXME("url info: stub\n");
193 if (!pUrlInfo)
194 *pcbUrlInfo = sizeof(CRYPT_URL_INFO);
195 else if (*pcbUrlInfo < sizeof(CRYPT_URL_INFO))
197 *pcbUrlInfo = sizeof(CRYPT_URL_INFO);
198 SetLastError(ERROR_MORE_DATA);
199 ret = FALSE;
201 else
203 *pcbUrlInfo = sizeof(CRYPT_URL_INFO);
204 memset(pUrlInfo, 0, sizeof(CRYPT_URL_INFO));
208 LocalFree(aia);
211 else
212 SetLastError(CRYPT_E_NOT_FOUND);
213 return ret;
216 static BOOL CRYPT_GetUrlFromCRLDistPointsExt(const CRYPT_DATA_BLOB *value,
217 PCRYPT_URL_ARRAY pUrlArray, DWORD *pcbUrlArray, PCRYPT_URL_INFO pUrlInfo,
218 DWORD *pcbUrlInfo)
220 BOOL ret;
221 CRL_DIST_POINTS_INFO *info;
222 DWORD size;
224 ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_CRL_DIST_POINTS,
225 value->pbData, value->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &info, &size);
226 if (ret)
228 DWORD i, cUrl, bytesNeeded = sizeof(CRYPT_URL_ARRAY);
230 for (i = 0, cUrl = 0; i < info->cDistPoint; i++)
231 if (info->rgDistPoint[i].DistPointName.dwDistPointNameChoice
232 == CRL_DIST_POINT_FULL_NAME)
234 DWORD j;
235 CERT_ALT_NAME_INFO *name =
236 &info->rgDistPoint[i].DistPointName.u.FullName;
238 for (j = 0; j < name->cAltEntry; j++)
239 if (name->rgAltEntry[j].dwAltNameChoice ==
240 CERT_ALT_NAME_URL)
242 if (name->rgAltEntry[j].u.pwszURL)
244 cUrl++;
245 bytesNeeded += sizeof(LPWSTR) +
246 (lstrlenW(name->rgAltEntry[j].u.pwszURL) + 1)
247 * sizeof(WCHAR);
251 if (!pcbUrlArray)
253 SetLastError(E_INVALIDARG);
254 ret = FALSE;
256 else if (!pUrlArray)
257 *pcbUrlArray = bytesNeeded;
258 else if (*pcbUrlArray < bytesNeeded)
260 SetLastError(ERROR_MORE_DATA);
261 *pcbUrlArray = bytesNeeded;
262 ret = FALSE;
264 else
266 LPWSTR nextUrl;
268 *pcbUrlArray = bytesNeeded;
269 pUrlArray->cUrl = 0;
270 pUrlArray->rgwszUrl =
271 (LPWSTR *)((BYTE *)pUrlArray + sizeof(CRYPT_URL_ARRAY));
272 nextUrl = (LPWSTR)((BYTE *)pUrlArray + sizeof(CRYPT_URL_ARRAY)
273 + cUrl * sizeof(LPWSTR));
274 for (i = 0; i < info->cDistPoint; i++)
275 if (info->rgDistPoint[i].DistPointName.dwDistPointNameChoice
276 == CRL_DIST_POINT_FULL_NAME)
278 DWORD j;
279 CERT_ALT_NAME_INFO *name =
280 &info->rgDistPoint[i].DistPointName.u.FullName;
282 for (j = 0; j < name->cAltEntry; j++)
283 if (name->rgAltEntry[j].dwAltNameChoice ==
284 CERT_ALT_NAME_URL)
286 if (name->rgAltEntry[j].u.pwszURL)
288 lstrcpyW(nextUrl,
289 name->rgAltEntry[j].u.pwszURL);
290 pUrlArray->rgwszUrl[pUrlArray->cUrl++] =
291 nextUrl;
292 nextUrl +=
293 (lstrlenW(name->rgAltEntry[j].u.pwszURL) + 1);
298 if (ret)
300 if (pcbUrlInfo)
302 FIXME("url info: stub\n");
303 if (!pUrlInfo)
304 *pcbUrlInfo = sizeof(CRYPT_URL_INFO);
305 else if (*pcbUrlInfo < sizeof(CRYPT_URL_INFO))
307 *pcbUrlInfo = sizeof(CRYPT_URL_INFO);
308 SetLastError(ERROR_MORE_DATA);
309 ret = FALSE;
311 else
313 *pcbUrlInfo = sizeof(CRYPT_URL_INFO);
314 memset(pUrlInfo, 0, sizeof(CRYPT_URL_INFO));
318 LocalFree(info);
320 return ret;
323 static BOOL WINAPI CRYPT_GetUrlFromCertificateCRLDistPoint(LPCSTR pszUrlOid,
324 LPVOID pvPara, DWORD dwFlags, PCRYPT_URL_ARRAY pUrlArray, DWORD *pcbUrlArray,
325 PCRYPT_URL_INFO pUrlInfo, DWORD *pcbUrlInfo, LPVOID pvReserved)
327 PCCERT_CONTEXT cert = pvPara;
328 PCERT_EXTENSION ext;
329 BOOL ret = FALSE;
331 /* The only applicable flag is CRYPT_GET_URL_FROM_EXTENSION */
332 if (dwFlags && !(dwFlags & CRYPT_GET_URL_FROM_EXTENSION))
334 SetLastError(CRYPT_E_NOT_FOUND);
335 return FALSE;
337 if ((ext = CertFindExtension(szOID_CRL_DIST_POINTS,
338 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension)))
339 ret = CRYPT_GetUrlFromCRLDistPointsExt(&ext->Value, pUrlArray,
340 pcbUrlArray, pUrlInfo, pcbUrlInfo);
341 else
342 SetLastError(CRYPT_E_NOT_FOUND);
343 return ret;
346 /***********************************************************************
347 * CryptGetObjectUrl (CRYPTNET.@)
349 BOOL WINAPI CryptGetObjectUrl(LPCSTR pszUrlOid, LPVOID pvPara, DWORD dwFlags,
350 PCRYPT_URL_ARRAY pUrlArray, DWORD *pcbUrlArray, PCRYPT_URL_INFO pUrlInfo,
351 DWORD *pcbUrlInfo, LPVOID pvReserved)
353 UrlDllGetObjectUrlFunc func = NULL;
354 HCRYPTOIDFUNCADDR hFunc = NULL;
355 BOOL ret = FALSE;
357 TRACE("(%s, %p, %08x, %p, %p, %p, %p, %p)\n", debugstr_a(pszUrlOid),
358 pvPara, dwFlags, pUrlArray, pcbUrlArray, pUrlInfo, pcbUrlInfo, pvReserved);
360 if (IS_INTOID(pszUrlOid))
362 switch (LOWORD(pszUrlOid))
364 case LOWORD(URL_OID_CERTIFICATE_ISSUER):
365 func = CRYPT_GetUrlFromCertificateIssuer;
366 break;
367 case LOWORD(URL_OID_CERTIFICATE_CRL_DIST_POINT):
368 func = CRYPT_GetUrlFromCertificateCRLDistPoint;
369 break;
370 default:
371 FIXME("unimplemented for %s\n", url_oid_to_str(pszUrlOid));
372 SetLastError(ERROR_FILE_NOT_FOUND);
375 else
377 static HCRYPTOIDFUNCSET set = NULL;
379 if (!set)
380 set = CryptInitOIDFunctionSet(URL_OID_GET_OBJECT_URL_FUNC, 0);
381 CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING, pszUrlOid, 0,
382 (void **)&func, &hFunc);
384 if (func)
385 ret = func(pszUrlOid, pvPara, dwFlags, pUrlArray, pcbUrlArray,
386 pUrlInfo, pcbUrlInfo, pvReserved);
387 if (hFunc)
388 CryptFreeOIDFunctionAddress(hFunc, 0);
389 return ret;
392 /***********************************************************************
393 * CryptRetrieveObjectByUrlA (CRYPTNET.@)
395 BOOL WINAPI CryptRetrieveObjectByUrlA(LPCSTR pszURL, LPCSTR pszObjectOid,
396 DWORD dwRetrievalFlags, DWORD dwTimeout, LPVOID *ppvObject,
397 HCRYPTASYNC hAsyncRetrieve, PCRYPT_CREDENTIALS pCredentials, LPVOID pvVerify,
398 PCRYPT_RETRIEVE_AUX_INFO pAuxInfo)
400 BOOL ret = FALSE;
401 int len;
403 TRACE("(%s, %s, %08x, %d, %p, %p, %p, %p, %p)\n", debugstr_a(pszURL),
404 debugstr_a(pszObjectOid), dwRetrievalFlags, dwTimeout, ppvObject,
405 hAsyncRetrieve, pCredentials, pvVerify, pAuxInfo);
407 if (!pszURL)
409 SetLastError(ERROR_INVALID_PARAMETER);
410 return FALSE;
412 len = MultiByteToWideChar(CP_ACP, 0, pszURL, -1, NULL, 0);
413 if (len)
415 LPWSTR url = CryptMemAlloc(len * sizeof(WCHAR));
417 if (url)
419 MultiByteToWideChar(CP_ACP, 0, pszURL, -1, url, len);
420 ret = CryptRetrieveObjectByUrlW(url, pszObjectOid,
421 dwRetrievalFlags, dwTimeout, ppvObject, hAsyncRetrieve,
422 pCredentials, pvVerify, pAuxInfo);
423 CryptMemFree(url);
425 else
426 SetLastError(ERROR_OUTOFMEMORY);
428 return ret;
431 static void WINAPI CRYPT_FreeBlob(LPCSTR pszObjectOid,
432 PCRYPT_BLOB_ARRAY pObject, void *pvFreeContext)
434 DWORD i;
436 for (i = 0; i < pObject->cBlob; i++)
437 CryptMemFree(pObject->rgBlob[i].pbData);
438 CryptMemFree(pObject->rgBlob);
441 static BOOL CRYPT_GetObjectFromFile(HANDLE hFile, PCRYPT_BLOB_ARRAY pObject)
443 BOOL ret;
444 LARGE_INTEGER size;
446 if ((ret = GetFileSizeEx(hFile, &size)))
448 if (size.u.HighPart)
450 WARN("file too big\n");
451 SetLastError(ERROR_INVALID_DATA);
452 ret = FALSE;
454 else
456 CRYPT_DATA_BLOB blob;
458 blob.pbData = CryptMemAlloc(size.u.LowPart);
459 if (blob.pbData)
461 ret = ReadFile(hFile, blob.pbData, size.u.LowPart, &blob.cbData,
462 NULL);
463 if (ret)
465 pObject->rgBlob = CryptMemAlloc(sizeof(CRYPT_DATA_BLOB));
466 if (pObject->rgBlob)
468 pObject->cBlob = 1;
469 memcpy(pObject->rgBlob, &blob, sizeof(CRYPT_DATA_BLOB));
471 else
473 SetLastError(ERROR_OUTOFMEMORY);
474 ret = FALSE;
477 if (!ret)
478 CryptMemFree(blob.pbData);
480 else
482 SetLastError(ERROR_OUTOFMEMORY);
483 ret = FALSE;
487 return ret;
490 static BOOL CRYPT_GetObjectFromCache(LPCWSTR pszURL, PCRYPT_BLOB_ARRAY pObject,
491 PCRYPT_RETRIEVE_AUX_INFO pAuxInfo)
493 BOOL ret = FALSE;
494 INTERNET_CACHE_ENTRY_INFOW *pCacheInfo = NULL;
495 DWORD size = 0;
497 TRACE("(%s, %p, %p)\n", debugstr_w(pszURL), pObject, pAuxInfo);
499 RetrieveUrlCacheEntryFileW(pszURL, NULL, &size, 0);
500 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
501 return FALSE;
503 pCacheInfo = CryptMemAlloc(size);
504 if (!pCacheInfo)
506 SetLastError(ERROR_OUTOFMEMORY);
507 return FALSE;
510 if ((ret = RetrieveUrlCacheEntryFileW(pszURL, pCacheInfo, &size, 0)))
512 FILETIME ft;
514 GetSystemTimeAsFileTime(&ft);
515 if (CompareFileTime(&pCacheInfo->ExpireTime, &ft) >= 0)
517 HANDLE hFile = CreateFileW(pCacheInfo->lpszLocalFileName, GENERIC_READ,
518 FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
520 if (hFile != INVALID_HANDLE_VALUE)
522 if ((ret = CRYPT_GetObjectFromFile(hFile, pObject)))
524 if (pAuxInfo && pAuxInfo->cbSize >=
525 offsetof(CRYPT_RETRIEVE_AUX_INFO,
526 pLastSyncTime) + sizeof(PFILETIME) &&
527 pAuxInfo->pLastSyncTime)
528 memcpy(pAuxInfo->pLastSyncTime,
529 &pCacheInfo->LastSyncTime,
530 sizeof(FILETIME));
532 CloseHandle(hFile);
534 else
536 DeleteUrlCacheEntryW(pszURL);
537 ret = FALSE;
540 else
542 DeleteUrlCacheEntryW(pszURL);
543 ret = FALSE;
545 UnlockUrlCacheEntryFileW(pszURL, 0);
547 CryptMemFree(pCacheInfo);
548 TRACE("returning %d\n", ret);
549 return ret;
552 /* Parses the URL, and sets components' lpszHostName and lpszUrlPath members
553 * to NULL-terminated copies of those portions of the URL (to be freed with
554 * CryptMemFree.)
556 static BOOL CRYPT_CrackUrl(LPCWSTR pszURL, URL_COMPONENTSW *components)
558 BOOL ret;
560 TRACE("(%s, %p)\n", debugstr_w(pszURL), components);
562 memset(components, 0, sizeof(*components));
563 components->dwStructSize = sizeof(*components);
564 components->lpszHostName = CryptMemAlloc(INTERNET_MAX_HOST_NAME_LENGTH * sizeof(WCHAR));
565 components->dwHostNameLength = INTERNET_MAX_HOST_NAME_LENGTH;
566 if (!components->lpszHostName)
568 SetLastError(ERROR_OUTOFMEMORY);
569 return FALSE;
571 components->lpszUrlPath = CryptMemAlloc(INTERNET_MAX_PATH_LENGTH * sizeof(WCHAR));
572 components->dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
573 if (!components->lpszUrlPath)
575 CryptMemFree(components->lpszHostName);
576 SetLastError(ERROR_OUTOFMEMORY);
577 return FALSE;
580 ret = InternetCrackUrlW(pszURL, 0, ICU_DECODE, components);
581 if (ret)
583 switch (components->nScheme)
585 case INTERNET_SCHEME_FTP:
586 if (!components->nPort)
587 components->nPort = INTERNET_DEFAULT_FTP_PORT;
588 break;
589 case INTERNET_SCHEME_HTTP:
590 if (!components->nPort)
591 components->nPort = INTERNET_DEFAULT_HTTP_PORT;
592 break;
593 default:
594 ; /* do nothing */
597 TRACE("returning %d\n", ret);
598 return ret;
601 struct InetContext
603 HANDLE event;
604 DWORD timeout;
605 DWORD error;
608 static struct InetContext *CRYPT_MakeInetContext(DWORD dwTimeout)
610 struct InetContext *context = CryptMemAlloc(sizeof(struct InetContext));
612 if (context)
614 context->event = CreateEventW(NULL, FALSE, FALSE, NULL);
615 if (!context->event)
617 CryptMemFree(context);
618 context = NULL;
620 else
622 context->timeout = dwTimeout;
623 context->error = ERROR_SUCCESS;
626 return context;
629 static BOOL CRYPT_DownloadObject(DWORD dwRetrievalFlags, HINTERNET hHttp,
630 struct InetContext *context, PCRYPT_BLOB_ARRAY pObject,
631 PCRYPT_RETRIEVE_AUX_INFO pAuxInfo)
633 CRYPT_DATA_BLOB object = { 0, NULL };
634 DWORD bytesAvailable;
635 BOOL ret;
637 do {
638 if ((ret = InternetQueryDataAvailable(hHttp, &bytesAvailable, 0, 0)))
640 if (bytesAvailable)
642 if (object.pbData)
643 object.pbData = CryptMemRealloc(object.pbData,
644 object.cbData + bytesAvailable);
645 else
646 object.pbData = CryptMemAlloc(bytesAvailable);
647 if (object.pbData)
649 INTERNET_BUFFERSA buffer = { sizeof(buffer), 0 };
651 buffer.dwBufferLength = bytesAvailable;
652 buffer.lpvBuffer = object.pbData + object.cbData;
653 if (!(ret = InternetReadFileExA(hHttp, &buffer, IRF_NO_WAIT,
654 (DWORD_PTR)context)))
656 if (GetLastError() == ERROR_IO_PENDING)
658 if (WaitForSingleObject(context->event,
659 context->timeout) == WAIT_TIMEOUT)
660 SetLastError(ERROR_TIMEOUT);
661 else if (context->error)
662 SetLastError(context->error);
663 else
664 ret = TRUE;
667 if (ret)
668 object.cbData += buffer.dwBufferLength;
670 else
672 SetLastError(ERROR_OUTOFMEMORY);
673 ret = FALSE;
677 else if (GetLastError() == ERROR_IO_PENDING)
679 if (WaitForSingleObject(context->event, context->timeout) ==
680 WAIT_TIMEOUT)
681 SetLastError(ERROR_TIMEOUT);
682 else
683 ret = TRUE;
685 } while (ret && bytesAvailable);
686 if (ret)
688 pObject->rgBlob = CryptMemAlloc(sizeof(CRYPT_DATA_BLOB));
689 if (!pObject->rgBlob)
691 CryptMemFree(object.pbData);
692 SetLastError(ERROR_OUTOFMEMORY);
693 ret = FALSE;
695 else
697 pObject->rgBlob[0].cbData = object.cbData;
698 pObject->rgBlob[0].pbData = object.pbData;
699 pObject->cBlob = 1;
702 TRACE("returning %d\n", ret);
703 return ret;
706 /* Finds the object specified by pszURL in the cache. If it's not found,
707 * creates a new cache entry for the object and writes the object to it.
708 * Sets the expiration time of the cache entry to expires.
710 static void CRYPT_CacheURL(LPCWSTR pszURL, const CRYPT_BLOB_ARRAY *pObject,
711 DWORD dwRetrievalFlags, FILETIME expires)
713 WCHAR cacheFileName[MAX_PATH];
714 HANDLE hCacheFile;
715 DWORD size = 0, entryType;
716 FILETIME ft;
718 GetUrlCacheEntryInfoW(pszURL, NULL, &size);
719 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
721 INTERNET_CACHE_ENTRY_INFOW *info = CryptMemAlloc(size);
723 if (!info)
725 ERR("out of memory\n");
726 return;
729 if (GetUrlCacheEntryInfoW(pszURL, info, &size))
731 lstrcpyW(cacheFileName, info->lpszLocalFileName);
732 /* Check if the existing cache entry is up to date. If it isn't,
733 * remove the existing cache entry, and create a new one with the
734 * new value.
736 GetSystemTimeAsFileTime(&ft);
737 if (CompareFileTime(&info->ExpireTime, &ft) < 0)
739 DeleteUrlCacheEntryW(pszURL);
741 else
743 info->ExpireTime = expires;
744 SetUrlCacheEntryInfoW(pszURL, info, CACHE_ENTRY_EXPTIME_FC);
745 CryptMemFree(info);
746 return;
749 CryptMemFree(info);
752 if (!CreateUrlCacheEntryW(pszURL, pObject->rgBlob[0].cbData, NULL, cacheFileName, 0))
753 return;
755 hCacheFile = CreateFileW(cacheFileName, GENERIC_WRITE, 0,
756 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
757 if(hCacheFile == INVALID_HANDLE_VALUE)
758 return;
760 WriteFile(hCacheFile, pObject->rgBlob[0].pbData,
761 pObject->rgBlob[0].cbData, &size, NULL);
762 CloseHandle(hCacheFile);
764 if (!(dwRetrievalFlags & CRYPT_STICKY_CACHE_RETRIEVAL))
765 entryType = NORMAL_CACHE_ENTRY;
766 else
767 entryType = STICKY_CACHE_ENTRY;
768 memset(&ft, 0, sizeof(ft));
769 CommitUrlCacheEntryW(pszURL, cacheFileName, expires, ft, entryType,
770 NULL, 0, NULL, NULL);
773 static void CALLBACK CRYPT_InetStatusCallback(HINTERNET hInt,
774 DWORD_PTR dwContext, DWORD status, void *statusInfo, DWORD statusInfoLen)
776 struct InetContext *context = (struct InetContext *)dwContext;
777 LPINTERNET_ASYNC_RESULT result;
779 switch (status)
781 case INTERNET_STATUS_REQUEST_COMPLETE:
782 result = statusInfo;
783 context->error = result->dwError;
784 SetEvent(context->event);
788 static BOOL CRYPT_Connect(const URL_COMPONENTSW *components,
789 struct InetContext *context, PCRYPT_CREDENTIALS pCredentials,
790 HINTERNET *phInt, HINTERNET *phHost)
792 BOOL ret;
794 TRACE("(%s:%d, %p, %p, %p, %p)\n", debugstr_w(components->lpszHostName),
795 components->nPort, context, pCredentials, phInt, phInt);
797 *phHost = NULL;
798 *phInt = InternetOpenW(NULL, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL,
799 context ? INTERNET_FLAG_ASYNC : 0);
800 if (*phInt)
802 DWORD service;
804 if (context)
805 InternetSetStatusCallbackW(*phInt, CRYPT_InetStatusCallback);
806 switch (components->nScheme)
808 case INTERNET_SCHEME_FTP:
809 service = INTERNET_SERVICE_FTP;
810 break;
811 case INTERNET_SCHEME_HTTP:
812 service = INTERNET_SERVICE_HTTP;
813 break;
814 default:
815 service = 0;
817 /* FIXME: use pCredentials for username/password */
818 *phHost = InternetConnectW(*phInt, components->lpszHostName,
819 components->nPort, NULL, NULL, service, 0, (DWORD_PTR)context);
820 if (!*phHost)
822 InternetCloseHandle(*phInt);
823 *phInt = NULL;
824 ret = FALSE;
826 else
827 ret = TRUE;
829 else
830 ret = FALSE;
831 TRACE("returning %d\n", ret);
832 return ret;
835 static BOOL WINAPI FTP_RetrieveEncodedObjectW(LPCWSTR pszURL,
836 LPCSTR pszObjectOid, DWORD dwRetrievalFlags, DWORD dwTimeout,
837 PCRYPT_BLOB_ARRAY pObject, PFN_FREE_ENCODED_OBJECT_FUNC *ppfnFreeObject,
838 void **ppvFreeContext, HCRYPTASYNC hAsyncRetrieve,
839 PCRYPT_CREDENTIALS pCredentials, PCRYPT_RETRIEVE_AUX_INFO pAuxInfo)
841 FIXME("(%s, %s, %08x, %d, %p, %p, %p, %p, %p, %p)\n", debugstr_w(pszURL),
842 debugstr_a(pszObjectOid), dwRetrievalFlags, dwTimeout, pObject,
843 ppfnFreeObject, ppvFreeContext, hAsyncRetrieve, pCredentials, pAuxInfo);
845 pObject->cBlob = 0;
846 pObject->rgBlob = NULL;
847 *ppfnFreeObject = CRYPT_FreeBlob;
848 *ppvFreeContext = NULL;
849 return FALSE;
852 static BOOL WINAPI HTTP_RetrieveEncodedObjectW(LPCWSTR pszURL,
853 LPCSTR pszObjectOid, DWORD dwRetrievalFlags, DWORD dwTimeout,
854 PCRYPT_BLOB_ARRAY pObject, PFN_FREE_ENCODED_OBJECT_FUNC *ppfnFreeObject,
855 void **ppvFreeContext, HCRYPTASYNC hAsyncRetrieve,
856 PCRYPT_CREDENTIALS pCredentials, PCRYPT_RETRIEVE_AUX_INFO pAuxInfo)
858 BOOL ret = FALSE;
860 TRACE("(%s, %s, %08x, %d, %p, %p, %p, %p, %p, %p)\n", debugstr_w(pszURL),
861 debugstr_a(pszObjectOid), dwRetrievalFlags, dwTimeout, pObject,
862 ppfnFreeObject, ppvFreeContext, hAsyncRetrieve, pCredentials, pAuxInfo);
864 pObject->cBlob = 0;
865 pObject->rgBlob = NULL;
866 *ppfnFreeObject = CRYPT_FreeBlob;
867 *ppvFreeContext = NULL;
869 if (!(dwRetrievalFlags & CRYPT_WIRE_ONLY_RETRIEVAL))
870 ret = CRYPT_GetObjectFromCache(pszURL, pObject, pAuxInfo);
871 if (!ret && (!(dwRetrievalFlags & CRYPT_CACHE_ONLY_RETRIEVAL) ||
872 (dwRetrievalFlags & CRYPT_WIRE_ONLY_RETRIEVAL)))
874 URL_COMPONENTSW components;
876 if ((ret = CRYPT_CrackUrl(pszURL, &components)))
878 HINTERNET hInt, hHost;
879 struct InetContext *context = NULL;
881 if (dwTimeout)
882 context = CRYPT_MakeInetContext(dwTimeout);
883 ret = CRYPT_Connect(&components, context, pCredentials, &hInt,
884 &hHost);
885 if (ret)
887 static LPCWSTR types[] =
889 L"application/x-x509-ca-cert", L"application/x-x509-email-cert",
890 L"application/x-x509-server-cert", L"application/x-x509-user-cert",
891 L"application/x-pkcs7-certificates", L"application/pkix-crl",
892 L"application/x-pkcs7-crl", L"application/x-pkcs7-signature",
893 L"application/x-pkcs7-mime", NULL
895 HINTERNET hHttp = HttpOpenRequestW(hHost, NULL,
896 components.lpszUrlPath, NULL, NULL, types,
897 INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_NO_UI,
898 (DWORD_PTR)context);
900 if (hHttp)
902 if (dwTimeout)
904 InternetSetOptionW(hHttp,
905 INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeout,
906 sizeof(dwTimeout));
907 InternetSetOptionW(hHttp, INTERNET_OPTION_SEND_TIMEOUT,
908 &dwTimeout, sizeof(dwTimeout));
910 ret = HttpSendRequestExW(hHttp, NULL, NULL, 0,
911 (DWORD_PTR)context);
912 if (!ret && GetLastError() == ERROR_IO_PENDING)
914 if (WaitForSingleObject(context->event,
915 context->timeout) == WAIT_TIMEOUT)
916 SetLastError(ERROR_TIMEOUT);
917 else
918 ret = TRUE;
920 if (ret &&
921 !(ret = HttpEndRequestW(hHttp, NULL, 0, (DWORD_PTR)context)) &&
922 GetLastError() == ERROR_IO_PENDING)
924 if (WaitForSingleObject(context->event,
925 context->timeout) == WAIT_TIMEOUT)
926 SetLastError(ERROR_TIMEOUT);
927 else
928 ret = TRUE;
930 if (ret)
931 ret = CRYPT_DownloadObject(dwRetrievalFlags, hHttp,
932 context, pObject, pAuxInfo);
933 if (ret && !(dwRetrievalFlags & CRYPT_DONT_CACHE_RESULT))
935 SYSTEMTIME st;
936 FILETIME ft;
937 DWORD len = sizeof(st);
939 if (HttpQueryInfoW(hHttp, HTTP_QUERY_EXPIRES | HTTP_QUERY_FLAG_SYSTEMTIME,
940 &st, &len, NULL) && SystemTimeToFileTime(&st, &ft))
941 CRYPT_CacheURL(pszURL, pObject, dwRetrievalFlags, ft);
943 InternetCloseHandle(hHttp);
945 InternetCloseHandle(hHost);
946 InternetCloseHandle(hInt);
948 if (context)
950 CloseHandle(context->event);
951 CryptMemFree(context);
953 CryptMemFree(components.lpszUrlPath);
954 CryptMemFree(components.lpszHostName);
957 TRACE("returning %d\n", ret);
958 return ret;
961 static BOOL WINAPI File_RetrieveEncodedObjectW(LPCWSTR pszURL,
962 LPCSTR pszObjectOid, DWORD dwRetrievalFlags, DWORD dwTimeout,
963 PCRYPT_BLOB_ARRAY pObject, PFN_FREE_ENCODED_OBJECT_FUNC *ppfnFreeObject,
964 void **ppvFreeContext, HCRYPTASYNC hAsyncRetrieve,
965 PCRYPT_CREDENTIALS pCredentials, PCRYPT_RETRIEVE_AUX_INFO pAuxInfo)
967 URL_COMPONENTSW components = { sizeof(components), 0 };
968 BOOL ret;
970 TRACE("(%s, %s, %08x, %d, %p, %p, %p, %p, %p, %p)\n", debugstr_w(pszURL),
971 debugstr_a(pszObjectOid), dwRetrievalFlags, dwTimeout, pObject,
972 ppfnFreeObject, ppvFreeContext, hAsyncRetrieve, pCredentials, pAuxInfo);
974 pObject->cBlob = 0;
975 pObject->rgBlob = NULL;
976 *ppfnFreeObject = CRYPT_FreeBlob;
977 *ppvFreeContext = NULL;
979 components.lpszUrlPath = CryptMemAlloc(INTERNET_MAX_PATH_LENGTH * sizeof(WCHAR));
980 components.dwUrlPathLength = INTERNET_MAX_PATH_LENGTH;
981 if (!components.lpszUrlPath)
983 SetLastError(ERROR_OUTOFMEMORY);
984 return FALSE;
987 ret = InternetCrackUrlW(pszURL, 0, ICU_DECODE, &components);
988 if (ret)
990 LPWSTR path;
992 /* 3 == lstrlenW(L"c:") + 1 */
993 path = CryptMemAlloc((components.dwUrlPathLength + 3) * sizeof(WCHAR));
994 if (path)
996 HANDLE hFile;
998 /* Try to create the file directly - Wine handles / in pathnames */
999 lstrcpynW(path, components.lpszUrlPath,
1000 components.dwUrlPathLength + 1);
1001 hFile = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ,
1002 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1003 if (hFile == INVALID_HANDLE_VALUE)
1005 /* Try again on the current drive */
1006 GetCurrentDirectoryW(components.dwUrlPathLength, path);
1007 if (path[1] == ':')
1009 lstrcpynW(path + 2, components.lpszUrlPath,
1010 components.dwUrlPathLength + 1);
1011 hFile = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ,
1012 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1014 if (hFile == INVALID_HANDLE_VALUE)
1016 /* Try again on the Windows drive */
1017 GetWindowsDirectoryW(path, components.dwUrlPathLength);
1018 if (path[1] == ':')
1020 lstrcpynW(path + 2, components.lpszUrlPath,
1021 components.dwUrlPathLength + 1);
1022 hFile = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ,
1023 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1027 if (hFile != INVALID_HANDLE_VALUE)
1029 if ((ret = CRYPT_GetObjectFromFile(hFile, pObject)))
1031 if (pAuxInfo && pAuxInfo->cbSize >=
1032 offsetof(CRYPT_RETRIEVE_AUX_INFO,
1033 pLastSyncTime) + sizeof(PFILETIME) &&
1034 pAuxInfo->pLastSyncTime)
1035 GetFileTime(hFile, NULL, NULL,
1036 pAuxInfo->pLastSyncTime);
1038 CloseHandle(hFile);
1040 else
1041 ret = FALSE;
1042 CryptMemFree(path);
1044 else
1046 SetLastError(ERROR_OUTOFMEMORY);
1047 ret = FALSE;
1050 CryptMemFree(components.lpszUrlPath);
1051 return ret;
1054 typedef BOOL (WINAPI *SchemeDllRetrieveEncodedObjectW)(LPCWSTR pwszUrl,
1055 LPCSTR pszObjectOid, DWORD dwRetrievalFlags, DWORD dwTimeout,
1056 PCRYPT_BLOB_ARRAY pObject, PFN_FREE_ENCODED_OBJECT_FUNC *ppfnFreeObject,
1057 void **ppvFreeContext, HCRYPTASYNC hAsyncRetrieve,
1058 PCRYPT_CREDENTIALS pCredentials, PCRYPT_RETRIEVE_AUX_INFO pAuxInfo);
1060 static BOOL CRYPT_GetRetrieveFunction(LPCWSTR pszURL,
1061 SchemeDllRetrieveEncodedObjectW *pFunc, HCRYPTOIDFUNCADDR *phFunc)
1063 URL_COMPONENTSW components = { sizeof(components), 0 };
1064 BOOL ret;
1066 TRACE("(%s, %p, %p)\n", debugstr_w(pszURL), pFunc, phFunc);
1068 *pFunc = NULL;
1069 *phFunc = 0;
1070 components.dwSchemeLength = 1;
1071 ret = InternetCrackUrlW(pszURL, 0, 0, &components);
1072 if (ret)
1074 /* Microsoft always uses CryptInitOIDFunctionSet/
1075 * CryptGetOIDFunctionAddress, but there doesn't seem to be a pressing
1076 * reason to do so for builtin schemes.
1078 switch (components.nScheme)
1080 case INTERNET_SCHEME_FTP:
1081 *pFunc = FTP_RetrieveEncodedObjectW;
1082 break;
1083 case INTERNET_SCHEME_HTTP:
1084 *pFunc = HTTP_RetrieveEncodedObjectW;
1085 break;
1086 case INTERNET_SCHEME_FILE:
1087 *pFunc = File_RetrieveEncodedObjectW;
1088 break;
1089 default:
1091 int len = WideCharToMultiByte(CP_ACP, 0, components.lpszScheme,
1092 components.dwSchemeLength, NULL, 0, NULL, NULL);
1094 if (len)
1096 LPSTR scheme = CryptMemAlloc(len);
1098 if (scheme)
1100 static HCRYPTOIDFUNCSET set = NULL;
1102 if (!set)
1103 set = CryptInitOIDFunctionSet(
1104 SCHEME_OID_RETRIEVE_ENCODED_OBJECTW_FUNC, 0);
1105 WideCharToMultiByte(CP_ACP, 0, components.lpszScheme,
1106 components.dwSchemeLength, scheme, len, NULL, NULL);
1107 ret = CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING,
1108 scheme, 0, (void **)pFunc, phFunc);
1109 CryptMemFree(scheme);
1111 else
1113 SetLastError(ERROR_OUTOFMEMORY);
1114 ret = FALSE;
1117 else
1118 ret = FALSE;
1122 TRACE("returning %d\n", ret);
1123 return ret;
1126 static BOOL WINAPI CRYPT_CreateBlob(LPCSTR pszObjectOid,
1127 DWORD dwRetrievalFlags, const CRYPT_BLOB_ARRAY *pObject, void **ppvContext)
1129 DWORD size, i;
1130 CRYPT_BLOB_ARRAY *context;
1131 BOOL ret = FALSE;
1133 size = sizeof(CRYPT_BLOB_ARRAY) + pObject->cBlob * sizeof(CRYPT_DATA_BLOB);
1134 for (i = 0; i < pObject->cBlob; i++)
1135 size += pObject->rgBlob[i].cbData;
1136 context = CryptMemAlloc(size);
1137 if (context)
1139 LPBYTE nextData;
1141 context->cBlob = 0;
1142 context->rgBlob =
1143 (CRYPT_DATA_BLOB *)((LPBYTE)context + sizeof(CRYPT_BLOB_ARRAY));
1144 nextData =
1145 (LPBYTE)context->rgBlob + pObject->cBlob * sizeof(CRYPT_DATA_BLOB);
1146 for (i = 0; i < pObject->cBlob; i++)
1148 memcpy(nextData, pObject->rgBlob[i].pbData,
1149 pObject->rgBlob[i].cbData);
1150 context->rgBlob[i].pbData = nextData;
1151 context->rgBlob[i].cbData = pObject->rgBlob[i].cbData;
1152 nextData += pObject->rgBlob[i].cbData;
1153 context->cBlob++;
1155 *ppvContext = context;
1156 ret = TRUE;
1158 return ret;
1161 typedef BOOL (WINAPI *AddContextToStore)(HCERTSTORE hCertStore,
1162 const void *pContext, DWORD dwAddDisposition, const void **ppStoreContext);
1164 static BOOL decode_base64_blob( const CRYPT_DATA_BLOB *in, CRYPT_DATA_BLOB *out )
1166 BOOL ret;
1167 DWORD len = in->cbData;
1169 while (len && !in->pbData[len - 1]) len--;
1170 if (!CryptStringToBinaryA( (char *)in->pbData, len, CRYPT_STRING_BASE64_ANY,
1171 NULL, &out->cbData, NULL, NULL )) return FALSE;
1173 if (!(out->pbData = CryptMemAlloc( out->cbData ))) return FALSE;
1174 ret = CryptStringToBinaryA( (char *)in->pbData, len, CRYPT_STRING_BASE64_ANY,
1175 out->pbData, &out->cbData, NULL, NULL );
1176 if (!ret) CryptMemFree( out->pbData );
1177 return ret;
1180 static BOOL CRYPT_CreateContext(const CRYPT_BLOB_ARRAY *pObject,
1181 DWORD dwExpectedContentTypeFlags, AddContextToStore addFunc, void **ppvContext)
1183 BOOL ret = TRUE;
1184 CRYPT_DATA_BLOB blob;
1186 if (!pObject->cBlob)
1188 SetLastError(ERROR_INVALID_DATA);
1189 *ppvContext = NULL;
1190 ret = FALSE;
1192 else if (pObject->cBlob == 1)
1194 if (decode_base64_blob(&pObject->rgBlob[0], &blob))
1196 ret = CryptQueryObject(CERT_QUERY_OBJECT_BLOB, &blob,
1197 dwExpectedContentTypeFlags, CERT_QUERY_FORMAT_FLAG_BINARY, 0,
1198 NULL, NULL, NULL, NULL, NULL, (const void **)ppvContext);
1199 CryptMemFree(blob.pbData);
1201 else
1203 ret = CryptQueryObject(CERT_QUERY_OBJECT_BLOB, &pObject->rgBlob[0],
1204 dwExpectedContentTypeFlags, CERT_QUERY_FORMAT_FLAG_BINARY, 0,
1205 NULL, NULL, NULL, NULL, NULL, (const void **)ppvContext);
1207 if (!ret)
1209 SetLastError(CRYPT_E_NO_MATCH);
1210 ret = FALSE;
1213 else
1215 HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1216 CERT_STORE_CREATE_NEW_FLAG, NULL);
1218 if (store)
1220 DWORD i;
1221 const void *context;
1223 for (i = 0; i < pObject->cBlob; i++)
1225 if (decode_base64_blob(&pObject->rgBlob[i], &blob))
1227 ret = CryptQueryObject(CERT_QUERY_OBJECT_BLOB, &blob,
1228 dwExpectedContentTypeFlags, CERT_QUERY_FORMAT_FLAG_BINARY,
1229 0, NULL, NULL, NULL, NULL, NULL, &context);
1230 CryptMemFree(blob.pbData);
1232 else
1234 ret = CryptQueryObject(CERT_QUERY_OBJECT_BLOB,
1235 &pObject->rgBlob[i], dwExpectedContentTypeFlags,
1236 CERT_QUERY_FORMAT_FLAG_BINARY, 0, NULL, NULL, NULL, NULL,
1237 NULL, &context);
1239 if (ret)
1241 if (!addFunc(store, context, CERT_STORE_ADD_ALWAYS, NULL))
1242 ret = FALSE;
1244 else
1246 SetLastError(CRYPT_E_NO_MATCH);
1247 ret = FALSE;
1251 else
1252 ret = FALSE;
1253 *ppvContext = store;
1255 return ret;
1258 static BOOL WINAPI CRYPT_CreateCert(LPCSTR pszObjectOid,
1259 DWORD dwRetrievalFlags, const CRYPT_BLOB_ARRAY *pObject, void **ppvContext)
1261 return CRYPT_CreateContext(pObject, CERT_QUERY_CONTENT_FLAG_CERT,
1262 (AddContextToStore)CertAddCertificateContextToStore, ppvContext);
1265 static BOOL WINAPI CRYPT_CreateCRL(LPCSTR pszObjectOid,
1266 DWORD dwRetrievalFlags, const CRYPT_BLOB_ARRAY *pObject, void **ppvContext)
1268 return CRYPT_CreateContext(pObject, CERT_QUERY_CONTENT_FLAG_CRL,
1269 (AddContextToStore)CertAddCRLContextToStore, ppvContext);
1272 static BOOL WINAPI CRYPT_CreateCTL(LPCSTR pszObjectOid,
1273 DWORD dwRetrievalFlags, const CRYPT_BLOB_ARRAY *pObject, void **ppvContext)
1275 return CRYPT_CreateContext(pObject, CERT_QUERY_CONTENT_FLAG_CTL,
1276 (AddContextToStore)CertAddCTLContextToStore, ppvContext);
1279 static BOOL WINAPI CRYPT_CreatePKCS7(LPCSTR pszObjectOid,
1280 DWORD dwRetrievalFlags, const CRYPT_BLOB_ARRAY *pObject, void **ppvContext)
1282 BOOL ret;
1284 if (!pObject->cBlob)
1286 SetLastError(ERROR_INVALID_DATA);
1287 *ppvContext = NULL;
1288 ret = FALSE;
1290 else if (pObject->cBlob == 1)
1291 ret = CryptQueryObject(CERT_QUERY_OBJECT_BLOB, &pObject->rgBlob[0],
1292 CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED |
1293 CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED, CERT_QUERY_FORMAT_FLAG_BINARY,
1294 0, NULL, NULL, NULL, ppvContext, NULL, NULL);
1295 else
1297 FIXME("multiple messages unimplemented\n");
1298 ret = FALSE;
1300 return ret;
1303 static BOOL WINAPI CRYPT_CreateAny(LPCSTR pszObjectOid,
1304 DWORD dwRetrievalFlags, const CRYPT_BLOB_ARRAY *pObject, void **ppvContext)
1306 BOOL ret;
1308 if (!pObject->cBlob)
1310 SetLastError(ERROR_INVALID_DATA);
1311 *ppvContext = NULL;
1312 ret = FALSE;
1314 else
1316 HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
1317 CERT_STORE_CREATE_NEW_FLAG, NULL);
1319 if (store)
1321 HCERTSTORE memStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
1322 CERT_STORE_CREATE_NEW_FLAG, NULL);
1324 if (memStore)
1326 CertAddStoreToCollection(store, memStore,
1327 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
1328 CertCloseStore(memStore, 0);
1330 else
1332 CertCloseStore(store, 0);
1333 store = NULL;
1336 if (store)
1338 DWORD i;
1340 ret = TRUE;
1341 for (i = 0; i < pObject->cBlob; i++)
1343 DWORD contentType, expectedContentTypes =
1344 CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED |
1345 CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED |
1346 CERT_QUERY_CONTENT_FLAG_CERT |
1347 CERT_QUERY_CONTENT_FLAG_CRL |
1348 CERT_QUERY_CONTENT_FLAG_CTL;
1349 HCERTSTORE contextStore;
1350 const void *context;
1352 if (CryptQueryObject(CERT_QUERY_OBJECT_BLOB,
1353 &pObject->rgBlob[i], expectedContentTypes,
1354 CERT_QUERY_FORMAT_FLAG_BINARY, 0, NULL, &contentType, NULL,
1355 &contextStore, NULL, &context))
1357 switch (contentType)
1359 case CERT_QUERY_CONTENT_CERT:
1360 if (!CertAddCertificateContextToStore(store,
1361 context, CERT_STORE_ADD_ALWAYS, NULL))
1362 ret = FALSE;
1363 CertFreeCertificateContext(context);
1364 break;
1365 case CERT_QUERY_CONTENT_CRL:
1366 if (!CertAddCRLContextToStore(store,
1367 context, CERT_STORE_ADD_ALWAYS, NULL))
1368 ret = FALSE;
1369 CertFreeCRLContext(context);
1370 break;
1371 case CERT_QUERY_CONTENT_CTL:
1372 if (!CertAddCTLContextToStore(store,
1373 context, CERT_STORE_ADD_ALWAYS, NULL))
1374 ret = FALSE;
1375 CertFreeCTLContext(context);
1376 break;
1377 default:
1378 CertAddStoreToCollection(store, contextStore, 0, 0);
1380 CertCloseStore(contextStore, 0);
1382 else
1383 ret = FALSE;
1386 else
1387 ret = FALSE;
1388 *ppvContext = store;
1390 return ret;
1393 typedef BOOL (WINAPI *ContextDllCreateObjectContext)(LPCSTR pszObjectOid,
1394 DWORD dwRetrievalFlags, const CRYPT_BLOB_ARRAY *pObject, void **ppvContext);
1396 static BOOL CRYPT_GetCreateFunction(LPCSTR pszObjectOid,
1397 ContextDllCreateObjectContext *pFunc, HCRYPTOIDFUNCADDR *phFunc)
1399 BOOL ret = TRUE;
1401 TRACE("(%s, %p, %p)\n", debugstr_a(pszObjectOid), pFunc, phFunc);
1403 *pFunc = NULL;
1404 *phFunc = 0;
1405 if (IS_INTOID(pszObjectOid))
1407 switch (LOWORD(pszObjectOid))
1409 case 0:
1410 *pFunc = CRYPT_CreateBlob;
1411 break;
1412 case LOWORD(CONTEXT_OID_CERTIFICATE):
1413 *pFunc = CRYPT_CreateCert;
1414 break;
1415 case LOWORD(CONTEXT_OID_CRL):
1416 *pFunc = CRYPT_CreateCRL;
1417 break;
1418 case LOWORD(CONTEXT_OID_CTL):
1419 *pFunc = CRYPT_CreateCTL;
1420 break;
1421 case LOWORD(CONTEXT_OID_PKCS7):
1422 *pFunc = CRYPT_CreatePKCS7;
1423 break;
1424 case LOWORD(CONTEXT_OID_CAPI2_ANY):
1425 *pFunc = CRYPT_CreateAny;
1426 break;
1429 if (!*pFunc)
1431 static HCRYPTOIDFUNCSET set = NULL;
1433 if (!set)
1434 set = CryptInitOIDFunctionSet(
1435 CONTEXT_OID_CREATE_OBJECT_CONTEXT_FUNC, 0);
1436 ret = CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING, pszObjectOid,
1437 0, (void **)pFunc, phFunc);
1439 TRACE("returning %d\n", ret);
1440 return ret;
1443 static BOOL CRYPT_GetExpiration(const void *object, const char *pszObjectOid, FILETIME *expiration)
1445 if (!IS_INTOID(pszObjectOid))
1446 return FALSE;
1448 switch (LOWORD(pszObjectOid)) {
1449 case LOWORD(CONTEXT_OID_CERTIFICATE):
1450 *expiration = ((const CERT_CONTEXT*)object)->pCertInfo->NotAfter;
1451 return TRUE;
1452 case LOWORD(CONTEXT_OID_CRL):
1453 *expiration = ((const CRL_CONTEXT*)object)->pCrlInfo->NextUpdate;
1454 return TRUE;
1455 case LOWORD(CONTEXT_OID_CTL):
1456 *expiration = ((const CTL_CONTEXT*)object)->pCtlInfo->NextUpdate;
1457 return TRUE;
1460 return FALSE;
1463 /***********************************************************************
1464 * CryptRetrieveObjectByUrlW (CRYPTNET.@)
1466 BOOL WINAPI CryptRetrieveObjectByUrlW(LPCWSTR pszURL, LPCSTR pszObjectOid,
1467 DWORD dwRetrievalFlags, DWORD dwTimeout, LPVOID *ppvObject,
1468 HCRYPTASYNC hAsyncRetrieve, PCRYPT_CREDENTIALS pCredentials, LPVOID pvVerify,
1469 PCRYPT_RETRIEVE_AUX_INFO pAuxInfo)
1471 BOOL ret;
1472 SchemeDllRetrieveEncodedObjectW retrieve;
1473 ContextDllCreateObjectContext create;
1474 HCRYPTOIDFUNCADDR hRetrieve = 0, hCreate = 0;
1476 TRACE("(%s, %s, %08x, %d, %p, %p, %p, %p, %p)\n", debugstr_w(pszURL),
1477 debugstr_a(pszObjectOid), dwRetrievalFlags, dwTimeout, ppvObject,
1478 hAsyncRetrieve, pCredentials, pvVerify, pAuxInfo);
1480 if (!pszURL)
1482 SetLastError(ERROR_INVALID_PARAMETER);
1483 return FALSE;
1485 ret = CRYPT_GetRetrieveFunction(pszURL, &retrieve, &hRetrieve);
1486 if (ret)
1487 ret = CRYPT_GetCreateFunction(pszObjectOid, &create, &hCreate);
1488 if (ret)
1490 CRYPT_BLOB_ARRAY object = { 0, NULL };
1491 PFN_FREE_ENCODED_OBJECT_FUNC freeObject;
1492 void *freeContext;
1493 FILETIME expires;
1495 ret = retrieve(pszURL, pszObjectOid, dwRetrievalFlags, dwTimeout,
1496 &object, &freeObject, &freeContext, hAsyncRetrieve, pCredentials,
1497 pAuxInfo);
1498 if (ret)
1500 ret = create(pszObjectOid, dwRetrievalFlags, &object, ppvObject);
1501 if (ret && !(dwRetrievalFlags & CRYPT_DONT_CACHE_RESULT) &&
1502 CRYPT_GetExpiration(*ppvObject, pszObjectOid, &expires))
1504 CRYPT_CacheURL(pszURL, &object, dwRetrievalFlags, expires);
1506 freeObject(pszObjectOid, &object, freeContext);
1509 if (hCreate)
1510 CryptFreeOIDFunctionAddress(hCreate, 0);
1511 if (hRetrieve)
1512 CryptFreeOIDFunctionAddress(hRetrieve, 0);
1513 TRACE("returning %d\n", ret);
1514 return ret;
1517 static DWORD verify_cert_revocation_with_crl_online(PCCERT_CONTEXT cert,
1518 PCCRL_CONTEXT crl, DWORD index, FILETIME *pTime,
1519 PCERT_REVOCATION_STATUS pRevStatus)
1521 DWORD error;
1522 PCRL_ENTRY entry = NULL;
1524 CertFindCertificateInCRL(cert, crl, 0, NULL, &entry);
1525 if (entry)
1527 error = CRYPT_E_REVOKED;
1528 pRevStatus->dwIndex = index;
1530 else
1532 /* Since the CRL was retrieved for the cert being checked, then it's
1533 * guaranteed to be fresh, and the cert is not revoked.
1535 error = ERROR_SUCCESS;
1537 return error;
1540 static DWORD verify_cert_revocation_from_dist_points_ext(
1541 const CRYPT_DATA_BLOB *value, PCCERT_CONTEXT cert, DWORD index,
1542 FILETIME *pTime, DWORD dwFlags, const CERT_REVOCATION_PARA *pRevPara,
1543 PCERT_REVOCATION_STATUS pRevStatus)
1545 DWORD error = ERROR_SUCCESS, cbUrlArray;
1547 if (CRYPT_GetUrlFromCRLDistPointsExt(value, NULL, &cbUrlArray, NULL, NULL))
1549 CRYPT_URL_ARRAY *urlArray = CryptMemAlloc(cbUrlArray);
1551 if (urlArray)
1553 DWORD j, retrievalFlags = 0, startTime, endTime, timeout;
1554 BOOL ret;
1556 ret = CRYPT_GetUrlFromCRLDistPointsExt(value, urlArray,
1557 &cbUrlArray, NULL, NULL);
1558 if (dwFlags & CERT_VERIFY_CACHE_ONLY_BASED_REVOCATION)
1559 retrievalFlags |= CRYPT_CACHE_ONLY_RETRIEVAL;
1560 if (dwFlags & CERT_VERIFY_REV_ACCUMULATIVE_TIMEOUT_FLAG &&
1561 pRevPara && pRevPara->cbSize >= offsetof(CERT_REVOCATION_PARA,
1562 dwUrlRetrievalTimeout) + sizeof(DWORD))
1564 startTime = GetTickCount();
1565 endTime = startTime + pRevPara->dwUrlRetrievalTimeout;
1566 timeout = pRevPara->dwUrlRetrievalTimeout;
1568 else
1569 endTime = timeout = 0;
1570 if (!ret)
1571 error = GetLastError();
1572 /* continue looping if one was offline; break if revoked or timed out */
1573 for (j = 0; (!error || error == CRYPT_E_REVOCATION_OFFLINE) && j < urlArray->cUrl; j++)
1575 PCCRL_CONTEXT crl;
1577 ret = CryptRetrieveObjectByUrlW(urlArray->rgwszUrl[j],
1578 CONTEXT_OID_CRL, retrievalFlags, timeout, (void **)&crl,
1579 NULL, NULL, NULL, NULL);
1580 if (ret)
1582 error = verify_cert_revocation_with_crl_online(cert, crl,
1583 index, pTime, pRevStatus);
1584 if (!error && timeout)
1586 DWORD time = GetTickCount();
1588 if ((int)(endTime - time) <= 0)
1590 error = ERROR_TIMEOUT;
1591 pRevStatus->dwIndex = index;
1593 else
1594 timeout = endTime - time;
1596 CertFreeCRLContext(crl);
1598 else
1599 error = CRYPT_E_REVOCATION_OFFLINE;
1601 CryptMemFree(urlArray);
1603 else
1605 error = ERROR_OUTOFMEMORY;
1606 pRevStatus->dwIndex = index;
1609 else
1611 error = GetLastError();
1612 pRevStatus->dwIndex = index;
1614 return error;
1617 static DWORD verify_cert_revocation_from_aia_ext(
1618 const CRYPT_DATA_BLOB *value, PCCERT_CONTEXT cert, DWORD index,
1619 FILETIME *pTime, DWORD dwFlags, PCERT_REVOCATION_PARA pRevPara,
1620 PCERT_REVOCATION_STATUS pRevStatus)
1622 BOOL ret;
1623 DWORD error, size;
1624 CERT_AUTHORITY_INFO_ACCESS *aia;
1626 ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_AUTHORITY_INFO_ACCESS,
1627 value->pbData, value->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &aia, &size);
1628 if (ret)
1630 DWORD i;
1632 for (i = 0; i < aia->cAccDescr; i++)
1633 if (!strcmp(aia->rgAccDescr[i].pszAccessMethod,
1634 szOID_PKIX_OCSP))
1636 if (aia->rgAccDescr[i].AccessLocation.dwAltNameChoice ==
1637 CERT_ALT_NAME_URL)
1638 FIXME("OCSP URL = %s\n",
1639 debugstr_w(aia->rgAccDescr[i].AccessLocation.u.pwszURL));
1640 else
1641 FIXME("unsupported AccessLocation type %d\n",
1642 aia->rgAccDescr[i].AccessLocation.dwAltNameChoice);
1644 LocalFree(aia);
1645 /* FIXME: lie and pretend OCSP validated the cert */
1646 error = ERROR_SUCCESS;
1648 else
1649 error = GetLastError();
1650 return error;
1653 static DWORD verify_cert_revocation_with_crl_offline(PCCERT_CONTEXT cert,
1654 PCCRL_CONTEXT crl, DWORD index, FILETIME *pTime,
1655 PCERT_REVOCATION_STATUS pRevStatus)
1657 DWORD error;
1658 LONG valid;
1660 valid = CompareFileTime(pTime, &crl->pCrlInfo->ThisUpdate);
1661 if (valid <= 0)
1663 /* If this CRL is not older than the time being verified, there's no
1664 * way to know whether the certificate was revoked.
1666 TRACE("CRL not old enough\n");
1667 error = CRYPT_E_REVOCATION_OFFLINE;
1669 else
1671 PCRL_ENTRY entry = NULL;
1673 CertFindCertificateInCRL(cert, crl, 0, NULL, &entry);
1674 if (entry)
1676 error = CRYPT_E_REVOKED;
1677 pRevStatus->dwIndex = index;
1679 else
1681 /* Since the CRL was not retrieved for the cert being checked,
1682 * there's no guarantee it's fresh, so the cert *might* be okay,
1683 * but it's safer not to guess.
1685 TRACE("certificate not found\n");
1686 error = CRYPT_E_REVOCATION_OFFLINE;
1689 return error;
1692 static DWORD verify_cert_revocation(PCCERT_CONTEXT cert, DWORD index,
1693 FILETIME *pTime, DWORD dwFlags, PCERT_REVOCATION_PARA pRevPara,
1694 PCERT_REVOCATION_STATUS pRevStatus)
1696 DWORD error = ERROR_SUCCESS;
1697 PCERT_EXTENSION ext;
1699 if ((ext = CertFindExtension(szOID_CRL_DIST_POINTS,
1700 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension)))
1701 error = verify_cert_revocation_from_dist_points_ext(&ext->Value, cert,
1702 index, pTime, dwFlags, pRevPara, pRevStatus);
1703 else if ((ext = CertFindExtension(szOID_AUTHORITY_INFO_ACCESS,
1704 cert->pCertInfo->cExtension, cert->pCertInfo->rgExtension)))
1705 error = verify_cert_revocation_from_aia_ext(&ext->Value, cert,
1706 index, pTime, dwFlags, pRevPara, pRevStatus);
1707 else
1709 if (pRevPara && pRevPara->hCrlStore && pRevPara->pIssuerCert)
1711 PCCRL_CONTEXT crl = NULL;
1712 BOOL canSignCRLs;
1714 /* If the caller told us about the issuer, make sure the issuer
1715 * can sign CRLs before looking for one.
1717 if ((ext = CertFindExtension(szOID_KEY_USAGE,
1718 pRevPara->pIssuerCert->pCertInfo->cExtension,
1719 pRevPara->pIssuerCert->pCertInfo->rgExtension)))
1721 CRYPT_BIT_BLOB usage;
1722 DWORD size = sizeof(usage);
1724 if (!CryptDecodeObjectEx(cert->dwCertEncodingType, X509_BITS,
1725 ext->Value.pbData, ext->Value.cbData,
1726 CRYPT_DECODE_NOCOPY_FLAG, NULL, &usage, &size))
1727 canSignCRLs = FALSE;
1728 else if (usage.cbData > 2)
1730 /* The key usage extension only defines 9 bits => no more
1731 * than 2 bytes are needed to encode all known usages.
1733 canSignCRLs = FALSE;
1735 else
1737 BYTE usageBits = usage.pbData[usage.cbData - 1];
1739 canSignCRLs = usageBits & CERT_CRL_SIGN_KEY_USAGE;
1742 else
1743 canSignCRLs = TRUE;
1744 if (canSignCRLs)
1746 /* If the caller was helpful enough to tell us where to find a
1747 * CRL for the cert, look for one and check it.
1749 crl = CertFindCRLInStore(pRevPara->hCrlStore,
1750 cert->dwCertEncodingType,
1751 CRL_FIND_ISSUED_BY_SIGNATURE_FLAG |
1752 CRL_FIND_ISSUED_BY_AKI_FLAG,
1753 CRL_FIND_ISSUED_BY, pRevPara->pIssuerCert, NULL);
1755 if (crl)
1757 error = verify_cert_revocation_with_crl_offline(cert, crl,
1758 index, pTime, pRevStatus);
1759 CertFreeCRLContext(crl);
1761 else
1763 TRACE("no CRL found\n");
1764 error = CRYPT_E_NO_REVOCATION_CHECK;
1765 pRevStatus->dwIndex = index;
1768 else
1770 if (!pRevPara)
1771 WARN("no CERT_REVOCATION_PARA\n");
1772 else if (!pRevPara->hCrlStore)
1773 WARN("no dist points/aia extension and no CRL store\n");
1774 else if (!pRevPara->pIssuerCert)
1775 WARN("no dist points/aia extension and no issuer\n");
1776 error = CRYPT_E_NO_REVOCATION_CHECK;
1777 pRevStatus->dwIndex = index;
1780 return error;
1783 typedef struct _CERT_REVOCATION_PARA_NO_EXTRA_FIELDS {
1784 DWORD cbSize;
1785 PCCERT_CONTEXT pIssuerCert;
1786 DWORD cCertStore;
1787 HCERTSTORE *rgCertStore;
1788 HCERTSTORE hCrlStore;
1789 LPFILETIME pftTimeToUse;
1790 } CERT_REVOCATION_PARA_NO_EXTRA_FIELDS;
1792 typedef struct _OLD_CERT_REVOCATION_STATUS {
1793 DWORD cbSize;
1794 DWORD dwIndex;
1795 DWORD dwError;
1796 DWORD dwReason;
1797 } OLD_CERT_REVOCATION_STATUS;
1799 /***********************************************************************
1800 * CertDllVerifyRevocation (CRYPTNET.@)
1802 BOOL WINAPI CertDllVerifyRevocation(DWORD dwEncodingType, DWORD dwRevType,
1803 DWORD cContext, PVOID rgpvContext[], DWORD dwFlags,
1804 PCERT_REVOCATION_PARA pRevPara, PCERT_REVOCATION_STATUS pRevStatus)
1806 DWORD error = 0, i;
1807 FILETIME now;
1808 LPFILETIME pTime = NULL;
1810 TRACE("(%08x, %d, %d, %p, %08x, %p, %p)\n", dwEncodingType, dwRevType,
1811 cContext, rgpvContext, dwFlags, pRevPara, pRevStatus);
1813 if (pRevStatus->cbSize != sizeof(OLD_CERT_REVOCATION_STATUS) &&
1814 pRevStatus->cbSize != sizeof(CERT_REVOCATION_STATUS))
1816 SetLastError(E_INVALIDARG);
1817 return FALSE;
1819 if (!cContext)
1821 SetLastError(E_INVALIDARG);
1822 return FALSE;
1824 if (pRevPara && pRevPara->cbSize >=
1825 sizeof(CERT_REVOCATION_PARA_NO_EXTRA_FIELDS))
1826 pTime = pRevPara->pftTimeToUse;
1827 if (!pTime)
1829 GetSystemTimeAsFileTime(&now);
1830 pTime = &now;
1832 memset(&pRevStatus->dwIndex, 0, pRevStatus->cbSize - sizeof(DWORD));
1833 if (dwRevType != CERT_CONTEXT_REVOCATION_TYPE)
1834 error = CRYPT_E_NO_REVOCATION_CHECK;
1835 else
1837 for (i = 0; !error && i < cContext; i++)
1838 error = verify_cert_revocation(rgpvContext[i], i, pTime, dwFlags,
1839 pRevPara, pRevStatus);
1841 if (error)
1843 SetLastError(error);
1844 pRevStatus->dwError = error;
1846 TRACE("returning %d (%08x)\n", !error, error);
1847 return !error;