msxml3: Fix parameter validation for endElement().
[wine] / dlls / wintrust / crypt.c
1 /*
2  * WinTrust Cryptography functions
3  *
4  * Copyright 2006 James Hawkins
5  * Copyright 2000-2002 Stuart Caie
6  * Copyright 2002 Patrik Stridvall
7  * Copyright 2003 Greg Turner
8  * Copyright 2008 Juan Lang
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include "windef.h"
28 #include "winbase.h"
29 #include "wintrust.h"
30 #include "mscat.h"
31 #include "mssip.h"
32 #include "imagehlp.h"
33 #include "winternl.h"
34
35 #include "wine/debug.h"
36 #include "wine/unicode.h"
37
38 WINE_DEFAULT_DEBUG_CHANNEL(wintrust);
39
40 #define CATADMIN_MAGIC 0x43415441 /* 'CATA' */
41 #define CRYPTCAT_MAGIC 0x43415443 /* 'CATC' */
42 #define CATINFO_MAGIC  0x43415449 /* 'CATI' */
43
44 struct cryptcat
45 {
46     DWORD     magic;
47     HCRYPTMSG msg;
48     DWORD     encoding;
49     CTL_INFO *inner;
50     DWORD     inner_len;
51     GUID      subject;
52     DWORD     attr_count;
53     CRYPTCATATTRIBUTE *attr;
54 };
55
56 struct catadmin
57 {
58     DWORD magic;
59     WCHAR path[MAX_PATH];
60     HANDLE find;
61 };
62
63 struct catinfo
64 {
65     DWORD magic;
66     WCHAR file[MAX_PATH];
67 };
68
69 static HCATINFO create_catinfo(const WCHAR *filename)
70 {
71     struct catinfo *ci;
72
73     if (!(ci = HeapAlloc(GetProcessHeap(), 0, sizeof(*ci))))
74     {
75         SetLastError(ERROR_OUTOFMEMORY);
76         return INVALID_HANDLE_VALUE;
77     }
78     strcpyW(ci->file, filename);
79     ci->magic = CATINFO_MAGIC;
80     return ci;
81 }
82
83 /***********************************************************************
84  *      CryptCATAdminAcquireContext (WINTRUST.@)
85  *
86  * Get a catalog administrator context handle.
87  *
88  * PARAMS
89  *   catAdmin  [O] Pointer to the context handle.
90  *   sys       [I] Pointer to a GUID for the needed subsystem.
91  *   dwFlags   [I] Reserved.
92  *
93  * RETURNS
94  *   Success: TRUE. catAdmin contains the context handle.
95  *   Failure: FALSE.
96  *
97  */
98 BOOL WINAPI CryptCATAdminAcquireContext(HCATADMIN *catAdmin,
99                                         const GUID *sys, DWORD dwFlags)
100 {
101     static const WCHAR catroot[] =
102         {'\\','c','a','t','r','o','o','t',0};
103     static const WCHAR fmt[] =
104         {'%','s','\\','{','%','0','8','x','-','%','0','4','x','-','%','0',
105          '4','x','-','%','0','2','x','%','0','2','x','-','%','0','2','x',
106          '%','0','2','x','%','0','2','x','%','0','2','x','%','0','2','x',
107          '%','0','2','x','}',0};
108     static const GUID defsys =
109         {0x127d0a1d,0x4ef2,0x11d1,{0x86,0x08,0x00,0xc0,0x4f,0xc2,0x95,0xee}};
110
111     WCHAR catroot_dir[MAX_PATH];
112     struct catadmin *ca;
113
114     TRACE("%p %s %x\n", catAdmin, debugstr_guid(sys), dwFlags);
115
116     if (!catAdmin)
117     {
118         SetLastError(ERROR_INVALID_PARAMETER);
119         return FALSE;
120     }
121     if (!(ca = HeapAlloc(GetProcessHeap(), 0, sizeof(*ca))))
122     {
123         SetLastError(ERROR_OUTOFMEMORY);
124         return FALSE;
125     }
126
127     GetSystemDirectoryW(catroot_dir, MAX_PATH);
128     strcatW(catroot_dir, catroot);
129
130     /* create the directory if it doesn't exist */
131     CreateDirectoryW(catroot_dir, NULL);
132
133     if (!sys) sys = &defsys;
134     sprintfW(ca->path, fmt, catroot_dir, sys->Data1, sys->Data2,
135              sys->Data3, sys->Data4[0], sys->Data4[1], sys->Data4[2],
136              sys->Data4[3], sys->Data4[4], sys->Data4[5], sys->Data4[6],
137              sys->Data4[7]);
138
139     /* create the directory if it doesn't exist */
140     CreateDirectoryW(ca->path, NULL);
141
142     ca->magic = CATADMIN_MAGIC;
143     ca->find = INVALID_HANDLE_VALUE;
144
145     *catAdmin = ca;
146     return TRUE;
147 }
148
149 /***********************************************************************
150  *             CryptCATAdminAddCatalog (WINTRUST.@)
151  */
152 HCATINFO WINAPI CryptCATAdminAddCatalog(HCATADMIN catAdmin, PWSTR catalogFile,
153                                         PWSTR selectBaseName, DWORD flags)
154 {
155     static const WCHAR slashW[] = {'\\',0};
156     struct catadmin *ca = catAdmin;
157     struct catinfo *ci;
158     WCHAR *target;
159     DWORD len;
160
161     TRACE("%p %s %s %d\n", catAdmin, debugstr_w(catalogFile),
162           debugstr_w(selectBaseName), flags);
163
164     if (!selectBaseName)
165     {
166         FIXME("NULL basename not handled\n");
167         SetLastError(ERROR_INVALID_PARAMETER);
168         return NULL;
169     }
170     if (!ca || ca->magic != CATADMIN_MAGIC || !catalogFile || flags)
171     {
172         SetLastError(ERROR_INVALID_PARAMETER);
173         return NULL;
174     }
175
176     len = strlenW(ca->path) + strlenW(selectBaseName) + 2;
177     if (!(target = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR))))
178     {
179         SetLastError(ERROR_OUTOFMEMORY);
180         return NULL;
181     }
182     strcpyW(target, ca->path);
183     strcatW(target, slashW);
184     strcatW(target, selectBaseName);
185
186     if (!CopyFileW(catalogFile, target, FALSE))
187     {
188         HeapFree(GetProcessHeap(), 0, target);
189         return NULL;
190     }
191     SetFileAttributesW(target, FILE_ATTRIBUTE_SYSTEM);
192
193     if (!(ci = HeapAlloc(GetProcessHeap(), 0, sizeof(*ci))))
194     {
195         HeapFree(GetProcessHeap(), 0, target);
196         SetLastError(ERROR_OUTOFMEMORY);
197         return NULL;
198     }
199     ci->magic = CATINFO_MAGIC;
200     strcpyW(ci->file, target);
201
202     HeapFree(GetProcessHeap(), 0, target);
203     return ci;
204 }
205
206 /***********************************************************************
207  *             CryptCATAdminCalcHashFromFileHandle (WINTRUST.@)
208  */
209 BOOL WINAPI CryptCATAdminCalcHashFromFileHandle(HANDLE hFile, DWORD* pcbHash,
210                                                 BYTE* pbHash, DWORD dwFlags )
211 {
212     BOOL ret = FALSE;
213
214     TRACE("%p %p %p %x\n", hFile, pcbHash, pbHash, dwFlags);
215
216     if (!hFile || !pcbHash || dwFlags)
217     {
218         SetLastError(ERROR_INVALID_PARAMETER);
219         return FALSE;
220     }
221     if (*pcbHash < 20)
222     {
223         *pcbHash = 20;
224         SetLastError(ERROR_INSUFFICIENT_BUFFER);
225         return TRUE;
226     }
227
228     *pcbHash = 20;
229     if (pbHash)
230     {
231         HCRYPTPROV prov;
232         HCRYPTHASH hash;
233         DWORD bytes_read;
234         BYTE *buffer;
235
236         if (!(buffer = HeapAlloc(GetProcessHeap(), 0, 4096)))
237         {
238             SetLastError(ERROR_OUTOFMEMORY);
239             return FALSE;
240         }
241         ret = CryptAcquireContextW(&prov, NULL, MS_DEF_PROV_W, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
242         if (!ret)
243         {
244             HeapFree(GetProcessHeap(), 0, buffer);
245             return FALSE;
246         }
247         ret = CryptCreateHash(prov, CALG_SHA1, 0, 0, &hash);
248         if (!ret)
249         {
250             HeapFree(GetProcessHeap(), 0, buffer);
251             CryptReleaseContext(prov, 0);
252             return FALSE;
253         }
254         while ((ret = ReadFile(hFile, buffer, 4096, &bytes_read, NULL)) && bytes_read)
255         {
256             CryptHashData(hash, buffer, bytes_read, 0);
257         }
258         if (ret) ret = CryptGetHashParam(hash, HP_HASHVAL, pbHash, pcbHash, 0);
259
260         HeapFree(GetProcessHeap(), 0, buffer);
261         CryptDestroyHash(hash);
262         CryptReleaseContext(prov, 0);
263     }
264     return ret;
265 }
266
267 /***********************************************************************
268  *             CryptCATAdminEnumCatalogFromHash (WINTRUST.@)
269  */
270 HCATINFO WINAPI CryptCATAdminEnumCatalogFromHash(HCATADMIN hCatAdmin, BYTE* pbHash,
271                                                  DWORD cbHash, DWORD dwFlags,
272                                                  HCATINFO* phPrevCatInfo )
273 {
274     static const WCHAR slashW[] = {'\\',0};
275     static const WCHAR globW[]  = {'\\','*','.','c','a','t',0};
276
277     struct catadmin *ca = hCatAdmin;
278     WIN32_FIND_DATAW data;
279     HCATINFO prev = NULL;
280     HCRYPTPROV prov;
281     DWORD size;
282     BOOL ret;
283
284     TRACE("%p %p %d %x %p\n", hCatAdmin, pbHash, cbHash, dwFlags, phPrevCatInfo);
285
286     if (!ca || ca->magic != CATADMIN_MAGIC || !pbHash || cbHash != 20 || dwFlags)
287     {
288         SetLastError(ERROR_INVALID_PARAMETER);
289         return NULL;
290     }
291     if (phPrevCatInfo) prev = *phPrevCatInfo;
292
293     ret = CryptAcquireContextW(&prov, NULL, MS_DEF_PROV_W, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
294     if (!ret) return NULL;
295
296     if (!prev)
297     {
298         WCHAR *path;
299
300         size = strlenW(ca->path) * sizeof(WCHAR) + sizeof(globW);
301         if (!(path = HeapAlloc(GetProcessHeap(), 0, size)))
302         {
303             CryptReleaseContext(prov, 0);
304             SetLastError(ERROR_OUTOFMEMORY);
305             return NULL;
306         }
307         strcpyW(path, ca->path);
308         strcatW(path, globW);
309
310         FindClose(ca->find);
311         ca->find = FindFirstFileW(path, &data);
312
313         HeapFree(GetProcessHeap(), 0, path);
314         if (ca->find == INVALID_HANDLE_VALUE)
315         {
316             CryptReleaseContext(prov, 0);
317             return NULL;
318         }
319     }
320     else if (!FindNextFileW(ca->find, &data))
321     {
322         CryptCATAdminReleaseCatalogContext(hCatAdmin, prev, 0);
323         CryptReleaseContext(prov, 0);
324         return NULL;
325     }
326
327     while (1)
328     {
329         WCHAR *filename;
330         CRYPTCATMEMBER *member = NULL;
331         struct catinfo *ci;
332         HANDLE hcat;
333
334         size = (strlenW(ca->path) + strlenW(data.cFileName) + 2) * sizeof(WCHAR);
335         if (!(filename = HeapAlloc(GetProcessHeap(), 0, size)))
336         {
337             SetLastError(ERROR_OUTOFMEMORY);
338             return NULL;
339         }
340         strcpyW(filename, ca->path);
341         strcatW(filename, slashW);
342         strcatW(filename, data.cFileName);
343
344         hcat = CryptCATOpen(filename, CRYPTCAT_OPEN_EXISTING, prov, 0, 0);
345         if (hcat == INVALID_HANDLE_VALUE)
346         {
347             WARN("couldn't open %s (%u)\n", debugstr_w(filename), GetLastError());
348             continue;
349         }
350         while ((member = CryptCATEnumerateMember(hcat, member)))
351         {
352             if (member->pIndirectData->Digest.cbData != cbHash)
353             {
354                 WARN("amount of hash bytes differs: %u/%u\n", member->pIndirectData->Digest.cbData, cbHash);
355                 continue;
356             }
357             if (!memcmp(member->pIndirectData->Digest.pbData, pbHash, cbHash))
358             {
359                 TRACE("file %s matches\n", debugstr_w(data.cFileName));
360
361                 CryptCATClose(hcat);
362                 CryptReleaseContext(prov, 0);
363                 if (!phPrevCatInfo)
364                 {
365                     FindClose(ca->find);
366                     ca->find = INVALID_HANDLE_VALUE;
367                 }
368                 ci = create_catinfo(filename);
369                 HeapFree(GetProcessHeap(), 0, filename);
370                 return ci;
371             }
372         }
373         CryptCATClose(hcat);
374         HeapFree(GetProcessHeap(), 0, filename);
375
376         if (!FindNextFileW(ca->find, &data))
377         {
378             FindClose(ca->find);
379             ca->find = INVALID_HANDLE_VALUE;
380             CryptReleaseContext(prov, 0);
381             return NULL;
382         }
383     }
384     return NULL;
385 }
386
387 /***********************************************************************
388  *      CryptCATAdminReleaseCatalogContext (WINTRUST.@)
389  *
390  * Release a catalog context handle.
391  *
392  * PARAMS
393  *   hCatAdmin [I] Context handle.
394  *   hCatInfo  [I] Catalog handle.
395  *   dwFlags   [I] Reserved.
396  *
397  * RETURNS
398  *   Success: TRUE.
399  *   Failure: FALSE.
400  *
401  */
402 BOOL WINAPI CryptCATAdminReleaseCatalogContext(HCATADMIN hCatAdmin,
403                                                HCATINFO hCatInfo,
404                                                DWORD dwFlags)
405 {
406     struct catinfo *ci = hCatInfo;
407     struct catadmin *ca = hCatAdmin;
408
409     TRACE("%p %p %x\n", hCatAdmin, hCatInfo, dwFlags);
410
411     if (!ca || ca->magic != CATADMIN_MAGIC || !ci || ci->magic != CATINFO_MAGIC)
412     {
413         SetLastError(ERROR_INVALID_PARAMETER);
414         return FALSE;
415     }
416     ci->magic = 0;
417     return HeapFree(GetProcessHeap(), 0, ci);
418 }
419
420 /***********************************************************************
421  *      CryptCATAdminReleaseContext (WINTRUST.@)
422  *
423  * Release a catalog administrator context handle.
424  *
425  * PARAMS
426  *   catAdmin  [I] Context handle.
427  *   dwFlags   [I] Reserved.
428  *
429  * RETURNS
430  *   Success: TRUE.
431  *   Failure: FALSE.
432  *
433  */
434 BOOL WINAPI CryptCATAdminReleaseContext(HCATADMIN hCatAdmin, DWORD dwFlags )
435 {
436     struct catadmin *ca = hCatAdmin;
437
438     TRACE("%p %x\n", hCatAdmin, dwFlags);
439
440     if (!ca || ca->magic != CATADMIN_MAGIC)
441     {
442         SetLastError(ERROR_INVALID_PARAMETER);
443         return FALSE;
444     }
445     if (ca->find != INVALID_HANDLE_VALUE) FindClose(ca->find);
446     ca->magic = 0;
447     return HeapFree(GetProcessHeap(), 0, ca);
448 }
449
450 /***********************************************************************
451  *      CryptCATAdminRemoveCatalog (WINTRUST.@)
452  *
453  * Remove a catalog file.
454  *
455  * PARAMS
456  *   catAdmin         [I] Context handle.
457  *   pwszCatalogFile  [I] Catalog file.
458  *   dwFlags          [I] Reserved.
459  *
460  * RETURNS
461  *   Success: TRUE.
462  *   Failure: FALSE.
463  *
464  */
465 BOOL WINAPI CryptCATAdminRemoveCatalog(HCATADMIN hCatAdmin, LPCWSTR pwszCatalogFile, DWORD dwFlags)
466 {
467     struct catadmin *ca = hCatAdmin;
468
469     TRACE("%p %s %x\n", hCatAdmin, debugstr_w(pwszCatalogFile), dwFlags);
470
471     if (!ca || ca->magic != CATADMIN_MAGIC)
472     {
473         SetLastError(ERROR_INVALID_PARAMETER);
474         return FALSE;
475     }
476
477     /* Only delete when there is a filename and no path */
478     if (pwszCatalogFile && pwszCatalogFile[0] != 0 &&
479         !strchrW(pwszCatalogFile, '\\') && !strchrW(pwszCatalogFile, '/') &&
480         !strchrW(pwszCatalogFile, ':'))
481     {
482         static const WCHAR slashW[] = {'\\',0};
483         WCHAR *target;
484         DWORD len;
485
486         len = strlenW(ca->path) + strlenW(pwszCatalogFile) + 2;
487         if (!(target = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR))))
488         {
489             SetLastError(ERROR_OUTOFMEMORY);
490             return FALSE;
491         }
492         strcpyW(target, ca->path);
493         strcatW(target, slashW);
494         strcatW(target, pwszCatalogFile);
495
496         DeleteFileW(target);
497
498         HeapFree(GetProcessHeap(), 0, target);
499     }
500
501     return TRUE;
502 }
503
504 /***********************************************************************
505  *      CryptCATAdminResolveCatalogPath  (WINTRUST.@)
506  */
507 BOOL WINAPI CryptCATAdminResolveCatalogPath(HCATADMIN hcatadmin, WCHAR *catalog_file,
508                                             CATALOG_INFO *info, DWORD flags)
509 {
510     static const WCHAR slashW[] = {'\\',0};
511     struct catadmin *ca = hcatadmin;
512
513     TRACE("%p %s %p %x\n", hcatadmin, debugstr_w(catalog_file), info, flags);
514
515     if (!ca || ca->magic != CATADMIN_MAGIC || !info || info->cbStruct != sizeof(*info) || flags)
516     {
517         SetLastError(ERROR_INVALID_PARAMETER);
518         return FALSE;
519     }
520     strcpyW(info->wszCatalogFile, ca->path);
521     strcatW(info->wszCatalogFile, slashW);
522     strcatW(info->wszCatalogFile, catalog_file);
523
524     return TRUE;
525 }
526
527 /***********************************************************************
528  *      CryptCATClose  (WINTRUST.@)
529  */
530 BOOL WINAPI CryptCATClose(HANDLE hCatalog)
531 {
532     struct cryptcat *cc = hCatalog;
533
534     TRACE("(%p)\n", hCatalog);
535
536     if (!hCatalog || hCatalog == INVALID_HANDLE_VALUE || cc->magic != CRYPTCAT_MAGIC)
537     {
538         SetLastError(ERROR_INVALID_PARAMETER);
539         return FALSE;
540     }
541     HeapFree(GetProcessHeap(), 0, cc->attr);
542     HeapFree(GetProcessHeap(), 0, cc->inner);
543     CryptMsgClose(cc->msg);
544
545     cc->magic = 0;
546     HeapFree(GetProcessHeap(), 0, cc);
547     return TRUE;
548 }
549
550 /***********************************************************************
551  *      CryptCATGetAttrInfo  (WINTRUST.@)
552  */
553 CRYPTCATATTRIBUTE * WINAPI CryptCATGetAttrInfo(HANDLE hCatalog, CRYPTCATMEMBER *member, LPWSTR tag)
554 {
555     struct cryptcat *cc = hCatalog;
556
557     FIXME("%p, %p, %s\n", hCatalog, member, debugstr_w(tag));
558
559     if (!hCatalog || hCatalog == INVALID_HANDLE_VALUE || cc->magic != CRYPTCAT_MAGIC)
560     {
561         SetLastError(ERROR_INVALID_PARAMETER);
562         return NULL;
563     }
564     SetLastError(CRYPT_E_NOT_FOUND);
565     return NULL;
566 }
567
568 /***********************************************************************
569  *      CryptCATGetCatAttrInfo  (WINTRUST.@)
570  */
571 CRYPTCATATTRIBUTE * WINAPI CryptCATGetCatAttrInfo(HANDLE hCatalog, LPWSTR tag)
572 {
573     struct cryptcat *cc = hCatalog;
574
575     FIXME("%p, %s\n", hCatalog, debugstr_w(tag));
576
577     if (!hCatalog || hCatalog == INVALID_HANDLE_VALUE || cc->magic != CRYPTCAT_MAGIC)
578     {
579         SetLastError(ERROR_INVALID_PARAMETER);
580         return NULL;
581     }
582     SetLastError(CRYPT_E_NOT_FOUND);
583     return NULL;
584 }
585
586 CRYPTCATMEMBER * WINAPI CryptCATGetMemberInfo(HANDLE hCatalog, LPWSTR tag)
587 {
588     struct cryptcat *cc = hCatalog;
589
590     FIXME("%p, %s\n", hCatalog, debugstr_w(tag));
591
592     if (!hCatalog || hCatalog == INVALID_HANDLE_VALUE || cc->magic != CRYPTCAT_MAGIC)
593     {
594         SetLastError(ERROR_INVALID_PARAMETER);
595         return NULL;
596     }
597     SetLastError(CRYPT_E_NOT_FOUND);
598     return NULL;
599 }
600
601 /***********************************************************************
602  *      CryptCATEnumerateAttr  (WINTRUST.@)
603  */
604 CRYPTCATATTRIBUTE * WINAPI CryptCATEnumerateAttr(HANDLE hCatalog, CRYPTCATMEMBER *member, CRYPTCATATTRIBUTE *prev)
605 {
606     struct cryptcat *cc = hCatalog;
607
608     FIXME("%p, %p, %p\n", hCatalog, member, prev);
609
610     if (!hCatalog || hCatalog == INVALID_HANDLE_VALUE || cc->magic != CRYPTCAT_MAGIC)
611     {
612         SetLastError(ERROR_INVALID_PARAMETER);
613         return NULL;
614     }
615     SetLastError(CRYPT_E_NOT_FOUND);
616     return NULL;
617 }
618
619 /***********************************************************************
620  *      CryptCATEnumerateCatAttr  (WINTRUST.@)
621  */
622 CRYPTCATATTRIBUTE * WINAPI CryptCATEnumerateCatAttr(HANDLE hCatalog, CRYPTCATATTRIBUTE *prev)
623 {
624     struct cryptcat *cc = hCatalog;
625
626     FIXME("%p, %p\n", hCatalog, prev);
627
628     if (!hCatalog || hCatalog == INVALID_HANDLE_VALUE || cc->magic != CRYPTCAT_MAGIC)
629     {
630         SetLastError(ERROR_INVALID_PARAMETER);
631         return NULL;
632     }
633     SetLastError(CRYPT_E_NOT_FOUND);
634     return NULL;
635 }
636
637 /***********************************************************************
638  *      CryptCATEnumerateMember  (WINTRUST.@)
639  */
640 CRYPTCATMEMBER * WINAPI CryptCATEnumerateMember(HANDLE hCatalog, CRYPTCATMEMBER *prev)
641 {
642     struct cryptcat *cc = hCatalog;
643     CRYPTCATMEMBER *member = prev;
644     CTL_ENTRY *entry;
645     DWORD size, i;
646
647     TRACE("%p, %p\n", hCatalog, prev);
648
649     if (!hCatalog || hCatalog == INVALID_HANDLE_VALUE || cc->magic != CRYPTCAT_MAGIC)
650     {
651         SetLastError(ERROR_INVALID_PARAMETER);
652         return NULL;
653     }
654
655     /* dumping the contents makes me think that dwReserved is the iteration number */
656     if (!member)
657     {
658         if (!(member = HeapAlloc(GetProcessHeap(), 0, sizeof(*member))))
659         {
660             SetLastError(ERROR_OUTOFMEMORY);
661             return NULL;
662         }
663         member->cbStruct = sizeof(*member);
664         member->pwszFileName = member->pwszReferenceTag = NULL;
665         member->dwReserved = 0;
666         member->hReserved = NULL;
667         member->gSubjectType = cc->subject;
668         member->fdwMemberFlags = 0;
669         member->pIndirectData = NULL;
670         member->dwCertVersion = cc->inner->dwVersion;
671     }
672     else member->dwReserved++;
673
674     if (member->dwReserved >= cc->inner->cCTLEntry)
675     {
676         SetLastError(ERROR_INVALID_PARAMETER);
677         goto error;
678     }
679
680     /* list them backwards, like native */
681     entry = &cc->inner->rgCTLEntry[cc->inner->cCTLEntry - member->dwReserved - 1];
682
683     member->sEncodedIndirectData.cbData = member->sEncodedMemberInfo.cbData = 0;
684     member->sEncodedIndirectData.pbData = member->sEncodedMemberInfo.pbData = NULL;
685     HeapFree(GetProcessHeap(), 0, member->pIndirectData);
686     member->pIndirectData = NULL;
687
688     for (i = 0; i < entry->cAttribute; i++)
689     {
690         CRYPT_ATTRIBUTE *attr = entry->rgAttribute + i;
691
692         if (attr->cValue != 1)
693         {
694             ERR("Can't handle attr->cValue of %u\n", attr->cValue);
695             continue;
696         }
697         if (!strcmp(attr->pszObjId, CAT_MEMBERINFO_OBJID))
698         {
699             CAT_MEMBERINFO *mi;
700             BOOL ret;
701
702             member->sEncodedMemberInfo.cbData = attr->rgValue->cbData;
703             member->sEncodedMemberInfo.pbData = attr->rgValue->pbData;
704
705             CryptDecodeObject(cc->encoding, CAT_MEMBERINFO_OBJID, attr->rgValue->pbData, attr->rgValue->cbData, 0, NULL, &size);
706
707             if (!(mi = HeapAlloc(GetProcessHeap(), 0, size)))
708             {
709                 SetLastError(ERROR_OUTOFMEMORY);
710                 goto error;
711             }
712             ret = CryptDecodeObject(cc->encoding, CAT_MEMBERINFO_OBJID, attr->rgValue->pbData, attr->rgValue->cbData, 0, mi, &size);
713             if (ret)
714             {
715                 UNICODE_STRING guid;
716
717                 member->dwCertVersion = mi->dwCertVersion;
718                 RtlInitUnicodeString(&guid, mi->pwszSubjGuid);
719                 if (RtlGUIDFromString(&guid, &member->gSubjectType))
720                 {
721                     HeapFree(GetProcessHeap(), 0, mi);
722                     goto error;
723                 }
724             }
725             HeapFree(GetProcessHeap(), 0, mi);
726             if (!ret) goto error;
727         }
728         else if (!strcmp(attr->pszObjId, SPC_INDIRECT_DATA_OBJID))
729         {
730             /* SPC_INDIRECT_DATA_CONTENT is equal to SIP_INDIRECT_DATA */
731
732             member->sEncodedIndirectData.cbData = attr->rgValue->cbData;
733             member->sEncodedIndirectData.pbData = attr->rgValue->pbData;
734
735             CryptDecodeObject(cc->encoding, SPC_INDIRECT_DATA_OBJID, attr->rgValue->pbData, attr->rgValue->cbData, 0, NULL, &size);
736
737             if (!(member->pIndirectData = HeapAlloc(GetProcessHeap(), 0, size)))
738             {
739                 SetLastError(ERROR_OUTOFMEMORY);
740                 goto error;
741             }
742             CryptDecodeObject(cc->encoding, SPC_INDIRECT_DATA_OBJID, attr->rgValue->pbData, attr->rgValue->cbData, 0, member->pIndirectData, &size);
743         }
744         else
745             /* this object id should probably be handled in CryptCATEnumerateAttr */
746             FIXME("unhandled object id \"%s\"\n", attr->pszObjId);
747     }
748
749     if (!member->sEncodedMemberInfo.cbData || !member->sEncodedIndirectData.cbData)
750     {
751         ERR("Corrupted catalog entry?\n");
752         SetLastError(CRYPT_E_ATTRIBUTES_MISSING);
753         goto error;
754     }
755     size = (2 * member->pIndirectData->Digest.cbData + 1) * sizeof(WCHAR);
756     if (member->pwszReferenceTag)
757         member->pwszReferenceTag = HeapReAlloc(GetProcessHeap(), 0, member->pwszReferenceTag, size);
758     else
759         member->pwszReferenceTag = HeapAlloc(GetProcessHeap(), 0, size);
760
761     if (!member->pwszReferenceTag)
762     {
763         SetLastError(ERROR_OUTOFMEMORY);
764         goto error;
765     }
766     /* FIXME: reference tag is usually the file hash but doesn't have to be */
767     for (i = 0; i < member->pIndirectData->Digest.cbData; i++)
768     {
769         DWORD sub;
770
771         sub = member->pIndirectData->Digest.pbData[i] >> 4;
772         member->pwszReferenceTag[i * 2] = (sub < 10 ? '0' + sub : 'A' + sub - 10);
773         sub = member->pIndirectData->Digest.pbData[i] & 0xf;
774         member->pwszReferenceTag[i * 2 + 1] = (sub < 10 ? '0' + sub : 'A' + sub - 10);
775     }
776     member->pwszReferenceTag[i * 2] = 0;
777     return member;
778
779 error:
780     HeapFree(GetProcessHeap(), 0, member->pIndirectData);
781     HeapFree(GetProcessHeap(), 0, member->pwszReferenceTag);
782     HeapFree(GetProcessHeap(), 0, member);
783     return NULL;
784 }
785
786 static CTL_INFO *decode_inner_content(HANDLE hmsg, DWORD encoding, DWORD *len)
787 {
788     DWORD size;
789     LPSTR oid = NULL;
790     BYTE *buffer = NULL;
791     CTL_INFO *inner = NULL;
792
793     if (!CryptMsgGetParam(hmsg, CMSG_INNER_CONTENT_TYPE_PARAM, 0, NULL, &size)) return NULL;
794     if (!(oid = HeapAlloc(GetProcessHeap(), 0, size)))
795     {
796         SetLastError(ERROR_OUTOFMEMORY);
797         return NULL;
798     }
799     if (!CryptMsgGetParam(hmsg, CMSG_INNER_CONTENT_TYPE_PARAM, 0, oid, &size)) goto out;
800     if (!CryptMsgGetParam(hmsg, CMSG_CONTENT_PARAM, 0, NULL, &size)) goto out;
801     if (!(buffer = HeapAlloc(GetProcessHeap(), 0, size)))
802     {
803         SetLastError(ERROR_OUTOFMEMORY);
804         goto out;
805     }
806     if (!CryptMsgGetParam(hmsg, CMSG_CONTENT_PARAM, 0, buffer, &size)) goto out;
807     if (!CryptDecodeObject(encoding, oid, buffer, size, 0, NULL, &size)) goto out;
808     if (!(inner = HeapAlloc(GetProcessHeap(), 0, size)))
809     {
810         SetLastError(ERROR_OUTOFMEMORY);
811         goto out;
812     }
813     if (!CryptDecodeObject(encoding, oid, buffer, size, 0, inner, &size)) goto out;
814     *len = size;
815
816 out:
817     HeapFree(GetProcessHeap(), 0, oid);
818     HeapFree(GetProcessHeap(), 0, buffer);
819     return inner;
820 }
821
822 /***********************************************************************
823  *      CryptCATCatalogInfoFromContext  (WINTRUST.@)
824  */
825 BOOL WINAPI CryptCATCatalogInfoFromContext(HCATINFO hcatinfo, CATALOG_INFO *info, DWORD flags)
826 {
827     struct catinfo *ci = hcatinfo;
828
829     TRACE("%p, %p, %x\n", hcatinfo, info, flags);
830
831     if (!hcatinfo || hcatinfo == INVALID_HANDLE_VALUE || ci->magic != CATINFO_MAGIC ||
832         flags || !info || info->cbStruct != sizeof(*info))
833     {
834         SetLastError(ERROR_INVALID_PARAMETER);
835         return FALSE;
836     }
837     strcpyW(info->wszCatalogFile, ci->file);
838     return TRUE;
839 }
840
841 /***********************************************************************
842  *      CryptCATOpen  (WINTRUST.@)
843  */
844 HANDLE WINAPI CryptCATOpen(LPWSTR pwszFileName, DWORD fdwOpenFlags, HCRYPTPROV hProv,
845                            DWORD dwPublicVersion, DWORD dwEncodingType)
846 {
847     HANDLE file, hmsg;
848     BYTE *buffer = NULL;
849     DWORD size, flags = OPEN_EXISTING;
850     struct cryptcat *cc;
851
852     TRACE("%s, %x, %lx, %x, %x\n", debugstr_w(pwszFileName), fdwOpenFlags,
853           hProv, dwPublicVersion, dwEncodingType);
854
855     if (!pwszFileName)
856     {
857         SetLastError(ERROR_INVALID_PARAMETER);
858         return INVALID_HANDLE_VALUE;
859     }
860
861     if (!dwEncodingType)  dwEncodingType  = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING;
862
863     if (fdwOpenFlags & CRYPTCAT_OPEN_ALWAYS)    flags |= OPEN_ALWAYS;
864     if (fdwOpenFlags & CRYPTCAT_OPEN_CREATENEW) flags |= CREATE_NEW;
865
866     file = CreateFileW(pwszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, flags, 0, NULL);
867     if (file == INVALID_HANDLE_VALUE) return INVALID_HANDLE_VALUE;
868
869     size = GetFileSize(file, NULL);
870     if (!(buffer = HeapAlloc(GetProcessHeap(), 0, size)))
871     {
872         CloseHandle(file);
873         SetLastError(ERROR_OUTOFMEMORY);
874         return INVALID_HANDLE_VALUE;
875     }
876     if (!(hmsg = CryptMsgOpenToDecode(dwEncodingType, 0, 0, hProv, NULL, NULL)))
877     {
878         CloseHandle(file);
879         HeapFree(GetProcessHeap(), 0, buffer);
880         return INVALID_HANDLE_VALUE;
881     }
882     if (!ReadFile(file, buffer, size, &size, NULL) || !CryptMsgUpdate(hmsg, buffer, size, TRUE))
883     {
884         CloseHandle(file);
885         HeapFree(GetProcessHeap(), 0, buffer);
886         CryptMsgClose(hmsg);
887         return INVALID_HANDLE_VALUE;
888     }
889     HeapFree(GetProcessHeap(), 0, buffer);
890     CloseHandle(file);
891
892     size = sizeof(DWORD);
893     if (!(cc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*cc))))
894     {
895         CryptMsgClose(hmsg);
896         SetLastError(ERROR_OUTOFMEMORY);
897         return INVALID_HANDLE_VALUE;
898     }
899
900     cc->msg = hmsg;
901     cc->encoding = dwEncodingType;
902     if (CryptMsgGetParam(hmsg, CMSG_ATTR_CERT_COUNT_PARAM, 0, &cc->attr_count, &size))
903     {
904         DWORD i, sum = 0;
905         BYTE *p;
906
907         for (i = 0; i < cc->attr_count; i++)
908         {
909             if (!CryptMsgGetParam(hmsg, CMSG_ATTR_CERT_PARAM, i, NULL, &size))
910             {
911                 CryptMsgClose(hmsg);
912                 return INVALID_HANDLE_VALUE;
913             }
914             sum += size;
915         }
916         if (!(cc->attr = HeapAlloc(GetProcessHeap(), 0, sizeof(*cc->attr) * cc->attr_count + sum)))
917         {
918             CryptMsgClose(hmsg);
919             SetLastError(ERROR_OUTOFMEMORY);
920             return INVALID_HANDLE_VALUE;
921         }
922         p = (BYTE *)(cc->attr + cc->attr_count);
923         for (i = 0; i < cc->attr_count; i++)
924         {
925             if (!CryptMsgGetParam(hmsg, CMSG_ATTR_CERT_PARAM, i, NULL, &size))
926             {
927                 CryptMsgClose(hmsg);
928                 HeapFree(GetProcessHeap(), 0, cc->attr);
929                 return INVALID_HANDLE_VALUE;
930             }
931             if (!CryptMsgGetParam(hmsg, CMSG_ATTR_CERT_PARAM, i, p, &size))
932             {
933                 CryptMsgClose(hmsg);
934                 HeapFree(GetProcessHeap(), 0, cc->attr);
935                 return INVALID_HANDLE_VALUE;
936             }
937             p += size;
938         }
939         cc->inner = decode_inner_content(hmsg, dwEncodingType, &cc->inner_len);
940         if (!cc->inner || !CryptSIPRetrieveSubjectGuid(pwszFileName, NULL, &cc->subject))
941         {
942             CryptMsgClose(hmsg);
943             HeapFree(GetProcessHeap(), 0, cc->attr);
944             HeapFree(GetProcessHeap(), 0, cc->inner);
945             HeapFree(GetProcessHeap(), 0, cc);
946             return INVALID_HANDLE_VALUE;
947         }
948         cc->magic = CRYPTCAT_MAGIC;
949         return cc;
950     }
951     return INVALID_HANDLE_VALUE;
952 }
953
954 /***********************************************************************
955  *      CryptSIPCreateIndirectData  (WINTRUST.@)
956  */
957 BOOL WINAPI CryptSIPCreateIndirectData(SIP_SUBJECTINFO* pSubjectInfo, DWORD* pcbIndirectData,
958                                        SIP_INDIRECT_DATA* pIndirectData)
959 {
960     FIXME("(%p %p %p) stub\n", pSubjectInfo, pcbIndirectData, pIndirectData);
961  
962     return FALSE;
963 }
964
965
966 /***********************************************************************
967  *      CryptCATCDFClose  (WINTRUST.@)
968  */
969 BOOL WINAPI CryptCATCDFClose(CRYPTCATCDF *pCDF)
970 {
971     FIXME("(%p) stub\n", pCDF);
972
973     return FALSE;
974 }
975
976 /***********************************************************************
977  *      CryptCATCDFEnumCatAttributes  (WINTRUST.@)
978  */
979 CRYPTCATATTRIBUTE * WINAPI CryptCATCDFEnumCatAttributes(CRYPTCATCDF *pCDF,
980                                                         CRYPTCATATTRIBUTE *pPrevAttr,
981                                                         PFN_CDF_PARSE_ERROR_CALLBACK pfnParseError)
982 {
983     FIXME("(%p %p %p) stub\n", pCDF, pPrevAttr, pfnParseError);
984
985     return NULL;
986 }
987
988 /***********************************************************************
989  *      CryptCATCDFEnumMembersByCDFTagEx  (WINTRUST.@)
990  */
991 LPWSTR WINAPI CryptCATCDFEnumMembersByCDFTagEx(CRYPTCATCDF *pCDF, LPWSTR pwszPrevCDFTag,
992                                                PFN_CDF_PARSE_ERROR_CALLBACK pfnParseError,
993                                                CRYPTCATMEMBER **ppMember, BOOL fContinueOnError,
994                                                LPVOID pvReserved)
995 {
996     FIXME("(%p %s %p %p %d %p) stub\n", pCDF, debugstr_w(pwszPrevCDFTag), pfnParseError,
997           ppMember, fContinueOnError, pvReserved);
998
999     return NULL;
1000 }
1001
1002 /***********************************************************************
1003  *      CryptCATCDFOpen  (WINTRUST.@)
1004  */
1005 CRYPTCATCDF * WINAPI CryptCATCDFOpen(LPWSTR pwszFilePath,
1006                                      PFN_CDF_PARSE_ERROR_CALLBACK pfnParseError)
1007 {
1008     FIXME("(%s %p) stub\n", debugstr_w(pwszFilePath), pfnParseError);
1009
1010     return NULL;
1011 }
1012
1013 static BOOL WINTRUST_GetSignedMsgFromPEFile(SIP_SUBJECTINFO *pSubjectInfo,
1014  DWORD *pdwEncodingType, DWORD dwIndex, DWORD *pcbSignedDataMsg,
1015  BYTE *pbSignedDataMsg)
1016 {
1017     BOOL ret;
1018     WIN_CERTIFICATE *pCert = NULL;
1019     HANDLE file;
1020
1021     TRACE("(%p %p %d %p %p)\n", pSubjectInfo, pdwEncodingType, dwIndex,
1022           pcbSignedDataMsg, pbSignedDataMsg);
1023
1024     if(pSubjectInfo->hFile && pSubjectInfo->hFile!=INVALID_HANDLE_VALUE)
1025         file = pSubjectInfo->hFile;
1026     else
1027     {
1028         file = CreateFileW(pSubjectInfo->pwsFileName, GENERIC_READ,
1029                 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
1030         if(file == INVALID_HANDLE_VALUE)
1031             return FALSE;
1032     }
1033  
1034     if (!pbSignedDataMsg)
1035     {
1036         WIN_CERTIFICATE cert;
1037
1038         /* app hasn't passed buffer, just get the length */
1039         ret = ImageGetCertificateHeader(file, dwIndex, &cert);
1040         if (ret)
1041         {
1042             switch (cert.wCertificateType)
1043             {
1044             case WIN_CERT_TYPE_X509:
1045             case WIN_CERT_TYPE_PKCS_SIGNED_DATA:
1046                 *pcbSignedDataMsg = cert.dwLength;
1047                 break;
1048             default:
1049                 WARN("unknown certificate type %d\n", cert.wCertificateType);
1050                 ret = FALSE;
1051             }
1052         }
1053     }
1054     else
1055     {
1056         DWORD len = 0;
1057
1058         ret = ImageGetCertificateData(file, dwIndex, NULL, &len);
1059         if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1060             goto error;
1061         pCert = HeapAlloc(GetProcessHeap(), 0, len);
1062         if (!pCert)
1063         {
1064             ret = FALSE;
1065             goto error;
1066         }
1067         ret = ImageGetCertificateData(file, dwIndex, pCert, &len);
1068         if (!ret)
1069             goto error;
1070         pCert->dwLength -= FIELD_OFFSET(WIN_CERTIFICATE, bCertificate);
1071         if (*pcbSignedDataMsg < pCert->dwLength)
1072         {
1073             *pcbSignedDataMsg = pCert->dwLength;
1074             SetLastError(ERROR_INSUFFICIENT_BUFFER);
1075             ret = FALSE;
1076         }
1077         else
1078         {
1079             memcpy(pbSignedDataMsg, pCert->bCertificate, pCert->dwLength);
1080             *pcbSignedDataMsg = pCert->dwLength;
1081             switch (pCert->wCertificateType)
1082             {
1083             case WIN_CERT_TYPE_X509:
1084                 *pdwEncodingType = X509_ASN_ENCODING;
1085                 break;
1086             case WIN_CERT_TYPE_PKCS_SIGNED_DATA:
1087                 *pdwEncodingType = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING;
1088                 break;
1089             default:
1090                 WARN("don't know what to do for encoding type %d\n",
1091                  pCert->wCertificateType);
1092                 *pdwEncodingType = 0;
1093                 ret = FALSE;
1094             }
1095         }
1096     }
1097 error:
1098     if(pSubjectInfo->hFile != file)
1099         CloseHandle(file);
1100     HeapFree(GetProcessHeap(), 0, pCert);
1101     return ret;
1102 }
1103
1104 static BOOL WINTRUST_PutSignedMsgToPEFile(SIP_SUBJECTINFO* pSubjectInfo, DWORD pdwEncodingType,
1105         DWORD* pdwIndex, DWORD cbSignedDataMsg, BYTE* pbSignedDataMsg)
1106 {
1107     WIN_CERTIFICATE *cert;
1108     HANDLE file;
1109     DWORD size;
1110     BOOL ret;
1111
1112     if(pSubjectInfo->hFile && pSubjectInfo->hFile!=INVALID_HANDLE_VALUE)
1113         file = pSubjectInfo->hFile;
1114     else
1115     {
1116         file = CreateFileW(pSubjectInfo->pwsFileName, GENERIC_READ|GENERIC_WRITE,
1117                 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
1118         if(file == INVALID_HANDLE_VALUE)
1119             return FALSE;
1120     }
1121
1122     /* int aligned WIN_CERTIFICATE structure with cbSignedDataMsg+1 bytes of data */
1123     size = FIELD_OFFSET(WIN_CERTIFICATE, bCertificate[cbSignedDataMsg+4]) & (~3);
1124     cert = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
1125     if(!cert)
1126         return FALSE;
1127
1128     cert->dwLength = size;
1129     cert->wRevision = WIN_CERT_REVISION_2_0;
1130     cert->wCertificateType = WIN_CERT_TYPE_PKCS_SIGNED_DATA;
1131     memcpy(cert->bCertificate, pbSignedDataMsg, cbSignedDataMsg);
1132     ret = ImageAddCertificate(file, cert, pdwIndex);
1133
1134     HeapFree(GetProcessHeap(), 0, cert);
1135     if(file != pSubjectInfo->hFile)
1136         CloseHandle(file);
1137     return ret;
1138 }
1139
1140 /* structure offsets */
1141 #define cfhead_Signature         (0x00)
1142 #define cfhead_CabinetSize       (0x08)
1143 #define cfhead_MinorVersion      (0x18)
1144 #define cfhead_MajorVersion      (0x19)
1145 #define cfhead_Flags             (0x1E)
1146 #define cfhead_SIZEOF            (0x24)
1147 #define cfheadext_HeaderReserved (0x00)
1148 #define cfheadext_SIZEOF         (0x04)
1149 #define cfsigninfo_CertOffset    (0x04)
1150 #define cfsigninfo_CertSize      (0x08)
1151 #define cfsigninfo_SIZEOF        (0x0C)
1152
1153 /* flags */
1154 #define cfheadRESERVE_PRESENT          (0x0004)
1155
1156 /* endian-neutral reading of little-endian data */
1157 #define EndGetI32(a)  ((((a)[3])<<24)|(((a)[2])<<16)|(((a)[1])<<8)|((a)[0]))
1158 #define EndGetI16(a)  ((((a)[1])<<8)|((a)[0]))
1159
1160 /* For documentation purposes only:  this is the structure in the reserved
1161  * area of a signed cabinet file.  The cert offset indicates where in the
1162  * cabinet file the signature resides, and the count indicates its size.
1163  */
1164 typedef struct _CAB_SIGNINFO
1165 {
1166     WORD unk0; /* always 0? */
1167     WORD unk1; /* always 0x0010? */
1168     DWORD dwCertOffset;
1169     DWORD cbCertBlock;
1170 } CAB_SIGNINFO, *PCAB_SIGNINFO;
1171
1172 static BOOL WINTRUST_GetSignedMsgFromCabFile(SIP_SUBJECTINFO *pSubjectInfo,
1173  DWORD *pdwEncodingType, DWORD dwIndex, DWORD *pcbSignedDataMsg,
1174  BYTE *pbSignedDataMsg)
1175 {
1176     int header_resv;
1177     LONG base_offset, cabsize;
1178     USHORT flags;
1179     BYTE buf[64];
1180     DWORD cert_offset, cert_size, dwRead;
1181
1182     TRACE("(%p %p %d %p %p)\n", pSubjectInfo, pdwEncodingType, dwIndex,
1183           pcbSignedDataMsg, pbSignedDataMsg);
1184
1185     /* get basic offset & size info */
1186     base_offset = SetFilePointer(pSubjectInfo->hFile, 0L, NULL, SEEK_CUR);
1187
1188     if (SetFilePointer(pSubjectInfo->hFile, 0, NULL, SEEK_END) == INVALID_SET_FILE_POINTER)
1189     {
1190         TRACE("seek error\n");
1191         return FALSE;
1192     }
1193
1194     cabsize = SetFilePointer(pSubjectInfo->hFile, 0L, NULL, SEEK_CUR);
1195     if ((cabsize == -1) || (base_offset == -1) ||
1196      (SetFilePointer(pSubjectInfo->hFile, 0, NULL, SEEK_SET) == INVALID_SET_FILE_POINTER))
1197     {
1198         TRACE("seek error\n");
1199         return FALSE;
1200     }
1201
1202     /* read in the CFHEADER */
1203     if (!ReadFile(pSubjectInfo->hFile, buf, cfhead_SIZEOF, &dwRead, NULL) ||
1204      dwRead != cfhead_SIZEOF)
1205     {
1206         TRACE("reading header failed\n");
1207         return FALSE;
1208     }
1209
1210     /* check basic MSCF signature */
1211     if (EndGetI32(buf+cfhead_Signature) != 0x4643534d)
1212     {
1213         WARN("cabinet signature not present\n");
1214         return FALSE;
1215     }
1216
1217     /* Ignore the number of folders and files and the set and cabinet IDs */
1218
1219     /* check the header revision */
1220     if ((buf[cfhead_MajorVersion] > 1) ||
1221         (buf[cfhead_MajorVersion] == 1 && buf[cfhead_MinorVersion] > 3))
1222     {
1223         WARN("cabinet format version > 1.3\n");
1224         return FALSE;
1225     }
1226
1227     /* pull the flags out */
1228     flags = EndGetI16(buf+cfhead_Flags);
1229
1230     if (!(flags & cfheadRESERVE_PRESENT))
1231     {
1232         TRACE("no header present, not signed\n");
1233         return FALSE;
1234     }
1235
1236     if (!ReadFile(pSubjectInfo->hFile, buf, cfheadext_SIZEOF, &dwRead, NULL) ||
1237      dwRead != cfheadext_SIZEOF)
1238     {
1239         ERR("bunk reserve-sizes?\n");
1240         return FALSE;
1241     }
1242
1243     header_resv = EndGetI16(buf+cfheadext_HeaderReserved);
1244     if (!header_resv)
1245     {
1246         TRACE("no header_resv, not signed\n");
1247         return FALSE;
1248     }
1249     else if (header_resv < cfsigninfo_SIZEOF)
1250     {
1251         TRACE("header_resv too small, not signed\n");
1252         return FALSE;
1253     }
1254
1255     if (header_resv > 60000)
1256     {
1257         WARN("WARNING; header reserved space > 60000\n");
1258     }
1259
1260     if (!ReadFile(pSubjectInfo->hFile, buf, cfsigninfo_SIZEOF, &dwRead, NULL) ||
1261      dwRead != cfsigninfo_SIZEOF)
1262     {
1263         ERR("couldn't read reserve\n");
1264         return FALSE;
1265     }
1266
1267     cert_offset = EndGetI32(buf+cfsigninfo_CertOffset);
1268     TRACE("cert_offset: %d\n", cert_offset);
1269     cert_size = EndGetI32(buf+cfsigninfo_CertSize);
1270     TRACE("cert_size: %d\n", cert_size);
1271
1272     /* The redundant checks are to avoid wraparound */
1273     if (cert_offset > cabsize || cert_size > cabsize ||
1274      cert_offset + cert_size > cabsize)
1275     {
1276         WARN("offset beyond file, not attempting to read\n");
1277         return FALSE;
1278     }
1279
1280     SetFilePointer(pSubjectInfo->hFile, base_offset, NULL, SEEK_SET);
1281     if (!pbSignedDataMsg)
1282     {
1283         *pcbSignedDataMsg = cert_size;
1284         return TRUE;
1285     }
1286     if (*pcbSignedDataMsg < cert_size)
1287     {
1288         *pcbSignedDataMsg = cert_size;
1289         SetLastError(ERROR_INSUFFICIENT_BUFFER);
1290         return FALSE;
1291     }
1292     if (SetFilePointer(pSubjectInfo->hFile, cert_offset, NULL, SEEK_SET) == INVALID_SET_FILE_POINTER)
1293     {
1294         ERR("couldn't seek to cert location\n");
1295         return FALSE;
1296     }
1297     if (!ReadFile(pSubjectInfo->hFile, pbSignedDataMsg, cert_size, &dwRead,
1298      NULL) || dwRead != cert_size)
1299     {
1300         ERR("couldn't read cert\n");
1301         SetFilePointer(pSubjectInfo->hFile, base_offset, NULL, SEEK_SET);
1302         return FALSE;
1303     }
1304     /* The encoding of the files I've seen appears to be in ASN.1
1305      * format, and there isn't a field indicating the type, so assume it
1306      * always is.
1307      */
1308     *pdwEncodingType = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING;
1309     /* Restore base offset */
1310     SetFilePointer(pSubjectInfo->hFile, base_offset, NULL, SEEK_SET);
1311     return TRUE;
1312 }
1313
1314 static BOOL WINTRUST_GetSignedMsgFromCatFile(SIP_SUBJECTINFO *pSubjectInfo,
1315  DWORD *pdwEncodingType, DWORD dwIndex, DWORD *pcbSignedDataMsg,
1316  BYTE *pbSignedDataMsg)
1317 {
1318     BOOL ret;
1319
1320     TRACE("(%p %p %d %p %p)\n", pSubjectInfo, pdwEncodingType, dwIndex,
1321           pcbSignedDataMsg, pbSignedDataMsg);
1322
1323     if (!pbSignedDataMsg)
1324     {
1325         *pcbSignedDataMsg = GetFileSize(pSubjectInfo->hFile, NULL);
1326          ret = TRUE;
1327     }
1328     else
1329     {
1330         DWORD len = GetFileSize(pSubjectInfo->hFile, NULL);
1331
1332         if (*pcbSignedDataMsg < len)
1333         {
1334             *pcbSignedDataMsg = len;
1335             SetLastError(ERROR_INSUFFICIENT_BUFFER);
1336             ret = FALSE;
1337         }
1338         else
1339         {
1340             ret = ReadFile(pSubjectInfo->hFile, pbSignedDataMsg, len,
1341              pcbSignedDataMsg, NULL);
1342             if (ret)
1343                 *pdwEncodingType = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING;
1344         }
1345     }
1346     return ret;
1347 }
1348
1349 /* GUIDs used by CryptSIPGetSignedDataMsg and CryptSIPPutSignedDataMsg */
1350 static const GUID unknown = { 0xC689AAB8, 0x8E78, 0x11D0, { 0x8C,0x47,
1351     0x00,0xC0,0x4F,0xC2,0x95,0xEE } };
1352 static const GUID cabGUID = { 0xC689AABA, 0x8E78, 0x11D0, { 0x8C,0x47,
1353     0x00,0xC0,0x4F,0xC2,0x95,0xEE } };
1354 static const GUID catGUID = { 0xDE351A43, 0x8E59, 0x11D0, { 0x8C,0x47,
1355      0x00,0xC0,0x4F,0xC2,0x95,0xEE }};
1356
1357 /***********************************************************************
1358  *      CryptSIPGetSignedDataMsg  (WINTRUST.@)
1359  */
1360 BOOL WINAPI CryptSIPGetSignedDataMsg(SIP_SUBJECTINFO* pSubjectInfo, DWORD* pdwEncodingType,
1361                                        DWORD dwIndex, DWORD* pcbSignedDataMsg, BYTE* pbSignedDataMsg)
1362 {
1363     BOOL ret;
1364
1365     TRACE("(%p %p %d %p %p)\n", pSubjectInfo, pdwEncodingType, dwIndex,
1366           pcbSignedDataMsg, pbSignedDataMsg);
1367
1368     if(!pSubjectInfo)
1369     {
1370         SetLastError(ERROR_INVALID_PARAMETER);
1371         return FALSE;
1372     }
1373
1374     if (!memcmp(pSubjectInfo->pgSubjectType, &unknown, sizeof(unknown)))
1375         ret = WINTRUST_GetSignedMsgFromPEFile(pSubjectInfo, pdwEncodingType,
1376          dwIndex, pcbSignedDataMsg, pbSignedDataMsg);
1377     else if (!memcmp(pSubjectInfo->pgSubjectType, &cabGUID, sizeof(cabGUID)))
1378         ret = WINTRUST_GetSignedMsgFromCabFile(pSubjectInfo, pdwEncodingType,
1379          dwIndex, pcbSignedDataMsg, pbSignedDataMsg);
1380     else if (!memcmp(pSubjectInfo->pgSubjectType, &catGUID, sizeof(catGUID)))
1381         ret = WINTRUST_GetSignedMsgFromCatFile(pSubjectInfo, pdwEncodingType,
1382          dwIndex, pcbSignedDataMsg, pbSignedDataMsg);
1383     else
1384     {
1385         FIXME("unimplemented for subject type %s\n",
1386          debugstr_guid(pSubjectInfo->pgSubjectType));
1387         ret = FALSE;
1388     }
1389
1390     TRACE("returning %d\n", ret);
1391     return ret;
1392 }
1393
1394 /***********************************************************************
1395  *      CryptSIPPutSignedDataMsg  (WINTRUST.@)
1396  */
1397 BOOL WINAPI CryptSIPPutSignedDataMsg(SIP_SUBJECTINFO* pSubjectInfo, DWORD pdwEncodingType,
1398         DWORD* pdwIndex, DWORD cbSignedDataMsg, BYTE* pbSignedDataMsg)
1399 {
1400     TRACE("(%p %d %p %d %p)\n", pSubjectInfo, pdwEncodingType, pdwIndex,
1401           cbSignedDataMsg, pbSignedDataMsg);
1402
1403     if(!pSubjectInfo) {
1404         SetLastError(ERROR_INVALID_PARAMETER);
1405         return FALSE;
1406     }
1407
1408     if(!memcmp(pSubjectInfo->pgSubjectType, &unknown, sizeof(unknown)))
1409         return WINTRUST_PutSignedMsgToPEFile(pSubjectInfo, pdwEncodingType,
1410                 pdwIndex, cbSignedDataMsg, pbSignedDataMsg);
1411     else
1412         FIXME("unimplemented for subject type %s\n",
1413                 debugstr_guid(pSubjectInfo->pgSubjectType));
1414
1415     return FALSE;
1416 }
1417
1418 /***********************************************************************
1419  *      CryptSIPRemoveSignedDataMsg  (WINTRUST.@)
1420  */
1421 BOOL WINAPI CryptSIPRemoveSignedDataMsg(SIP_SUBJECTINFO* pSubjectInfo,
1422                                        DWORD dwIndex)
1423 {
1424     FIXME("(%p %d) stub\n", pSubjectInfo, dwIndex);
1425  
1426     return FALSE;
1427 }
1428
1429 /***********************************************************************
1430  *      CryptSIPVerifyIndirectData  (WINTRUST.@)
1431  */
1432 BOOL WINAPI CryptSIPVerifyIndirectData(SIP_SUBJECTINFO* pSubjectInfo,
1433                                        SIP_INDIRECT_DATA* pIndirectData)
1434 {
1435     FIXME("(%p %p) stub\n", pSubjectInfo, pIndirectData);
1436  
1437     return FALSE;
1438 }