File: gcm_encryption_provider.cc

package info (click to toggle)
chromium-browser 57.0.2987.98-1~deb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 2,637,852 kB
  • ctags: 2,544,394
  • sloc: cpp: 12,815,961; ansic: 3,676,222; python: 1,147,112; asm: 526,608; java: 523,212; xml: 286,794; perl: 92,654; sh: 86,408; objc: 73,271; makefile: 27,698; cs: 18,487; yacc: 13,031; tcl: 12,957; pascal: 4,875; ml: 4,716; lex: 3,904; sql: 3,862; ruby: 1,982; lisp: 1,508; php: 1,368; exp: 404; awk: 325; csh: 117; jsp: 39; sed: 37
file content (271 lines) | stat: -rw-r--r-- 9,644 bytes parent folder | download
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
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/gcm_driver/crypto/gcm_encryption_provider.h"

#include <vector>

#include "base/base64.h"
#include "base/bind.h"
#include "base/logging.h"
#include "components/gcm_driver/common/gcm_messages.h"
#include "components/gcm_driver/crypto/encryption_header_parsers.h"
#include "components/gcm_driver/crypto/gcm_key_store.h"
#include "components/gcm_driver/crypto/gcm_message_cryptographer.h"
#include "components/gcm_driver/crypto/p256_key_util.h"
#include "components/gcm_driver/crypto/proto/gcm_encryption_data.pb.h"

namespace gcm {

namespace {

const char kEncryptionProperty[] = "encryption";
const char kCryptoKeyProperty[] = "crypto-key";

// Directory in the GCM Store in which the encryption database will be stored.
const base::FilePath::CharType kEncryptionDirectoryName[] =
    FILE_PATH_LITERAL("Encryption");

}  // namespace

std::string GCMEncryptionProvider::ToDecryptionResultDetailsString(
    DecryptionResult result) {
  switch (result) {
    case DECRYPTION_RESULT_UNENCRYPTED:
      return "Message was not encrypted";
    case DECRYPTION_RESULT_DECRYPTED:
      return "Message decrypted";
    case DECRYPTION_RESULT_INVALID_ENCRYPTION_HEADER:
      return "Invalid format for the Encryption header";
    case DECRYPTION_RESULT_INVALID_CRYPTO_KEY_HEADER:
      return "Invalid format for the Crypto-Key header";
    case DECRYPTION_RESULT_NO_KEYS:
      return "There are no associated keys with the subscription";
    case DECRYPTION_RESULT_INVALID_SHARED_SECRET:
      return "The shared secret cannot be derived from the keying material";
    case DECRYPTION_RESULT_INVALID_PAYLOAD:
      return "AES-GCM decryption failed";
  }

  NOTREACHED();
  return "(invalid result)";
}

GCMEncryptionProvider::GCMEncryptionProvider()
    : weak_ptr_factory_(this) {
}

GCMEncryptionProvider::~GCMEncryptionProvider() {
}

void GCMEncryptionProvider::Init(
    const base::FilePath& store_path,
    const scoped_refptr<base::SequencedTaskRunner>& blocking_task_runner) {
  DCHECK(!key_store_);

  base::FilePath encryption_store_path = store_path;

  // |store_path| can be empty in tests, which means that the database should
  // be created in memory rather than on-disk.
  if (!store_path.empty())
    encryption_store_path = store_path.Append(kEncryptionDirectoryName);

  key_store_.reset(
      new GCMKeyStore(encryption_store_path, blocking_task_runner));
}

void GCMEncryptionProvider::GetEncryptionInfo(
    const std::string& app_id,
    const std::string& authorized_entity,
    const EncryptionInfoCallback& callback) {
  DCHECK(key_store_);
  key_store_->GetKeys(app_id, authorized_entity,
                      false /* fallback_to_empty_authorized_entity */,
                      base::Bind(&GCMEncryptionProvider::DidGetEncryptionInfo,
                                 weak_ptr_factory_.GetWeakPtr(), app_id,
                                 authorized_entity, callback));
}

void GCMEncryptionProvider::RemoveEncryptionInfo(
    const std::string& app_id,
    const std::string& authorized_entity,
    const base::Closure& callback) {
  DCHECK(key_store_);
  key_store_->RemoveKeys(app_id, authorized_entity, callback);
}

bool GCMEncryptionProvider::IsEncryptedMessage(const IncomingMessage& message)
    const {
  // The Web Push protocol requires the encryption and crypto-key properties to
  // be set, and the raw_data field to be populated with the payload.
  if (message.data.find(kEncryptionProperty) == message.data.end() ||
      message.data.find(kCryptoKeyProperty) == message.data.end())
    return false;

  return message.raw_data.size() > 0;
}

void GCMEncryptionProvider::DecryptMessage(
    const std::string& app_id,
    const IncomingMessage& message,
    const MessageCallback& callback) {
  DCHECK(key_store_);
  if (!IsEncryptedMessage(message)) {
    callback.Run(DECRYPTION_RESULT_UNENCRYPTED, message);
    return;
  }

  // IsEncryptedMessage() verifies that both the Encryption and Crypto-Key HTTP
  // headers have been provided for the |message|.
  const auto& encryption_header = message.data.find(kEncryptionProperty);
  const auto& crypto_key_header = message.data.find(kCryptoKeyProperty);

  DCHECK(encryption_header != message.data.end());
  DCHECK(crypto_key_header != message.data.end());

  EncryptionHeaderIterator encryption_header_iterator(
      encryption_header->second.begin(), encryption_header->second.end());
  if (!encryption_header_iterator.GetNext()) {
    DLOG(ERROR) << "Unable to parse the value of the Encryption header";
    callback.Run(DECRYPTION_RESULT_INVALID_ENCRYPTION_HEADER,
                 IncomingMessage());
    return;
  }

  if (encryption_header_iterator.salt().size() !=
          GCMMessageCryptographer::kSaltSize) {
    DLOG(ERROR) << "Invalid values supplied in the Encryption header";
    callback.Run(DECRYPTION_RESULT_INVALID_ENCRYPTION_HEADER,
                 IncomingMessage());
    return;
  }

  CryptoKeyHeaderIterator crypto_key_header_iterator(
      crypto_key_header->second.begin(), crypto_key_header->second.end());
  if (!crypto_key_header_iterator.GetNext()) {
    DLOG(ERROR) << "Unable to parse the value of the Crypto-Key header";
    callback.Run(DECRYPTION_RESULT_INVALID_CRYPTO_KEY_HEADER,
                 IncomingMessage());
    return;
  }

  // Ignore values that don't include the "dh" property. When using VAPID, it is
  // valid for the application server to supply multiple values.
  while (crypto_key_header_iterator.dh().empty() &&
         crypto_key_header_iterator.GetNext()) {}

  bool valid_crypto_key_header = false;
  std::string dh;

  if (!crypto_key_header_iterator.dh().empty()) {
    dh = crypto_key_header_iterator.dh();
    valid_crypto_key_header = true;

    // Guard against the "dh" property being included more than once.
    while (crypto_key_header_iterator.GetNext()) {
      if (crypto_key_header_iterator.dh().empty())
        continue;

      valid_crypto_key_header = false;
      break;
    }
  }

  if (!valid_crypto_key_header) {
    DLOG(ERROR) << "Invalid values supplied in the Crypto-Key header";
    callback.Run(DECRYPTION_RESULT_INVALID_CRYPTO_KEY_HEADER,
                 IncomingMessage());
    return;
  }

  // Use |fallback_to_empty_authorized_entity|, since this message might have
  // been sent to either an InstanceID token or a non-InstanceID registration.
  key_store_->GetKeys(app_id, message.sender_id /* authorized_entity */,
                      true /* fallback_to_empty_authorized_entity */,
                      base::Bind(&GCMEncryptionProvider::DecryptMessageWithKey,
                                 weak_ptr_factory_.GetWeakPtr(), message,
                                 callback, encryption_header_iterator.salt(),
                                 dh, encryption_header_iterator.rs()));
}

void GCMEncryptionProvider::DidGetEncryptionInfo(
    const std::string& app_id,
    const std::string& authorized_entity,
    const EncryptionInfoCallback& callback,
    const KeyPair& pair,
    const std::string& auth_secret) {
  if (!pair.IsInitialized()) {
    key_store_->CreateKeys(
        app_id, authorized_entity,
        base::Bind(&GCMEncryptionProvider::DidCreateEncryptionInfo,
                   weak_ptr_factory_.GetWeakPtr(), callback));
    return;
  }

  DCHECK_EQ(KeyPair::ECDH_P256, pair.type());
  callback.Run(pair.public_key(), auth_secret);
}

void GCMEncryptionProvider::DidCreateEncryptionInfo(
    const EncryptionInfoCallback& callback,
    const KeyPair& pair,
    const std::string& auth_secret) {
  if (!pair.IsInitialized()) {
    callback.Run(std::string() /* p256dh */,
                 std::string() /* auth_secret */);
    return;
  }

  DCHECK_EQ(KeyPair::ECDH_P256, pair.type());
  callback.Run(pair.public_key(), auth_secret);
}

void GCMEncryptionProvider::DecryptMessageWithKey(
    const IncomingMessage& message,
    const MessageCallback& callback,
    const std::string& salt,
    const std::string& dh,
    uint64_t rs,
    const KeyPair& pair,
    const std::string& auth_secret) {
  if (!pair.IsInitialized()) {
    DLOG(ERROR) << "Unable to retrieve the keys for the incoming message.";
    callback.Run(DECRYPTION_RESULT_NO_KEYS, IncomingMessage());
    return;
  }

  DCHECK_EQ(KeyPair::ECDH_P256, pair.type());

  std::string shared_secret;
  if (!ComputeSharedP256Secret(pair.private_key(), pair.public_key_x509(), dh,
                               &shared_secret)) {
    DLOG(ERROR) << "Unable to calculate the shared secret.";
    callback.Run(DECRYPTION_RESULT_INVALID_SHARED_SECRET, IncomingMessage());
    return;
  }

  std::string plaintext;

  GCMMessageCryptographer cryptographer(pair.public_key(), dh, auth_secret);
  if (!cryptographer.Decrypt(message.raw_data, shared_secret, salt, rs,
                             &plaintext)) {
    DLOG(ERROR) << "Unable to decrypt the incoming data.";
    callback.Run(DECRYPTION_RESULT_INVALID_PAYLOAD, IncomingMessage());
    return;
  }

  IncomingMessage decrypted_message;
  decrypted_message.collapse_key = message.collapse_key;
  decrypted_message.sender_id = message.sender_id;
  decrypted_message.raw_data.swap(plaintext);
  decrypted_message.decrypted = true;

  // There must be no data associated with the decrypted message at this point,
  // to make sure that we don't end up in an infinite decryption loop.
  DCHECK_EQ(0u, decrypted_message.data.size());

  callback.Run(DECRYPTION_RESULT_DECRYPTED, decrypted_message);
}

}  // namespace gcm