comparison cinst/windowsstore.c @ 144:dc9970d7b9bf

Merged
author Sascha Wilde <wilde@intevation.de>
date Mon, 24 Mar 2014 16:10:26 +0100
parents 4904fe01055d
children bd5a5d3e5674
comparison
equal deleted inserted replaced
143:b026e6d2a161 144:dc9970d7b9bf
1 #ifdef WIN32
2
3 #include <polarssl/base64.h>
4 #include "windowsstore.h"
5
6 static LPWSTR getLastErrorMsg() {
7 LPWSTR bufPtr = NULL;
8 DWORD err = GetLastError();
9 FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
10 FORMAT_MESSAGE_FROM_SYSTEM |
11 FORMAT_MESSAGE_IGNORE_INSERTS,
12 NULL, err, 0, (LPWSTR)&bufPtr, 0, NULL);
13 if (!bufPtr) {
14 HMODULE hWinhttp = GetModuleHandleW(L"winhttp");
15 if (hWinhttp) {
16 FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
17 FORMAT_MESSAGE_FROM_HMODULE |
18 FORMAT_MESSAGE_IGNORE_INSERTS,
19 hWinhttp, HRESULT_CODE(err), 0,
20 (LPWSTR)&bufPtr, 0, NULL);
21 }
22 }
23 if (!bufPtr)
24 printf("Error getting last error\n");
25 return bufPtr;
26 }
27
28 int install_certificates_win(const char **to_install, int user_store)
29 {
30 int i = 0;
31 HCERTSTORE hStore = NULL;
32
33 if (user_store) {
34 // Access user store
35 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0,
36 0, CERT_SYSTEM_STORE_CURRENT_USER, L"Root");
37 } else {
38 // Access machine store
39 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0,
40 0, CERT_SYSTEM_STORE_LOCAL_MACHINE, L"Root");
41 }
42
43 if (!hStore) {
44 return ERR_STORE_ACCESS_DENIED;
45 }
46
47 while (to_install[i]) {
48 size_t needed_len = 0;
49 size_t cert_len = strnlen(to_install[i], MAX_LINE_LENGTH);
50 int ret = -1;
51 unsigned char *buf;
52
53 /* Check the needed size for the buffer */
54 ret = base64_decode(NULL, &needed_len,
55 (unsigned char *)to_install[i], cert_len);
56
57 if (ret != 0 && ret != POLARSSL_ERR_BASE64_BUFFER_TOO_SMALL) {
58 return ERR_INVALID_INSTRUCTIONS;
59 }
60
61 buf = xmalloc(needed_len);
62 memset (buf, 0, needed_len);
63
64 ret = base64_decode(buf, &needed_len,
65 (unsigned char *)to_install[i], cert_len);
66
67 if (ret != 0) {
68 return ERR_INVALID_INSTRUCTIONS;
69 }
70
71 ret = CertAddEncodedCertificateToStore (hStore,
72 X509_ASN_ENCODING,
73 (PBYTE)buf,
74 needed_len,
75 CERT_STORE_ADD_ALWAYS,
76 NULL);
77
78 if (ret == 0) {
79 LPWSTR error = getLastErrorMsg();
80 if (error) {
81 printf("Failed to add certificate: %S \n", error);
82 LocalFree(error);
83 }
84 }
85 i++;
86 free(buf);
87 }
88 if(hStore) {
89 CertCloseStore(hStore, 0);
90 }
91 return 0;
92 }
93 #endif // WIN32

http://wald.intevation.org/projects/trustbridge/