1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except
6  * in compliance with the License. You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "adb/tls/adb_ca_list.h"
18 
19 #include <iomanip>
20 #include <sstream>
21 #include <vector>
22 
23 #include <android-base/logging.h>
24 #include <android-base/strings.h>
25 #include <openssl/ssl.h>
26 
27 namespace adb {
28 namespace tls {
29 
30 namespace {
31 
32 // CA issuer identifier to distinguished embedded keys. Also has version
33 // information appended to the end of the string (e.g. "AdbKey-0").
34 static constexpr int kAdbKeyIdentifierNid = NID_organizationName;
35 static constexpr char kAdbKeyIdentifierV0[] = "AdbKey-0";
36 
37 // Where we store the actual data
38 static constexpr int kAdbKeyValueNid = NID_commonName;
39 
40 // TODO: Remove this once X509_NAME_add_entry_by_NID is fixed to use const unsigned char*
41 // https://boringssl-review.googlesource.com/c/boringssl/+/39764
X509_NAME_add_entry_by_NID_const(X509_NAME * name,int nid,int type,const unsigned char * bytes,int len,int loc,int set)42 int X509_NAME_add_entry_by_NID_const(X509_NAME* name, int nid, int type, const unsigned char* bytes,
43                                      int len, int loc, int set) {
44     return X509_NAME_add_entry_by_NID(name, nid, type, const_cast<unsigned char*>(bytes), len, loc,
45                                       set);
46 }
47 
IsHexDigit(char c)48 bool IsHexDigit(char c) {
49     return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f');
50 }
51 
52 // Wrapper around X509_NAME_get_text_by_NID that first calculates the size
53 // of the string. Returns empty string on failure.
GetX509NameTextByNid(X509_NAME * name,int nid)54 std::optional<std::string> GetX509NameTextByNid(X509_NAME* name, int nid) {
55     // |len| is the len of the text excluding the final null
56     int len = X509_NAME_get_text_by_NID(name, nid, nullptr, -1);
57     if (len <= 0) {
58         return std::nullopt;
59     }
60 
61     // Include the space for the final null byte
62     std::vector<char> buf(len + 1, '\0');
63     CHECK(X509_NAME_get_text_by_NID(name, nid, buf.data(), buf.size()));
64     return std::make_optional(std::string(buf.data()));
65 }
66 
67 }  // namespace
68 
69 // Takes an encoded public key and generates a X509_NAME that can be used in
70 // TlsConnection::SetClientCAList(), to allow the client to figure out which of
71 // its keys it should try to use in the TLS handshake.
CreateCAIssuerFromEncodedKey(std::string_view key)72 bssl::UniquePtr<X509_NAME> CreateCAIssuerFromEncodedKey(std::string_view key) {
73     // "O=AdbKey-0;CN=<key>;"
74     CHECK(!key.empty());
75 
76     std::string identifier = kAdbKeyIdentifierV0;
77     bssl::UniquePtr<X509_NAME> name(X509_NAME_new());
78     CHECK(X509_NAME_add_entry_by_NID_const(name.get(), kAdbKeyIdentifierNid, MBSTRING_ASC,
79                                            reinterpret_cast<const uint8_t*>(identifier.data()),
80                                            identifier.size(), -1, 0));
81 
82     CHECK(X509_NAME_add_entry_by_NID_const(name.get(), kAdbKeyValueNid, MBSTRING_ASC,
83                                            reinterpret_cast<const uint8_t*>(key.data()), key.size(),
84                                            -1, 0));
85     return name;
86 }
87 
88 // Parses a CA issuer and returns the encoded key, if any.
ParseEncodedKeyFromCAIssuer(X509_NAME * issuer)89 std::optional<std::string> ParseEncodedKeyFromCAIssuer(X509_NAME* issuer) {
90     CHECK(issuer);
91 
92     auto buf = GetX509NameTextByNid(issuer, kAdbKeyIdentifierNid);
93     if (!buf) {
94         return std::nullopt;
95     }
96 
97     // Check for supported versions
98     if (*buf == kAdbKeyIdentifierV0) {
99         return GetX509NameTextByNid(issuer, kAdbKeyValueNid);
100     }
101     return std::nullopt;
102 }
103 
SHA256BitsToHexString(std::string_view sha256)104 std::string SHA256BitsToHexString(std::string_view sha256) {
105     CHECK_EQ(sha256.size(), static_cast<size_t>(SHA256_DIGEST_LENGTH));
106     std::stringstream ss;
107     auto* u8 = reinterpret_cast<const uint8_t*>(sha256.data());
108     ss << std::uppercase << std::setfill('0') << std::hex;
109     // Convert to hex-string representation
110     for (size_t i = 0; i < SHA256_DIGEST_LENGTH; ++i) {
111         // Need to cast to something bigger than one byte, or
112         // stringstream will interpret it as a char value.
113         ss << std::setw(2) << static_cast<uint16_t>(u8[i]);
114     }
115     return ss.str();
116 }
117 
SHA256HexStringToBits(std::string_view sha256_str)118 std::optional<std::string> SHA256HexStringToBits(std::string_view sha256_str) {
119     if (sha256_str.size() != SHA256_DIGEST_LENGTH * 2) {
120         return std::nullopt;
121     }
122 
123     std::string result;
124     for (size_t i = 0; i < SHA256_DIGEST_LENGTH; ++i) {
125         auto bytestr = std::string(sha256_str.substr(i * 2, 2));
126         if (!IsHexDigit(bytestr[0]) || !IsHexDigit(bytestr[1])) {
127             LOG(ERROR) << "SHA256 string has invalid non-hex chars";
128             return std::nullopt;
129         }
130         result += static_cast<char>(std::stol(bytestr, nullptr, 16));
131     }
132     return result;
133 }
134 
135 }  // namespace tls
136 }  // namespace adb
137