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
47namespace networking_private_crypto {
48
49bool VerifyCredentials(const std::string& certificate,
50                       const std::string& signature,
51                       const std::string& data,
52                       const std::string& connected_mac) {
53  crypto::EnsureNSSInit();
54
55  std::vector<uint8_t> cert_data;
56  if (!GetDERFromPEM(certificate, "CERTIFICATE", &cert_data)) {
57    LOG(ERROR) << "Failed to parse certificate.";
58    return false;
59  }
60  SECItem der_cert;
61  der_cert.type = siDERCertBuffer;
62  der_cert.data = cert_data.data();
63  der_cert.len = cert_data.size();
64
65  // Parse into a certificate structure.
66  typedef scoped_ptr<
67      CERTCertificate,
68      crypto::NSSDestroyer<CERTCertificate, CERT_DestroyCertificate> >
69      ScopedCERTCertificate;
70  ScopedCERTCertificate cert(CERT_NewTempCertificate(
71      CERT_GetDefaultCertDB(), &der_cert, NULL, PR_FALSE, PR_TRUE));
72  if (!cert.get()) {
73    LOG(ERROR) << "Failed to parse certificate.";
74    return false;
75  }
76
77  // Check that the certificate is signed by trusted CA.
78  SECItem trusted_ca_key_der_item;
79  trusted_ca_key_der_item.type = siDERCertBuffer;
80  trusted_ca_key_der_item.data =
81      const_cast<unsigned char*>(kTrustedCAPublicKeyDER);
82  trusted_ca_key_der_item.len = kTrustedCAPublicKeyDERLength;
83  crypto::ScopedSECKEYPublicKey ca_public_key(
84      SECKEY_ImportDERPublicKey(&trusted_ca_key_der_item, CKK_RSA));
85  SECStatus verified = CERT_VerifySignedDataWithPublicKey(
86      &cert->signatureWrap, ca_public_key.get(), NULL);
87  if (verified != SECSuccess) {
88    LOG(ERROR) << "Certificate is not issued by the trusted CA.";
89    return false;
90  }
91
92  // Check that the device listed in the certificate is correct.
93  // Something like evt_e161 001a11ffacdf
94  char* common_name = CERT_GetCommonName(&cert->subject);
95  if (!common_name) {
96    LOG(ERROR) << "Certificate does not have common name.";
97    return false;
98  }
99
100  std::string subject_name(common_name);
101  PORT_Free(common_name);
102  std::string translated_mac;
103  base::RemoveChars(connected_mac, ":", &translated_mac);
104  if (!EndsWith(subject_name, translated_mac, false)) {
105    LOG(ERROR) << "MAC addresses don't match.";
106    return false;
107  }
108
109  // Make sure that the certificate matches the unsigned data presented.
110  // Verify that the |signature| matches |data|.
111  crypto::ScopedSECKEYPublicKey public_key(CERT_ExtractPublicKey(cert.get()));
112  if (!public_key.get()) {
113    LOG(ERROR) << "Unable to extract public key from certificate.";
114    return false;
115  }
116  SECItem signature_item;
117  signature_item.type = siBuffer;
118  signature_item.data =
119      reinterpret_cast<unsigned char*>(const_cast<char*>(signature.c_str()));
120  signature_item.len = static_cast<unsigned int>(signature.size());
121  verified = VFY_VerifyDataDirect(
122      reinterpret_cast<unsigned char*>(const_cast<char*>(data.c_str())),
123      data.size(),
124      public_key.get(),
125      &signature_item,
126      SEC_OID_PKCS1_RSA_ENCRYPTION,
127      SEC_OID_SHA1,
128      NULL,
129      NULL);
130  if (verified != SECSuccess) {
131    LOG(ERROR) << "Signed blobs did not match.";
132    return false;
133  }
134  return true;
135}
136
137bool EncryptByteString(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 DecryptByteString(const std::string& private_key_pem,
179                       const std::vector<uint8_t>& encrypted_data,
180                       std::string* decrypted_output) {
181  crypto::EnsureNSSInit();
182
183  std::vector<uint8_t> private_key_data;
184  if (!GetDERFromPEM(private_key_pem, "PRIVATE KEY", &private_key_data)) {
185    LOG(ERROR) << "Failed to parse private key PEM.";
186    return false;
187  }
188  scoped_ptr<crypto::RSAPrivateKey> private_key(
189      crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(private_key_data));
190  if (!private_key || !private_key->public_key()) {
191    LOG(ERROR) << "Failed to parse private key DER.";
192    return false;
193  }
194
195  size_t encrypted_length = SECKEY_SignatureLen(private_key->public_key());
196  scoped_ptr<unsigned char[]> rsa_output(new unsigned char[encrypted_length]);
197  unsigned int output_length = 0;
198  SECStatus decrypted =
199      PK11_PrivDecryptPKCS1(private_key->key(),
200                            rsa_output.get(),
201                            &output_length,
202                            encrypted_length,
203                            const_cast<unsigned char*>(encrypted_data.data()),
204                            encrypted_data.size());
205  if (decrypted != SECSuccess) {
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
214}  // namespace networking_private_crypto
215