Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chromeos / network / onc / onc_validator.cc
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 #include "chromeos/network/onc/onc_validator.h"
6
7 #include <algorithm>
8 #include <string>
9
10 #include "base/json/json_writer.h"
11 #include "base/logging.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_util.h"
14 #include "base/values.h"
15 #include "chromeos/network/onc/onc_signature.h"
16 #include "components/onc/onc_constants.h"
17
18 namespace chromeos {
19 namespace onc {
20
21 namespace {
22
23 // Copied from policy/configuration_policy_handler.cc.
24 // TODO(pneubeck): move to a common place like base/.
25 std::string ValueTypeToString(base::Value::Type type) {
26   static const char* strings[] = {
27     "null",
28     "boolean",
29     "integer",
30     "double",
31     "string",
32     "binary",
33     "dictionary",
34     "list"
35   };
36   CHECK(static_cast<size_t>(type) < arraysize(strings));
37   return strings[type];
38 }
39
40 }  // namespace
41
42 Validator::Validator(bool error_on_unknown_field,
43                      bool error_on_wrong_recommended,
44                      bool error_on_missing_field,
45                      bool managed_onc)
46     : error_on_unknown_field_(error_on_unknown_field),
47       error_on_wrong_recommended_(error_on_wrong_recommended),
48       error_on_missing_field_(error_on_missing_field),
49       managed_onc_(managed_onc),
50       onc_source_(::onc::ONC_SOURCE_NONE) {}
51
52 Validator::~Validator() {}
53
54 scoped_ptr<base::DictionaryValue> Validator::ValidateAndRepairObject(
55     const OncValueSignature* object_signature,
56     const base::DictionaryValue& onc_object,
57     Result* result) {
58   CHECK(object_signature != NULL);
59   *result = VALID;
60   error_or_warning_found_ = false;
61   bool error = false;
62   scoped_ptr<base::Value> result_value =
63       MapValue(*object_signature, onc_object, &error);
64   if (error) {
65     *result = INVALID;
66     result_value.reset();
67   } else if (error_or_warning_found_) {
68     *result = VALID_WITH_WARNINGS;
69   }
70   // The return value should be NULL if, and only if, |result| equals INVALID.
71   DCHECK_EQ(result_value.get() == NULL, *result == INVALID);
72
73   base::DictionaryValue* result_dict = NULL;
74   if (result_value.get() != NULL) {
75     result_value.release()->GetAsDictionary(&result_dict);
76     CHECK(result_dict != NULL);
77   }
78
79   return make_scoped_ptr(result_dict);
80 }
81
82 scoped_ptr<base::Value> Validator::MapValue(const OncValueSignature& signature,
83                                             const base::Value& onc_value,
84                                             bool* error) {
85   if (onc_value.GetType() != signature.onc_type) {
86     LOG(ERROR) << MessageHeader() << "Found value '" << onc_value
87                << "' of type '" << ValueTypeToString(onc_value.GetType())
88                << "', but type '" << ValueTypeToString(signature.onc_type)
89                << "' is required.";
90     error_or_warning_found_ = *error = true;
91     return scoped_ptr<base::Value>();
92   }
93
94   scoped_ptr<base::Value> repaired =
95       Mapper::MapValue(signature, onc_value, error);
96   if (repaired.get() != NULL)
97     CHECK_EQ(repaired->GetType(), signature.onc_type);
98   return repaired.Pass();
99 }
100
101 scoped_ptr<base::DictionaryValue> Validator::MapObject(
102     const OncValueSignature& signature,
103     const base::DictionaryValue& onc_object,
104     bool* error) {
105   scoped_ptr<base::DictionaryValue> repaired(new base::DictionaryValue);
106
107   bool valid = ValidateObjectDefault(signature, onc_object, repaired.get());
108   if (valid) {
109     if (&signature == &kToplevelConfigurationSignature)
110       valid = ValidateToplevelConfiguration(repaired.get());
111     else if (&signature == &kNetworkConfigurationSignature)
112       valid = ValidateNetworkConfiguration(repaired.get());
113     else if (&signature == &kEthernetSignature)
114       valid = ValidateEthernet(repaired.get());
115     else if (&signature == &kIPConfigSignature)
116       valid = ValidateIPConfig(repaired.get());
117     else if (&signature == &kWiFiSignature)
118       valid = ValidateWiFi(repaired.get());
119     else if (&signature == &kVPNSignature)
120       valid = ValidateVPN(repaired.get());
121     else if (&signature == &kIPsecSignature)
122       valid = ValidateIPsec(repaired.get());
123     else if (&signature == &kOpenVPNSignature)
124       valid = ValidateOpenVPN(repaired.get());
125     else if (&signature == &kVerifyX509Signature)
126       valid = ValidateVerifyX509(repaired.get());
127     else if (&signature == &kCertificatePatternSignature)
128       valid = ValidateCertificatePattern(repaired.get());
129     else if (&signature == &kProxySettingsSignature)
130       valid = ValidateProxySettings(repaired.get());
131     else if (&signature == &kProxyLocationSignature)
132       valid = ValidateProxyLocation(repaired.get());
133     else if (&signature == &kEAPSignature)
134       valid = ValidateEAP(repaired.get());
135     else if (&signature == &kCertificateSignature)
136       valid = ValidateCertificate(repaired.get());
137   }
138
139   if (valid) {
140     return repaired.Pass();
141   } else {
142     DCHECK(error_or_warning_found_);
143     error_or_warning_found_ = *error = true;
144     return scoped_ptr<base::DictionaryValue>();
145   }
146 }
147
148 scoped_ptr<base::Value> Validator::MapField(
149     const std::string& field_name,
150     const OncValueSignature& object_signature,
151     const base::Value& onc_value,
152     bool* found_unknown_field,
153     bool* error) {
154   path_.push_back(field_name);
155   bool current_field_unknown = false;
156   scoped_ptr<base::Value> result = Mapper::MapField(
157       field_name, object_signature, onc_value, &current_field_unknown, error);
158
159   DCHECK_EQ(field_name, path_.back());
160   path_.pop_back();
161
162   if (current_field_unknown) {
163     error_or_warning_found_ = *found_unknown_field = true;
164     std::string message = MessageHeader() + "Field name '" + field_name +
165         "' is unknown.";
166     if (error_on_unknown_field_)
167       LOG(ERROR) << message;
168     else
169       LOG(WARNING) << message;
170   }
171
172   return result.Pass();
173 }
174
175 scoped_ptr<base::ListValue> Validator::MapArray(
176     const OncValueSignature& array_signature,
177     const base::ListValue& onc_array,
178     bool* nested_error) {
179   bool nested_error_in_current_array = false;
180   scoped_ptr<base::ListValue> result = Mapper::MapArray(
181       array_signature, onc_array, &nested_error_in_current_array);
182
183   // Drop individual networks and certificates instead of rejecting all of
184   // the configuration.
185   if (nested_error_in_current_array &&
186       &array_signature != &kNetworkConfigurationListSignature &&
187       &array_signature != &kCertificateListSignature) {
188     *nested_error = nested_error_in_current_array;
189   }
190   return result.Pass();
191 }
192
193 scoped_ptr<base::Value> Validator::MapEntry(int index,
194                                             const OncValueSignature& signature,
195                                             const base::Value& onc_value,
196                                             bool* error) {
197   std::string str = base::IntToString(index);
198   path_.push_back(str);
199   scoped_ptr<base::Value> result =
200       Mapper::MapEntry(index, signature, onc_value, error);
201   DCHECK_EQ(str, path_.back());
202   path_.pop_back();
203   return result.Pass();
204 }
205
206 bool Validator::ValidateObjectDefault(const OncValueSignature& signature,
207                                       const base::DictionaryValue& onc_object,
208                                       base::DictionaryValue* result) {
209   bool found_unknown_field = false;
210   bool nested_error_occured = false;
211   MapFields(signature, onc_object, &found_unknown_field, &nested_error_occured,
212             result);
213
214   if (found_unknown_field && error_on_unknown_field_) {
215     DVLOG(1) << "Unknown field names are errors: Aborting.";
216     return false;
217   }
218
219   if (nested_error_occured)
220     return false;
221
222   return ValidateRecommendedField(signature, result);
223 }
224
225 bool Validator::ValidateRecommendedField(
226     const OncValueSignature& object_signature,
227     base::DictionaryValue* result) {
228   CHECK(result != NULL);
229
230   scoped_ptr<base::ListValue> recommended;
231   scoped_ptr<base::Value> recommended_value;
232   // This remove passes ownership to |recommended_value|.
233   if (!result->RemoveWithoutPathExpansion(::onc::kRecommended,
234                                           &recommended_value)) {
235     return true;
236   }
237   base::ListValue* recommended_list = NULL;
238   recommended_value.release()->GetAsList(&recommended_list);
239   CHECK(recommended_list);
240
241   recommended.reset(recommended_list);
242
243   if (!managed_onc_) {
244     error_or_warning_found_ = true;
245     LOG(WARNING) << MessageHeader() << "Found the field '"
246                  << ::onc::kRecommended
247                  << "' in an unmanaged ONC. Removing it.";
248     return true;
249   }
250
251   scoped_ptr<base::ListValue> repaired_recommended(new base::ListValue);
252   for (base::ListValue::iterator it = recommended->begin();
253        it != recommended->end(); ++it) {
254     std::string field_name;
255     if (!(*it)->GetAsString(&field_name)) {
256       NOTREACHED();
257       continue;
258     }
259
260     const OncFieldSignature* field_signature =
261         GetFieldSignature(object_signature, field_name);
262
263     bool found_error = false;
264     std::string error_cause;
265     if (field_signature == NULL) {
266       found_error = true;
267       error_cause = "unknown";
268     } else if (field_signature->value_signature->onc_type ==
269                base::Value::TYPE_DICTIONARY) {
270       found_error = true;
271       error_cause = "dictionary-typed";
272     }
273
274     if (found_error) {
275       error_or_warning_found_ = true;
276       path_.push_back(::onc::kRecommended);
277       std::string message = MessageHeader() + "The " + error_cause +
278           " field '" + field_name + "' cannot be recommended.";
279       path_.pop_back();
280       if (error_on_wrong_recommended_) {
281         LOG(ERROR) << message;
282         return false;
283       } else {
284         LOG(WARNING) << message;
285         continue;
286       }
287     }
288
289     repaired_recommended->Append((*it)->DeepCopy());
290   }
291
292   result->Set(::onc::kRecommended, repaired_recommended.release());
293   return true;
294 }
295
296 namespace {
297
298 std::string JoinStringRange(const char** range_begin,
299                             const char** range_end,
300                             const std::string& separator) {
301   std::vector<std::string> string_vector;
302   std::copy(range_begin, range_end, std::back_inserter(string_vector));
303   return JoinString(string_vector, separator);
304 }
305
306 }  // namespace
307
308 bool Validator::FieldExistsAndHasNoValidValue(
309     const base::DictionaryValue& object,
310     const std::string& field_name,
311     const char** valid_values) {
312   std::string actual_value;
313   if (!object.GetStringWithoutPathExpansion(field_name, &actual_value))
314     return false;
315
316   const char** it = valid_values;
317   for (; *it != NULL; ++it) {
318     if (actual_value == *it)
319       return false;
320   }
321   error_or_warning_found_ = true;
322   std::string valid_values_str =
323       "[" + JoinStringRange(valid_values, it, ", ") + "]";
324   path_.push_back(field_name);
325   LOG(ERROR) << MessageHeader() << "Found value '" << actual_value <<
326       "', but expected one of the values " << valid_values_str;
327   path_.pop_back();
328   return true;
329 }
330
331 bool Validator::FieldExistsAndIsNotInRange(const base::DictionaryValue& object,
332                                            const std::string& field_name,
333                                            int lower_bound,
334                                            int upper_bound) {
335   int actual_value;
336   if (!object.GetIntegerWithoutPathExpansion(field_name, &actual_value) ||
337       (lower_bound <= actual_value && actual_value <= upper_bound)) {
338     return false;
339   }
340   error_or_warning_found_ = true;
341   path_.push_back(field_name);
342   LOG(ERROR) << MessageHeader() << "Found value '" << actual_value
343              << "', but expected a value in the range [" << lower_bound
344              << ", " << upper_bound << "] (boundaries inclusive)";
345   path_.pop_back();
346   return true;
347 }
348
349 bool Validator::FieldExistsAndIsEmpty(const base::DictionaryValue& object,
350                                       const std::string& field_name) {
351   const base::Value* value = NULL;
352   if (!object.GetWithoutPathExpansion(field_name, &value))
353     return false;
354
355   std::string str;
356   const base::ListValue* list = NULL;
357   if (value->GetAsString(&str)) {
358     if (!str.empty())
359       return false;
360   } else if (value->GetAsList(&list)) {
361     if (!list->empty())
362       return false;
363   } else {
364     NOTREACHED();
365     return false;
366   }
367
368   error_or_warning_found_ = true;
369   path_.push_back(field_name);
370   LOG(ERROR) << MessageHeader() << "Found an empty string, but expected a "
371              << "non-empty string.";
372   path_.pop_back();
373   return true;
374 }
375
376 bool Validator::RequireField(const base::DictionaryValue& dict,
377                              const std::string& field_name) {
378   if (dict.HasKey(field_name))
379     return true;
380   error_or_warning_found_ = true;
381   std::string message = MessageHeader() + "The required field '" + field_name +
382       "' is missing.";
383   if (error_on_missing_field_)
384     LOG(ERROR) << message;
385   else
386     LOG(WARNING) << message;
387   return false;
388 }
389
390 bool Validator::CheckGuidIsUniqueAndAddToSet(const base::DictionaryValue& dict,
391                                              const std::string& key_guid,
392                                              std::set<std::string> *guids) {
393   std::string guid;
394   if (dict.GetStringWithoutPathExpansion(key_guid, &guid)) {
395     if (guids->count(guid) != 0) {
396       error_or_warning_found_ = true;
397       LOG(ERROR) << MessageHeader() << "Found a duplicate GUID " << guid << ".";
398       return false;
399     }
400     guids->insert(guid);
401   }
402   return true;
403 }
404
405 bool Validator::IsCertPatternInDevicePolicy(const std::string& cert_type) {
406   if (cert_type == ::onc::certificate::kPattern &&
407       onc_source_ == ::onc::ONC_SOURCE_DEVICE_POLICY) {
408     error_or_warning_found_ = true;
409     LOG(ERROR) << MessageHeader() << "Client certificate patterns are "
410                << "prohibited in ONC device policies.";
411     return true;
412   }
413   return false;
414 }
415
416 bool Validator::IsGlobalNetworkConfigInUserImport(
417     const base::DictionaryValue& onc_object) {
418   if (onc_source_ == ::onc::ONC_SOURCE_USER_IMPORT &&
419       onc_object.HasKey(::onc::toplevel_config::kGlobalNetworkConfiguration)) {
420     error_or_warning_found_ = true;
421     LOG(ERROR) << MessageHeader() << "GlobalNetworkConfiguration is prohibited "
422                << "in ONC user imports";
423     return true;
424   }
425   return false;
426 }
427
428 bool Validator::ValidateToplevelConfiguration(base::DictionaryValue* result) {
429   using namespace ::onc::toplevel_config;
430
431   static const char* kValidTypes[] = { kUnencryptedConfiguration,
432                                        kEncryptedConfiguration,
433                                        NULL };
434   if (FieldExistsAndHasNoValidValue(*result, kType, kValidTypes))
435     return false;
436
437   bool all_required_exist = true;
438
439   // Not part of the ONC spec yet:
440   // We don't require the type field and default to UnencryptedConfiguration.
441   std::string type = kUnencryptedConfiguration;
442   result->GetStringWithoutPathExpansion(kType, &type);
443   if (type == kUnencryptedConfiguration &&
444       !result->HasKey(kNetworkConfigurations) &&
445       !result->HasKey(kCertificates)) {
446     error_or_warning_found_ = true;
447     std::string message = MessageHeader() + "Neither the field '" +
448         kNetworkConfigurations + "' nor '" + kCertificates +
449         "is present, but at least one is required.";
450     if (error_on_missing_field_)
451       LOG(ERROR) << message;
452     else
453       LOG(WARNING) << message;
454     all_required_exist = false;
455   }
456
457   if (IsGlobalNetworkConfigInUserImport(*result))
458     return false;
459
460   return !error_on_missing_field_ || all_required_exist;
461 }
462
463 bool Validator::ValidateNetworkConfiguration(base::DictionaryValue* result) {
464   using namespace ::onc::network_config;
465
466   static const char* kValidTypes[] = { ::onc::network_type::kEthernet,
467                                        ::onc::network_type::kVPN,
468                                        ::onc::network_type::kWiFi,
469                                        ::onc::network_type::kCellular,
470                                        NULL };
471   if (FieldExistsAndHasNoValidValue(*result, kType, kValidTypes) ||
472       FieldExistsAndIsEmpty(*result, kGUID)) {
473     return false;
474   }
475
476   if (!CheckGuidIsUniqueAndAddToSet(*result, kGUID, &network_guids_))
477     return false;
478
479   bool all_required_exist = RequireField(*result, kGUID);
480
481   bool remove = false;
482   result->GetBooleanWithoutPathExpansion(::onc::kRemove, &remove);
483   if (!remove) {
484     all_required_exist &=
485         RequireField(*result, kName) && RequireField(*result, kType);
486
487     std::string type;
488     result->GetStringWithoutPathExpansion(kType, &type);
489
490     // Prohibit anything but WiFi and Ethernet for device-level policy (which
491     // corresponds to shared networks). See also http://crosbug.com/28741.
492     if (onc_source_ == ::onc::ONC_SOURCE_DEVICE_POLICY &&
493         type != ::onc::network_type::kWiFi &&
494         type != ::onc::network_type::kEthernet) {
495       error_or_warning_found_ = true;
496       LOG(ERROR) << MessageHeader() << "Networks of type '"
497                  << type << "' are prohibited in ONC device policies.";
498       return false;
499     }
500
501     if (type == ::onc::network_type::kWiFi) {
502       all_required_exist &= RequireField(*result, ::onc::network_config::kWiFi);
503     } else if (type == ::onc::network_type::kEthernet) {
504       all_required_exist &=
505           RequireField(*result, ::onc::network_config::kEthernet);
506     } else if (type == ::onc::network_type::kCellular) {
507       all_required_exist &=
508           RequireField(*result, ::onc::network_config::kCellular);
509     } else if (type == ::onc::network_type::kVPN) {
510       all_required_exist &= RequireField(*result, ::onc::network_config::kVPN);
511     } else if (!type.empty()) {
512       NOTREACHED();
513     }
514   }
515
516   return !error_on_missing_field_ || all_required_exist;
517 }
518
519 bool Validator::ValidateEthernet(base::DictionaryValue* result) {
520   using namespace ::onc::ethernet;
521
522   static const char* kValidAuthentications[] = { kNone, k8021X, NULL };
523   if (FieldExistsAndHasNoValidValue(
524           *result, kAuthentication, kValidAuthentications)) {
525     return false;
526   }
527
528   bool all_required_exist = true;
529   std::string auth;
530   result->GetStringWithoutPathExpansion(kAuthentication, &auth);
531   if (auth == k8021X)
532     all_required_exist &= RequireField(*result, kEAP);
533
534   return !error_on_missing_field_ || all_required_exist;
535 }
536
537 bool Validator::ValidateIPConfig(base::DictionaryValue* result) {
538   using namespace ::onc::ipconfig;
539
540   static const char* kValidTypes[] = { kIPv4, kIPv6, NULL };
541   if (FieldExistsAndHasNoValidValue(
542           *result, ::onc::ipconfig::kType, kValidTypes))
543     return false;
544
545   std::string type;
546   result->GetStringWithoutPathExpansion(::onc::ipconfig::kType, &type);
547   int lower_bound = 1;
548   // In case of missing type, choose higher upper_bound.
549   int upper_bound = (type == kIPv4) ? 32 : 128;
550   if (FieldExistsAndIsNotInRange(
551           *result, kRoutingPrefix, lower_bound, upper_bound)) {
552     return false;
553   }
554
555   bool all_required_exist = RequireField(*result, kIPAddress) &&
556                             RequireField(*result, kRoutingPrefix) &&
557                             RequireField(*result, ::onc::ipconfig::kType);
558
559   return !error_on_missing_field_ || all_required_exist;
560 }
561
562 bool Validator::ValidateWiFi(base::DictionaryValue* result) {
563   using namespace ::onc::wifi;
564
565   static const char* kValidSecurities[] =
566       { kNone, kWEP_PSK, kWEP_8021X, kWPA_PSK, kWPA_EAP, NULL };
567   if (FieldExistsAndHasNoValidValue(*result, kSecurity, kValidSecurities))
568     return false;
569
570   bool all_required_exist =
571       RequireField(*result, kSecurity) && RequireField(*result, kSSID);
572
573   std::string security;
574   result->GetStringWithoutPathExpansion(kSecurity, &security);
575   if (security == kWEP_8021X || security == kWPA_EAP)
576     all_required_exist &= RequireField(*result, kEAP);
577   else if (security == kWEP_PSK || security == kWPA_PSK)
578     all_required_exist &= RequireField(*result, kPassphrase);
579
580   return !error_on_missing_field_ || all_required_exist;
581 }
582
583 bool Validator::ValidateVPN(base::DictionaryValue* result) {
584   using namespace ::onc::vpn;
585
586   static const char* kValidTypes[] =
587       { kIPsec, kTypeL2TP_IPsec, kOpenVPN, NULL };
588   if (FieldExistsAndHasNoValidValue(*result, ::onc::vpn::kType, kValidTypes))
589     return false;
590
591   bool all_required_exist = RequireField(*result, ::onc::vpn::kType);
592   std::string type;
593   result->GetStringWithoutPathExpansion(::onc::vpn::kType, &type);
594   if (type == kOpenVPN) {
595     all_required_exist &= RequireField(*result, kOpenVPN);
596   } else if (type == kIPsec) {
597     all_required_exist &= RequireField(*result, kIPsec);
598   } else if (type == kTypeL2TP_IPsec) {
599     all_required_exist &=
600         RequireField(*result, kIPsec) && RequireField(*result, kL2TP);
601   }
602
603   return !error_on_missing_field_ || all_required_exist;
604 }
605
606 bool Validator::ValidateIPsec(base::DictionaryValue* result) {
607   using namespace ::onc::ipsec;
608   using namespace ::onc::certificate;
609
610   static const char* kValidAuthentications[] = { kPSK, kCert, NULL };
611   static const char* kValidCertTypes[] = { kRef, kPattern, NULL };
612   if (FieldExistsAndHasNoValidValue(
613           *result, kAuthenticationType, kValidAuthentications) ||
614       FieldExistsAndHasNoValidValue(
615           *result, ::onc::vpn::kClientCertType, kValidCertTypes) ||
616       FieldExistsAndIsEmpty(*result, kServerCARefs)) {
617     return false;
618   }
619
620   if (result->HasKey(kServerCARefs) && result->HasKey(kServerCARef)) {
621     error_or_warning_found_ = true;
622     LOG(ERROR) << MessageHeader() << "At most one of " << kServerCARefs
623                << " and " << kServerCARef << " can be set.";
624     return false;
625   }
626
627   bool all_required_exist = RequireField(*result, kAuthenticationType) &&
628                             RequireField(*result, kIKEVersion);
629   std::string auth;
630   result->GetStringWithoutPathExpansion(kAuthenticationType, &auth);
631   bool has_server_ca_cert =
632       result->HasKey(kServerCARefs) || result->HasKey(kServerCARef);
633   if (auth == kCert) {
634     all_required_exist &= RequireField(*result, ::onc::vpn::kClientCertType);
635     if (!has_server_ca_cert) {
636       all_required_exist = false;
637       error_or_warning_found_ = true;
638       std::string message = MessageHeader() + "The required field '" +
639                             kServerCARefs + "' is missing.";
640       if (error_on_missing_field_)
641         LOG(ERROR) << message;
642       else
643         LOG(WARNING) << message;
644     }
645   } else if (has_server_ca_cert) {
646     error_or_warning_found_ = true;
647     LOG(ERROR) << MessageHeader() << kServerCARefs << " (or " << kServerCARef
648                << ") can only be set if " << kAuthenticationType
649                << " is set to " << kCert << ".";
650     return false;
651   }
652
653   std::string cert_type;
654   result->GetStringWithoutPathExpansion(::onc::vpn::kClientCertType,
655                                         &cert_type);
656
657   if (IsCertPatternInDevicePolicy(cert_type))
658     return false;
659
660   if (cert_type == kPattern)
661     all_required_exist &= RequireField(*result, ::onc::vpn::kClientCertPattern);
662   else if (cert_type == kRef)
663     all_required_exist &= RequireField(*result, ::onc::vpn::kClientCertRef);
664
665   return !error_on_missing_field_ || all_required_exist;
666 }
667
668 bool Validator::ValidateOpenVPN(base::DictionaryValue* result) {
669   using namespace ::onc::openvpn;
670   using namespace ::onc::certificate;
671
672   static const char* kValidAuthRetryValues[] =
673       { ::onc::openvpn::kNone, kInteract, kNoInteract, NULL };
674   static const char* kValidCertTypes[] =
675       { ::onc::certificate::kNone, kRef, kPattern, NULL };
676   static const char* kValidCertTlsValues[] =
677       { ::onc::openvpn::kNone, ::onc::openvpn::kServer, NULL };
678
679   if (FieldExistsAndHasNoValidValue(
680           *result, kAuthRetry, kValidAuthRetryValues) ||
681       FieldExistsAndHasNoValidValue(
682           *result, ::onc::vpn::kClientCertType, kValidCertTypes) ||
683       FieldExistsAndHasNoValidValue(
684           *result, kRemoteCertTLS, kValidCertTlsValues) ||
685       FieldExistsAndIsEmpty(*result, kServerCARefs)) {
686     return false;
687   }
688
689   if (result->HasKey(kServerCARefs) && result->HasKey(kServerCARef)) {
690     error_or_warning_found_ = true;
691     LOG(ERROR) << MessageHeader() << "At most one of " << kServerCARefs
692                << " and " << kServerCARef << " can be set.";
693     return false;
694   }
695
696   bool all_required_exist = RequireField(*result, ::onc::vpn::kClientCertType);
697   std::string cert_type;
698   result->GetStringWithoutPathExpansion(::onc::vpn::kClientCertType,
699                                         &cert_type);
700
701   if (IsCertPatternInDevicePolicy(cert_type))
702     return false;
703
704   if (cert_type == kPattern)
705     all_required_exist &= RequireField(*result, ::onc::vpn::kClientCertPattern);
706   else if (cert_type == kRef)
707     all_required_exist &= RequireField(*result, ::onc::vpn::kClientCertRef);
708
709   return !error_on_missing_field_ || all_required_exist;
710 }
711
712 bool Validator::ValidateVerifyX509(base::DictionaryValue* result) {
713   using namespace ::onc::verify_x509;
714
715   static const char* kValidTypeValues[] =
716     {types::kName, types::kNamePrefix, types::kSubject, NULL};
717
718   if (FieldExistsAndHasNoValidValue(*result, kType, kValidTypeValues))
719     return false;
720
721   bool all_required_exist = RequireField(*result, kName);
722
723   return !error_on_missing_field_ || all_required_exist;
724 }
725
726 bool Validator::ValidateCertificatePattern(base::DictionaryValue* result) {
727   using namespace ::onc::certificate;
728
729   bool all_required_exist = true;
730   if (!result->HasKey(kSubject) && !result->HasKey(kIssuer) &&
731       !result->HasKey(kIssuerCARef)) {
732     error_or_warning_found_ = true;
733     all_required_exist = false;
734     std::string message = MessageHeader() + "None of the fields '" + kSubject +
735         "', '" + kIssuer + "', and '" + kIssuerCARef +
736         "' is present, but at least one is required.";
737     if (error_on_missing_field_)
738       LOG(ERROR) << message;
739     else
740       LOG(WARNING) << message;
741   }
742
743   return !error_on_missing_field_ || all_required_exist;
744 }
745
746 bool Validator::ValidateProxySettings(base::DictionaryValue* result) {
747   using namespace ::onc::proxy;
748
749   static const char* kValidTypes[] = { kDirect, kManual, kPAC, kWPAD, NULL };
750   if (FieldExistsAndHasNoValidValue(*result, ::onc::proxy::kType, kValidTypes))
751     return false;
752
753   bool all_required_exist = RequireField(*result, ::onc::proxy::kType);
754   std::string type;
755   result->GetStringWithoutPathExpansion(::onc::proxy::kType, &type);
756   if (type == kManual)
757     all_required_exist &= RequireField(*result, kManual);
758   else if (type == kPAC)
759     all_required_exist &= RequireField(*result, kPAC);
760
761   return !error_on_missing_field_ || all_required_exist;
762 }
763
764 bool Validator::ValidateProxyLocation(base::DictionaryValue* result) {
765   using namespace ::onc::proxy;
766
767   bool all_required_exist =
768       RequireField(*result, kHost) && RequireField(*result, kPort);
769
770   return !error_on_missing_field_ || all_required_exist;
771 }
772
773 bool Validator::ValidateEAP(base::DictionaryValue* result) {
774   using namespace ::onc::eap;
775   using namespace ::onc::certificate;
776
777   static const char* kValidInnerValues[] =
778       { kAutomatic, kMD5, kMSCHAPv2, kPAP, NULL };
779   static const char* kValidOuterValues[] =
780       { kPEAP, kEAP_TLS, kEAP_TTLS, kLEAP, kEAP_SIM, kEAP_FAST, kEAP_AKA,
781         NULL };
782   static const char* kValidCertTypes[] = { kRef, kPattern, NULL };
783
784   if (FieldExistsAndHasNoValidValue(*result, kInner, kValidInnerValues) ||
785       FieldExistsAndHasNoValidValue(*result, kOuter, kValidOuterValues) ||
786       FieldExistsAndHasNoValidValue(
787           *result, kClientCertType, kValidCertTypes) ||
788       FieldExistsAndIsEmpty(*result, kServerCARefs)) {
789     return false;
790   }
791
792   if (result->HasKey(kServerCARefs) && result->HasKey(kServerCARef)) {
793     error_or_warning_found_ = true;
794     LOG(ERROR) << MessageHeader() << "At most one of " << kServerCARefs
795                << " and " << kServerCARef << " can be set.";
796     return false;
797   }
798
799   bool all_required_exist = RequireField(*result, kOuter);
800   std::string cert_type;
801   result->GetStringWithoutPathExpansion(kClientCertType, &cert_type);
802
803   if (IsCertPatternInDevicePolicy(cert_type))
804     return false;
805
806   if (cert_type == kPattern)
807     all_required_exist &= RequireField(*result, kClientCertPattern);
808   else if (cert_type == kRef)
809     all_required_exist &= RequireField(*result, kClientCertRef);
810
811   return !error_on_missing_field_ || all_required_exist;
812 }
813
814 bool Validator::ValidateCertificate(base::DictionaryValue* result) {
815   using namespace ::onc::certificate;
816
817   static const char* kValidTypes[] = { kClient, kServer, kAuthority, NULL };
818   if (FieldExistsAndHasNoValidValue(*result, kType, kValidTypes) ||
819       FieldExistsAndIsEmpty(*result, kGUID)) {
820     return false;
821   }
822
823   std::string type;
824   result->GetStringWithoutPathExpansion(kType, &type);
825   if (onc_source_ == ::onc::ONC_SOURCE_DEVICE_POLICY &&
826       (type == kServer || type == kAuthority)) {
827     error_or_warning_found_ = true;
828     LOG(ERROR) << MessageHeader() << "Server and authority certificates are "
829                << "prohibited in ONC device policies.";
830     return false;
831   }
832
833   if (!CheckGuidIsUniqueAndAddToSet(*result, kGUID, &certificate_guids_))
834     return false;
835
836   bool all_required_exist = RequireField(*result, kGUID);
837
838   bool remove = false;
839   result->GetBooleanWithoutPathExpansion(::onc::kRemove, &remove);
840   if (!remove) {
841     all_required_exist &= RequireField(*result, kType);
842
843     if (type == kClient)
844       all_required_exist &= RequireField(*result, kPKCS12);
845     else if (type == kServer || type == kAuthority)
846       all_required_exist &= RequireField(*result, kX509);
847   }
848
849   return !error_on_missing_field_ || all_required_exist;
850 }
851
852 std::string Validator::MessageHeader() {
853   std::string path = path_.empty() ? "toplevel" : JoinString(path_, ".");
854   std::string message = "At " + path + ": ";
855   return message;
856 }
857
858 }  // namespace onc
859 }  // namespace chromeos