1 /* Copyright (c) 2014, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15 #if !defined(_POSIX_C_SOURCE)
16 #define _POSIX_C_SOURCE 201410L
17 #endif
18
19 #include <algorithm>
20 #include <string>
21
22 #include <gtest/gtest.h>
23
24 #include <openssl/bio.h>
25 #include <openssl/crypto.h>
26 #include <openssl/err.h>
27 #include <openssl/mem.h>
28
29 #include "../internal.h"
30 #include "../test/test_util.h"
31
32 #if !defined(OPENSSL_WINDOWS)
33 #include <arpa/inet.h>
34 #include <fcntl.h>
35 #include <netinet/in.h>
36 #include <string.h>
37 #include <sys/socket.h>
38 #include <unistd.h>
39 #else
40 #include <io.h>
41 OPENSSL_MSVC_PRAGMA(warning(push, 3))
42 #include <winsock2.h>
43 #include <ws2tcpip.h>
OPENSSL_MSVC_PRAGMA(warning (pop))44 OPENSSL_MSVC_PRAGMA(warning(pop))
45 #endif
46
47
48 #if !defined(OPENSSL_WINDOWS)
49 static int closesocket(int sock) { return close(sock); }
LastSocketError()50 static std::string LastSocketError() { return strerror(errno); }
51 #else
52 static std::string LastSocketError() {
53 char buf[DECIMAL_SIZE(int) + 1];
54 BIO_snprintf(buf, sizeof(buf), "%d", WSAGetLastError());
55 return buf;
56 }
57 #endif
58
59 class ScopedSocket {
60 public:
ScopedSocket(int sock)61 explicit ScopedSocket(int sock) : sock_(sock) {}
~ScopedSocket()62 ~ScopedSocket() {
63 closesocket(sock_);
64 }
65
66 private:
67 const int sock_;
68 };
69
TEST(BIOTest,SocketConnect)70 TEST(BIOTest, SocketConnect) {
71 static const char kTestMessage[] = "test";
72 int listening_sock = -1;
73 socklen_t len = 0;
74 sockaddr_storage ss;
75 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) &ss;
76 struct sockaddr_in *sin = (struct sockaddr_in *) &ss;
77 OPENSSL_memset(&ss, 0, sizeof(ss));
78
79 ss.ss_family = AF_INET6;
80 listening_sock = socket(AF_INET6, SOCK_STREAM, 0);
81 ASSERT_NE(-1, listening_sock) << LastSocketError();
82 len = sizeof(*sin6);
83 ASSERT_EQ(1, inet_pton(AF_INET6, "::1", &sin6->sin6_addr))
84 << LastSocketError();
85 if (bind(listening_sock, (struct sockaddr *)sin6, sizeof(*sin6)) == -1) {
86 closesocket(listening_sock);
87
88 ss.ss_family = AF_INET;
89 listening_sock = socket(AF_INET, SOCK_STREAM, 0);
90 ASSERT_NE(-1, listening_sock) << LastSocketError();
91 len = sizeof(*sin);
92 ASSERT_EQ(1, inet_pton(AF_INET, "127.0.0.1", &sin->sin_addr))
93 << LastSocketError();
94 ASSERT_EQ(0, bind(listening_sock, (struct sockaddr *)sin, sizeof(*sin)))
95 << LastSocketError();
96 }
97
98 ScopedSocket listening_sock_closer(listening_sock);
99 ASSERT_EQ(0, listen(listening_sock, 1)) << LastSocketError();
100 ASSERT_EQ(0, getsockname(listening_sock, (struct sockaddr *)&ss, &len))
101 << LastSocketError();
102
103 char hostname[80];
104 if (ss.ss_family == AF_INET6) {
105 BIO_snprintf(hostname, sizeof(hostname), "[::1]:%d",
106 ntohs(sin6->sin6_port));
107 } else if (ss.ss_family == AF_INET) {
108 BIO_snprintf(hostname, sizeof(hostname), "127.0.0.1:%d",
109 ntohs(sin->sin_port));
110 }
111
112 // Connect to it with a connect BIO.
113 bssl::UniquePtr<BIO> bio(BIO_new_connect(hostname));
114 ASSERT_TRUE(bio);
115
116 // Write a test message to the BIO.
117 ASSERT_EQ(static_cast<int>(sizeof(kTestMessage)),
118 BIO_write(bio.get(), kTestMessage, sizeof(kTestMessage)));
119
120 // Accept the socket.
121 int sock = accept(listening_sock, (struct sockaddr *) &ss, &len);
122 ASSERT_NE(-1, sock) << LastSocketError();
123 ScopedSocket sock_closer(sock);
124
125 // Check the same message is read back out.
126 char buf[sizeof(kTestMessage)];
127 ASSERT_EQ(static_cast<int>(sizeof(kTestMessage)),
128 recv(sock, buf, sizeof(buf), 0))
129 << LastSocketError();
130 EXPECT_EQ(Bytes(kTestMessage, sizeof(kTestMessage)), Bytes(buf, sizeof(buf)));
131 }
132
TEST(BIOTest,Printf)133 TEST(BIOTest, Printf) {
134 // Test a short output, a very long one, and various sizes around
135 // 256 (the size of the buffer) to ensure edge cases are correct.
136 static const size_t kLengths[] = {5, 250, 251, 252, 253, 254, 1023};
137
138 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
139 ASSERT_TRUE(bio);
140
141 for (size_t length : kLengths) {
142 SCOPED_TRACE(length);
143
144 std::string in(length, 'a');
145
146 int ret = BIO_printf(bio.get(), "test %s", in.c_str());
147 ASSERT_GE(ret, 0);
148 EXPECT_EQ(5 + length, static_cast<size_t>(ret));
149
150 const uint8_t *contents;
151 size_t len;
152 ASSERT_TRUE(BIO_mem_contents(bio.get(), &contents, &len));
153 EXPECT_EQ("test " + in,
154 std::string(reinterpret_cast<const char *>(contents), len));
155
156 ASSERT_TRUE(BIO_reset(bio.get()));
157 }
158 }
159
160 static const size_t kLargeASN1PayloadLen = 8000;
161
162 struct ASN1TestParam {
163 bool should_succeed;
164 std::vector<uint8_t> input;
165 // suffix_len is the number of zeros to append to |input|.
166 size_t suffix_len;
167 // expected_len, if |should_succeed| is true, is the expected length of the
168 // ASN.1 element.
169 size_t expected_len;
170 size_t max_len;
171 } kASN1TestParams[] = {
172 {true, {0x30, 2, 1, 2, 0, 0}, 0, 4, 100},
173 {false /* truncated */, {0x30, 3, 1, 2}, 0, 0, 100},
174 {false /* should be short len */, {0x30, 0x81, 1, 1}, 0, 0, 100},
175 {false /* zero padded */, {0x30, 0x82, 0, 1, 1}, 0, 0, 100},
176
177 // Test a large payload.
178 {true,
179 {0x30, 0x82, kLargeASN1PayloadLen >> 8, kLargeASN1PayloadLen & 0xff},
180 kLargeASN1PayloadLen,
181 4 + kLargeASN1PayloadLen,
182 kLargeASN1PayloadLen * 2},
183 {false /* max_len too short */,
184 {0x30, 0x82, kLargeASN1PayloadLen >> 8, kLargeASN1PayloadLen & 0xff},
185 kLargeASN1PayloadLen,
186 4 + kLargeASN1PayloadLen,
187 3 + kLargeASN1PayloadLen},
188
189 // Test an indefinite-length input.
190 {true,
191 {0x30, 0x80},
192 kLargeASN1PayloadLen + 2,
193 2 + kLargeASN1PayloadLen + 2,
194 kLargeASN1PayloadLen * 2},
195 {false /* max_len too short */,
196 {0x30, 0x80},
197 kLargeASN1PayloadLen + 2,
198 2 + kLargeASN1PayloadLen + 2,
199 2 + kLargeASN1PayloadLen + 1},
200 };
201
202 class BIOASN1Test : public testing::TestWithParam<ASN1TestParam> {};
203
TEST_P(BIOASN1Test,ReadASN1)204 TEST_P(BIOASN1Test, ReadASN1) {
205 const ASN1TestParam& param = GetParam();
206 std::vector<uint8_t> input = param.input;
207 input.resize(input.size() + param.suffix_len, 0);
208
209 bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(input.data(), input.size()));
210 ASSERT_TRUE(bio);
211
212 uint8_t *out;
213 size_t out_len;
214 int ok = BIO_read_asn1(bio.get(), &out, &out_len, param.max_len);
215 if (!ok) {
216 out = nullptr;
217 }
218 bssl::UniquePtr<uint8_t> out_storage(out);
219
220 ASSERT_EQ(param.should_succeed, (ok == 1));
221 if (param.should_succeed) {
222 EXPECT_EQ(Bytes(input.data(), param.expected_len), Bytes(out, out_len));
223 }
224 }
225
226 INSTANTIATE_TEST_CASE_P(, BIOASN1Test, testing::ValuesIn(kASN1TestParams));
227
228 // Run through the tests twice, swapping |bio1| and |bio2|, for symmetry.
229 class BIOPairTest : public testing::TestWithParam<bool> {};
230
TEST_P(BIOPairTest,TestPair)231 TEST_P(BIOPairTest, TestPair) {
232 BIO *bio1, *bio2;
233 ASSERT_TRUE(BIO_new_bio_pair(&bio1, 10, &bio2, 10));
234 bssl::UniquePtr<BIO> free_bio1(bio1), free_bio2(bio2);
235
236 if (GetParam()) {
237 std::swap(bio1, bio2);
238 }
239
240 // Check initial states.
241 EXPECT_EQ(10u, BIO_ctrl_get_write_guarantee(bio1));
242 EXPECT_EQ(0u, BIO_ctrl_get_read_request(bio1));
243
244 // Data written in one end may be read out the other.
245 uint8_t buf[20];
246 EXPECT_EQ(5, BIO_write(bio1, "12345", 5));
247 EXPECT_EQ(5u, BIO_ctrl_get_write_guarantee(bio1));
248 ASSERT_EQ(5, BIO_read(bio2, buf, sizeof(buf)));
249 EXPECT_EQ(Bytes("12345"), Bytes(buf, 5));
250 EXPECT_EQ(10u, BIO_ctrl_get_write_guarantee(bio1));
251
252 // Attempting to write more than 10 bytes will write partially.
253 EXPECT_EQ(10, BIO_write(bio1, "1234567890___", 13));
254 EXPECT_EQ(0u, BIO_ctrl_get_write_guarantee(bio1));
255 EXPECT_EQ(-1, BIO_write(bio1, "z", 1));
256 EXPECT_TRUE(BIO_should_write(bio1));
257 ASSERT_EQ(10, BIO_read(bio2, buf, sizeof(buf)));
258 EXPECT_EQ(Bytes("1234567890"), Bytes(buf, 10));
259 EXPECT_EQ(10u, BIO_ctrl_get_write_guarantee(bio1));
260
261 // Unsuccessful reads update the read request.
262 EXPECT_EQ(-1, BIO_read(bio2, buf, 5));
263 EXPECT_TRUE(BIO_should_read(bio2));
264 EXPECT_EQ(5u, BIO_ctrl_get_read_request(bio1));
265
266 // The read request is clamped to the size of the buffer.
267 EXPECT_EQ(-1, BIO_read(bio2, buf, 20));
268 EXPECT_TRUE(BIO_should_read(bio2));
269 EXPECT_EQ(10u, BIO_ctrl_get_read_request(bio1));
270
271 // Data may be written and read in chunks.
272 EXPECT_EQ(5, BIO_write(bio1, "12345", 5));
273 EXPECT_EQ(5u, BIO_ctrl_get_write_guarantee(bio1));
274 EXPECT_EQ(5, BIO_write(bio1, "67890___", 8));
275 EXPECT_EQ(0u, BIO_ctrl_get_write_guarantee(bio1));
276 ASSERT_EQ(3, BIO_read(bio2, buf, 3));
277 EXPECT_EQ(Bytes("123"), Bytes(buf, 3));
278 EXPECT_EQ(3u, BIO_ctrl_get_write_guarantee(bio1));
279 ASSERT_EQ(7, BIO_read(bio2, buf, sizeof(buf)));
280 EXPECT_EQ(Bytes("4567890"), Bytes(buf, 7));
281 EXPECT_EQ(10u, BIO_ctrl_get_write_guarantee(bio1));
282
283 // Successful reads reset the read request.
284 EXPECT_EQ(0u, BIO_ctrl_get_read_request(bio1));
285
286 // Test writes and reads starting in the middle of the ring buffer and
287 // wrapping to front.
288 EXPECT_EQ(8, BIO_write(bio1, "abcdefgh", 8));
289 EXPECT_EQ(2u, BIO_ctrl_get_write_guarantee(bio1));
290 ASSERT_EQ(3, BIO_read(bio2, buf, 3));
291 EXPECT_EQ(Bytes("abc"), Bytes(buf, 3));
292 EXPECT_EQ(5u, BIO_ctrl_get_write_guarantee(bio1));
293 EXPECT_EQ(5, BIO_write(bio1, "ijklm___", 8));
294 EXPECT_EQ(0u, BIO_ctrl_get_write_guarantee(bio1));
295 ASSERT_EQ(10, BIO_read(bio2, buf, sizeof(buf)));
296 EXPECT_EQ(Bytes("defghijklm"), Bytes(buf, 10));
297 EXPECT_EQ(10u, BIO_ctrl_get_write_guarantee(bio1));
298
299 // Data may flow from both ends in parallel.
300 EXPECT_EQ(5, BIO_write(bio1, "12345", 5));
301 EXPECT_EQ(5, BIO_write(bio2, "67890", 5));
302 ASSERT_EQ(5, BIO_read(bio2, buf, sizeof(buf)));
303 EXPECT_EQ(Bytes("12345"), Bytes(buf, 5));
304 ASSERT_EQ(5, BIO_read(bio1, buf, sizeof(buf)));
305 EXPECT_EQ(Bytes("67890"), Bytes(buf, 5));
306
307 // Closing the write end causes an EOF on the read half, after draining.
308 EXPECT_EQ(5, BIO_write(bio1, "12345", 5));
309 EXPECT_TRUE(BIO_shutdown_wr(bio1));
310 ASSERT_EQ(5, BIO_read(bio2, buf, sizeof(buf)));
311 EXPECT_EQ(Bytes("12345"), Bytes(buf, 5));
312 EXPECT_EQ(0, BIO_read(bio2, buf, sizeof(buf)));
313
314 // A closed write end may not be written to.
315 EXPECT_EQ(0u, BIO_ctrl_get_write_guarantee(bio1));
316 EXPECT_EQ(-1, BIO_write(bio1, "_____", 5));
317
318 uint32_t err = ERR_get_error();
319 EXPECT_EQ(ERR_LIB_BIO, ERR_GET_LIB(err));
320 EXPECT_EQ(BIO_R_BROKEN_PIPE, ERR_GET_REASON(err));
321
322 // The other end is still functional.
323 EXPECT_EQ(5, BIO_write(bio2, "12345", 5));
324 ASSERT_EQ(5, BIO_read(bio1, buf, sizeof(buf)));
325 EXPECT_EQ(Bytes("12345"), Bytes(buf, 5));
326 }
327
328 INSTANTIATE_TEST_CASE_P(, BIOPairTest, testing::Values(false, true));
329