registry_util.cc 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. //
  5. // A helper library to keep track of a user's key by SID.
  6. // Used by RLZ libary. Also to be used by SearchWithGoogle library.
  7. #include "rlz/win/lib/registry_util.h"
  8. #include "base/process/process_info.h"
  9. #include "base/strings/utf_string_conversions.h"
  10. #include "base/win/registry.h"
  11. #include "base/win/windows_version.h"
  12. #include "rlz/lib/assert.h"
  13. #include "rlz/win/lib/process_info.h"
  14. #include <windows.h>
  15. namespace rlz_lib {
  16. bool RegKeyReadValue(const base::win::RegKey& key, const wchar_t* name,
  17. char* value, size_t* value_size) {
  18. value[0] = 0;
  19. std::wstring value_string;
  20. if (key.ReadValue(name, &value_string) != ERROR_SUCCESS) {
  21. return false;
  22. }
  23. if (value_string.length() > *value_size) {
  24. *value_size = value_string.length();
  25. return false;
  26. }
  27. // Note that RLZ string are always ASCII by design.
  28. strncpy(value, base::WideToUTF8(value_string).c_str(), *value_size);
  29. value[*value_size - 1] = 0;
  30. return true;
  31. }
  32. bool RegKeyWriteValue(base::win::RegKey* key, const wchar_t* name,
  33. const char* value) {
  34. std::wstring value_string(base::ASCIIToWide(value));
  35. return key->WriteValue(name, value_string.c_str()) == ERROR_SUCCESS;
  36. }
  37. bool HasUserKeyAccess(bool write_access) {
  38. // The caller is trying to access HKEY_CURRENT_USER. Test to see if we can
  39. // read from there. Don't try HKEY_CURRENT_USER because this will cause
  40. // problems in the unit tests: if we open HKEY_CURRENT_USER directly here,
  41. // the overriding done for unit tests will no longer work. So we try subkey
  42. // "Software" which is known to always exist.
  43. base::win::RegKey key;
  44. if (key.Open(HKEY_CURRENT_USER, L"Software", KEY_READ) != ERROR_SUCCESS)
  45. ASSERT_STRING("Could not open HKEY_CURRENT_USER");
  46. if (ProcessInfo::IsRunningAsSystem()) {
  47. ASSERT_STRING("UserKey::HasAccess: No access as SYSTEM without SID set.");
  48. return false;
  49. }
  50. if (write_access) {
  51. if (base::GetCurrentProcessIntegrityLevel() <= base::LOW_INTEGRITY) {
  52. ASSERT_STRING("UserKey::HasAccess: Cannot write from Low Integrity.");
  53. return false;
  54. }
  55. }
  56. return true;
  57. }
  58. } // namespace rlz_lib