1 /*
2  * Copyright 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 in compliance with the License.
6  * 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 #define LOG_TAG "AdbWifiTlsConnectionTest"
18 
19 #include <thread>
20 
21 #include <gtest/gtest.h>
22 
23 #include <adb/crypto/rsa_2048_key.h>
24 #include <adb/crypto/x509_generator.h>
25 #include <adb/tls/adb_ca_list.h>
26 #include <adb/tls/tls_connection.h>
27 #include <android-base/logging.h>
28 #include <android-base/strings.h>
29 #include <android-base/unique_fd.h>
30 #include <openssl/ssl.h>
31 
32 using namespace adb::crypto;
33 
34 namespace adb {
35 namespace tls {
36 
37 using android::base::unique_fd;
38 using TlsError = TlsConnection::TlsError;
39 
40 // Test X.509 certificates (RSA 2048)
41 static const std::string kTestRsa2048ServerCert =
42         "-----BEGIN CERTIFICATE-----\n"
43         "MIIDFzCCAf+gAwIBAgIBATANBgkqhkiG9w0BAQsFADAtMQswCQYDVQQGEwJVUzEQ\n"
44         "MA4GA1UECgwHQW5kcm9pZDEMMAoGA1UEAwwDQWRiMB4XDTIwMDEyMTIyMjU1NVoX\n"
45         "DTMwMDExODIyMjU1NVowLTELMAkGA1UEBhMCVVMxEDAOBgNVBAoMB0FuZHJvaWQx\n"
46         "DDAKBgNVBAMMA0FkYjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK8E\n"
47         "2Ck9TfuKlz7wqWdMfknjZ1luFDp2IHxAUZzh/F6jeI2dOFGAjpeloSnGOE86FIaT\n"
48         "d1EvpyTh7nBwbrLZAA6XFZTo7Bl6BdNOQdqb2d2+cLEN0inFxqUIycevRtohUE1Y\n"
49         "FHM9fg442X1jOTWXjDZWeiqFWo95paAPhzm6pWqfJK1+YKfT1LsWZpYqJGGQE5pi\n"
50         "C3qOBYYgFpoXMxTYJNoZo3uOYEdM6upc8/vh15nMgIxX/ymJxEY5BHPpZPPWjXLg\n"
51         "BfzVaV9fUfv0JT4HQ4t2WvxC3cD/UsjWp2a6p454uUp2ENrANa+jRdRJepepg9D2\n"
52         "DKsx9L8zjc5Obqexrt0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B\n"
53         "Af8EBAMCAYYwHQYDVR0OBBYEFDFW+8GTErwoZN5Uu9KyY4QdGYKpMA0GCSqGSIb3\n"
54         "DQEBCwUAA4IBAQBCDEn6SHXGlq5TU7J8cg1kRPd9bsJW+0hDuKSq0REXDkl0PcBf\n"
55         "fy282Agg9enKPPKmnpeQjM1dmnxdM8tT8LIUbMl779i3fn6v9HJVB+yG4gmRFThW\n"
56         "c+AGlBnrIT820cX/gU3h3R3FTahfsq+1rrSJkEgHyuC0HYeRyveSckBdaEOLvx0S\n"
57         "toun+32JJl5hWydpUUZhE9Mbb3KHBRM2YYZZU9JeJ08Apjl+3lRUeMAUwI5fkAAu\n"
58         "z/1SqnuGL96bd8P5ixdkA1+rF8FPhodGcq9mQOuUGP9g5HOXjaNoJYvwVRUdLeGh\n"
59         "cP/ReOTwQIzM1K5a83p8cX8AGGYmM7dQp7ec\n"
60         "-----END CERTIFICATE-----\n";
61 
62 static const std::string kTestRsa2048ServerPrivKey =
63         "-----BEGIN PRIVATE KEY-----\n"
64         "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCvBNgpPU37ipc+\n"
65         "8KlnTH5J42dZbhQ6diB8QFGc4fxeo3iNnThRgI6XpaEpxjhPOhSGk3dRL6ck4e5w\n"
66         "cG6y2QAOlxWU6OwZegXTTkHam9ndvnCxDdIpxcalCMnHr0baIVBNWBRzPX4OONl9\n"
67         "Yzk1l4w2VnoqhVqPeaWgD4c5uqVqnyStfmCn09S7FmaWKiRhkBOaYgt6jgWGIBaa\n"
68         "FzMU2CTaGaN7jmBHTOrqXPP74deZzICMV/8picRGOQRz6WTz1o1y4AX81WlfX1H7\n"
69         "9CU+B0OLdlr8Qt3A/1LI1qdmuqeOeLlKdhDawDWvo0XUSXqXqYPQ9gyrMfS/M43O\n"
70         "Tm6nsa7dAgMBAAECggEAFCS2bPdUKIgjbzLgtHW+hT+J2hD20rcHdyAp+dNH/2vI\n"
71         "yLfDJHJA4chGMRondKA704oDw2bSJxxlG9t83326lB35yxPhye7cM8fqgWrK8PVl\n"
72         "tU22FhO1ZgeJvb9OeXWNxKZyDW9oOOJ8eazNXVMuEo+dFj7B6l3MXQyHJPL2mJDm\n"
73         "u9ofFLdypX+gJncVO0oW0FNJnEUn2MMwHDNlo7gc4WdQuidPkuZItKRGcB8TTGF3\n"
74         "Ka1/2taYdTQ4Aq//Z84LlFvE0zD3T4c8LwYYzOzD4gGGTXvft7vSHzIun1S8YLRS\n"
75         "dEKXdVjtaFhgH3uUe4j+1b/vMvSHeoGBNX/G88GD+wKBgQDWUYVlMVqc9HD2IeYi\n"
76         "EfBcNwAJFJkh51yAl5QbUBgFYgFJVkkS/EDxEGFPvEmI3/pAeQFHFY13BI466EPs\n"
77         "o8Z8UUwWDp+Z1MFHHKQKnFakbsZbZlbqjJ9VJsqpezbpWhMHTOmcG0dmE7rf0lyM\n"
78         "eQv9slBB8qp2NEUs5Of7f2C2bwKBgQDRDq4nUuMQF1hbjM05tGKSIwkobmGsLspv\n"
79         "TMhkM7fq4RpbFHmbNgsFqMhcqYZ8gY6/scv5KCuAZ4yHUkbqwf5h+QCwrJ4uJeUJ\n"
80         "ZgJfHus2mmcNSo8FwSkNoojIQtzcbJav7bs2K9VTuertk/i7IJLApU4FOZZ5pghN\n"
81         "EXu0CZF1cwKBgDWFGhjRIF29tU/h20R60llU6s9Zs3wB+NmsALJpZ/ZAKS4VPB5f\n"
82         "nCAXBRYSYRKrTCU5kpYbzb4BBzuysPOxWmnFK4j+keCqfrGxd02nCQP7HdHJVr8v\n"
83         "6sIq88UrHeVcNxBFprjzHvtgxfQK5k22FMZ/9wbhAKyQFQ5HA5+MiaxFAoGAIcZZ\n"
84         "ZIkDninnYIMS9OursShv5lRO+15j3i9tgKLKZ+wOMgDQ1L6acUOfezj4PU1BHr8+\n"
85         "0PYocQpJreMhCfRlgLaV4fVBaPs+UZJld7CrF5tCYudUy/01ALrtlk0XGZWBktK5\n"
86         "mDrksC4tQkzRtonAq9cJD9cJ9IVaefkFH0UcdvkCgYBpZj50VLeGhnHHBnkJRlV1\n"
87         "fV+/P6PAq6RtqjA6O9Qdaoj5V3w2d63aQcQXQLJjH2BBmtCIy47r04rFvZpbCxP7\n"
88         "NH/OnK9NHpk2ucRTe8TAnVbvF/TZzPJoIxAO/D3OWaW6df4R8en8u6GYzWFglAyT\n"
89         "sydGT8yfWD1FYUWgfrVRbg==\n"
90         "-----END PRIVATE KEY-----\n";
91 
92 static const std::string kTestRsa2048ClientCert =
93         "-----BEGIN CERTIFICATE-----\n"
94         "MIIDFzCCAf+gAwIBAgIBATANBgkqhkiG9w0BAQsFADAtMQswCQYDVQQGEwJVUzEQ\n"
95         "MA4GA1UECgwHQW5kcm9pZDEMMAoGA1UEAwwDQWRiMB4XDTIwMDEyMTIyMjU1NloX\n"
96         "DTMwMDExODIyMjU1NlowLTELMAkGA1UEBhMCVVMxEDAOBgNVBAoMB0FuZHJvaWQx\n"
97         "DDAKBgNVBAMMA0FkYjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAI3a\n"
98         "EXh1S5FTbet7JVONswffRPaekdIK53cb8SnAbSO9X5OLA4zGwdkrBvDTsd96SKrp\n"
99         "JxmoNOE1DhbZh05KPlWAPkGKacjGWaz+S7biDOL0I6aaLbTlU/il1Ub9olPSBVUx\n"
100         "0nhdtEFgIOzddnP6/1KmyIIeRxS5lTKeg4avqUkZNXkz/wL1dHBFL7FNFf0SCcbo\n"
101         "tsub/deFbjZ27LTDN+SIBgFttTNqC5NTvoBAoMdyCOAgNYwaHO+fKiK3edfJieaw\n"
102         "7HD8qqmQxcpCtRlA8CUPj7GfR+WHiCJmlevhnkFXCo56R1BS0F4wuD4KPdSWt8gc\n"
103         "27ejH/9/z2cKo/6SLJMCAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B\n"
104         "Af8EBAMCAYYwHQYDVR0OBBYEFO/Mr5ygqqpyU/EHM9v7RDvcqaOkMA0GCSqGSIb3\n"
105         "DQEBCwUAA4IBAQAH33KMouzF2DYbjg90KDrDQr4rq3WfNb6P743knxdUFuvb+40U\n"
106         "QjC2OJZHkSexH7wfG/y6ic7vfCfF4clNs3QvU1lEjOZC57St8Fk7mdNdsWLwxEMD\n"
107         "uePFz0dvclSxNUHyCVMqNxddzQYzxiDWQRmXWrUBliMduQqEQelcxW2yDtg8bj+s\n"
108         "aMpR1ra9scaD4jzIZIIxLoOS9zBMuNRbgP217sZrniyGMhzoI1pZ/izN4oXpyH7O\n"
109         "THuaCzzRT3ph2f8EgmHSodz3ttgSf2DHzi/Ez1xUkk7NOlgNtmsxEdrM47+cC5ae\n"
110         "fIf2V+1o1JW8J7D11RmRbNPh3vfisueB4f88\n"
111         "-----END CERTIFICATE-----\n";
112 
113 static const std::string kTestRsa2048ClientPrivKey =
114         "-----BEGIN PRIVATE KEY-----\n"
115         "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCN2hF4dUuRU23r\n"
116         "eyVTjbMH30T2npHSCud3G/EpwG0jvV+TiwOMxsHZKwbw07Hfekiq6ScZqDThNQ4W\n"
117         "2YdOSj5VgD5BimnIxlms/ku24gzi9COmmi205VP4pdVG/aJT0gVVMdJ4XbRBYCDs\n"
118         "3XZz+v9SpsiCHkcUuZUynoOGr6lJGTV5M/8C9XRwRS+xTRX9EgnG6LbLm/3XhW42\n"
119         "duy0wzfkiAYBbbUzaguTU76AQKDHcgjgIDWMGhzvnyoit3nXyYnmsOxw/KqpkMXK\n"
120         "QrUZQPAlD4+xn0flh4giZpXr4Z5BVwqOekdQUtBeMLg+Cj3UlrfIHNu3ox//f89n\n"
121         "CqP+kiyTAgMBAAECggEAAa64eP6ggCob1P3c73oayYPIbvRqiQdAFOrr7Vwu7zbr\n"
122         "z0rde+n6RU0mrpc+4NuzyPMtrOGQiatLbidJB5Cx3z8U00ovqbCl7PtcgorOhFKe\n"
123         "VEzihebCcYyQqbWQcKtpDMhOgBxRwFoXieJb6VGXfa96FAZalCWvXgOrTl7/BF2X\n"
124         "qMqIm9nJi+yS5tIO8VdOsOmrMWRH/b/ENUcef4WpLoxTXr0EEgyKWraeZ/hhXo1e\n"
125         "z29dZKqdr9wMsq11NPsRddwS94jnDkXTo+EQyWVTfB7gb6yyp07s8jysaDb21tVv\n"
126         "UXB9MRhDV1mOv0ncXfXZ4/+4A2UahmZaLDAVLaat4QKBgQDAVRredhGRGl2Nkic3\n"
127         "KvZCAfyxug788CgasBdEiouz19iCCwcgMIDwnq0s3/WM7h/laCamT2x38riYDnpq\n"
128         "rkYMfuVtU9CjEL9pTrdfwbIRhTwYNqADaPz2mXwQUhRXutE5TIdgxxC/a+ZTh0qN\n"
129         "S+vhTj/4hf0IZhMh5Nqj7IPExQKBgQC8zxEzhmSGjys0GuE6Wl6Doo2TpiR6vwvi\n"
130         "xPLU9lmIz5eca/Rd/eERioFQqeoIWDLzx52DXuz6rUoQhbJWz9hP3yqCwXD+pbNP\n"
131         "oDJqDDbCC4IMYEb0IK/PEPH+gIpnTjoFcW+ecKDFG7W5Lt05J8WsJsfOaJvMrOU+\n"
132         "dLXq3IgxdwKBgQC5RAFq0v6e8G+3hFaEHL0z3igkpt3zJf7rnj37hx2FMmDa+3Z0\n"
133         "umQp5B9af61PgL12xLmeMBmC/Wp1BlVDV/Yf6Uhk5Hyv5t0KuomHEtTNbbLyfAPs\n"
134         "5P/vJu/L5NS1oT4S3LX3MineyjgGs+bLbpub3z1dzutrYLADUSiPCK/xJQKBgBQt\n"
135         "nQ0Ao+Wtj1R2OvPdjJRM3wyUiPmFSWPm4HzaBx+T8AQLlYYmB9O0FbXlMtnJc0iS\n"
136         "YMcVcgYoVu4FG9YjSF7g3s4yljzgwJUV7c1fmMqMKE3iTDLy+1cJ3JLycdgwiArk\n"
137         "4KTyLHxkRbuQwpvFIF8RlfD9RQlOwQE3v+llwDhpAoGBAL6XG6Rp6mBoD2Ds5c9R\n"
138         "943yYgSUes3ji1SI9zFqeJtj8Ml/enuK1xu+8E/BxB0//+vgZsH6i3i8GFwygKey\n"
139         "CGJF8CbiHc3EJc3NQIIRXcni/CGacf0HwC6m+PGFDBIpA4H2iDpVvCSofxttQiq0\n"
140         "/Z7HXmXUvZHVyYi/QzX2Gahj\n"
141         "-----END PRIVATE KEY-----\n";
142 
143 static const std::string kTestRsa2048UnknownPrivKey =
144         "-----BEGIN PRIVATE KEY-----\n"
145         "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCrIhr+CS+6UI0w\n"
146         "CTaVzQAicKBe6X531LeQAGYx7j5RLHR1QIoJ0WCc5msmXKe2VzcWuLbVdTGAIP1H\n"
147         "mwbPqlbO4ioxeJhiDv+WPuLG8+j4Iw1Yqxt8cfohxjfvNmIQM8aF5hGyyaaTetDF\n"
148         "EYWONoYCBC4WnFWgYCPb8mzWXlhHE3F66GnHpc32zydPTg3ZurGvSsFf7fNY9yRw\n"
149         "8WtwPiI6mpRxt+n2bQUp+LZ+g/3rXLFPg8uWDGYG7IvLluWc9gR9lxjL64t6ryLU\n"
150         "2cm7eTfDgLw/B1F/wEgCJDnby1JgQ4rq6klJO3BR2ooUr/7T343y5njG5hQJreV7\n"
151         "5ZnSmRLZAgMBAAECggEABPrfeHZFuWkj7KqN+DbAmt/2aMCodZ3+7/20+528WkIe\n"
152         "CvXzdmTth+9UHagLWNzpnVuHdYd9JuZ+3F00aelh8JAIDIu++naHhUSj9ohtRoBF\n"
153         "oIeNK5ZJAj/Zi5hkauaIz8dxyyc/VdIYfm2bundXd7pNqYqH2tyFWp6PwH67GKlZ\n"
154         "1lC7o8gKAK8sz9g0Ctdoe+hDqAsvYFCW4EWDM2qboucSgn8g3E/Gux/KrpXVv7d0\n"
155         "PMQ60m+dyTOCMGqXIoDR3TAvQR7ex5sQ/QZSREdxKy878s/2FY4ktxtCUWlhrmcI\n"
156         "VKtrDOGEKwNoiMluf2635rsVq2e01XhQlmdxbRFU0QKBgQDjOhhD1m9duFTQ2b+J\n"
157         "Xfn6m8Rs7sZqO4Az7gLOWmD/vYWlK4n2nZsh6u5/cB1N+PA+ncvvV4yKJAlLHxbT\n"
158         "pVvfzJ/jbUsj/NJg/w7+KYC9gXgRmBonuG2gRZF/5Otdlza4vMcoSkqGjlGxJyzL\n"
159         "+9umEziN3tEYMRwipYvt7BgbUQKBgQDAzaXryJ3YD3jpecy/+fSnQvFjpyeDRqU1\n"
160         "KDA9nxN5tJN6bnKhUlMhy64SsgvVX9jUuN7cK+qYV0uzdBn6kIAJNLWTdbtH93+e\n"
161         "vNVgluR3jmixW4QfY9vfZKdXZbVGNc0DFMi1vJqgxTgQ5Mq5PxxxRL4FsAF840V1\n"
162         "Wu9uhU0NCQKBgBfjga2QG8E0oeYbHmHouWE5gxsYt09v1fifqzfalJwOZsCIpUaC\n"
163         "J08Xjd9kABC0fT14BXqyL5pOU5PMPvAdUF1k++JDGUU9TTjZV9AsuNYziFYBMa6/\n"
164         "WvcgmT1i6cO7JAuj/SQlO1SOHdSME8+WOO9q0eVIaZ8repPB58YprhchAoGBAJyR\n"
165         "Y8AJdkTSq7nNszvi245IioYGY8vzPo3gSOyBlesrfOfbcTMYC3JSWNXNyFZKM2br\n"
166         "ie75qtRzb4IXMlGLrq3LI/jPjnpuvjBF4HFDl9yOxO3iB3UGPrM2pb4PVhnh7s4l\n"
167         "vqf2tQsBnPn7EbVFTu+ch0NPHqYwWWNnqS/zCBMhAoGBAIkYjOE0iD9W2FXee6VL\n"
168         "iN8wDqlqsGEEtLvykIDmTmM+ZX5ftQuPo18khpE9wQKmJ5OpoVTYIP1UsJFBakgo\n"
169         "+dGaf6xVuPvmydNFqixlW3z227n4Px6GX7CXlCaAleTeItezli+dWf/9astwTA3x\n"
170         "IazYzsxUUpZFC4dJ1GhBn3y1\n"
171         "-----END PRIVATE KEY-----\n";
172 
173 static const std::string kTestRsa2048UnknownCert =
174         "-----BEGIN CERTIFICATE-----\n"
175         "MIIDFzCCAf+gAwIBAgIBATANBgkqhkiG9w0BAQsFADAtMQswCQYDVQQGEwJVUzEQ\n"
176         "MA4GA1UECgwHQW5kcm9pZDEMMAoGA1UEAwwDQWRiMB4XDTIwMDEyNDE4MzMwNVoX\n"
177         "DTMwMDEyMTE4MzMwNVowLTELMAkGA1UEBhMCVVMxEDAOBgNVBAoMB0FuZHJvaWQx\n"
178         "DDAKBgNVBAMMA0FkYjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKsi\n"
179         "Gv4JL7pQjTAJNpXNACJwoF7pfnfUt5AAZjHuPlEsdHVAignRYJzmayZcp7ZXNxa4\n"
180         "ttV1MYAg/UebBs+qVs7iKjF4mGIO/5Y+4sbz6PgjDVirG3xx+iHGN+82YhAzxoXm\n"
181         "EbLJppN60MURhY42hgIELhacVaBgI9vybNZeWEcTcXroacelzfbPJ09ODdm6sa9K\n"
182         "wV/t81j3JHDxa3A+IjqalHG36fZtBSn4tn6D/etcsU+Dy5YMZgbsi8uW5Zz2BH2X\n"
183         "GMvri3qvItTZybt5N8OAvD8HUX/ASAIkOdvLUmBDiurqSUk7cFHaihSv/tPfjfLm\n"
184         "eMbmFAmt5XvlmdKZEtkCAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B\n"
185         "Af8EBAMCAYYwHQYDVR0OBBYEFDtRSOm1ilhnq6bKN4qJ1ekK/PAkMA0GCSqGSIb3\n"
186         "DQEBCwUAA4IBAQAP6Q8/OxnBA3BO8oxKer0tjI4rZMefUhbAKUWXYjTTNEBm5//b\n"
187         "lVGP2RptO7bxj8w1L3rxsjmVcv2TqBOhrbJqvGVPE2ntoYlFhBBkRvmxuu1y5W9V\n"
188         "uJU7SF9lNmDXShTURULu3P8GdeT1HGeXzWQ4x7VhY9a3VIbmN5VxjB+3C6hYZxSs\n"
189         "DCpmidu/sR+n5Azlh6oqrhOxmv17PuF/ioTUsHd4y2Z41IvvO47oghxNDtboUUsg\n"
190         "LfsM1MOxVC9PqOfQphFU4i8owNIYzBMadDLw+1TSQj0ALqZVyc9Dq+WDFdz+JAE+\n"
191         "k7TkVU06UPGVSnLVzJeYwGCXQp3apBszY9vO\n"
192         "-----END CERTIFICATE-----\n";
193 
194 struct CAIssuerField {
195     int nid;
196     std::vector<uint8_t> val;
197 };
198 using CAIssuer = std::vector<CAIssuerField>;
199 static std::vector<CAIssuer> kCAIssuers = {
200         {
201                 {NID_commonName, {'a', 'b', 'c', 'd', 'e'}},
202                 {NID_organizationName, {'d', 'e', 'f', 'g'}},
203         },
204         {
205                 {NID_commonName, {'h', 'i', 'j', 'k', 'l', 'm'}},
206                 {NID_countryName, {'n', 'o'}},
207         },
208 };
209 
210 class AdbWifiTlsConnectionTest : public testing::Test {
211   protected:
SetUp()212     virtual void SetUp() override {
213         android::base::Socketpair(SOCK_STREAM, &server_fd_, &client_fd_);
214         server_ = TlsConnection::Create(TlsConnection::Role::Server, kTestRsa2048ServerCert,
215                                         kTestRsa2048ServerPrivKey, server_fd_);
216         client_ = TlsConnection::Create(TlsConnection::Role::Client, kTestRsa2048ClientCert,
217                                         kTestRsa2048ClientPrivKey, client_fd_);
218         ASSERT_NE(nullptr, server_);
219         ASSERT_NE(nullptr, client_);
220     }
221 
TearDown()222     virtual void TearDown() override {
223         WaitForClientConnection();
224         // Shutdown the SSL connection first.
225         server_.reset();
226         client_.reset();
227     }
228 
GetCAIssuerList()229     bssl::UniquePtr<STACK_OF(X509_NAME)> GetCAIssuerList() {
230         bssl::UniquePtr<STACK_OF(X509_NAME)> ret(sk_X509_NAME_new_null());
231         for (auto& issuer : kCAIssuers) {
232             bssl::UniquePtr<X509_NAME> name(X509_NAME_new());
233             for (auto& attr : issuer) {
234                 CHECK(X509_NAME_add_entry_by_NID(name.get(), attr.nid, MBSTRING_ASC,
235                                                  attr.val.data(), attr.val.size(), -1, 0));
236             }
237 
238             CHECK(bssl::PushToStack(ret.get(), std::move(name)));
239         }
240 
241         return ret;
242     }
243 
StartClientHandshakeAsync(TlsError expected)244     void StartClientHandshakeAsync(TlsError expected) {
245         client_thread_ = std::thread([=]() { EXPECT_EQ(client_->DoHandshake(), expected); });
246     }
247 
WaitForClientConnection()248     void WaitForClientConnection() {
249         if (client_thread_.joinable()) {
250             client_thread_.join();
251         }
252     }
253 
254     unique_fd server_fd_;
255     unique_fd client_fd_;
256     const std::vector<uint8_t> msg_{0xff, 0xab, 0x32, 0xf6, 0x12, 0x56};
257     std::unique_ptr<TlsConnection> server_;
258     std::unique_ptr<TlsConnection> client_;
259     std::thread client_thread_;
260 };
261 
TEST_F(AdbWifiTlsConnectionTest,InvalidCreationParams)262 TEST_F(AdbWifiTlsConnectionTest, InvalidCreationParams) {
263     // Verify that passing empty certificate/private key results in a crash.
264     ASSERT_DEATH(
265             {
266                 server_ = TlsConnection::Create(TlsConnection::Role::Server, "",
267                                                 kTestRsa2048ServerPrivKey, server_fd_);
268             },
269             "");
270     ASSERT_DEATH(
271             {
272                 server_ = TlsConnection::Create(TlsConnection::Role::Server, kTestRsa2048ServerCert,
273                                                 "", server_fd_);
274             },
275             "");
276     ASSERT_DEATH(
277             {
278                 client_ = TlsConnection::Create(TlsConnection::Role::Client, "",
279                                                 kTestRsa2048ClientPrivKey, client_fd_);
280             },
281             "");
282     ASSERT_DEATH(
283             {
284                 client_ = TlsConnection::Create(TlsConnection::Role::Client, kTestRsa2048ClientCert,
285                                                 "", client_fd_);
286             },
287             "");
288 }
289 
TEST_F(AdbWifiTlsConnectionTest,NoCertificateVerification)290 TEST_F(AdbWifiTlsConnectionTest, NoCertificateVerification) {
291     // Allow any certificate
292     server_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
293     client_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
294     StartClientHandshakeAsync(TlsError::Success);
295 
296     // Handshake should succeed
297     ASSERT_EQ(server_->DoHandshake(), TlsError::Success);
298     WaitForClientConnection();
299 
300     // Test client/server read and writes
301     client_thread_ = std::thread([&]() {
302         EXPECT_TRUE(client_->WriteFully(
303                 std::string_view(reinterpret_cast<const char*>(msg_.data()), msg_.size())));
304         // Try with overloaded ReadFully
305         std::vector<uint8_t> buf(msg_.size());
306         ASSERT_TRUE(client_->ReadFully(buf.data(), msg_.size()));
307         EXPECT_EQ(buf, msg_);
308     });
309 
310     auto data = server_->ReadFully(msg_.size());
311     EXPECT_EQ(data, msg_);
312     EXPECT_TRUE(server_->WriteFully(
313             std::string_view(reinterpret_cast<const char*>(msg_.data()), msg_.size())));
314 
315     WaitForClientConnection();
316 }
317 
TEST_F(AdbWifiTlsConnectionTest,NoTrustedCertificates)318 TEST_F(AdbWifiTlsConnectionTest, NoTrustedCertificates) {
319     StartClientHandshakeAsync(TlsError::CertificateRejected);
320 
321     // Handshake should not succeed
322     ASSERT_EQ(server_->DoHandshake(), TlsError::PeerRejectedCertificate);
323     WaitForClientConnection();
324 
325     // All writes and reads should fail
326     client_thread_ = std::thread([&]() {
327         // Client write, server read should fail
328         EXPECT_FALSE(client_->WriteFully(
329                 std::string_view(reinterpret_cast<const char*>(msg_.data()), msg_.size())));
330         auto data = client_->ReadFully(msg_.size());
331         EXPECT_EQ(data.size(), 0);
332     });
333 
334     auto data = server_->ReadFully(msg_.size());
335     EXPECT_EQ(data.size(), 0);
336     EXPECT_FALSE(server_->WriteFully(
337             std::string_view(reinterpret_cast<const char*>(msg_.data()), msg_.size())));
338 
339     WaitForClientConnection();
340 }
341 
TEST_F(AdbWifiTlsConnectionTest,AddTrustedCertificates)342 TEST_F(AdbWifiTlsConnectionTest, AddTrustedCertificates) {
343     // Add peer certificates
344     EXPECT_TRUE(client_->AddTrustedCertificate(kTestRsa2048ServerCert));
345     EXPECT_TRUE(server_->AddTrustedCertificate(kTestRsa2048ClientCert));
346 
347     StartClientHandshakeAsync(TlsError::Success);
348 
349     // Handshake should succeed
350     ASSERT_EQ(server_->DoHandshake(), TlsError::Success);
351     WaitForClientConnection();
352 
353     // All read writes should succeed
354     client_thread_ = std::thread([&]() {
355         EXPECT_TRUE(client_->WriteFully(
356                 std::string_view(reinterpret_cast<const char*>(msg_.data()), msg_.size())));
357         auto data = client_->ReadFully(msg_.size());
358         EXPECT_EQ(data, msg_);
359     });
360 
361     auto data = server_->ReadFully(msg_.size());
362     EXPECT_EQ(data, msg_);
363     EXPECT_TRUE(server_->WriteFully(
364             std::string_view(reinterpret_cast<const char*>(msg_.data()), msg_.size())));
365 
366     WaitForClientConnection();
367 }
368 
TEST_F(AdbWifiTlsConnectionTest,AddTrustedCertificates_ClientWrongCert)369 TEST_F(AdbWifiTlsConnectionTest, AddTrustedCertificates_ClientWrongCert) {
370     // Server trusts a certificate, client has the wrong certificate
371     EXPECT_TRUE(server_->AddTrustedCertificate(kTestRsa2048UnknownCert));
372     // Client accepts any certificate
373     client_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
374 
375     // Without enabling EnableClientPostHandshakeCheck(), DoHandshake() will
376     // succeed, because in TLS 1.3, the client doesn't get notified if the
377     // server rejected the certificate until a read operation is called.
378     StartClientHandshakeAsync(TlsError::Success);
379 
380     // Handshake should fail for server, succeed for client
381     ASSERT_EQ(server_->DoHandshake(), TlsError::CertificateRejected);
382     WaitForClientConnection();
383 
384     // Client writes will succeed, everything else will fail.
385     client_thread_ = std::thread([&]() {
386         EXPECT_TRUE(client_->WriteFully(
387                 std::string_view(reinterpret_cast<const char*>(msg_.data()), msg_.size())));
388         auto data = client_->ReadFully(msg_.size());
389         EXPECT_EQ(data.size(), 0);
390     });
391 
392     auto data = server_->ReadFully(msg_.size());
393     EXPECT_EQ(data.size(), 0);
394     EXPECT_FALSE(server_->WriteFully(
395             std::string_view(reinterpret_cast<const char*>(msg_.data()), msg_.size())));
396 
397     WaitForClientConnection();
398 }
399 
TEST_F(AdbWifiTlsConnectionTest,ExportKeyingMaterial)400 TEST_F(AdbWifiTlsConnectionTest, ExportKeyingMaterial) {
401     // Allow any certificate
402     server_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
403     client_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
404 
405     // Add peer certificates
406     EXPECT_TRUE(client_->AddTrustedCertificate(kTestRsa2048ServerCert));
407     EXPECT_TRUE(server_->AddTrustedCertificate(kTestRsa2048ClientCert));
408 
409     StartClientHandshakeAsync(TlsError::Success);
410 
411     // Handshake should succeed
412     ASSERT_EQ(server_->DoHandshake(), TlsError::Success);
413     WaitForClientConnection();
414 
415     // Verify the client and server's exported key material match.
416     const size_t key_size = 64;
417     auto client_key_material = client_->ExportKeyingMaterial(key_size);
418     ASSERT_FALSE(client_key_material.empty());
419     auto server_key_material = server_->ExportKeyingMaterial(key_size);
420     ASSERT_TRUE(!server_key_material.empty());
421     ASSERT_EQ(client_key_material.size(), key_size);
422     ASSERT_EQ(client_key_material, server_key_material);
423 }
424 
TEST_F(AdbWifiTlsConnectionTest,SetCertVerifyCallback_ClientAcceptsServerRejects)425 TEST_F(AdbWifiTlsConnectionTest, SetCertVerifyCallback_ClientAcceptsServerRejects) {
426     // Client accepts all
427     client_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
428     // Server rejects all
429     server_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 0; });
430     // Client handshake should succeed, because in TLS 1.3, client does not
431     // realize that the peer rejected the certificate until after a read
432     // operation.
433     StartClientHandshakeAsync(TlsError::Success);
434 
435     // Server handshake should fail
436     ASSERT_EQ(server_->DoHandshake(), TlsError::CertificateRejected);
437     WaitForClientConnection();
438 }
439 
TEST_F(AdbWifiTlsConnectionTest,SetCertVerifyCallback_ClientAcceptsServerRejects_PostHSCheck)440 TEST_F(AdbWifiTlsConnectionTest, SetCertVerifyCallback_ClientAcceptsServerRejects_PostHSCheck) {
441     // Client accepts all
442     client_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
443     // Client should now get a failure in the handshake
444     client_->EnableClientPostHandshakeCheck(true);
445     // Server rejects all
446     server_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 0; });
447 
448     // Client handshake should fail because server rejects everything
449     StartClientHandshakeAsync(TlsError::PeerRejectedCertificate);
450 
451     // Server handshake should fail
452     ASSERT_EQ(server_->DoHandshake(), TlsError::CertificateRejected);
453     WaitForClientConnection();
454 }
455 
TEST_F(AdbWifiTlsConnectionTest,SetCertVerifyCallback_ClientRejectsServerAccepts)456 TEST_F(AdbWifiTlsConnectionTest, SetCertVerifyCallback_ClientRejectsServerAccepts) {
457     // Client rejects all
458     client_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 0; });
459     // Server accepts all
460     server_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
461     // Client handshake should fail
462     StartClientHandshakeAsync(TlsError::CertificateRejected);
463 
464     // Server handshake should fail
465     ASSERT_EQ(server_->DoHandshake(), TlsError::PeerRejectedCertificate);
466     WaitForClientConnection();
467 }
468 
TEST_F(AdbWifiTlsConnectionTest,SetCertVerifyCallback_ClientRejectsServerAccepts_PostHSCheck)469 TEST_F(AdbWifiTlsConnectionTest, SetCertVerifyCallback_ClientRejectsServerAccepts_PostHSCheck) {
470     // Client rejects all
471     client_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 0; });
472     // This shouldn't affect the error types returned in the
473     // #SetCertVerifyCallback_ClientRejectsServerAccepts test, since
474     // the failure is still within the TLS 1.3 handshake.
475     client_->EnableClientPostHandshakeCheck(true);
476     // Server accepts all
477     server_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
478 
479     // Client handshake should fail
480     StartClientHandshakeAsync(TlsError::CertificateRejected);
481 
482     // Server handshake should fail
483     ASSERT_EQ(server_->DoHandshake(), TlsError::PeerRejectedCertificate);
484     WaitForClientConnection();
485 }
486 
TEST_F(AdbWifiTlsConnectionTest,EnableClientPostHandshakeCheck_ClientWrongCert)487 TEST_F(AdbWifiTlsConnectionTest, EnableClientPostHandshakeCheck_ClientWrongCert) {
488     client_->AddTrustedCertificate(kTestRsa2048ServerCert);
489     // client's DoHandshake() will fail if the server rejected the certificate
490     client_->EnableClientPostHandshakeCheck(true);
491 
492     // Add peer certificates
493     EXPECT_TRUE(server_->AddTrustedCertificate(kTestRsa2048UnknownCert));
494 
495     // Handshake should fail for client
496     StartClientHandshakeAsync(TlsError::PeerRejectedCertificate);
497 
498     // Handshake should fail for server
499     ASSERT_EQ(server_->DoHandshake(), TlsError::CertificateRejected);
500     WaitForClientConnection();
501 
502     // All read writes should fail
503     client_thread_ = std::thread([&]() {
504         EXPECT_FALSE(client_->WriteFully(
505                 std::string_view(reinterpret_cast<const char*>(msg_.data()), msg_.size())));
506         auto data = client_->ReadFully(msg_.size());
507         EXPECT_EQ(data.size(), 0);
508     });
509 
510     auto data = server_->ReadFully(msg_.size());
511     EXPECT_EQ(data.size(), 0);
512     EXPECT_FALSE(server_->WriteFully(
513             std::string_view(reinterpret_cast<const char*>(msg_.data()), msg_.size())));
514 
515     WaitForClientConnection();
516 }
517 
TEST_F(AdbWifiTlsConnectionTest,SetClientCAList_Empty)518 TEST_F(AdbWifiTlsConnectionTest, SetClientCAList_Empty) {
519     // Setting an empty CA list should not crash
520     server_->SetClientCAList(nullptr);
521     ASSERT_DEATH(
522             {
523                 // Client cannot use this API
524                 client_->SetClientCAList(nullptr);
525             },
526             "");
527 }
528 
TEST_F(AdbWifiTlsConnectionTest,SetClientCAList_Smoke)529 TEST_F(AdbWifiTlsConnectionTest, SetClientCAList_Smoke) {
530     auto bsslIssuerList = GetCAIssuerList();
531     server_->SetClientCAList(bsslIssuerList.get());
532     client_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
533 
534     client_thread_ = std::thread([&]() {
535         client_->SetCertificateCallback([&](SSL* ssl) -> int {
536             const STACK_OF(X509_NAME)* received = SSL_get_client_CA_list(ssl);
537             EXPECT_NE(received, nullptr);
538             const size_t num_names = sk_X509_NAME_num(received);
539             EXPECT_EQ(kCAIssuers.size(), num_names);
540 
541             // Client initially registered with the wrong key. Let's change it
542             // here to verify this callback actually changes the client
543             // certificate to the right one.
544             EXPECT_TRUE(TlsConnection::SetCertAndKey(ssl, kTestRsa2048UnknownCert,
545                                                      kTestRsa2048UnknownPrivKey));
546 
547             const size_t buf_size = 256;
548             uint8_t buf[buf_size];
549             size_t idx = 0;
550             for (auto& issuer : kCAIssuers) {
551                 auto* name = sk_X509_NAME_value(received, idx++);
552                 for (auto& attr : issuer) {
553                     EXPECT_EQ(X509_NAME_get_text_by_NID(name, attr.nid,
554                                                         reinterpret_cast<char*>(buf), buf_size),
555                               attr.val.size());
556                     std::vector<uint8_t> out(buf, buf + attr.val.size());
557                     EXPECT_EQ(out, attr.val);
558                 }
559             }
560 
561             return 1;
562         });
563         // Client handshake should succeed
564         ASSERT_EQ(client_->DoHandshake(), TlsError::Success);
565     });
566 
567     EXPECT_TRUE(server_->AddTrustedCertificate(kTestRsa2048UnknownCert));
568     // Server handshake should succeed
569     ASSERT_EQ(server_->DoHandshake(), TlsError::Success);
570     client_thread_.join();
571 }
572 
TEST_F(AdbWifiTlsConnectionTest,SetClientCAList_AdbCAList)573 TEST_F(AdbWifiTlsConnectionTest, SetClientCAList_AdbCAList) {
574     bssl::UniquePtr<STACK_OF(X509_NAME)> ca_list(sk_X509_NAME_new_null());
575     std::string keyhash = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
576     auto issuer = CreateCAIssuerFromEncodedKey(keyhash);
577     ASSERT_TRUE(bssl::PushToStack(ca_list.get(), std::move(issuer)));
578     server_->SetClientCAList(ca_list.get());
579     client_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
580 
581     client_thread_ = std::thread([&]() {
582         client_->SetCertificateCallback([&](SSL* ssl) -> int {
583             // Client initially registered with a certificate that is not trusted by
584             // the server. Let's test that we can change the certificate to the
585             // trusted one here.
586             const STACK_OF(X509_NAME)* received = SSL_get_client_CA_list(ssl);
587             EXPECT_NE(received, nullptr);
588             const size_t num_names = sk_X509_NAME_num(received);
589             EXPECT_EQ(1, num_names);
590 
591             auto* name = sk_X509_NAME_value(received, 0);
592             EXPECT_NE(name, nullptr);
593             auto enc_key = ParseEncodedKeyFromCAIssuer(name);
594             EXPECT_EQ(keyhash, enc_key);
595 
596             return 1;
597         });
598         // Client handshake should succeed
599         ASSERT_EQ(client_->DoHandshake(), TlsError::Success);
600     });
601 
602     server_->SetCertVerifyCallback([](X509_STORE_CTX*) { return 1; });
603     // Server handshake should succeed
604     ASSERT_EQ(server_->DoHandshake(), TlsError::Success);
605     client_thread_.join();
606 }
607 }  // namespace tls
608 }  // namespace adb
609