1 #include "fuzz.h"
2
3 #define MODULE_NAME "nfc_llcp_fuzzer"
4
5 const char fuzzer_name[] = MODULE_NAME;
6
7 enum {
8 SUB_TYPE_DUMMY,
9
10 SUB_TYPE_MAX
11 };
12
llcp_cback(uint8_t event,uint8_t reason)13 static void llcp_cback(uint8_t event, uint8_t reason) {
14 FUZZLOG(MODULE_NAME ": : event=0x%02x, reason=0x%02X", event, reason);
15 }
16
Init(Fuzz_Context &)17 static bool Init(Fuzz_Context& /*ctx*/) {
18 uint8_t LLCP_GEN_BYTES[] = {
19 LLCP_MAGIC_NUMBER_BYTE0, LLCP_MAGIC_NUMBER_BYTE1,
20 LLCP_MAGIC_NUMBER_BYTE2, LLCP_VERSION_TYPE,
21 LLCP_VERSION_LEN, (LLCP_VERSION_MAJOR << 4) | LLCP_VERSION_MINOR,
22 };
23
24 tLLCP_ACTIVATE_CONFIG config = {
25 .is_initiator = false,
26 .max_payload_size = LLCP_NCI_MAX_PAYL_SIZE,
27 .p_gen_bytes = LLCP_GEN_BYTES,
28 .gen_bytes_len = sizeof(LLCP_GEN_BYTES),
29 };
30
31 GKI_init();
32 llcp_init();
33 if (NFC_STATUS_OK != LLCP_ActivateLink(config, llcp_cback)) {
34 FUZZLOG(MODULE_NAME ": LLCP_ActivateLink failed");
35 return false;
36 }
37
38 return true;
39 }
40
Fuzz_Init(Fuzz_Context & ctx)41 static bool Fuzz_Init(Fuzz_Context& ctx) {
42 if (!Init(ctx)) {
43 FUZZLOG(MODULE_NAME ": initialization failed");
44 return false;
45 }
46
47 return true;
48 }
49
Fuzz_Deinit(Fuzz_Context &)50 static void Fuzz_Deinit(Fuzz_Context& /*ctx*/) {
51 LLCP_DeactivateLink();
52
53 // Explicitly calling llcp_link_deactivate with LLCP_LINK_TIMEOUT to avoid
54 // memory leak.
55 llcp_link_deactivate(LLCP_LINK_TIMEOUT);
56
57 llcp_cleanup();
58 GKI_shutdown();
59 }
60
Fuzz_Run(Fuzz_Context & ctx)61 static void Fuzz_Run(Fuzz_Context& ctx) {
62 for (auto it = ctx.Data.cbegin(); it != ctx.Data.cend(); ++it) {
63 FUZZLOG(MODULE_NAME ": Input[%u/%zu](Payload)=%s",
64 (uint)(it - ctx.Data.cbegin() + 1), ctx.Data.size(),
65 BytesToHex(*it).c_str());
66
67 NFC_HDR* p_msg;
68 p_msg = (NFC_HDR*)GKI_getbuf(sizeof(NFC_HDR) + it->size());
69 if (p_msg == nullptr) {
70 FUZZLOG(MODULE_NAME ": GKI_getbuf returns null, size=%zu", it->size());
71 return;
72 }
73
74 /* Initialize NFC_HDR */
75 p_msg->len = it->size();
76 p_msg->offset = 0;
77
78 uint8_t* p = (uint8_t*)(p_msg + 1) + p_msg->offset;
79 memcpy(p, it->data(), it->size());
80
81 tNFC_CONN conn = {.data = {
82 .status = NFC_STATUS_OK,
83 .p_data = p_msg,
84 }};
85
86 rf_cback(NFC_RF_CONN_ID, NFC_DATA_CEVT, &conn);
87 }
88 }
89
Fuzz_FixPackets(std::vector<bytes_t> & Packets,uint)90 void Fuzz_FixPackets(std::vector<bytes_t>& Packets, uint /*Seed*/) {
91 for (auto it = Packets.begin(); it != Packets.end(); ++it) {
92 if (it->size() < LLCP_PDU_HEADER_SIZE) {
93 it->resize(LLCP_PDU_HEADER_SIZE);
94 }
95 }
96 }
97
Fuzz_RunPackets(const std::vector<bytes_t> & Packets)98 void Fuzz_RunPackets(const std::vector<bytes_t>& Packets) {
99 Fuzz_Context ctx(SUB_TYPE_DUMMY, Packets);
100 if (Fuzz_Init(ctx)) {
101 Fuzz_Run(ctx);
102 }
103 Fuzz_Deinit(ctx);
104 }
105