Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2309 lines
78 KiB

  1. /*++
  2. Copyright (C) 1996-2000 Microsoft Corporation
  3. Module Name:
  4. IMPORT.CPP
  5. Abstract:
  6. History:
  7. --*/
  8. #include "precomp.h"
  9. #include <StdIo.h>
  10. #include <ConIo.h>
  11. #include <wbemint.h>
  12. #include <WbemUtil.h>
  13. #include <corex.h>
  14. #include "upgrade.h"
  15. #include "Import.h"
  16. #include "export.h"
  17. #include "reg.h"
  18. template <class T> class CMyRelMe
  19. {
  20. T m_p;
  21. public:
  22. CMyRelMe(T p) : m_p(p) {};
  23. ~CMyRelMe() { if (m_p) m_p->Release(); }
  24. void Set(T p) { m_p = p; }
  25. };
  26. class CSysFreeMe
  27. {
  28. protected:
  29. BSTR m_str;
  30. public:
  31. CSysFreeMe(BSTR str) : m_str(str){}
  32. ~CSysFreeMe() {SysFreeString(m_str);}
  33. };
  34. bool CRepImporter::CheckOldSecurityClass(const wchar_t* wszClass)
  35. {
  36. // check whether it is an old security class
  37. bool bOldSecurityClass = false;
  38. if(m_bSecurityMode)
  39. {
  40. if(!_wcsicmp(wszClass, L"__SecurityRelatedClass"))
  41. bOldSecurityClass = true;
  42. else if(!_wcsicmp(wszClass, L"__Subject"))
  43. bOldSecurityClass = true;
  44. else if(!_wcsicmp(wszClass, L"__User"))
  45. bOldSecurityClass = true;
  46. else if(!_wcsicmp(wszClass, L"__NTLMUser"))
  47. bOldSecurityClass = true;
  48. else if(!_wcsicmp(wszClass, L"__Group"))
  49. bOldSecurityClass = true;
  50. else if(!_wcsicmp(wszClass, L"__NTLMGroup"))
  51. bOldSecurityClass = true;
  52. }
  53. return bOldSecurityClass;
  54. }
  55. void CRepImporter::DecodeTrailer()
  56. {
  57. DWORD dwTrailerSize = 0;
  58. DWORD dwTrailer[4];
  59. DWORD dwSize = 0;
  60. if ((ReadFile(m_hFile, &dwTrailerSize, 4, &dwSize, NULL) == 0) || (dwSize != 4))
  61. {
  62. LogMessage(MSG_ERROR, "Failed to read a block trailer size.");
  63. throw FAILURE_READ;
  64. }
  65. if (dwTrailerSize != REP_EXPORT_END_TAG_SIZE)
  66. {
  67. LogMessage(MSG_ERROR, "Block trailer size is invalid.");
  68. throw FAILURE_INVALID_TRAILER;
  69. }
  70. if ((ReadFile(m_hFile, dwTrailer, REP_EXPORT_END_TAG_SIZE, &dwSize, NULL) == 0) || (dwSize != REP_EXPORT_END_TAG_SIZE))
  71. {
  72. LogMessage(MSG_ERROR, "Failed to read a block trailer.");
  73. throw FAILURE_READ;
  74. }
  75. for (int i = 0; i < 4; i++)
  76. {
  77. if (dwTrailer[i] != REP_EXPORT_FILE_END_TAG)
  78. {
  79. LogMessage(MSG_ERROR, "Block trailer has invalid contents.");
  80. throw FAILURE_INVALID_TRAILER;
  81. }
  82. }
  83. }
  84. void CRepImporter::DecodeInstanceInt(IWbemServices* pNamespace, const wchar_t *wszFullPath, const wchar_t *pszParentClass, _IWmiObject* pOldParentClass, _IWmiObject *pNewParentClass)
  85. {
  86. char szMsg[MAX_MSG_TEXT_LENGTH];
  87. //Read the key and object size
  88. INT_PTR dwKey = 0;
  89. DWORD dwSize = 0;
  90. if ((ReadFile(m_hFile, &dwKey, sizeof(INT_PTR), &dwSize, NULL) == 0) || (dwSize != sizeof(INT_PTR)))
  91. {
  92. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve instance key for class %S. (i)", pszParentClass);
  93. LogMessage(MSG_ERROR, szMsg);
  94. throw FAILURE_READ;
  95. }
  96. DWORD dwHeader;
  97. if ((ReadFile(m_hFile, &dwHeader, 4, &dwSize, NULL) == 0) || (dwSize != 4))
  98. {
  99. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve instance object size for class %S. (i)", pszParentClass);
  100. LogMessage(MSG_ERROR, szMsg);
  101. throw FAILURE_READ;
  102. }
  103. char *pObjectBlob = new char[dwHeader];
  104. if (pObjectBlob == 0)
  105. {
  106. throw FAILURE_OUT_OF_MEMORY;
  107. }
  108. CVectorDeleteMe<char> delMe(pObjectBlob);
  109. //Read the blob
  110. if ((ReadFile(m_hFile, pObjectBlob, dwHeader, &dwSize, NULL) == 0) || (dwSize != dwHeader))
  111. {
  112. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve instance information for class %S. (i)", pszParentClass);
  113. LogMessage(MSG_ERROR, szMsg);
  114. throw FAILURE_READ;
  115. }
  116. if (pNewParentClass == (_IWmiObject*)-1)
  117. {
  118. //We are working with a class which has problems... we need to ignore this instance...
  119. return;
  120. }
  121. // create old Nova-style instance
  122. HRESULT hr;
  123. _IWmiObject* pOldInstance = 0;
  124. CMyRelMe<_IWmiObject*> relMe(pOldInstance);
  125. _IWmiObject* pNewInstance = 0;
  126. CMyRelMe<_IWmiObject*> relMe2(pNewInstance);
  127. hr = pOldParentClass->Merge(WMIOBJECT_MERGE_FLAG_INSTANCE, dwSize, pObjectBlob, &pOldInstance);
  128. if (FAILED(hr))
  129. {
  130. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Unable to merge old instance (i); HRESULT = %#lx", hr);
  131. LogMessage(MSG_ERROR, szMsg);
  132. throw FAILURE_CANNOT_MERGE_INSTANCE;
  133. }
  134. if (pOldInstance == 0)
  135. {
  136. throw FAILURE_OUT_OF_MEMORY;
  137. }
  138. relMe.Set(pOldInstance);
  139. // put the new instance into the repository
  140. hr = pNamespace->PutInstance(pOldInstance, WBEM_FLAG_CREATE_OR_UPDATE, NULL, NULL);
  141. if (FAILED(hr))
  142. {
  143. // Original put failed, so we will try to upgrade the instance and retry the put
  144. // upgrade to new Whistler instance
  145. hr = pOldInstance->Upgrade(pNewParentClass, 0L, &pNewInstance);
  146. if (FAILED(hr))
  147. {
  148. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Unable to upgrade to new instance (i); HRESULT = %#lx", hr);
  149. LogMessage(MSG_ERROR, szMsg);
  150. throw FAILURE_CANNOT_UPGRADE_INSTANCE;
  151. }
  152. if (pNewInstance == 0)
  153. {
  154. throw FAILURE_OUT_OF_MEMORY;
  155. }
  156. relMe2.Set(pNewInstance);
  157. hr = pNamespace->PutInstance(pNewInstance, WBEM_FLAG_CREATE_OR_UPDATE, NULL, NULL);
  158. if ( FAILED(hr))
  159. {
  160. if (!CheckOldSecurityClass(pszParentClass))
  161. {
  162. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to create instance %S.%d in repository. (i); HRESULT = %#lx", pszParentClass, dwKey, hr);
  163. LogMessage(MSG_ERROR, szMsg);
  164. throw FAILURE_CANNOT_CREATE_INSTANCE;
  165. }
  166. else
  167. {
  168. // This is an old Win9x security class, but it can't be put yet because the win9x users haven't been migrated at this point in setup.
  169. // Instead, write it out to the win9x security blob file so it can be processed later after setup is completed
  170. if (!AppendWin9xBlobFile(wszFullPath, pszParentClass, pNewInstance))
  171. {
  172. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Unable to write Win9x security class to file for instance %S.%d", pszParentClass, dwKey);
  173. LogMessage(MSG_ERROR, szMsg);
  174. }
  175. }
  176. }
  177. }
  178. }
  179. void CRepImporter::DecodeInstanceString(IWbemServices* pNamespace, const wchar_t *wszFullPath, const wchar_t *pszParentClass, _IWmiObject* pOldParentClass, _IWmiObject *pNewParentClass)
  180. {
  181. char szMsg[MAX_MSG_TEXT_LENGTH];
  182. //Read the key and object size
  183. DWORD dwKeySize;
  184. DWORD dwSize = 0;
  185. if ((ReadFile(m_hFile, &dwKeySize, 4, &dwSize, NULL) == 0) || (dwSize != 4))
  186. {
  187. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve instance key size for class %S. (s)", pszParentClass);
  188. LogMessage(MSG_ERROR, szMsg);
  189. throw FAILURE_READ;
  190. }
  191. wchar_t *wszKey = new wchar_t[dwKeySize];
  192. if (wszKey == NULL)
  193. {
  194. throw FAILURE_OUT_OF_MEMORY;
  195. }
  196. CVectorDeleteMe<wchar_t> delMe(wszKey);
  197. if ((ReadFile(m_hFile, wszKey, dwKeySize, &dwSize, NULL) == 0) || (dwSize != dwKeySize))
  198. {
  199. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve instance key for class %S. (s)", pszParentClass);
  200. LogMessage(MSG_ERROR, szMsg);
  201. throw FAILURE_READ;
  202. }
  203. DWORD dwBlobSize;
  204. if ((ReadFile(m_hFile, &dwBlobSize, 4, &dwSize, NULL) == 0) || (dwSize != 4))
  205. {
  206. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve instance object size for %S.%S from import file. (s)", pszParentClass, wszKey);
  207. LogMessage(MSG_ERROR, szMsg);
  208. throw FAILURE_READ;
  209. }
  210. char *pObjectBlob = new char[dwBlobSize];
  211. if (pObjectBlob == NULL)
  212. {
  213. throw FAILURE_OUT_OF_MEMORY;
  214. }
  215. CVectorDeleteMe<char> delMe2(pObjectBlob);
  216. //Read the blob
  217. if ((ReadFile(m_hFile, pObjectBlob, dwBlobSize, &dwSize, NULL) == 0) || (dwSize != dwBlobSize))
  218. {
  219. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve instance %S.%S from import file. (s)", pszParentClass, wszKey);
  220. LogMessage(MSG_ERROR, szMsg);
  221. throw FAILURE_READ;
  222. }
  223. if (pNewParentClass == (_IWmiObject*)-1)
  224. {
  225. //We are working with a class which has problems... we need to ignore this instance...
  226. return;
  227. }
  228. // create old Nova-style instance
  229. HRESULT hr;
  230. _IWmiObject* pOldInstance = 0;
  231. CMyRelMe<_IWmiObject*> relMe(pOldInstance);
  232. _IWmiObject* pNewInstance = 0;
  233. CMyRelMe<_IWmiObject*> relMe2(pNewInstance);
  234. hr = pOldParentClass->Merge(WMIOBJECT_MERGE_FLAG_INSTANCE, dwSize, pObjectBlob, &pOldInstance);
  235. if (FAILED(hr))
  236. {
  237. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Unable to merge old instance (s); HRESULT = %#lx", hr);
  238. LogMessage(MSG_ERROR, szMsg);
  239. throw FAILURE_CANNOT_MERGE_INSTANCE;
  240. }
  241. if (pOldInstance == 0)
  242. {
  243. throw FAILURE_OUT_OF_MEMORY;
  244. }
  245. relMe.Set(pOldInstance);
  246. // put the instance into the repository
  247. // if this fails, upgrade and retry
  248. hr = pNamespace->PutInstance(pOldInstance, WBEM_FLAG_CREATE_OR_UPDATE, NULL, NULL);
  249. if (FAILED(hr))
  250. {
  251. // upgrade to new Whistler instance
  252. hr = pOldInstance->Upgrade(pNewParentClass, 0L, &pNewInstance);
  253. if (FAILED(hr))
  254. {
  255. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Unable to upgrade to new instance (s); HRESULT = %#lx", hr);
  256. LogMessage(MSG_ERROR, szMsg);
  257. throw FAILURE_CANNOT_UPGRADE_INSTANCE;
  258. }
  259. if (pNewInstance == 0)
  260. {
  261. throw FAILURE_OUT_OF_MEMORY;
  262. }
  263. relMe2.Set(pNewInstance);
  264. hr = pNamespace->PutInstance(pNewInstance, WBEM_FLAG_CREATE_OR_UPDATE, NULL, NULL);
  265. if ( FAILED(hr))
  266. {
  267. if (!CheckOldSecurityClass(pszParentClass))
  268. {
  269. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to create instance %S.%S in repository. (s); HRESULT = %#lx", pszParentClass, wszKey, hr);
  270. LogMessage(MSG_ERROR, szMsg);
  271. throw FAILURE_CANNOT_CREATE_INSTANCE;
  272. }
  273. else
  274. {
  275. // This is an old Win9x security class, but it can't be put yet because the win9x users haven't been migrated at this point in setup.
  276. // Instead, write it out to the win9x security blob file so it can be processed later after setup is completed
  277. if (!AppendWin9xBlobFile(wszFullPath, pszParentClass, pNewInstance))
  278. {
  279. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Unable to write Win9x security class to file for instance %S.%S", pszParentClass, wszKey);
  280. LogMessage(MSG_ERROR, szMsg);
  281. }
  282. }
  283. }
  284. }
  285. }
  286. void CRepImporter::DecodeClass(IWbemServices* pNamespace, const wchar_t *wszFullPath, const wchar_t *wszParentClass, _IWmiObject* pOldParentClass, _IWmiObject *pNewParentClass)
  287. {
  288. char szMsg[MAX_MSG_TEXT_LENGTH];
  289. //Read our current class from the file...
  290. HRESULT hr;
  291. DWORD dwClassSize = 0;
  292. DWORD dwSize = 0;
  293. _IWmiObject* pOldClass = 0;
  294. CMyRelMe<_IWmiObject*> relMe(pOldClass);
  295. _IWmiObject* pNewClass = 0;
  296. CMyRelMe<_IWmiObject*> relMe2(pNewClass);
  297. if ((ReadFile(m_hFile, &dwClassSize, 4, &dwSize, NULL) == 0) || (dwSize != 4))
  298. {
  299. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve class size for class with parent class %S.", wszParentClass);
  300. LogMessage(MSG_ERROR, szMsg);
  301. throw FAILURE_READ;
  302. }
  303. wchar_t *wszClass = new wchar_t[dwClassSize];
  304. if (wszClass == NULL)
  305. {
  306. throw FAILURE_OUT_OF_MEMORY;
  307. }
  308. CVectorDeleteMe<wchar_t> delMe(wszClass);
  309. if ((ReadFile(m_hFile, wszClass, dwClassSize, &dwSize, NULL) == 0) || (dwSize != dwClassSize))
  310. {
  311. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve class information for class with parent class %S.", wszParentClass);
  312. LogMessage(MSG_ERROR, szMsg);
  313. throw FAILURE_READ;
  314. }
  315. //Now we have the class blob...
  316. if ((ReadFile(m_hFile, &dwClassSize, 4, &dwSize, NULL) == 0) || (dwSize != 4))
  317. {
  318. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve class size for class %S.", wszClass);
  319. LogMessage(MSG_ERROR, szMsg);
  320. throw FAILURE_READ;
  321. }
  322. if (dwClassSize)
  323. {
  324. char *pClassBlob = new char[dwClassSize];
  325. if (pClassBlob == NULL)
  326. {
  327. throw FAILURE_OUT_OF_MEMORY;
  328. }
  329. CVectorDeleteMe<char> delMe2(pClassBlob);
  330. if ((ReadFile(m_hFile, pClassBlob, dwClassSize, &dwSize, NULL) == 0) || (dwSize != dwClassSize))
  331. {
  332. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve class information for class %S.", wszClass);
  333. LogMessage(MSG_ERROR, szMsg);
  334. throw FAILURE_READ;
  335. }
  336. if (pNewParentClass == (_IWmiObject*)-1)
  337. {
  338. // parent class was bad, so don't process this class
  339. pNewClass = (_IWmiObject*)-1;
  340. }
  341. else
  342. {
  343. // create old Nova-style class
  344. hr = pOldParentClass->Merge(WMIOBJECT_MERGE_FLAG_CLASS, dwSize, pClassBlob, &pOldClass);
  345. if (FAILED(hr))
  346. {
  347. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Unable to merge old class; HRESULT = %#lx", hr);
  348. LogMessage(MSG_ERROR, szMsg);
  349. throw FAILURE_CANNOT_MERGE_CLASS;
  350. }
  351. if (pOldClass == 0)
  352. {
  353. throw FAILURE_OUT_OF_MEMORY;
  354. }
  355. relMe.Set(pOldClass);
  356. //If the class is a system class then we do not write it... it may have changed for starters,
  357. //but also we create all system classes when a new database/namespace is created...
  358. if (_wcsnicmp(wszClass, L"__", 2) != 0)
  359. {
  360. // put the class into the repository
  361. // if this fails, upgrade it and retry
  362. hr = pNamespace->PutClass(pOldClass, WBEM_FLAG_CREATE_OR_UPDATE | WBEM_FLAG_UPDATE_FORCE_MODE, NULL, NULL);
  363. if (FAILED(hr))
  364. {
  365. // upgrade to new Whistler class (note: pNewParentClass will be NULL for base classes)
  366. hr = pOldClass->Upgrade(pNewParentClass, 0L, &pNewClass);
  367. if (FAILED(hr))
  368. {
  369. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Unable to upgrade to new class; HRESULT = %#lx", hr);
  370. LogMessage(MSG_ERROR, szMsg);
  371. throw FAILURE_CANNOT_UPGRADE_CLASS;
  372. }
  373. if (pNewClass == 0)
  374. {
  375. throw FAILURE_OUT_OF_MEMORY;
  376. }
  377. relMe2.Set(pNewClass);
  378. // retry the put
  379. hr = pNamespace->PutClass(pNewClass, WBEM_FLAG_CREATE_OR_UPDATE | WBEM_FLAG_UPDATE_FORCE_MODE, NULL, NULL);
  380. if ( FAILED(hr) )
  381. {
  382. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to create class for class %S; HRESULT = %#lx", wszClass, hr);
  383. LogMessage(MSG_ERROR, szMsg);
  384. throw FAILURE_CANNOT_CREATE_CLASS;
  385. }
  386. }
  387. }
  388. // We need to re-get the class as class comparisons may fail to see
  389. // that this class is in fact the same as the one in the database!
  390. if ( NULL != pNewClass )
  391. {
  392. pNewClass->Release();
  393. pNewClass = 0;
  394. relMe2.Set(NULL);
  395. }
  396. BSTR bstrClassName = SysAllocString(wszClass);
  397. if (!bstrClassName)
  398. throw FAILURE_OUT_OF_MEMORY;
  399. CSysFreeMe fm(bstrClassName);
  400. hr = pNamespace->GetObject(bstrClassName, 0L, NULL, (IWbemClassObject**) &pNewClass, NULL);
  401. if (FAILED(hr))
  402. {
  403. if (_wcsnicmp(wszClass, L"__", 2) != 0)
  404. {
  405. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve class %S from the repository after creating it; HRESULT = %#lx", wszClass, hr);
  406. LogMessage(MSG_ERROR, szMsg);
  407. throw FAILURE_CANNOT_GET_PARENT_CLASS;
  408. }
  409. else
  410. {
  411. if (_wcsicmp(wszClass, L"__CIMOMIdentification") != 0) // we don't want to warn about failures to retrieve this class
  412. {
  413. // couldn't get the system class
  414. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve system class %S from the repository; HRESULT = %#lx", wszClass, hr);
  415. LogMessage(MSG_WARNING, szMsg);
  416. }
  417. // set pointer to -1 and continue processing file
  418. // old comment said: If this does not exist then it cannot be important!
  419. pNewClass = (_IWmiObject*)-1;
  420. }
  421. }
  422. else
  423. relMe2.Set(pNewClass);
  424. }
  425. }
  426. else
  427. {
  428. // This is a situation where we have a class in the export file,
  429. // but the size is zero, so we just get the class from the repository.
  430. // ***** So what do we do about pOldClass? At this point it is NULL. *****
  431. // ***** We need the old class to be able to upgrade child classes properly. *****
  432. if (pNewParentClass == (_IWmiObject*)-1)
  433. {
  434. // parent class was bad, so don't process this class
  435. pNewClass = (_IWmiObject*)-1;
  436. }
  437. else
  438. {
  439. // get the class from the repository
  440. BSTR bstrClassName = SysAllocString(wszClass);
  441. if (!bstrClassName)
  442. throw FAILURE_OUT_OF_MEMORY;
  443. CSysFreeMe fm(bstrClassName);
  444. hr = pNamespace->GetObject(bstrClassName, 0L, NULL, (IWbemClassObject**) &pNewClass, NULL);
  445. if (FAILED(hr))
  446. {
  447. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve class %S from the repository; HRESULT = %#lx", wszClass, hr);
  448. LogMessage(MSG_ERROR, szMsg);
  449. throw FAILURE_CANNOT_GET_PARENT_CLASS;
  450. }
  451. relMe2.Set(pNewClass);
  452. }
  453. }
  454. //Now we iterate through all child classes and instances until we get an end of class marker...
  455. while (1)
  456. {
  457. DWORD dwType = 0;
  458. if ((ReadFile(m_hFile, &dwType, 4, &dwSize, NULL) == 0) || (dwSize != 4))
  459. {
  460. LogMessage(MSG_ERROR, "Failed to read next block type from import file.");
  461. throw FAILURE_READ;
  462. }
  463. if (dwType == REP_EXPORT_CLASS_TAG)
  464. {
  465. DecodeClass(pNamespace, wszFullPath, wszClass, pOldClass, pNewClass);
  466. }
  467. else if (dwType == REP_EXPORT_INST_INT_TAG)
  468. {
  469. DecodeInstanceInt(pNamespace, wszFullPath, wszClass, pOldClass, pNewClass);
  470. }
  471. else if (dwType == REP_EXPORT_INST_STR_TAG)
  472. {
  473. DecodeInstanceString(pNamespace, wszFullPath, wszClass, pOldClass, pNewClass);
  474. }
  475. else if (dwType == REP_EXPORT_CLASS_END_TAG)
  476. {
  477. //That's the end of this class...
  478. DecodeTrailer();
  479. break;
  480. }
  481. else
  482. {
  483. LogMessage(MSG_ERROR, "Next block type in import file is invalid.");
  484. throw FAILURE_INVALID_TYPE;
  485. }
  486. }
  487. }
  488. void CRepImporter::DecodeNamespace(IWbemServices* pParentNamespace, const wchar_t *wszParentNamespace)
  489. {
  490. char szMsg[MAX_MSG_TEXT_LENGTH];
  491. //Read our current namespace from the file...
  492. DWORD dwNsSize = 0;
  493. DWORD dwSize = 0;
  494. if ((ReadFile(m_hFile, &dwNsSize, 4, &dwSize, NULL) == 0) || (dwSize != 4))
  495. {
  496. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve a namespace whose parent namespace is %S.", wszParentNamespace);
  497. LogMessage(MSG_ERROR, szMsg);
  498. throw FAILURE_READ;
  499. }
  500. wchar_t *wszNs = new wchar_t[dwNsSize];
  501. if (wszNs == NULL)
  502. {
  503. throw FAILURE_OUT_OF_MEMORY;
  504. }
  505. CVectorDeleteMe<wchar_t> delMe(wszNs);
  506. if ((ReadFile(m_hFile, wszNs, dwNsSize, &dwSize, NULL) == 0) || (dwSize != dwNsSize))
  507. {
  508. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve a namespace whose parent namespace is %S.", wszParentNamespace);
  509. LogMessage(MSG_ERROR, szMsg);
  510. throw FAILURE_READ;
  511. }
  512. if (wbem_wcsicmp(wszNs, L"security") == 0)
  513. {
  514. m_bSecurityMode = true;
  515. }
  516. wchar_t *wszFullPath = new wchar_t[wcslen(wszParentNamespace) + 1 + wcslen(wszNs) + 1];
  517. if (wszFullPath == NULL)
  518. {
  519. throw FAILURE_OUT_OF_MEMORY;
  520. }
  521. CVectorDeleteMe<wchar_t> delMe2(wszFullPath);
  522. StringCchCopyW(wszFullPath, MAX_MSG_TEXT_LENGTH, wszParentNamespace);
  523. if (wcslen(wszParentNamespace) != 0)
  524. {
  525. StringCchCatW(wszFullPath, MAX_MSG_TEXT_LENGTH, L"\\");
  526. }
  527. StringCchCatW(wszFullPath, MAX_MSG_TEXT_LENGTH, wszNs);
  528. // open the namespace
  529. IWbemServices* pNamespace = NULL;
  530. CMyRelMe<IWbemServices*> relMe2(pNamespace);
  531. HRESULT hr;
  532. if (pParentNamespace)
  533. {
  534. BSTR bstrNamespace = SysAllocString(wszNs);
  535. if (!bstrNamespace)
  536. throw FAILURE_OUT_OF_MEMORY;
  537. CSysFreeMe fm(bstrNamespace);
  538. hr = pParentNamespace->OpenNamespace(bstrNamespace, WBEM_FLAG_CONNECT_REPOSITORY_ONLY, NULL, &pNamespace, NULL);
  539. if (FAILED(hr))
  540. {
  541. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve namespace %S from the repository; HRESULT = %#lx", wszFullPath, hr);
  542. LogMessage(MSG_ERROR, szMsg);
  543. throw FAILURE_CANNOT_FIND_NAMESPACE;
  544. }
  545. }
  546. else // special start case for root
  547. {
  548. IWbemLocator* pLocator = NULL;
  549. CMyRelMe<IWbemLocator*> relMe(pLocator);
  550. hr = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_ALL, IID_IWbemLocator, (void**) &pLocator);
  551. if(FAILED(hr))
  552. {
  553. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to create instance of IWbemLocator; HRESULT = %#lx", hr);
  554. LogMessage(MSG_ERROR, szMsg);
  555. throw FAILURE_CANNOT_CREATE_IWBEMLOCATOR;
  556. }
  557. else
  558. {
  559. relMe.Set(pLocator);
  560. BSTR bstrNamespace = SysAllocString(L"root");
  561. if (!bstrNamespace)
  562. throw FAILURE_OUT_OF_MEMORY;
  563. CSysFreeMe fm(bstrNamespace);
  564. hr = pLocator->ConnectServer(bstrNamespace, NULL, NULL, NULL, WBEM_FLAG_CONNECT_REPOSITORY_ONLY, NULL, NULL, &pNamespace);
  565. if (FAILED(hr))
  566. {
  567. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to connect server; HRESULT = %#lx", hr);
  568. LogMessage(MSG_ERROR, szMsg);
  569. throw FAILURE_CANNOT_CONNECT_SERVER;
  570. }
  571. }
  572. }
  573. if (pNamespace == NULL)
  574. {
  575. throw FAILURE_OUT_OF_MEMORY;
  576. }
  577. relMe2.Set(pNamespace);
  578. //Get and set the namespace security...
  579. DWORD dwBuffer[2];
  580. if ((ReadFile(m_hFile, dwBuffer, 8, &dwSize, NULL) == 0) || (dwSize != 8))
  581. {
  582. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve a namespace security header for namespace %S.", wszFullPath);
  583. LogMessage(MSG_ERROR, szMsg);
  584. throw FAILURE_READ;
  585. }
  586. if (dwBuffer[0] != REP_EXPORT_NAMESPACE_SEC_TAG)
  587. {
  588. LogMessage(MSG_ERROR, "Expecting a namespace security blob and did not find it.");
  589. throw FAILURE_INVALID_TYPE;
  590. }
  591. if (dwBuffer[1] != 0)
  592. {
  593. char *pNsSecurity = new char[dwBuffer[1]];
  594. CVectorDeleteMe<char> delMe3(pNsSecurity);
  595. if (pNsSecurity == NULL)
  596. {
  597. throw FAILURE_OUT_OF_MEMORY;
  598. }
  599. if ((ReadFile(m_hFile, pNsSecurity, dwBuffer[1], &dwSize, NULL) == 0) || (dwSize != dwBuffer[1]))
  600. {
  601. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to retrieve a namespace security blob for namespace %S.", wszFullPath);
  602. LogMessage(MSG_ERROR, szMsg);
  603. throw FAILURE_READ;
  604. }
  605. // we have the security blob, now set the SECURITY_DESCRIPTOR property in the namespace
  606. DecodeNamespaceSecurity(pNamespace, pParentNamespace, pNsSecurity, dwBuffer[1], wszFullPath);
  607. }
  608. // create empty Nova-style class object for use in decoding base classes
  609. _IWmiObjectFactory* pObjFactory = NULL;
  610. CMyRelMe<_IWmiObjectFactory*> relMe3(pObjFactory);
  611. hr = CoCreateInstance(CLSID__WmiObjectFactory, NULL, CLSCTX_ALL, IID__IWmiObjectFactory, (void**) &pObjFactory);
  612. if(FAILED(hr))
  613. {
  614. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to create instance of IWmiObjectFactory; HRESULT = %#lx", hr);
  615. LogMessage(MSG_ERROR, szMsg);
  616. throw FAILURE_CANNOT_CREATE_OBJECTFACTORY;
  617. }
  618. if (pObjFactory == NULL)
  619. {
  620. throw FAILURE_OUT_OF_MEMORY;
  621. }
  622. relMe3.Set(pObjFactory);
  623. _IWmiObject* pBaseObject = NULL;
  624. CMyRelMe<_IWmiObject*> relMe4(pBaseObject);
  625. hr = pObjFactory->Create(NULL, 0L, CLSID__WbemEmptyClassObject, IID__IWmiObject, (void**) &pBaseObject);
  626. if(FAILED(hr))
  627. {
  628. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to create instance of IWmiObject; HRESULT = %#lx", hr);
  629. LogMessage(MSG_ERROR, szMsg);
  630. throw FAILURE_CANNOT_CREATE_IWMIOBJECT;
  631. }
  632. if (pBaseObject == NULL)
  633. {
  634. throw FAILURE_OUT_OF_MEMORY;
  635. }
  636. relMe4.Set(pBaseObject);
  637. //Now we need to iterate through the next set of blocks of namespace or class
  638. //until we get to an end of NS marker
  639. while (1)
  640. {
  641. DWORD dwType = 0;
  642. if ((ReadFile(m_hFile, &dwType, 4, &dwSize, NULL) == 0) || (dwSize != 4))
  643. {
  644. LogMessage(MSG_ERROR, "Failed to read next block type (namespace/class) from import file.");
  645. throw FAILURE_READ;
  646. }
  647. if (dwType == REP_EXPORT_NAMESPACE_TAG)
  648. {
  649. DecodeNamespace(pNamespace, wszFullPath);
  650. }
  651. else if (dwType == REP_EXPORT_CLASS_TAG)
  652. {
  653. DecodeClass(pNamespace, wszFullPath, L"", pBaseObject, NULL);
  654. }
  655. else if (dwType == REP_EXPORT_NAMESPACE_END_TAG)
  656. {
  657. //That's the end of this namespace...
  658. DecodeTrailer();
  659. break;
  660. }
  661. else
  662. {
  663. LogMessage(MSG_ERROR, "Next block type (namespace/class) in import file is invalid.");
  664. throw FAILURE_INVALID_TYPE;
  665. }
  666. }
  667. m_bSecurityMode = false;
  668. }
  669. void CRepImporter::DecodeNamespaceSecurity(IWbemServices* pNamespace, IWbemServices* pParentNamespace, const char* pNsSecurity, DWORD dwSize, const wchar_t* wszFullPath)
  670. {
  671. char szMsg[MAX_MSG_TEXT_LENGTH];
  672. // determine whether we have an old Win9x pseudo-blob
  673. DWORD dwStoredAsNT = 0;
  674. if (pNsSecurity)
  675. {
  676. DWORD* pdwData = (DWORD*)pNsSecurity;
  677. DWORD dwBlobSize = *pdwData;
  678. pdwData++;
  679. DWORD dwVersion = *pdwData;
  680. if(dwVersion != 1 || dwBlobSize == 0 || dwBlobSize > 64000)
  681. {
  682. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Invalid namespace security blob header for namespace %S.", wszFullPath);
  683. LogMessage(MSG_ERROR, szMsg);
  684. return;
  685. }
  686. pdwData++;
  687. dwStoredAsNT = *pdwData;
  688. }
  689. if (!dwStoredAsNT)
  690. {
  691. // Do not process Win9x security blobs, because Win9x users haven't been migrated over yet at this point in setup.
  692. // Instead, write them out to a file to be processed after setup is complete.
  693. if (!AppendWin9xBlobFile(wszFullPath, dwSize, pNsSecurity))
  694. {
  695. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Unable to write Win9x security blob to file for namespace %S.", wszFullPath);
  696. LogMessage(MSG_ERROR, szMsg);
  697. }
  698. return;
  699. }
  700. // now transform the old security blob that consisted of a header and array of ACE's
  701. // into a proper Security Descriptor that can be stored in the property
  702. CNtSecurityDescriptor mmfNsSD;
  703. if (!TransformBlobToSD(pParentNamespace, pNsSecurity, dwStoredAsNT, mmfNsSD))
  704. {
  705. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to convert security blob to SD for namespace %S.", wszFullPath);
  706. LogMessage(MSG_ERROR, szMsg);
  707. return;
  708. }
  709. // now set the security
  710. if (!SetNamespaceSecurity(pNamespace, mmfNsSD))
  711. {
  712. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to set namespace security for namespace %S.", wszFullPath);
  713. LogMessage(MSG_ERROR, szMsg);
  714. return;
  715. }
  716. }
  717. void CRepImporter::Decode()
  718. {
  719. char pszBuff[7];
  720. DWORD dwSize = 0;
  721. if ((ReadFile(m_hFile, pszBuff, 7, &dwSize, NULL) == 0) || (dwSize != 7))
  722. {
  723. LogMessage(MSG_ERROR, "Failed to retrieve the import file header information.");
  724. throw FAILURE_READ;
  725. }
  726. if (strncmp(pszBuff, REP_EXPORT_FILE_START_TAG, 7) != 0)
  727. {
  728. LogMessage(MSG_ERROR, "The import file specified is not an import file.");
  729. throw FAILURE_INVALID_FILE;
  730. }
  731. //We should have a tag for a namespace...
  732. DWORD dwType = 0;
  733. if ((ReadFile(m_hFile, &dwType, 4, &dwSize, NULL) == 0) || (dwSize != 4))
  734. {
  735. LogMessage(MSG_ERROR, "Failed to read next block type from import file.");
  736. throw FAILURE_READ;
  737. }
  738. if (dwType != REP_EXPORT_NAMESPACE_TAG)
  739. {
  740. LogMessage(MSG_ERROR, "Next block type in import file is invalid.");
  741. throw FAILURE_INVALID_TYPE;
  742. }
  743. DecodeNamespace(NULL, L"");
  744. // if we opened a Win9x security blob upgrade file, close it
  745. CloseWin9xBlobFile();
  746. // force ROOT\DEFAULT and ROOT\SECURITY namespaces to inherit their inheritable security settings
  747. ForceInherit();
  748. //Now we should have the file trailer
  749. if ((ReadFile(m_hFile, &dwType, 4, &dwSize, NULL) == 0) || (dwSize != 4))
  750. {
  751. LogMessage(MSG_ERROR, "Failed to read next block type (trailer) from import file.");
  752. throw FAILURE_READ;
  753. }
  754. if (dwType != REP_EXPORT_FILE_END_TAG)
  755. {
  756. LogMessage(MSG_ERROR, "Next block type (trailer) in import file is invalid.");
  757. throw FAILURE_INVALID_TYPE;
  758. }
  759. DecodeTrailer();
  760. }
  761. int CRepImporter::ImportRepository(const TCHAR *pszFromFile)
  762. {
  763. LogMessage(MSG_INFO, "Beginning ImportRepository");
  764. int nRet = no_error;
  765. m_hFile = CreateFile(pszFromFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  766. if (m_hFile != INVALID_HANDLE_VALUE)
  767. {
  768. try
  769. {
  770. Decode();
  771. }
  772. catch (CX_MemoryException)
  773. {
  774. LogMessage(MSG_ERROR, "Memory Exception.");
  775. nRet = out_of_memory;
  776. }
  777. catch (...)
  778. {
  779. LogMessage(MSG_ERROR, "Traversal of import file failed.");
  780. nRet = critical_error;
  781. }
  782. CloseHandle(m_hFile);
  783. }
  784. else
  785. {
  786. char szMsg[MAX_MSG_TEXT_LENGTH];
  787. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Could not open the import file \"%s\" for reading.", pszFromFile);
  788. LogMessage(MSG_ERROR, szMsg);
  789. nRet = critical_error;
  790. }
  791. if (nRet == no_error)
  792. LogMessage(MSG_INFO, "ImportRepository completed successfully.");
  793. else
  794. LogMessage(MSG_ERROR, "ImportRepository failed to complete.");
  795. return nRet;
  796. }
  797. //***************************************************************************
  798. //***************************************************************************
  799. //
  800. // Helper functions for DecodeNamespaceSecurity
  801. //
  802. //***************************************************************************
  803. //***************************************************************************
  804. bool CRepImporter::TransformBlobToSD(IWbemServices* pParentNamespace, const char* pNsSecurity, DWORD dwStoredAsNT, CNtSecurityDescriptor& mmfNsSD)
  805. {
  806. // now transform the old security blob that consisted of a header and array of ACE's
  807. // into a proper Security Descriptor that can be stored in the property
  808. // build up an ACL from our blob, if we have one
  809. CNtAcl acl;
  810. if (pNsSecurity)
  811. {
  812. DWORD* pdwData = (DWORD*) pNsSecurity;
  813. pdwData += 3;
  814. int iAceCount = (int)*pdwData;
  815. pdwData += 2;
  816. BYTE* pAceData = (BYTE*)pdwData;
  817. PGENERIC_ACE pAce = NULL;
  818. for (int iCnt = 0; iCnt < iAceCount; iCnt++)
  819. {
  820. pAce = (PGENERIC_ACE)pAceData;
  821. if (!pAce)
  822. {
  823. LogMessage(MSG_ERROR, "Failed to access GENERIC_ACE within security blob");
  824. return false;
  825. }
  826. CNtAce ace(pAce);
  827. if(ace.GetStatus() != 0)
  828. {
  829. LogMessage(MSG_ERROR, "Failed to construct CNtAce from GENERIC_ACE");
  830. return false;
  831. }
  832. acl.AddAce(&ace);
  833. if (acl.GetStatus() != 0)
  834. {
  835. LogMessage(MSG_ERROR, "Failed to add ACE to ACL");
  836. return false;
  837. }
  838. pAceData += ace.GetSize();
  839. }
  840. }
  841. // a real SD was constructed and passed in by reference, now set it up properly
  842. SetOwnerAndGroup(mmfNsSD);
  843. mmfNsSD.SetDacl(&acl);
  844. if (mmfNsSD.GetStatus() != 0)
  845. {
  846. LogMessage(MSG_ERROR, "Failed to convert namespace security blob to SD");
  847. return false;
  848. }
  849. // add in the parent's inheritable aces, if this is not ROOT
  850. if (pParentNamespace)
  851. {
  852. if (!GetParentsInheritableAces(pParentNamespace, mmfNsSD))
  853. {
  854. LogMessage(MSG_ERROR, "Failed to inherit parent's inheritable ACE's");
  855. return false;
  856. }
  857. }
  858. return true;
  859. }
  860. bool CRepImporter::SetNamespaceSecurity(IWbemServices* pNamespace, CNtSecurityDescriptor& mmfNsSD)
  861. {
  862. // now set the security
  863. if (!pNamespace)
  864. return false;
  865. IWbemClassObject* pThisNamespace = NULL;
  866. BSTR bstrNamespace = SysAllocString(L"__thisnamespace=@");
  867. if (!bstrNamespace)
  868. throw FAILURE_OUT_OF_MEMORY;
  869. CSysFreeMe fm(bstrNamespace);
  870. HRESULT hr = pNamespace->GetObject(bstrNamespace, 0, NULL, &pThisNamespace, NULL);
  871. if (FAILED(hr))
  872. {
  873. LogMessage(MSG_ERROR, "Failed to get singleton namespace object");
  874. return false;
  875. }
  876. CMyRelMe<IWbemClassObject*> relMe(pThisNamespace);
  877. //
  878. // Check to see if namespace contains any ALLOW or DENY ACEs for NETWORK/LOCAL SERVICE
  879. // If they do exist, we leave them as is, otherwise we want to add them to the SD.
  880. //
  881. if ( CheckNetworkLocalService ( mmfNsSD ) == false )
  882. {
  883. LogMessage(MSG_ERROR, "Failed to add NETWORK/LOCAL service ACEs");
  884. return false;
  885. }
  886. SAFEARRAY FAR* psa;
  887. SAFEARRAYBOUND rgsabound[1];
  888. rgsabound[0].lLbound = 0;
  889. rgsabound[0].cElements = mmfNsSD.GetSize();
  890. psa = SafeArrayCreate( VT_UI1, 1 , rgsabound );
  891. if (!psa)
  892. throw FAILURE_OUT_OF_MEMORY;
  893. char* pData = NULL;
  894. hr = SafeArrayAccessData(psa, (void HUGEP* FAR*)&pData);
  895. if (FAILED(hr))
  896. {
  897. LogMessage(MSG_ERROR, "Failed SafeArrayAccessData");
  898. return false;
  899. }
  900. memcpy(pData, mmfNsSD.GetPtr(), mmfNsSD.GetSize());
  901. hr = SafeArrayUnaccessData(psa);
  902. if (FAILED(hr))
  903. {
  904. LogMessage(MSG_ERROR, "Failed SafeArrayUnaccessData");
  905. return false;
  906. }
  907. pData = NULL;
  908. VARIANT var;
  909. var.vt = VT_UI1|VT_ARRAY;
  910. var.parray = psa;
  911. hr = pThisNamespace->Put(L"SECURITY_DESCRIPTOR" , 0, &var, 0);
  912. VariantClear(&var);
  913. if (FAILED(hr))
  914. {
  915. if (hr == WBEM_E_OUT_OF_MEMORY)
  916. throw FAILURE_OUT_OF_MEMORY;
  917. else
  918. {
  919. LogMessage(MSG_ERROR, "Failed to put SECURITY_DESCRIPTOR property");
  920. return false;
  921. }
  922. }
  923. hr = pNamespace->PutInstance(pThisNamespace, WBEM_FLAG_CREATE_OR_UPDATE, NULL, NULL);
  924. if (FAILED(hr))
  925. {
  926. if (hr == WBEM_E_OUT_OF_MEMORY)
  927. throw FAILURE_OUT_OF_MEMORY;
  928. else
  929. {
  930. LogMessage(MSG_ERROR, "Failed to put back singleton instance");
  931. return false;
  932. }
  933. }
  934. return true;
  935. }
  936. /*
  937. --------------------------------------------------------------------------
  938. |
  939. | Checks to see if the namespace had a previous ACE with NETWORK or LOCAL
  940. | service accounts. If so, it simply leaves them, otherwise, it adds a
  941. | ACE with default settings for these accounts. The default settings are:
  942. | WBEM_ENABLE | WBEM_METHOD_EXECUTE | WBEM_WRITE_PROVIDER
  943. | The characteristics of the ACE is irrelevant. Only SID comparison applies.
  944. |
  945. --------------------------------------------------------------------------
  946. */
  947. bool CRepImporter::CheckNetworkLocalService ( CNtSecurityDescriptor& mmfNsSD )
  948. {
  949. DWORD dwAccessMaskNetworkLocalService = WBEM_ENABLE | WBEM_METHOD_EXECUTE | WBEM_WRITE_PROVIDER ;
  950. PSID pRawSid = NULL ;
  951. SID_IDENTIFIER_AUTHORITY id = SECURITY_NT_AUTHORITY;
  952. BOOL bStatus = TRUE ;
  953. BYTE flags = 0 ;
  954. CNtAcl* pAcl = mmfNsSD.GetDacl ( ) ;
  955. CDeleteMe<CNtAcl> AclDelete ( pAcl ) ;
  956. //
  957. // Start with NETWORK_SERVICE account
  958. //
  959. if(AllocateAndInitializeSid( &id, 1,
  960. SECURITY_NETWORK_SERVICE_RID,0,0,0,0,0,0,0,&pRawSid))
  961. {
  962. CNtSid SidNetworkService (pRawSid);
  963. FreeSid(pRawSid);
  964. {
  965. CNtAce * pace = new CNtAce(dwAccessMaskNetworkLocalService,
  966. ACCESS_ALLOWED_ACE_TYPE,
  967. CONTAINER_INHERIT_ACE,
  968. SidNetworkService );
  969. if ( NULL == pace )
  970. {
  971. bStatus = FALSE ;
  972. }
  973. else
  974. {
  975. CDeleteMe<CNtAce> dm(pace);
  976. pAcl->AddAce(pace);
  977. }
  978. }
  979. }
  980. //
  981. // Next, LOCAL_SERVICE account
  982. //
  983. if ( bStatus == TRUE )
  984. {
  985. pRawSid = NULL ;
  986. if(AllocateAndInitializeSid( &id, 1,
  987. SECURITY_LOCAL_SERVICE_RID,0,0,0,0,0,0,0,&pRawSid))
  988. {
  989. CNtSid SidLocalService (pRawSid);
  990. FreeSid(pRawSid);
  991. {
  992. CNtAce * pace = new CNtAce(dwAccessMaskNetworkLocalService,
  993. ACCESS_ALLOWED_ACE_TYPE,
  994. CONTAINER_INHERIT_ACE,
  995. SidLocalService );
  996. if ( NULL == pace )
  997. {
  998. bStatus = FALSE ;
  999. }
  1000. else
  1001. {
  1002. CDeleteMe<CNtAce> dm(pace);
  1003. pAcl->AddAce(pace);
  1004. }
  1005. }
  1006. }
  1007. }
  1008. if ( bStatus == TRUE )
  1009. {
  1010. mmfNsSD.SetDacl ( pAcl ) ;
  1011. }
  1012. return bStatus ? true : false ;
  1013. }
  1014. bool CRepImporter::GetParentsInheritableAces(IWbemServices* pParentNamespace, CNtSecurityDescriptor &sd)
  1015. {
  1016. if (!pParentNamespace)
  1017. return false;
  1018. // Get the parent namespace's SD
  1019. CNtSecurityDescriptor sdParent;
  1020. if (!GetSDFromNamespace(pParentNamespace, sdParent))
  1021. return false;
  1022. // strip out the inherited aces so we have a consistent SD
  1023. if (!StripOutInheritedAces(sd))
  1024. return false;
  1025. // Go through the parents dacl and add any inheritable aces to ours.
  1026. if (!CopyInheritAces(sd, sdParent))
  1027. return false;
  1028. return true;
  1029. }
  1030. bool CRepImporter::GetSDFromNamespace(IWbemServices* pNamespace, CNtSecurityDescriptor& sd)
  1031. {
  1032. if (!pNamespace)
  1033. return false;
  1034. // get the singleton object
  1035. IWbemClassObject* pThisNamespace = NULL;
  1036. BSTR bstrNamespace = SysAllocString(L"__thisnamespace=@");
  1037. if (!bstrNamespace)
  1038. throw FAILURE_OUT_OF_MEMORY;
  1039. CSysFreeMe fm(bstrNamespace);
  1040. HRESULT hr = pNamespace->GetObject(bstrNamespace, 0, NULL, &pThisNamespace, NULL);
  1041. if (FAILED(hr))
  1042. {
  1043. LogMessage(MSG_ERROR, "Failed to get singleton namespace object");
  1044. return false;
  1045. }
  1046. CMyRelMe<IWbemClassObject*> relMe(pThisNamespace);
  1047. // Get the security descriptor argument
  1048. VARIANT var;
  1049. VariantInit(&var);
  1050. hr = pThisNamespace->Get(L"SECURITY_DESCRIPTOR", 0, &var, NULL, NULL);
  1051. if (FAILED(hr))
  1052. {
  1053. VariantClear(&var);
  1054. LogMessage(MSG_ERROR, "Failed to get SECURITY_DESCRIPTOR property");
  1055. return false;
  1056. }
  1057. if(var.vt != (VT_ARRAY | VT_UI1))
  1058. {
  1059. VariantClear(&var);
  1060. LogMessage(MSG_ERROR, "Failed to get SECURITY_DESCRIPTOR property due to incorrect variant type");
  1061. return false;
  1062. }
  1063. SAFEARRAY* psa = var.parray;
  1064. PSECURITY_DESCRIPTOR pSD;
  1065. hr = SafeArrayAccessData(psa, (void HUGEP* FAR*)&pSD);
  1066. if (FAILED(hr))
  1067. {
  1068. VariantClear(&var);
  1069. LogMessage(MSG_ERROR, "GetSDFromNamespace failed SafeArrayAccessData");
  1070. return false;
  1071. }
  1072. BOOL bValid = IsValidSecurityDescriptor(pSD);
  1073. if (!bValid)
  1074. {
  1075. VariantClear(&var);
  1076. LogMessage(MSG_ERROR, "GetSDFromNamespace retrieved an invalid security descriptor");
  1077. return false;
  1078. }
  1079. CNtSecurityDescriptor sdNew(pSD);
  1080. // Check to make sure the owner and group is not NULL!!!!
  1081. CNtSid *pTmpSid = sdNew.GetOwner();
  1082. if (pTmpSid == NULL)
  1083. {
  1084. LogMessage(MSG_ERROR, "Security descriptor was retrieved and it had no owner");
  1085. }
  1086. delete pTmpSid;
  1087. pTmpSid = sdNew.GetGroup();
  1088. if (pTmpSid == NULL)
  1089. {
  1090. LogMessage(MSG_ERROR, "Security descriptor was retrieved and it had no group");
  1091. }
  1092. delete pTmpSid;
  1093. sd = sdNew;
  1094. SafeArrayUnaccessData(psa);
  1095. VariantClear(&var);
  1096. return true;
  1097. }
  1098. bool CRepImporter::StripOutInheritedAces(CNtSecurityDescriptor &sd)
  1099. {
  1100. // Get the DACL
  1101. CNtAcl* pAcl;
  1102. pAcl = sd.GetDacl();
  1103. if(!pAcl)
  1104. return false;
  1105. CDeleteMe<CNtAcl> dm(pAcl);
  1106. // enumerate through the aces
  1107. DWORD dwNumAces = pAcl->GetNumAces();
  1108. BOOL bChanged = FALSE;
  1109. for(long nIndex = (long)dwNumAces-1; nIndex >= 0; nIndex--)
  1110. {
  1111. CNtAce *pAce = pAcl->GetAce(nIndex);
  1112. if(pAce)
  1113. {
  1114. long lFlags = pAce->GetFlags();
  1115. if(lFlags & INHERITED_ACE)
  1116. {
  1117. pAcl->DeleteAce(nIndex);
  1118. bChanged = TRUE;
  1119. }
  1120. }
  1121. }
  1122. if(bChanged)
  1123. sd.SetDacl(pAcl);
  1124. return true;
  1125. }
  1126. bool CRepImporter::CopyInheritAces(CNtSecurityDescriptor& sd, CNtSecurityDescriptor& sdParent)
  1127. {
  1128. // Get the acl list for both SDs
  1129. CNtAcl * pacl = sd.GetDacl();
  1130. if(pacl == NULL)
  1131. return false;
  1132. CDeleteMe<CNtAcl> dm0(pacl);
  1133. CNtAcl * paclParent = sdParent.GetDacl();
  1134. if(paclParent == NULL)
  1135. return false;
  1136. CDeleteMe<CNtAcl> dm1(paclParent);
  1137. int iNumParent = paclParent->GetNumAces();
  1138. for(int iCnt = 0; iCnt < iNumParent; iCnt++)
  1139. {
  1140. CNtAce *pParentAce = paclParent->GetAce(iCnt);
  1141. CDeleteMe<CNtAce> dm2(pParentAce);
  1142. long lFlags = pParentAce->GetFlags();
  1143. if(lFlags & CONTAINER_INHERIT_ACE)
  1144. {
  1145. if(lFlags & NO_PROPAGATE_INHERIT_ACE)
  1146. lFlags ^= CONTAINER_INHERIT_ACE;
  1147. lFlags |= INHERITED_ACE;
  1148. // If this is an inherit only ace we need to clear this
  1149. // in the children.
  1150. // NT RAID: 161761 [marioh]
  1151. if ( lFlags & INHERIT_ONLY_ACE )
  1152. lFlags ^= INHERIT_ONLY_ACE;
  1153. pParentAce->SetFlags(lFlags);
  1154. pacl->AddAce(pParentAce);
  1155. }
  1156. }
  1157. sd.SetDacl(pacl);
  1158. return true;
  1159. }
  1160. BOOL CRepImporter::SetOwnerAndGroup(CNtSecurityDescriptor &sd)
  1161. {
  1162. PSID pRawSid;
  1163. BOOL bRet = FALSE;
  1164. SID_IDENTIFIER_AUTHORITY id = SECURITY_NT_AUTHORITY;
  1165. if(AllocateAndInitializeSid( &id, 2,
  1166. SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
  1167. 0,0,0,0,0,0,&pRawSid))
  1168. {
  1169. CNtSid SidAdmins(pRawSid);
  1170. bRet = sd.SetGroup(&SidAdmins); // Access check doesn't really care what you put,
  1171. // so long as you put something for the owner
  1172. if(bRet)
  1173. bRet = sd.SetOwner(&SidAdmins);
  1174. FreeSid(pRawSid);
  1175. return bRet;
  1176. }
  1177. return bRet;
  1178. }
  1179. void CRepImporter::ForceInherit()
  1180. {
  1181. // force ROOT\DEFAULT and ROOT\SECURITY namespaces to inherit their inheritable security settings
  1182. char szMsg[MAX_MSG_TEXT_LENGTH];
  1183. IWbemLocator* pLocator = NULL;
  1184. HRESULT hr = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_ALL, IID_IWbemLocator, (void**) &pLocator);
  1185. if(FAILED(hr))
  1186. {
  1187. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to create instance of IWbemLocator; HRESULT = %#lx", hr);
  1188. LogMessage(MSG_ERROR, szMsg);
  1189. throw FAILURE_CANNOT_CREATE_IWBEMLOCATOR;
  1190. }
  1191. CMyRelMe<IWbemLocator*> relMe1(pLocator);
  1192. IWbemServices* pRootNamespace = NULL;
  1193. ConnectNamespace(pLocator, L"root", &pRootNamespace);
  1194. CMyRelMe<IWbemServices*> relMe2(pRootNamespace);
  1195. if (!InheritSecurity(pLocator, pRootNamespace, L"root\\default"))
  1196. LogMessage(MSG_ERROR, "Failed to force inherit for root\\default");
  1197. if (!InheritSecurity(pLocator, pRootNamespace, L"root\\security"))
  1198. LogMessage(MSG_ERROR, "Failed to force inherit for root\\security");
  1199. }
  1200. bool CRepImporter::InheritSecurity(IWbemLocator* pLocator, IWbemServices* pRootNamespace, const wchar_t* wszNamespace)
  1201. {
  1202. IWbemServices* pNamespace = NULL;
  1203. ConnectNamespace(pLocator, wszNamespace, &pNamespace);
  1204. CMyRelMe<IWbemServices*> relMe(pNamespace);
  1205. CNtSecurityDescriptor sdNamespace;
  1206. if (!GetSDFromNamespace(pNamespace, sdNamespace))
  1207. return false;
  1208. if (!GetParentsInheritableAces(pRootNamespace, sdNamespace))
  1209. return false;
  1210. if (!SetNamespaceSecurity(pNamespace, sdNamespace))
  1211. return false;
  1212. return true;
  1213. }
  1214. void CRepImporter::ConnectNamespace(IWbemLocator* pLocator, const wchar_t* wszNamespaceName, IWbemServices** ppNamespace)
  1215. {
  1216. char szMsg[MAX_MSG_TEXT_LENGTH];
  1217. // get the namespace
  1218. BSTR bstrNamespace = SysAllocString(wszNamespaceName);
  1219. if (!bstrNamespace)
  1220. throw FAILURE_OUT_OF_MEMORY;
  1221. CSysFreeMe fm(bstrNamespace);
  1222. HRESULT hres = pLocator->ConnectServer(bstrNamespace, NULL, NULL, NULL, WBEM_FLAG_CONNECT_REPOSITORY_ONLY, NULL, NULL, ppNamespace);
  1223. if (FAILED(hres))
  1224. {
  1225. StringCchPrintfA(szMsg, MAX_MSG_TEXT_LENGTH, "Failed to connect server for namespace %S; HRESULT = %#lx", wszNamespaceName, hres);
  1226. LogMessage(MSG_ERROR, szMsg);
  1227. throw FAILURE_CANNOT_CONNECT_SERVER;
  1228. }
  1229. if (!*ppNamespace)
  1230. {
  1231. throw FAILURE_OUT_OF_MEMORY;
  1232. }
  1233. }
  1234. //***************************************************************************
  1235. //***************************************************************************
  1236. //
  1237. // Helper functions for Win9x security processing
  1238. //
  1239. //***************************************************************************
  1240. //***************************************************************************
  1241. bool CRepImporter::AppendWin9xBlobFile(const wchar_t* wszFullPath, DWORD dwBlobSize, const char* pNsSecurity)
  1242. {
  1243. // check whether we need to create the blob file
  1244. if (m_h9xBlobFile == INVALID_HANDLE_VALUE)
  1245. {
  1246. if (!CreateWin9xBlobFile())
  1247. return false;
  1248. }
  1249. // write the blob header containing the type, namespace name size, and blob size to the file
  1250. BLOB9X_SPACER header;
  1251. header.dwSpacerType = BLOB9X_TYPE_SECURITY_BLOB;
  1252. header.dwNamespaceNameSize = (wcslen(wszFullPath)+1)*sizeof(wchar_t);
  1253. header.dwParentClassNameSize = 0;
  1254. header.dwBlobSize = dwBlobSize;
  1255. DWORD dwSize = 0;
  1256. if (WriteFile(m_h9xBlobFile, &header, sizeof(header), &dwSize, NULL) && (dwSize == sizeof(header)))
  1257. {
  1258. // write the namespace name to the file
  1259. dwSize = 0;
  1260. if (WriteFile(m_h9xBlobFile, wszFullPath, header.dwNamespaceNameSize, &dwSize, NULL) && (dwSize == header.dwNamespaceNameSize))
  1261. {
  1262. // write the blob to the file
  1263. dwSize = 0;
  1264. if (WriteFile(m_h9xBlobFile, pNsSecurity, dwBlobSize, &dwSize, NULL) && (dwSize == dwBlobSize))
  1265. return true;
  1266. }
  1267. }
  1268. // if we failed to write to the file, something is wrong with the file, so close and delete it
  1269. DeleteWin9xBlobFile();
  1270. return false;
  1271. }
  1272. bool CRepImporter::AppendWin9xBlobFile(const wchar_t* wszFullPath, const wchar_t* wszParentClass, _IWmiObject* pInstance)
  1273. {
  1274. // check whether we need to create the blob file
  1275. if (m_h9xBlobFile == INVALID_HANDLE_VALUE)
  1276. {
  1277. if (!CreateWin9xBlobFile())
  1278. return false;
  1279. }
  1280. //Get the size of the object
  1281. DWORD dwObjPartLen = 0;
  1282. HRESULT hRes = pInstance->Unmerge(0, 0, &dwObjPartLen, 0);
  1283. //Allocate the size of the object
  1284. BYTE *pObjPart = NULL;
  1285. if (hRes == WBEM_E_BUFFER_TOO_SMALL)
  1286. {
  1287. hRes = WBEM_S_NO_ERROR;
  1288. pObjPart = new BYTE[dwObjPartLen];
  1289. }
  1290. if (pObjPart)
  1291. {
  1292. CVectorDeleteMe<BYTE> delMe(pObjPart);
  1293. //retrieve the object blob
  1294. if (SUCCEEDED(hRes))
  1295. {
  1296. DWORD dwLen;
  1297. hRes = pInstance->Unmerge(0, dwObjPartLen, &dwLen, pObjPart);
  1298. }
  1299. if (SUCCEEDED(hRes))
  1300. {
  1301. // write the blob header containing the type, namespace name size, parent class name size, and blob size to the file
  1302. BLOB9X_SPACER header;
  1303. header.dwSpacerType = BLOB9X_TYPE_SECURITY_INSTANCE;
  1304. header.dwNamespaceNameSize = (wcslen(wszFullPath)+1)*sizeof(wchar_t);
  1305. header.dwParentClassNameSize = (wcslen(wszParentClass)+1)*sizeof(wchar_t);
  1306. header.dwBlobSize = dwObjPartLen;
  1307. DWORD dwSize = 0;
  1308. if (WriteFile(m_h9xBlobFile, &header, sizeof(header), &dwSize, NULL) && (dwSize == sizeof(header)))
  1309. {
  1310. // write the namespace name to the file
  1311. dwSize = 0;
  1312. if (WriteFile(m_h9xBlobFile, wszFullPath, header.dwNamespaceNameSize, &dwSize, NULL) && (dwSize == header.dwNamespaceNameSize))
  1313. {
  1314. // write the parent class name to the file
  1315. dwSize = 0;
  1316. if (WriteFile(m_h9xBlobFile, wszParentClass, header.dwParentClassNameSize, &dwSize, NULL) && (dwSize == header.dwParentClassNameSize))
  1317. {
  1318. // write the blob to the file
  1319. dwSize = 0;
  1320. if (WriteFile(m_h9xBlobFile, pObjPart, dwObjPartLen, &dwSize, NULL) && (dwSize == dwObjPartLen))
  1321. return true;
  1322. }
  1323. }
  1324. }
  1325. }
  1326. }
  1327. // if we failed to write to the file, something is wrong with the file, so close and delete it
  1328. DeleteWin9xBlobFile();
  1329. return false;
  1330. }
  1331. bool CRepImporter::CreateWin9xBlobFile()
  1332. {
  1333. // get the root directory of the repository
  1334. wchar_t wszFilePath[MAX_PATH+1];
  1335. if (!GetRepositoryDirectory(wszFilePath))
  1336. return false;
  1337. // append blob file name
  1338. StringCchCatW(wszFilePath, MAX_PATH+1, BLOB9X_FILENAME);
  1339. // create a new file in which to store blob info
  1340. m_h9xBlobFile = CreateFileW(wszFilePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  1341. if (m_h9xBlobFile == INVALID_HANDLE_VALUE)
  1342. return false;
  1343. // write the blob file header
  1344. BLOB9X_HEADER header;
  1345. StringCchCopyA(header.szSignature, sizeof(header.szSignature)/sizeof(char), BLOB9X_SIGNATURE);
  1346. DWORD dwSize = 0;
  1347. if (WriteFile(m_h9xBlobFile, &header, sizeof(header), &dwSize, NULL) && (dwSize == sizeof(header)))
  1348. return true;
  1349. // if we failed to write to the file we should close the handle and delete the file
  1350. CloseHandle(m_h9xBlobFile);
  1351. DeleteFileW(wszFilePath);
  1352. m_h9xBlobFile = INVALID_HANDLE_VALUE;
  1353. return false;
  1354. }
  1355. void CRepImporter::DeleteWin9xBlobFile()
  1356. {
  1357. // close and invalidate the handle if necessary
  1358. if (m_h9xBlobFile != INVALID_HANDLE_VALUE)
  1359. {
  1360. CloseHandle(m_h9xBlobFile);
  1361. m_h9xBlobFile = INVALID_HANDLE_VALUE;
  1362. }
  1363. // delete the file
  1364. wchar_t wszFilePath[MAX_PATH+1];
  1365. if (GetRepositoryDirectory(wszFilePath))
  1366. {
  1367. StringCchCatW(wszFilePath, MAX_PATH+1, BLOB9X_FILENAME);
  1368. DeleteFileW(wszFilePath);
  1369. }
  1370. }
  1371. bool CRepImporter::GetRepositoryDirectory(wchar_t wszRepositoryDirectory[MAX_PATH+1])
  1372. {
  1373. HKEY hKey;
  1374. if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\WBEM\\CIMOM", 0, KEY_READ, &hKey))
  1375. return false;
  1376. wchar_t wszTmp[MAX_PATH + 1];
  1377. DWORD dwLen = (MAX_PATH + 1) * sizeof(wchar_t);
  1378. long lRes = RegQueryValueExW(hKey, L"Repository Directory", NULL, NULL, (LPBYTE)wszTmp, &dwLen);
  1379. RegCloseKey(hKey);
  1380. if(lRes)
  1381. return false;
  1382. if (ExpandEnvironmentStringsW(wszTmp,wszRepositoryDirectory, MAX_PATH + 1) == 0)
  1383. return false;
  1384. return true;
  1385. }
  1386. bool CRepImporter::CloseWin9xBlobFile()
  1387. {
  1388. // if no valid handle, then we don't have a file to close, return success
  1389. if (m_h9xBlobFile == INVALID_HANDLE_VALUE)
  1390. return true;
  1391. // write the end of blob file marker
  1392. BLOB9X_SPACER trailer;
  1393. trailer.dwSpacerType = BLOB9X_TYPE_END_OF_FILE;
  1394. trailer.dwNamespaceNameSize = 0;
  1395. trailer.dwParentClassNameSize = 0;
  1396. trailer.dwBlobSize = 0;
  1397. DWORD dwSize = 0;
  1398. if ((WriteFile(m_h9xBlobFile, &trailer, sizeof(trailer), &dwSize, NULL) == 0) || (dwSize != sizeof(trailer)))
  1399. {
  1400. // if we failed to write the trailer, something is wrong with the file, so close and delete it
  1401. DeleteWin9xBlobFile();
  1402. return false;
  1403. }
  1404. CloseHandle(m_h9xBlobFile);
  1405. m_h9xBlobFile = INVALID_HANDLE_VALUE;
  1406. return true;
  1407. }
  1408. /******************************************************************************
  1409. *
  1410. * Name:
  1411. *
  1412. *
  1413. * Description:
  1414. *
  1415. *
  1416. *****************************************************************************/
  1417. extern HRESULT Traverse (
  1418. IWbemServices *a_Service ,
  1419. BSTR a_Namespace
  1420. ) ;
  1421. /******************************************************************************
  1422. *
  1423. * Name:
  1424. *
  1425. *
  1426. * Description:
  1427. *
  1428. *
  1429. *****************************************************************************/
  1430. PSID g_NetworkServiceSid = NULL ;
  1431. PSID g_LocalServiceSid = NULL ;
  1432. ACCESS_ALLOWED_ACE *g_NetworkService_Ace = NULL ;
  1433. WORD g_NetworkService_AceSize = 0 ;
  1434. ACCESS_ALLOWED_ACE *g_LocalService_Ace = NULL ;
  1435. WORD g_LocalService_AceSize = 0 ;
  1436. /******************************************************************************
  1437. *
  1438. * Name:
  1439. *
  1440. *
  1441. * Description:
  1442. *
  1443. *
  1444. *****************************************************************************/
  1445. HRESULT TraverseSetSecurity ( IWbemServices *a_Service )
  1446. {
  1447. IClientSecurity *t_Security = NULL ;
  1448. HRESULT t_Result = a_Service->QueryInterface ( IID_IClientSecurity , ( void ** ) & t_Security ) ;
  1449. if ( SUCCEEDED ( t_Result ) )
  1450. {
  1451. t_Result = t_Security->SetBlanket (
  1452. a_Service ,
  1453. RPC_C_AUTHN_WINNT,
  1454. RPC_C_AUTHZ_NONE,
  1455. NULL,
  1456. RPC_C_AUTHN_LEVEL_DEFAULT ,
  1457. RPC_C_IMP_LEVEL_IDENTIFY,
  1458. NULL,
  1459. EOAC_NONE
  1460. ) ;
  1461. t_Security->Release () ;
  1462. }
  1463. return t_Result ;
  1464. }
  1465. /******************************************************************************
  1466. *
  1467. * Name:
  1468. *
  1469. *
  1470. * Description:
  1471. *
  1472. *
  1473. *****************************************************************************/
  1474. HRESULT InsertServiceAccess (
  1475. SAFEARRAY *a_Array ,
  1476. SAFEARRAY *&a_NewArray
  1477. )
  1478. {
  1479. HRESULT t_Result = S_OK ;
  1480. if ( SafeArrayGetDim ( a_Array ) == 1 )
  1481. {
  1482. LONG t_Dimension = 1 ;
  1483. LONG t_Lower ;
  1484. SafeArrayGetLBound ( a_Array , t_Dimension , & t_Lower ) ;
  1485. LONG t_Upper ;
  1486. SafeArrayGetUBound ( a_Array , t_Dimension , & t_Upper ) ;
  1487. LONG t_Count = ( t_Upper - t_Lower ) + 1 ;
  1488. BYTE *t_SecurityDescriptor = new BYTE [ t_Count ] ;
  1489. if ( t_SecurityDescriptor )
  1490. {
  1491. if ( t_Count )
  1492. {
  1493. for ( LONG t_ElementIndex = t_Lower ; t_ElementIndex <= t_Upper ; t_ElementIndex ++ )
  1494. {
  1495. BYTE t_Element ;
  1496. if ( SUCCEEDED ( SafeArrayGetElement ( a_Array , & t_ElementIndex , & t_Element ) ) )
  1497. {
  1498. t_SecurityDescriptor [ t_ElementIndex - t_Lower ] = t_Element ;
  1499. }
  1500. else
  1501. {
  1502. t_Result = WBEM_E_CRITICAL_ERROR ;
  1503. break ;
  1504. }
  1505. }
  1506. }
  1507. }
  1508. else
  1509. {
  1510. t_Result = WBEM_E_OUT_OF_MEMORY ;
  1511. }
  1512. if ( SUCCEEDED ( t_Result ) )
  1513. {
  1514. if ( IsValidSecurityDescriptor ( t_SecurityDescriptor ) == FALSE )
  1515. {
  1516. t_Result = WBEM_E_CRITICAL_ERROR ;
  1517. }
  1518. }
  1519. bool t_NetworkServicePresent = false ;
  1520. bool t_LocalServicePresent = false ;
  1521. if ( SUCCEEDED ( t_Result ) )
  1522. {
  1523. BOOL t_AclPresent = FALSE ;
  1524. BOOL t_AclDefaulted = FALSE ;
  1525. ACL *t_Dacl = NULL ;
  1526. BOOL t_Status = GetSecurityDescriptorDacl (t_SecurityDescriptor ,& t_AclPresent ,& t_Dacl ,& t_AclDefaulted) ;
  1527. if ( t_Status )
  1528. {
  1529. DWORD SidNetworkSvcSize = GetLengthSid(g_NetworkServiceSid);
  1530. DWORD SidLocalSvcSize = GetLengthSid(g_LocalServiceSid);
  1531. ACCESS_ALLOWED_ACE * pACE = (ACCESS_ALLOWED_ACE *)(t_Dacl+1);
  1532. for (USHORT i=0;i<t_Dacl->AceCount;i++)
  1533. {
  1534. DWORD sidSize = GetLengthSid((PSID)&pACE->SidStart);
  1535. if ((sidSize == SidNetworkSvcSize) &&
  1536. (0 == memcmp(&pACE->SidStart,g_NetworkServiceSid,sidSize)))
  1537. {
  1538. t_NetworkServicePresent = true;
  1539. }
  1540. if ((sidSize == SidLocalSvcSize) &&
  1541. (0 == memcmp(&pACE->SidStart,g_LocalServiceSid,sidSize)))
  1542. {
  1543. t_LocalServicePresent = true;
  1544. }
  1545. pACE = (ACCESS_ALLOWED_ACE *)((BYTE *)pACE + pACE->Header.AceSize);
  1546. }
  1547. }
  1548. else
  1549. {
  1550. t_Result = HRESULT_FROM_WIN32(GetLastError());
  1551. }
  1552. }
  1553. if ( SUCCEEDED ( t_Result ) )
  1554. {
  1555. SECURITY_DESCRIPTOR *t_AbsoluteSecurityDescriptor = NULL ;
  1556. DWORD t_AbsoluteSecurityDescriptorSize = sizeof ( SECURITY_DESCRIPTOR ) ;
  1557. PACL t_Dacl = NULL ;
  1558. PACL t_Sacl = NULL ;
  1559. PSID t_Owner = NULL ;
  1560. PSID t_PrimaryGroup = NULL ;
  1561. DWORD t_DaclSize = 0 ;
  1562. DWORD t_SaclSize = 0 ;
  1563. DWORD t_OwnerSize = 0 ;
  1564. DWORD t_PrimaryGroupSize = 0 ;
  1565. BOOL t_Status = MakeAbsoluteSD (t_SecurityDescriptor ,t_AbsoluteSecurityDescriptor ,& t_AbsoluteSecurityDescriptorSize ,
  1566. t_Dacl,& t_DaclSize,t_Sacl,& t_SaclSize,t_Owner,& t_OwnerSize,t_PrimaryGroup,& t_PrimaryGroupSize) ;
  1567. if ( ( t_Status == FALSE ) && GetLastError () == ERROR_INSUFFICIENT_BUFFER )
  1568. {
  1569. WORD t_Extra = 0 ;
  1570. if ( t_NetworkServicePresent == false )
  1571. {
  1572. t_Extra = t_Extra + g_NetworkService_AceSize ;
  1573. }
  1574. if ( t_LocalServicePresent == false )
  1575. {
  1576. t_Extra = t_Extra + g_LocalService_AceSize ;
  1577. }
  1578. t_DaclSize = t_DaclSize + t_Extra ;
  1579. t_Dacl = ( PACL ) new BYTE [ t_DaclSize ] ;
  1580. t_Sacl = ( PACL ) new BYTE [ t_SaclSize ] ;
  1581. t_Owner = ( PSID ) new BYTE [ t_OwnerSize ] ;
  1582. t_PrimaryGroup = ( PSID ) new BYTE [ t_PrimaryGroupSize ] ;
  1583. t_AbsoluteSecurityDescriptor = ( SECURITY_DESCRIPTOR * ) new BYTE [ t_AbsoluteSecurityDescriptorSize ] ;
  1584. if ( t_AbsoluteSecurityDescriptor && t_Dacl && t_Sacl && t_Owner && t_PrimaryGroup )
  1585. {
  1586. BOOL t_Status = InitializeSecurityDescriptor ( t_AbsoluteSecurityDescriptor , SECURITY_DESCRIPTOR_REVISION ) ;
  1587. if ( t_Status )
  1588. {
  1589. t_Status = MakeAbsoluteSD (t_SecurityDescriptor ,t_AbsoluteSecurityDescriptor ,& t_AbsoluteSecurityDescriptorSize ,
  1590. t_Dacl ,& t_DaclSize ,t_Sacl,& t_SaclSize,t_Owner,& t_OwnerSize,t_PrimaryGroup,& t_PrimaryGroupSize
  1591. ) ;
  1592. WORD t_AceCount = t_Dacl->AceCount ;
  1593. if ( t_Status )
  1594. {
  1595. t_Dacl->AclSize = ( WORD ) t_DaclSize ;
  1596. if ( t_NetworkServicePresent == false )
  1597. {
  1598. t_Status = AddAce ( t_Dacl , ACL_REVISION, t_AceCount ++ , g_NetworkService_Ace , g_NetworkService_AceSize) ;
  1599. }
  1600. }
  1601. if ( t_Status )
  1602. {
  1603. if ( t_LocalServicePresent == false )
  1604. {
  1605. t_Status = AddAce ( t_Dacl , ACL_REVISION, t_AceCount ++ , g_LocalService_Ace , g_LocalService_AceSize) ;
  1606. }
  1607. }
  1608. if ( t_Status == FALSE )
  1609. {
  1610. t_Result = WBEM_E_CRITICAL_ERROR ;
  1611. }
  1612. }
  1613. }
  1614. }
  1615. if ( SUCCEEDED ( t_Result ) )
  1616. {
  1617. SECURITY_DESCRIPTOR *t_SecurityDescriptorRelative = NULL ;
  1618. DWORD t_FinalLength = 0 ;
  1619. t_Status = MakeSelfRelativeSD (t_AbsoluteSecurityDescriptor ,t_SecurityDescriptorRelative ,& t_FinalLength ) ;
  1620. if ( t_Status == FALSE && GetLastError () == ERROR_INSUFFICIENT_BUFFER )
  1621. {
  1622. t_SecurityDescriptorRelative = ( SECURITY_DESCRIPTOR * ) new BYTE [ t_FinalLength ] ;
  1623. if ( t_SecurityDescriptorRelative )
  1624. {
  1625. t_Status = InitializeSecurityDescriptor ( t_SecurityDescriptorRelative , SECURITY_DESCRIPTOR_REVISION ) ;
  1626. if ( t_Status )
  1627. {
  1628. t_Status = MakeSelfRelativeSD (t_AbsoluteSecurityDescriptor ,t_SecurityDescriptorRelative ,& t_FinalLength ) ;
  1629. if ( t_Status == FALSE )
  1630. {
  1631. t_Result = WBEM_E_CRITICAL_ERROR ;
  1632. }
  1633. }
  1634. else
  1635. {
  1636. t_Result = WBEM_E_CRITICAL_ERROR ;
  1637. }
  1638. }
  1639. else
  1640. {
  1641. t_Result = WBEM_E_OUT_OF_MEMORY ;
  1642. }
  1643. }
  1644. else
  1645. {
  1646. t_Result = WBEM_E_CRITICAL_ERROR ;
  1647. }
  1648. if ( SUCCEEDED ( t_Result ) )
  1649. {
  1650. SAFEARRAYBOUND t_Bounds ;
  1651. t_Bounds.lLbound = 0;
  1652. t_Bounds.cElements = t_FinalLength ;
  1653. a_NewArray = SafeArrayCreate ( VT_UI1 , 1 , & t_Bounds ) ;
  1654. if ( a_NewArray )
  1655. {
  1656. for ( LONG t_Index = 0 ; ( ( ULONG ) t_Index ) < t_FinalLength ; t_Index ++ )
  1657. {
  1658. BYTE t_Byte = * ( ( ( BYTE * ) t_SecurityDescriptorRelative ) + t_Index ) ;
  1659. t_Result = SafeArrayPutElement ( a_NewArray , & t_Index , & t_Byte ) ;
  1660. if ( FAILED ( t_Result ) )
  1661. {
  1662. break ;
  1663. }
  1664. }
  1665. }
  1666. else
  1667. {
  1668. t_Result = WBEM_E_OUT_OF_MEMORY ;
  1669. }
  1670. }
  1671. delete [] ( BYTE * ) t_SecurityDescriptorRelative ;
  1672. }
  1673. delete [] ( BYTE * ) t_Dacl ;
  1674. delete [] ( BYTE * ) t_Sacl ;
  1675. delete [] ( BYTE * ) t_Owner ;
  1676. delete [] ( BYTE * ) t_PrimaryGroup ;
  1677. }
  1678. delete [] t_SecurityDescriptor ;
  1679. }
  1680. else
  1681. {
  1682. t_Result = WBEM_E_CRITICAL_ERROR ;
  1683. }
  1684. return t_Result ;
  1685. }
  1686. /******************************************************************************
  1687. *
  1688. * Name:
  1689. *
  1690. *
  1691. * Description:
  1692. *
  1693. *
  1694. *****************************************************************************/
  1695. HRESULT ConfigureSecurity (
  1696. IWbemServices *a_Service
  1697. )
  1698. {
  1699. HRESULT t_Result = S_OK ;
  1700. BSTR t_ObjectPath = SysAllocString ( L"__SystemSecurity" ) ;
  1701. BSTR t_MethodName = SysAllocString ( L"GetSD" ) ;
  1702. if ( t_ObjectPath && t_MethodName )
  1703. {
  1704. IWbemClassObject *t_Object = NULL ;
  1705. t_Result = a_Service->ExecMethod (t_ObjectPath ,t_MethodName ,0 ,NULL ,NULL ,& t_Object ,NULL);
  1706. if ( SUCCEEDED ( t_Result ) )
  1707. {
  1708. VARIANT t_Variant ;
  1709. VariantInit ( & t_Variant ) ;
  1710. LONG t_VarType = 0 ;
  1711. LONG t_Flavour = 0 ;
  1712. HRESULT t_Result = t_Object->Get ( L"SD" , 0 , & t_Variant , & t_VarType , & t_Flavour ) ;
  1713. if ( SUCCEEDED ( t_Result ) )
  1714. {
  1715. if ( t_Variant.vt == ( VT_UI1 | VT_ARRAY ) )
  1716. {
  1717. SAFEARRAY *t_Array = t_Variant.parray ;
  1718. SAFEARRAY *t_NewArray = NULL ;
  1719. t_Result = InsertServiceAccess (t_Array ,t_NewArray ) ;
  1720. if ( SUCCEEDED ( t_Result ) )
  1721. {
  1722. BSTR t_Class = SysAllocString ( L"__SystemSecurity" ) ;
  1723. if ( t_Class )
  1724. {
  1725. IWbemClassObject *t_InObject = NULL ;
  1726. t_Result = a_Service->GetObject (t_Class ,0 , NULL , & t_InObject ,NULL ) ;
  1727. if ( SUCCEEDED ( t_Result ) )
  1728. {
  1729. BSTR t_SetMethodName = SysAllocString ( L"SetSD" ) ;
  1730. if ( t_SetMethodName )
  1731. {
  1732. IWbemClassObject *t_InArgsClass = NULL ;
  1733. t_Result = t_InObject->GetMethod (t_SetMethodName ,0 ,& t_InArgsClass ,NULL ) ;
  1734. if ( SUCCEEDED ( t_Result ) )
  1735. {
  1736. IWbemClassObject *t_InArgs = NULL ;
  1737. t_Result = t_InArgsClass->SpawnInstance ( 0 , & t_InArgs ) ;
  1738. if ( SUCCEEDED ( t_Result ) )
  1739. {
  1740. VARIANT t_Variant ;
  1741. VariantInit ( & t_Variant ) ;
  1742. t_Variant.vt = VT_UI1 | VT_ARRAY ;
  1743. t_Variant.parray = t_NewArray ;
  1744. t_Result = t_InArgs->Put ( L"SD" ,0 ,& t_Variant ,CIM_UINT8 | CIM_FLAG_ARRAY) ;
  1745. if ( SUCCEEDED ( t_Result ) )
  1746. {
  1747. IWbemClassObject *t_OutArgs = NULL ;
  1748. a_Service->ExecMethod (t_ObjectPath ,t_SetMethodName ,0 ,NULL ,t_InArgs ,& t_OutArgs ,NULL ) ;
  1749. if ( SUCCEEDED ( t_Result ) )
  1750. {
  1751. if ( t_OutArgs )
  1752. {
  1753. t_OutArgs->Release () ;
  1754. }
  1755. }
  1756. }
  1757. t_InArgs->Release () ;
  1758. }
  1759. t_InArgsClass->Release () ;
  1760. }
  1761. SysFreeString ( t_SetMethodName ) ;
  1762. }
  1763. t_InObject->Release () ;
  1764. }
  1765. }
  1766. else
  1767. {
  1768. t_Result = WBEM_E_OUT_OF_MEMORY ;
  1769. }
  1770. SafeArrayDestroy ( t_NewArray ) ;
  1771. }
  1772. }
  1773. else
  1774. {
  1775. t_Result = WBEM_E_CRITICAL_ERROR ;
  1776. }
  1777. VariantClear ( & t_Variant ) ;
  1778. }
  1779. t_Object->Release () ;
  1780. }
  1781. }
  1782. else
  1783. {
  1784. t_Result = WBEM_E_OUT_OF_MEMORY ;
  1785. }
  1786. SysFreeString ( t_ObjectPath ) ;
  1787. SysFreeString ( t_MethodName ) ;
  1788. return t_Result ;
  1789. }
  1790. /******************************************************************************
  1791. *
  1792. * Name:
  1793. *
  1794. *
  1795. * Description:
  1796. *
  1797. *
  1798. *****************************************************************************/
  1799. HRESULT Traverse (
  1800. IWbemServices *a_Service ,
  1801. BSTR a_Namespace
  1802. )
  1803. {
  1804. if ( wcslen ( a_Namespace ) < ( MAX_MSG_TEXT_LENGTH >> 1 ) )
  1805. {
  1806. char t_Buffer [ MAX_MSG_TEXT_LENGTH ] ;
  1807. StringCchPrintfA ( t_Buffer , MAX_MSG_TEXT_LENGTH, "\nTraversing [%S]" , a_Namespace ) ;
  1808. LogMessage(MSG_INFO, t_Buffer);
  1809. }
  1810. HRESULT t_Result = ConfigureSecurity (a_Service ) ;
  1811. if ( FAILED ( t_Result ) )
  1812. {
  1813. char t_Buffer [ MAX_MSG_TEXT_LENGTH ] ;
  1814. StringCchPrintfA ( t_Buffer, MAX_MSG_TEXT_LENGTH , "\nConfiguration of Security failed [%lx]" , t_Result ) ;
  1815. LogMessage(MSG_INFO, t_Buffer);
  1816. }
  1817. return t_Result ;
  1818. }
  1819. /******************************************************************************
  1820. *
  1821. * Name:
  1822. *
  1823. *
  1824. * Description:
  1825. *
  1826. *
  1827. *****************************************************************************/
  1828. HRESULT ConfigureServiceSecurity ()
  1829. {
  1830. IWbemLocator *t_Locator = NULL ;
  1831. HRESULT t_Result = CoCreateInstance (CLSID_WbemLocator ,NULL ,CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER ,
  1832. IID_IUnknown ,( void ** ) & t_Locator);
  1833. if ( SUCCEEDED ( t_Result ) )
  1834. {
  1835. BSTR t_Root = SysAllocString ( L"root" ) ;
  1836. if ( t_Root )
  1837. {
  1838. IWbemServices *t_Service = NULL ;
  1839. HRESULT t_Result = t_Locator->ConnectServer (t_Root ,NULL ,NULL,NULL ,0 ,NULL,NULL,&t_Service) ;
  1840. if ( SUCCEEDED ( t_Result ) )
  1841. {
  1842. t_Result = TraverseSetSecurity ( t_Service ) ;
  1843. if ( SUCCEEDED ( t_Result ) )
  1844. {
  1845. t_Result = Traverse (t_Service ,t_Root ) ;
  1846. }
  1847. t_Service->Release () ;
  1848. }
  1849. else
  1850. {
  1851. char t_Buffer [ MAX_MSG_TEXT_LENGTH ] ;
  1852. StringCchPrintfA ( t_Buffer , MAX_MSG_TEXT_LENGTH, "\nFailing Connecting to Namespace [%s] with result [%lx]" , t_Root , t_Result ) ;
  1853. LogMessage(MSG_INFO, t_Buffer);
  1854. }
  1855. SysFreeString ( t_Root ) ;
  1856. }
  1857. else
  1858. {
  1859. t_Result = WBEM_E_OUT_OF_MEMORY ;
  1860. }
  1861. t_Locator->Release () ;
  1862. }
  1863. return t_Result ;
  1864. }
  1865. /******************************************************************************
  1866. *
  1867. * Name:
  1868. *
  1869. *
  1870. * Description:
  1871. *
  1872. *
  1873. *****************************************************************************/
  1874. HRESULT InitializeConstants ()
  1875. {
  1876. HRESULT t_Result = S_OK ;
  1877. SID_IDENTIFIER_AUTHORITY t_NtAuthoritySid = SECURITY_NT_AUTHORITY ;
  1878. BOOL t_Status = AllocateAndInitializeSid (& t_NtAuthoritySid ,1 ,SECURITY_NETWORK_SERVICE_RID,0,0,0,0,0,0,0,& g_NetworkServiceSid) ;
  1879. if ( t_Status )
  1880. {
  1881. DWORD t_SidLength = :: GetLengthSid ( g_NetworkServiceSid );
  1882. g_NetworkService_AceSize = sizeof(ACCESS_ALLOWED_ACE) + (WORD) ( t_SidLength - sizeof(DWORD) ) ;
  1883. g_NetworkService_Ace = (ACCESS_ALLOWED_ACE*) new BYTE [ g_NetworkService_AceSize ] ;
  1884. if ( g_NetworkService_Ace )
  1885. {
  1886. CopySid ( t_SidLength, (PSID) & g_NetworkService_Ace->SidStart, g_NetworkServiceSid ) ;
  1887. g_NetworkService_Ace->Mask = WBEM_ENABLE | WBEM_METHOD_EXECUTE | WBEM_WRITE_PROVIDER ;
  1888. g_NetworkService_Ace->Header.AceType = ACCESS_ALLOWED_ACE_TYPE ;
  1889. g_NetworkService_Ace->Header.AceFlags = CONTAINER_INHERIT_ACE ;
  1890. g_NetworkService_Ace->Header.AceSize = g_NetworkService_AceSize ;
  1891. }
  1892. else
  1893. {
  1894. t_Result = WBEM_E_OUT_OF_MEMORY ;
  1895. }
  1896. }
  1897. else
  1898. {
  1899. t_Result = WBEM_E_OUT_OF_MEMORY ;
  1900. }
  1901. if ( SUCCEEDED ( t_Result ) )
  1902. {
  1903. t_Status = AllocateAndInitializeSid (& t_NtAuthoritySid ,1 ,SECURITY_LOCAL_SERVICE_RID,0,0,0,0,0,0,0,& g_LocalServiceSid) ;
  1904. if ( t_Status )
  1905. {
  1906. DWORD t_SidLength = :: GetLengthSid ( g_LocalServiceSid );
  1907. g_LocalService_AceSize = sizeof(ACCESS_ALLOWED_ACE) + (WORD) ( t_SidLength - sizeof(DWORD) ) ;
  1908. g_LocalService_Ace = (ACCESS_ALLOWED_ACE*) new BYTE [ g_LocalService_AceSize ] ;
  1909. if ( g_LocalService_Ace )
  1910. {
  1911. CopySid ( t_SidLength, (PSID) & g_LocalService_Ace->SidStart, g_LocalServiceSid ) ;
  1912. g_LocalService_Ace->Mask = WBEM_ENABLE | WBEM_METHOD_EXECUTE | WBEM_WRITE_PROVIDER ;
  1913. g_LocalService_Ace->Header.AceType = ACCESS_ALLOWED_ACE_TYPE ;
  1914. g_LocalService_Ace->Header.AceFlags = CONTAINER_INHERIT_ACE ;
  1915. g_LocalService_Ace->Header.AceSize = g_LocalService_AceSize ;
  1916. }
  1917. else
  1918. {
  1919. t_Result = WBEM_E_OUT_OF_MEMORY ;
  1920. }
  1921. }
  1922. else
  1923. {
  1924. t_Result = WBEM_E_OUT_OF_MEMORY ;
  1925. }
  1926. }
  1927. return t_Result ;
  1928. }
  1929. /******************************************************************************
  1930. *
  1931. * Name:
  1932. *
  1933. *
  1934. * Description:
  1935. *
  1936. *
  1937. *****************************************************************************/
  1938. HRESULT UnInitializeConstants ()
  1939. {
  1940. FreeSid ( g_NetworkServiceSid ) ;
  1941. FreeSid ( g_LocalServiceSid ) ;
  1942. delete [] ( ( BYTE * ) g_NetworkService_Ace ) ;
  1943. delete [] ( ( BYTE * ) g_LocalService_Ace ) ;
  1944. return S_OK ;
  1945. }
  1946. /******************************************************************************
  1947. *
  1948. * Name:
  1949. *
  1950. *
  1951. * Description:
  1952. *
  1953. *
  1954. *****************************************************************************/
  1955. HRESULT UpdateServiceSecurity ()
  1956. {
  1957. HRESULT t_Result = InitializeConstants () ;
  1958. if ( SUCCEEDED ( t_Result ) )
  1959. {
  1960. t_Result = ConfigureServiceSecurity () ;
  1961. UnInitializeConstants () ;
  1962. }
  1963. return t_Result ;
  1964. }
  1965. /******************************************************************************
  1966. *
  1967. * Name:
  1968. *
  1969. *
  1970. * Description:
  1971. *
  1972. *
  1973. *****************************************************************************/
  1974. HRESULT CheckForServiceSecurity ()
  1975. {
  1976. Registry r(WBEM_REG_WBEM);
  1977. if (r.GetStatus() != no_error)
  1978. {
  1979. LogMessage(MSG_ERROR, "Unable to access registry for UpdateServiceSecurity.");
  1980. return WBEM_E_CRITICAL_ERROR ;
  1981. }
  1982. char *t_BuildVersion = NULL ;
  1983. if ( r.GetStr ("Build", & t_BuildVersion ) )
  1984. {
  1985. LogMessage(MSG_ERROR, "Unable to get build version number for UpdateServiceSecurity.");
  1986. return WBEM_E_CRITICAL_ERROR ;
  1987. }
  1988. if ( strlen ( t_BuildVersion ) >= 4 )
  1989. {
  1990. t_BuildVersion [ 4 ] = 0 ;
  1991. }
  1992. else
  1993. {
  1994. LogMessage(MSG_ERROR, "Unexpected build version number for UpdateServiceSecurity.");
  1995. return WBEM_E_CRITICAL_ERROR ;
  1996. }
  1997. DWORD t_BuildVersionNumber = 0 ;
  1998. if ( sscanf ( t_BuildVersion , "%lu" , & t_BuildVersionNumber ) == NULL )
  1999. {
  2000. LogMessage(MSG_ERROR, "Unable to convert build version number for UpdateServiceSecurity.");
  2001. return WBEM_E_CRITICAL_ERROR ;
  2002. }
  2003. if ( t_BuildVersionNumber < 2600 )
  2004. {
  2005. LogMessage(MSG_INFO, "Operating System Version < WindowsXP (2600) UpdateServiceSecurity.");
  2006. return S_OK ;
  2007. }
  2008. else
  2009. {
  2010. return S_FALSE ;
  2011. }
  2012. }