File: onc_utils.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1119 lines) | stat: -rw-r--r-- 40,819 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/components/onc/onc_utils.h"

#include <string>
#include <vector>

#include "base/base64.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/notreached.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_view_util.h"
#include "base/values.h"
#include "chromeos/components/onc/onc_mapper.h"
#include "chromeos/components/onc/onc_signature.h"
#include "chromeos/components/onc/onc_validator.h"
#include "chromeos/components/onc/variable_expander.h"
#include "components/device_event_log/device_event_log.h"
#include "crypto/aes_cbc.h"
#include "crypto/hmac.h"
#include "crypto/kdf.h"
#include "net/cert/x509_certificate.h"
#include "third_party/boringssl/src/pki/pem.h"

namespace chromeos::onc {
namespace {

using IdToAPNMap = std::map<std::string, const base::Value::Dict*>;

// Error messages that can be reported when decrypting encrypted ONC.
constexpr char kUnableToDecrypt[] = "Unable to decrypt encrypted ONC";
constexpr char kUnableToDecode[] = "Unable to decode encrypted ONC";

bool GetString(const base::Value::Dict& dict,
               const char* key,
               std::string* result) {
  const std::string* value = dict.FindString(key);
  if (!value) {
    return false;
  }
  *result = *value;
  return true;
}

bool GetInt(const base::Value::Dict& dict, const char* key, int* result) {
  const std::optional<int> value = dict.FindInt(key);
  if (!value) {
    return false;
  }
  *result = value.value();
  return true;
}

// Runs |variable_expander.ExpandString| on the field |fieldname| in
// |onc_object|.
void ExpandField(const std::string& fieldname,
                 const VariableExpander& variable_expander,
                 base::Value::Dict* onc_object) {
  std::string* field_value = onc_object->FindString(fieldname);
  if (!field_value) {
    return;
  }
  variable_expander.ExpandString(field_value);
}

bool CanContainPasswordPlaceholder(const std::string& field_name,
                                   const OncValueSignature& object_signature) {
  return (&object_signature == &kEAPSignature &&
          field_name == ::onc::eap::kPassword) ||
         (&object_signature == &kL2TPSignature &&
          field_name == ::onc::l2tp::kPassword);
}

bool IsUserLoginPasswordPlaceholder(const std::string& field_name,
                                    const OncValueSignature& object_signature,
                                    const base::Value& onc_value) {
  if (!CanContainPasswordPlaceholder(field_name, object_signature)) {
    return false;
  }
  DCHECK(onc_value.is_string());
  return onc_value.GetString() ==
         ::onc::substitutes::kPasswordPlaceholderVerbatim;
}

// A |Mapper| for masking sensitive fields (e.g. credentials such as
// passphrases) in ONC.
class OncMaskValues : public Mapper {
 public:
  static base::Value::Dict Mask(const OncValueSignature& signature,
                                const base::Value::Dict& onc_object,
                                const std::string& mask) {
    OncMaskValues masker(mask);
    bool error = false;
    base::Value::Dict result = masker.MapObject(signature, onc_object, &error);
    return result;
  }

 protected:
  explicit OncMaskValues(const std::string& mask) : mask_(mask) {}

  base::Value MapField(const std::string& field_name,
                       const OncValueSignature& object_signature,
                       const base::Value& onc_value,
                       bool* found_unknown_field,
                       bool* error) override {
    if (FieldIsCredential(object_signature, field_name)) {
      // If it's the password field and the substitution string is used, don't
      // mask it.
      if (IsUserLoginPasswordPlaceholder(field_name, object_signature,
                                         onc_value)) {
        return Mapper::MapField(field_name, object_signature, onc_value,
                                found_unknown_field, error);
      }
      return base::Value(mask_);
    } else {
      return Mapper::MapField(field_name, object_signature, onc_value,
                              found_unknown_field, error);
    }
  }

 private:
  // Mask to insert in place of the sensitive values.
  std::string mask_;
};

// Returns a map GUID->PEM of all server and authority certificates defined in
// the Certificates section of ONC, which is passed in as |certificates|.
CertPEMsByGUIDMap GetServerAndCACertsByGUID(
    const base::Value::List& certificates) {
  CertPEMsByGUIDMap certs_by_guid;
  for (const auto& cert_value : certificates) {
    const base::Value::Dict& cert = cert_value.GetDict();

    const std::string* guid = cert.FindString(::onc::certificate::kGUID);
    if (!guid || guid->empty()) {
      NET_LOG(ERROR) << "Certificate with missing or empty GUID.";
      continue;
    }
    const std::string* cert_type = cert.FindString(::onc::certificate::kType);
    DCHECK(cert_type);
    if (*cert_type != ::onc::certificate::kServer &&
        *cert_type != ::onc::certificate::kAuthority) {
      continue;
    }
    const std::string* x509_data = cert.FindString(::onc::certificate::kX509);
    std::string der;
    if (x509_data) {
      der = DecodePEM(*x509_data);
    }
    std::string pem;
    if (der.empty() || !net::X509Certificate::GetPEMEncodedFromDER(der, &pem)) {
      NET_LOG(ERROR) << "Certificate not PEM encoded, GUID: " << *guid;
      continue;
    }
    certs_by_guid[*guid] = pem;
  }

  return certs_by_guid;
}

// Set APN dictionary and associated recommended values to solve the issue
// of setting the APN for managed eSIM profiles (see http://b/295226668) in
// old APN UI.
void SetAPNDictAndRecommendedIfNone(base::Value::Dict& cellular_fields) {
  if (cellular_fields.Find(::onc::cellular::kAPN)) {
    return;
  }

  auto apn_recommended_list = base::Value::List()
                                  .Append(::onc::cellular_apn::kAccessPointName)
                                  .Append(::onc::cellular_apn::kAttach)
                                  .Append(::onc::cellular_apn::kAuthentication)
                                  .Append(::onc::cellular_apn::kUsername)
                                  .Append(::onc::cellular_apn::kPassword);

  base::Value* apn_dict = cellular_fields.Set(
      ::onc::cellular::kAPN, base::Value(base::Value::Type::DICT));
  apn_dict->GetDict().Set(::onc::kRecommended, std::move(apn_recommended_list));
}

// Modify recommended list to include custom APN list field to solve the issue
// of setting the APN for managed eSIM profiles (see http://b/295226668) in
// revamp APN UI.
void AddCustomAPNListToRecommended(base::Value::Dict& cellular_fields) {
  auto* recommended = cellular_fields.Find(::onc::kRecommended);
  if (!recommended) {
    recommended = cellular_fields.Set(::onc::kRecommended,
                                      base::Value(base::Value::Type::LIST));
  }
  for (const auto& field : recommended->GetList()) {
    if (field == ::onc::cellular::kCustomAPNList) {
      return;
    }
  }
  recommended->GetList().Append(::onc::cellular::kCustomAPNList);
}

void FillInCellularDefaultsInOncObject(const OncValueSignature& signature,
                                       base::Value::Dict& onc_object,
                                       bool allow_apn_modification) {
  if (&signature == &kCellularSignature) {
    if (allow_apn_modification) {
      AddCustomAPNListToRecommended(onc_object);
    } else {
      onc_object.Set(::onc::cellular::kCustomAPNList, base::Value::List());
    }
    SetAPNDictAndRecommendedIfNone(onc_object);

    return;
  }

  // The function takes any ONC object and recursively searches until it finds a
  // Cellular dictionary to set the default values.
  for (auto it : onc_object) {
    if (!it.second.is_dict()) {
      continue;
    }

    const OncFieldSignature* field_signature =
        GetFieldSignature(signature, it.first);
    if (!field_signature) {
      continue;
    }

    FillInCellularDefaultsInOncObject(*field_signature->value_signature,
                                      it.second.GetDict(),
                                      allow_apn_modification);
  }
}

// Creates an APN dict with nested recommended field in cellular entries lacking
// an APN dict in |network_configs| list. If |allow_apn_modification| is true,
// "CustomAPNList" is added as a recommended field to the cellular config,
// otherwise, the CustomAPNList field is set to an empty list.
void FillInCellularDefaultsInNetworks(base::Value::List& network_configs,
                                      bool allow_apn_modification) {
  for (auto& network : network_configs) {
    FillInCellularDefaultsInOncObject(kNetworkConfigurationSignature,
                                      network.GetDict(),
                                      allow_apn_modification);
  }
}

// Creates a map from APN IDs to their corresponding configuration dictionaries.
IdToAPNMap BuildIdToAPNMap(const base::Value::List* apn_list) {
  IdToAPNMap apn_map;

  if (!apn_list) {
    return apn_map;
  }

  for (const base::Value& apn_value : *apn_list) {
    const base::Value::Dict& apn_dict = apn_value.GetDict();
    const std::string* apn_id = apn_dict.FindString(::onc::cellular_apn::kId);

    if (apn_id) {
      apn_map.emplace(*apn_id, &apn_dict);
    }
  }

  return apn_map;
}

// Extracts a list of APN dictionaries based on a provided list of APN IDs, such
// that |apn_id_list| is a list of string IDs representing the APNs to extract,
// and |apn_map| is a map of all available APN dictionaries with key being APN
// ID. Returns a base::List if IDs are successfully extracted and the source is
// set successfully, and an std::nullopt otherwise.
std::optional<base::Value::List> ExtractAPNsByIdsAndSetAdminSource(
    const base::Value::List* apn_id_list,
    const IdToAPNMap& apn_map) {
  base::Value::List result = base::Value::List();

  for (const base::Value& apn_id_value : *apn_id_list) {
    const std::string apn_id = apn_id_value.GetString();

    // Find the APN in the map
    auto it = apn_map.find(apn_id);
    if (it == apn_map.end()) {
      NET_LOG(ERROR)
          << "Failed to find an admin provided APN associated to an ID of "
          << apn_id;
      return std::nullopt;
    }
    base::Value::Dict apn_cpy = it->second->Clone();
    apn_cpy.Set(::onc::cellular_apn::kSource,
                ::onc::cellular_apn::kSourceAdmin);

    result.Append(std::move(apn_cpy));
  }

  return result;
}

// Updates a cellular network configuration with custom APN information from
// admin-assigned APNs. Looks for a list of admin-assigned APN IDs in
// |cellular_fields|. If found, it extracts the corresponding APN dictionaries
// from |admin_apn_by_id| and sets the CustomAPNList field in |cellular_fields|.
// Note that if |admin_apn_by_id| is null, no changes are made to
// |cellular_fields|. Also note that each extracted APN will have a
// |::onc::cellular_apn::kSource| of
// |::onc::cellular_apn::kSourceAdmin|. Returns true if |cellular_fields| are
// successfully updated.
bool UpdateCellularFieldsWithAdminApns(base::Value::Dict& cellular_fields,
                                       const IdToAPNMap& admin_apn_by_id) {
  const base::Value::List* admin_apn_id_list =
      cellular_fields.FindList(::onc::cellular::kAdminAssignedAPNIds);
  if (!admin_apn_id_list) {
    return true;
  }

  if (admin_apn_id_list->empty()) {
    cellular_fields.Set(::onc::cellular::kCustomAPNList, base::Value::List());
    return true;
  }

  std::optional<base::Value::List> admin_apns =
      ExtractAPNsByIdsAndSetAdminSource(admin_apn_id_list, admin_apn_by_id);
  if (!admin_apns.has_value()) {
    NET_LOG(ERROR) << "Failed to extract admin APNs";
    return false;
  }

  cellular_fields.Set(::onc::cellular::kCustomAPNList, std::move(*admin_apns));
  return true;
}

bool ConstructAndSetPSIMAdminAPNs(base::Value::Dict& global_network_config,
                                  const IdToAPNMap& admin_apn_by_id) {
  if (admin_apn_by_id.empty()) {
    return true;
  }
  const base::Value::List* psim_admin_apn_id_list =
      global_network_config.FindList(
          ::onc::global_network_config::kPSIMAdminAssignedAPNIds);
  if (!psim_admin_apn_id_list) {
    return true;
  }

  std::optional<base::Value::List> psim_admin_apns =
      ExtractAPNsByIdsAndSetAdminSource(psim_admin_apn_id_list,
                                        admin_apn_by_id);
  if (!psim_admin_apns.has_value()) {
    NET_LOG(ERROR) << "Failed to extract pSIM admin APNs";
    return false;
  }

  global_network_config.Set(
      ::onc::global_network_config::kPSIMAdminAssignedAPNs,
      std::move(*psim_admin_apns));
  return true;
}

// Recursively traverses the |onc_object|, searching for
// cellular dictionaries. If found, it updates the 'CustomAPNList' field within
// the Cellular dictionary using |admin_apn_by_id| if applicable.
//
// The recursion is guided by the |signature|, which defines the structure of
// the ONC object and helps the function determine which fields to traverse.
// Returns true if admin APNs are successfully applied.
bool ApplyAdminApnsToOncObject(const OncValueSignature& signature,
                               base::Value::Dict& onc_object,
                               const IdToAPNMap& admin_apn_by_id) {
  if (&signature == &kCellularSignature) {
    return UpdateCellularFieldsWithAdminApns(onc_object, admin_apn_by_id);
  }

  // The function takes any ONC object and recursively searches until it finds a
  // Cellular dictionary to set the Custom APN List.
  for (auto it : onc_object) {
    if (!it.second.is_dict()) {
      continue;
    }

    const OncFieldSignature* field_signature =
        GetFieldSignature(signature, it.first);
    if (!field_signature) {
      continue;
    }

    if (!ApplyAdminApnsToOncObject(*field_signature->value_signature,
                                   it.second.GetDict(), admin_apn_by_id)) {
      return false;
    }
  }
  return true;
}

// Processes a list of network configurations, identifying those of cellular
// type. For each cellular configuration, it associates and embeds the
// corresponding admin defined APN details found in |admin_apn_by_id|. This is
// achieved by recursively traversing the cellular configuration's structure and
// updating the APN information where applicable.
//
// The function relies on a top-level ONC configuration that contains a list of
// APNs provided by administrators. Cellular networks within the configuration
// may reference these APNs using unique identifiers (IDs).
//
// Ultimately, this function ensures that the cellular networks in the provided
// |network_configs| list are populated with the complete APN configurations
// that they are associated with. Otherwise, it returns false.
bool ConfigureAdminApnsInCellularNetworks(base::Value::List& network_configs,
                                          const IdToAPNMap& admin_apn_by_id) {
  if (admin_apn_by_id.empty()) {
    return true;
  }
  for (auto& network : network_configs) {
    if (!ApplyAdminApnsToOncObject(kNetworkConfigurationSignature,
                                   network.GetDict(), admin_apn_by_id)) {
      return false;
    }
  }
  return true;
}

// Fills HexSSID fields in all entries in the |network_configs| list.
void FillInHexSSIDFieldsInNetworks(base::Value::List& network_configs) {
  for (auto& network : network_configs) {
    FillInHexSSIDFieldsInOncObject(kNetworkConfigurationSignature,
                                   network.GetDict());
  }
}

// Sets HiddenSSID fields in all entries in the |network_configs| list.
void SetHiddenSSIDFieldsInNetworks(base::Value::List& network_configs) {
  for (auto& network : network_configs) {
    SetHiddenSSIDFieldInOncObject(kNetworkConfigurationSignature,
                                  network.GetDict());
  }
}

// Given a GUID->PEM certificate mapping |certs_by_guid|, looks up the PEM
// encoded certificate referenced by |guid_ref|. If a match is found, sets
// |*pem_encoded| to the PEM encoded certificate and returns true. Otherwise,
// returns false.
bool GUIDRefToPEMEncoding(const CertPEMsByGUIDMap& certs_by_guid,
                          const std::string& guid_ref,
                          std::string* pem_encoded) {
  CertPEMsByGUIDMap::const_iterator it = certs_by_guid.find(guid_ref);
  if (it == certs_by_guid.end()) {
    LOG(ERROR) << "Couldn't resolve certificate reference " << guid_ref;
    return false;
  }
  *pem_encoded = it->second;
  if (pem_encoded->empty()) {
    LOG(ERROR) << "Couldn't PEM-encode certificate with GUID " << guid_ref;
    return false;
  }
  return true;
}

// Given a GUID-> PM certificate mapping |certs_by_guid|, attempts to resolve
// the certificate referenced by the |key_guid_ref| field in |onc_object|.
// * If |onc_object| has no |key_guid_ref| field, returns true.
// * If no matching certificate is found in |certs_by_guid|, returns false.
// * If a matching certificate is found, removes the |key_guid_ref| field,
//   fills the |key_pem| field in |onc_object| and returns true.
bool ResolveSingleCertRef(const CertPEMsByGUIDMap& certs_by_guid,
                          const std::string& key_guid_ref,
                          const std::string& key_pem,
                          base::Value::Dict& onc_object) {
  std::string* guid_ref = onc_object.FindString(key_guid_ref);
  if (!guid_ref) {
    return true;
  }

  std::string pem_encoded;
  if (!GUIDRefToPEMEncoding(certs_by_guid, *guid_ref, &pem_encoded)) {
    return false;
  }

  onc_object.Remove(key_guid_ref);
  onc_object.Set(key_pem, pem_encoded);
  return true;
}

// Given a GUID-> PM certificate mapping |certs_by_guid|, attempts to resolve
// the certificates referenced by the list-of-strings field |key_guid_ref_list|
// in |onc_object|.
// * If |key_guid_ref_list| does not exist in |onc_object|, returns true.
// * If any element |key_guid_ref_list| can not be found in |certs_by_guid|,
//   aborts processing and returns false. |onc_object| is unchanged in this
//   case.
// * Otherwise, sets |key_pem_list| to be a list-of-strings field in
//   |onc_object|, containing all PEM encoded resolved certificates in order and
//   returns true.
bool ResolveCertRefList(const CertPEMsByGUIDMap& certs_by_guid,
                        const std::string& key_guid_ref_list,
                        const std::string& key_pem_list,
                        base::Value::Dict& onc_object) {
  const base::Value::List* guid_ref_list =
      onc_object.FindList(key_guid_ref_list);
  if (!guid_ref_list) {
    return true;
  }

  base::Value::List pem_list;
  for (const auto& entry : *guid_ref_list) {
    std::string pem_encoded;
    if (!GUIDRefToPEMEncoding(certs_by_guid, entry.GetString(), &pem_encoded)) {
      return false;
    }

    pem_list.Append(pem_encoded);
  }

  onc_object.Remove(key_guid_ref_list);
  onc_object.Set(key_pem_list, std::move(pem_list));
  return true;
}

// Same as |ResolveSingleCertRef|, but the output |key_pem_list| will be set to
// a list with exactly one value when resolution succeeds.
bool ResolveSingleCertRefToList(const CertPEMsByGUIDMap& certs_by_guid,
                                const std::string& key_guid_ref,
                                const std::string& key_pem_list,
                                base::Value::Dict& onc_object) {
  std::string* guid_ref = onc_object.FindString(key_guid_ref);
  if (!guid_ref) {
    return true;
  }

  std::string pem_encoded;
  if (!GUIDRefToPEMEncoding(certs_by_guid, *guid_ref, &pem_encoded)) {
    return false;
  }

  base::Value::List pem_list;
  pem_list.Append(pem_encoded);
  onc_object.Remove(key_guid_ref);
  onc_object.Set(key_pem_list, std::move(pem_list));
  return true;
}

// Resolves the reference list at |key_guid_refs| if present and otherwise the
// single reference at |key_guid_ref|. Returns whether the respective resolving
// was successful.
bool ResolveCertRefsOrRefToList(const CertPEMsByGUIDMap& certs_by_guid,
                                const std::string& key_guid_refs,
                                const std::string& key_guid_ref,
                                const std::string& key_pem_list,
                                base::Value::Dict& onc_dict) {
  if (onc_dict.contains(key_guid_refs)) {
    if (onc_dict.contains(key_guid_ref)) {
      LOG(ERROR) << "Found both " << key_guid_refs << " and " << key_guid_ref
                 << ". Ignoring and removing the latter.";
      onc_dict.Remove(key_guid_ref);
    }
    return ResolveCertRefList(certs_by_guid, key_guid_refs, key_pem_list,
                              onc_dict);
  }

  // Only resolve |key_guid_ref| if |key_guid_refs| isn't present.
  return ResolveSingleCertRefToList(certs_by_guid, key_guid_ref, key_pem_list,
                                    onc_dict);
}

// Resolve known server and authority certificate reference fields in
// |onc_object|.
bool ResolveServerCertRefsInObject(const CertPEMsByGUIDMap& certs_by_guid,
                                   const OncValueSignature& signature,
                                   base::Value::Dict& onc_object) {
  if (&signature == &kCertificatePatternSignature) {
    if (!ResolveCertRefList(certs_by_guid, ::onc::client_cert::kIssuerCARef,
                            ::onc::client_cert::kIssuerCAPEMs, onc_object)) {
      return false;
    }
  } else if (&signature == &kEAPSignature) {
    if (!ResolveCertRefsOrRefToList(certs_by_guid, ::onc::eap::kServerCARefs,
                                    ::onc::eap::kServerCARef,
                                    ::onc::eap::kServerCAPEMs, onc_object)) {
      return false;
    }
  } else if (&signature == &kIPsecSignature) {
    if (!ResolveCertRefsOrRefToList(certs_by_guid, ::onc::ipsec::kServerCARefs,
                                    ::onc::ipsec::kServerCARef,
                                    ::onc::ipsec::kServerCAPEMs, onc_object)) {
      return false;
    }
  } else if (&signature == &kIPsecSignature ||
             &signature == &kOpenVPNSignature) {
    if (!ResolveSingleCertRef(certs_by_guid, ::onc::openvpn::kServerCertRef,
                              ::onc::openvpn::kServerCertPEM, onc_object) ||
        !ResolveCertRefsOrRefToList(
            certs_by_guid, ::onc::openvpn::kServerCARefs,
            ::onc::openvpn::kServerCARef, ::onc::openvpn::kServerCAPEMs,
            onc_object)) {
      return false;
    }
  }

  // Recurse into nested objects.
  for (auto it : onc_object) {
    if (!it.second.is_dict()) {
      continue;
    }

    const OncFieldSignature* field_signature =
        GetFieldSignature(signature, it.first);
    if (!field_signature) {
      continue;
    }

    if (!ResolveServerCertRefsInObject(certs_by_guid,
                                       *field_signature->value_signature,
                                       it.second.GetDict())) {
      return false;
    }
  }
  return true;
}

}  // namespace

std::optional<base::Value::Dict> ReadDictionaryFromJson(std::string_view json) {
  if (json.empty()) {
    // Policy may contain empty values, just log a debug message.
    NET_LOG(DEBUG) << "Empty json string";
    return std::nullopt;
  }
  auto parsed_json = base::JSONReader::ReadAndReturnValueWithError(
      json,
      base::JSON_PARSE_CHROMIUM_EXTENSIONS | base::JSON_ALLOW_TRAILING_COMMAS);
  if (!parsed_json.has_value()) {
    NET_LOG(ERROR) << "Invalid JSON Dictionary: "
                   << parsed_json.error().message;
    return std::nullopt;
  }
  if (!parsed_json->is_dict()) {
    NET_LOG(ERROR) << "Invalid JSON Dictionary: Expected a dictionary.";
    return std::nullopt;
  }
  return std::move(*parsed_json).TakeDict();
}

struct UnpackedMessage {
  std::vector<uint8_t> salt;
  std::array<uint8_t, crypto::aes_cbc::kBlockSize> iv;
  std::vector<uint8_t> ciphertext;
  std::array<uint8_t, crypto::hash::kSha1Size> hmac;
  crypto::kdf::Pbkdf2HmacSha1Params kdf_params;
};

// Unpack the passed-in JSON message into either a correctly-formed message to
// be decrypted, or a std::nullopt.
std::optional<UnpackedMessage> UnpackMessage(const base::Value::Dict& root) {
  const int kMaxIterationCount = 500000;
  std::string onc_type;
  std::string iv;
  std::string salt;
  std::string cipher;
  std::string stretch_method;
  std::string hmac_method;
  std::string hmac;
  int iterations;
  std::string ciphertext;

  if (!GetString(root, ::onc::encrypted::kCiphertext, &ciphertext) ||
      !GetString(root, ::onc::encrypted::kCipher, &cipher) ||
      !GetString(root, ::onc::encrypted::kHMAC, &hmac) ||
      !GetString(root, ::onc::encrypted::kHMACMethod, &hmac_method) ||
      !GetString(root, ::onc::encrypted::kIV, &iv) ||
      !GetInt(root, ::onc::encrypted::kIterations, &iterations) ||
      !GetString(root, ::onc::encrypted::kSalt, &salt) ||
      !GetString(root, ::onc::encrypted::kStretch, &stretch_method) ||
      !GetString(root, ::onc::toplevel_config::kType, &onc_type) ||
      onc_type != ::onc::toplevel_config::kEncryptedConfiguration) {
    NET_LOG(ERROR) << "Encrypted ONC malformed.";
    return std::nullopt;
  }

  if (hmac_method != ::onc::encrypted::kSHA1 ||
      cipher != ::onc::encrypted::kAES256 ||
      stretch_method != ::onc::encrypted::kPBKDF2) {
    NET_LOG(ERROR) << "Encrypted ONC unsupported encryption scheme.";
    return std::nullopt;
  }

  // Make sure iterations != 0, since that's not valid.
  if (iterations == 0) {
    NET_LOG(ERROR) << kUnableToDecrypt;
    return std::nullopt;
  }

  // Simply a sanity check to make sure we can't lock up the machine
  // for too long with a huge number (or a negative number).
  if (iterations < 0 || iterations > kMaxIterationCount) {
    NET_LOG(ERROR) << "Too many iterations in encrypted ONC";
    return std::nullopt;
  }

  if (!base::Base64Decode(salt, &salt) || !base::Base64Decode(iv, &iv) ||
      !base::Base64Decode(ciphertext, &ciphertext) ||
      !base::Base64Decode(hmac, &hmac) ||
      iv.length() != crypto::aes_cbc::kBlockSize) {
    NET_LOG(ERROR) << kUnableToDecode;
    return std::nullopt;
  }

  UnpackedMessage m;
  m.salt.assign(salt.begin(), salt.end());
  std::copy(iv.begin(), iv.end(), m.iv.begin());
  m.ciphertext.assign(ciphertext.begin(), ciphertext.end());
  std::copy(hmac.begin(), hmac.end(), m.hmac.begin());
  m.kdf_params.iterations = iterations;
  return m;
}

crypto::SubtlePassKey MakeCryptoPassKey() {
  return crypto::SubtlePassKey{};
}

// Given a message (passed in as a base::Value::Dict), unpack and validate it,
// check the HMAC on its contained ciphertext, deobfuscate, then unpack the
// deobfuscated plaintext as a JSON dictionary and return it. If any of these
// steps fails, returns std::nullopt.
std::optional<base::Value::Dict> Decrypt(const base::Value::Dict& root) {
  const size_t kKeyBytes = 32;
  std::optional<UnpackedMessage> m = UnpackMessage(root);
  if (!m) {
    return std::nullopt;
  }

  std::array<uint8_t, kKeyBytes> key;
  crypto::kdf::DeriveKeyPbkdf2HmacSha1(m->kdf_params,
                                       base::span<const uint8_t>(), m->salt,
                                       key, MakeCryptoPassKey());

  if (!crypto::hmac::VerifySha1(key, m->ciphertext, m->hmac)) {
    NET_LOG(ERROR) << kUnableToDecrypt;
    return std::nullopt;
  }

  auto plaintext = crypto::aes_cbc::Decrypt(key, m->iv, m->ciphertext);
  if (!plaintext) {
    NET_LOG(ERROR) << kUnableToDecrypt;
    return std::nullopt;
  }

  std::optional<base::Value::Dict> new_root =
      ReadDictionaryFromJson(base::as_string_view(*plaintext));
  if (!new_root) {
    NET_LOG(ERROR) << "Property dictionary malformed.";
  }
  return new_root;
}

std::string GetSourceAsString(::onc::ONCSource source) {
  switch (source) {
    case ::onc::ONC_SOURCE_UNKNOWN:
      return "unknown";
    case ::onc::ONC_SOURCE_NONE:
      return "none";
    case ::onc::ONC_SOURCE_DEVICE_POLICY:
      return "device policy";
    case ::onc::ONC_SOURCE_USER_POLICY:
      return "user policy";
    case ::onc::ONC_SOURCE_USER_IMPORT:
      return "user import";
  }
  NOTREACHED();
}

void ExpandStringsInOncObject(const OncValueSignature& signature,
                              const VariableExpander& variable_expander,
                              base::Value::Dict* onc_object) {
  if (&signature == &kEAPSignature) {
    ExpandField(::onc::eap::kAnonymousIdentity, variable_expander, onc_object);
    ExpandField(::onc::eap::kIdentity, variable_expander, onc_object);
  } else if (&signature == &kL2TPSignature ||
             &signature == &kOpenVPNSignature) {
    ExpandField(::onc::vpn::kUsername, variable_expander, onc_object);
  } else if (&signature == &kIssuerSubjectPatternSignature) {
    ExpandField(::onc::client_cert::kCommonName, variable_expander, onc_object);
    ExpandField(::onc::client_cert::kLocality, variable_expander, onc_object);
    ExpandField(::onc::client_cert::kOrganization, variable_expander,
                onc_object);
    ExpandField(::onc::client_cert::kOrganizationalUnit, variable_expander,
                onc_object);
  }

  // Recurse into nested objects.
  for (auto it : *onc_object) {
    if (!it.second.is_dict())
      continue;

    const OncFieldSignature* field_signature =
        GetFieldSignature(signature, it.first);
    if (!field_signature)
      continue;

    ExpandStringsInOncObject(*field_signature->value_signature,
                             variable_expander, &it.second.GetDict());
  }
}

void ExpandStringsInNetworks(const VariableExpander& variable_expander,
                             base::Value::List& network_configs) {
  for (auto& network : network_configs) {
    ExpandStringsInOncObject(kNetworkConfigurationSignature, variable_expander,
                             &network.GetDict());
  }
}

void FillInCellularCustomAPNListField(
    base::Value::Dict& cellular_fields,
    const base::Value::List* custom_apn_list) {
  if (cellular_fields.Find(::onc::cellular::kCustomAPNList)) {
    NET_LOG(DEBUG) << "kCustomAPNList found, skipping";
    return;
  }

  NET_LOG(DEBUG) << "Filling in kCustomAPNList with "
                 << custom_apn_list->DebugString();
  cellular_fields.Set(::onc::cellular::kCustomAPNList,
                      custom_apn_list->Clone());
}

void FillInCellularCustomAPNListFieldsInOncObject(
    const OncValueSignature& signature,
    base::Value::Dict& onc_object,
    const base::Value::List* custom_apn_list) {
  if (&signature == &kCellularSignature) {
    FillInCellularCustomAPNListField(onc_object, custom_apn_list);
  }

  for (auto it : onc_object) {
    if (!it.second.is_dict()) {
      continue;
    }

    const OncFieldSignature* field_signature =
        GetFieldSignature(signature, it.first);
    if (!field_signature) {
      continue;
    }

    FillInCellularCustomAPNListFieldsInOncObject(
        *field_signature->value_signature, it.second.GetDict(),
        custom_apn_list);
  }
}

void FillInHexSSIDFieldsInOncObject(const OncValueSignature& signature,
                                    base::Value::Dict& onc_object) {
  if (&signature == &kWiFiSignature)
    FillInHexSSIDField(onc_object);

  // Recurse into nested objects.
  for (auto it : onc_object) {
    if (!it.second.is_dict())
      continue;

    const OncFieldSignature* field_signature =
        GetFieldSignature(signature, it.first);
    if (!field_signature)
      continue;

    FillInHexSSIDFieldsInOncObject(*field_signature->value_signature,
                                   it.second.GetDict());
  }
}

void FillInHexSSIDField(base::Value::Dict& wifi_fields) {
  if (wifi_fields.Find(::onc::wifi::kHexSSID)) {
    return;
  }
  std::string* ssid = wifi_fields.FindString(::onc::wifi::kSSID);
  if (!ssid) {
    return;
  }
  if (ssid->empty()) {
    NET_LOG(ERROR) << "Found empty SSID field.";
    return;
  }
  wifi_fields.Set(::onc::wifi::kHexSSID, base::HexEncode(*ssid));
}

void SetHiddenSSIDFieldInOncObject(const OncValueSignature& signature,
                                   base::Value::Dict& onc_object) {
  if (&signature == &kWiFiSignature) {
    SetHiddenSSIDField(onc_object);
  }

  // Recurse into nested objects.
  for (auto it : onc_object) {
    if (!it.second.is_dict()) {
      continue;
    }

    const OncFieldSignature* field_signature =
        GetFieldSignature(signature, it.first);
    if (!field_signature) {
      continue;
    }

    SetHiddenSSIDFieldInOncObject(*field_signature->value_signature,
                                  it.second.GetDict());
  }
}

void SetHiddenSSIDField(base::Value::Dict& wifi_fields) {
  if (wifi_fields.Find(::onc::wifi::kHiddenSSID)) {
    return;
  }
  wifi_fields.Set(::onc::wifi::kHiddenSSID, false);
}

base::Value::Dict MaskCredentialsInOncObject(
    const OncValueSignature& signature,
    const base::Value::Dict& onc_object,
    const std::string& mask) {
  return OncMaskValues::Mask(signature, onc_object, mask);
}

std::string DecodePEM(const std::string& pem_encoded) {
  // The PEM block header used for DER certificates
  const char kCertificateHeader[] = "CERTIFICATE";

  // This is an older PEM marker for DER certificates.
  const char kX509CertificateHeader[] = "X509 CERTIFICATE";

  std::vector<std::string> pem_headers;
  pem_headers.push_back(kCertificateHeader);
  pem_headers.push_back(kX509CertificateHeader);

  bssl::PEMTokenizer pem_tokenizer(pem_encoded, pem_headers);
  std::string decoded;
  if (pem_tokenizer.GetNext()) {
    decoded = pem_tokenizer.data();
  } else {
    // If we failed to read the data as a PEM file, then try plain base64 decode
    // in case the PEM marker strings are missing. For this to work, there has
    // to be no white space, and it has to only contain the base64-encoded data.
    if (!base::Base64Decode(pem_encoded, &decoded)) {
      LOG(ERROR) << "Unable to base64 decode X509 data: " << pem_encoded;
      return std::string();
    }
  }
  return decoded;
}

bool ParseAndValidateOncForImport(const std::string& onc_blob,
                                  ::onc::ONCSource onc_source,
                                  base::Value::List* network_configs,
                                  base::Value::Dict* global_network_config,
                                  base::Value::List* certificates) {
  if (network_configs) {
    network_configs->clear();
  }
  if (global_network_config) {
    global_network_config->clear();
  }
  if (certificates) {
    certificates->clear();
  }
  if (onc_blob.empty()) {
    return true;
  }

  std::optional<base::Value::Dict> toplevel_onc =
      ReadDictionaryFromJson(onc_blob);
  if (!toplevel_onc) {
    NET_LOG(ERROR) << "Not a valid ONC JSON dictionary: "
                   << GetSourceAsString(onc_source);
    return false;
  }

  // Check and see if this is an encrypted ONC file. If so, decrypt it.
  std::string onc_type;
  if (GetString(toplevel_onc.value(), ::onc::toplevel_config::kType,
                &onc_type) &&
      onc_type == ::onc::toplevel_config::kEncryptedConfiguration) {
    toplevel_onc = Decrypt(toplevel_onc.value());
    if (!toplevel_onc.has_value()) {
      NET_LOG(ERROR) << "Unable to decrypt ONC from "
                     << GetSourceAsString(onc_source);
      return false;
    }
  }

  bool from_policy = (onc_source == ::onc::ONC_SOURCE_USER_POLICY ||
                      onc_source == ::onc::ONC_SOURCE_DEVICE_POLICY);

  // Validate the ONC dictionary. We are liberal and ignore unknown field
  // names and ignore invalid field names in kRecommended arrays.
  Validator validator(/*error_on_unknown_field=*/false,
                      /*error_on_wrong_recommended=*/false,
                      /*error_on_missing_field=*/true,
                      /*managed_onc=*/from_policy,
                      /*log_warnings=*/true);
  validator.SetOncSource(onc_source);

  Validator::Result validation_result;
  std::optional<base::Value::Dict> validated_toplevel_onc =
      validator.ValidateAndRepairObject(&kToplevelConfigurationSignature,
                                        toplevel_onc.value(),
                                        &validation_result);

  bool success = true;
  if (validation_result == Validator::VALID_WITH_WARNINGS) {
    NET_LOG(DEBUG) << "ONC validation produced warnings: "
                   << GetSourceAsString(onc_source);
    success = false;
  } else if (validation_result == Validator::INVALID ||
             !validated_toplevel_onc.has_value()) {
    NET_LOG(ERROR) << "ONC is invalid and couldn't be repaired: "
                   << GetSourceAsString(onc_source);
    return false;
  }

  if (certificates) {
    base::Value::List* validated_certs =
        validated_toplevel_onc->FindList(::onc::toplevel_config::kCertificates);
    if (validated_certs)
      *certificates = std::move(*validated_certs);
  }

  // Note that this processing is performed even if |network_configs| is
  // nullptr, because ResolveServerCertRefsInNetworks could affect the return
  // value of the function (which is supposed to aggregate validation issues in
  // all segments of the ONC blob).
  base::Value::List* validated_networks_list = validated_toplevel_onc->FindList(
      ::onc::toplevel_config::kNetworkConfigurations);

  base::Value::Dict* validated_global_config = validated_toplevel_onc->FindDict(
      ::onc::toplevel_config::kGlobalNetworkConfiguration);

  const IdToAPNMap id_to_apn_map = BuildIdToAPNMap(
      validated_toplevel_onc->FindList(::onc::toplevel_config::kAdminAPNList));

  if (validated_networks_list) {
    FillInHexSSIDFieldsInNetworks(*validated_networks_list);

    bool allow_apn_modification = true;
    if (validated_global_config) {
      allow_apn_modification =
          (validated_global_config->FindBool(
               ::onc::global_network_config::kAllowAPNModification))
              .value_or(allow_apn_modification);
    }

    FillInCellularDefaultsInNetworks(*validated_networks_list,
                                     allow_apn_modification);

    // Sets the CustomAPNList for cellular networks if an AdminAPNList and
    // AdminAssignedAPNIds have been specified for a cellular network.
    if (!ConfigureAdminApnsInCellularNetworks(*validated_networks_list,
                                              id_to_apn_map)) {
      success = false;
    }

    // Set HiddenSSID to default value to solve the issue crbug.com/1171837
    SetHiddenSSIDFieldsInNetworks(*validated_networks_list);

    CertPEMsByGUIDMap server_and_ca_certs =
        GetServerAndCACertsByGUID(*certificates);

    if (!ResolveServerCertRefsInNetworks(server_and_ca_certs,
                                         *validated_networks_list)) {
      NET_LOG(ERROR) << "Some certificate references in the ONC policy could "
                        "not be resolved: "
                     << GetSourceAsString(onc_source);
      success = false;
    }

    if (network_configs) {
      *network_configs = std::move(*validated_networks_list);
    }
  }

  if (global_network_config) {
    if (validated_global_config) {
      // Constructs and sets the PSIMAdminAssignedAPNs global network
      // configuration field if an AdminAPNList and PSIMAdminAssignedAPNIds have
      // been specified.
      if (!ConstructAndSetPSIMAdminAPNs(*validated_global_config,
                                        id_to_apn_map)) {
        success = false;
      }
      *global_network_config = std::move(*validated_global_config);
    }
  }

  return success;
}

bool ResolveServerCertRefsInNetworks(const CertPEMsByGUIDMap& certs_by_guid,
                                     base::Value::List& network_configs) {
  bool success = true;
  base::Value::List filtered_configs;
  for (base::Value& network : network_configs) {
    if (!ResolveServerCertRefsInNetwork(certs_by_guid, network.GetDict())) {
      std::string* guid =
          network.GetDict().FindString(::onc::network_config::kGUID);
      // This might happen even with correct validation, if the referenced
      // certificate couldn't be imported.
      LOG(ERROR) << "Couldn't resolve some certificate reference of network "
                 << (guid ? *guid : "(unable to find GUID)");
      success = false;
      continue;
    }

    filtered_configs.Append(std::move(network));
  }
  network_configs = std::move(filtered_configs);
  return success;
}

bool ResolveServerCertRefsInNetwork(const CertPEMsByGUIDMap& certs_by_guid,
                                    base::Value::Dict& network_config) {
  return ResolveServerCertRefsInObject(
      certs_by_guid, kNetworkConfigurationSignature, network_config);
}

}  // namespace chromeos::onc