1 // Copyright 2013 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 #include "components/policy/core/common/registry_dict.h"
6 
7 #include <utility>
8 
9 #include "base/json/json_reader.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/sys_byteorder.h"
14 #include "base/values.h"
15 #include "components/policy/core/common/schema.h"
16 
17 #if defined(OS_WIN)
18 #include "base/win/registry.h"
19 
20 using base::win::RegistryKeyIterator;
21 using base::win::RegistryValueIterator;
22 #endif  // #if defined(OS_WIN)
23 
24 namespace policy {
25 
26 namespace {
27 
28 // Validates that a key is numerical. Used for lists below.
IsKeyNumerical(const std::string & key)29 bool IsKeyNumerical(const std::string& key) {
30   int temp = 0;
31   return base::StringToInt(key, &temp);
32 }
33 
34 }  // namespace
35 
ConvertRegistryValue(const base::Value & value,const Schema & schema)36 std::unique_ptr<base::Value> ConvertRegistryValue(const base::Value& value,
37                                                   const Schema& schema) {
38   if (!schema.valid())
39     return value.CreateDeepCopy();
40 
41   // If the type is good already, go with it.
42   if (value.type() == schema.type()) {
43     // Recurse for complex types.
44     const base::DictionaryValue* dict = nullptr;
45     const base::ListValue* list = nullptr;
46     if (value.GetAsDictionary(&dict)) {
47       std::unique_ptr<base::DictionaryValue> result(
48           new base::DictionaryValue());
49       for (base::DictionaryValue::Iterator entry(*dict); !entry.IsAtEnd();
50            entry.Advance()) {
51         std::unique_ptr<base::Value> converted = ConvertRegistryValue(
52             entry.value(), schema.GetProperty(entry.key()));
53         if (converted)
54           result->SetWithoutPathExpansion(entry.key(), std::move(converted));
55       }
56       return std::move(result);
57     } else if (value.GetAsList(&list)) {
58       std::unique_ptr<base::ListValue> result(new base::ListValue());
59       for (base::ListValue::const_iterator entry(list->begin());
60            entry != list->end(); ++entry) {
61         std::unique_ptr<base::Value> converted =
62             ConvertRegistryValue(*entry, schema.GetItems());
63         if (converted)
64           result->Append(std::move(converted));
65       }
66       return std::move(result);
67     }
68     return value.CreateDeepCopy();
69   }
70 
71   // Else, do some conversions to map windows registry data types to JSON types.
72   std::string string_value;
73   int int_value = 0;
74   switch (schema.type()) {
75     case base::Value::Type::NONE: {
76       return std::make_unique<base::Value>();
77     }
78     case base::Value::Type::BOOLEAN: {
79       // Accept booleans encoded as either string or integer.
80       if (value.GetAsInteger(&int_value) ||
81           (value.GetAsString(&string_value) &&
82            base::StringToInt(string_value, &int_value))) {
83         return std::unique_ptr<base::Value>(new base::Value(int_value != 0));
84       }
85       break;
86     }
87     case base::Value::Type::INTEGER: {
88       // Integers may be string-encoded.
89       if (value.GetAsString(&string_value) &&
90           base::StringToInt(string_value, &int_value)) {
91         return std::unique_ptr<base::Value>(new base::Value(int_value));
92       }
93       break;
94     }
95     case base::Value::Type::DOUBLE: {
96       // Doubles may be string-encoded or integer-encoded.
97       double double_value = 0;
98       if (value.GetAsDouble(&double_value) ||
99           (value.GetAsString(&string_value) &&
100            base::StringToDouble(string_value, &double_value))) {
101         return std::unique_ptr<base::Value>(new base::Value(double_value));
102       }
103       break;
104     }
105     case base::Value::Type::LIST: {
106       // Lists are encoded as subkeys with numbered value in the registry
107       // (non-numerical keys are ignored).
108       const base::DictionaryValue* dict = nullptr;
109       if (value.GetAsDictionary(&dict)) {
110         std::unique_ptr<base::ListValue> result(new base::ListValue());
111         for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd();
112              it.Advance()) {
113           if (!IsKeyNumerical(it.key()))
114             continue;
115           std::unique_ptr<base::Value> converted =
116               ConvertRegistryValue(it.value(), schema.GetItems());
117           if (converted)
118             result->Append(std::move(converted));
119         }
120         return std::move(result);
121       }
122       // Fall through in order to accept lists encoded as JSON strings.
123       FALLTHROUGH;
124     }
125     case base::Value::Type::DICTIONARY: {
126       // Dictionaries may be encoded as JSON strings.
127       if (value.GetAsString(&string_value)) {
128         std::unique_ptr<base::Value> result =
129             base::JSONReader::Read(string_value);
130         if (result && result->type() == schema.type())
131           return result;
132       }
133       break;
134     }
135     case base::Value::Type::STRING:
136     case base::Value::Type::BINARY:
137       // No conversion possible.
138       break;
139   }
140 
141   LOG(WARNING) << "Failed to convert " << value.type() << " to "
142                << schema.type();
143   return nullptr;
144 }
145 
operator ()(const std::string & a,const std::string & b) const146 bool CaseInsensitiveStringCompare::operator()(const std::string& a,
147                                               const std::string& b) const {
148   return base::CompareCaseInsensitiveASCII(a, b) < 0;
149 }
150 
RegistryDict()151 RegistryDict::RegistryDict() {}
152 
~RegistryDict()153 RegistryDict::~RegistryDict() {
154   ClearKeys();
155   ClearValues();
156 }
157 
GetKey(const std::string & name)158 RegistryDict* RegistryDict::GetKey(const std::string& name) {
159   KeyMap::iterator entry = keys_.find(name);
160   return entry != keys_.end() ? entry->second.get() : nullptr;
161 }
162 
GetKey(const std::string & name) const163 const RegistryDict* RegistryDict::GetKey(const std::string& name) const {
164   KeyMap::const_iterator entry = keys_.find(name);
165   return entry != keys_.end() ? entry->second.get() : nullptr;
166 }
167 
SetKey(const std::string & name,std::unique_ptr<RegistryDict> dict)168 void RegistryDict::SetKey(const std::string& name,
169                           std::unique_ptr<RegistryDict> dict) {
170   if (!dict) {
171     RemoveKey(name);
172     return;
173   }
174 
175   keys_[name] = std::move(dict);
176 }
177 
RemoveKey(const std::string & name)178 std::unique_ptr<RegistryDict> RegistryDict::RemoveKey(const std::string& name) {
179   std::unique_ptr<RegistryDict> result;
180   KeyMap::iterator entry = keys_.find(name);
181   if (entry != keys_.end()) {
182     result = std::move(entry->second);
183     keys_.erase(entry);
184   }
185   return result;
186 }
187 
ClearKeys()188 void RegistryDict::ClearKeys() {
189   keys_.clear();
190 }
191 
GetValue(const std::string & name)192 base::Value* RegistryDict::GetValue(const std::string& name) {
193   ValueMap::iterator entry = values_.find(name);
194   return entry != values_.end() ? entry->second.get() : nullptr;
195 }
196 
GetValue(const std::string & name) const197 const base::Value* RegistryDict::GetValue(const std::string& name) const {
198   ValueMap::const_iterator entry = values_.find(name);
199   return entry != values_.end() ? entry->second.get() : nullptr;
200 }
201 
SetValue(const std::string & name,std::unique_ptr<base::Value> dict)202 void RegistryDict::SetValue(const std::string& name,
203                             std::unique_ptr<base::Value> dict) {
204   if (!dict) {
205     RemoveValue(name);
206     return;
207   }
208 
209   values_[name] = std::move(dict);
210 }
211 
RemoveValue(const std::string & name)212 std::unique_ptr<base::Value> RegistryDict::RemoveValue(
213     const std::string& name) {
214   std::unique_ptr<base::Value> result;
215   ValueMap::iterator entry = values_.find(name);
216   if (entry != values_.end()) {
217     result = std::move(entry->second);
218     values_.erase(entry);
219   }
220   return result;
221 }
222 
ClearValues()223 void RegistryDict::ClearValues() {
224   values_.clear();
225 }
226 
Merge(const RegistryDict & other)227 void RegistryDict::Merge(const RegistryDict& other) {
228   for (KeyMap::const_iterator entry(other.keys_.begin());
229        entry != other.keys_.end(); ++entry) {
230     std::unique_ptr<RegistryDict>& subdict = keys_[entry->first];
231     if (!subdict)
232       subdict = std::make_unique<RegistryDict>();
233     subdict->Merge(*entry->second);
234   }
235 
236   for (ValueMap::const_iterator entry(other.values_.begin());
237        entry != other.values_.end(); ++entry) {
238     SetValue(entry->first, entry->second->CreateDeepCopy());
239   }
240 }
241 
Swap(RegistryDict * other)242 void RegistryDict::Swap(RegistryDict* other) {
243   keys_.swap(other->keys_);
244   values_.swap(other->values_);
245 }
246 
247 #if defined(OS_WIN)
ReadRegistry(HKEY hive,const base::string16 & root)248 void RegistryDict::ReadRegistry(HKEY hive, const base::string16& root) {
249   ClearKeys();
250   ClearValues();
251 
252   // First, read all the values of the key.
253   for (RegistryValueIterator it(hive, root.c_str()); it.Valid(); ++it) {
254     const std::string name = base::UTF16ToUTF8(it.Name());
255     switch (it.Type()) {
256       case REG_SZ:
257       case REG_EXPAND_SZ:
258         SetValue(name, std::unique_ptr<base::Value>(
259                            new base::Value(base::UTF16ToUTF8(it.Value()))));
260         continue;
261       case REG_DWORD_LITTLE_ENDIAN:
262       case REG_DWORD_BIG_ENDIAN:
263         if (it.ValueSize() == sizeof(DWORD)) {
264           DWORD dword_value = *(reinterpret_cast<const DWORD*>(it.Value()));
265           if (it.Type() == REG_DWORD_BIG_ENDIAN)
266             dword_value = base::NetToHost32(dword_value);
267           else
268             dword_value = base::ByteSwapToLE32(dword_value);
269           SetValue(name, std::unique_ptr<base::Value>(
270                              new base::Value(static_cast<int>(dword_value))));
271           continue;
272         }
273         FALLTHROUGH;
274       case REG_NONE:
275       case REG_LINK:
276       case REG_MULTI_SZ:
277       case REG_RESOURCE_LIST:
278       case REG_FULL_RESOURCE_DESCRIPTOR:
279       case REG_RESOURCE_REQUIREMENTS_LIST:
280       case REG_QWORD_LITTLE_ENDIAN:
281         // Unsupported type, message gets logged below.
282         break;
283     }
284 
285     LOG(WARNING) << "Failed to read hive " << hive << " at " << root << "\\"
286                  << name << " type " << it.Type();
287   }
288 
289   // Recurse for all subkeys.
290   for (RegistryKeyIterator it(hive, root.c_str()); it.Valid(); ++it) {
291     std::string name(base::UTF16ToUTF8(it.Name()));
292     std::unique_ptr<RegistryDict> subdict(new RegistryDict());
293     subdict->ReadRegistry(hive, root + L"\\" + it.Name());
294     SetKey(name, std::move(subdict));
295   }
296 }
297 
ConvertToJSON(const Schema & schema) const298 std::unique_ptr<base::Value> RegistryDict::ConvertToJSON(
299     const Schema& schema) const {
300   base::Value::Type type =
301       schema.valid() ? schema.type() : base::Value::Type::DICTIONARY;
302   switch (type) {
303     case base::Value::Type::DICTIONARY: {
304       std::unique_ptr<base::DictionaryValue> result(
305           new base::DictionaryValue());
306       for (RegistryDict::ValueMap::const_iterator entry(values_.begin());
307            entry != values_.end(); ++entry) {
308         Schema subschema =
309             schema.valid() ? schema.GetProperty(entry->first) : Schema();
310         std::unique_ptr<base::Value> converted =
311             ConvertRegistryValue(*entry->second, subschema);
312         if (converted)
313           result->SetWithoutPathExpansion(entry->first, std::move(converted));
314       }
315       for (RegistryDict::KeyMap::const_iterator entry(keys_.begin());
316            entry != keys_.end(); ++entry) {
317         Schema subschema =
318             schema.valid() ? schema.GetProperty(entry->first) : Schema();
319         std::unique_ptr<base::Value> converted =
320             entry->second->ConvertToJSON(subschema);
321         if (converted)
322           result->SetWithoutPathExpansion(entry->first, std::move(converted));
323       }
324       return std::move(result);
325     }
326     case base::Value::Type::LIST: {
327       std::unique_ptr<base::ListValue> result(new base::ListValue());
328       Schema item_schema = schema.valid() ? schema.GetItems() : Schema();
329       for (RegistryDict::KeyMap::const_iterator entry(keys_.begin());
330            entry != keys_.end(); ++entry) {
331         if (!IsKeyNumerical(entry->first))
332           continue;
333         std::unique_ptr<base::Value> converted =
334             entry->second->ConvertToJSON(item_schema);
335         if (converted)
336           result->Append(std::move(converted));
337       }
338       for (RegistryDict::ValueMap::const_iterator entry(values_.begin());
339            entry != values_.end(); ++entry) {
340         if (!IsKeyNumerical(entry->first))
341           continue;
342         std::unique_ptr<base::Value> converted =
343             ConvertRegistryValue(*entry->second, item_schema);
344         if (converted)
345           result->Append(std::move(converted));
346       }
347       return std::move(result);
348     }
349     default:
350       LOG(WARNING) << "Can't convert registry key to schema type " << type;
351   }
352 
353   return nullptr;
354 }
355 #endif  // #if defined(OS_WIN)
356 }  // namespace policy
357