├── LICENSE ├── README.md └── json2pcap.py /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # json2pcap 2 | 3 | Script which can be used to reconstruct pcap and perform packet modifications from tshark json output. 4 | Script is also allowing to perform pcap masking or anonymization. 5 | 6 | This repository contains more recent and experimental changes compared to Wireshark (https://github.com/wireshark/wireshark/tree/master/tools/json2pcap). 7 | 8 | Command tshark -T json -x or -T jsonraw output adds into hex-data output in JSON also the information on which position each field is dissected in the original frame, what is the field length, the bitmask (for not byte aligned fields) and the type. This information can be used for latter processing. One use-case is the json2pcap script included in wireshark, which assembles the protocol layers back together from upper to lowers layers. This allows reverse json to pcap conversion and also the packet modification/editing/rewriting. 9 | 10 | /wireshark/tools/json2pcap/json2pcap.py 11 | 12 | ## Prerequisites 13 | ``` 14 | pip install scapy 15 | pip install ijson 16 | pip install bitstring 17 | ``` 18 | 19 | ## Usage 20 | ``` 21 | usage: json2pcap.py [-h] [--version] [-i [INFILE]] -o OUTFILE [-p] [-m MASKED_FIELD] [-a ANONYMIZED_FIELD] [-s SALT] [-v] 22 | 23 | json2pcap 1.3 24 | 25 | Utility to generate pcap from json format. 26 | 27 | Packet modification: 28 | In input json it is possible to modify the raw values of decoded fields. 29 | The output pcap will include the modified values. The algorithm of 30 | generating the output pcap is to get all raw hex fields from input json and 31 | then assembling them by layering from longest (less decoded fields) to 32 | shortest (more decoded fields). It means if the modified raw field is 33 | shorter field (more decoded field) it takes precedence against modification 34 | in longer field (less decoded field). If the json includes duplicated raw 35 | fields with same position and length, the behavior is not deterministic. 36 | For manual packet editing it is always possible to remove any not required 37 | raw fields from json, only frame_raw is field mandatory for reconstruction. 38 | 39 | Packet modification with -p switch: 40 | The python script is generated instead of pcap. This python script when 41 | executed will generate the pcap of 1st packet from input json. The 42 | generated code includes the decoded fields and the function to assembly the 43 | packet. This enables to modify the script and programmatically edit or 44 | encode the packet variables. The assembling algorithm is different, because 45 | the decoded packet fields are relative and points to parent node with their 46 | position (compared to input json which has absolute positions). 47 | 48 | Pcap masking and anonymization with -m and -a switch: 49 | The script allows to mask or anonymize the selected json raw fields. If the 50 | The fields are selected and located on lower protocol layers, they are not 51 | The overwritten by upper fields which are not marked by these switches. 52 | The pcap masking and anonymization can be performed in the following way: 53 | 54 | tshark -r orig.pcap -T json -x --no-duplicate-keys | \ python json2pcap.py 55 | -m "ip.src_raw" -a "ip.dst_raw" -o anonymized.pcap 56 | In this example the ip.src_raw field is masked with ffffffff by byte values 57 | and ip.dst_raw is hashed by randomly generated salt. 58 | 59 | Additionally the following syntax is valid to anonymize portion of field 60 | tshark -r orig.pcap -T json -x --no-duplicate-keys | \ python json2pcap.py 61 | -m "ip.src_raw[2:]" -a "ip.dst_raw[:-2]" -o anonymized.pcap 62 | Where the src_ip first byte is preserved and dst_ip last byte is preserved. 63 | And the same can be achieved by 64 | tshark -r orig.pcap -T json -x --no-duplicate-keys | \ python json2pcap.py 65 | -m "ip.src_raw[2:8]" -a "ip.dst_raw[0:6]" -o anonymized.pcap 66 | 67 | Masking and anonymization limitations are mainly the following: 68 | - In case the tshark is performing reassembling from multiple frames, the 69 | backward pcap reconstruction is not properly performed and can result in 70 | malformed frames. 71 | - The new values in the fields could violate the field format, as the 72 | json2pcap is no performing correct protocol encoding with respect to 73 | allowed values of the target field and field encoding. 74 | 75 | optional arguments: 76 | -h, --help show this help message and exit 77 | --version show program's version number and exit 78 | -i [INFILE], --infile [INFILE] 79 | json generated by tshark -T json -x 80 | or by tshark -T jsonraw (not preserving frame timestamps). 81 | If no inpout file is specified script reads from stdin. 82 | -o OUTFILE, --outfile OUTFILE 83 | output pcap filename 84 | -p, --python generate python payload instead of pcap (only 1st packet) 85 | -m MASKED_FIELD, --mask MASKED_FIELD 86 | mask the specific raw field (e.g. -m "ip.src_raw" -m "ip.dst_raw[2:6]") 87 | -a ANONYMIZED_FIELD, --anonymize ANONYMIZED_FIELD 88 | anonymize the specific raw field (e.g. -a "ip.src_raw[2:]" -a "ip.dst_raw[:-2]") 89 | -s SALT, --salt SALT salt use for anonymization. If no value is provided it is randomized. 90 | -v, --verbose verbose output 91 | ``` 92 | 93 | # Pcap anonymization 94 | Pcap anonymization can be performed in the following way: 95 | ``` 96 | tshark -r original.pcap -T json -x --no-duplicate-keys | \ 97 | python json2pcap.py -a "ip.src_raw" -a "ip.dst_raw" -o anonymized.pcap 98 | ``` 99 | 100 | By -a switch should be specified all fields which require anonymization. 101 | 102 | # Limitations 103 | In case the tshark is performing reassembly from multiple frames, the backward pcap reconstruction performed by json2pcap is not properly recovering the original frames. 104 | 105 | To overcome this limitation it is possible to use tshark with supressed packet reassembly. To disable reassembly for specific protocol use `tshark -o :FALSE`. And for `` see `tshark -G defaultprefs`. After disabling packet reassembly, the protocol frames should be assembled correctly by json2pcap. However the masking/anonymization will not be performed for fragmented protocols. 106 | 107 | The fields that are using bitmask could be incorrectly re-encoded. From the tshark json raw output it is ambigious if the field is encoded by little endian or by big endian. 108 | 109 | # Attribution 110 | Copyright 2020, Martin Kacer and contributors 111 | 112 | # License 113 | This program is free software; you can redistribute it and/or 114 | modify it under the terms of the GNU General Public License 115 | as published by the Free Software Foundation; either version 2 116 | of the License, or (at your option) any later version. 117 | 118 | This program is distributed in the hope that it will be useful, 119 | but WITHOUT ANY WARRANTY; without even the implied warranty of 120 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 121 | GNU General Public License for more details. 122 | 123 | You should have received a copy of the GNU General Public License 124 | along with this program; if not, write to the Free Software 125 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 126 | -------------------------------------------------------------------------------- /json2pcap.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # 5 | # Copyright 2020, Martin Kacer and contributors 6 | # 7 | # Wireshark - Network traffic analyzer 8 | # By Gerald Combs 9 | # Copyright 1998 Gerald Combs 10 | # 11 | # SPDX-License-Identifier: GPL-2.0-or-later 12 | 13 | import sys 14 | import ijson 15 | import operator 16 | import copy 17 | import os 18 | import binascii 19 | import array 20 | import argparse 21 | import subprocess 22 | import string 23 | import random 24 | import math 25 | import hashlib 26 | import re 27 | from collections import OrderedDict 28 | from scapy import all as scapy 29 | import bitstring 30 | from scapy.config import conf 31 | from scapy.packet import Packet 32 | 33 | conf.l2types.register(1, Packet) 34 | 35 | try: 36 | # Python 2 forward compatibility 37 | range = xrange 38 | except NameError: 39 | pass 40 | 41 | # Field anonymization class 42 | class AnonymizedField: 43 | ''' 44 | The Anonymization field object specifying anonymization 45 | :filed arg: field name 46 | :type arg: anonymization type [0 masking 0xff, 1 anonymization shake_256] 47 | :start arg: If specified, the anonymization starts at given byte number 48 | :end arg: If specified, the anonymization ends at given byte number 49 | ''' 50 | def __init__(self, field, type): 51 | self.field = field 52 | self.type = type 53 | self.start = None 54 | self.end = None 55 | 56 | match = re.search(r'(\S+)\[(-?\d+)?:(-?\d+)?\]', field) 57 | if match: 58 | self.field = match.group(1) 59 | self.start = match.group(2) 60 | if self.start is not None: 61 | self.start = int(self.start) 62 | self.end = match.group(3) 63 | if self.end is not None: 64 | self.end = int(self.end) 65 | 66 | # Returns the new field value after anonymization 67 | def anonymize_field_shake256(self, field, type, salt): 68 | shake = hashlib.shake_256(str(field + ':' + salt).encode('utf-8')) 69 | 70 | # String type, output should be ASCII 71 | if type in [26, 27, 28]: 72 | length = math.ceil(len(field)/4) 73 | shake_hash = shake.hexdigest(length) 74 | ret_string = array.array('B', str.encode(shake_hash)) 75 | ret_string = ''.join('{:02x}'.format(x) for x in ret_string) 76 | # Other types, output could be HEX 77 | else: 78 | length = math.ceil(len(field)/2) 79 | shake_hash = shake.hexdigest(length) 80 | ret_string = shake_hash 81 | 82 | # Correct the string length 83 | if (len(ret_string) < len(field)): 84 | ret_string = ret_string.ljust(len(field)) 85 | if (len(ret_string) > len(field)): 86 | ret_string = ret_string[:len(field)] 87 | 88 | return ret_string 89 | 90 | def anonymize_field(self, _h, _t, salt): 91 | s = 0 92 | e = None 93 | if self.start: 94 | s = self.start 95 | if self.end: 96 | e = self.end 97 | if e < 0: 98 | e = len(_h) + e 99 | else: 100 | e = len(_h) 101 | h = _h[s:e] 102 | if self.type == 0: 103 | h = 'f' * len(h) 104 | elif self.type == 1: 105 | h = self.anonymize_field_shake256(h, _t, salt) 106 | 107 | h_mask = '0' * len(_h[0:s]) + 'f' * len(h) + '0' * len(_h[e:]) 108 | h = _h[0:s] + h + _h[e:] 109 | return [h, h_mask] 110 | 111 | def make_unique(key, dct): 112 | counter = 0 113 | unique_key = key 114 | 115 | while unique_key in dct: 116 | counter += 1 117 | unique_key = '{}_{}'.format(key, counter) 118 | return unique_key 119 | 120 | 121 | def parse_object_pairs(pairs): 122 | dct = OrderedDict() 123 | for key, value in pairs: 124 | if key in dct: 125 | key = make_unique(key, dct) 126 | dct[key] = value 127 | 128 | return dct 129 | 130 | # 131 | # ********* PY TEMPLATES ********* 132 | # 133 | def read_py_function(name): 134 | s = '' 135 | record = False 136 | indent = 0 137 | 138 | file = open(__file__) 139 | for line in file: 140 | 141 | ind = len(line) - len(line.lstrip()) 142 | 143 | if (line.find("def " + name) != -1): 144 | record = True 145 | indent = ind 146 | elif (record == True and indent == ind and len(line) > 1): 147 | record = False 148 | 149 | if (record == True): 150 | s = s + line 151 | 152 | file.close() 153 | return s 154 | 155 | py_header = """#!/usr/bin/env python 156 | # -*- coding: utf-8 -*- 157 | 158 | # File generated by json2pcap.py 159 | # json2pcap.py created by Martin Kacer, 2020 160 | 161 | import os 162 | import binascii 163 | import array 164 | import sys 165 | import subprocess 166 | from collections import OrderedDict 167 | from scapy import all as scapy 168 | 169 | try: 170 | # Python 2 forward compatibility 171 | range = xrange 172 | except NameError: 173 | pass 174 | 175 | # ***************************************************** 176 | # * PACKET PAYLOAD GENERATED FROM INPUT PCAP * 177 | # * Modify this function to edit the packet * 178 | # ***************************************************** 179 | def main(): 180 | d = OrderedDict() 181 | """ 182 | 183 | py_footer = """ generate_pcap(d) 184 | 185 | # ***************************************************** 186 | # * FUNCTIONS from TEMPLATE * 187 | # * Do not edit these functions if not required * 188 | # ***************************************************** 189 | 190 | """ 191 | py_footer = py_footer + read_py_function("to_bytes") 192 | py_footer = py_footer + read_py_function("lsb") 193 | py_footer = py_footer + read_py_function("multiply_strings") 194 | py_footer = py_footer + read_py_function("rewrite_frame") 195 | py_footer = py_footer + read_py_function("assemble_frame") 196 | py_footer = py_footer + read_py_function("generate_pcap") 197 | 198 | py_footer = py_footer + """ 199 | 200 | if __name__ == '__main__': 201 | main() 202 | """ 203 | # 204 | # ***** End of PY TEMPLATES ****** 205 | # 206 | 207 | 208 | 209 | # 210 | # ********** FUNCTIONS *********** 211 | # 212 | 213 | def raw_flat_collector(dict): 214 | if hasattr(dict, 'items'): 215 | for k, v in dict.items(): 216 | if k.endswith("_raw"): 217 | # check if the _raw value is nested list 218 | if any(isinstance(i, list) for i in v): 219 | for _v in v: 220 | yield k, _v 221 | # else 222 | else: 223 | yield k, v 224 | else: 225 | # check if the non _raw value is list 226 | if type(v) is list: 227 | for _v in v: 228 | for val in raw_flat_collector(_v): 229 | yield val 230 | # else 231 | else: 232 | for val in raw_flat_collector(v): 233 | yield val 234 | 235 | # d - input dictionary, parsed from json 236 | # r - result dictionary 237 | # frame_name - parent protocol name 238 | # frame_position - parent protocol position 239 | def py_generator(d, r, frame_name='frame_raw', frame_position=0): 240 | if (d is None or d is None): 241 | return 242 | 243 | if hasattr(d, 'items'): 244 | for k, v in d.items(): 245 | 246 | # no recursion 247 | if ( k.endswith("_raw") or ("_raw_" in k) ): 248 | if (isinstance(v[1], (list, tuple)) or isinstance(v[2], (list, tuple)) ): 249 | #i = 1; 250 | for _v in v: 251 | h = _v[0] 252 | p = _v[1] 253 | l = _v[2] * 2 254 | b = _v[3] 255 | t = _v[4] 256 | if (len(h) != l): 257 | l = len(h) 258 | 259 | p = p - frame_position 260 | 261 | # Add into result dictionary 262 | key = str(k).replace('.', '_') 263 | key = make_unique(key, r) 264 | 265 | fn = frame_name.replace('.', '_') 266 | if (fn == key): 267 | fn = None 268 | value = [fn , h, p, l, b, t] 269 | 270 | r[key] = value 271 | 272 | else: 273 | h = v[0] 274 | p = v[1] 275 | l = v[2] * 2 276 | b = v[3] 277 | t = v[4] 278 | if (len(h) != l): 279 | l = len(h) 280 | 281 | p = p - frame_position 282 | 283 | # Add into result dictionary 284 | key = str(k).replace('.', '_') 285 | key = make_unique(key, r) 286 | 287 | fn = frame_name.replace('.', '_') 288 | if (fn == key): 289 | fn = None 290 | value = [fn , h, p, l, b, t] 291 | 292 | r[key] = value 293 | 294 | # recursion 295 | else: 296 | if isinstance(v, dict): 297 | fn = frame_name 298 | fp = frame_position 299 | 300 | # if there is also preceding raw protocol frame use it 301 | # remove tree suffix 302 | key = k 303 | if (key.endswith("_tree") or ("_tree_" in key)): 304 | key = key.replace('_tree', '') 305 | 306 | raw_key = key + "_raw" 307 | if (raw_key in d): 308 | # f = d[raw_key][0] 309 | fn = raw_key 310 | fp = d[raw_key][1] 311 | 312 | 313 | py_generator(v, r, fn, fp) 314 | 315 | elif isinstance(v, (list, tuple)): 316 | 317 | fn = frame_name 318 | fp = frame_position 319 | 320 | # if there is also preceding raw protocol frame use it 321 | # remove tree suffix 322 | key = k 323 | if (key.endswith("_tree") or ("_tree_" in key)): 324 | key = key.replace('_tree', '') 325 | 326 | raw_key = key + "_raw" 327 | if (raw_key in d): 328 | fn = raw_key 329 | fp = d[raw_key][1] 330 | 331 | for _v in v: 332 | py_generator(_v, r, frame_name, frame_position) 333 | 334 | # To emulate Python 3.2 335 | def to_bytes(n, length, endianess='big'): 336 | h = '%x' % n 337 | s = bytearray.fromhex(('0' * (len(h) % 2) + h).zfill(length * 2)[:length * 2]) 338 | return s if endianess == 'big' else s[::-1] 339 | 340 | # Returns the index, counting from 0, of the least significant set bit in x 341 | def lsb(x): 342 | return (x & -x).bit_length() - 1 343 | 344 | # Returns the index, counting from 0, of the least significant set bit in x from bytetarray 345 | def lsb_bytearray(X): 346 | r = 0 347 | for x in reversed(X): 348 | if (lsb(x) != -1): 349 | return r + lsb(x) 350 | else: 351 | r = r + 8 352 | return -1 353 | 354 | # Replace parts of original_string by new_string, only if mask in the byte is not ff 355 | def multiply_strings(original_string, new_string, mask): 356 | 357 | ret_string = new_string 358 | if mask == None: 359 | return ret_string 360 | for i in range(0, min(len(original_string), len(new_string), len(mask)), 2): 361 | if mask[i:i + 2] == 'ff': 362 | #print("ff") 363 | ret_string = ret_string[:i] + original_string[i:i + 2] + ret_string[i + 2:] 364 | 365 | return ret_string 366 | 367 | # Rewrite frame 368 | # h - hex bytes 369 | # p - position 370 | # l - length 371 | # b - bitmask 372 | # t - type 373 | # frame_mmask - optional, modification mask (00 - further modifiable byte, ff - further not modifiable byte) 374 | def rewrite_frame(frame_raw, h, p, l, b, t, frame_mmask = None): 375 | 376 | #print("frame_raw = " + str(frame_raw)) 377 | #print("h = " + str(h)) 378 | #print("p = " + str(p)) 379 | #print("l = " + str(l)) 380 | #print("b = " + str(b)) 381 | #print("t = " + str(t)) 382 | #print("frame_mmask = " + str(frame_mmask)) 383 | 384 | if p < 0 or l <= 0 or h is None or not h: 385 | return frame_raw 386 | 387 | # no bitmask 388 | if(b == 0): 389 | if (len(h) != l): 390 | l = len(h) 391 | 392 | frame_raw_new = frame_raw[:p] + h + frame_raw[p + l:] 393 | return multiply_strings(frame_raw, frame_raw_new, frame_mmask) 394 | # bitmask 395 | else: 396 | 397 | # TODO: currently do not perform modification for bitmask fields - not reliable 398 | return frame_raw 399 | 400 | # get hex string from frame which will be replaced 401 | _h = frame_raw[p:p + l] 402 | #print("_h = " + _h) 403 | 404 | # add 0 padding to have correct length 405 | if (len(_h) % 2 == 1): 406 | _h = '0' + _h 407 | if (len(h) % 2 == 1): 408 | h = '0' + h 409 | 410 | # Only replace bits defined by mask 411 | # new_hex = (old_hex & !mask) | (new_hex & mask) 412 | _H = bytearray.fromhex(_h) 413 | _H = (array.array('B', _H)) 414 | #b_H = bitstring.BitArray("0x" + _h) 415 | 416 | # for certain types reverse byte array 417 | REVERSED_BYTE_ORDER_TYPES = [] 418 | if(t in REVERSED_BYTE_ORDER_TYPES): 419 | _H = _H[::-1] 420 | b_H = bitstring.BitArray(_H) 421 | 422 | # reset the mask byte array 423 | M = to_bytes(b, len(_H)) 424 | M = array.array('B', M) 425 | bM = bitstring.BitArray(M) 426 | 427 | # shift mask aligned to position 428 | #for i in range(len(M)): 429 | # if (i + p / 2) < len(M): 430 | # M[i] = M[i + int(p / 2)] 431 | # else: 432 | # M[i] = 0x00 433 | 434 | #for i in range(len(_H)): 435 | # print("_H = {0:08b}".format(_H[i])) 436 | #for i in range(len(M)): 437 | # print(" M = {0:08b}".format(M[i])) 438 | 439 | # increase the array if needed 440 | if len(h) < len(M)*2: 441 | h = h.zfill(len(M)*2) 442 | #if len(h) < len(M)*2: 443 | # h = h[::-1].zfill(len(M)*2)[::-1] 444 | 445 | H = bytearray.fromhex(h) 446 | H = array.array('B', H) 447 | bH = bitstring.BitArray("0x" + h) 448 | 449 | #print("bM = " + str(bM.bin)) 450 | # bit shift the H to the left by bitmask, increase h if the mask is larger 451 | if lsb_bytearray(M) != -1: 452 | bH = bH << int(lsb_bytearray(M)) 453 | 454 | 455 | #for i in range(len(H)): 456 | # print("after shift H = {0:08b}".format(_H[i])) 457 | 458 | #for i in range(len(H)): 459 | # print(" H = {0:08b}".format(H[i])) 460 | 461 | #j = 0; 462 | #for i in range(len(_H)): 463 | #if (M[i] != 0): 464 | #v = H[j] << lsb(M[i]) 465 | #print("Debug: {0:08b}".format(v)) 466 | # _H[i] = (H[i] & M[i]) | (_H[i] & ~M[i]) #| (v & M[i]) 467 | #print("Debug: " + str(_H[i])) 468 | # j = j + 1; 469 | 470 | #print("================") 471 | #print("b_H = " + str(b_H.bin)) 472 | #print("bM = " + str(bM.bin)) 473 | #print("bH = " + str(bH.bin)) 474 | b_H = bH & bM | b_H & ~bM 475 | #print("b_H = " + str(b_H.bin)) 476 | #print("================") 477 | _H = b_H.tobytes() 478 | 479 | #for i in range(len(_H)): 480 | # print("_H = {0:08b}".format(_H[i])) 481 | 482 | # for certain types reverse byte array 483 | if(t in REVERSED_BYTE_ORDER_TYPES): 484 | _H = _H[::-1] 485 | masked_h = binascii.hexlify(_H[::-1]) 486 | masked_h = masked_h.decode('ascii') 487 | 488 | frame_raw_new = frame_raw[:p] + str(masked_h) + frame_raw[p + l:] 489 | 490 | return multiply_strings(frame_raw, frame_raw_new, frame_mmask) 491 | 492 | 493 | def assemble_frame(d, frame_time): 494 | input = d['frame_raw'][1] 495 | isFlat = False 496 | linux_cooked_header = False; 497 | while(isFlat == False): 498 | isFlat = True 499 | _d = d.copy() 500 | for key, val in _d.items(): 501 | h = str(val[1]) # hex 502 | p = val[2] * 2 # position 503 | l = val[3] * 2 # length 504 | b = val[4] # bitmask 505 | t = val[5] # type 506 | 507 | if (key == "sll_raw"): 508 | linux_cooked_header = True; 509 | 510 | # only if the node is not parent 511 | isParent = False 512 | for k, v in d.items(): 513 | if (v[0] == key): 514 | isParent = True 515 | isFlat = False 516 | break 517 | 518 | if (isParent == False and val[0] is not None): 519 | d[val[0]][1] = rewrite_frame(d[val[0]][1], h, p, l, b, t) 520 | del d[key] 521 | 522 | output = d['frame_raw'][1] 523 | 524 | # for Linux cooked header replace dest MAC and remove two bytes to reconstruct normal frame 525 | if (linux_cooked_header): 526 | output = "000000000000" + output[6*2:] # replce dest MAC 527 | output = output[:12*2] + "" + output[14*2:] # remove two bytes before Protocol 528 | 529 | return output 530 | 531 | def generate_pcap(d): 532 | # 1. Assemble frame 533 | input = d['frame_raw'][1] 534 | output = assemble_frame(d, None) 535 | #print(input) 536 | #print(output) 537 | # 2. Testing: compare input and output for not modified json 538 | if (input != output): 539 | #print("Modified frames: ") 540 | s1 = input 541 | s2 = output 542 | #print(s1) 543 | #print(s2) 544 | if (len(s1) == len(s2)): 545 | d = [i for i in range(len(s1)) if s1[i] != s2[i]] 546 | #print(d) 547 | # 3. Generate pcap 548 | outfile = sys.argv[0] + ".pcap" 549 | pcap_out = scapy.PcapWriter(outfile, append=False, sync=False) 550 | new_packet = scapy.Packet(bytearray.fromhex(output)) 551 | pcap_out.write(new_packet) 552 | #print("Generated " + outfile) 553 | 554 | # 555 | # ************ MAIN ************** 556 | # 557 | VERSION = "1.3" 558 | 559 | parser = argparse.ArgumentParser(description=r""" 560 | json2pcap {version} 561 | 562 | Utility to generate pcap from json format. 563 | 564 | Packet modification: 565 | In input json it is possible to modify the raw values of decoded fields. 566 | The output pcap will include the modified values. The algorithm of 567 | generating the output pcap is to get all raw hex fields from input json and 568 | then assembling them by layering from longest (less decoded fields) to 569 | shortest (more decoded fields). It means if the modified raw field is 570 | shorter field (more decoded field) it takes precedence against modification 571 | in longer field (less decoded field). If the json includes duplicated raw 572 | fields with same position and length, the behavior is not deterministic. 573 | For manual packet editing it is always possible to remove any not required 574 | raw fields from json, only frame_raw is field mandatory for reconstruction. 575 | 576 | Packet modification with -p switch: 577 | The python script is generated instead of pcap. This python script when 578 | executed will generate the pcap of 1st packet from input json. The 579 | generated code includes the decoded fields and the function to assembly the 580 | packet. This enables to modify the script and programmatically edit or 581 | encode the packet variables. The assembling algorithm is different, because 582 | the decoded packet fields are relative and points to parent node with their 583 | position (compared to input json which has absolute positions). 584 | 585 | Pcap masking and anonymization with -m and -a switch: 586 | The script allows to mask or anonymize the selected json raw fields. If the 587 | The fields are selected and located on lower protocol layers, they are not 588 | The overwritten by upper fields which are not marked by these switches. 589 | The pcap masking and anonymization can be performed in the following way: 590 | 591 | tshark -r orig.pcap -T json -x --no-duplicate-keys | \ python json2pcap.py 592 | -m "ip.src_raw" -a "ip.dst_raw" -o anonymized.pcap 593 | In this example the ip.src_raw field is masked with ffffffff by byte values 594 | and ip.dst_raw is hashed by randomly generated salt. 595 | 596 | Additionally the following syntax is valid to anonymize portion of field 597 | tshark -r orig.pcap -T json -x --no-duplicate-keys | \ python json2pcap.py 598 | -m "ip.src_raw[2:]" -a "ip.dst_raw[:-2]" -o anonymized.pcap 599 | Where the src_ip first byte is preserved and dst_ip last byte is preserved. 600 | And the same can be achieved by 601 | tshark -r orig.pcap -T json -x --no-duplicate-keys | \ python json2pcap.py 602 | -m "ip.src_raw[2:8]" -a "ip.dst_raw[0:6]" -o anonymized.pcap 603 | 604 | Masking and anonymization limitations are mainly the following: 605 | - In case the tshark is performing reassembling from multiple frames, the 606 | backward pcap reconstruction is not properly performed and can result in 607 | malformed frames. 608 | - The new values in the fields could violate the field format, as the 609 | json2pcap is no performing correct protocol encoding with respect to 610 | allowed values of the target field and field encoding. 611 | 612 | """.format(version=VERSION), formatter_class=argparse.RawTextHelpFormatter) 613 | parser.add_argument('--version', action='version', version='%(prog)s ' + VERSION) 614 | parser.add_argument('-i', '--infile', nargs='?', help='json generated by tshark -T json -x\nor by tshark -T jsonraw (not preserving frame timestamps).\nIf no inpout file is specified script reads from stdin.') 615 | parser.add_argument('-o', '--outfile', required=True, help='output pcap filename') 616 | parser.add_argument('-p', '--python', help='generate python payload instead of pcap (only 1st packet)', default=False, action='store_true') 617 | parser.add_argument('-m', '--mask', help='mask the specific raw field (e.g. -m "ip.src_raw" -m "ip.dst_raw[2:6]")', action='append', metavar='MASKED_FIELD') 618 | parser.add_argument('-a', '--anonymize', help='anonymize the specific raw field (e.g. -a "ip.src_raw[2:]" -a "ip.dst_raw[:-2]")', action='append', metavar='ANONYMIZED_FIELD') 619 | parser.add_argument('-s', '--salt', help='salt use for anonymization. If no value is provided it is randomized.', default=None) 620 | parser.add_argument('-v', '--verbose', help='verbose output', default=False, action='store_true') 621 | args = parser.parse_args() 622 | 623 | # read JSON 624 | infile = args.infile 625 | outfile = args.outfile 626 | 627 | # Read from input file 628 | if infile: 629 | data_file = open(infile) 630 | # Read from pipe 631 | else: 632 | data_file = sys.stdin 633 | 634 | # Parse anonymization fields 635 | anonymize = {} 636 | if args.mask: 637 | for m in args.mask: 638 | if not '_raw' in m: 639 | print("Error: The specified fields by -m switch should be raw fields. " + m + " does not have _raw suffix") 640 | sys.exit() 641 | af = AnonymizedField(m, 0) 642 | anonymize[af.field] = af 643 | if args.anonymize: 644 | for a in args.anonymize: 645 | if not '_raw' in a: 646 | print("Error: The specified fields by -a switch should be raw fields. " + a + " does not have _raw suffix") 647 | sys.exit() 648 | af = AnonymizedField(a, 1) 649 | anonymize[af.field] = af 650 | 651 | input_frame_raw = '' 652 | frame_raw = '' 653 | frame_time = None 654 | 655 | salt = args.salt 656 | if salt is None: 657 | # generate random salt if no salt was provided 658 | salt = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(10)) 659 | 660 | # Generate pcap 661 | if args.python == False: 662 | pcap_out = scapy.PcapWriter(outfile, append=False, sync=False) 663 | 664 | # Iterate over packets in JSON 665 | for packet in ijson.items(data_file, "item", buf_size=200000): 666 | _list = [] 667 | linux_cooked_header = False; 668 | 669 | # get flat raw fields into _list 670 | for raw in raw_flat_collector(packet['_source']['layers']): 671 | if len(raw) >= 2: 672 | if (raw[0] == "frame_raw"): 673 | frame_raw = raw[1][0] 674 | frame_mmask = "0"*len(frame_raw) # initialize anonymization mask 675 | input_frame_raw = copy.copy(frame_raw) 676 | frame_time = None 677 | if 'frame.time_epoch' in packet['_source']['layers']['frame']: 678 | frame_time = packet['_source']['layers']['frame']['frame.time_epoch'] 679 | else: 680 | # add into value list into raw[5] the field name 681 | if isinstance(raw[1], list): 682 | raw[1].append(raw[0]) 683 | _list.append(raw[1]) 684 | if (raw[0] == "sll_raw"): 685 | linux_cooked_header = True 686 | 687 | # sort _list 688 | sorted_list = sorted(_list, key=operator.itemgetter(1), reverse=False) 689 | sorted_list = sorted(sorted_list, key=operator.itemgetter(2), reverse=True) 690 | # print("Debug: " + str(sorted_list)) 691 | 692 | # rewrite frame 693 | for raw in sorted_list: 694 | if len(raw) >= 6: 695 | h = str(raw[0]) # hex 696 | p = raw[1] * 2 # position 697 | l = raw[2] * 2 # length 698 | b = raw[3] # bitmask 699 | t = raw[4] # type 700 | # raw[5] # field_name (added by script) 701 | h_mask = 'f' * len(h) # hex for modification mask 702 | 703 | # anonymize fields 704 | if (raw[5] in anonymize): 705 | [h, h_mask] = anonymize[raw[5]].anonymize_field(h, t, salt) 706 | 707 | if (isinstance(p, (list, tuple)) or isinstance(l, (list, tuple))): 708 | for r in raw: 709 | _h = str(r[0]) # hex 710 | _p = r[1] * 2 # position 711 | _l = r[2] * 2 # length 712 | _b = r[3] # bitmask 713 | _t = r[4] # type 714 | # raw[5] # field_name (added by script) 715 | _h_mask = 'f' * len(_h) # hex for modification mask 716 | 717 | # anonymize fields 718 | if (raw[5] in anonymize): 719 | [_h, _h_mask] = anonymize[raw[5]].anonymize_field(_h, _t, salt) 720 | 721 | # print("Debug: " + str(raw)) 722 | s1 = frame_raw 723 | frame_raw = rewrite_frame(frame_raw, _h, _p, _l, _b, _t, frame_mmask) 724 | s2 = frame_raw 725 | 726 | # update modification mask 727 | if (raw[5] in anonymize) or (s1 != s2): 728 | frame_mmask = rewrite_frame(frame_mmask, _h_mask, _p, _l, _b, _t) 729 | 730 | else: 731 | #print("Debug: " + str(raw)) 732 | #print("Debug: " + str(frame_raw)) 733 | s1 = frame_raw 734 | a1 = frame_mmask 735 | frame_raw = rewrite_frame(frame_raw, h, p, l, b, t, frame_mmask) 736 | s2 = frame_raw 737 | a2 = frame_mmask 738 | 739 | #if (s1 != s2): 740 | # print("Modified fields: ") 741 | # print("Field: " + str(raw)) 742 | # print("In : " + str(s1)) 743 | # print("In amask: " + str(a1)) 744 | # print("Out: " + str(s2)) 745 | # print("Out amask: " + str(a2)) 746 | # d = [i for i in range(len(s1)) if s1[i] != s2[i]] 747 | # print(d) 748 | #print("Debug: " + str(frame_raw)) 749 | 750 | # update modification mask 751 | if (raw[5] in anonymize) or (s1 != s2): 752 | frame_mmask = rewrite_frame(frame_mmask, h_mask, p, l, b, t) 753 | 754 | # for Linux cooked header replace dest MAC and remove two bytes to reconstruct normal frame 755 | if (linux_cooked_header): 756 | frame_raw = "000000000000" + frame_raw[6 * 2:] # replce dest MAC 757 | frame_raw = frame_raw[:12 * 2] + "" + frame_raw[14 * 2:] # remove two bytes before Protocol 758 | 759 | # Testing: remove comment to compare input and output for not modified json 760 | if (args.verbose and input_frame_raw != frame_raw): 761 | #print("Modified frames: ") 762 | s1 = input_frame_raw 763 | s2 = frame_raw 764 | #print(s1) 765 | #print(s2) 766 | if (len(s1) == len(s2)): 767 | d = [i for i in range(len(s1)) if s1[i] != s2[i]] 768 | #print(d) 769 | 770 | new_packet = scapy.Packet(bytes(bytearray.fromhex(frame_raw))) 771 | if frame_time: 772 | new_packet.time = float(frame_time) 773 | #print(type(new_packet)) 774 | pcap_out.write(new_packet) 775 | 776 | # Generate python payload only for first packet 777 | else: 778 | py_outfile = outfile + '.py' 779 | f = open(py_outfile, 'w') 780 | 781 | #for packet in json: 782 | for packet in ijson.items(data_file, "item", buf_size=200000): 783 | f.write(py_header) 784 | 785 | r = OrderedDict({}) 786 | 787 | #print "packet = " + str(packet['_source']['layers']) 788 | py_generator(packet['_source']['layers'], r) 789 | 790 | for key, value in r.items() : 791 | f.write(" d['" + key + "'] =",) 792 | f.write(" " + str(value) + "\n") 793 | 794 | f.write(py_footer) 795 | 796 | # Currently only first packet is used from pcap 797 | f.close 798 | 799 | print("Generated " + py_outfile) 800 | 801 | break 802 | --------------------------------------------------------------------------------