├── .github └── workflows │ └── rust.yml ├── .gitignore ├── .gitlab-ci.yml ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── bors.toml ├── examples └── main.rs └── src ├── arp.rs ├── ethernet.rs ├── icmp.rs ├── ipv4.rs ├── lib.rs ├── payload.rs ├── tcp.rs ├── udp.rs └── vlan.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Build 20 | run: cargo build --verbose 21 | - name: Run tests 22 | run: cargo test --verbose 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /target 3 | **/*.rs.bk 4 | 5 | /.idea 6 | *.swp 7 | Cargo.lock 8 | -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | image: "rust:latest" 2 | 3 | # Use cargo to test the project 4 | test:cargo: 5 | script: 6 | - rustc --version && cargo --version # Print version info for debugging 7 | - cargo test --all --verbose 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | cache: cargo 3 | rust: 4 | - stable 5 | - beta 6 | - nightly 7 | matrix: 8 | allow_failures: 9 | - rust: nightly 10 | 11 | branches: 12 | except: 13 | - staging.tmp 14 | - trying.tmp 15 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "packet-builder" 3 | version = "0.7.0" 4 | description = "High-level library for interacting with low-level network data." 5 | homepage = "https://github.com/hughesac/packet_builder" 6 | repository = "https://github.com/hughesac/packet_builder" 7 | license = "MIT OR Apache-2.0" 8 | authors = [ 9 | "Aaron Hughes ", 10 | ] 11 | readme = "README.md" 12 | keywords = ["networking", "transport", "packet", "protocol", "packet-crafting"] 13 | categories = ["network-programming"] 14 | 15 | 16 | [dependencies] 17 | derive-new = "0.5" 18 | ipnetwork = "0.19.0" 19 | pnet_datalink = "0.31.0" 20 | pnet = "0.31.0" 21 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 ChatExchange Developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # packet_builder 2 | [![Crates.io - packet_builder](https://img.shields.io/crates/v/packet_builder.svg)](https://crates.io/crates/packet_builder) 3 | [![Build Status](https://travis-ci.org/hughesac/packet_builder.svg?branch=master)](https://travis-ci.org/hughesac/packet_builder) [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT) [![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-green.svg)](http://www.apache.org/licenses/LICENSE-2.0) 4 | 5 | [packet_builder](https://github.com/hughesac/packet_builder) is a high-level rust library for low-level networking that makes use of macros to provide a "kwargs-like" interface a-la python's dpkt/scapy. 6 | 7 | With `packet_builder` you can construct and modify arbitrary packet data and attempt to send it via a NIC, which uses `libpnet` under the covers. 8 | 9 | [sendpacket](https://github.com/Metaswitch/sendpacket) wasn't being maintained so as an exercise in learning Rust I forked it to make `packet_builder`. Sane defaults are used for fields that aren't set by the caller and checksums are calculated for you. Currently the following protocols are supported: 10 | * Ethernet 11 | * ARP 12 | * 802.1Q 13 | * IPv4 14 | * ICMP 15 | * UDP 16 | * TCP 17 | 18 | ## Examples 19 | All the macros are essentially wrappers around the packet structures and functions in libpnet so all the set functions for the various packet types within libpnet are valid. See the examples directory for complete examples. 20 | 21 | Generate a destination unreachable ICMP packet and send it 22 | ```rust 23 | let mut pkt_buf = [0u8; 1500]; 24 | let pkt = packet_builder!( 25 | pkt_buf, 26 | ether({set_source => MacAddr(10,1,1,1,1,1)}) / 27 | ipv4({set_source => ipv4addr!("127.0.0.1"), set_destination => ipv4addr!("127.0.0.1") }) / 28 | icmp_dest_unreach({set_icmp_type => IcmpTypes::DestinationUnreachable}) / 29 | ipv4({set_source => ipv4addr!("10.8.0.1"), set_destination => ipv4addr!("127.0.0.1") }) / 30 | udp({set_source => 53, set_destination => 5353}) / 31 | payload({"hello".to_string().into_bytes()}) 32 | ); 33 | 34 | let if_name = env::args().nth(1) 35 | .expect("Usage: ./packet_builder "); 36 | let (mut sender, _receiver) = build_channel!(if_name); 37 | sender.send_to(pkt.packet(), None).unwrap().unwrap(); 38 | ``` 39 | Generate a TCP PSH|ACK packet with data 40 | ```rust 41 | let mut pkt_buf = [0u8; 1500]; 42 | let pkt = packet_builder!( 43 | pkt_buf, 44 | ether({set_destination => MacAddr(1,2,3,4,5,6), set_source => MacAddr(10,1,1,1,1,1)}) / 45 | ipv4({set_source => ipv4addr!("127.0.0.1"), set_destination => ipv4addr!("127.0.0.1") }) / 46 | tcp({set_source => 43455, set_destination => 80, set_flags => (TcpFlags::PSH | TcpFlags::ACK)}) / 47 | payload({"hello".to_string().into_bytes()}) 48 | ); 49 | ``` 50 | Generate a TCP SYN packet with mss and wscale options specified over VLAN ID 10 51 | ```rust 52 | let mut pkt_buf = [0u8; 1500]; 53 | let pkt = packet_builder!( 54 | pkt_buf, 55 | ether({set_destination => MacAddr(1,2,3,4,5,6), set_source => MacAddr(10,1,1,1,1,1)}) / 56 | vlan({set_vlan_identifier => 10}) / 57 | ipv4({set_source => ipv4addr!("192.168.1.1"), set_destination => ipv4addr!("127.0.0.1") }) / 58 | tcp({set_source => 43455, set_destination => 80, set_options => &[TcpOption::mss(1200), TcpOption::wscale(2)]}) / 59 | payload({[0; 0]}) 60 | ); 61 | ``` 62 | Generate a UDP packet with data 63 | ```rust 64 | let mut pkt_buf = [0u8; 1500]; 65 | let pkt = packet_builder!( 66 | pkt_buf, 67 | ether({set_destination => MacAddr(1,2,3,4,5,6), set_source => MacAddr(10,1,1,1,1,1)}) / 68 | ipv4({set_source => ipv4addr!("127.0.0.1"), set_destination => ipv4addr!("127.0.0.1") }) / 69 | udp({set_source => 12312, set_destination => 143}) / 70 | payload({"hello".to_string().into_bytes()}) 71 | ); 72 | ``` 73 | Generate an ICMP Echo Request packet 74 | ```rust 75 | let mut pkt_buf = [0u8; 1500]; 76 | let pkt = packet_builder!( 77 | pkt_buf, 78 | ether({set_destination => MacAddr(1,2,3,4,5,6), set_source => MacAddr(10,1,1,1,1,1)}) / 79 | ipv4({set_source => ipv4addr!("127.0.0.1"), set_destination => ipv4addr!("127.0.0.1") }) / 80 | icmp_echo_req({set_icmp_type => IcmpTypes::EchoRequest}) / 81 | payload({"hello".to_string().into_bytes()}) 82 | ); 83 | ``` 84 | 85 | ## License 86 | 87 | Licensed under either of 88 | 89 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 90 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 91 | 92 | at your option. 93 | 94 | ### Contribution 95 | 96 | Unless you explicitly state otherwise, any contribution intentionally submitted 97 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any 98 | additional terms or conditions. 99 | -------------------------------------------------------------------------------- /bors.toml: -------------------------------------------------------------------------------- 1 | status = ["continuous-integration/travis-ci/push"] 2 | delete-merged-branches = true 3 | -------------------------------------------------------------------------------- /examples/main.rs: -------------------------------------------------------------------------------- 1 | extern crate packet_builder; 2 | extern crate pnet_datalink; 3 | extern crate pnet; 4 | 5 | use packet_builder::payload::PayloadData; 6 | use packet_builder::*; 7 | use pnet_datalink::Channel::Ethernet; 8 | use pnet_datalink::NetworkInterface; 9 | use pnet::packet::icmp::IcmpTypes; 10 | use pnet::packet::tcp::TcpFlags; 11 | use pnet::packet::tcp::TcpOption; 12 | use pnet::packet::Packet; 13 | use pnet::util::MacAddr; 14 | use std::env; 15 | 16 | fn main() { 17 | //trace_macros!(true); 18 | let if_name = env::args() 19 | .nth(1) 20 | .expect("Usage: ./sendpacket "); 21 | 22 | let interfaces = pnet_datalink::interfaces(); 23 | let interface = interfaces 24 | .into_iter() 25 | .filter(|iface: &NetworkInterface| iface.name == if_name) 26 | .next() 27 | .unwrap_or_else(|| panic!("No such network interface: {}", if_name)); 28 | 29 | let (mut sender, mut _receiver) = match pnet_datalink::channel(&interface, Default::default()) { 30 | Ok(Ethernet(tx, rx)) => (tx, rx), 31 | Ok(_) => panic!("packetdump: unhandled channel type"), 32 | Err(e) => panic!("packetdump: unable to create channel: {}", e), 33 | }; 34 | 35 | { 36 | // Generate a destination unreachable ICMP packet 37 | let mut pkt_buf = [0u8; 1500]; 38 | let pkt = packet_builder!( 39 | pkt_buf, 40 | ether({set_source => MacAddr(10,1,1,1,1,1)}) / 41 | ipv4({set_source => ipv4addr!("127.0.0.1"), set_destination => ipv4addr!("127.0.0.1") }) / 42 | icmp_dest_unreach({set_icmp_type => IcmpTypes::DestinationUnreachable}) / 43 | ipv4({set_source => ipv4addr!("10.8.0.1"), set_destination => ipv4addr!("127.0.0.1") }) / 44 | udp({set_source => 53, set_destination => 5353}) / 45 | payload({"hello".to_string().into_bytes()}) 46 | ); 47 | 48 | sender.send_to(pkt.packet(), None).unwrap().unwrap(); 49 | } 50 | 51 | { 52 | // Generate a TCP PSH|ACK packet with data 53 | let mut pkt_buf = [0u8; 1500]; 54 | let pkt = packet_builder!( 55 | pkt_buf, 56 | ether({set_destination => MacAddr(1,2,3,4,5,6), set_source => MacAddr(10,1,1,1,1,1)}) / 57 | ipv4({set_source => ipv4addr!("192.168.1.1"), set_destination => ipv4addr!("127.0.0.1") }) / 58 | tcp({set_source => 43455, set_destination => 80, set_flags => (TcpFlags::PSH | TcpFlags::ACK)}) / 59 | payload({"hello".to_string().into_bytes()}) 60 | ); 61 | 62 | sender.send_to(pkt.packet(), None).unwrap().unwrap(); 63 | } 64 | { 65 | // Generate an ARP request 66 | let mut pkt_buf = [0u8; 1500]; 67 | let pkt = packet_builder!( 68 | pkt_buf, 69 | ether({set_destination => MacAddr(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF)}) / 70 | arp({set_target_proto_addr => ipv4addr!("192.168.1.1"), set_sender_proto_addr => ipv4addr!("192.168.1.245")}) 71 | ); 72 | sender.send_to(pkt.packet(), None).unwrap().unwrap(); 73 | } 74 | { 75 | // Generate a TCP SYN packet with mss and wscale options specified over VLAN ID 10 76 | let mut pkt_buf = [0u8; 1500]; 77 | let pkt = packet_builder!( 78 | pkt_buf, 79 | ether({set_destination => MacAddr(1,2,3,4,5,6), set_source => MacAddr(10,1,1,1,1,1)}) / 80 | vlan({set_vlan_identifier => 10}) / 81 | ipv4({set_source => ipv4addr!("192.168.1.1"), set_destination => ipv4addr!("127.0.0.1") }) / 82 | tcp({set_source => 43455, set_destination => 80, set_options => &[TcpOption::mss(1200), TcpOption::wscale(2)]}) / 83 | payload({[0; 0]}) 84 | ); 85 | 86 | sender.send_to(pkt.packet(), None).unwrap().unwrap(); 87 | } 88 | { 89 | // Generate a UDP packet with data 90 | let mut pkt_buf = [0u8; 1500]; 91 | let pkt = packet_builder!( 92 | pkt_buf, 93 | ether({set_destination => MacAddr(1,2,3,4,5,6), set_source => MacAddr(10,1,1,1,1,1)}) / 94 | ipv4({set_source => ipv4addr!("127.0.0.1"), set_destination => ipv4addr!("127.0.0.1") }) / 95 | udp({set_source => 12312, set_destination => 143}) / 96 | payload({"hello".to_string().into_bytes()}) 97 | ); 98 | sender.send_to(pkt.packet(), None).unwrap().unwrap(); 99 | } 100 | { 101 | // Generate an ICMP echo request 102 | let mut pkt_buf = [0u8; 1500]; 103 | let pkt = packet_builder!( 104 | pkt_buf, 105 | ether({set_destination => MacAddr(1,2,3,4,5,6), set_source => MacAddr(10,1,1,1,1,1)}) / 106 | ipv4({set_source => ipv4addr!("127.0.0.1"), set_destination => ipv4addr!("127.0.0.1") }) / 107 | icmp_echo_req({set_icmp_type => IcmpTypes::EchoRequest}) / 108 | payload({"hello".to_string().into_bytes()}) 109 | ); 110 | 111 | sender.send_to(pkt.packet(), None).unwrap().unwrap(); 112 | } 113 | 114 | // let rcv_pkt = packet.recv(&session); 115 | // println!("Received: {:?}", rcv_pkt); 116 | } 117 | -------------------------------------------------------------------------------- /src/arp.rs: -------------------------------------------------------------------------------- 1 | 2 | 3 | #[macro_export] 4 | macro_rules! arp { 5 | ({$($func:ident => $value:expr), *}, $buf:expr) => {{ 6 | const ARP_HEADER_LEN: usize = 28; 7 | let total_len = ARP_HEADER_LEN; 8 | let buf_len = $buf.len(); 9 | let mut pkt = pnet::packet::arp::MutableArpPacket::new(&mut $buf[buf_len - total_len..]).unwrap(); 10 | pkt.set_hw_addr_len(6); 11 | pkt.set_proto_addr_len(4); 12 | pkt.set_sender_proto_addr("127.0.0.1".parse().unwrap()); 13 | pkt.set_target_proto_addr("192.168.1.1".parse().unwrap()); 14 | pkt.set_operation(pnet::packet::arp::ArpOperations::Request); 15 | pkt.set_hardware_type(pnet::packet::arp::ArpHardwareTypes::Ethernet); 16 | pkt.set_protocol_type(pnet::packet::ethernet::EtherTypes::Ipv4); 17 | pkt.set_sender_hw_addr(pnet::util::MacAddr(1,2,3,4,5,6)); 18 | $( 19 | pkt.$func($value); 20 | )* 21 | (pkt, pnet::packet::ethernet::EtherTypes::Arp) 22 | }}; 23 | } 24 | 25 | #[cfg(test)] 26 | mod tests { 27 | use pnet::packet::Packet; 28 | use ::ipv4addr; 29 | 30 | #[test] 31 | fn macro_arp_basic() { 32 | let mut buf = [0; 28]; 33 | let (pkt, proto) = arp!({set_target_proto_addr => ipv4addr!("192.168.1.1"), set_sender_proto_addr => ipv4addr!("192.168.1.245")}, buf); 34 | assert_eq!(proto, pnet::packet::ethernet::EtherTypes::Arp ); 35 | 36 | let buf_expected = vec![0; 28]; 37 | let mut pkt_expected = pnet::packet::arp::MutableArpPacket::owned(buf_expected).unwrap(); 38 | pkt_expected.set_hw_addr_len(6); 39 | pkt_expected.set_proto_addr_len(4); 40 | pkt_expected.set_sender_proto_addr("192.168.1.245".parse().unwrap()); 41 | pkt_expected.set_target_proto_addr("192.168.1.1".parse().unwrap()); 42 | pkt_expected.set_operation(pnet::packet::arp::ArpOperations::Request); 43 | pkt_expected.set_hardware_type(pnet::packet::arp::ArpHardwareTypes::Ethernet); 44 | pkt_expected.set_protocol_type(pnet::packet::ethernet::EtherTypes::Ipv4); 45 | pkt_expected.set_sender_hw_addr(pnet::util::MacAddr(1,2,3,4,5,6)); 46 | assert_eq!(pkt_expected.packet(), pkt.packet()); 47 | } 48 | } 49 | 50 | -------------------------------------------------------------------------------- /src/ethernet.rs: -------------------------------------------------------------------------------- 1 | 2 | #[macro_export] 3 | macro_rules! ether { 4 | ({$($func:ident => $value:expr), *}, $payload_pkt:expr, $protocol:expr, $buf:expr ) => {{ 5 | const ETHERNET_HEADER_LEN: usize = 14; 6 | let total_len = ETHERNET_HEADER_LEN + $payload_pkt.packet().len(); 7 | let buf_len = $buf.len(); 8 | let mut pkt = pnet::packet::ethernet::MutableEthernetPacket::new(&mut $buf[buf_len - total_len..]).unwrap(); 9 | pkt.set_ethertype($protocol); 10 | $( 11 | pkt.$func($value); 12 | )* 13 | // The protocol element of the tuple is not actually used but the compiler requires us to 14 | // provide a type. 15 | (pkt, None as Option<&u16>) 16 | }}; 17 | ({$($func:ident => $value:expr), *}, $buf:expr) => {{ 18 | const ETHERNET_HEADER_LEN: usize = 14; 19 | let buf_len = $buf.len(); 20 | let mut pkt = pnet::packet::ethernet::MutableEthernetPacket::new(&mut $buf[buf_len - ETHERNET_HEADER_LEN..]).unwrap(); 21 | $( 22 | pkt.$func($value); 23 | )* 24 | // The protocol element of the tuple is not actually used but the compiler requires us to 25 | // provide a type. 26 | (pkt, None as Option<&u16>) 27 | }}; 28 | } 29 | 30 | 31 | #[cfg(test)] 32 | mod tests { 33 | use pnet::packet::Packet; 34 | 35 | #[test] 36 | fn macro_ether_basic() { 37 | let mut buf = vec![0; 14]; 38 | let (pkt, proto) = ether!({set_destination => pnet::util::MacAddr(10,1,3,1,1,2), set_source => pnet::util::MacAddr(10,1,1,1,1,1)}, buf); 39 | assert_eq!(proto, None); 40 | let buf_expected = vec![0; 14]; 41 | let mut pkt_expected = pnet::packet::ethernet::MutableEthernetPacket::owned(buf_expected).unwrap(); 42 | pkt_expected.set_destination(pnet::util::MacAddr(10,1,3,1,1,2)); 43 | pkt_expected.set_source(pnet::util::MacAddr(10,1,1,1,1,1)); 44 | assert_eq!(pkt_expected.packet(), pkt.packet()); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/icmp.rs: -------------------------------------------------------------------------------- 1 | use pnet::packet::util::checksum as generic_checksum; 2 | use pnet::packet::Packet; 3 | use std::net::Ipv4Addr; 4 | use L4Checksum; 5 | 6 | macro_rules! icmp_pkt_macro_generator { 7 | ($($name:ident => $icmp_type:ty), *) => { 8 | $( 9 | #[macro_export] 10 | macro_rules! $name { 11 | ($args:tt, $payload_pkt:expr, $proto:expr, $buf:expr) => {{ 12 | icmp!($args, $payload_pkt, $icmp_type, $buf) 13 | }}; 14 | ($args:tt, $buf:expr) => {{ 15 | icmp!($args, $icmp_type, $buf) 16 | }}; 17 | } 18 | )* 19 | }; 20 | } 21 | 22 | macro_rules! icmp_checksum_func_gen { 23 | ($($icmp_type:ty),*) => { 24 | $( 25 | impl <'p>L4Checksum for $icmp_type { 26 | fn checksum_ipv4(&mut self, _source: &Ipv4Addr, _destination: &Ipv4Addr) { 27 | // ICMP checksum is the same as IP 28 | self.set_checksum(generic_checksum(&self.packet(), 1)); 29 | } 30 | } 31 | )* 32 | }; 33 | } 34 | 35 | icmp_checksum_func_gen!(pnet::packet::icmp::echo_reply::MutableEchoReplyPacket<'p>, 36 | pnet::packet::icmp::echo_request::MutableEchoRequestPacket<'p>, 37 | pnet::packet::icmp::destination_unreachable::MutableDestinationUnreachablePacket<'p>, 38 | pnet::packet::icmp::time_exceeded::MutableTimeExceededPacket<'p>); 39 | 40 | icmp_pkt_macro_generator!(icmp_echo_req => pnet::packet::icmp::echo_request::MutableEchoRequestPacket, 41 | icmp_echo_reply => pnet::packet::icmp::echo_reply::MutableEchoReplyPacket, 42 | icmp_dest_unreach => pnet::packet::icmp::destination_unreachable::MutableDestinationUnreachablePacket, 43 | icmp_time_exceed => pnet::packet::icmp::time_exceeded::MutableTimeExceededPacket); 44 | 45 | #[macro_export] 46 | macro_rules! icmp { 47 | ({$($func:ident => $value:expr), *}, $icmp_type:ty, $buf:expr) => {{ 48 | let total_len = <$icmp_type>::minimum_packet_size(); 49 | let buf_len = $buf.len(); 50 | let mut pkt = <$icmp_type>::new(&mut $buf[buf_len - total_len..]).unwrap(); 51 | pkt.set_icmp_type(IcmpTypes::EchoRequest); 52 | $( 53 | pkt.$func($value); 54 | )* 55 | (pkt, pnet::packet::ip::IpNextHeaderProtocols::Icmp) 56 | }}; 57 | ({$($func:ident => $value:expr), *}, $payload_pkt:expr, $icmp_type:ty, $buf:expr) => {{ 58 | let total_len = <$icmp_type>::minimum_packet_size() + $payload_pkt.packet().len(); 59 | let buf_len = $buf.len(); 60 | let mut pkt = <$icmp_type>::new(&mut $buf[buf_len - total_len..]).unwrap(); 61 | pkt.set_icmp_type(IcmpTypes::EchoRequest); 62 | $( 63 | pkt.$func($value); 64 | )* 65 | (pkt, pnet::packet::ip::IpNextHeaderProtocols::Icmp) 66 | }}; 67 | } 68 | 69 | 70 | #[cfg(test)] 71 | mod tests { 72 | use pnet::packet::Packet; 73 | use ::payload; 74 | use payload::PayloadData; 75 | use pnet::packet::icmp::{IcmpTypes}; 76 | use icmp; 77 | 78 | #[test] 79 | fn macro_icmp_basic() { 80 | let mut buf = [0; 13]; 81 | let (pkt, proto) = icmp_dest_unreach!({set_icmp_type => IcmpTypes::DestinationUnreachable}, 82 | payload!({"hello".to_string().into_bytes()}, buf).0, None, buf); 83 | assert_eq!(proto, pnet::packet::ip::IpNextHeaderProtocols::Icmp); 84 | 85 | let buf_expected = vec![0; 13]; 86 | let mut pkt_expected = pnet::packet::icmp::destination_unreachable::MutableDestinationUnreachablePacket::owned(buf_expected).unwrap(); 87 | pkt_expected.set_icmp_type(IcmpTypes::DestinationUnreachable); 88 | pkt_expected.set_payload(&"hello".to_string().into_bytes()); 89 | assert_eq!(pkt_expected.packet(), pkt.packet()); 90 | } 91 | } 92 | 93 | -------------------------------------------------------------------------------- /src/ipv4.rs: -------------------------------------------------------------------------------- 1 | use pnet::packet::ipv4::{MutableIpv4Packet}; 2 | 3 | pub const IPV4_HEADER_LEN: usize = 20; 4 | pub const DEFAULT_SOURCE: std::net::Ipv4Addr = std::net::Ipv4Addr::new(127,0,0,1); 5 | pub const DEFAULT_DESTINATION: std::net::Ipv4Addr = std::net::Ipv4Addr::new(127,0,0,1); 6 | 7 | pub fn init_ipv4_pkt(pkt: &mut MutableIpv4Packet, len: u16) -> () { 8 | pkt.set_version(4); 9 | pkt.set_header_length(5); 10 | pkt.set_total_length(len); 11 | pkt.set_ttl(128); 12 | // TODO make the ID a random value 13 | pkt.set_identification(256); 14 | pkt.set_fragment_offset(0); 15 | pkt.set_flags(pnet::packet::ipv4::Ipv4Flags::DontFragment); 16 | } 17 | 18 | #[macro_export] 19 | macro_rules! extract_address { 20 | (set_source, $value:expr) => {{ 21 | $value 22 | }}; 23 | (set_destination, $value:expr) => {{ 24 | $value 25 | }}; 26 | ($func:ident, $value:expr) => {{ 27 | println!("Unexpected case matched in extract_address: {} {}", stringify!($func), stringify!($value)); 28 | ipv4::DEFAULT_SOURCE 29 | }}; 30 | } 31 | 32 | 33 | #[macro_export] 34 | macro_rules! ipv4 { 35 | ({$($func:ident => $value:expr), *}, $l4_pkt:expr, $protocol:expr, $buf:expr) => {{ 36 | 37 | let total_len = ipv4::IPV4_HEADER_LEN + $l4_pkt.packet().len(); 38 | let mut source = ipv4::DEFAULT_SOURCE; 39 | let mut dest = ipv4::DEFAULT_DESTINATION; 40 | // Get the source/destination IP addresses so we can set the L4 checksum before 41 | // creating the MutableIpv4Packet which is another mutable reference to the packet buffer. 42 | // Once the MutableIpv4Packet is created we can't use $l4_pkt or we will get borrow errors. 43 | $( 44 | // If we only used this match without calling the extract_address macro, the compiler can't 45 | // determine which func/value combos apply to which branch of the match and it assume they 46 | // can all match which will cause type errors. The extract_address macro avoids this 47 | // problem. 48 | match stringify!($func) { 49 | "set_source" => source = extract_address!($func, $value), 50 | "set_destination" => dest = extract_address!($func, $value), 51 | _ => (), 52 | } 53 | )* 54 | 55 | $l4_pkt.checksum_ipv4(&source, &dest); 56 | let buf_len = $buf.len(); 57 | let mut pkt = pnet::packet::ipv4::MutableIpv4Packet::new(&mut $buf[buf_len - total_len..]).unwrap(); 58 | pkt.set_next_level_protocol($protocol); 59 | ipv4::init_ipv4_pkt(&mut pkt, total_len as u16); 60 | $( 61 | pkt.$func($value); 62 | )* 63 | pkt.set_checksum(pnet::packet::ipv4::checksum(&pkt.to_immutable())); 64 | 65 | (pkt, pnet::packet::ethernet::EtherTypes::Ipv4) 66 | }}; 67 | } 68 | 69 | 70 | #[macro_export] 71 | macro_rules! ipv4addr { 72 | ($addr_str:expr) => {{ 73 | $addr_str.parse().unwrap() 74 | }}; 75 | } 76 | 77 | #[cfg(test)] 78 | mod tests { 79 | use pnet::packet::Packet; 80 | use pnet::packet::ethernet::EtherTypes::Ipv4; 81 | use L4Checksum; 82 | use ::payload; 83 | use payload::PayloadData; 84 | use ipv4; 85 | 86 | #[test] 87 | fn macro_ipv4_basic() { 88 | let mut buf = [0; 25]; 89 | let (pkt, proto) = ipv4!({set_source => ipv4addr!("127.0.0.1"), set_destination => ipv4addr!("192.168.1.1"), set_version => 4}, 90 | payload!({"hello".to_string().into_bytes()}, buf).0, pnet::packet::ip::IpNextHeaderProtocols::Udp, buf); 91 | assert_eq!(proto, Ipv4); 92 | 93 | let buf_expected = vec![0; 25]; 94 | let mut pkt_expected = pnet::packet::ipv4::MutableIpv4Packet::owned(buf_expected).unwrap(); 95 | pkt_expected.set_destination(ipv4addr!("192.168.1.1")); 96 | pkt_expected.set_source(ipv4addr!("127.0.0.1")); 97 | pkt_expected.set_version(4); 98 | pkt_expected.set_header_length(5); 99 | pkt_expected.set_total_length(25); 100 | pkt_expected.set_payload(&"hello".to_string().into_bytes()); 101 | pkt_expected.set_ttl(128); 102 | pkt_expected.set_identification(256); 103 | pkt_expected.set_flags(pnet::packet::ipv4::Ipv4Flags::DontFragment); 104 | pkt_expected.set_next_level_protocol(pnet::packet::ip::IpNextHeaderProtocols::Udp); 105 | pkt_expected.set_checksum(pnet::packet::ipv4::checksum(&pkt_expected.to_immutable())); 106 | assert_eq!(pkt_expected.packet(), pkt.packet()); 107 | } 108 | } 109 | 110 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![macro_use] 2 | #![allow(unused_macros)] 3 | 4 | extern crate derive_new; 5 | extern crate ipnetwork; 6 | extern crate pnet; 7 | 8 | pub mod icmp; 9 | pub mod tcp; 10 | pub mod udp; 11 | pub mod ethernet; 12 | pub mod arp; 13 | pub mod vlan; 14 | pub mod ipv4; 15 | pub mod payload; 16 | 17 | use std::net::Ipv4Addr; 18 | 19 | pub trait L4Checksum { 20 | fn checksum_ipv4(&mut self, source: &Ipv4Addr, destination: &Ipv4Addr) -> (); 21 | } 22 | 23 | #[macro_export] 24 | macro_rules! build_channel { 25 | ($ifname:expr) => {{ 26 | let interfaces = pnet_datalink::interfaces(); 27 | let interface = interfaces 28 | .into_iter() 29 | .find(|iface| iface.name == $ifname) 30 | .unwrap(); 31 | 32 | let (sender, receiver) = match pnet_datalink::channel(&interface, Default::default()) { 33 | Ok(pnet_datalink::Channel::Ethernet(tx, rx)) => (tx, rx), 34 | Ok(_) => panic!("Unknown channel type"), 35 | Err(e) => panic!("Error happened {}", e), 36 | }; 37 | (sender, receiver) 38 | }}; 39 | } 40 | 41 | 42 | #[macro_export] 43 | macro_rules! sub_builder { 44 | ($pkt_buf:expr, $build_macro:ident($args:tt) $(/ $rem_macros:ident($rem_args:tt))+) => {{ 45 | let (mut payload_pkt, _payload_proto) = sub_builder!($pkt_buf, $($rem_macros($rem_args) )/ *); 46 | let (pkt, proto) = $build_macro!($args, payload_pkt, _payload_proto, $pkt_buf); 47 | (pkt, proto) 48 | }}; 49 | ($pkt_buf:expr, $build_macro:ident($args:tt)) => {{ 50 | $build_macro!($args, $pkt_buf) 51 | }}; 52 | } 53 | 54 | // Call the sub builder so we can return just the packet rather than the tuple that gets returned 55 | // by the sub builder for use during the recursion. 56 | #[macro_export] 57 | macro_rules! packet_builder { 58 | ($pkt_buf:expr, $( $rem_macros:ident($rem_args:tt))/ * ) => {{ 59 | let (pkt, _proto) = sub_builder!($pkt_buf, $( $rem_macros($rem_args) )/ *); 60 | pkt 61 | }}; 62 | } 63 | 64 | -------------------------------------------------------------------------------- /src/payload.rs: -------------------------------------------------------------------------------- 1 | use std::net::Ipv4Addr; 2 | use L4Checksum; 3 | 4 | impl <'p>L4Checksum for PayloadData<'p> { 5 | fn checksum_ipv4(&mut self, _source: &Ipv4Addr, _destination: &Ipv4Addr) -> () { 6 | // The payload has no checksum we just need to implement the trait. 7 | } 8 | } 9 | 10 | pub struct PayloadData<'p> { 11 | pub data: &'p mut[u8], 12 | } 13 | 14 | // Implement the pnet Packet trait so we can use the same interface in the macro for getting the 15 | // data. 16 | impl <'p>pnet::packet::Packet for PayloadData<'p> { 17 | fn packet(& self) -> & [u8] { &self.data[..] } 18 | fn payload(& self) -> & [u8] { &self.data[..] } 19 | } 20 | 21 | #[macro_export] 22 | macro_rules! payload { 23 | ($value:expr, $buf:expr) => {{ 24 | let buf_len = $buf.len(); 25 | let pdata = PayloadData { 26 | data : &mut$buf[buf_len - $value.len()..], 27 | }; 28 | for i in 0..$value.len() { 29 | pdata.data[i] = $value[i]; 30 | } 31 | (pdata, None as Option<&u16>) 32 | }}; 33 | } 34 | 35 | -------------------------------------------------------------------------------- /src/tcp.rs: -------------------------------------------------------------------------------- 1 | use pnet::packet::tcp::{MutableTcpPacket}; 2 | use pnet::packet::tcp::ipv4_checksum as ipv4_tcp_checksum; 3 | use std::net::Ipv4Addr; 4 | use pnet::packet::tcp::{TcpOption, TcpOptionPacket}; 5 | use L4Checksum; 6 | 7 | impl <'p>L4Checksum for MutableTcpPacket<'p> { 8 | fn checksum_ipv4(&mut self, source: &Ipv4Addr, destination: &Ipv4Addr) -> () { 9 | self.set_checksum(ipv4_tcp_checksum(&self.to_immutable(), source, destination)); 10 | } 11 | } 12 | 13 | /// Calculate the length (in double words) of an array of TcpOption structs 14 | pub fn get_options_len(vals: &[TcpOption]) -> u8 { 15 | let mut len = 0; 16 | for opt in vals.iter() { 17 | len += TcpOptionPacket::packet_size(&opt); 18 | } 19 | 20 | match len { 21 | 0 => 0, 22 | _ => { 23 | let mut ret = len / 4; 24 | ret += 1; 25 | ret as u8 26 | } 27 | } 28 | } 29 | 30 | #[macro_export] 31 | macro_rules! extract_options_len { 32 | (set_options, $value:expr) => {{ 33 | tcp::get_options_len($value) 34 | }}; 35 | ($func:ident, $value:expr) => {{ 36 | println!("Unexpected case matched in extract_set_options: {} {}", stringify!($func), stringify!($value)); 37 | 0 38 | }}; 39 | } 40 | 41 | 42 | #[macro_export] 43 | macro_rules! tcp { 44 | ({$($func:ident => $value:expr), *}, $payload_pkt:expr, $protocol:expr, $buf:expr) => {{ 45 | const TCP_HEADER_LEN: usize = 20; 46 | // We need to calculate the length of the options before we create the MutableTcpPacket 47 | let mut opts_len = 0; 48 | $( 49 | match stringify!($func) { 50 | "set_options" => { 51 | opts_len = extract_options_len!($func, $value); 52 | } 53 | _ => (), 54 | } 55 | )* 56 | 57 | let total_len = TCP_HEADER_LEN + $payload_pkt.packet().len() + (opts_len as usize * 4); 58 | let buf_len = $buf.len(); 59 | let mut pkt = pnet::packet::tcp::MutableTcpPacket::new(&mut $buf[buf_len - total_len..]).unwrap(); 60 | pkt.set_data_offset(5 + opts_len); 61 | pkt.set_flags(pnet::packet::tcp::TcpFlags::SYN); 62 | pkt.set_sequence(0); 63 | pkt.set_acknowledgement(0); 64 | pkt.set_urgent_ptr(0); 65 | pkt.set_window(65535); 66 | $( 67 | pkt.$func($value); 68 | )* 69 | (pkt, pnet::packet::ip::IpNextHeaderProtocols::Tcp) 70 | }}; 71 | } 72 | 73 | #[cfg(test)] 74 | mod tests { 75 | use pnet::packet::Packet; 76 | use ::payload; 77 | use payload::PayloadData; 78 | use tcp; 79 | use pnet::packet::tcp::TcpOption; 80 | 81 | #[test] 82 | fn macro_tcp_basic() { 83 | let mut buf = [0; 33]; 84 | let (pkt, proto) = tcp!({set_source => 53, set_destination => 5353, set_options => &vec!(TcpOption::mss(1200), TcpOption::wscale(2))}, 85 | payload!({"hello".to_string().into_bytes()}, buf).0, None, buf); 86 | assert_eq!(proto, pnet::packet::ip::IpNextHeaderProtocols::Tcp); 87 | 88 | let buf_expected = vec![0; 33]; 89 | let mut pkt_expected = pnet::packet::tcp::MutableTcpPacket::owned(buf_expected).unwrap(); 90 | pkt_expected.set_destination(5353); 91 | pkt_expected.set_source(53); 92 | pkt_expected.set_data_offset(7); 93 | pkt_expected.set_payload(&"hello".to_string().into_bytes()); 94 | pkt_expected.set_options(&vec!(TcpOption::mss(1200), TcpOption::wscale(2))); 95 | pkt_expected.set_flags(pnet::packet::tcp::TcpFlags::SYN); 96 | pkt_expected.set_sequence(0); 97 | pkt_expected.set_acknowledgement(0); 98 | pkt_expected.set_urgent_ptr(0); 99 | pkt_expected.set_window(65535); 100 | assert_eq!(pkt_expected.packet(), pkt.packet()); 101 | } 102 | } 103 | 104 | -------------------------------------------------------------------------------- /src/udp.rs: -------------------------------------------------------------------------------- 1 | use pnet::packet::udp::{MutableUdpPacket}; 2 | use pnet::packet::udp::ipv4_checksum as ipv4_udp_checksum; 3 | use std::net::Ipv4Addr; 4 | use L4Checksum; 5 | 6 | impl <'p>L4Checksum for MutableUdpPacket<'p> { 7 | fn checksum_ipv4(&mut self, source: &Ipv4Addr, destination: &Ipv4Addr) -> () { 8 | self.set_checksum(ipv4_udp_checksum(&self.to_immutable(), source, destination)); 9 | } 10 | } 11 | 12 | #[macro_export] 13 | macro_rules! udp { 14 | ({$($func:ident => $value:expr), *}, $payload_pkt:expr, $protocol:expr, $buf:expr) => {{ 15 | const UDP_HEADER_LEN: usize = 8; 16 | let total_len = UDP_HEADER_LEN + $payload_pkt.packet().len(); 17 | let buf_len = $buf.len(); 18 | let mut pkt = pnet::packet::udp::MutableUdpPacket::new(&mut $buf[buf_len - total_len..]).unwrap(); 19 | pkt.set_length(total_len as u16); 20 | pkt.set_destination(53); 21 | pkt.set_source(12345); 22 | $( 23 | pkt.$func($value); 24 | )* 25 | (pkt, pnet::packet::ip::IpNextHeaderProtocols::Udp) 26 | }}; 27 | } 28 | 29 | #[cfg(test)] 30 | mod tests { 31 | use pnet::packet::Packet; 32 | use ::payload; 33 | use payload::PayloadData; 34 | use udp; 35 | 36 | #[test] 37 | fn macro_udp_basic() { 38 | let mut buf = [0; 13]; 39 | let (pkt, proto) = udp!({set_source => 53, set_destination => 5353}, 40 | payload!({"hello".to_string().into_bytes()}, buf).0, None, buf); 41 | assert_eq!(proto, pnet::packet::ip::IpNextHeaderProtocols::Udp); 42 | 43 | let buf_expected = vec![0; 13]; 44 | let mut pkt_expected = pnet::packet::udp::MutableUdpPacket::owned(buf_expected).unwrap(); 45 | pkt_expected.set_destination(5353); 46 | pkt_expected.set_source(53); 47 | pkt_expected.set_length(13 as u16); 48 | pkt_expected.set_payload(&"hello".to_string().into_bytes()); 49 | assert_eq!(pkt_expected.packet(), pkt.packet()); 50 | } 51 | } 52 | 53 | -------------------------------------------------------------------------------- /src/vlan.rs: -------------------------------------------------------------------------------- 1 | 2 | 3 | #[macro_export] 4 | macro_rules! vlan { 5 | ({$($func:ident => $value:expr), *}, $payload_pkt:expr, $protocol:expr, $buf:expr) => {{ 6 | const VLAN_HEADER_LEN: usize = 4; 7 | let total_len = VLAN_HEADER_LEN + $payload_pkt.packet().len(); 8 | let buf_len = $buf.len(); 9 | let mut pkt = pnet::packet::vlan::MutableVlanPacket::new(&mut $buf[buf_len - total_len..]).unwrap(); 10 | pkt.set_ethertype($protocol); 11 | pkt.set_vlan_identifier(0); 12 | pkt.set_priority_code_point(pnet::packet::vlan::ClassesOfService::BE); 13 | pkt.set_drop_eligible_indicator(0); 14 | $( 15 | pkt.$func($value); 16 | )* 17 | (pkt, pnet::packet::ethernet::EtherTypes::Vlan) 18 | }}; 19 | } 20 | 21 | #[cfg(test)] 22 | mod tests { 23 | use pnet::packet::Packet; 24 | use ::payload; 25 | use payload::PayloadData; 26 | 27 | #[test] 28 | fn macro_vlan_basic() { 29 | let mut buf = [0; 4]; 30 | let (pkt, proto) = vlan!({set_vlan_identifier => 10, set_drop_eligible_indicator => 2}, 31 | payload!({[0; 0]}, buf).0, pnet::packet::ethernet::EtherTypes::Ipv4, buf); 32 | assert_eq!(proto, pnet::packet::ethernet::EtherTypes::Vlan); 33 | 34 | let buf_expected = vec![0; 4]; 35 | let mut pkt_expected = pnet::packet::vlan::MutableVlanPacket::owned(buf_expected).unwrap(); 36 | pkt_expected.set_ethertype(pnet::packet::ethernet::EtherTypes::Ipv4); 37 | pkt_expected.set_vlan_identifier(10); 38 | pkt_expected.set_priority_code_point(pnet::packet::vlan::ClassesOfService::BE); 39 | pkt_expected.set_drop_eligible_indicator(2); 40 | assert_eq!(pkt_expected.packet(), pkt.packet()); 41 | } 42 | } 43 | 44 | --------------------------------------------------------------------------------