1 /*
2  * Copyright 2016, 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 // Simple program to try running an APF program against a packet.
18 
19 #include <errno.h>
20 #include <getopt.h>
21 #include <inttypes.h>
22 #include <libgen.h>
23 #include <limits.h>
24 #include <pcap.h>
25 #include <stdint.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 
30 #include "disassembler.h"
31 #include "apf_interpreter.h"
32 #include "v7/apf_interpreter.h"
33 #include "v7/test_buf_allocator.h"
34 
35 #define __unused __attribute__((unused))
36 
37 // The following list must be in sync with
38 // https://cs.android.com/android/platform/superproject/main/+/main:packages/modules/NetworkStack/src/android/net/apf/ApfFilter.java;l=125
39 static const char* counter_name [] = {
40     "RESERVED_OOB",
41     "TOTAL_PACKETS",
42     "PASSED_ARP",
43     "PASSED_DHCP",
44     "PASSED_IPV4",
45     "PASSED_IPV6_NON_ICMP",
46     "PASSED_IPV4_UNICAST",
47     "PASSED_IPV6_ICMP",
48     "PASSED_IPV6_UNICAST_NON_ICMP",
49     "PASSED_ARP_NON_IPV4",
50     "PASSED_ARP_UNKNOWN",
51     "PASSED_ARP_UNICAST_REPLY",
52     "PASSED_NON_IP_UNICAST",
53     "PASSED_MDNS",
54     "DROPPED_ETH_BROADCAST",
55     "DROPPED_RA",
56     "DROPPED_GARP_REPLY",
57     "DROPPED_ARP_OTHER_HOST",
58     "DROPPED_IPV4_L2_BROADCAST",
59     "DROPPED_IPV4_BROADCAST_ADDR",
60     "DROPPED_IPV4_BROADCAST_NET",
61     "DROPPED_IPV4_MULTICAST",
62     "DROPPED_IPV6_ROUTER_SOLICITATION",
63     "DROPPED_IPV6_MULTICAST_NA",
64     "DROPPED_IPV6_MULTICAST",
65     "DROPPED_IPV6_MULTICAST_PING",
66     "DROPPED_IPV6_NON_ICMP_MULTICAST",
67     "DROPPED_802_3_FRAME",
68     "DROPPED_ETHERTYPE_BLACKLISTED",
69     "DROPPED_ARP_REPLY_SPA_NO_HOST",
70     "DROPPED_IPV4_KEEPALIVE_ACK",
71     "DROPPED_IPV6_KEEPALIVE_ACK",
72     "DROPPED_IPV4_NATT_KEEPALIVE",
73     "DROPPED_MDNS"
74 };
75 
76 enum {
77     OPT_PROGRAM,
78     OPT_PACKET,
79     OPT_PCAP,
80     OPT_DATA,
81     OPT_AGE,
82     OPT_TRACE,
83     OPT_V6,
84 };
85 
86 const struct option long_options[] = {{"program", 1, NULL, OPT_PROGRAM},
87                                       {"packet", 1, NULL, OPT_PACKET},
88                                       {"pcap", 1, NULL, OPT_PCAP},
89                                       {"data", 1, NULL, OPT_DATA},
90                                       {"age", 1, NULL, OPT_AGE},
91                                       {"trace", 0, NULL, OPT_TRACE},
92                                       {"v6", 0, NULL, OPT_V6},
93                                       {"help", 0, NULL, 'h'},
94                                       {"cnt", 0, NULL, 'c'},
95                                       {NULL, 0, NULL, 0}};
96 
97 const int COUNTER_SIZE = 4;
98 
99 // Parses hex in "input". Allocates and fills "*output" with parsed bytes.
100 // Returns length in bytes of "*output".
parse_hex(const char * input,uint8_t ** output)101 size_t parse_hex(const char* input, uint8_t** output) {
102     int length = strlen(input);
103     if (length & 1) {
104         fprintf(stderr, "Argument not even number of characters: %s\n", input);
105         exit(1);
106     }
107     length >>= 1;
108     *output = malloc(length);
109     if (*output == NULL) {
110         fprintf(stderr, "Out of memory, tried to allocate %d\n", length);
111         exit(1);
112     }
113     for (int i = 0; i < length; i++) {
114         char byte[3] = { input[i*2], input[i*2+1], 0 };
115         char* end_ptr;
116         (*output)[i] = strtol(byte, &end_ptr, 16);
117         if (end_ptr != byte + 2) {
118             fprintf(stderr, "Failed to parse hex %s\n", byte);
119             exit(1);
120         }
121     }
122     return length;
123 }
124 
print_hex(const uint8_t * input,int len)125 void print_hex(const uint8_t* input, int len) {
126     for (int i = 0; i < len; ++i) {
127         printf("%02x", input[i]);
128     }
129 }
130 
get_counter_value(const uint8_t * data,int data_len,int neg_offset)131 uint32_t get_counter_value(const uint8_t* data, int data_len, int neg_offset) {
132     if (neg_offset > -COUNTER_SIZE || neg_offset + data_len < 0) {
133         return 0;
134     }
135     uint32_t value = 0;
136     for (int i = 0; i < 4; ++i) {
137         value = value << 8 | data[data_len + neg_offset];
138         neg_offset++;
139     }
140     return value;
141 }
142 
print_counter(const uint8_t * data,int data_len)143 void print_counter(const uint8_t* data, int data_len) {
144     int counter_len = sizeof(counter_name) / sizeof(counter_name[0]);
145     for (int i = 0; i < counter_len; ++i) {
146         uint32_t value = get_counter_value(data, data_len, -COUNTER_SIZE * i);
147         if (value != 0) {
148             printf("%s : %d \n", counter_name[i], value);
149         }
150     }
151 }
152 
153 int tracing_enabled = 0;
154 
maybe_print_tracing_header()155 void maybe_print_tracing_header() {
156     if (!tracing_enabled) return;
157 
158     printf("      R0       R1       PC  Instruction\n");
159     printf("-------------------------------------------------\n");
160 
161 }
162 
print_transmitted_packet()163 void print_transmitted_packet() {
164     printf("transmitted packet: ");
165     print_hex(apf_test_buffer, (int) apf_test_tx_packet_len);
166     printf("\n");
167 }
168 
169 // Process packet through APF filter
packet_handler(int use_apf_v6_interpreter,uint8_t * program,uint32_t program_len,uint32_t ram_len,const char * pkt,uint32_t filter_age)170 void packet_handler(int use_apf_v6_interpreter, uint8_t* program,
171                     uint32_t program_len, uint32_t ram_len, const char* pkt, uint32_t filter_age) {
172     uint8_t* packet;
173     uint32_t packet_len = parse_hex(pkt, &packet);
174 
175     maybe_print_tracing_header();
176 
177     int ret;
178     if (use_apf_v6_interpreter) {
179         ret = apf_run(NULL, (uint32_t*)program, program_len, ram_len, packet, packet_len,
180                             filter_age);
181     } else {
182         ret = accept_packet(program, program_len, ram_len, packet, packet_len,
183                         filter_age);
184     }
185     printf("Packet %sed\n", ret ? "pass" : "dropp");
186 
187     free(packet);
188 }
189 
190 
apf_trace_hook(uint32_t pc,const uint32_t * regs,const uint8_t * program,uint32_t program_len,const uint8_t * packet __unused,uint32_t packet_len __unused,const uint32_t * memory __unused,uint32_t memory_len __unused)191 void apf_trace_hook(uint32_t pc, const uint32_t* regs, const uint8_t* program, uint32_t program_len,
192                     const uint8_t* packet __unused, uint32_t packet_len __unused,
193                     const uint32_t* memory __unused, uint32_t memory_len __unused) {
194     if (!tracing_enabled) return;
195 
196     printf("%8" PRIx32 " %8" PRIx32 " ", regs[0], regs[1]);
197     printf("%s\n", apf_disassemble(program, program_len, &pc));
198 }
199 
200 // Process pcap file through APF filter and generate output files
file_handler(int use_apf_v6_interpreter,uint8_t * program,uint32_t program_len,uint32_t ram_len,const char * filename,uint32_t filter_age)201 void file_handler(int use_apf_v6_interpreter, uint8_t* program,
202                   uint32_t program_len, uint32_t ram_len, const char* filename,
203                   uint32_t filter_age) {
204     char errbuf[PCAP_ERRBUF_SIZE];
205     pcap_t *pcap;
206     struct pcap_pkthdr apf_header;
207     const uint8_t* apf_packet;
208     pcap_dumper_t *passed_dumper, *dropped_dumper;
209     const char passed_file[] = "passed.pcap";
210     const char dropped_file[] = "dropped.pcap";
211     int pass = 0;
212     int drop = 0;
213 
214     pcap = pcap_open_offline(filename, errbuf);
215     if (pcap == NULL) {
216         printf("Open pcap file failed.\n");
217         exit(1);
218     }
219 
220     passed_dumper = pcap_dump_open(pcap, passed_file);
221     dropped_dumper = pcap_dump_open(pcap, dropped_file);
222 
223     if (!passed_dumper || !dropped_dumper) {
224         printf("pcap_dump_open(): open output file failed.\n");
225         pcap_close(pcap);
226         exit(1);
227     }
228 
229     while ((apf_packet = pcap_next(pcap, &apf_header)) != NULL) {
230         maybe_print_tracing_header();
231 
232         int result;
233         if (use_apf_v6_interpreter) {
234             result = apf_run(NULL, (uint32_t*)program, program_len, ram_len, apf_packet,
235                              apf_header.len, filter_age);
236         } else {
237             result = accept_packet(program, program_len, ram_len, apf_packet,
238                                    apf_header.len, filter_age);
239         }
240 
241         if (!result){
242             drop++;
243             pcap_dump((u_char*)dropped_dumper, &apf_header, apf_packet);
244         } else {
245             pass++;
246             pcap_dump((u_char*)passed_dumper, &apf_header, apf_packet);
247         }
248     }
249 
250     printf("%d packets dropped\n", drop);
251     printf("%d packets passed\n", pass);
252     pcap_dump_close(passed_dumper);
253     pcap_dump_close(dropped_dumper);
254     pcap_close(pcap);
255 }
256 
print_usage(char * cmd)257 void print_usage(char* cmd) {
258     fprintf(stderr,
259             "Usage: %s --program <program> --pcap <file>|--packet <packet> "
260             "[--data <content>] [--age <number>] [--trace]\n"
261             "  --program    APF program, in hex.\n"
262             "  --pcap       Pcap file to run through program.\n"
263             "  --packet     Packet to run through program.\n"
264             "  --data       Data memory contents, in hex.\n"
265             "  --age        Age of program in seconds (default: 0).\n"
266             "  --trace      Enable APF interpreter debug tracing\n"
267             "  --v6         Use APF v6\n"
268             "  -c, --cnt    Print the APF counters\n"
269             "  -h, --help   Show this message.\n",
270             basename(cmd));
271 }
272 
main(int argc,char * argv[])273 int main(int argc, char* argv[]) {
274     uint8_t* program = NULL;
275     uint32_t program_len;
276     const char* filename = NULL;
277     char* packet = NULL;
278     uint8_t* data = NULL;
279     uint32_t data_len = 0;
280     uint32_t filter_age = 0;
281     int print_counter_enabled = 0;
282     int use_apf_v6_interpreter = 0;
283 
284     int opt;
285     char *endptr;
286 
287     while ((opt = getopt_long_only(argc, argv, "ch", long_options, NULL)) != -1) {
288         switch (opt) {
289             case OPT_PROGRAM:
290                 program_len = parse_hex(optarg, &program);
291                 break;
292             case OPT_PACKET:
293                 if (!program) {
294                     printf("<packet> requires <program> first\n\'%s -h or --help\' "
295                            "for more information\n", basename(argv[0]));
296                     exit(1);
297                 }
298                 if (filename) {
299                     printf("Cannot use <file> with <packet> \n\'%s -h or --help\' "
300                            "for more information\n", basename(argv[0]));
301 
302                     exit(1);
303                 }
304                 packet = optarg;
305                 break;
306             case OPT_PCAP:
307                 if (!program) {
308                     printf("<file> requires <program> first\n\'%s -h or --help\' "
309                            "for more information\n", basename(argv[0]));
310 
311                     exit(1);
312                 }
313                 if (packet) {
314                     printf("Cannot use <packet> with <file>\n\'%s -h or --help\' "
315                            "for more information\n", basename(argv[0]));
316 
317                     exit(1);
318                 }
319                 filename = optarg;
320                 break;
321             case OPT_DATA:
322                 data_len = parse_hex(optarg, &data);
323                 break;
324             case OPT_AGE:
325                 errno = 0;
326                 filter_age = strtoul(optarg, &endptr, 10);
327                 if ((errno == ERANGE && filter_age == UINT32_MAX) ||
328                     (errno != 0 && filter_age == 0)) {
329                     perror("Error on age option: strtoul");
330                     exit(1);
331                 }
332                 if (endptr == optarg) {
333                     printf("No digit found in age.\n");
334                     exit(1);
335                 }
336                 break;
337             case OPT_TRACE:
338                 tracing_enabled = 1;
339                 break;
340             case OPT_V6:
341                 use_apf_v6_interpreter = 1;
342                 break;
343             case 'h':
344                 print_usage(argv[0]);
345                 exit(0);
346                 break;
347             case 'c':
348                 print_counter_enabled = 1;
349                 break;
350             default:
351                 print_usage(argv[0]);
352                 exit(1);
353                 break;
354         }
355     }
356 
357     if (!program) {
358         printf("Must have APF program in option.\n");
359         exit(1);
360     }
361 
362     if (!filename && !packet) {
363         printf("Missing file or packet after program.\n");
364         exit(1);
365     }
366 
367     // Combine the program and data into the unified APF buffer.
368     uint32_t ram_len = program_len + data_len;
369     if (use_apf_v6_interpreter) {
370        ram_len += 3;
371        ram_len &= ~3;
372        if (data_len < 20) ram_len += 20;
373     }
374 
375     if (data) {
376         program = realloc(program, ram_len);
377         memcpy(program + ram_len - data_len, data, data_len);
378         free(data);
379     }
380 
381     if (filename)
382         file_handler(use_apf_v6_interpreter, program, program_len, ram_len,
383                      filename, filter_age);
384     else
385         packet_handler(use_apf_v6_interpreter, program, program_len, ram_len,
386                        packet, filter_age);
387 
388     if (data_len) {
389         printf("Data: ");
390         print_hex(program + ram_len - data_len, data_len);
391         printf("\n");
392         if (print_counter_enabled) {
393           printf("APF packet counters: \n");
394           print_counter(program + ram_len - data_len, data_len);
395         }
396     }
397 
398     if (use_apf_v6_interpreter && apf_test_tx_packet_len != 0) {
399         print_transmitted_packet();
400     }
401 
402     free(program);
403     return 0;
404 }
405