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 
73   // Set up a listening socket on localhost.
74   int listening_sock = socket(AF_INET, SOCK_STREAM, 0);
75   ASSERT_NE(-1, listening_sock) << LastSocketError();
76   ScopedSocket listening_sock_closer(listening_sock);
77 
78   struct sockaddr_in sin;
79   OPENSSL_memset(&sin, 0, sizeof(sin));
80   sin.sin_family = AF_INET;
81   ASSERT_EQ(1, inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr))
82       << LastSocketError();
83   ASSERT_EQ(0, bind(listening_sock, (struct sockaddr *)&sin, sizeof(sin)))
84       << LastSocketError();
85   ASSERT_EQ(0, listen(listening_sock, 1)) << LastSocketError();
86   socklen_t sockaddr_len = sizeof(sin);
87   ASSERT_EQ(0,
88             getsockname(listening_sock, (struct sockaddr *)&sin, &sockaddr_len))
89       << LastSocketError();
90   // The Android NDK, contrary to POSIX, makes |socklen_t| signed.
91   ASSERT_EQ(sizeof(sin), static_cast<size_t>(sockaddr_len));
92 
93   // Connect to it with a connect BIO.
94   char hostname[80];
95   BIO_snprintf(hostname, sizeof(hostname), "%s:%d", "127.0.0.1",
96                ntohs(sin.sin_port));
97   bssl::UniquePtr<BIO> bio(BIO_new_connect(hostname));
98   ASSERT_TRUE(bio);
99 
100   // Write a test message to the BIO.
101   ASSERT_EQ(static_cast<int>(sizeof(kTestMessage)),
102             BIO_write(bio.get(), kTestMessage, sizeof(kTestMessage)));
103 
104   // Accept the socket.
105   int sock = accept(listening_sock, (struct sockaddr *) &sin, &sockaddr_len);
106   ASSERT_NE(-1, sock) << LastSocketError();
107   ScopedSocket sock_closer(sock);
108 
109   // Check the same message is read back out.
110   char buf[sizeof(kTestMessage)];
111   ASSERT_EQ(static_cast<int>(sizeof(kTestMessage)),
112             recv(sock, buf, sizeof(buf), 0))
113       << LastSocketError();
114   EXPECT_EQ(Bytes(kTestMessage, sizeof(kTestMessage)), Bytes(buf, sizeof(buf)));
115 }
116 
TEST(BIOTest,Printf)117 TEST(BIOTest, Printf) {
118   // Test a short output, a very long one, and various sizes around
119   // 256 (the size of the buffer) to ensure edge cases are correct.
120   static const size_t kLengths[] = {5, 250, 251, 252, 253, 254, 1023};
121 
122   bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem()));
123   ASSERT_TRUE(bio);
124 
125   for (size_t length : kLengths) {
126     SCOPED_TRACE(length);
127 
128     std::string in(length, 'a');
129 
130     int ret = BIO_printf(bio.get(), "test %s", in.c_str());
131     ASSERT_GE(ret, 0);
132     EXPECT_EQ(5 + length, static_cast<size_t>(ret));
133 
134     const uint8_t *contents;
135     size_t len;
136     ASSERT_TRUE(BIO_mem_contents(bio.get(), &contents, &len));
137     EXPECT_EQ("test " + in,
138               std::string(reinterpret_cast<const char *>(contents), len));
139 
140     ASSERT_TRUE(BIO_reset(bio.get()));
141   }
142 }
143 
144 static const size_t kLargeASN1PayloadLen = 8000;
145 
146 struct ASN1TestParam {
147   bool should_succeed;
148   std::vector<uint8_t> input;
149   // suffix_len is the number of zeros to append to |input|.
150   size_t suffix_len;
151   // expected_len, if |should_succeed| is true, is the expected length of the
152   // ASN.1 element.
153   size_t expected_len;
154   size_t max_len;
155 } kASN1TestParams[] = {
156     {true, {0x30, 2, 1, 2, 0, 0}, 0, 4, 100},
157     {false /* truncated */, {0x30, 3, 1, 2}, 0, 0, 100},
158     {false /* should be short len */, {0x30, 0x81, 1, 1}, 0, 0, 100},
159     {false /* zero padded */, {0x30, 0x82, 0, 1, 1}, 0, 0, 100},
160 
161     // Test a large payload.
162     {true,
163      {0x30, 0x82, kLargeASN1PayloadLen >> 8, kLargeASN1PayloadLen & 0xff},
164      kLargeASN1PayloadLen,
165      4 + kLargeASN1PayloadLen,
166      kLargeASN1PayloadLen * 2},
167     {false /* max_len too short */,
168      {0x30, 0x82, kLargeASN1PayloadLen >> 8, kLargeASN1PayloadLen & 0xff},
169      kLargeASN1PayloadLen,
170      4 + kLargeASN1PayloadLen,
171      3 + kLargeASN1PayloadLen},
172 
173     // Test an indefinite-length input.
174     {true,
175      {0x30, 0x80},
176      kLargeASN1PayloadLen + 2,
177      2 + kLargeASN1PayloadLen + 2,
178      kLargeASN1PayloadLen * 2},
179     {false /* max_len too short */,
180      {0x30, 0x80},
181      kLargeASN1PayloadLen + 2,
182      2 + kLargeASN1PayloadLen + 2,
183      2 + kLargeASN1PayloadLen + 1},
184 };
185 
186 class BIOASN1Test : public testing::TestWithParam<ASN1TestParam> {};
187 
TEST_P(BIOASN1Test,ReadASN1)188 TEST_P(BIOASN1Test, ReadASN1) {
189   const ASN1TestParam& param = GetParam();
190   std::vector<uint8_t> input = param.input;
191   input.resize(input.size() + param.suffix_len, 0);
192 
193   bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(input.data(), input.size()));
194   ASSERT_TRUE(bio);
195 
196   uint8_t *out;
197   size_t out_len;
198   int ok = BIO_read_asn1(bio.get(), &out, &out_len, param.max_len);
199   if (!ok) {
200     out = nullptr;
201   }
202   bssl::UniquePtr<uint8_t> out_storage(out);
203 
204   ASSERT_EQ(param.should_succeed, (ok == 1));
205   if (param.should_succeed) {
206     EXPECT_EQ(Bytes(input.data(), param.expected_len), Bytes(out, out_len));
207   }
208 }
209 
210 INSTANTIATE_TEST_CASE_P(, BIOASN1Test, testing::ValuesIn(kASN1TestParams));
211 
212 // Run through the tests twice, swapping |bio1| and |bio2|, for symmetry.
213 class BIOPairTest : public testing::TestWithParam<bool> {};
214 
TEST_P(BIOPairTest,TestPair)215 TEST_P(BIOPairTest, TestPair) {
216   BIO *bio1, *bio2;
217   ASSERT_TRUE(BIO_new_bio_pair(&bio1, 10, &bio2, 10));
218   bssl::UniquePtr<BIO> free_bio1(bio1), free_bio2(bio2);
219 
220   if (GetParam()) {
221     std::swap(bio1, bio2);
222   }
223 
224   // Check initial states.
225   EXPECT_EQ(10u, BIO_ctrl_get_write_guarantee(bio1));
226   EXPECT_EQ(0u, BIO_ctrl_get_read_request(bio1));
227 
228   // Data written in one end may be read out the other.
229   uint8_t buf[20];
230   EXPECT_EQ(5, BIO_write(bio1, "12345", 5));
231   EXPECT_EQ(5u, BIO_ctrl_get_write_guarantee(bio1));
232   ASSERT_EQ(5, BIO_read(bio2, buf, sizeof(buf)));
233   EXPECT_EQ(Bytes("12345"), Bytes(buf, 5));
234   EXPECT_EQ(10u, BIO_ctrl_get_write_guarantee(bio1));
235 
236   // Attempting to write more than 10 bytes will write partially.
237   EXPECT_EQ(10, BIO_write(bio1, "1234567890___", 13));
238   EXPECT_EQ(0u, BIO_ctrl_get_write_guarantee(bio1));
239   EXPECT_EQ(-1, BIO_write(bio1, "z", 1));
240   EXPECT_TRUE(BIO_should_write(bio1));
241   ASSERT_EQ(10, BIO_read(bio2, buf, sizeof(buf)));
242   EXPECT_EQ(Bytes("1234567890"), Bytes(buf, 10));
243   EXPECT_EQ(10u, BIO_ctrl_get_write_guarantee(bio1));
244 
245   // Unsuccessful reads update the read request.
246   EXPECT_EQ(-1, BIO_read(bio2, buf, 5));
247   EXPECT_TRUE(BIO_should_read(bio2));
248   EXPECT_EQ(5u, BIO_ctrl_get_read_request(bio1));
249 
250   // The read request is clamped to the size of the buffer.
251   EXPECT_EQ(-1, BIO_read(bio2, buf, 20));
252   EXPECT_TRUE(BIO_should_read(bio2));
253   EXPECT_EQ(10u, BIO_ctrl_get_read_request(bio1));
254 
255   // Data may be written and read in chunks.
256   EXPECT_EQ(5, BIO_write(bio1, "12345", 5));
257   EXPECT_EQ(5u, BIO_ctrl_get_write_guarantee(bio1));
258   EXPECT_EQ(5, BIO_write(bio1, "67890___", 8));
259   EXPECT_EQ(0u, BIO_ctrl_get_write_guarantee(bio1));
260   ASSERT_EQ(3, BIO_read(bio2, buf, 3));
261   EXPECT_EQ(Bytes("123"), Bytes(buf, 3));
262   EXPECT_EQ(3u, BIO_ctrl_get_write_guarantee(bio1));
263   ASSERT_EQ(7, BIO_read(bio2, buf, sizeof(buf)));
264   EXPECT_EQ(Bytes("4567890"), Bytes(buf, 7));
265   EXPECT_EQ(10u, BIO_ctrl_get_write_guarantee(bio1));
266 
267   // Successful reads reset the read request.
268   EXPECT_EQ(0u, BIO_ctrl_get_read_request(bio1));
269 
270   // Test writes and reads starting in the middle of the ring buffer and
271   // wrapping to front.
272   EXPECT_EQ(8, BIO_write(bio1, "abcdefgh", 8));
273   EXPECT_EQ(2u, BIO_ctrl_get_write_guarantee(bio1));
274   ASSERT_EQ(3, BIO_read(bio2, buf, 3));
275   EXPECT_EQ(Bytes("abc"), Bytes(buf, 3));
276   EXPECT_EQ(5u, BIO_ctrl_get_write_guarantee(bio1));
277   EXPECT_EQ(5, BIO_write(bio1, "ijklm___", 8));
278   EXPECT_EQ(0u, BIO_ctrl_get_write_guarantee(bio1));
279   ASSERT_EQ(10, BIO_read(bio2, buf, sizeof(buf)));
280   EXPECT_EQ(Bytes("defghijklm"), Bytes(buf, 10));
281   EXPECT_EQ(10u, BIO_ctrl_get_write_guarantee(bio1));
282 
283   // Data may flow from both ends in parallel.
284   EXPECT_EQ(5, BIO_write(bio1, "12345", 5));
285   EXPECT_EQ(5, BIO_write(bio2, "67890", 5));
286   ASSERT_EQ(5, BIO_read(bio2, buf, sizeof(buf)));
287   EXPECT_EQ(Bytes("12345"), Bytes(buf, 5));
288   ASSERT_EQ(5, BIO_read(bio1, buf, sizeof(buf)));
289   EXPECT_EQ(Bytes("67890"), Bytes(buf, 5));
290 
291   // Closing the write end causes an EOF on the read half, after draining.
292   EXPECT_EQ(5, BIO_write(bio1, "12345", 5));
293   EXPECT_TRUE(BIO_shutdown_wr(bio1));
294   ASSERT_EQ(5, BIO_read(bio2, buf, sizeof(buf)));
295   EXPECT_EQ(Bytes("12345"), Bytes(buf, 5));
296   EXPECT_EQ(0, BIO_read(bio2, buf, sizeof(buf)));
297 
298   // A closed write end may not be written to.
299   EXPECT_EQ(0u, BIO_ctrl_get_write_guarantee(bio1));
300   EXPECT_EQ(-1, BIO_write(bio1, "_____", 5));
301 
302   uint32_t err = ERR_get_error();
303   EXPECT_EQ(ERR_LIB_BIO, ERR_GET_LIB(err));
304   EXPECT_EQ(BIO_R_BROKEN_PIPE, ERR_GET_REASON(err));
305 
306   // The other end is still functional.
307   EXPECT_EQ(5, BIO_write(bio2, "12345", 5));
308   ASSERT_EQ(5, BIO_read(bio1, buf, sizeof(buf)));
309   EXPECT_EQ(Bytes("12345"), Bytes(buf, 5));
310 }
311 
312 INSTANTIATE_TEST_CASE_P(, BIOPairTest, testing::Values(false, true));
313