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

Side by Side Diff: extensions/browser/api/cast_channel/cast_auth_util.cc

Issue 2709523008: [Cast Channel] Add support for nonce challenge to Cast channel authentication. (Closed)
Patch Set: Rebase-only Created 3 years, 9 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
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "extensions/browser/api/cast_channel/cast_auth_util.h" 5 #include "extensions/browser/api/cast_channel/cast_auth_util.h"
6 6
7 #include <vector> 7 #include <vector>
8 8
9 #include "base/feature_list.h" 9 #include "base/feature_list.h"
10 #include "base/logging.h" 10 #include "base/logging.h"
11 #include "base/macros.h" 11 #include "base/macros.h"
12 #include "base/memory/ptr_util.h"
13 #include "base/memory/singleton.h"
12 #include "base/metrics/histogram_macros.h" 14 #include "base/metrics/histogram_macros.h"
13 #include "base/strings/string_number_conversions.h" 15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/string_util.h"
14 #include "base/strings/stringprintf.h" 17 #include "base/strings/stringprintf.h"
15 #include "components/cast_certificate/cast_cert_validator.h" 18 #include "components/cast_certificate/cast_cert_validator.h"
16 #include "components/cast_certificate/cast_crl.h" 19 #include "components/cast_certificate/cast_crl.h"
20 #include "crypto/random.h"
17 #include "extensions/browser/api/cast_channel/cast_message_util.h" 21 #include "extensions/browser/api/cast_channel/cast_message_util.h"
18 #include "extensions/common/api/cast_channel/cast_channel.pb.h" 22 #include "extensions/common/api/cast_channel/cast_channel.pb.h"
19 #include "net/cert/x509_certificate.h" 23 #include "net/cert/x509_certificate.h"
20 #include "net/der/parse_values.h" 24 #include "net/der/parse_values.h"
21 25
22 namespace extensions { 26 namespace extensions {
23 namespace api { 27 namespace api {
24 namespace cast_channel { 28 namespace cast_channel {
25 namespace { 29 namespace {
26 30
27 const char kParseErrorPrefix[] = "Failed to parse auth message: "; 31 const char kParseErrorPrefix[] = "Failed to parse auth message: ";
28 32
29 // The maximum number of days a cert can live for. 33 // The maximum number of days a cert can live for.
30 const int kMaxSelfSignedCertLifetimeInDays = 4; 34 const int kMaxSelfSignedCertLifetimeInDays = 4;
31 35
36 // The size of the nonce challenge in bytes.
37 const int kNonceSizeInBytes = 16;
38
39 // The number of hours after which a nonce is regenerated.
40 long kNonceExpirationTimeInHours = 24;
41
32 // Enforce certificate revocation when enabled. 42 // Enforce certificate revocation when enabled.
33 // If disabled, any revocation failures are ignored. 43 // If disabled, any revocation failures are ignored.
34 // 44 //
35 // This flags only controls the enforcement. Revocation is checked regardless. 45 // This flags only controls the enforcement. Revocation is checked regardless.
36 // 46 //
37 // This flag tracks the changes necessary to fully enforce revocation. 47 // This flag tracks the changes necessary to fully enforce revocation.
38 const base::Feature kEnforceRevocationChecking{ 48 const base::Feature kEnforceRevocationChecking{
39 "CastCertificateRevocation", base::FEATURE_DISABLED_BY_DEFAULT}; 49 "CastCertificateRevocation", base::FEATURE_DISABLED_BY_DEFAULT};
40 50
51 // Enforce nonce checking when enabled.
52 // If disabled, the nonce value returned from the device is not checked against
53 // the one sent to the device. As a result, the nonce can be empty and omitted
54 // from the signature. This allows backwards compatibility with legacy Cast
55 // receivers.
56
57 const base::Feature kEnforceNonceChecking{"CastNonceEnforced",
58 base::FEATURE_DISABLED_BY_DEFAULT};
59
41 namespace cast_crypto = ::cast_certificate; 60 namespace cast_crypto = ::cast_certificate;
42 61
43 // Extracts an embedded DeviceAuthMessage payload from an auth challenge reply 62 // Extracts an embedded DeviceAuthMessage payload from an auth challenge reply
44 // message. 63 // message.
45 AuthResult ParseAuthMessage(const CastMessage& challenge_reply, 64 AuthResult ParseAuthMessage(const CastMessage& challenge_reply,
46 DeviceAuthMessage* auth_message) { 65 DeviceAuthMessage* auth_message) {
47 if (challenge_reply.payload_type() != CastMessage_PayloadType_BINARY) { 66 if (challenge_reply.payload_type() != CastMessage_PayloadType_BINARY) {
48 return AuthResult::CreateWithParseError( 67 return AuthResult::CreateWithParseError(
49 "Wrong payload type in challenge reply", 68 "Wrong payload type in challenge reply",
50 AuthResult::ERROR_WRONG_PAYLOAD_TYPE); 69 AuthResult::ERROR_WRONG_PAYLOAD_TYPE);
(...skipping 17 matching lines...) Expand all
68 base::IntToString(auth_message->error().error_type()), 87 base::IntToString(auth_message->error().error_type()),
69 AuthResult::ERROR_MESSAGE_ERROR); 88 AuthResult::ERROR_MESSAGE_ERROR);
70 } 89 }
71 if (!auth_message->has_response()) { 90 if (!auth_message->has_response()) {
72 return AuthResult::CreateWithParseError( 91 return AuthResult::CreateWithParseError(
73 "Auth message has no response field", AuthResult::ERROR_NO_RESPONSE); 92 "Auth message has no response field", AuthResult::ERROR_NO_RESPONSE);
74 } 93 }
75 return AuthResult(); 94 return AuthResult();
76 } 95 }
77 96
97 class CastNonce {
98 public:
99 static CastNonce* GetInstance() {
100 return base::Singleton<CastNonce,
101 base::LeakySingletonTraits<CastNonce>>::get();
102 }
103
104 static const std::string& Get() {
105 GetInstance()->EnsureNonceTimely();
106 return GetInstance()->nonce_;
107 }
108
109 private:
110 friend struct base::DefaultSingletonTraits<CastNonce>;
111
112 CastNonce() { GenerateNonce(); }
113 void GenerateNonce() {
114 // Create a cryptographically secure nonce.
115 crypto::RandBytes(base::WriteInto(&nonce_, kNonceSizeInBytes + 1),
116 kNonceSizeInBytes);
117 nonce_generation_time_ = base::Time::Now();
118 }
119
120 void EnsureNonceTimely() {
121 if (base::Time::Now() >
122 (nonce_generation_time_ +
123 base::TimeDelta::FromHours(kNonceExpirationTimeInHours))) {
124 GenerateNonce();
125 }
126 }
127
128 // The nonce challenge to send to the Cast receiver.
129 // The nonce is updated daily.
130 std::string nonce_;
131 base::Time nonce_generation_time_;
132 };
133
78 // Must match with histogram enum CastCertificateStatus. 134 // Must match with histogram enum CastCertificateStatus.
79 // This should never be reordered. 135 // This should never be reordered.
80 enum CertVerificationStatus { 136 enum CertVerificationStatus {
81 CERT_STATUS_OK, 137 CERT_STATUS_OK,
82 CERT_STATUS_INVALID_CRL, 138 CERT_STATUS_INVALID_CRL,
83 CERT_STATUS_VERIFICATION_FAILED, 139 CERT_STATUS_VERIFICATION_FAILED,
84 CERT_STATUS_REVOKED, 140 CERT_STATUS_REVOKED,
85 CERT_STATUS_COUNT, 141 CERT_STATUS_COUNT,
86 }; 142 };
87 143
144 // Must match with histogram enum CastNonce.
145 // This should never be reordered.
146 enum NonceVerificationStatus {
147 NONCE_MATCH,
148 NONCE_MISMATCH,
149 NONCE_MISSING,
150 NONCE_COUNT,
151 };
152
153 // Record certificate verification histogram events.
154 void RecordCertificateEvent(CertVerificationStatus event) {
155 UMA_HISTOGRAM_ENUMERATION("Cast.Channel.Certificate", event,
156 CERT_STATUS_COUNT);
157 }
158
159 // Record nonce verification histogram events.
160 void RecordNonceEvent(NonceVerificationStatus event) {
161 UMA_HISTOGRAM_ENUMERATION("Cast.Channel.Nonce", event, NONCE_COUNT);
162 }
163
88 } // namespace 164 } // namespace
89 165
90 AuthResult::AuthResult() 166 AuthResult::AuthResult()
91 : error_type(ERROR_NONE), channel_policies(POLICY_NONE) {} 167 : error_type(ERROR_NONE), channel_policies(POLICY_NONE) {}
92 168
93 AuthResult::AuthResult(const std::string& error_message, ErrorType error_type) 169 AuthResult::AuthResult(const std::string& error_message, ErrorType error_type)
94 : error_message(error_message), error_type(error_type) {} 170 : error_message(error_message), error_type(error_type) {}
95 171
96 AuthResult::~AuthResult() { 172 AuthResult::~AuthResult() {
97 } 173 }
98 174
99 // static 175 // static
100 AuthResult AuthResult::CreateWithParseError(const std::string& error_message, 176 AuthResult AuthResult::CreateWithParseError(const std::string& error_message,
101 ErrorType error_type) { 177 ErrorType error_type) {
102 return AuthResult(kParseErrorPrefix + error_message, error_type); 178 return AuthResult(kParseErrorPrefix + error_message, error_type);
103 } 179 }
104 180
105 AuthResult AuthenticateChallengeReply(const CastMessage& challenge_reply, 181 // static
106 const net::X509Certificate& peer_cert) { 182 AuthContext AuthContext::Create() {
107 DeviceAuthMessage auth_message; 183 return AuthContext(CastNonce::Get());
108 AuthResult result = ParseAuthMessage(challenge_reply, &auth_message); 184 }
109 if (!result.success()) { 185
110 return result; 186 AuthContext::AuthContext(const std::string& nonce) : nonce_(nonce) {}
187
188 AuthContext::~AuthContext() {}
189
190 AuthResult AuthContext::VerifySenderNonce(
191 const std::string& nonce_response) const {
192 if (nonce_ != nonce_response) {
193 if (nonce_response.empty()) {
194 RecordNonceEvent(NONCE_MISSING);
195 } else {
196 RecordNonceEvent(NONCE_MISMATCH);
197 }
198 if (base::FeatureList::IsEnabled(kEnforceNonceChecking)) {
199 return AuthResult("Sender nonce mismatched.",
200 AuthResult::ERROR_SENDER_NONCE_MISMATCH);
201 }
202 } else {
203 RecordNonceEvent(NONCE_MATCH);
111 } 204 }
205 return AuthResult();
206 }
112 207
208 // Verifies the peer certificate and populates |peer_cert_der| with the DER
209 // encoded certificate.
210 AuthResult VerifyTLSCertificate(const net::X509Certificate& peer_cert,
211 std::string* peer_cert_der,
212 const base::Time& verification_time) {
113 // Get the DER-encoded form of the certificate. 213 // Get the DER-encoded form of the certificate.
114 std::string peer_cert_der;
115 if (!net::X509Certificate::GetDEREncoded(peer_cert.os_cert_handle(), 214 if (!net::X509Certificate::GetDEREncoded(peer_cert.os_cert_handle(),
116 &peer_cert_der) || 215 peer_cert_der) ||
117 peer_cert_der.empty()) { 216 peer_cert_der->empty()) {
118 return AuthResult::CreateWithParseError( 217 return AuthResult::CreateWithParseError(
119 "Could not create DER-encoded peer cert.", 218 "Could not create DER-encoded peer cert.",
120 AuthResult::ERROR_CERT_PARSING_FAILED); 219 AuthResult::ERROR_CERT_PARSING_FAILED);
121 } 220 }
122 221
123 // Ensure the peer cert is valid and doesn't have an excessive remaining 222 // Ensure the peer cert is valid and doesn't have an excessive remaining
124 // lifetime. Although it is not verified as an X.509 certificate, the entire 223 // lifetime. Although it is not verified as an X.509 certificate, the entire
125 // structure is signed by the AuthResponse, so the validity field from X.509 224 // structure is signed by the AuthResponse, so the validity field from X.509
126 // is repurposed as this signature's expiration. 225 // is repurposed as this signature's expiration.
127 base::Time expiry = peer_cert.valid_expiry(); 226 base::Time expiry = peer_cert.valid_expiry();
128 base::Time lifetime_limit = 227 base::Time lifetime_limit =
129 base::Time::Now() + 228 verification_time +
130 base::TimeDelta::FromDays(kMaxSelfSignedCertLifetimeInDays); 229 base::TimeDelta::FromDays(kMaxSelfSignedCertLifetimeInDays);
131 if (peer_cert.valid_start().is_null() || 230 if (peer_cert.valid_start().is_null() ||
132 peer_cert.valid_start() > base::Time::Now()) { 231 peer_cert.valid_start() > verification_time) {
133 return AuthResult::CreateWithParseError( 232 return AuthResult::CreateWithParseError(
134 "Certificate's valid start date is in the future.", 233 "Certificate's valid start date is in the future.",
135 AuthResult::ERROR_TLS_CERT_VALID_START_DATE_IN_FUTURE); 234 AuthResult::ERROR_TLS_CERT_VALID_START_DATE_IN_FUTURE);
136 } 235 }
137 if (expiry.is_null() || peer_cert.HasExpired()) { 236 if (expiry.is_null() || peer_cert.valid_expiry() < verification_time) {
138 return AuthResult::CreateWithParseError("Certificate has expired.", 237 return AuthResult::CreateWithParseError("Certificate has expired.",
139 AuthResult::ERROR_TLS_CERT_EXPIRED); 238 AuthResult::ERROR_TLS_CERT_EXPIRED);
140 } 239 }
141 if (expiry > lifetime_limit) { 240 if (expiry > lifetime_limit) {
142 return AuthResult::CreateWithParseError( 241 return AuthResult::CreateWithParseError(
143 "Peer cert lifetime is too long.", 242 "Peer cert lifetime is too long.",
144 AuthResult::ERROR_TLS_CERT_VALIDITY_PERIOD_TOO_LONG); 243 AuthResult::ERROR_TLS_CERT_VALIDITY_PERIOD_TOO_LONG);
145 } 244 }
245 return AuthResult();
246 }
247
248 AuthResult AuthenticateChallengeReply(const CastMessage& challenge_reply,
249 const net::X509Certificate& peer_cert,
250 const AuthContext& auth_context) {
251 DeviceAuthMessage auth_message;
252 AuthResult result = ParseAuthMessage(challenge_reply, &auth_message);
253 if (!result.success()) {
254 return result;
255 }
256
257 std::string peer_cert_der;
258 result = VerifyTLSCertificate(peer_cert, &peer_cert_der, base::Time::Now());
259 if (!result.success()) {
260 return result;
261 }
146 262
147 const AuthResponse& response = auth_message.response(); 263 const AuthResponse& response = auth_message.response();
148 return VerifyCredentials(response, peer_cert_der); 264 const std::string& nonce_response = response.sender_nonce();
265
266 result = auth_context.VerifySenderNonce(nonce_response);
267 if (!result.success()) {
268 return result;
269 }
270
271 return VerifyCredentials(response, nonce_response + peer_cert_der);
149 } 272 }
150 273
151 // This function does the following 274 // This function does the following
152 // 275 //
153 // * Verifies that the certificate chain |response.client_auth_certificate| + 276 // * Verifies that the certificate chain |response.client_auth_certificate| +
154 // |response.intermediate_certificate| is valid and chains to a trusted 277 // |response.intermediate_certificate| is valid and chains to a trusted
155 // Cast root. The list of trusted Cast roots can be overrided by providing a 278 // Cast root. The list of trusted Cast roots can be overrided by providing a
156 // non-nullptr |cast_trust_store|. The certificate is verified at 279 // non-nullptr |cast_trust_store|. The certificate is verified at
157 // |verification_time|. 280 // |verification_time|.
158 // 281 //
(...skipping 23 matching lines...) Expand all
182 cert_chain.insert(cert_chain.end(), 305 cert_chain.insert(cert_chain.end(),
183 response.intermediate_certificate().begin(), 306 response.intermediate_certificate().begin(),
184 response.intermediate_certificate().end()); 307 response.intermediate_certificate().end());
185 308
186 // Parse the CRL. 309 // Parse the CRL.
187 std::unique_ptr<cast_crypto::CastCRL> crl = 310 std::unique_ptr<cast_crypto::CastCRL> crl =
188 cast_crypto::ParseAndVerifyCRLUsingCustomTrustStore( 311 cast_crypto::ParseAndVerifyCRLUsingCustomTrustStore(
189 response.crl(), verification_time, crl_trust_store); 312 response.crl(), verification_time, crl_trust_store);
190 if (!crl) { 313 if (!crl) {
191 // CRL is invalid. 314 // CRL is invalid.
192 UMA_HISTOGRAM_ENUMERATION("Cast.Channel.Certificate", 315 RecordCertificateEvent(CERT_STATUS_INVALID_CRL);
193 CERT_STATUS_INVALID_CRL, CERT_STATUS_COUNT);
194 if (crl_policy == cast_crypto::CRLPolicy::CRL_REQUIRED) { 316 if (crl_policy == cast_crypto::CRLPolicy::CRL_REQUIRED) {
195 return AuthResult("Failed verifying Cast CRL.", 317 return AuthResult("Failed verifying Cast CRL.",
196 AuthResult::ERROR_CRL_INVALID); 318 AuthResult::ERROR_CRL_INVALID);
197 } 319 }
198 } 320 }
199 321
200 cast_crypto::CastDeviceCertPolicy device_policy; 322 cast_crypto::CastDeviceCertPolicy device_policy;
201 bool verification_success = 323 bool verification_success =
202 cast_crypto::VerifyDeviceCertUsingCustomTrustStore( 324 cast_crypto::VerifyDeviceCertUsingCustomTrustStore(
203 cert_chain, verification_time, &verification_context, &device_policy, 325 cert_chain, verification_time, &verification_context, &device_policy,
204 crl.get(), crl_policy, cast_trust_store); 326 crl.get(), crl_policy, cast_trust_store);
205 if (!verification_success) { 327 if (!verification_success) {
206 // TODO(ryanchung): Once this feature is completely rolled-out, remove the 328 // TODO(ryanchung): Once this feature is completely rolled-out, remove the
207 // reverification step and use error reporting to get verification errors 329 // reverification step and use error reporting to get verification errors
208 // for metrics. 330 // for metrics.
209 bool verification_no_crl_success = 331 bool verification_no_crl_success =
210 cast_crypto::VerifyDeviceCertUsingCustomTrustStore( 332 cast_crypto::VerifyDeviceCertUsingCustomTrustStore(
211 cert_chain, verification_time, &verification_context, 333 cert_chain, verification_time, &verification_context,
212 &device_policy, nullptr, cast_crypto::CRLPolicy::CRL_OPTIONAL, 334 &device_policy, nullptr, cast_crypto::CRLPolicy::CRL_OPTIONAL,
213 cast_trust_store); 335 cast_trust_store);
214 if (!verification_no_crl_success) { 336 if (!verification_no_crl_success) {
215 // TODO(eroman): The error information was lost; this error is ambiguous. 337 // TODO(eroman): The error information was lost; this error is ambiguous.
216 UMA_HISTOGRAM_ENUMERATION("Cast.Channel.Certificate", 338 RecordCertificateEvent(CERT_STATUS_VERIFICATION_FAILED);
217 CERT_STATUS_VERIFICATION_FAILED,
218 CERT_STATUS_COUNT);
219 return AuthResult("Failed verifying cast device certificate", 339 return AuthResult("Failed verifying cast device certificate",
220 AuthResult::ERROR_CERT_NOT_SIGNED_BY_TRUSTED_CA); 340 AuthResult::ERROR_CERT_NOT_SIGNED_BY_TRUSTED_CA);
221 } 341 }
222 if (crl) { 342 if (crl) {
223 // If CRL was not present, it should've been recorded as such. 343 // If CRL was not present, it should've been recorded as such.
224 UMA_HISTOGRAM_ENUMERATION("Cast.Channel.Certificate", CERT_STATUS_REVOKED, 344 RecordCertificateEvent(CERT_STATUS_REVOKED);
225 CERT_STATUS_COUNT);
226 } 345 }
227 if (crl_policy == cast_crypto::CRLPolicy::CRL_REQUIRED) { 346 if (crl_policy == cast_crypto::CRLPolicy::CRL_REQUIRED) {
228 // Device is revoked. 347 // Device is revoked.
229 return AuthResult("Failed certificate revocation check.", 348 return AuthResult("Failed certificate revocation check.",
230 AuthResult::ERROR_CERT_REVOKED); 349 AuthResult::ERROR_CERT_REVOKED);
231 } 350 }
232 } 351 }
233 // The certificate is verified at this point. 352 // The certificate is verified at this point.
234 UMA_HISTOGRAM_ENUMERATION("Cast.Channel.Certificate", CERT_STATUS_OK, 353 RecordCertificateEvent(CERT_STATUS_OK);
235 CERT_STATUS_COUNT);
236 if (!verification_context->VerifySignatureOverData(response.signature(), 354 if (!verification_context->VerifySignatureOverData(response.signature(),
237 signature_input)) { 355 signature_input)) {
238 return AuthResult("Failed verifying signature over data", 356 return AuthResult("Failed verifying signature over data",
239 AuthResult::ERROR_SIGNED_BLOBS_MISMATCH); 357 AuthResult::ERROR_SIGNED_BLOBS_MISMATCH);
240 } 358 }
241 359
242 AuthResult success; 360 AuthResult success;
243 361
244 // Set the policy into the result. 362 // Set the policy into the result.
245 switch (device_policy) { 363 switch (device_policy) {
(...skipping 26 matching lines...) Expand all
272 net::TrustStore* crl_trust_store, 390 net::TrustStore* crl_trust_store,
273 const base::Time& verification_time) { 391 const base::Time& verification_time) {
274 return VerifyCredentialsImpl(response, signature_input, crl_policy, 392 return VerifyCredentialsImpl(response, signature_input, crl_policy,
275 cast_trust_store, crl_trust_store, 393 cast_trust_store, crl_trust_store,
276 verification_time); 394 verification_time);
277 } 395 }
278 396
279 } // namespace cast_channel 397 } // namespace cast_channel
280 } // namespace api 398 } // namespace api
281 } // namespace extensions 399 } // namespace extensions
OLDNEW
« no previous file with comments | « extensions/browser/api/cast_channel/cast_auth_util.h ('k') | extensions/browser/api/cast_channel/cast_auth_util_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698