networking_private_crypto_openssl.cc revision 5f1c94371a64b3196d4be9466099bb892df9b88e
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
3// found in the LICENSE file.
4
5#include "chrome/common/extensions/api/networking_private/networking_private_crypto.h"
6
7#include <openssl/digest.h>
8#include <openssl/evp.h>
9#include <openssl/rsa.h>
10#include <openssl/x509.h>
11
12#include "base/logging.h"
13#include "base/strings/string_util.h"
14#include "crypto/openssl_util.h"
15#include "crypto/rsa_private_key.h"
16#include "crypto/scoped_openssl_types.h"
17#include "net/cert/pem_tokenizer.h"
18
19namespace {
20
21typedef crypto::ScopedOpenSSL<X509, X509_free>::Type ScopedX509;
22
23// Parses |pem_data| for a PEM block of |pem_type|.
24// Returns true if a |pem_type| block is found, storing the decoded result in
25// |der_output|.
26bool GetDERFromPEM(const std::string& pem_data,
27                   const std::string& pem_type,
28                   std::vector<uint8_t>* der_output) {
29  std::vector<std::string> headers;
30  headers.push_back(pem_type);
31  net::PEMTokenizer pem_tok(pem_data, headers);
32  if (!pem_tok.GetNext()) {
33    return false;
34  }
35
36  der_output->assign(pem_tok.data().begin(), pem_tok.data().end());
37  return true;
38}
39
40}  // namespace
41
42bool NetworkingPrivateCrypto::VerifyCredentials(
43    const std::string& certificate,
44    const std::string& signature,
45    const std::string& data,
46    const std::string& connected_mac) {
47  crypto::EnsureOpenSSLInit();
48  crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
49
50  std::vector<uint8_t> cert_data;
51  if (!GetDERFromPEM(certificate, "CERTIFICATE", &cert_data)) {
52    LOG(ERROR) << "Failed to parse certificate.";
53    return false;
54  }
55
56  // Parse into an OpenSSL X509.
57  const uint8_t* ptr = cert_data.empty() ? NULL : &cert_data[0];
58  const uint8_t* end = ptr + cert_data.size();
59  ScopedX509 cert(d2i_X509(NULL, &ptr, cert_data.size()));
60  if (!cert || ptr != end) {
61    LOG(ERROR) << "Failed to parse certificate.";
62    return false;
63  }
64
65  // Import the trusted public key.
66  ptr = kTrustedCAPublicKeyDER;
67  crypto::ScopedRSA ca_public_key_rsa(
68      d2i_RSAPublicKey(NULL, &ptr, kTrustedCAPublicKeyDERLength));
69  if (!ca_public_key_rsa ||
70      ptr != kTrustedCAPublicKeyDER + kTrustedCAPublicKeyDERLength) {
71    NOTREACHED();
72    LOG(ERROR) << "Failed to import trusted public key.";
73    return false;
74  }
75  crypto::ScopedEVP_PKEY ca_public_key(EVP_PKEY_new());
76  if (!ca_public_key ||
77      !EVP_PKEY_set1_RSA(ca_public_key.get(), ca_public_key_rsa.get())) {
78    LOG(ERROR) << "Failed to initialize EVP_PKEY";
79    return false;
80  }
81
82  // Check that the certificate is signed by the trusted public key.
83  if (X509_verify(cert.get(), ca_public_key.get()) <= 0) {
84    LOG(ERROR) << "Certificate is not issued by the trusted CA.";
85    return false;
86  }
87
88  // Check that the device listed in the certificate is correct.
89  // Something like evt_e161 001a11ffacdf
90  std::string common_name;
91  int common_name_length = X509_NAME_get_text_by_NID(
92      cert->cert_info->subject, NID_commonName, NULL, 0);
93  if (common_name_length < 0) {
94    LOG(ERROR) << "Certificate does not have common name.";
95    return false;
96  }
97  if (common_name_length > 0) {
98    common_name_length = X509_NAME_get_text_by_NID(
99        cert->cert_info->subject,
100        NID_commonName,
101        WriteInto(&common_name, common_name_length + 1),
102        common_name_length + 1);
103    DCHECK_EQ((int)common_name.size(), common_name_length);
104    if (common_name_length < 0) {
105      LOG(ERROR) << "Certificate does not have common name.";
106      return false;
107    }
108    common_name.resize(common_name_length);
109  }
110
111  std::string translated_mac;
112  base::RemoveChars(connected_mac, ":", &translated_mac);
113  if (!EndsWith(common_name, translated_mac, false)) {
114    LOG(ERROR) << "MAC addresses don't match.";
115    return false;
116  }
117
118  // Make sure that the certificate matches the unsigned data presented.
119  // Verify that the |signature| matches |data|.
120  crypto::ScopedEVP_PKEY public_key(X509_get_pubkey(cert.get()));
121  if (!public_key) {
122    LOG(ERROR) << "Unable to extract public key from certificate.";
123    return false;
124  }
125
126  crypto::ScopedEVP_MD_CTX ctx(EVP_MD_CTX_create());
127  if (!ctx) {
128    LOG(ERROR) << "Unable to allocate EVP_MD_CTX.";
129    return false;
130  }
131  if (EVP_DigestVerifyInit(
132          ctx.get(), NULL, EVP_sha1(), NULL, public_key.get()) <= 0 ||
133      EVP_DigestVerifyUpdate(ctx.get(), data.data(), data.size()) <= 0 ||
134      EVP_DigestVerifyFinal(ctx.get(),
135                            reinterpret_cast<const uint8_t*>(signature.data()),
136                            signature.size()) <= 0) {
137    LOG(ERROR) << "Signed blobs did not match.";
138    return false;
139  }
140  return true;
141}
142
143bool NetworkingPrivateCrypto::EncryptByteString(
144    const std::vector<uint8_t>& pub_key_der,
145    const std::string& data,
146    std::vector<uint8_t>* encrypted_output) {
147  crypto::EnsureOpenSSLInit();
148  crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
149
150  const uint8_t* ptr = pub_key_der.empty() ? NULL : &pub_key_der[0];
151  const uint8_t* end = ptr + pub_key_der.size();
152  crypto::ScopedRSA rsa(d2i_RSAPublicKey(NULL, &ptr, pub_key_der.size()));
153  if (!rsa || ptr != end || RSA_size(rsa.get()) == 0) {
154    LOG(ERROR) << "Failed to parse public key";
155    return false;
156  }
157
158  scoped_ptr<uint8_t[]> rsa_output(new uint8_t[RSA_size(rsa.get())]);
159  int encrypted_length =
160      RSA_public_encrypt(data.size(),
161                         reinterpret_cast<const uint8_t*>(data.data()),
162                         rsa_output.get(),
163                         rsa.get(),
164                         RSA_PKCS1_PADDING);
165  if (encrypted_length < 0) {
166    LOG(ERROR) << "Error during decryption";
167    return false;
168  }
169  encrypted_output->assign(rsa_output.get(),
170                           rsa_output.get() + encrypted_length);
171  return true;
172}
173
174bool NetworkingPrivateCrypto::DecryptByteString(
175    const std::string& private_key_pem,
176    const std::vector<uint8_t>& encrypted_data,
177    std::string* decrypted_output) {
178  crypto::EnsureOpenSSLInit();
179  crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
180
181  std::vector<uint8_t> private_key_data;
182  if (!GetDERFromPEM(private_key_pem, "PRIVATE KEY", &private_key_data)) {
183    LOG(ERROR) << "Failed to parse private key PEM.";
184    return false;
185  }
186  scoped_ptr<crypto::RSAPrivateKey> private_key(
187      crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(private_key_data));
188  if (!private_key || !private_key->key()) {
189    LOG(ERROR) << "Failed to parse private key DER.";
190    return false;
191  }
192
193  crypto::ScopedRSA rsa(EVP_PKEY_get1_RSA(private_key->key()));
194  if (!rsa || RSA_size(rsa.get()) == 0) {
195    LOG(ERROR) << "Failed to get RSA key.";
196    return false;
197  }
198
199  scoped_ptr<uint8_t[]> rsa_output(new uint8_t[RSA_size(rsa.get())]);
200  int output_length = RSA_private_decrypt(encrypted_data.size(),
201                                          &encrypted_data[0],
202                                          rsa_output.get(),
203                                          rsa.get(),
204                                          RSA_PKCS1_PADDING);
205  if (output_length < 0) {
206    LOG(ERROR) << "Error during decryption.";
207    return false;
208  }
209  decrypted_output->assign(reinterpret_cast<char*>(rsa_output.get()),
210                           output_length);
211  return true;
212}
213