├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── arp.py ├── main.py ├── ping.py ├── raw_python ├── __init__.py ├── development_info.readme ├── lib │ ├── Ether.py │ ├── ICMP.py │ ├── IP.py │ ├── Tcp.py │ ├── Udp.py │ ├── __init__.py │ └── util.py ├── samples │ ├── PcapHandler.py │ ├── __init__.py │ ├── utils.py │ └── wsk.py └── tests │ └── __main__.py ├── requirements.txt └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | .idea/* 3 | 4 | # macOS 5 | .DS_Store 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.6" 4 | - "3.7-dev" 5 | install: 6 | - pip install . 7 | script: 8 | - python -m raw_python.tests 9 | 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | 180 | 181 | Copyright 2018 Suraj Singh Bisht 182 | 183 | 184 | 185 | 186 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/lightsing/raw_python.svg?branch=master)](https://travis-ci.org/lightsing/raw_python) 2 | 3 | # Raw Python (aka. pye) 4 | 5 | Util for Python to work with raw socket and network protocols (Ethernet/TCP/IP/UDP/ICMP etc.). 6 | 7 | ## STILL UNDER DEVELOPING 8 | 9 | This project is migrate from pye (python2) to current project. 10 | 11 | Fork and send pr to this project! 12 | 13 | ### Disclaimer 14 | 15 | This project is for Computer Network Course, Dept. CSE, SUSTech. 16 | 17 | Education purpose Mainly. 18 | 19 | ## Getting Started 20 | 21 | ```bash 22 | pip install git+https://github.com/lightsing/raw_python 23 | ``` 24 | 25 | Well, If you also want to play with low level networking problems and want to learn about networking protocol. Fork it! 26 | 27 | ## Newbie? 28 | 29 | ohh, you are a new kid! that's Nice. Then, This project definately can help you in understanding Networking Protocols, Etc Etc. 30 | 31 | #### For Help/Reference You can check below sites 32 | 33 | * [Bitforestinfo](http://www.bitforestinfo.com) - Bitforestinfo Blog. 34 | 35 | * [Google](https://www.google.com) - Google Search Engine 36 | 37 | 38 | 39 | ### Prerequisites 40 | 41 | What things you need to install the software. 42 | 43 | - This Project is Not Tested On Windows Platform (Use Linux). 44 | - Wireshark 45 | 46 | ## Want to Contribute? Great! 47 | 48 | ### Pull Request 49 | 50 | 1. Fork it! 51 | 52 | 2. Create your feature branch: `git checkout -b my-new-feature` 53 | 54 | 3. Commit your changes: `git commit -am 'Add some feature'` 55 | 56 | 4. Push to the branch: `git push origin my-new-feature` 57 | 58 | 5. Submit a pull request :D 59 | 60 | ## Built With 61 | 62 | * [Python](https://www.python.org/doc/) - Python Programming language 63 | 64 | ## Authors 65 | 66 | * **SurajSingh** - *Initial work* - [SurajSingh](https://github.com/surajsinghbisht054) 67 | * **HHQ. ZHANG** - *Current Matainer* - [Lightsing](https://github.com/lightsing) 68 | 69 | ## License 70 | 71 | This project is licensed under the APACHE 2.0 License - see the [LICENSE.md](LICENSE.md) file for details 72 | 73 | ## Acknowledgments 74 | 75 | * Hat tip to anyone who's code was used 76 | * Inspiration 77 | * etc 78 | -------------------------------------------------------------------------------- /arp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # 5 | # Copyright 2018 Dept. CSE SUSTech 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | # -------------------------------------------------------------------------- 21 | # Don't Remove Authors Info | 22 | # -------------------------------------------------------------------------- 23 | 24 | 25 | __author__ = 'Suraj Singh Bisht, HHQ. ZHANG' 26 | __credit__ = '["Suraj Singh Bisht",]' 27 | __contact__ = 'contact@jinlab.cn' 28 | __copyright__ = 'Copyright 2018 Dept. CSE SUSTech' 29 | __license__ = 'Apache 2.0' 30 | __Update__ = '2018-01-11 12:33:09.399381' 31 | __version__ = '0.1' 32 | __maintainer__ = 'HHQ. ZHANG' 33 | __status__ = 'Production' 34 | 35 | import socket 36 | from binascii import unhexlify 37 | from struct import pack 38 | 39 | from raw_python.lib.Ether import EtherPacket 40 | from raw_python.samples.utils import get_ip, get_mac 41 | 42 | ARP_FORMAT = "!HHBBH6s4s6s4s" 43 | 44 | 45 | class ARPPacket: 46 | def __init__(self, src_ip, dst_ip, src_mac): 47 | packet = '' 48 | packet += pack(ARP_FORMAT[0] + ARP_FORMAT[1], 0x0001) 49 | packet += pack(ARP_FORMAT[0] + ARP_FORMAT[2], 0x0800) 50 | packet += pack(ARP_FORMAT[0] + ARP_FORMAT[3], 0x06) 51 | packet += pack(ARP_FORMAT[0] + ARP_FORMAT[4], 0x04) 52 | packet += pack(ARP_FORMAT[0] + ARP_FORMAT[5], 0x0001) 53 | packet += pack(ARP_FORMAT[0] + ARP_FORMAT[6:8], unhexlify(src_mac)) 54 | packet += pack(ARP_FORMAT[0] + ARP_FORMAT[8:10], socket.inet_aton(src_ip)) 55 | packet += pack(ARP_FORMAT[0] + ARP_FORMAT[10:12], unhexlify("000000000000")) 56 | packet += pack(ARP_FORMAT[0] + ARP_FORMAT[12:14], socket.inet_aton(dst_ip)) 57 | self.raw = packet 58 | 59 | 60 | def arp_request(ip, addr, mac): 61 | eth = EtherPacket(src=mac, protocol=0x0806).raw 62 | arp = ARPPacket(ip, addr, mac) 63 | pkt = eth + arp.raw 64 | return pkt 65 | 66 | 67 | def main(iface): 68 | s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW) 69 | s.bind((iface, 0)) 70 | 71 | mac = get_mac(iface) 72 | ip = get_ip() 73 | addr = '127.0.0.1' # socket.gethostbyname('www.google.com') 74 | ip = '127.0.0.1' 75 | packet = arp_request(ip, addr, mac) 76 | 77 | # ShowPacket([arp_request(ip, addr, mac)]) 78 | # print(ARP_FRAME) 79 | s.send(packet) 80 | # print repr(s.recv(1024)) 81 | s.close() 82 | return 83 | 84 | 85 | if __name__ == '__main__': 86 | main("lo") 87 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # 5 | # Copyright 2018 Dept. CSE SUSTech 6 | # Copyright 2018 Suraj Singh Bisht 7 | # 8 | # Licensed under the Apache License, Version 2.0 (the "License"); 9 | # you may not use this file except in compliance with the License. 10 | # You may obtain a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, software 15 | # distributed under the License is distributed on an "AS IS" BASIS, 16 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | # See the License for the specific language governing permissions and 18 | # limitations under the License. 19 | # 20 | # 21 | # -------------------------------------------------------------------------- 22 | # Don't Remove Authors Info | 23 | # -------------------------------------------------------------------------- 24 | 25 | 26 | __author__ = 'Suraj Singh Bisht, HHQ. ZHANG' 27 | __credit__ = '["Suraj Singh Bisht",]' 28 | __contact__ = 'contact@jinlab.cn' 29 | __copyright__ = 'Copyright 2018 Dept. CSE SUSTech' 30 | __license__ = 'Apache 2.0' 31 | __Update__ = '2018-01-11 12:33:09.399381' 32 | __version__ = '0.1' 33 | __maintainer__ = 'HHQ. ZHANG' 34 | __status__ = 'Production' 35 | -------------------------------------------------------------------------------- /ping.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # 5 | # Copyright 2018 Dept. CSE SUSTech 6 | # Copyright 2018 Suraj Singh Bisht 7 | # 8 | # Licensed under the Apache License, Version 2.0 (the "License"); 9 | # you may not use this file except in compliance with the License. 10 | # You may obtain a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, software 15 | # distributed under the License is distributed on an "AS IS" BASIS, 16 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | # See the License for the specific language governing permissions and 18 | # limitations under the License. 19 | # 20 | # 21 | # -------------------------------------------------------------------------- 22 | # Don't Remove Authors Info | 23 | # -------------------------------------------------------------------------- 24 | 25 | 26 | __author__ = 'Suraj Singh Bisht, HHQ. ZHANG' 27 | __credit__ = '["Suraj Singh Bisht",]' 28 | __contact__ = 'contact@jinlab.cn' 29 | __copyright__ = 'Copyright 2018 Dept. CSE SUSTech' 30 | __license__ = 'Apache 2.0' 31 | __Update__ = '2018-01-11 12:33:09.399381' 32 | __version__ = '0.1' 33 | __maintainer__ = 'HHQ. ZHANG' 34 | __status__ = 'Production' 35 | 36 | import random 37 | import select 38 | # import module 39 | import socket 40 | import time 41 | 42 | from raw_python import ICMPPacket, parse_icmp_header, parse_eth_header, parse_ip_header 43 | 44 | 45 | def calc_rtt(time_sent): 46 | return time.time() - time_sent 47 | 48 | 49 | def catch_ping_reply(s, ID, time_sent, timeout=1): 50 | # create while loop 51 | while True: 52 | starting_time = time.time() # Record Starting Time 53 | 54 | # to handle timeout function of socket 55 | process = select.select([s], [], [], timeout) 56 | 57 | # check if timeout 58 | if not process[0]: 59 | return calc_rtt(time_sent), None, None 60 | 61 | # receive packet 62 | rec_packet, addr = s.recvfrom(1024) 63 | 64 | # extract icmp packet from received packet 65 | icmp = parse_icmp_header(rec_packet[20:28]) 66 | 67 | # check identification 68 | if icmp['id'] == ID: 69 | return calc_rtt(time_sent), parse_ip_header(rec_packet[:20]), icmp 70 | 71 | 72 | def single_ping_request(s, addr=None): 73 | # Random Packet Id 74 | pkt_id = random.randrange(10000, 65000) 75 | 76 | # Create ICMP Packet 77 | packet = ICMPPacket(_id=pkt_id).raw 78 | 79 | # Send ICMP Packet 80 | while packet: 81 | sent = s.sendto(packet, (addr, 1)) 82 | packet = packet[sent:] 83 | 84 | return pkt_id 85 | 86 | 87 | def main(): 88 | # create socket 89 | s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) 90 | 91 | # take Input 92 | addr = input("[+] Enter Domain Name : ") or "www.sustc.edu.cn" 93 | print('PING {0} ({1}) 56(84) bytes of data.'.format(addr, socket.gethostbyname(addr))) 94 | # Request sent 95 | ID = single_ping_request(s, addr) 96 | 97 | # Catch Reply 98 | rtt, reply, icmp_reply = catch_ping_reply(s, ID, time.time()) 99 | 100 | if reply: 101 | reply['length'] = reply['Total Length'] - 20 # sub header 102 | print('{0[length]} bytes reply from {0[Source Address]} ({0[Source Address]}): ' 103 | 'icmp_seq={1[seq]} ttl={0[TTL]} time={2:.2f} ms' 104 | .format(reply, icmp_reply, rtt*1000)) 105 | 106 | # close socket 107 | s.close() 108 | return 109 | 110 | 111 | if __name__ == '__main__': 112 | main() 113 | -------------------------------------------------------------------------------- /raw_python/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # 5 | # Copyright 2018 Dept. CSE SUSTech 6 | # Copyright 2018 Suraj Singh Bisht 7 | # 8 | # Licensed under the Apache License, Version 2.0 (the "License"); 9 | # you may not use this file except in compliance with the License. 10 | # You may obtain a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, software 15 | # distributed under the License is distributed on an "AS IS" BASIS, 16 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | # See the License for the specific language governing permissions and 18 | # limitations under the License. 19 | # 20 | # 21 | # -------------------------------------------------------------------------- 22 | # Don't Remove Authors Info | 23 | # -------------------------------------------------------------------------- 24 | 25 | 26 | __author__ = 'Suraj Singh Bisht, HHQ. ZHANG' 27 | __credit__ = '["Suraj Singh Bisht",]' 28 | __contact__ = 'contact@jinlab.cn' 29 | __copyright__ = 'Copyright 2018 Dept. CSE SUSTech' 30 | __license__ = 'Apache 2.0' 31 | __Update__ = '2018-01-11 12:33:09.399381' 32 | __version__ = '0.1' 33 | __maintainer__ = 'HHQ. ZHANG' 34 | __status__ = 'Production' 35 | 36 | from .lib import * 37 | -------------------------------------------------------------------------------- /raw_python/development_info.readme: -------------------------------------------------------------------------------- 1 | 2 | # Under-Development Scripts 3 | 4 | 1. Ether (Assembly and Deassembly Of Ethernet Layer) 5 | 2. IP (Assembly and Deassembly of Internet Protocol layer) 6 | 3. TCP (Assembly and Deassembly of Transmission Control Protocol) 7 | -------------------------------------------------------------------------------- /raw_python/lib/Ether.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # 5 | # Copyright 2018 Dept. CSE SUSTech 6 | # Copyright 2018 Suraj Singh Bisht 7 | # 8 | # Licensed under the Apache License, Version 2.0 (the "License"); 9 | # you may not use this file except in compliance with the License. 10 | # You may obtain a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, software 15 | # distributed under the License is distributed on an "AS IS" BASIS, 16 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | # See the License for the specific language governing permissions and 18 | # limitations under the License. 19 | # 20 | # 21 | # -------------------------------------------------------------------------- 22 | # Don't Remove Authors Info | 23 | # -------------------------------------------------------------------------- 24 | 25 | 26 | __author__ = 'Suraj Singh Bisht, HHQ. ZHANG' 27 | __credit__ = '["Suraj Singh Bisht",]' 28 | __contact__ = 'contact@jinlab.cn' 29 | __copyright__ = 'Copyright 2018 Dept. CSE SUSTech' 30 | __license__ = 'Apache 2.0' 31 | __Update__ = '2018-01-11 12:33:09.399381' 32 | __version__ = '0.1' 33 | __maintainer__ = 'HHQ. ZHANG' 34 | __status__ = 'Production' 35 | 36 | import binascii # binary ASCII module 37 | import struct # struct module 38 | 39 | from ..samples import utils 40 | 41 | # Ethernet II (DIX) Protocol Types 42 | 43 | ETH_P_LOOP = 0x0060 # hernet Loopback packet 44 | ETH_P_PUP = 0x0200 # rox PUP packet 45 | ETH_P_PUPAT = 0x0201 # rox PUP Addr Trans packet 46 | ETH_P_IP = 0x0800 # ternet Protocol packet 47 | ETH_P_X25 = 0x0805 # ITT X.25 48 | ETH_P_ARP = 0x0806 # dress Resolution packet 49 | ETH_P_IEEEPUP = 0x0a00 # rox IEEE802.3 PUP packet 50 | ETH_P_IEEEPUPAT = 0x0a01 # rox IEEE802.3 PUP Addr Trans packet 51 | ETH_P_DEC = 0x6000 # C Assigned proto 52 | ETH_P_DNA_DL = 0x6001 # C DNA Dump/Load 53 | ETH_P_DNA_RC = 0x6002 # C DNA Remote Console 54 | ETH_P_DNA_RT = 0x6003 # C DNA Routing 55 | ETH_P_LAT = 0x6004 # C LAT 56 | ETH_P_DIAG = 0x6005 # C Diagnostics 57 | ETH_P_CUST = 0x6006 # C Customer use 58 | ETH_P_SCA = 0x6007 # C Systems Comms Arch 59 | ETH_P_TEB = 0x6558 # ans Ether Bridging 60 | ETH_P_RARP = 0x8035 # verse Addr Res packet 61 | ETH_P_ATALK = 0x809B # pletalk DDP 62 | ETH_P_AARP = 0x80F3 # pletalk AARP 63 | ETH_P_8021Q = 0x8100 # 2.1Q VLAN Extended Header 64 | ETH_P_IPX = 0x8137 # X over DIX 65 | ETH_P_IPV6 = 0x86DD # v6 over bluebook 66 | ETH_P_PAUSE = 0x8808 # EE Pause frames. See 802.3 31B 67 | ETH_P_SLOW = 0x8809 # ow Protocol. See 802.3ad 43B 68 | ETH_P_WCCP = 0x883E # b-cache coordination protocol 69 | 70 | 71 | # Simple Ethernet Frame Class 72 | class EtherPacket: 73 | def __init__(self, dst='ff:ff:ff:ff:ff:ff', src='', protocol=ETH_P_IP, data=''): 74 | self.dst = dst # Destination MAC 75 | if not src: 76 | interface = utils.all_interfaces()[::-1][0][0] 77 | src = utils.get_mac(interface=interface) 78 | self.src = src # Source MAC 79 | self.protocol = protocol # Protocol Types 80 | self.raw = None # Raw Data 81 | self.data = data 82 | self.assemble_eth_feilds() 83 | 84 | def assemble_eth_feilds(self): 85 | # Assemble All Feilds Of Ether Packet 86 | 87 | self.raw = struct.pack( 88 | "!6s6sH", 89 | binascii.unhexlify(self.dst.replace(":", "")), 90 | binascii.unhexlify(self.src.replace(":", "")), 91 | self.protocol) 92 | return self.raw # ''.join([self.raw, self.data]) 93 | 94 | 95 | # Ethernet Header 96 | def parse_eth_header(data): 97 | storeobj = data 98 | storeobj = struct.unpack("!6s6sH", storeobj) 99 | destination_mac = binascii.hexlify(storeobj[0]) 100 | source_mac = binascii.hexlify(storeobj[1]) 101 | eth_protocol = storeobj[2] 102 | data = {"Destination Mac": destination_mac, 103 | "Source Mac": source_mac, 104 | "Protocol": eth_protocol} 105 | return data 106 | -------------------------------------------------------------------------------- /raw_python/lib/ICMP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # 5 | # Copyright 2018 Dept. CSE SUSTech 6 | # Copyright 2018 Suraj Singh Bisht 7 | # 8 | # Licensed under the Apache License, Version 2.0 (the "License"); 9 | # you may not use this file except in compliance with the License. 10 | # You may obtain a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, software 15 | # distributed under the License is distributed on an "AS IS" BASIS, 16 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | # See the License for the specific language governing permissions and 18 | # limitations under the License. 19 | # 20 | # 21 | # -------------------------------------------------------------------------- 22 | # Don't Remove Authors Info | 23 | # -------------------------------------------------------------------------- 24 | 25 | 26 | __author__ = 'Suraj Singh Bisht, HHQ. ZHANG' 27 | __credit__ = '["Suraj Singh Bisht",]' 28 | __contact__ = 'contact@jinlab.cn' 29 | __copyright__ = 'Copyright 2018 Dept. CSE SUSTech' 30 | __license__ = 'Apache 2.0' 31 | __Update__ = '2018-01-11 12:33:09.399381' 32 | __version__ = '0.1' 33 | __maintainer__ = 'HHQ. ZHANG' 34 | __status__ = 'Production' 35 | 36 | import socket 37 | import struct 38 | 39 | from .util import Packet 40 | 41 | # Header is type (8), code (8), checksum (16), id (16), sequence (16) 42 | # header = struct.pack('bbHHh', ICMP_ECHO_REQUEST, 0, 0, id, 1) 43 | ICMP_STRUCTURE_FMT = 'bbHHh' 44 | ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris. 45 | 46 | ICMP_CODE = socket.getprotobyname('icmp') 47 | ERROR_DESCR = { 48 | 1: ' - Note that ICMP messages can only be ' 49 | 'sent from processes running as root.', 50 | 10013: ' - Note that ICMP messages can only be sent by' 51 | ' users or processes with administrator rights.' 52 | } 53 | 54 | 55 | class ICMPPacket(Packet): 56 | def __init__(self, _type=ICMP_ECHO_REQUEST, code=0, checksum=0, _id=1, _seq=1, data=b''): 57 | self.type = _type 58 | self.code = code 59 | self.checksum = checksum 60 | self.id = _id 61 | self.seq = _seq 62 | self.data = data 63 | self.raw = None 64 | self.create_icmp_field() 65 | 66 | def create_icmp_field(self): 67 | _raw = struct.pack(ICMP_STRUCTURE_FMT, self.type, self.code, self.checksum, self.id, self.seq) 68 | # calculate checksum 69 | self.checksum = self.calc_checksum(_raw + self.data) 70 | self.raw = struct.pack(ICMP_STRUCTURE_FMT, self.type, self.code, self.checksum, self.id, self.seq) 71 | 72 | 73 | # ICMP HEADER Extraction 74 | def parse_icmp_header(data): 75 | icmph = struct.unpack(ICMP_STRUCTURE_FMT, data) 76 | data = { 77 | 'type': icmph[0], 78 | "code": icmph[1], 79 | "checksum": icmph[2], 80 | 'id': icmph[3], 81 | 'seq': icmph[4], 82 | } 83 | return data 84 | -------------------------------------------------------------------------------- /raw_python/lib/IP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # 5 | # Copyright 2018 Dept. CSE SUSTech 6 | # Copyright 2018 Suraj Singh Bisht 7 | # 8 | # Licensed under the Apache License, Version 2.0 (the "License"); 9 | # you may not use this file except in compliance with the License. 10 | # You may obtain a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, software 15 | # distributed under the License is distributed on an "AS IS" BASIS, 16 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | # See the License for the specific language governing permissions and 18 | # limitations under the License. 19 | # 20 | # 21 | # -------------------------------------------------------------------------- 22 | # Don't Remove Authors Info | 23 | # -------------------------------------------------------------------------- 24 | 25 | 26 | __author__ = 'Suraj Singh Bisht, HHQ. ZHANG' 27 | __credit__ = '["Suraj Singh Bisht",]' 28 | __contact__ = 'contact@jinlab.cn' 29 | __copyright__ = 'Copyright 2018 Dept. CSE SUSTech' 30 | __license__ = 'Apache 2.0' 31 | __Update__ = '2018-01-11 12:33:09.399381' 32 | __version__ = '0.1' 33 | __maintainer__ = 'HHQ. ZHANG' 34 | __status__ = 'Production' 35 | 36 | # import module 37 | import socket 38 | import struct 39 | 40 | from .util import Packet 41 | from ..samples.utils import get_ip 42 | 43 | # Link type [required for wireshark pcap file] 44 | LINKTYPE0 = 101 45 | LINKTYPE1 = 228 46 | 47 | 48 | class IPPacket(Packet): 49 | def __init__(self, dst='127.0.0.1', src=get_ip(), ver=4, vhl=5, dsc=0, ecn=0, tol=20, idf=1, flag_rsv=0, flag_dtf=0, 50 | flag_mrf=0, frag_offset=0, ttl=64, proto=socket.IPPROTO_TCP, checksum=0): 51 | # load data into self container 52 | self.dst = dst 53 | self.src = src 54 | self.raw = None 55 | 56 | # ---- [Internet Protocol Version] ---- 57 | self.ver = (ver << 4) + vhl 58 | # ---- [ Differentiate Service Field ] 59 | self.dfc = (dsc << 2) + ecn 60 | # ---- [ Total Length] 61 | self.tol = tol 62 | # ---- [ Identification ] 63 | self.idf = idf 64 | # ---- [ Flags ] 65 | self.flags = flag_rsv + flag_dtf + flag_mrf + frag_offset 66 | # ---- [ Time to live ] 67 | self.ttl = ttl 68 | # ---- [ Protocol ] 69 | self.protocol = proto 70 | # ---- [ Check Sum ] 71 | self.checksum = checksum 72 | # ---- [ Source Address ] 73 | self.source_address = socket.inet_aton(self.src) 74 | # ---- [ Destination Address ] 75 | self.destination_address = socket.inet_aton(self.dst) 76 | 77 | self.assemble_ipv4_fields() # assemble all values 78 | self.checksum = self.calc_checksum(self.raw) # Calculate Checksum 79 | self.assemble_ipv4_fields() # assemble ipv4 fields 80 | 81 | def assemble_ipv4_fields(self): 82 | # Size = 1+1+2+2+2+1+1+2+4+4 83 | 84 | self.raw = struct.pack('!BBHHhBB', 85 | self.ver, # IP Version 86 | self.dfc, # Differentiate Service Field 87 | self.tol, # Total Length 88 | self.idf, # Identification 89 | self.flags, # Flags 90 | self.ttl, # Time to leave 91 | self.protocol, # protocol 92 | ) 93 | 94 | self.raw = self.raw + struct.pack('H', 95 | self.checksum # checksum 96 | ) 97 | 98 | self.raw = self.raw + struct.pack('!4s4s', 99 | self.source_address, # Source IP 100 | self.destination_address, # Destination IP 101 | # self.padding 102 | ) 103 | return self.raw 104 | 105 | 106 | # IP Header Extraction 107 | def parse_ip_header(data): 108 | unpacked = struct.unpack("!BBHHHBBH4s4s", data) 109 | _version = unpacked[0] >> 4 110 | _ihl = unpacked[0] & 0xf 111 | _tos = unpacked[1] 112 | _total_length = unpacked[2] 113 | _identification = unpacked[3] 114 | _fragment_Offset = unpacked[4] 115 | _ttl = unpacked[5] 116 | _protocol = unpacked[6] 117 | _header_checksum = unpacked[7] 118 | _source_address = socket.inet_ntoa(unpacked[8]) 119 | _destination_address = socket.inet_ntoa(unpacked[9]) 120 | 121 | data = {'Version': _version, 122 | 'IHL': _ihl, 123 | "Tos": _tos, 124 | "Total Length": _total_length, 125 | "Identification": _identification, 126 | "Fragment": _fragment_Offset, 127 | "TTL": _ttl, 128 | "Protocol": _protocol, 129 | "Header CheckSum": _header_checksum, 130 | "Source Address": _source_address, 131 | "Destination Address": _destination_address} 132 | return data 133 | 134 | 135 | def load_ip(tcp=None, **kwargs): 136 | ip = IPPacket() 137 | length = len(tcp.raw) + len(ip.raw) 138 | kwargs['ip_tol'] = length 139 | return IPPacket() 140 | -------------------------------------------------------------------------------- /raw_python/lib/Tcp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # 5 | # Copyright 2018 Dept. CSE SUSTech 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | # -------------------------------------------------------------------------- 21 | # Don't Remove Authors Info | 22 | # -------------------------------------------------------------------------- 23 | 24 | 25 | __author__ = 'Suraj Singh Bisht, HHQ. ZHANG' 26 | __credit__ = '["Suraj Singh Bisht",]' 27 | __contact__ = 'contact@jinlab.cn' 28 | __copyright__ = 'Copyright 2018 Dept. CSE SUSTech' 29 | __license__ = 'Apache 2.0' 30 | __Update__ = '2018-01-11 12:33:09.399381' 31 | __version__ = '0.1' 32 | __maintainer__ = 'HHQ. ZHANG' 33 | __status__ = 'Production' 34 | 35 | import socket 36 | import struct 37 | 38 | from ..samples import utils 39 | 40 | TCP_STRUCTURE_FMT = '!HHLLBBHHH' 41 | 42 | 43 | class TCPPacket: 44 | def __init__(self, 45 | dport=80, 46 | sport=65535, 47 | dst='127.0.0.1', 48 | src=utils.get_ip(), # '192.168.1.101', 49 | data='', 50 | seq=0, 51 | ack_seq=0, 52 | flags=(0, 0, 0, 0, 0, 0, 0, 0, 1, 0), # (rsv, noc, cwr, ecn, urg, ack, psh, rst, syn, fin) 53 | ): 54 | self.dport = dport 55 | self.sport = sport 56 | self.src_ip = src 57 | self.dst_ip = dst 58 | self.ack = ack_seq 59 | self.seq = seq 60 | self.flags = flags 61 | self.data = data 62 | self.raw = None 63 | self.create_tcp_feilds() 64 | self.assemble_tcp_feilds() 65 | # self.calculate_chksum() 66 | # self.reassemble_tcp_feilds() 67 | 68 | def assemble_tcp_feilds(self): 69 | self.raw = struct.pack('!HHLLBBHHH', # Data Structure Representation 70 | self.sport, # Source Port 71 | self.dport, # Destination Port 72 | self.tcp_seq, # Sequence 73 | self.tcp_ack_seq, # Acknownlegment Sequence 74 | self.tcp_hdr_len, # Header Length 75 | self.tcp_flags, # TCP Flags 76 | self.tcp_wdw, # TCP Windows 77 | self.tcp_chksum, # TCP cheksum 78 | self.tcp_urg_ptr # TCP Urgent Pointer 79 | ) 80 | 81 | self.calculate_chksum() # Call Calculate CheckSum 82 | return 83 | 84 | def reassemble_tcp_feilds(self): 85 | self.raw = struct.pack(TCP_STRUCTURE_FMT, 86 | self.tcp_src, 87 | self.tcp_dst, 88 | self.tcp_seq, 89 | self.tcp_ack_seq, 90 | self.tcp_hdr_len, 91 | self.tcp_flags, 92 | self.tcp_wdw, 93 | socket.htons(self.tcp_chksum), 94 | self.tcp_urg_ptr 95 | ) 96 | return 97 | 98 | def calculate_chksum(self): 99 | src_addr = socket.inet_aton(self.src_ip) 100 | dest_addr = socket.inet_aton(self.dst_ip) 101 | placeholder = 0 102 | protocol = socket.IPPROTO_TCP 103 | tcp_len = len(self.raw) + len(self.data) 104 | 105 | psh = struct.pack('!4s4sBBH', 106 | src_addr, 107 | dest_addr, 108 | placeholder, 109 | protocol, 110 | tcp_len 111 | ) 112 | 113 | psh = ''.join([psh, self.raw, self.data]) 114 | 115 | self.tcp_chksum = self.chksum(psh) 116 | 117 | self.reassemble_tcp_feilds() 118 | 119 | return 120 | 121 | def chksum(self, msg): 122 | s = 0 # Binary Sum 123 | 124 | # loop taking 2 characters at a time 125 | for i in range(0, len(msg), 2): 126 | if (i + 1) < len(msg): 127 | a = ord(msg[i]) 128 | b = ord(msg[i + 1]) 129 | s = s + (a + (b << 8)) 130 | elif (i + 1) == len(msg): 131 | s += ord(msg[i]) 132 | else: 133 | raise Exception("Something Wrong here") 134 | 135 | s = (s >> 16) + (s & 0xffff) 136 | # One's Complement 137 | s = s + (s >> 16) 138 | s = ~s & 0xffff 139 | 140 | return s 141 | 142 | def create_tcp_feilds(self): 143 | 144 | # ---- [ Source Port ] 145 | self.tcp_src = self.sport 146 | 147 | # ---- [ Destination Port ] 148 | self.tcp_dst = self.dport 149 | 150 | # ---- [ TCP Sequence Number] 151 | self.tcp_seq = self.seq 152 | 153 | # ---- [ TCP Acknowledgement Number] 154 | self.tcp_ack_seq = self.ack 155 | 156 | # ---- [ Header Length ] 157 | self.tcp_hdr_len = 80 158 | 159 | # ---- [ TCP Flags ] 160 | f = self.flags 161 | 162 | tcp_flags_rsv = (f[0] << 9) 163 | tcp_flags_noc = (f[1] << 8) 164 | tcp_flags_cwr = (f[2] << 7) 165 | tcp_flags_ecn = (f[3] << 6) 166 | tcp_flags_urg = (f[4] << 5) 167 | tcp_flags_ack = (f[5] << 4) 168 | tcp_flags_psh = (f[6] << 3) 169 | tcp_flags_rst = (f[7] << 2) 170 | tcp_flags_syn = (f[8] << 1) 171 | tcp_flags_fin = (f[9]) 172 | 173 | self.tcp_flags = tcp_flags_rsv + tcp_flags_noc + tcp_flags_cwr + \ 174 | tcp_flags_ecn + tcp_flags_urg + tcp_flags_ack + \ 175 | tcp_flags_psh + tcp_flags_rst + tcp_flags_syn + tcp_flags_fin 176 | 177 | # ---- [ TCP Window Size ] 178 | self.tcp_wdw = 8192 # socket.htons (5840)# 179 | 180 | # ---- [ TCP CheckSum ] 181 | self.tcp_chksum = 0 182 | 183 | # ---- [ TCP Urgent Pointer ] 184 | self.tcp_urg_ptr = 0 185 | 186 | return 187 | -------------------------------------------------------------------------------- /raw_python/lib/Udp.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # 5 | # Copyright 2018 Dept. CSE SUSTech 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | # -------------------------------------------------------------------------- 21 | # Don't Remove Authors Info | 22 | # -------------------------------------------------------------------------- 23 | 24 | 25 | __author__ = 'Suraj Singh Bisht ' # Name Of Author 26 | __credit__ = '[] ' # Contributers Name 27 | __contact__ = 'surajsinghbisht054@gmail.com ' # Email 28 | __copyright__ = 'Copyright 2018 Suraj Singh Bisht ' # Copyright 29 | __license__ = 'Apache 2.0 ' # LICENSE 30 | __Update__ = '2018-01-11 12:00:29.991758 ' # Last Update 31 | __version__ = '0.1 ' # Version 32 | __maintainer__ = 'Suraj Singh Bisht ' # Project Current Maintainer 33 | __status__ = 'Production ' # Project Status 34 | 35 | 36 | # TODO: complete this 37 | -------------------------------------------------------------------------------- /raw_python/lib/__init__.py: -------------------------------------------------------------------------------- 1 | from .Ether import EtherPacket, parse_eth_header 2 | from .IP import IPPacket, parse_ip_header 3 | from .ICMP import ICMPPacket, parse_icmp_header 4 | from .Tcp import TCPPacket 5 | # from .Udp import UDPPacket -------------------------------------------------------------------------------- /raw_python/lib/util.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # 5 | # Copyright 2018 Dept. CSE SUSTech 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | # -------------------------------------------------------------------------- 21 | # Don't Remove Authors Info | 22 | # -------------------------------------------------------------------------- 23 | 24 | 25 | __author__ = 'HHQ. ZHANG' 26 | __credit__ = '["Suraj Singh Bisht",]' 27 | __contact__ = 'contact@jinlab.cn' 28 | __copyright__ = 'Copyright 2018 Dept. CSE SUSTech' 29 | __license__ = 'Apache 2.0' 30 | __Update__ = '2018-01-11 12:33:09.399381' 31 | __version__ = '0.1' 32 | __maintainer__ = 'HHQ. ZHANG' 33 | __status__ = 'Production' 34 | 35 | class Packet: 36 | @staticmethod 37 | def calc_checksum(msg): 38 | s = 0 # Binary Sum 39 | # loop taking 2 characters at a time 40 | for i in range(0, len(msg), 2): 41 | a = msg[i] 42 | b = msg[i + 1] 43 | s = s + (a + (b << 8)) 44 | # One's Complement 45 | s = s + (s >> 16) 46 | s = ~s & 0xffff 47 | return s -------------------------------------------------------------------------------- /raw_python/samples/PcapHandler.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # 5 | # Copyright 2018 Dept. CSE SUSTech 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | # -------------------------------------------------------------------------- 21 | # Don't Remove Authors Info | 22 | # -------------------------------------------------------------------------- 23 | 24 | 25 | __author__ = 'Suraj Singh Bisht ' # Name Of Author 26 | __credit__ = '[] ' # Contributers Name 27 | __contact__ = 'surajsinghbisht054@gmail.com ' # Email 28 | __copyright__ = 'Copyright 2018 Suraj Singh Bisht ' # Copyright 29 | __license__ = 'Apache 2.0 ' # LICENSE 30 | __Update__ = '2018-01-11 12:00:29.991758 ' # Last Update 31 | __version__ = '0.1 ' # Version 32 | __maintainer__ = 'Suraj Singh Bisht ' # Project Current Maintainer 33 | __status__ = 'Production ' # Project Status 34 | 35 | # import module 36 | import time 37 | import struct 38 | 39 | # Pcap Global Header Format : 40 | # ( magic number + 41 | # major version number + 42 | # minor version number + 43 | # GMT to local correction + 44 | # accuracy of timestamps + 45 | # max length of captured #packets, in octets + 46 | # data link type) 47 | # 48 | # 49 | 50 | PCAP_GLOBAL_HEADER_FMT = '@ I H H i I I I ' 51 | 52 | # Global Header Values 53 | PCAP_MAGICAL_NUMBER = 2712847316 54 | PCAP_MJ_VERN_NUMBER = 2 55 | PCAP_MI_VERN_NUMBER = 4 56 | PCAP_LOCAL_CORECTIN = 0 57 | PCAP_ACCUR_TIMSTAMP = 0 58 | PCAP_MAX_LENGTH_CAP = 65535 59 | PCAP_DATA_LINK_TYPE = 1 60 | 61 | 62 | class Pcap: 63 | 64 | def __init__(self, filename, link_type=PCAP_DATA_LINK_TYPE): 65 | self.pcap_file = open(filename, 'wb') # 4 + 2 + 2 + 4 + 4 + 4 + 4 66 | self.pcap_file.write( 67 | struct.pack('@ I H H i I I I ', PCAP_MAGICAL_NUMBER, PCAP_MJ_VERN_NUMBER, PCAP_MI_VERN_NUMBER, 68 | PCAP_LOCAL_CORECTIN, PCAP_ACCUR_TIMSTAMP, PCAP_MAX_LENGTH_CAP, link_type)) 69 | print 70 | "[+] Link Type : {}".format(link_type) 71 | 72 | def writelist(self, data=[]): 73 | for i in data: 74 | self.write(i) 75 | return 76 | 77 | def write(self, data): 78 | ts_sec, ts_usec = map(int, str(time.time()).split('.')) 79 | length = len(data) 80 | self.pcap_file.write(struct.pack('@ I I I I', ts_sec, ts_usec, length, length)) 81 | self.pcap_file.write(data) 82 | 83 | def close(self): 84 | self.pcap_file.close() 85 | 86 | 87 | if __name__ == '__main__': 88 | 89 | # import modules 90 | import socket 91 | import struct 92 | import os 93 | 94 | # Create Socket 95 | if os.name == "nt": 96 | s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) 97 | s.bind((input("[+] YOUR_INTERFACE : "), 0)) 98 | s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) 99 | s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) 100 | else: 101 | s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800)) 102 | 103 | # Create Object 104 | p = Pcap('temp.pcap') 105 | 106 | while True: 107 | # Sniff Packet 108 | pkt = s.recvfrom(65565) 109 | 110 | # Save captured packets into pcap file 111 | p.write(pkt[0]) 112 | 113 | # flush data 114 | p.pcap_file.flush() 115 | 116 | # close file 117 | p.close() 118 | -------------------------------------------------------------------------------- /raw_python/samples/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # 5 | # Copyright 2018 Dept. CSE SUSTech 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | # -------------------------------------------------------------------------- 21 | # Don't Remove Authors Info | 22 | # -------------------------------------------------------------------------- 23 | 24 | 25 | __author__ = 'Suraj Singh Bisht ' # Name Of Author 26 | __credit__ = '[] ' # Contributers Name 27 | __contact__ = 'surajsinghbisht054@gmail.com ' # Email 28 | __copyright__ = 'Copyright 2018 Suraj Singh Bisht ' # Copyright 29 | __license__ = 'Apache 2.0 ' # LICENSE 30 | __Update__ = '2018-01-11 12:00:29.991758 ' # Last Update 31 | __version__ = '0.1 ' # Version 32 | __maintainer__ = 'Suraj Singh Bisht ' # Project Current Maintainer 33 | __status__ = 'Production ' # Project Status 34 | -------------------------------------------------------------------------------- /raw_python/samples/utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # 5 | # Copyright 2018 Dept. CSE SUSTech 6 | # Copyright 2018 Suraj Singh Bisht 7 | # 8 | # Licensed under the Apache License, Version 2.0 (the "License"); 9 | # you may not use this file except in compliance with the License. 10 | # You may obtain a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, software 15 | # distributed under the License is distributed on an "AS IS" BASIS, 16 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | # See the License for the specific language governing permissions and 18 | # limitations under the License. 19 | # 20 | # 21 | # -------------------------------------------------------------------------- 22 | # Don't Remove Authors Info | 23 | # -------------------------------------------------------------------------- 24 | 25 | 26 | __author__ = 'Suraj Singh Bisht, HHQ. ZHANG' 27 | __credit__ = '["Suraj Singh Bisht",]' 28 | __contact__ = 'contact@jinlab.cn' 29 | __copyright__ = 'Copyright 2018 Dept. CSE SUSTech' 30 | __license__ = 'Apache 2.0' 31 | __Update__ = '2018-01-11 12:33:09.399381' 32 | __version__ = '0.1' 33 | __maintainer__ = 'HHQ. ZHANG' 34 | __status__ = 'Production' 35 | 36 | import array 37 | import fcntl 38 | import socket 39 | import struct 40 | from binascii import hexlify 41 | 42 | 43 | # # found on 44 | # get all interface names 45 | def all_interfaces(): 46 | max_possible = 128 # arbitrary. raise if needed. 47 | 48 | bytes = max_possible * 32 49 | 50 | # Create a dummy socket 51 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 52 | 53 | names = array.array('B', b'\0' * bytes) 54 | 55 | outbytes = struct.unpack('iL', fcntl.ioctl( 56 | s.fileno(), 57 | 0x8912, # SIOCGIFCONF 58 | struct.pack('iL', bytes, names.buffer_info()[0]) 59 | ))[0] 60 | 61 | namestr = names.tostring() 62 | 63 | lst = [] 64 | 65 | for i in range(0, outbytes, 40): 66 | name = namestr[i:i + 16].split(b'\0', 1)[0] 67 | ip = namestr[i + 20:i + 24] 68 | lst.append((name, socket.inet_ntoa(ip))) 69 | 70 | s.close() 71 | return lst 72 | 73 | 74 | def get_mac(interface, p=0): 75 | s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW) 76 | s.bind((interface.decode(), p)) 77 | mac = hexlify(s.getsockname()[4]) 78 | s.close() 79 | return mac 80 | 81 | 82 | def get_ip(): 83 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 84 | try: 85 | # doesn't even have to be reachable 86 | s.connect(('10.255.255.255', 1)) 87 | IP = s.getsockname()[0] 88 | except: 89 | IP = '127.0.0.1' 90 | finally: 91 | s.close() 92 | return IP 93 | 94 | 95 | def get_ipv6(): 96 | s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) 97 | 98 | s.connect(('2001:0db8:85a3:0000:0000:8a2e:0370:7334', 1)) 99 | 100 | ip = s.getsockname()[0] 101 | 102 | s.close() 103 | return ip 104 | 105 | 106 | if __name__ == '__main__': 107 | print(all_interfaces()) 108 | print(get_ip()) 109 | print(get_ipv6()) 110 | -------------------------------------------------------------------------------- /raw_python/samples/wsk.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # 5 | # Copyright 2018 Dept. CSE SUSTech 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | # 20 | # -------------------------------------------------------------------------- 21 | # Don't Remove Authors Info | 22 | # -------------------------------------------------------------------------- 23 | 24 | 25 | __author__ = 'Suraj Singh Bisht ' # Name Of Author 26 | __credit__ = '[] ' # Contributers Name 27 | __contact__ = 'surajsinghbisht054@gmail.com ' # Email 28 | __copyright__ = 'Copyright 2018 Suraj Singh Bisht ' # Copyright 29 | __license__ = 'Apache 2.0 ' # LICENSE 30 | __Update__ = '2018-01-11 12:00:29.991758 ' # Last Update 31 | __version__ = '0.1 ' # Version 32 | __maintainer__ = 'Suraj Singh Bisht ' # Project Current Maintainer 33 | __status__ = 'Production ' # Project Status 34 | 35 | import binascii 36 | import os 37 | # import module 38 | import tempfile 39 | 40 | from .PcapHandler import Pcap 41 | 42 | 43 | def hexdump(data): 44 | hexdata = binascii.hexlify(data) 45 | # print hexdata 46 | print 47 | "\t", "_" * 50, '\n' 48 | a = 0 49 | for num, i in enumerate(range(0, len(hexdata) + 32, 32)[1:]): 50 | line = hexdata[a:i] 51 | # print '='*60,line 52 | print 53 | "00{}0\t".format(num), 54 | x = 0 55 | for j in range(0, len(line) + 2, 2): 56 | print 57 | line[x:j].upper(), 58 | 59 | x = j 60 | print 61 | '' 62 | a = i 63 | print 64 | "\t", "_" * 50 65 | return 66 | 67 | 68 | class ShowPacket: 69 | def __init__(self, data=[], **kwargs): 70 | self.data = data 71 | self.kwargs = kwargs 72 | self.showpacket() 73 | 74 | def showpacket(self): 75 | tmp = tempfile.mkstemp(suffix='.cap') 76 | pkt = Pcap(tmp[1], **self.kwargs) 77 | for i in self.data: 78 | pkt.write(i) 79 | pkt.close() 80 | cmd = 'wireshark \"{}\" '.format(tmp[1]) 81 | print 82 | cmd 83 | os.system(cmd) 84 | return 85 | -------------------------------------------------------------------------------- /raw_python/tests/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # 5 | # Copyright 2018 Dept. CSE SUSTech 6 | # Copyright 2018 Suraj Singh Bisht 7 | # 8 | # Licensed under the Apache License, Version 2.0 (the "License"); 9 | # you may not use this file except in compliance with the License. 10 | # You may obtain a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, software 15 | # distributed under the License is distributed on an "AS IS" BASIS, 16 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | # See the License for the specific language governing permissions and 18 | # limitations under the License. 19 | # 20 | # 21 | # -------------------------------------------------------------------------- 22 | # Don't Remove Authors Info | 23 | # -------------------------------------------------------------------------- 24 | 25 | 26 | __author__ = 'Suraj Singh Bisht, HHQ. ZHANG' 27 | __credit__ = '["Suraj Singh Bisht",]' 28 | __contact__ = 'contact@jinlab.cn' 29 | __copyright__ = 'Copyright 2018 Dept. CSE SUSTech' 30 | __license__ = 'Apache 2.0' 31 | __Update__ = '2018-01-11 12:33:09.399381' 32 | __version__ = '0.1' 33 | __maintainer__ = 'HHQ. ZHANG' 34 | __status__ = 'Production' 35 | 36 | import socket 37 | 38 | from .. import EtherPacket, IPPacket, ICMPPacket, TCPPacket, \ 39 | parse_icmp_header, parse_ip_header, parse_eth_header 40 | from ..lib.IP import load_ip, LINKTYPE0 41 | 42 | 43 | def ether_test(): 44 | pkt = EtherPacket() 45 | print(parse_eth_header(pkt.raw)) 46 | # return 47 | pkt1 = IPPacket() 48 | try: 49 | from ..samples.wsk import ShowPacket 50 | ShowPacket([pkt.raw + pkt1.raw], link_type=1) 51 | except: 52 | print("[+] Unable To Find pye.samples.wsk script.") 53 | return 54 | 55 | 56 | def ip_test(): 57 | pkt = IPPacket(flag_dtf=1) 58 | print(parse_ip_header(pkt.raw)) 59 | 60 | try: 61 | from ..samples.wsk import ShowPacket 62 | ShowPacket(data=[pkt.raw], link_type=LINKTYPE0) 63 | except: 64 | print("[+] Unable To Find pye.samples.wsk script.") 65 | return 66 | 67 | 68 | def icmp_test(): 69 | icmp = ICMPPacket() 70 | print(parse_icmp_header(icmp.raw)) 71 | ip = load_ip(tcp=icmp, ip_proto=socket.IPPROTO_ICMP) 72 | eth = EtherPacket(data=ip) 73 | 74 | try: 75 | from ..samples.wsk import ShowPacket 76 | pkt = eth.raw + ip.raw + icmp.raw 77 | ShowPacket([pkt], link_type=1) 78 | except Exception as e: 79 | print(e) 80 | print("[+] Unable To Find pye.samples.wsk script.") 81 | return 82 | 83 | 84 | def tcp_test(): 85 | tcp = TCPPacket() 86 | ip = load_ip(tcp=tcp) 87 | eth = EtherPacket(data=ip) 88 | 89 | try: 90 | from ..samples.wsk import ShowPacket 91 | pkt = eth.raw + ip.raw + tcp.raw 92 | ShowPacket([pkt], link_type=1) 93 | except Exception as e: 94 | print(e) 95 | print("[+] Unable To Find pye.samples.wsk script.") 96 | return 97 | 98 | 99 | def udp_test(): 100 | # TODO: complete this 101 | pass 102 | 103 | 104 | if __name__ == '__main__': 105 | # ether_test() 106 | ip_test() 107 | # icmp_test() 108 | # tcp_test() 109 | # udp_test() 110 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lightsing/raw_python/96482b02a2cf6cd6f41d2404c2fd00441ba1444f/requirements.txt -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from distutils.core import setup 4 | 5 | setup(name='raw_python', 6 | version='2018.12.04', 7 | description='Python Package For Raw Packets Programming', 8 | python_requires='>3.0', 9 | license='Apache-2.0', 10 | url='https://github.com/lightsing/raw_python', 11 | author='Lightsing', 12 | packages=['raw_python', 'raw_python.lib', 'raw_python.samples'], 13 | package_data = { 14 | '': ['README.md', '*.readme'] 15 | } 16 | ) 17 | --------------------------------------------------------------------------------