summaryrefslogtreecommitdiffstats
path: root/toolkit/components/telemetry/dap/DAPTelemetry.cpp
blob: 31d634e47b7f2041e3a6dae9786d88d22fa4adc6 (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "DAPTelemetryBindings.h"

#include "mozilla/Logging.h"
#include "nsPromiseFlatString.h"

#include "nss.h"
#include "nsNSSComponent.h"
#include "secmodt.h"
#include "pk11pub.h"
#include "ScopedNSSTypes.h"

static mozilla::LazyLogModule sLogger("DAPTelemetry");
#undef LOG
#define LOG(...) MOZ_LOG(sLogger, mozilla::LogLevel::Debug, (__VA_ARGS__))

namespace mozilla {

NS_IMPL_ISUPPORTS(DAPTelemetry, nsIDAPTelemetry)

// This function was copied from pk11_hpke_unittest.cc
// And modified to take a Span.
static std::vector<uint8_t> Pkcs8(Span<const uint8_t> sk,
                                  Span<const uint8_t> pk) {
  // Only X25519 format.
  std::vector<uint8_t> v(105);
  v.assign({
      0x30, 0x67, 0x02, 0x01, 0x00, 0x30, 0x14, 0x06, 0x07, 0x2a, 0x86, 0x48,
      0xce, 0x3d, 0x02, 0x01, 0x06, 0x09, 0x2b, 0x06, 0x01, 0x04, 0x01, 0xda,
      0x47, 0x0f, 0x01, 0x04, 0x4c, 0x30, 0x4a, 0x02, 0x01, 0x01, 0x04, 0x20,
  });
  v.insert(v.end(), sk.begin(), sk.end());
  v.insert(v.end(), {
                        0xa1,
                        0x23,
                        0x03,
                        0x21,
                        0x00,
                    });
  v.insert(v.end(), pk.begin(), pk.end());
  return v;
}

// This function was copied from cpputil.h
static unsigned char* toUcharPtr(const uint8_t* v) {
  return const_cast<unsigned char*>(static_cast<const unsigned char*>(v));
}

/// If successful this returns a pointer to a HpkeContext which must be
/// released using dapDestroyHpkeContext or PK11_HPKE_DestroyContext.
HpkeContext* dapSetupHpkeContextInternal(
    const uint8_t* aKey, uint32_t aKeyLength, const uint8_t* aInfo,
    uint32_t aInfoLength, SECKEYPublicKey* aPkE, SECKEYPrivateKey* aSkE,
    nsTArray<uint8_t>* aOutputEncapsulatedKey) {
  SECStatus status = PK11_HPKE_ValidateParameters(
      HpkeDhKemX25519Sha256, HpkeKdfHkdfSha256, HpkeAeadAes128Gcm);
  if (status != SECSuccess) {
    MOZ_LOG(sLogger, mozilla::LogLevel::Error,
            ("Invalid HKPE parameters found."));
    return nullptr;
  }

  UniqueHpkeContext context(
      PK11_HPKE_NewContext(HpkeDhKemX25519Sha256, HpkeKdfHkdfSha256,
                           HpkeAeadAes128Gcm, nullptr, nullptr));

  SECKEYPublicKey* pkR_raw = nullptr;
  status = PK11_HPKE_Deserialize(context.get(), aKey, aKeyLength, &pkR_raw);
  UniqueSECKEYPublicKey pkR(pkR_raw);
  pkR_raw = nullptr;
  if (status != SECSuccess) {
    MOZ_LOG(sLogger, mozilla::LogLevel::Error,
            ("Failed to deserialize HPKE encryption key."));
    return nullptr;
  }

  const SECItem hpkeInfo = {siBuffer, toUcharPtr(aInfo), aInfoLength};

  status = PK11_HPKE_SetupS(context.get(), aPkE, aSkE, pkR.get(), &hpkeInfo);
  if (status != SECSuccess) {
    MOZ_LOG(sLogger, mozilla::LogLevel::Error, ("HPKE setup failed."));
    return nullptr;
  }

  const SECItem* hpkeEncapKey = PK11_HPKE_GetEncapPubKey(context.get());
  if (!hpkeEncapKey) {
    MOZ_LOG(sLogger, mozilla::LogLevel::Error,
            ("Failed to get HPKE encapsulated public key."));
    return nullptr;
  }

  aOutputEncapsulatedKey->AppendElements(hpkeEncapKey->data, hpkeEncapKey->len);

  return context.release();
}

extern "C" {
/// Takes additional ephemeral keys to make everything deterministic for test
/// vectors.
/// If successful this returns a pointer to a HpkeContext which must be
/// released using dapDestroyHpkeContext or PK11_HPKE_DestroyContext.
HpkeContext* dapSetupHpkeContextForTesting(
    const uint8_t* aKey, uint32_t aKeyLength, const uint8_t* aInfo,
    uint32_t aInfoLength, const uint8_t* aPkEm, uint32_t aPkEmLength,
    const uint8_t* aSkEm, uint32_t aSkEmLength,
    nsTArray<uint8_t>* aOutputEncapsulatedKey) {
  Span<const uint8_t> sk_e(aSkEm, aSkEm + aSkEmLength);
  Span<const uint8_t> pk_e(aPkEm, aPkEm + aPkEmLength);
  std::vector<uint8_t> pkcs8_e = Pkcs8(sk_e, pk_e);

  MOZ_RELEASE_ASSERT(EnsureNSSInitializedChromeOrContent(),
                     "Could not initialize NSS.");

  UniquePK11SlotInfo slot(PK11_GetInternalSlot());
  MOZ_RELEASE_ASSERT(slot, "Failed to get slot.");

  SECItem keys_e = {siBuffer, toUcharPtr(pkcs8_e.data()),
                    static_cast<unsigned int>(pkcs8_e.size())};
  SECKEYPrivateKey* internal_skE_raw = nullptr;
  SECStatus rv = PK11_ImportDERPrivateKeyInfoAndReturnKey(
      slot.get(), &keys_e, nullptr, nullptr, false, false, KU_ALL,
      &internal_skE_raw, nullptr);
  UniqueSECKEYPrivateKey internal_skE(internal_skE_raw);
  internal_skE_raw = nullptr;
  MOZ_RELEASE_ASSERT(rv == SECSuccess, "Failed to import skE/pkE.");

  UniqueSECKEYPublicKey internal_pkE(
      SECKEY_ConvertToPublicKey(internal_skE.get()));

  UniqueHpkeContext result(dapSetupHpkeContextInternal(
      aKey, aKeyLength, aInfo, aInfoLength, internal_pkE.get(),
      internal_skE.get(), aOutputEncapsulatedKey));

  return result.release();
}

void dapDestroyHpkeContext(HpkeContext* aContext) {
  PK11_HPKE_DestroyContext(aContext, true);
}

bool dapHpkeEncrypt(HpkeContext* aContext, const uint8_t* aAad,
                    uint32_t aAadLength, const uint8_t* aPlaintext,
                    uint32_t aPlaintextLength,
                    nsTArray<uint8_t>* aOutputShare) {
  SECItem aad_si = {siBuffer, toUcharPtr(aAad), aAadLength};
  SECItem plaintext_si = {siBuffer, toUcharPtr(aPlaintext), aPlaintextLength};
  SECItem* chCt = nullptr;
  SECStatus rv = PK11_HPKE_Seal(aContext, &aad_si, &plaintext_si, &chCt);
  if (rv != SECSuccess) {
    return false;
  }
  UniqueSECItem ct(chCt);

  aOutputShare->AppendElements(ct->data, ct->len);
  return true;
}

bool dapHpkeEncryptOneshot(const uint8_t* aKey, uint32_t aKeyLength,
                           const uint8_t* aInfo, uint32_t aInfoLength,
                           const uint8_t* aAad, uint32_t aAadLength,
                           const uint8_t* aPlaintext, uint32_t aPlaintextLength,
                           nsTArray<uint8_t>* aOutputEncapsulatedKey,
                           nsTArray<uint8_t>* aOutputShare) {
  MOZ_RELEASE_ASSERT(EnsureNSSInitializedChromeOrContent(),
                     "Could not initialize NSS.");
  UniqueHpkeContext context(
      dapSetupHpkeContextInternal(aKey, aKeyLength, aInfo, aInfoLength, nullptr,
                                  nullptr, aOutputEncapsulatedKey));
  if (!context) {
    return false;
  }

  return dapHpkeEncrypt(context.get(), aAad, aAadLength, aPlaintext,
                        aPlaintextLength, aOutputShare);
}
}

NS_IMETHODIMP DAPTelemetry::GetReportU8(
    const nsTArray<uint8_t>& aLeaderHpkeConfig,
    const nsTArray<uint8_t>& aHelperHpkeConfig, uint8_t aMeasurement,
    const nsTArray<uint8_t>& aTaskID, const uint64_t aTimePrecision,
    nsTArray<uint8_t>& aOutReport) {
  MOZ_RELEASE_ASSERT(aTaskID.Length() == 32, "TaskID must have 32 bytes.");
  if (!dapGetReportU8(&aLeaderHpkeConfig, &aHelperHpkeConfig, aMeasurement,
                      &aTaskID, aTimePrecision, &aOutReport)) {
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}

NS_IMETHODIMP DAPTelemetry::GetReportVecU8(
    const nsTArray<uint8_t>& aLeaderHpkeConfig,
    const nsTArray<uint8_t>& aHelperHpkeConfig,
    const nsTArray<uint8_t>& aMeasurement, const nsTArray<uint8_t>& aTaskID,
    const uint64_t aTimePrecision, nsTArray<uint8_t>& aOutReport) {
  MOZ_RELEASE_ASSERT(aTaskID.Length() == 32, "TaskID must have 32 bytes.");
  if (!dapGetReportVecU8(&aLeaderHpkeConfig, &aHelperHpkeConfig, &aMeasurement,
                         &aTaskID, aTimePrecision, &aOutReport)) {
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}

NS_IMETHODIMP DAPTelemetry::GetReportVecU16(
    const nsTArray<uint8_t>& aLeaderHpkeConfig,
    const nsTArray<uint8_t>& aHelperHpkeConfig,
    const nsTArray<uint16_t>& aMeasurement, const nsTArray<uint8_t>& aTaskID,
    const uint64_t aTimePrecision, nsTArray<uint8_t>& aOutReport) {
  MOZ_RELEASE_ASSERT(aTaskID.Length() == 32, "TaskID must have 32 bytes.");
  if (!dapGetReportVecU16(&aLeaderHpkeConfig, &aHelperHpkeConfig, &aMeasurement,
                          &aTaskID, aTimePrecision, &aOutReport)) {
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}

}  // namespace mozilla