Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(639)

Side by Side Diff: google_apis/cup/client_update_protocol.cc

Issue 15793005: Per discussion, implement the Omaha Client Update Protocol (CUP) in src/crypto. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: Created 7 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2013 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 "google_apis/cup/client_update_protocol.h"
6
7 #include "base/base64.h"
8 #include "base/logging.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/sha1.h"
11 #include "base/string_util.h"
12 #include "base/stringprintf.h"
13 #include "crypto/hmac.h"
14 #include "crypto/random.h"
15
16 namespace {
17
18 base::StringPiece ByteVectorToSP(const std::vector<uint8>& vec) {
19 return base::StringPiece(reinterpret_cast<const char*>(&vec[0]), vec.size());
20 }
21
22 // This class needs to implement the same hashing and signing functions as the
23 // Google Update server; for now, this is SHA-1 and HMAC-SHA1, but this may
24 // change to SHA-256 in the near future. For this reason, all primitives are
25 // wrapped. The name "SymSign" is used to mirror the CUP specification.
26 size_t HashDigestSize() {
27 return base::kSHA1Length;
28 }
29
30 std::vector<uint8> Hash(const std::vector<uint8>& data) {
31 std::vector<uint8> result(HashDigestSize());
32 base::SHA1HashBytes(data.empty() ? NULL : &data[0],
33 data.size(),
34 &result[0]);
35 return result;
36 }
37
38 std::vector<uint8> Hash(const base::StringPiece& sdata) {
39 std::vector<uint8> result(HashDigestSize());
40 base::SHA1HashBytes(sdata.empty() ?
41 NULL :
42 reinterpret_cast<const unsigned char*>(sdata.data()),
43 sdata.length(),
44 &result[0]);
45 return result;
46 }
47
48 std::vector<uint8> SymConcat(uint8 id,
49 const std::vector<uint8>* h1,
50 const std::vector<uint8>* h2,
51 const std::vector<uint8>* h3) {
52 std::vector<uint8> result;
53 result.push_back(id);
54 const std::vector<uint8>* args[] = { h1, h2, h3 };
55 for (size_t i = 0; i != arraysize(args); ++i) {
56 if (args[i]) {
57 DCHECK_EQ(args[i]->size(), HashDigestSize());
58 result.insert(result.end(), args[i]->begin(), args[i]->end());
59 }
60 }
61
62 return result;
63 }
64
65 std::vector<uint8> SymSign(const std::vector<uint8>& key,
66 const std::vector<uint8>& hashes) {
67 crypto::HMAC hmac(crypto::HMAC::SHA1);
68 if (!hmac.Init(&key[0], key.size()))
69 return std::vector<uint8>();
70
71 std::vector<uint8> result(hmac.DigestLength());
72 if (!hmac.Sign(ByteVectorToSP(hashes), &result[0], result.size()))
73 return std::vector<uint8>();
74
75 return result;
76 }
77
78 bool SymSignVerify(const std::vector<uint8>& key,
79 const std::vector<uint8>& hashes,
80 const std::vector<uint8>& server_proof) {
81 crypto::HMAC hmac(crypto::HMAC::SHA1);
82 if (!hmac.Init(&key[0], key.size()))
83 return false;
84
85 return hmac.Verify(ByteVectorToSP(hashes), ByteVectorToSP(server_proof));
Ryan Sleevi 2013/06/06 19:59:10 If either |hashes| or |server_proof| are empty, th
Ryan Myers (chromium) 2013/06/06 21:09:10 Done. (Added safety to ByteVectorToSP, and also a
86 }
87
88 // RsaPad() is implemented as described in the CUP spec. It is NOT a general
89 // purpose padding algorithm.
90 std::vector<uint8> RsaPad(size_t rsa_key_size,
91 const std::vector<uint8>& entropy) {
92 DCHECK_GE(rsa_key_size, HashDigestSize());
93
94 // The result gets padded with zeros if the result size is greater than
95 // the size of the buffer provided by the caller.
96 std::vector<uint8> result(entropy);
97 result.resize(rsa_key_size - HashDigestSize());
98
99 // For use with RSA, the input needs to be smaller than the RSA modulus,
100 // which has always the msb set.
101 result[0] &= 127; // Reset msb
102 result[0] |= 64; // Set second highest bit.
103
104 std::vector<uint8> digest = Hash(result);
105 result.insert(result.end(), digest.begin(), digest.end());
106 DCHECK_EQ(result.size(), rsa_key_size);
107 return result;
108 }
109
110 // CUP passes the versioned secret in the query portion of the URL for the
111 // update check service -- that means we need URL-safe variants of Base64.
112 // Omaha has its own implementation in base/security/b64.c; for Chromium,
113 // call the standard Base64 encoder/decoder and then apply fixups.
114 std::string UrlSafeB64Encode(const std::vector<uint8>& data) {
115 std::string result;
116 if (!base::Base64Encode(ByteVectorToSP(data), &result)) {
117 return std::string();
118 }
Ryan Sleevi 2013/06/06 19:59:10 nit: drop the braces - you start off not using the
Ryan Myers (chromium) 2013/06/06 21:09:10 Done.
119
120 // Do an tr|+/|-_| on the output, and strip any '=' padding.
121 for (std::string::iterator it = result.begin(); it != result.end(); ++it) {
122 switch (*it) {
123 case '+':
124 *it = '-';
125 break;
126 case '/':
127 *it = '_';
128 break;
129 default:
130 break;
131 }
132 }
133 TrimString(result, "=", &result);
134
135 return result;
136 }
137
138 std::vector<uint8> UrlSafeB64Decode(const base::StringPiece& input) {
Ryan Sleevi 2013/06/06 19:59:10 In the Chromium compiler chain, you're guaranteed
Ryan Myers (chromium) 2013/06/06 21:09:10 I'm okay with the copying in this case, given that
139 std::string unsafe(input.begin(), input.end());
140 for (std::string::iterator it = unsafe.begin(); it != unsafe.end(); ++it) {
141 switch (*it) {
142 case '-':
143 *it = '+';
144 break;
145 case '_':
146 *it = '/';
147 break;
148 default:
149 break;
150 }
151 }
152 while (unsafe.length() % 4 != 0) {
153 unsafe.append("=");
Ryan Sleevi 2013/06/06 19:59:10 nit: switch the while loop with just unsafe.appen
Ryan Myers (chromium) 2013/06/06 21:09:10 NACK -- that has different behavior entirely. Whi
154 }
155
156 std::string decoded;
157 if (!base::Base64Decode(unsafe, &decoded)) {
158 return std::vector<uint8>();
159 }
160
161 return std::vector<uint8>(decoded.begin(), decoded.end());
162 }
163
164 } // end namespace
165
166 ClientUpdateProtocol::ClientUpdateProtocol(int key_version)
167 : pub_key_version_(key_version) {
168 }
169
170 ClientUpdateProtocol* ClientUpdateProtocol::Create(
171 int key_version,
172 const base::StringPiece& public_key) {
173 DCHECK_GT(key_version, 0);
174 DCHECK(!public_key.empty());
175 if (key_version <= 0 || public_key.empty())
176 return NULL; // At least one mandatory parameter is not valid.
177
178 scoped_ptr<ClientUpdateProtocol> result(
179 new ClientUpdateProtocol(key_version));
180 if (!result.get())
181 return NULL;
182
183 if (!result->LoadPublicKey(public_key))
184 return NULL; // Public key couldn't be loaded.
185
186 size_t key_size = result->PublicKeyLength();
187 if (key_size < HashDigestSize())
188 return NULL; // Public key is too small to be used.
189
190 if (!result->BuildSharedKey(key_size, NULL))
191 return NULL; // Failed to generate w.
192
193 return result.release();
Ryan Sleevi 2013/06/06 19:59:10 with the updated sig, this would be result.Pass()
Ryan Myers (chromium) 2013/06/06 21:09:10 Done.
194 }
195
196 std::string ClientUpdateProtocol::GetVersionedSecret() const {
197 return base::StringPrintf("%d:%s",
198 pub_key_version_,
199 UrlSafeB64Encode(encrypted_key_source_).c_str());
200 }
201
202 bool ClientUpdateProtocol::SignRequest(const base::StringPiece& url,
203 const base::StringPiece& request_body,
204 std::string* client_proof) {
205 if (encrypted_key_source_.empty())
206 return false; // Init() hasn't been called, and/or BuildSharedKey failed.
Ryan Sleevi 2013/06/06 19:59:10 Doesn't this make more sense to DCHECK(), rather t
Ryan Myers (chromium) 2013/06/06 21:09:10 Done.
207
208 // Compute the challenge hash:
209 // hw = HASH(HASH(v|w)|HASH(request_url)|HASH(body)).
210 // Keep the challenge hash for later to validate the server's response.
211 std::vector<uint8> internal_hashes;
212
213 std::vector<uint8> h;
214 h = Hash(GetVersionedSecret());
215 internal_hashes.insert(internal_hashes.end(), h.begin(), h.end());
216 h = Hash(url);
217 internal_hashes.insert(internal_hashes.end(), h.begin(), h.end());
218 h = Hash(request_body);
219 internal_hashes.insert(internal_hashes.end(), h.begin(), h.end());
220 DCHECK_EQ(internal_hashes.size(), 3 * HashDigestSize());
221
222 client_challenge_hash_ = Hash(internal_hashes);
223
224 // Sign the challenge hash (hw) using the shared key (sk) to produce the
225 // client proof (cp).
226 std::vector<uint8> raw_client_proof =
227 SymSign(shared_key_, SymConcat(3, &client_challenge_hash_, NULL, NULL));
228 if (raw_client_proof.empty()) {
229 client_challenge_hash_.clear();
230 return false;
231 }
232
233 if (client_proof)
234 *client_proof = UrlSafeB64Encode(raw_client_proof);
235
236 return true;
237 }
238
239 bool ClientUpdateProtocol::ValidateResponse(
240 const base::StringPiece& response_body,
241 const base::StringPiece& server_cookie,
242 const base::StringPiece& server_proof) {
243 if (client_challenge_hash_.empty())
244 return false; // There hasn't been a call to SignRequest() yet.
Ryan Sleevi 2013/06/06 19:59:10 Same comments here re: DCHECK
Ryan Myers (chromium) 2013/06/06 21:09:10 Done.
245
246 // Decode the server proof from URL-safe Base64 to a binary HMAC for the
247 // response.
248 std::vector<uint8> sp_decoded = UrlSafeB64Decode(server_proof);
249 if (sp_decoded.empty())
250 return false;
251
252 // If the request was received by the server, the server will use its
253 // private key to decrypt |w_|, yielding the original contents of |r_|.
254 // The server can then recreate |sk_|, compute |hw_|, and SymSign(3|hw)
255 // to ensure that the cp matches the contents. It will then use |sk_|
256 // to sign its response, producing the server proof |sp|.
257 std::vector<uint8> hm = Hash(response_body);
258 std::vector<uint8> hc = Hash(server_cookie);
259 return SymSignVerify(shared_key_,
260 SymConcat(1, &client_challenge_hash_, &hm, &hc),
261 sp_decoded);
262 }
263
264 bool ClientUpdateProtocol::BuildSharedKey(size_t public_key_length,
265 const uint8* opt_key_source) {
266 // Start by generating some random bytes that are suitable to be encrypted;
267 // this will be the source of the shared HMAC key that client and server use.
268 // (CUP specification calls this "r".)
269
Ryan Sleevi 2013/06/06 19:59:10 drop the newline.
Ryan Myers (chromium) 2013/06/06 21:09:10 Done.
270 DCHECK_GE(public_key_length, HashDigestSize());
271 if (public_key_length < HashDigestSize())
272 return false;
Ryan Sleevi 2013/06/06 19:59:10 Per http://www.chromium.org/developers/coding-styl
Ryan Myers (chromium) 2013/06/06 21:09:10 Done, both here and elsewhere.
273
274 std::vector<uint8> key_source;
275 if (opt_key_source) {
276 key_source.assign(opt_key_source, opt_key_source + public_key_length);
277 } else {
278 std::vector<uint8> entropy(public_key_length - HashDigestSize());
279 crypto::RandBytes(&entropy[0], entropy.size());
280
281 key_source = RsaPad(public_key_length, entropy);
282 }
283 DCHECK_EQ(public_key_length, key_source.size());
284
285 // Hash the key source (r) to generate a new shared HMAC key (sk').
286 shared_key_ = Hash(key_source);
287
288 // Encrypt the key source (r) using the public key (pk[v]) to generate the
289 // encrypted key source (w).
290 if (!EncryptKeySource(key_source))
291 return false;
292 if (encrypted_key_source_.size() != public_key_length)
293 return false;
294
295 return true;
296 }
297
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698