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

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));
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 }
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) {
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("=");
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() {
171 }
172
173 ClientUpdateProtocol* ClientUpdateProtocol::Create(
174 int key_version,
175 const base::StringPiece& public_key) {
176 DCHECK_GT(key_version, 0);
177 DCHECK(!public_key.empty());
178 if (key_version <= 0 || public_key.empty())
179 return NULL; // At least one mandatory parameter is not valid.
180
181 scoped_ptr<ClientUpdateProtocol> result(
182 new ClientUpdateProtocol(key_version));
183 if (!result.get())
184 return NULL;
185
186 result->public_key_impl_.reset(GetCupKeyImpl(public_key));
187 if (!result->public_key_impl_.get())
188 return NULL; // Public key couldn't be loaded.
189
190 size_t key_size = result->public_key_impl_->PublicKeyLength();
191 if (key_size < HashDigestSize())
192 return NULL; // Public key is too small to be used.
193
194 if (!result->BuildSharedKey(key_size, NULL))
195 return NULL; // Failed to generate w.
196
197 return result.release();
198 }
199
200 std::string ClientUpdateProtocol::GetVersionedSecret() const {
201 return base::StringPrintf("%d:%s",
202 pub_key_version_,
203 UrlSafeB64Encode(encrypted_key_source_).c_str());
204 }
205
206 bool ClientUpdateProtocol::SignRequest(const base::StringPiece& url,
207 const base::StringPiece& request_body,
208 std::string* client_proof) {
209 if (encrypted_key_source_.empty())
210 return false; // Init() hasn't been called, and/or BuildSharedKey failed.
211
212 // Compute the challenge hash:
213 // hw = HASH(HASH(v|w)|HASH(request_url)|HASH(body)).
214 // Keep the challenge hash for later to validate the server's response.
215 std::vector<uint8> internal_hashes;
216
217 std::vector<uint8> h;
218 h = Hash(GetVersionedSecret());
219 internal_hashes.insert(internal_hashes.end(), h.begin(), h.end());
220 h = Hash(url);
221 internal_hashes.insert(internal_hashes.end(), h.begin(), h.end());
222 h = Hash(request_body);
223 internal_hashes.insert(internal_hashes.end(), h.begin(), h.end());
224 DCHECK_EQ(internal_hashes.size(), 3 * HashDigestSize());
225
226 client_challenge_hash_ = Hash(internal_hashes);
227
228 // Sign the challenge hash (hw) using the shared key (sk) to produce the
229 // client proof (cp).
230 std::vector<uint8> raw_client_proof =
231 SymSign(shared_key_, SymConcat(3, &client_challenge_hash_, NULL, NULL));
232 if (raw_client_proof.empty()) {
233 client_challenge_hash_.clear();
234 return false;
235 }
236
237 if (client_proof)
238 *client_proof = UrlSafeB64Encode(raw_client_proof);
239
240 return true;
241 }
242
243 bool ClientUpdateProtocol::ValidateResponse(
244 const base::StringPiece& response_body,
245 const base::StringPiece& server_cookie,
246 const base::StringPiece& server_proof) {
247 if (client_challenge_hash_.empty())
248 return false; // There hasn't been a call to SignRequest() yet.
249
250 // Decode the server proof from URL-safe Base64 to a binary HMAC for the
251 // response.
252 std::vector<uint8> sp_decoded = UrlSafeB64Decode(server_proof);
253 if (sp_decoded.empty())
254 return false;
255
256 // If the request was received by the server, the server will use its
257 // private key to decrypt |w_|, yielding the original contents of |r_|.
258 // The server can then recreate |sk_|, compute |hw_|, and SymSign(3|hw)
259 // to ensure that the cp matches the contents. It will then use |sk_|
260 // to sign its response, producing the server proof |sp|.
261 std::vector<uint8> hm = Hash(response_body);
262 std::vector<uint8> hc = Hash(server_cookie);
263 return SymSignVerify(shared_key_,
264 SymConcat(1, &client_challenge_hash_, &hm, &hc),
265 sp_decoded);
266 }
267
268 bool ClientUpdateProtocol::BuildSharedKey(size_t public_key_length,
269 const uint8* opt_key_source) {
270 // Start by generating some random bytes that are suitable to be encrypted;
271 // this will be the source of the shared HMAC key that client and server use.
272 // (CUP specification calls this "r".)
273
274 DCHECK_GE(public_key_length, HashDigestSize());
275 if (public_key_length < HashDigestSize())
276 return false;
277
278 std::vector<uint8> key_source;
279 if (opt_key_source) {
280 key_source.assign(opt_key_source, opt_key_source + public_key_length);
281 } else {
282 std::vector<uint8> entropy(public_key_length - HashDigestSize());
283 crypto::RandBytes(&entropy[0], entropy.size());
284
285 key_source = RsaPad(public_key_length, entropy);
286 }
287 DCHECK_EQ(public_key_length, key_source.size());
288
289 // Hash the key source (r) to generate a new shared HMAC key (sk').
290 shared_key_ = Hash(key_source);
291
292 // Encrypt the key source (r) using the public key (pk[v]) to generate the
293 // encrypted key source (w).
294 encrypted_key_source_ = public_key_impl_->EncryptKeySource(key_source);
295 if (encrypted_key_source_.size() != public_key_length)
296 return false;
297
298 return true;
299 }
300
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698