networking_private_crypto_nss.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 <cert.h>
8#include <cryptohi.h>
9#include <keyhi.h>
10#include <keythi.h>
11#include <pk11pub.h>
12#include <sechash.h>
13#include <secport.h>
14
15#include "base/base64.h"
16#include "base/memory/scoped_ptr.h"
17#include "base/strings/string_number_conversions.h"
18#include "base/strings/string_util.h"
19#include "base/strings/stringprintf.h"
20#include "crypto/nss_util.h"
21#include "crypto/rsa_private_key.h"
22#include "crypto/scoped_nss_types.h"
23#include "net/cert/pem_tokenizer.h"
24#include "net/cert/x509_certificate.h"
25
26namespace {
27
28// Parses |pem_data| for a PEM block of |pem_type|.
29// Returns true if a |pem_type| block is found, storing the decoded result in
30// |der_output|.
31bool GetDERFromPEM(const std::string& pem_data,
32                   const std::string& pem_type,
33                   std::vector<uint8_t>* der_output) {
34  std::vector<std::string> headers;
35  headers.push_back(pem_type);
36  net::PEMTokenizer pem_tok(pem_data, headers);
37  if (!pem_tok.GetNext()) {
38    return false;
39  }
40
41  der_output->assign(pem_tok.data().begin(), pem_tok.data().end());
42  return true;
43}
44
45}  // namespace
46
47bool NetworkingPrivateCrypto::VerifyCredentials(
48    const std::string& certificate,
49    const std::string& signature,
50    const std::string& data,
51    const std::string& connected_mac) {
52  crypto::EnsureNSSInit();
53
54  std::vector<uint8_t> cert_data;
55  if (!GetDERFromPEM(certificate, "CERTIFICATE", &cert_data)) {
56    LOG(ERROR) << "Failed to parse certificate.";
57    return false;
58  }
59  SECItem der_cert;
60  der_cert.type = siDERCertBuffer;
61  der_cert.data = cert_data.data();
62  der_cert.len = cert_data.size();
63
64  // Parse into a certificate structure.
65  typedef scoped_ptr<
66      CERTCertificate,
67      crypto::NSSDestroyer<CERTCertificate, CERT_DestroyCertificate> >
68      ScopedCERTCertificate;
69  ScopedCERTCertificate cert(CERT_NewTempCertificate(
70      CERT_GetDefaultCertDB(), &der_cert, NULL, PR_FALSE, PR_TRUE));
71  if (!cert.get()) {
72    LOG(ERROR) << "Failed to parse certificate.";
73    return false;
74  }
75
76  // Check that the certificate is signed by trusted CA.
77  SECItem trusted_ca_key_der_item;
78  trusted_ca_key_der_item.type = siDERCertBuffer;
79  trusted_ca_key_der_item.data =
80      const_cast<unsigned char*>(kTrustedCAPublicKeyDER);
81  trusted_ca_key_der_item.len = kTrustedCAPublicKeyDERLength;
82  crypto::ScopedSECKEYPublicKey ca_public_key(
83      SECKEY_ImportDERPublicKey(&trusted_ca_key_der_item, CKK_RSA));
84  SECStatus verified = CERT_VerifySignedDataWithPublicKey(
85      &cert->signatureWrap, ca_public_key.get(), NULL);
86  if (verified != SECSuccess) {
87    LOG(ERROR) << "Certificate is not issued by the trusted CA.";
88    return false;
89  }
90
91  // Check that the device listed in the certificate is correct.
92  // Something like evt_e161 001a11ffacdf
93  char* common_name = CERT_GetCommonName(&cert->subject);
94  if (!common_name) {
95    LOG(ERROR) << "Certificate does not have common name.";
96    return false;
97  }
98
99  std::string subject_name(common_name);
100  PORT_Free(common_name);
101  std::string translated_mac;
102  base::RemoveChars(connected_mac, ":", &translated_mac);
103  if (!EndsWith(subject_name, translated_mac, false)) {
104    LOG(ERROR) << "MAC addresses don't match.";
105    return false;
106  }
107
108  // Make sure that the certificate matches the unsigned data presented.
109  // Verify that the |signature| matches |data|.
110  crypto::ScopedSECKEYPublicKey public_key(CERT_ExtractPublicKey(cert.get()));
111  if (!public_key.get()) {
112    LOG(ERROR) << "Unable to extract public key from certificate.";
113    return false;
114  }
115  SECItem signature_item;
116  signature_item.type = siBuffer;
117  signature_item.data =
118      reinterpret_cast<unsigned char*>(const_cast<char*>(signature.c_str()));
119  signature_item.len = static_cast<unsigned int>(signature.size());
120  verified = VFY_VerifyDataDirect(
121      reinterpret_cast<unsigned char*>(const_cast<char*>(data.c_str())),
122      data.size(),
123      public_key.get(),
124      &signature_item,
125      SEC_OID_PKCS1_RSA_ENCRYPTION,
126      SEC_OID_SHA1,
127      NULL,
128      NULL);
129  if (verified != SECSuccess) {
130    LOG(ERROR) << "Signed blobs did not match.";
131    return false;
132  }
133  return true;
134}
135
136bool NetworkingPrivateCrypto::EncryptByteString(
137    const std::vector<uint8_t>& pub_key_der,
138    const std::string& data,
139    std::vector<uint8_t>* encrypted_output) {
140  crypto::EnsureNSSInit();
141
142  SECItem pub_key_der_item;
143  pub_key_der_item.type = siDERCertBuffer;
144  pub_key_der_item.data = const_cast<unsigned char*>(pub_key_der.data());
145  pub_key_der_item.len = pub_key_der.size();
146
147  crypto::ScopedSECKEYPublicKey public_key(
148      SECKEY_ImportDERPublicKey(&pub_key_der_item, CKK_RSA));
149  if (!public_key.get()) {
150    LOG(ERROR) << "Failed to parse public key.";
151    return false;
152  }
153
154  size_t encrypted_length = SECKEY_PublicKeyStrength(public_key.get());
155  // RSAES is defined as operating on messages up to a length of k - 11, where
156  // k is the octet length of the RSA modulus.
157  if (encrypted_length < data.size() + 11) {
158    LOG(ERROR) << "Too much data to encrypt.";
159    return false;
160  }
161
162  scoped_ptr<unsigned char[]> rsa_output(new unsigned char[encrypted_length]);
163  SECStatus encrypted = PK11_PubEncryptPKCS1(
164      public_key.get(),
165      rsa_output.get(),
166      reinterpret_cast<unsigned char*>(const_cast<char*>(data.data())),
167      data.length(),
168      NULL);
169  if (encrypted != SECSuccess) {
170    LOG(ERROR) << "Error during encryption.";
171    return false;
172  }
173  encrypted_output->assign(rsa_output.get(),
174                           rsa_output.get() + encrypted_length);
175  return true;
176}
177
178bool NetworkingPrivateCrypto::DecryptByteString(
179    const std::string& private_key_pem,
180    const std::vector<uint8_t>& encrypted_data,
181    std::string* decrypted_output) {
182  crypto::EnsureNSSInit();
183
184  std::vector<uint8_t> private_key_data;
185  if (!GetDERFromPEM(private_key_pem, "PRIVATE KEY", &private_key_data)) {
186    LOG(ERROR) << "Failed to parse private key PEM.";
187    return false;
188  }
189  scoped_ptr<crypto::RSAPrivateKey> private_key(
190      crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(private_key_data));
191  if (!private_key || !private_key->public_key()) {
192    LOG(ERROR) << "Failed to parse private key DER.";
193    return false;
194  }
195
196  size_t encrypted_length = SECKEY_SignatureLen(private_key->public_key());
197  scoped_ptr<unsigned char[]> rsa_output(new unsigned char[encrypted_length]);
198  unsigned int output_length = 0;
199  SECStatus decrypted =
200      PK11_PrivDecryptPKCS1(private_key->key(),
201                            rsa_output.get(),
202                            &output_length,
203                            encrypted_length,
204                            const_cast<unsigned char*>(encrypted_data.data()),
205                            encrypted_data.size());
206  if (decrypted != SECSuccess) {
207    LOG(ERROR) << "Error during decryption.";
208    return false;
209  }
210  decrypted_output->assign(reinterpret_cast<char*>(rsa_output.get()),
211                           output_length);
212  return true;
213}
214