xref: /openbmc/qemu/qga/vss-win32/install.cpp (revision 64ed6f92)
1 /*
2  * QEMU Guest Agent win32 VSS Provider installer
3  *
4  * Copyright Hitachi Data Systems Corp. 2013
5  *
6  * Authors:
7  *  Tomoki Sekiyama   <tomoki.sekiyama@hds.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2 or later.
10  * See the COPYING file in the top-level directory.
11  */
12 
13 #include "qemu/osdep.h"
14 
15 #include "vss-common.h"
16 #include <inc/win2003/vscoordint.h>
17 #include "install.h"
18 #include <wbemidl.h>
19 #include <comdef.h>
20 #include <comutil.h>
21 #include <sddl.h>
22 #include <winsvc.h>
23 
24 #define BUFFER_SIZE 1024
25 
26 extern HINSTANCE g_hinstDll;
27 
28 const GUID CLSID_COMAdminCatalog = { 0xF618C514, 0xDFB8, 0x11d1,
29     {0xA2, 0xCF, 0x00, 0x80, 0x5F, 0xC7, 0x92, 0x35} };
30 const GUID IID_ICOMAdminCatalog2 = { 0x790C6E0B, 0x9194, 0x4cc9,
31     {0x94, 0x26, 0xA4, 0x8A, 0x63, 0x18, 0x56, 0x96} };
32 const GUID CLSID_WbemLocator = { 0x4590f811, 0x1d3a, 0x11d0,
33     {0x89, 0x1f, 0x00, 0xaa, 0x00, 0x4b, 0x2e, 0x24} };
34 const GUID IID_IWbemLocator = { 0xdc12a687, 0x737f, 0x11cf,
35     {0x88, 0x4d, 0x00, 0xaa, 0x00, 0x4b, 0x2e, 0x24} };
36 
37 void errmsg(DWORD err, const char *text)
38 {
39     /*
40      * `text' contains function call statement when errmsg is called via chk().
41      * To make error message more readable, we cut off the text after '('.
42      * If text doesn't contains '(', negative precision is given, which is
43      * treated as though it were missing.
44      */
45     char *msg = NULL, *nul = strchr(text, '(');
46     int len = nul ? nul - text : -1;
47 
48     FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
49                   FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
50                   NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
51                   (char *)&msg, 0, NULL);
52     fprintf(stderr, "%.*s. (Error: %lx) %s\n", len, text, err, msg);
53     LocalFree(msg);
54 }
55 
56 static void errmsg_dialog(DWORD err, const char *text, const char *opt = "")
57 {
58     char *msg, buf[512];
59 
60     FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
61                   FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
62                   NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
63                   (char *)&msg, 0, NULL);
64     snprintf(buf, sizeof(buf), "%s%s. (Error: %lx) %s", text, opt, err, msg);
65     MessageBox(NULL, buf, "Error from " QGA_PROVIDER_NAME, MB_OK|MB_ICONERROR);
66     LocalFree(msg);
67 }
68 
69 #define _chk(hr, status, msg, err_label)        \
70     do {                                        \
71         hr = (status);                          \
72         if (FAILED(hr)) {                       \
73             errmsg(hr, msg);                    \
74             goto err_label;                     \
75         }                                       \
76     } while (0)
77 
78 #define chk(status) _chk(hr, status, "Failed to " #status, out)
79 
80 #if !defined(__MINGW64_VERSION_MAJOR) || !defined(__MINGW64_VERSION_MINOR) || \
81     __MINGW64_VERSION_MAJOR * 100 + __MINGW64_VERSION_MINOR < 301
82 void __stdcall _com_issue_error(HRESULT hr)
83 {
84     errmsg(hr, "Unexpected error in COM");
85 }
86 #endif
87 
88 template<class T>
89 HRESULT put_Value(ICatalogObject *pObj, LPCWSTR name, T val)
90 {
91     return pObj->put_Value(_bstr_t(name), _variant_t(val));
92 }
93 
94 /* Lookup Administrators group name from winmgmt */
95 static HRESULT GetAdminName(_bstr_t *name)
96 {
97     HRESULT hr;
98     COMPointer<IWbemLocator> pLoc;
99     COMPointer<IWbemServices> pSvc;
100     COMPointer<IEnumWbemClassObject> pEnum;
101     COMPointer<IWbemClassObject> pWobj;
102     ULONG returned;
103     _variant_t var;
104 
105     chk(CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER,
106                          IID_IWbemLocator, (LPVOID *)pLoc.replace()));
107     chk(pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, NULL,
108                             0, 0, 0, pSvc.replace()));
109     chk(CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE,
110                           NULL, RPC_C_AUTHN_LEVEL_CALL,
111                           RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE));
112     chk(pSvc->ExecQuery(_bstr_t(L"WQL"),
113                         _bstr_t(L"select * from Win32_Account where "
114                                 "SID='S-1-5-32-544' and localAccount=TRUE"),
115                         WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY,
116                         NULL, pEnum.replace()));
117     if (!pEnum) {
118         hr = E_FAIL;
119         errmsg(hr, "Failed to query for Administrators");
120         goto out;
121     }
122     chk(pEnum->Next(WBEM_INFINITE, 1, pWobj.replace(), &returned));
123     if (returned == 0) {
124         hr = E_FAIL;
125         errmsg(hr, "No Administrators found");
126         goto out;
127     }
128 
129     chk(pWobj->Get(_bstr_t(L"Name"), 0, &var, 0, 0));
130     try {
131         *name = var;
132     } catch(...) {
133         hr = E_FAIL;
134         errmsg(hr, "Failed to get name of Administrators");
135         goto out;
136     }
137 
138 out:
139     return hr;
140 }
141 
142 /* Acquire group or user name by SID */
143 static HRESULT getNameByStringSID(
144     const wchar_t *sid, LPWSTR buffer, LPDWORD bufferLen)
145 {
146     HRESULT hr = S_OK;
147     PSID psid = NULL;
148     SID_NAME_USE groupType;
149     DWORD domainNameLen = BUFFER_SIZE;
150     wchar_t domainName[BUFFER_SIZE];
151 
152     if (!ConvertStringSidToSidW(sid, &psid)) {
153         hr = HRESULT_FROM_WIN32(GetLastError());
154         goto out;
155     }
156     if (!LookupAccountSidW(NULL, psid, buffer, bufferLen,
157                            domainName, &domainNameLen, &groupType)) {
158         hr = HRESULT_FROM_WIN32(GetLastError());
159         /* Fall through and free psid */
160     }
161 
162     LocalFree(psid);
163 
164 out:
165     return hr;
166 }
167 
168 /* Find and iterate QGA VSS provider in COM+ Application Catalog */
169 static HRESULT QGAProviderFind(
170     HRESULT (*found)(ICatalogCollection *, int, void *), void *arg)
171 {
172     HRESULT hr;
173     COMInitializer initializer;
174     COMPointer<IUnknown> pUnknown;
175     COMPointer<ICOMAdminCatalog2> pCatalog;
176     COMPointer<ICatalogCollection> pColl;
177     COMPointer<ICatalogObject> pObj;
178     _variant_t var;
179     long i, n;
180 
181     chk(CoCreateInstance(CLSID_COMAdminCatalog, NULL, CLSCTX_INPROC_SERVER,
182                          IID_IUnknown, (void **)pUnknown.replace()));
183     chk(pUnknown->QueryInterface(IID_ICOMAdminCatalog2,
184                                  (void **)pCatalog.replace()));
185     chk(pCatalog->GetCollection(_bstr_t(L"Applications"),
186                                 (IDispatch **)pColl.replace()));
187     chk(pColl->Populate());
188 
189     chk(pColl->get_Count(&n));
190     for (i = n - 1; i >= 0; i--) {
191         chk(pColl->get_Item(i, (IDispatch **)pObj.replace()));
192         chk(pObj->get_Value(_bstr_t(L"Name"), &var));
193         if (var == _variant_t(QGA_PROVIDER_LNAME)) {
194             if (FAILED(found(pColl, i, arg))) {
195                 goto out;
196             }
197         }
198     }
199     chk(pColl->SaveChanges(&n));
200 
201 out:
202     return hr;
203 }
204 
205 /* Count QGA VSS provider in COM+ Application Catalog */
206 static HRESULT QGAProviderCount(ICatalogCollection *coll, int i, void *arg)
207 {
208     (*(int *)arg)++;
209     return S_OK;
210 }
211 
212 /* Remove QGA VSS provider from COM+ Application Catalog Collection */
213 static HRESULT QGAProviderRemove(ICatalogCollection *coll, int i, void *arg)
214 {
215     HRESULT hr;
216 
217     fprintf(stderr, "Removing COM+ Application: %s\n", QGA_PROVIDER_NAME);
218     chk(coll->Remove(i));
219 out:
220     return hr;
221 }
222 
223 /* Unregister this module from COM+ Applications Catalog */
224 STDAPI COMUnregister(void)
225 {
226     HRESULT hr;
227 
228     DllUnregisterServer();
229     chk(QGAProviderFind(QGAProviderRemove, NULL));
230 out:
231     return hr;
232 }
233 
234 /* Register this module to COM+ Applications Catalog */
235 STDAPI COMRegister(void)
236 {
237     HRESULT hr;
238     COMInitializer initializer;
239     COMPointer<IUnknown> pUnknown;
240     COMPointer<ICOMAdminCatalog2> pCatalog;
241     COMPointer<ICatalogCollection> pApps, pRoles, pUsersInRole;
242     COMPointer<ICatalogObject> pObj;
243     long n;
244     _bstr_t name;
245     _variant_t key;
246     CHAR dllPath[MAX_PATH], tlbPath[MAX_PATH];
247     bool unregisterOnFailure = false;
248     int count = 0;
249     DWORD bufferLen = BUFFER_SIZE;
250     wchar_t buffer[BUFFER_SIZE];
251     const wchar_t *administratorsGroupSID = L"S-1-5-32-544";
252     const wchar_t *systemUserSID = L"S-1-5-18";
253 
254     if (!g_hinstDll) {
255         errmsg(E_FAIL, "Failed to initialize DLL");
256         return E_FAIL;
257     }
258 
259     chk(QGAProviderFind(QGAProviderCount, (void *)&count));
260     if (count) {
261         errmsg(E_ABORT, "QGA VSS Provider is already installed");
262         return E_ABORT;
263     }
264 
265     chk(CoCreateInstance(CLSID_COMAdminCatalog, NULL, CLSCTX_INPROC_SERVER,
266                          IID_IUnknown, (void **)pUnknown.replace()));
267     chk(pUnknown->QueryInterface(IID_ICOMAdminCatalog2,
268                                  (void **)pCatalog.replace()));
269 
270     /* Install COM+ Component */
271 
272     chk(pCatalog->GetCollection(_bstr_t(L"Applications"),
273                                 (IDispatch **)pApps.replace()));
274     chk(pApps->Populate());
275     chk(pApps->Add((IDispatch **)&pObj));
276     chk(put_Value(pObj, L"Name",        QGA_PROVIDER_LNAME));
277     chk(put_Value(pObj, L"Description", QGA_PROVIDER_LNAME));
278     chk(put_Value(pObj, L"ApplicationAccessChecksEnabled", true));
279     chk(put_Value(pObj, L"Authentication",                 short(6)));
280     chk(put_Value(pObj, L"AuthenticationCapability",       short(2)));
281     chk(put_Value(pObj, L"ImpersonationLevel",             short(2)));
282     chk(pApps->SaveChanges(&n));
283 
284     /* The app should be deleted if something fails after SaveChanges */
285     unregisterOnFailure = true;
286 
287     chk(pObj->get_Key(&key));
288 
289     if (!GetModuleFileName(g_hinstDll, dllPath, sizeof(dllPath))) {
290         hr = HRESULT_FROM_WIN32(GetLastError());
291         errmsg(hr, "GetModuleFileName failed");
292         goto out;
293     }
294     n = strlen(dllPath);
295     if (n < 3) {
296         hr = E_FAIL;
297         errmsg(hr, "Failed to lookup dll");
298         goto out;
299     }
300     strcpy(tlbPath, dllPath);
301     strcpy(tlbPath+n-3, "tlb");
302     fprintf(stderr, "Registering " QGA_PROVIDER_NAME ":\n");
303     fprintf(stderr, "  %s\n", dllPath);
304     fprintf(stderr, "  %s\n", tlbPath);
305     if (!PathFileExists(tlbPath)) {
306         hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
307         errmsg(hr, "Failed to lookup tlb");
308         goto out;
309     }
310 
311     chk(pCatalog->CreateServiceForApplication(
312             _bstr_t(QGA_PROVIDER_LNAME), _bstr_t(QGA_PROVIDER_LNAME),
313             _bstr_t(L"SERVICE_DEMAND_START"), _bstr_t(L"SERVICE_ERROR_NORMAL"),
314             _bstr_t(L""), _bstr_t(L".\\localsystem"), _bstr_t(L""), FALSE));
315     chk(pCatalog->InstallComponent(_bstr_t(QGA_PROVIDER_LNAME),
316                                    _bstr_t(dllPath), _bstr_t(tlbPath),
317                                    _bstr_t("")));
318 
319     /* Setup roles of the applicaion */
320 
321     chk(getNameByStringSID(administratorsGroupSID, buffer, &bufferLen));
322     chk(pApps->GetCollection(_bstr_t(L"Roles"), key,
323                              (IDispatch **)pRoles.replace()));
324     chk(pRoles->Populate());
325     chk(pRoles->Add((IDispatch **)pObj.replace()));
326     chk(put_Value(pObj, L"Name", buffer));
327     chk(put_Value(pObj, L"Description", L"Administrators group"));
328     chk(pRoles->SaveChanges(&n));
329     chk(pObj->get_Key(&key));
330 
331     /* Setup users in the role */
332 
333     chk(pRoles->GetCollection(_bstr_t(L"UsersInRole"), key,
334                               (IDispatch **)pUsersInRole.replace()));
335     chk(pUsersInRole->Populate());
336 
337     chk(pUsersInRole->Add((IDispatch **)pObj.replace()));
338     chk(GetAdminName(&name));
339     chk(put_Value(pObj, L"User", _bstr_t(".\\") + name));
340 
341     bufferLen = BUFFER_SIZE;
342     chk(getNameByStringSID(systemUserSID, buffer, &bufferLen));
343     chk(pUsersInRole->Add((IDispatch **)pObj.replace()));
344     chk(put_Value(pObj, L"User", buffer));
345     chk(pUsersInRole->SaveChanges(&n));
346 
347 out:
348     if (unregisterOnFailure && FAILED(hr)) {
349         COMUnregister();
350     }
351 
352     return hr;
353 }
354 
355 
356 static BOOL CreateRegistryKey(LPCTSTR key, LPCTSTR value, LPCTSTR data)
357 {
358     HKEY  hKey;
359     LONG  ret;
360     DWORD size;
361 
362     ret = RegCreateKeyEx(HKEY_CLASSES_ROOT, key, 0, NULL,
363         REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, NULL);
364     if (ret != ERROR_SUCCESS) {
365         goto out;
366     }
367 
368     if (data != NULL) {
369         size = strlen(data) + 1;
370     } else {
371         size = 0;
372     }
373 
374     ret = RegSetValueEx(hKey, value, 0, REG_SZ, (LPBYTE)data, size);
375     RegCloseKey(hKey);
376 
377 out:
378     if (ret != ERROR_SUCCESS) {
379         /* As we cannot printf within DllRegisterServer(), show a dialog. */
380         errmsg_dialog(ret, "Cannot add registry", key);
381         return FALSE;
382     }
383     return TRUE;
384 }
385 
386 /* Register this dll as a VSS provider */
387 STDAPI DllRegisterServer(void)
388 {
389     COMInitializer initializer;
390     COMPointer<IVssAdmin> pVssAdmin;
391     HRESULT hr = E_FAIL;
392     char dllPath[MAX_PATH];
393     char key[256];
394 
395     if (!g_hinstDll) {
396         errmsg_dialog(hr, "Module instance is not available");
397         goto out;
398     }
399 
400     /* Add this module to registery */
401 
402     sprintf(key, "CLSID\\%s", g_szClsid);
403     if (!CreateRegistryKey(key, NULL, g_szClsid)) {
404         goto out;
405     }
406 
407     if (!GetModuleFileName(g_hinstDll, dllPath, sizeof(dllPath))) {
408         errmsg_dialog(GetLastError(), "GetModuleFileName failed");
409         goto out;
410     }
411 
412     sprintf(key, "CLSID\\%s\\InprocServer32", g_szClsid);
413     if (!CreateRegistryKey(key, NULL, dllPath)) {
414         goto out;
415     }
416 
417     if (!CreateRegistryKey(key, "ThreadingModel", "Apartment")) {
418         goto out;
419     }
420 
421     sprintf(key, "CLSID\\%s\\ProgID", g_szClsid);
422     if (!CreateRegistryKey(key, NULL, g_szProgid)) {
423         goto out;
424     }
425 
426     if (!CreateRegistryKey(g_szProgid, NULL, QGA_PROVIDER_NAME)) {
427         goto out;
428     }
429 
430     sprintf(key, "%s\\CLSID", g_szProgid);
431     if (!CreateRegistryKey(key, NULL, g_szClsid)) {
432         goto out;
433     }
434 
435     hr = CoCreateInstance(CLSID_VSSCoordinator, NULL, CLSCTX_ALL,
436                           IID_IVssAdmin, (void **)pVssAdmin.replace());
437     if (FAILED(hr)) {
438         errmsg_dialog(hr, "CoCreateInstance(VSSCoordinator) failed");
439         goto out;
440     }
441 
442     hr = pVssAdmin->RegisterProvider(g_gProviderId, CLSID_QGAVSSProvider,
443                                      const_cast<WCHAR*>(QGA_PROVIDER_LNAME),
444                                      VSS_PROV_SOFTWARE,
445                                      const_cast<WCHAR*>(QGA_PROVIDER_VERSION),
446                                      g_gProviderVersion);
447     if (hr == (long int) VSS_E_PROVIDER_ALREADY_REGISTERED) {
448         DllUnregisterServer();
449         hr = pVssAdmin->RegisterProvider(g_gProviderId, CLSID_QGAVSSProvider,
450                                          const_cast<WCHAR * >
451                                          (QGA_PROVIDER_LNAME),
452                                          VSS_PROV_SOFTWARE,
453                                          const_cast<WCHAR * >
454                                          (QGA_PROVIDER_VERSION),
455                                          g_gProviderVersion);
456     }
457 
458     if (FAILED(hr)) {
459         errmsg_dialog(hr, "RegisterProvider failed");
460     }
461 
462 out:
463     if (FAILED(hr)) {
464         DllUnregisterServer();
465     }
466 
467     return hr;
468 }
469 
470 /* Unregister this VSS hardware provider from the system */
471 STDAPI DllUnregisterServer(void)
472 {
473     TCHAR key[256];
474     COMInitializer initializer;
475     COMPointer<IVssAdmin> pVssAdmin;
476 
477     HRESULT hr = CoCreateInstance(CLSID_VSSCoordinator,
478                                   NULL, CLSCTX_ALL, IID_IVssAdmin,
479                                   (void **)pVssAdmin.replace());
480     if (SUCCEEDED(hr)) {
481         hr = pVssAdmin->UnregisterProvider(g_gProviderId);
482     } else {
483         errmsg(hr, "CoCreateInstance(VSSCoordinator) failed");
484     }
485 
486     sprintf(key, "CLSID\\%s", g_szClsid);
487     SHDeleteKey(HKEY_CLASSES_ROOT, key);
488     SHDeleteKey(HKEY_CLASSES_ROOT, g_szProgid);
489 
490     return S_OK; /* Uninstall should never fail */
491 }
492 
493 
494 /* Support function to convert ASCII string into BSTR (used in _bstr_t) */
495 namespace _com_util
496 {
497     BSTR WINAPI ConvertStringToBSTR(const char *ascii) {
498         int len = strlen(ascii);
499         BSTR bstr = SysAllocStringLen(NULL, len);
500 
501         if (!bstr) {
502             return NULL;
503         }
504 
505         if (mbstowcs(bstr, ascii, len) == (size_t)-1) {
506             fprintf(stderr, "Failed to convert string '%s' into BSTR", ascii);
507             bstr[0] = 0;
508         }
509         return bstr;
510     }
511 }
512 
513 /* Stop QGA VSS provider service using Winsvc API  */
514 STDAPI StopService(void)
515 {
516     HRESULT hr;
517     SC_HANDLE manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
518     SC_HANDLE service = NULL;
519 
520     if (!manager) {
521         errmsg(E_FAIL, "Failed to open service manager");
522         hr = E_FAIL;
523         goto out;
524     }
525     service = OpenService(manager, QGA_PROVIDER_NAME, SC_MANAGER_ALL_ACCESS);
526 
527     if (!service) {
528         errmsg(E_FAIL, "Failed to open service");
529         hr =  E_FAIL;
530         goto out;
531     }
532     if (!(ControlService(service, SERVICE_CONTROL_STOP, NULL))) {
533         errmsg(E_FAIL, "Failed to stop service");
534         hr = E_FAIL;
535     }
536 
537 out:
538     CloseServiceHandle(service);
539     CloseServiceHandle(manager);
540     return hr;
541 }
542