2
0

noisydgrambio.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /*
  2. * Copyright 2023-2024 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <openssl/bio.h>
  10. #include "quictestlib.h"
  11. #include "../testutil.h"
  12. #define MSG_DATA_LEN_MAX 1472
  13. #define SAMPLING_WINDOW_PERIOD 10 /* in milliseconds */
  14. #define MAX_PKTS_PER_WINDOW 1024
  15. struct pkt_info_st {
  16. size_t size;
  17. OSSL_TIME timestamp;
  18. };
  19. struct bw_limiter_st {
  20. struct pkt_info_st pinfos[MAX_PKTS_PER_WINDOW]; /* ring buffer */
  21. size_t start, num; /* ring buffer start and number of items */
  22. size_t size_sum; /* sum of packet sizes in window */
  23. size_t bw; /* bandwidth in bytes/ms */
  24. };
  25. struct noisy_dgram_st {
  26. uint64_t this_dgram;
  27. BIO_MSG msg;
  28. uint64_t reinject_dgram;
  29. int backoff;
  30. int noise_rate; /* 1 in noise_rate packets will get noise */
  31. struct bw_limiter_st recv_limit, send_limit;
  32. OSSL_TIME (*now_cb)(void *arg);
  33. void *now_cb_arg;
  34. };
  35. static long noisy_dgram_ctrl(BIO *bio, int cmd, long num, void *ptr)
  36. {
  37. long ret;
  38. BIO *next = BIO_next(bio);
  39. if (next == NULL)
  40. return 0;
  41. switch (cmd) {
  42. case BIO_CTRL_DUP:
  43. ret = 0L;
  44. break;
  45. case BIO_CTRL_NOISE_BACK_OFF: {
  46. struct noisy_dgram_st *data;
  47. data = BIO_get_data(bio);
  48. if (!TEST_ptr(data))
  49. return 0;
  50. data->backoff = 1;
  51. ret = 1;
  52. break;
  53. }
  54. case BIO_CTRL_NOISE_RATE: {
  55. struct noisy_dgram_st *data;
  56. data = BIO_get_data(bio);
  57. if (!TEST_ptr(data))
  58. return 0;
  59. data->noise_rate = (int)num;
  60. ret = 1;
  61. break;
  62. }
  63. case BIO_CTRL_NOISE_RECV_BANDWIDTH: {
  64. struct noisy_dgram_st *data;
  65. data = BIO_get_data(bio);
  66. if (!TEST_ptr(data))
  67. return 0;
  68. data->recv_limit.bw = (size_t)num;
  69. ret = 1;
  70. break;
  71. }
  72. case BIO_CTRL_NOISE_SEND_BANDWIDTH: {
  73. struct noisy_dgram_st *data;
  74. data = BIO_get_data(bio);
  75. if (!TEST_ptr(data))
  76. return 0;
  77. data->send_limit.bw = (size_t)num;
  78. ret = 1;
  79. break;
  80. }
  81. case BIO_CTRL_NOISE_SET_NOW_CB: {
  82. struct noisy_dgram_st *data;
  83. struct bio_noise_now_cb_st *now_cb = ptr;
  84. data = BIO_get_data(bio);
  85. if (!TEST_ptr(data))
  86. return 0;
  87. data->now_cb = now_cb->now_cb;
  88. data->now_cb_arg = now_cb->now_cb_arg;
  89. ret = 1;
  90. break;
  91. }
  92. default:
  93. ret = BIO_ctrl(next, cmd, num, ptr);
  94. break;
  95. }
  96. return ret;
  97. }
  98. static size_t bandwidth_limit(struct bw_limiter_st *limit, OSSL_TIME now,
  99. BIO_MSG *msg, size_t num_msg)
  100. {
  101. size_t i;
  102. OSSL_TIME sampling_start
  103. = ossl_time_subtract(now, ossl_ms2time(SAMPLING_WINDOW_PERIOD));
  104. if (limit->bw == 0) /* 0 -> no limit */
  105. return num_msg;
  106. if (num_msg > MAX_PKTS_PER_WINDOW)
  107. num_msg = MAX_PKTS_PER_WINDOW;
  108. /* trim the start of the ring buffer */
  109. for (i = 0; i < limit->num; i++) {
  110. size_t idx = (limit->start + i) % MAX_PKTS_PER_WINDOW;
  111. if (ossl_time_compare(limit->pinfos[idx].timestamp, sampling_start) >= 0)
  112. break;
  113. limit->size_sum -= limit->pinfos[idx].size;
  114. }
  115. limit->start = (limit->start + i) % MAX_PKTS_PER_WINDOW;
  116. limit->num -= i;
  117. for (i = 0; i < num_msg; ++i) {
  118. size_t end;
  119. size_t pktsize = msg[i].data_len;
  120. if ((limit->size_sum + pktsize) / SAMPLING_WINDOW_PERIOD > limit->bw) {
  121. /*
  122. * Throw out all the packets once reaching the limit,
  123. * although some following packets could still fit.
  124. * This is accurate enough.
  125. */
  126. #ifdef OSSL_NOISY_DGRAM_DEBUG
  127. printf("**BW limit applied: now: %llu orig packets %u new packets %u\n",
  128. (unsigned long long)ossl_time2ms(now),
  129. (unsigned int)num_msg, (unsigned int) i);
  130. #endif
  131. num_msg = i;
  132. break;
  133. }
  134. if (limit->num >= MAX_PKTS_PER_WINDOW) {
  135. limit->size_sum -= limit->pinfos[limit->start].size;
  136. limit->start = (limit->start + 1) % MAX_PKTS_PER_WINDOW;
  137. } else {
  138. ++limit->num;
  139. }
  140. end = (limit->start + limit->num) % MAX_PKTS_PER_WINDOW;
  141. limit->pinfos[end].size = pktsize;
  142. limit->pinfos[end].timestamp = now;
  143. limit->size_sum += pktsize;
  144. }
  145. return num_msg;
  146. }
  147. static int noisy_dgram_sendmmsg(BIO *bio, BIO_MSG *msg, size_t stride,
  148. size_t num_msg, uint64_t flags,
  149. size_t *msgs_processed)
  150. {
  151. BIO *next = BIO_next(bio);
  152. struct noisy_dgram_st *data;
  153. OSSL_TIME now;
  154. if (next == NULL)
  155. return 0;
  156. data = BIO_get_data(bio);
  157. if (!TEST_ptr(data))
  158. return 0;
  159. now = data->now_cb != NULL ? data->now_cb(data->now_cb_arg)
  160. : ossl_time_now();
  161. /* bandwidth limit can be applied on both sides */
  162. num_msg = bandwidth_limit(&data->send_limit, now, msg, num_msg);
  163. if (num_msg == 0) {
  164. *msgs_processed = 0;
  165. ERR_raise(ERR_LIB_BIO, BIO_R_NON_FATAL);
  166. return 0;
  167. }
  168. /*
  169. * We only introduce noise when receiving messages. We just pass this on
  170. * to the underlying BIO.
  171. */
  172. return BIO_sendmmsg(next, msg, stride, num_msg, flags, msgs_processed);
  173. }
  174. /* Default noise_rate value. With a value of 5 that is 20% packets. */
  175. #define NOISE_RATE 5
  176. /*
  177. * We have 3 different types of noise: drop, duplicate and delay
  178. * Each of these have equal probability.
  179. */
  180. #define NOISE_TYPE_DROP 0
  181. #define NOISE_TYPE_DUPLICATE 1
  182. #define NOISE_TYPE_DELAY 2
  183. #define NOISE_TYPE_BITFLIPS 3
  184. #define NUM_NOISE_TYPES 4
  185. /*
  186. * When a duplicate occurs we reinject the new datagram after up to
  187. * MAX_DGRAM_REINJECT datagrams have been sent. A reinject of 1 means that the
  188. * duplicate follows immediately after the original datagram. A reinject of 4
  189. * means that original datagram plus 3 other datagrams are sent before the
  190. * reinjected datagram is inserted.
  191. * This also controls when a delay (not a duplicate) occurs. In that case
  192. * we add 1 to the number because there is no point in skipping the current
  193. * datagram only to immediately reinject it in the next datagram.
  194. */
  195. #define MAX_DGRAM_REINJECT 4
  196. static void get_noise(int noise_rate, int long_header, uint64_t *reinject,
  197. int *should_drop, uint16_t *flip, size_t *flip_offset)
  198. {
  199. uint32_t type;
  200. *flip = 0;
  201. if (test_random() % noise_rate != 0) {
  202. *reinject = 0;
  203. *should_drop = 0;
  204. return;
  205. }
  206. type = test_random() % NUM_NOISE_TYPES;
  207. /*
  208. * Of noisy datagrams, 25% drop, 25% duplicate, 25% delay, 25% flip bits
  209. * A duplicated datagram keeps the current datagram and reinjects a new
  210. * identical one after up to MAX_DGRAM_DELAY datagrams have been sent.
  211. * A delayed datagram is implemented as both a reinject and a drop, i.e. an
  212. * identical datagram is reinjected after the given number of datagrams have
  213. * been sent and the current datagram is dropped.
  214. */
  215. *should_drop = (type == NOISE_TYPE_DROP || type == NOISE_TYPE_DELAY);
  216. /*
  217. * Where a duplicate occurs we reinject the copy of the datagram up to
  218. * MAX_DGRAM_DELAY datagrams later
  219. */
  220. *reinject = (type == NOISE_TYPE_DUPLICATE || type == NOISE_TYPE_DELAY)
  221. ? (uint64_t)((test_random() % MAX_DGRAM_REINJECT) + 1)
  222. : 0;
  223. /*
  224. * No point in reinjecting after 1 datagram if the current datagram is also
  225. * dropped (i.e. this is a delay not a duplicate), so we reinject after an
  226. * extra datagram in that case
  227. */
  228. *reinject += type == NOISE_TYPE_DELAY;
  229. /* flip some bits in the header */
  230. if (type == NOISE_TYPE_BITFLIPS) {
  231. /* we flip at most 8 bits of the 16 bit value at once */
  232. *flip = (test_random() % 255 + 1) << (test_random() % 8);
  233. /*
  234. * 25/50 bytes of guesstimated header size (it depends on CID length)
  235. * It does not matter much if it is overestimated.
  236. */
  237. *flip_offset = test_random() % (25 * (1 + long_header));
  238. }
  239. }
  240. static void flip_bits(unsigned char *msg, size_t msg_len, uint16_t flip,
  241. size_t flip_offset)
  242. {
  243. if (flip == 0)
  244. return;
  245. /* None of these border conditions should happen but check them anyway */
  246. if (msg_len < 2)
  247. return;
  248. if (msg_len < flip_offset + 2)
  249. flip_offset = msg_len - 2;
  250. #ifdef OSSL_NOISY_DGRAM_DEBUG
  251. printf("**Flipping bits in a datagram at offset %u\n",
  252. (unsigned int)flip_offset);
  253. BIO_dump_fp(stdout, msg, msg_len);
  254. printf("\n");
  255. #endif
  256. msg[flip_offset] ^= flip >> 8;
  257. msg[flip_offset + 1] ^= flip & 0xff;
  258. }
  259. static int noisy_dgram_recvmmsg(BIO *bio, BIO_MSG *msg, size_t stride,
  260. size_t num_msg, uint64_t flags,
  261. size_t *msgs_processed)
  262. {
  263. BIO *next = BIO_next(bio);
  264. size_t i, j, data_len = 0, msg_cnt = 0;
  265. BIO_MSG *thismsg;
  266. struct noisy_dgram_st *data;
  267. OSSL_TIME now;
  268. if (!TEST_ptr(next))
  269. return 0;
  270. data = BIO_get_data(bio);
  271. if (!TEST_ptr(data))
  272. return 0;
  273. /*
  274. * For simplicity we assume that all elements in the msg array have the
  275. * same data_len. They are not required to by the API, but it would be quite
  276. * strange for that not to be the case - and our code that calls
  277. * BIO_recvmmsg does do this (which is all that is important for this test
  278. * code). We test the invariant here.
  279. */
  280. for (i = 0; i < num_msg; i++) {
  281. if (i == 0) {
  282. data_len = msg[i].data_len;
  283. if (!TEST_size_t_le(data_len, MSG_DATA_LEN_MAX))
  284. return 0;
  285. } else if (!TEST_size_t_eq(msg[i].data_len, data_len)) {
  286. return 0;
  287. }
  288. }
  289. if (!BIO_recvmmsg(next, msg, stride, num_msg, flags, msgs_processed))
  290. return 0;
  291. #ifdef OSSL_NOISY_DGRAM_DEBUG
  292. printf("Pre-filter datagram list:\n");
  293. for (i = 0; i < *msgs_processed; i++) {
  294. printf("Pre-filter Datagram:\n");
  295. BIO_dump_fp(stdout, msg[i].data, msg[i].data_len);
  296. printf("\n");
  297. }
  298. printf("End of pre-filter datagram list\nApplying noise filters:\n");
  299. #endif
  300. now = data->now_cb != NULL ? data->now_cb(data->now_cb_arg)
  301. : ossl_time_now();
  302. msg_cnt = *msgs_processed;
  303. msg_cnt = bandwidth_limit(&data->recv_limit, now, msg, msg_cnt);
  304. if (msg_cnt == 0)
  305. goto end;
  306. if (data->noise_rate == 0)
  307. goto end;
  308. /* Introduce noise */
  309. for (i = 0, thismsg = msg;
  310. i < msg_cnt;
  311. i++, thismsg++, data->this_dgram++) {
  312. uint64_t reinject;
  313. int should_drop;
  314. uint16_t flip;
  315. size_t flip_offset;
  316. /* If we have a message to reinject then insert it now */
  317. if (data->reinject_dgram > 0
  318. && data->reinject_dgram == data->this_dgram) {
  319. if (msg_cnt < num_msg) {
  320. /* Make space for the injected message */
  321. for (j = msg_cnt; j > i; j--) {
  322. if (!bio_msg_copy(&msg[j], &msg[j - 1]))
  323. return 0;
  324. }
  325. if (!bio_msg_copy(thismsg, &data->msg))
  326. return 0;
  327. msg_cnt++;
  328. data->reinject_dgram = 0;
  329. #ifdef OSSL_NOISY_DGRAM_DEBUG
  330. printf("**Injecting a datagram\n");
  331. BIO_dump_fp(stdout, thismsg->data, thismsg->data_len);
  332. printf("\n");
  333. #endif
  334. continue;
  335. } /* else we have no space for the injection, so just drop it */
  336. data->reinject_dgram = 0;
  337. }
  338. get_noise(data->noise_rate,
  339. /* long header */ (((uint8_t *)thismsg->data)[0] & 0x80) != 0,
  340. &reinject, &should_drop, &flip, &flip_offset);
  341. if (data->backoff) {
  342. /*
  343. * We might be asked to back off on introducing too much noise if
  344. * there is a danger that the connection will fail. In that case
  345. * we always ensure that the next datagram does not get dropped so
  346. * that the connection always survives. After that we can resume
  347. * with normal noise
  348. */
  349. #ifdef OSSL_NOISY_DGRAM_DEBUG
  350. printf("**Back off applied\n");
  351. #endif
  352. should_drop = 0;
  353. flip = 0;
  354. data->backoff = 0;
  355. }
  356. flip_bits(thismsg->data, thismsg->data_len, flip, flip_offset);
  357. /*
  358. * We ignore reinjection if a message is already waiting to be
  359. * reinjected
  360. */
  361. if (reinject > 0 && data->reinject_dgram == 0) {
  362. /*
  363. * Both duplicated and delayed datagrams get reintroduced after the
  364. * delay period. Datagrams that are delayed only (not duplicated)
  365. * will also have the current copy of the datagram dropped (i.e
  366. * should_drop below will be true).
  367. */
  368. if (!bio_msg_copy(&data->msg, thismsg))
  369. return 0;
  370. data->reinject_dgram = data->this_dgram + reinject;
  371. #ifdef OSSL_NOISY_DGRAM_DEBUG
  372. printf("**Scheduling a reinject after %u messages%s\n",
  373. (unsigned int)reinject, should_drop ? "" : "(duplicating)");
  374. BIO_dump_fp(stdout, thismsg->data, thismsg->data_len);
  375. printf("\n");
  376. #endif
  377. }
  378. if (should_drop) {
  379. #ifdef OSSL_NOISY_DGRAM_DEBUG
  380. printf("**Dropping a datagram\n");
  381. BIO_dump_fp(stdout, thismsg->data, thismsg->data_len);
  382. printf("\n");
  383. #endif
  384. for (j = i + 1; j < msg_cnt; j++) {
  385. if (!bio_msg_copy(&msg[j - 1], &msg[j]))
  386. return 0;
  387. }
  388. msg_cnt--;
  389. }
  390. }
  391. #ifdef OSSL_NOISY_DGRAM_DEBUG
  392. printf("End of noise filters\nPost-filter datagram list:\n");
  393. for (i = 0; i < msg_cnt; i++) {
  394. printf("Post-filter Datagram:\n");
  395. BIO_dump_fp(stdout, msg[i].data, msg[i].data_len);
  396. printf("\n");
  397. }
  398. printf("End of post-filter datagram list\n");
  399. #endif
  400. end:
  401. *msgs_processed = msg_cnt;
  402. if (msg_cnt == 0) {
  403. ERR_raise(ERR_LIB_BIO, BIO_R_NON_FATAL);
  404. return 0;
  405. }
  406. return 1;
  407. }
  408. static void data_free(struct noisy_dgram_st *data)
  409. {
  410. if (data == NULL)
  411. return;
  412. OPENSSL_free(data->msg.data);
  413. BIO_ADDR_free(data->msg.peer);
  414. BIO_ADDR_free(data->msg.local);
  415. OPENSSL_free(data);
  416. }
  417. static int noisy_dgram_new(BIO *bio)
  418. {
  419. struct noisy_dgram_st *data = OPENSSL_zalloc(sizeof(*data));
  420. if (!TEST_ptr(data))
  421. return 0;
  422. data->noise_rate = NOISE_RATE;
  423. data->msg.data = OPENSSL_malloc(MSG_DATA_LEN_MAX);
  424. data->msg.peer = BIO_ADDR_new();
  425. data->msg.local = BIO_ADDR_new();
  426. if (data->msg.data == NULL
  427. || data->msg.peer == NULL
  428. || data->msg.local == NULL) {
  429. data_free(data);
  430. return 0;
  431. }
  432. BIO_set_data(bio, data);
  433. BIO_set_init(bio, 1);
  434. return 1;
  435. }
  436. static int noisy_dgram_free(BIO *bio)
  437. {
  438. data_free(BIO_get_data(bio));
  439. BIO_set_data(bio, NULL);
  440. BIO_set_init(bio, 0);
  441. return 1;
  442. }
  443. /* Choose a sufficiently large type likely to be unused for this custom BIO */
  444. #define BIO_TYPE_NOISY_DGRAM_FILTER (0x80 | BIO_TYPE_FILTER)
  445. static BIO_METHOD *method_noisy_dgram = NULL;
  446. /* Note: Not thread safe! */
  447. const BIO_METHOD *bio_f_noisy_dgram_filter(void)
  448. {
  449. if (method_noisy_dgram == NULL) {
  450. method_noisy_dgram = BIO_meth_new(BIO_TYPE_NOISY_DGRAM_FILTER,
  451. "Noisy datagram filter");
  452. if (method_noisy_dgram == NULL
  453. || !BIO_meth_set_ctrl(method_noisy_dgram, noisy_dgram_ctrl)
  454. || !BIO_meth_set_sendmmsg(method_noisy_dgram, noisy_dgram_sendmmsg)
  455. || !BIO_meth_set_recvmmsg(method_noisy_dgram, noisy_dgram_recvmmsg)
  456. || !BIO_meth_set_create(method_noisy_dgram, noisy_dgram_new)
  457. || !BIO_meth_set_destroy(method_noisy_dgram, noisy_dgram_free))
  458. return NULL;
  459. }
  460. return method_noisy_dgram;
  461. }
  462. void bio_f_noisy_dgram_filter_free(void)
  463. {
  464. BIO_meth_free(method_noisy_dgram);
  465. }