File: spake2_authenticator.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • 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 (351 lines) | stat: -rw-r--r-- 12,087 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
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/protocol/spake2_authenticator.h"

#include <utility>

#include "base/base64.h"
#include "base/containers/span.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/numerics/byte_conversions.h"
#include "base/strings/string_view_util.h"
#include "crypto/hmac.h"
#include "crypto/secure_util.h"
#include "remoting/base/constants.h"
#include "remoting/base/rsa_key_pair.h"
#include "remoting/protocol/authenticator.h"
#include "remoting/protocol/ssl_hmac_channel_authenticator.h"
#include "third_party/boringssl/src/include/openssl/curve25519.h"
#include "third_party/libjingle_xmpp/xmllite/xmlelement.h"

namespace remoting::protocol {

namespace {

// Each peer sends 2 messages: <spake-message> and <verification-hash>. The
// content of <spake-message> is the output of SPAKE2_generate_msg() and must
// be passed to SPAKE2_process_msg() on the other end. This is enough to
// generate authentication key. <verification-hash> is sent to confirm that both
// ends get the same authentication key (which means they both know the
// password). This verification hash is calculated in
// CalculateVerificationHash() as follows:
//    HMAC_SHA256(auth_key, ("host"|"client") + local_jid.length() + local_jid +
//                remote_jid.length() + remote_jid)
// where auth_key is the key produced by SPAKE2.

const jingle_xmpp::StaticQName kSpakeMessageTag = {kChromotingXmlNamespace,
                                                   "spake-message"};
const jingle_xmpp::StaticQName kVerificationHashTag = {kChromotingXmlNamespace,
                                                       "verification-hash"};
const jingle_xmpp::StaticQName kCertificateTag = {kChromotingXmlNamespace,
                                                  "certificate"};

std::unique_ptr<jingle_xmpp::XmlElement> EncodeBinaryValueToXml(
    const jingle_xmpp::StaticQName& qname,
    const std::string& content) {
  std::string content_base64 = base::Base64Encode(content);

  std::unique_ptr<jingle_xmpp::XmlElement> result(
      new jingle_xmpp::XmlElement(qname));
  result->SetBodyText(content_base64);
  return result;
}

// Finds tag named |qname| in base_message and decodes it from base64 and stores
// in |data|. If the element is not present then found is set to false otherwise
// it's set to true. If the element is there and it's content couldn't be
// decoded then false is returned.
bool DecodeBinaryValueFromXml(const jingle_xmpp::XmlElement* message,
                              const jingle_xmpp::QName& qname,
                              bool* found,
                              std::string* data) {
  const jingle_xmpp::XmlElement* element = message->FirstNamed(qname);
  *found = element != nullptr;
  if (!*found) {
    return true;
  }

  if (!base::Base64Decode(element->BodyText(), data)) {
    LOG(WARNING) << "Failed to parse " << qname.LocalPart();
    return false;
  }

  return !data->empty();
}

std::string PrefixWithLength(const std::string& str) {
  std::string out;
  out += base::as_string_view(base::U32ToBigEndian(str.size()));
  out += str;
  return out;
}

}  // namespace

// static
std::unique_ptr<Authenticator> Spake2Authenticator::CreateForClient(
    const std::string& local_id,
    const std::string& remote_id,
    const std::string& shared_secret,
    Authenticator::State initial_state) {
  return base::WrapUnique(new Spake2Authenticator(
      local_id, remote_id, shared_secret, false, initial_state));
}

// static
std::unique_ptr<Authenticator> Spake2Authenticator::CreateForHost(
    const std::string& local_id,
    const std::string& remote_id,
    const std::string& local_cert,
    scoped_refptr<RsaKeyPair> key_pair,
    const std::string& shared_secret,
    Authenticator::State initial_state) {
  std::unique_ptr<Spake2Authenticator> result(new Spake2Authenticator(
      local_id, remote_id, shared_secret, true, initial_state));
  result->local_cert_ = local_cert;
  result->local_key_pair_ = key_pair;
  return std::move(result);
}

Spake2Authenticator::Spake2Authenticator(const std::string& local_id,
                                         const std::string& remote_id,
                                         const std::string& shared_secret,
                                         bool is_host,
                                         Authenticator::State initial_state)
    : local_id_(local_id),
      remote_id_(remote_id),
      shared_secret_(shared_secret),
      is_host_(is_host),
      state_(initial_state) {
  spake2_context_ = SPAKE2_CTX_new(
      is_host ? spake2_role_bob : spake2_role_alice,
      reinterpret_cast<const uint8_t*>(local_id_.data()), local_id_.size(),
      reinterpret_cast<const uint8_t*>(remote_id_.data()), remote_id_.size());

  // Generate first message and push it to |pending_messages_|.
  uint8_t message[SPAKE2_MAX_MSG_SIZE];
  size_t message_size;
  int result = SPAKE2_generate_msg(
      spake2_context_, message, &message_size, sizeof(message),
      reinterpret_cast<const uint8_t*>(shared_secret_.data()),
      shared_secret_.size());
  CHECK(result);
  local_spake_message_.assign(reinterpret_cast<char*>(message), message_size);
}

Spake2Authenticator::~Spake2Authenticator() {
  SPAKE2_CTX_free(spake2_context_);
}

CredentialsType Spake2Authenticator::credentials_type() const {
  return CredentialsType::SHARED_SECRET;
}

const Authenticator& Spake2Authenticator::implementing_authenticator() const {
  return *this;
}

Authenticator::State Spake2Authenticator::state() const {
  if (state_ == ACCEPTED && !outgoing_verification_hash_.empty()) {
    return MESSAGE_READY;
  }
  return state_;
}

bool Spake2Authenticator::started() const {
  return started_;
}

Authenticator::RejectionReason Spake2Authenticator::rejection_reason() const {
  DCHECK_EQ(state(), REJECTED);
  return rejection_reason_;
}

Authenticator::RejectionDetails Spake2Authenticator::rejection_details() const {
  DCHECK_EQ(state(), REJECTED);
  return rejection_details_;
}

void Spake2Authenticator::ProcessMessage(const jingle_xmpp::XmlElement* message,
                                         base::OnceClosure resume_callback) {
  ProcessMessageInternal(message);
  std::move(resume_callback).Run();
}

void Spake2Authenticator::ProcessMessageInternal(
    const jingle_xmpp::XmlElement* message) {
  DCHECK_EQ(state(), WAITING_MESSAGE);

  // Parse the certificate.
  bool cert_present;
  if (!DecodeBinaryValueFromXml(message, kCertificateTag, &cert_present,
                                &remote_cert_)) {
    state_ = REJECTED;
    rejection_reason_ = RejectionReason::INVALID_ARGUMENT;
    rejection_details_ = RejectionDetails(
        "Failed to decode the remote certificate in the incoming message.");
    return;
  }

  // Client always expects certificate in the first message.
  if (!is_host_ && remote_cert_.empty()) {
    state_ = REJECTED;
    rejection_reason_ = RejectionReason::INVALID_STATE;
    rejection_details_ = RejectionDetails("No valid host certificate.");
    return;
  }

  bool spake_message_present = false;
  std::string spake_message;
  bool verification_hash_present = false;
  std::string verification_hash;
  if (!DecodeBinaryValueFromXml(message, kSpakeMessageTag,
                                &spake_message_present, &spake_message) ||
      !DecodeBinaryValueFromXml(message, kVerificationHashTag,
                                &verification_hash_present,
                                &verification_hash)) {
    state_ = REJECTED;
    rejection_reason_ = RejectionReason::INVALID_ARGUMENT;
    rejection_details_ = RejectionDetails(
        "Failed to decode the spake message or the verification hash in the "
        "incoming message.");
    return;
  }

  // |auth_key_| is generated when <spake-message> is received.
  if (auth_key_.empty()) {
    if (!spake_message_present) {
      state_ = REJECTED;
      rejection_reason_ = RejectionReason::INVALID_ARGUMENT;
      rejection_details_ = RejectionDetails("<spake-message> not found.");
      return;
    }
    uint8_t key[SPAKE2_MAX_KEY_SIZE];
    size_t key_size;
    started_ = true;
    int result = SPAKE2_process_msg(
        spake2_context_, key, &key_size, sizeof(key),
        reinterpret_cast<const uint8_t*>(spake_message.data()),
        spake_message.size());
    if (!result) {
      state_ = REJECTED;
      rejection_reason_ = RejectionReason::INVALID_CREDENTIALS;
      rejection_details_ =
          RejectionDetails("Failed to process SPAKE2 message.");
      return;
    }
    CHECK(key_size);
    auth_key_.assign(reinterpret_cast<char*>(key), key_size);

    outgoing_verification_hash_ =
        CalculateVerificationHash(is_host_, local_id_, remote_id_);
    expected_verification_hash_ =
        CalculateVerificationHash(!is_host_, remote_id_, local_id_);
  } else if (spake_message_present) {
    state_ = REJECTED;
    rejection_reason_ = RejectionReason::INVALID_STATE;
    rejection_details_ =
        RejectionDetails("Received duplicate <spake-message>.");
    return;
  }

  if (spake_message_sent_ && !verification_hash_present) {
    state_ = REJECTED;
    rejection_reason_ = RejectionReason::INVALID_STATE;
    rejection_details_ =
        RejectionDetails("Didn't receive <verification-hash> when expected.");
    return;
  }

  if (verification_hash_present) {
    if (!crypto::SecureMemEqual(
            base::as_byte_span(verification_hash),
            base::as_byte_span(expected_verification_hash_))) {
      state_ = REJECTED;
      rejection_reason_ = RejectionReason::INVALID_CREDENTIALS;
      rejection_details_ = RejectionDetails("Verification hash mismatched.");
      return;
    }
    state_ = ACCEPTED;
    return;
  }

  state_ = MESSAGE_READY;
}

std::unique_ptr<jingle_xmpp::XmlElement> Spake2Authenticator::GetNextMessage() {
  DCHECK_EQ(state(), MESSAGE_READY);

  std::unique_ptr<jingle_xmpp::XmlElement> message =
      CreateEmptyAuthenticatorMessage();

  if (!spake_message_sent_) {
    if (!local_cert_.empty()) {
      message->AddElement(
          EncodeBinaryValueToXml(kCertificateTag, local_cert_).release());
    }

    message->AddElement(
        EncodeBinaryValueToXml(kSpakeMessageTag, local_spake_message_)
            .release());

    spake_message_sent_ = true;
  }

  if (!outgoing_verification_hash_.empty()) {
    message->AddElement(EncodeBinaryValueToXml(kVerificationHashTag,
                                               outgoing_verification_hash_)
                            .release());
    outgoing_verification_hash_.clear();
  }

  if (state_ != ACCEPTED) {
    state_ = WAITING_MESSAGE;
  }
  return message;
}

const std::string& Spake2Authenticator::GetAuthKey() const {
  return auth_key_;
}

const SessionPolicies* Spake2Authenticator::GetSessionPolicies() const {
  return nullptr;
}

std::unique_ptr<ChannelAuthenticator>
Spake2Authenticator::CreateChannelAuthenticator() const {
  DCHECK_EQ(state(), ACCEPTED);
  CHECK(!auth_key_.empty());

  if (is_host_) {
    return SslHmacChannelAuthenticator::CreateForHost(
        local_cert_, local_key_pair_, auth_key_);
  } else {
    return SslHmacChannelAuthenticator::CreateForClient(remote_cert_,
                                                        auth_key_);
  }
}

std::string Spake2Authenticator::CalculateVerificationHash(
    bool from_host,
    const std::string& local_id,
    const std::string& remote_id) {
  std::string message = (from_host ? "host" : "client") +
                        PrefixWithLength(local_id) +
                        PrefixWithLength(remote_id);
  crypto::HMAC hmac(crypto::HMAC::SHA256);
  std::string result(hmac.DigestLength(), '\0');
  if (!hmac.Init(auth_key_) ||
      !hmac.Sign(message, reinterpret_cast<uint8_t*>(&result[0]),
                 result.length())) {
    LOG(FATAL) << "Failed to calculate HMAC.";
  }
  return result;
}

}  // namespace remoting::protocol