pax_global_header 0000666 0000000 0000000 00000000064 13522305640 0014512 g ustar 00root root 0000000 0000000 52 comment=58a12c624afc34f933dbf83bce26ce570afb5fba
dhcpoptinj-0.5.3/ 0000775 0000000 0000000 00000000000 13522305640 0013661 5 ustar 00root root 0000000 0000000 dhcpoptinj-0.5.3/.travis.yml 0000664 0000000 0000000 00000000336 13522305640 0015774 0 ustar 00root root 0000000 0000000 addons:
apt:
update: true
packages:
- libnetfilter-queue-dev
dist: xenial
language: c
compiler:
- clang
- gcc
before_script:
- mkdir build
script:
- cd build
- cmake ..
- make -j2
dhcpoptinj-0.5.3/CHANGELOG.md 0000664 0000000 0000000 00000005753 13522305640 0015504 0 ustar 00root root 0000000 0000000 # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Unreleased
## 0.5.3 - 2019-08-06
### Fixed
- Fix two format arguments in debug output printing (fairly pedantic; not even
caught by clang analyser).
- Limit DHCP options to 255 bytes (not 256).
- Exit if a DHCP option is too long.
## 0.5.2 - 2019-05-09
### Added
- Add example output "screenshot" to README.
### Changed
- Create PID file after initialising signal handler.
- Remove incompatible compiler warning option when using clang.
- Use a variable for the project/binary name in CMakeLists.txt.
### Fixed
- Indicate that configuration file is an optional argument in usage output.
- Fix error message output when passing option/keyward too many times.
- Improve wording in configuration file parsing error messages.
## 0.5.1 - 2019-04-16
### Changed
- Use 1-byte alignment on DHCP options.
- Refer to salsa.debian.org for deb package source.
- Remove old bug reference in README.
### Fixed
- Allow optional values to configuration file keywords (correctly support
"pid-file" as on the command line).
## 0.5.0 - 2019-04-09
### Added
- Parse configuration from file.
- Add copyright to usage output.
### Fixed
- Fix pedantic errors from clang.
## 0.4.4 - 2019-03-25
### Fixed
- Update version number in binary.
## 0.4.3 - 2019-03-19
### Added
- DHCP option names are printed along with their option codes.
### Changed
- Debug output is more detailed and aligned.
### Fixed
- Alignment and explicit data type conversions are used to compile without
errors on 32-bit architectures.
- Do not fail on strict-overflow warnings, as some may be ignored.
- Do not use non-ASCII characters in debug output. They were not strictly
needed.
## 0.4.2 - 2019-01-17
### Changed
- Change usage string to reflect formatting used by man page.
- Add very strict compiler flags.
### Fixed
- Fix new compiler warnings (pedantic signed/unsigned issues and void function
declarations).
## 0.4.1 - 2016-12-18
### Fixed
- Update version number in --version output from 0.3.0.
## 0.4.0 - 2016-12-13
### Changed
- Use constant for maximum queue length instead of hard-coded value.
### Fixed
- Fix program name simplification bug.
- Remove typo in help text.
## 0.3.0 - 2016-06-10
### Added
- Add support for replacing existing DHCP options.
- Allow injecting multiple options of same type.
### Changed
- Update README.
- Improve debug output.
- Improve help text.
### Fixed
- Fix incorrect --version output.
- Drop/accept if packet fragmented depending on --forward-on-fail.
- Safe-guard against empty DHCP options as result of invalid hex strings.
- Fix erroneous new packet size calculation.
- Fix other minor bugs and warnings.
## 0.2.1 - 2015-07-28
### Changed
- Improve documentation
### Fixed
- Fix memory leak on exit with --version/--help.
## 0.2.0 - 2015-07-27
Initial release
dhcpoptinj-0.5.3/CMakeLists.txt 0000664 0000000 0000000 00000004235 13522305640 0016425 0 ustar 00root root 0000000 0000000 cmake_minimum_required(VERSION 3.0)
# Allow setting PROJECT_VERSION through project():
cmake_policy(SET CMP0048 NEW)
# Don't bother writing the project name all the time:
set(PROJECT dhcpoptinj)
if(DEFINED CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE} CACHE STRING "Choose the type of build, Debug or Release")
else()
SET(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build, Debug or Release")
endif()
if (DEFINED CMAKE_INSTALL_PREFIX)
set(CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE} CACHE STRING "Choose install prefix")
else()
set(CMAKE_INSTALL_PREFIX /usr CACHE STRING "Choose install prefix")
endif()
project(
${PROJECT}
VERSION 0.5.3
DESCRIPTION "DHCP option injector"
LANGUAGES C
)
add_definitions(-DDHCPOPTINJ_VERSION="${PROJECT_VERSION}")
set(SOURCES
src/config.c
src/dhcp.c
src/dhcpoptinj.c
src/ipv4.c
src/options.c
)
set(HEADERS
src/config.h
src/dhcp.h
src/ipv4.h
src/options.h
src/udp.h
)
add_executable(${PROJECT} ${SOURCES} ${HEADERS})
set_property(TARGET ${PROJECT} PROPERTY C_STANDARD 99)
target_compile_options(${PROJECT} PRIVATE
-Wall
-Wextra
-pedantic
-Wcast-align
-Wcast-qual
-Wdisabled-optimization
-Wformat=2
-Winit-self
-Wmissing-declarations
-Wmissing-include-dirs
-Wredundant-decls
-Wshadow
-Wsign-conversion
-Wstrict-overflow=5
-Wno-error=strict-overflow
-Wswitch-default
-Wundef
-Werror
-Wno-unused
-Wmissing-prototypes
-Wstrict-prototypes
-Wold-style-definition
-fstack-protector
-Wwrite-strings
-Wmissing-field-initializers
-D_POSIX_SOURCE
-D_DEFAULT_SOURCE
-D_FORTIFY_SOURCE=2
)
# Only add -Wlogical-op if using gcc; clang does not support this warning option:
if (CMAKE_C_COMPILER_ID STREQUAL "GNU")
target_compile_options(${PROJECT} PRIVATE "-Wlogical-op")
endif()
find_library(NFQ_LIB netfilter_queue REQUIRED)
target_link_libraries(${PROJECT} ${NFQ_LIB})
install(TARGETS ${PROJECT} DESTINATION sbin)
# Add uninstall target, since cmake does not:
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/cmake_uninstall.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake"
IMMEDIATE @ONLY)
add_custom_target(uninstall
COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake)
dhcpoptinj-0.5.3/LICENSE 0000664 0000000 0000000 00000104513 13522305640 0014672 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
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 .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
dhcpoptinj-0.5.3/README.md 0000664 0000000 0000000 00000023451 13522305640 0015145 0 ustar 00root root 0000000 0000000 # DHCP option injector
[](https://travis-ci.org/misje/dhcpoptinj) [](https://lgtm.com/projects/g/misje/dhcpoptinj/alerts/)
Have you ever wanted to intercept DHCP requests and squeeze in a few extra DHCP
options, unbeknownst to the sender? Probably not. However, should the need ever
come, **dhcpoptinj** will (hopefully) help you.
## Why
There can be many a reason to mangle DHCP requests, although chances are you
ought to look for a much better method for solving your problem. Perhaps you do
not have access to the DHCP server/clients and need to modify their DHCP
options, perhaps the DHCP software is difficult to configure (or does not
support what you want to do), perhaps you have a very complex and/or odd setup,
or perhaps you just want to experiment sending exotic or malformed options?
There is a small chance that dhcoptinj might actually be of some use.
## How
dhcpoptinj waits for packets to arrive in a netfilter queue. It will ensure
that a packet is in fact a BOOTP/DHCP packet, and if so proceed to inject
options. It will recalculate the IPv4 header checksum, disable the UDP
checksum (for a simpler implementation) and then give the packet back to
netfilter.
You need an iptables rule in order to intercept packets and send them to
dhcpoptinj. Let us say you have two interfaces bridged together, *eth0* and
*eth1*. Let us say you want to intercept all BOOTP requests coming from *eth0*
and inject the [relay agent information
option](https://tools.ietf.org/html/rfc3046) (82/0x52). Let us make up a silly
payload: An [agent circuit ID
sub-option](https://tools.ietf.org/html/rfc3046#section-3.1) with the value
"Fjas".
Add a rule to the iptables mangle table:`sudo iptables -t mangle -A PREROUTING
-m physdev --physdev-in eth0 -p udp --dport 67 -j NFQUEUE --queue-num 42`.
Then run dhcpoptinj (let us run it in the foreground with extra debug output):
`sudo dhcpoptinj -d -f -q 42 -o'52 01 04 46 6A 61 73'`. Note that dhcpoptinj
must be run by a user with the CAP\_NET\_ADMIN capability. You do not need to,
and you really should not run dhcpoptinj as root. Instead, you can for instance
grant the CAP\_NET\_ADMIN capability to the binary (using *setcap*) and limit
execution rights to only a specific user or group. This is a method used for
running wireshark as non-root, so you will find several guides helping you
accomplish this.
Now send a DHCP packet to the *eth0* interface and watch it (using a tool like
[wireshark](https://www.wireshark.org/)) having been modified when it reaches
the bridged interface. It should have the injected option at the end of the
option list. If you capture the incoming DHCP packet with Wireshark, it will
appear unmodified although it will in fact be mangled.
Note the format of the argument to the *-o* option: It should be a hexadecimal
string starting with the DHCP option code followed by the option payload. The
option length (the byte that normally follows the option code) is automatically
calculated and must not be specified. The hex string can be delimited by
non-hexadecimal characters for readability. All options must have a payload,
except for the special [pad
option](https://tools.ietf.org/html/rfc2132#section-2) (code 0).
The layout of the nonsensical option used in this example (first the [DHCP
option layout](https://tools.ietf.org/html/rfc2132#section-2), then the
specific [relay agent information option sub-option
layout](https://tools.ietf.org/html/rfc3046#section-2.0)) is as follows:
| Code | Length | Data |
|------|--------|----------------------------|
| 52 | (auto) | 01 04 46 6A 61 73 ("Fjas") |
| Sub-opt. | Length | Data |
|----------|--------|----------------------|
| 01 | 4 | 46 6A 61 73 ("Fjas") |
Note that dhcpoptinj does not care about what you write in the option payloads,
nor does it check whether your option code exists. It does however forbid you
to use the option code 255 (the terminating end option). dhcpoptinj inserts
this option as the last option automatically.
## Screenshot
```
dhcpoptinj -f -d -q42 -r -o'0C 66 6A 61 73 65 68 6F 73 74' -o'52 01 04 46 6A 61 73' -o 320A141E28
```
```
3 DHCP option(s) to inject (with a total of 25 bytes): 12 (0x0C) (Hostname), 82 (0x52) (Relay Agent Information), 50 (0x32) (Address Request)
Existing options will be removed
Initialising netfilter queue
Initialising signal handler
Initialisation completed. Waiting for packets to mangle on queue 42
Received 416 bytes
Inspecting 328-byte DHCP packet from B6:40:FE:41:30:DC to 255.255.255.255:67
Mangling packet
Found option 53 (0x35) (DHCP message type) DHCPREQUEST (copying)
Found option 54 (0x36) (DHCP Server Id) with 4-byte payload 0A 14 1E 01 (copying)
Found option 50 (0x32) (Address Request) with 4-byte payload 0A 14 1E 28 (removing)
Found option 12 (0x0C) (Hostname) with 12-byte payload 33 31 36 64 65 39 31 34 64 61 62 34 (removing)
Found option 55 (0x37) (Parameter List) with 13-byte payload 01 1C 02 03 0F 06 77 0C 2C 2F 1A 79 2A (copying)
Found END option (removing)
Injecting option 12 (0x0C) (Hostname) with 9-byte payload 66 6A 61 73 65 68 6F 73 74
Injecting option 82 (0x52) (Relay Agent Information) with 6-byte payload 01 04 46 6A 61 73
Injecting option 50 (0x32) (Address Request) with 4-byte payload 0A 14 1E 28
Inserting END option
Padding with 10 byte(s) to meet minimal BOOTP payload size
Sending mangled packet
```
## Installing
[](https://repology.org/project/dhcpoptinj/versions)
dhcpoptinj is in Debian/Ubuntu. The deb package is under source control at
[salsa](https://salsa.debian.org/misje-guest/dhcpoptinj). Installing
dhcpoptinj from the deb package is recommended over the following manual
installation procedure, because it also includes a man page, bash completion
rules, example files etc.
### Prerequisites
You need [cmake](http://www.cmake.org/) and
[libnetfilter\_queue](http://www.netfilter.org/projects/libnetfilter_queue/)
(and a C compiler that supports C99). Hopefully, you are using a Debian-like
system, in which case you can run the following to install them: `sudo apt-get
install cmake libnetfilter-queue-dev`.
### Build
1. Download or clone the source: `git clone git://github.com/misje/dhcpoptinj`
1. Enter the directory: `cd dhcpoptinj`
1. Create a build directory and enter it (optional, but recommended): `mkdir
build && cd build`
1. Run cmake: `cmake ..` (or `cmake -DCMAKE_BUILD_TYPE=Debug ..` if you want a
debug build)
1. Run make: `make -j4`
1. Install (optional, but you will benefit from having dhcpoptinj in your
PATH): `sudo make install`
### Demolish
1. Run `sudo make uninstall` from your build directory
The build directory with all its contents can be safely removed. If you did not
use a build directory, you can get rid of all the cmake rubbish by running `git
clean -dfx`. Note, however, that this removes **everything** in the project
directory that is not under source control.
## Configuration file
dhcptopinj will attempt to parse /etc/dhcpoptinj.conf or the file passed with
-c/--conf-file. The syntax of the configuration file is
* **key=value**, where *key* is the long option name, or
* **key** if the option does not take an argument
Whitespace is optional. Anything after and including the character **#** is
considered a comment. DHCP options are listed one-by-one as *option=01:02:03*.
Quotes around the option hex string is optional, and the bytes may be separated
by any number of non-hexadecimal characters.
The options *version*, *help* and *conf-file* are not accepted in a
configuration file.
Example:
```apache
# Run in foreground:
foreground
# Enable debug output:
debug
# Override hostname to "fjasehost":
option = '0C 66 6A 61 73 65 68 6F 73 74'
# Send agent ID "Fjas":
option = "52:01:04:46:6A:61:73"
# Override address request to ask for 10.20.30.40:
option=320A141E28
# Use queue 12:
queue = 12
remove-existing-opt # Remove options before inserting
```
## Help
This readme should have got you started. Also check out the man page (in the
deb package) and the help output (`dhcpoptinj -h`), which should cover
everything the utility has to offer.
For bugs and suggestions please create an issue.
### Limitations
dhcpoptinj is simple and will hopefully stay that way. Nonetheless, the
following are missing features that hopefully will be added some day:
1. Remove options instead of having to replace them
2. Filter incoming packets by their DHCP message type (code 53) before mangling
them
### Troubleshooting
1. *Failed to bind queue handler to AF_INET: Operation not permitted*
Most likely you do not have CAP\_NET\_ADMIN capability or there is another
process (perhaps another dhcpoptinj instance?) bound to the same netfilter
queue number.
### Known issues
1. Memory leak on non-normal exit.
This is not considered a leak. However, there should be no memory leak on a
normal exit (catching SIGTERM, SIGINT or SIGHUP).
## Useful information
When creating iptables rules to use with dhcpoptinj, the following options can
be useful:
- `--queue-bypass`
Do not drop packets, but let them pass through if dhcpoptinj is not running
(or not listening on the correct queue number).
## Contributing
If you have any suggestions please leave an issue, and I will come back to you.
You are welcome to contribute and pull requests are much appreciated.
If you find dhcpoptinj useful I would love to hear what you are using it for.
Update the [wiki
page](https://github.com/misje/dhcpoptinj/wiki#practical-use-cases) and
describe your use.
## License
I have chosen to use GPL for this project. If that does not suit you, contact
me, and we can agree on a different license.
dhcpoptinj-0.5.3/cmake_uninstall.cmake.in 0000664 0000000 0000000 00000002013 13522305640 0020435 0 ustar 00root root 0000000 0000000 if(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
message(FATAL_ERROR "Cannot find install manifest: @CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
endif(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
file(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files)
string(REGEX REPLACE "\n" ";" files "${files}")
foreach(file ${files})
message(STATUS "Uninstalling $ENV{DESTDIR}${file}")
if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
exec_program(
"@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\""
OUTPUT_VARIABLE rm_out
RETURN_VALUE rm_retval
)
if(NOT "${rm_retval}" STREQUAL 0)
message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}")
endif(NOT "${rm_retval}" STREQUAL 0)
else(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
message(STATUS "File $ENV{DESTDIR}${file} does not exist.")
endif(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
endforeach(file)
dhcpoptinj-0.5.3/src/ 0000775 0000000 0000000 00000000000 13522305640 0014450 5 ustar 00root root 0000000 0000000 dhcpoptinj-0.5.3/src/config.c 0000664 0000000 0000000 00000050022 13522305640 0016060 0 ustar 00root root 0000000 0000000 /*
* Copyright © 2015–2019 Andreas Misje
*
* This file is part of dhcpoptinj.
*
* dhcpoptinj 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.
*
* dhcpoptinj 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 dhcpoptinj. If not, see .
*/
#include
#include
#include "config.h"
#include
#include
#include
#include "options.h"
#include
#include "dhcp.h"
#include
#include
static const char programName[] = "dhcpoptinj";
static const char defaultPIDFilePath[] = "/var/run/dhcpoptinj.pid";
static const char defaultConfFilePath[] = "/etc/dhcpoptinj.conf";
/* DHCP option lists for later serialisation: One for command line input and
* one for configuration file(s). They need to be separated so that one source
* does not override the other; the configuration file may be read in the
* middle of the command line option parsing. */
static struct DHCPOptList *cmdDHCPOptList, *fileDHCPOptList;
enum Source
{
SOURCE_CMD_LINE = 0,
SOURCE_FILE,
};
enum ConfFileParseOption
{
PARSE_ALLOW_NOEXIST = 0,
PARSE_REQUIRE_EXIST = 1,
};
/* Definitions for long-only options that cannot be identified with an ASCII
* character: */
enum LongOnlyOpt {
ForwardOnFail = 1000,
};
/* Option definitions used to index options[] and optionCount[]: */
enum Option
{
OPT_CONF_FILE = 0,
OPT_DEBUG,
OPT_FOREGROUND,
OPT_FORWARD_ON_FAIL,
OPT_HELP,
OPT_IGNORE_EXISTING_OPT,
OPT_OPTION,
OPT_PID_FILE,
OPT_QUEUE,
OPT_REMOVE_EXISTING_OPT,
OPT_VERSION,
OPT_COUNT,
};
static const int sources[] =
{
SOURCE_CMD_LINE,
SOURCE_FILE,
};
static const struct option options[] =
{
[OPT_CONF_FILE] = { "conf-file", optional_argument, NULL, 'c' },
[OPT_DEBUG] = { "debug", no_argument, NULL, 'd' },
[OPT_FOREGROUND] = { "foreground", no_argument, NULL, 'f' },
[OPT_FORWARD_ON_FAIL] = { "forward-on-fail", no_argument, NULL, ForwardOnFail },
[OPT_HELP] = { "help", no_argument, NULL, 'h' },
[OPT_IGNORE_EXISTING_OPT] = { "ignore-existing-opt", no_argument, NULL, 'i' },
[OPT_OPTION] = { "option", required_argument, NULL, 'o' },
[OPT_PID_FILE] = { "pid-file", optional_argument, NULL, 'p' },
[OPT_QUEUE] = { "queue", required_argument, NULL, 'q' },
[OPT_REMOVE_EXISTING_OPT] = { "remove-existing-opt", no_argument, NULL, 'r' },
[OPT_VERSION] = { "version", no_argument, NULL, 'v' },
[OPT_COUNT] = {0},
};
/* Count the number of times arguments have been passed on the command line
* and listed as keywords in the configuration file: */
static unsigned int optionCount[][OPT_COUNT] =
{
[SOURCE_CMD_LINE] = {0},
[SOURCE_FILE] = {0},
};
static struct Config *createDefaultConfig(void);
static void printUsage(void);
static void printHelp(void);
static void printVersion(void);
static int parseQueueNum(const char *string, uint16_t *queueNum);
static void addDHCPOption(struct DHCPOptList *list, const char *string);
static void parseConfFile(struct Config *config, const char *filePath, int parseOpts);
static void parseOption(struct Config *config, int option, char *arg, enum Source source);
static void validateOptionCombinations(void);
static unsigned int totalOptionCount(int option);
static char *trim(char *text);
static int parseKeyValue(const char *key, const char *value, const char *filePath,
unsigned lineNo);
struct Config *conf_parseOpts(int argc, char * const *argv)
{
cmdDHCPOptList = dhcpOpt_createList();
fileDHCPOptList = dhcpOpt_createList();
if (!cmdDHCPOptList || !fileDHCPOptList)
{
fputs("Failed to allocate memory for DHCP option list\n", stderr);
exit(EXIT_FAILURE);
}
struct Config *config = createDefaultConfig();
while (true)
{
int optVal = getopt_long(argc, argv, "c::dfhio:p::q:rv", options, NULL);
/* Parsing finished: */
if (optVal == -1)
break;
int option = 0;
for (; option < OPT_COUNT; ++option)
{
/* Look for the option in the option list: */
if (optVal == options[option].val)
{
parseOption(config, option, optarg, SOURCE_CMD_LINE);
break;
}
}
/* The option was not found and is invalid: */
if (option == OPT_COUNT)
{
printUsage();
exit(EXIT_FAILURE);
}
}
/* If a config file path was not specified on the command line load the
* default file, but do not complain if it does not exist: */
if (!optionCount[SOURCE_CMD_LINE][OPT_CONF_FILE])
parseConfFile(config, defaultConfFilePath, PARSE_ALLOW_NOEXIST);
validateOptionCombinations();
/* dhcpoptinj does not accept any arguments, only options: */
if (argc - optind > 0)
{
fputs("No non-option arguments expected, but the following was passed: ", stderr);
for (int i = optind; i < argc; ++i)
fprintf(stderr, "\"%s\"%s", argv[i], i == argc - 1 ? "\n" : ", ");
printUsage();
exit(EXIT_FAILURE);
}
/* If no DHCP options were passed on the command line use the options from
* the configuration file: */
struct DHCPOptList *dhcpOptList = dhcpOpt_count(cmdDHCPOptList) ?
cmdDHCPOptList : fileDHCPOptList;
/* Add obligatory DHCP end option and serialise options: */
if (dhcpOpt_serialise(dhcpOptList, &config->dhcpOpts, &config->dhcpOptsSize))
{
fputs("Failed to create DHCP option list\n", stderr);
exit(EXIT_FAILURE);
}
/* Create an array of just the DHCP option codes: */
if (dhcpOpt_optCodes(dhcpOptList, &config->dhcpOptCodes, &config->dhcpOptCodeCount))
{
fputs("Failed to create DHCP option code list\n", stderr);
exit(EXIT_FAILURE);
}
dhcpOpt_destroyList(cmdDHCPOptList);
dhcpOpt_destroyList(fileDHCPOptList);
return config;
}
void conf_destroy(struct Config *config)
{
if (!config)
return;
free(config->pidFile);
free(config->dhcpOpts);
free(config->dhcpOptCodes);
free(config);
}
static struct Config *createDefaultConfig(void)
{
struct Config *config = malloc(sizeof(*config));
if (!config)
{
fputs("Could not allocate space for configuration object\n", stderr);
exit(EXIT_FAILURE);
}
*config = (struct Config) {0};
return config;
}
static void printUsage(void)
{
int progNameLen = (int)sizeof(programName) - 1;
printVersion();
printf(
"\n"
"Usage: %s [-df] [--forward-on-fail] [-i|-r] [-p [pid_file]] \n"
" %*s [-c [config_file]]\n"
" %*s -q queue_num -o dhcp_option [(-o dhcp_option) ...]\n"
" %s -h|-v\n"
,
programName,
progNameLen, "",
progNameLen, "",
programName
);
}
static void printHelp(void)
{
printUsage();
printf(
"\n"
"%s takes a packet from a netfilter queue, ensures that it is a\n"
"BOOTP/DHCP request, and injects additional DHCP options before\n"
"accepting the packet. The following criteria must be fulfilled for\n"
"%s to touch a packet:\n"
" - The UDP packet must be BOOTP packet with a DHCP cookie\n"
" - The UDP packet must not be fragmented\n"
"\n"
"Packets given to %s's queue are matched against protocol UDP\n"
"and port 67/68. The packet is then assumed to be a BOOTP message. If\n"
"it has the correct DHCP magic cookie value, %s will proceed to\n"
"inject new options (removing existing options if requested). If the\n"
"packet is not deemed a valid DHCP packet, it will be ignored and accepted.\n"
"If it is a valid DHCP packet it cannot be fragmented. If it is, it will\n"
"be dropped.\n"
"\n"
"Options:\n"
"\n"
" -c, --conf-file [file] Specify a different configuration file,\n"
" or skip loading one altogether\n"
" -d, --debug Make %s tell you as much as possible\n"
" about what it does and tries to do\n"
" -f, --foreground Prevent %s from running in the\n"
" background\n"
" --forward-on-fail If the process of injecting options should\n"
" fail, let the unaltered DHCP packet pass\n"
" through. The default behaviour is to drop\n"
" the packet if options could not be injected\n"
" -h, --help Print this help text\n"
" -i, --ignore-existing-opt Proceed if an injected option already exists\n"
" in the original packet. Unless\n"
" --remove-existing-opt is provided, the\n"
" default behaviour is to drop the packet\n"
" -o, --option dhcp_option DHCP option to inject as a hex string,\n"
" where the first byte indicates the option\n"
" code. The option length field is automatically\n"
" calculated and must be omitted. Several\n"
" options may be injected\n"
" -p, --pid-file [file] Write PID to file, using specified path\n"
" or a default sensible location\n"
" -q, --queue queue_num Netfilter queue number to use\n"
" -r, --remove-existing-opt Remove existing DHCP options of the same\n"
" kind as those to be injected\n"
" -v, --version Display version\n"
,
programName,
programName,
programName,
programName,
programName,
programName);
printf(
"\n"
"%s will read %s (or the file specified with\n"
"--conf-file) for options, specified as long option names with values\n"
"separated by \"=\". \"conf-file\" is forbidden in a configuration file.\n"
"Options passed on the command line will override options in the\n"
"configuration file\n"
"\n"
"All the DHCP options specified with the -o/--option flag will be\n"
"added before the terminating option (end option, 255). The packet is\n"
"padded if necessary and sent back to netfilter. The IPv4 header\n"
"checksum is recalculated, but the UDP checksum is set to 0 (disabled).\n"
"None of the added options are checked for whether they are valid, or\n"
"whether the option codes are valid. Options are currently not\n"
"(automatically) padded individually, but they can be manually padded\n"
"by adding options with code 0 (one pad byte per option). This special\n"
"option is the only option that does not have any payload (the end\n"
"option, 255, cannot be manually added). Padding individual options\n"
"should not be necessary.\n"
"\n"
"The option hex string is written as a series of two-digit pairs,\n"
"optionally delimited by one or more non-hexadecimal characters:\n"
"'466A6173','46 6A 61 73', '46:6A:61:73' etc. There is a maximum limit\n"
"of 255 bytes per option, excluding the option code (the first byte)\n"
"and the automatically inserted length byte. At least one option must\n"
"be provided.\n"
"\n"
"If the packet already contains a DHCP option that is to be injected\n"
"(matched by code), the behaviour depends on the command line options\n"
"--ignore-existing-opt and --remove-existing-opt:\n"
" (none) The packet will be dropped\n"
" -i The existing options are ignored and the injected options\n"
" are added\n"
" -r Any existing options are removed and the injected options\n"
" are added.\n"
"\n"
"Note that injected options will not be injected in the same place as\n"
"those that may have been removed if using -r. However, this should not\n"
"matter.\n"
"\n"
"This utility allows you to do things that you probably should not do.\n"
"Be good and leave packets alone.\n"
,
programName,
defaultConfFilePath);
}
static void printVersion(void)
{
printf(
"%s - DHCP option injector, version %s\n"
"Copyright (C) 2015-2019 by Andreas Misje\n"
"\n"
"%s comes with ABSOLUTELY NO WARRANTY. This is free software,\n"
"and you are welcome to redistribute it under certain conditions. See\n"
"the GNU General Public Licence for details.\n",
programName,
DHCPOPTINJ_VERSION,
programName);
}
static int parseQueueNum(const char *string, uint16_t *queueNum)
{
char *lastCh;
long int num = strtol(string, &lastCh, 10);
if (num == LONG_MAX || *lastCh != '\0' || num < 0 || num >= UINT16_MAX)
return 1;
*queueNum = num;
return 0;
}
static void addDHCPOption(struct DHCPOptList *list, const char *string)
{
if (!string)
return;
/* Make room for option code byte and payload */
uint8_t buffer[1 + UINT8_MAX];
size_t length = 0;
for (size_t i = 0; i < strlen(string) && length < sizeof(buffer);)
{
if (isxdigit(string[i]) && sscanf(&string[i], "%2hhx", &buffer[length]) == 1)
{
i += 2;
++length;
}
else
++i;
}
/* Will not happen; the cmd.line parsing code expects an argument: */
if (!length)
return;
if (length > UINT8_MAX)
{
fprintf(stderr, "DHCP option size exceeds the limit of %u bytes\n",
UINT8_MAX);
exit(EXIT_FAILURE);
}
uint16_t optCode = buffer[0];
if (optCode == DHCPOPT_END)
{
fputs("The DHCP end option (255) cannot be manually added", stderr);
exit(EXIT_FAILURE);
}
else if (optCode == DHCPOPT_PAD)
length = 1;
else
{
if (length < 2)
{
fprintf(stderr, "The DHCP option string is too short (payload expected): %s\n",
string);
exit(EXIT_FAILURE);
}
}
if (dhcpOpt_add(list, optCode, buffer + 1, length - 1))
{
fputs("Failed to add DHCP option\n", stderr);
exit(EXIT_FAILURE);
}
}
static void parseConfFile(struct Config *config, const char *filePath, int parseOpts)
{
FILE *file = fopen(filePath, "r");
if (!file && (parseOpts & PARSE_REQUIRE_EXIST))
{
fprintf(stderr, "Failed to open configuration file \"%s\": %s\n",
filePath, strerror(errno));
exit(EXIT_FAILURE);
}
else if (!file)
return;
printf("Parsing configuration file \"%s\"\n", filePath);
unsigned int lineNo = 0;
char line[1024];
while (fgets(line, sizeof(line), file))
{
++lineNo;
{
/* If the comment character '#' is found, terminate the string at
* this position: */
char *commentStart = strchr(line, '#');
if (commentStart)
*commentStart = '\0';
}
char *key = line;
/* Keywords and values are separated by '=': */
char *value = strchr(line, '=');
/* Ensure that the "value" pointer is not at the end of the buffer,
* since we aim to access data past it: */
if (value && value - key < (ptrdiff_t)(sizeof(line) - 1))
{
*value = '\0';
++value;
value = trim(value);
}
key = trim(key);
/* Line is a comment. Do not parse: */
if (!*key)
continue;
int option = parseKeyValue(key, value, filePath, lineNo);
parseOption(config, option, value, SOURCE_FILE);
}
fclose(file);
}
static void parseOption(struct Config *config, int option, char *arg, enum Source source)
{
/* Do not override command line options from configuration file: */
if (source == SOURCE_FILE && optionCount[SOURCE_CMD_LINE][option])
return;
++optionCount[source][option];
switch (option)
{
case OPT_CONF_FILE:
/* An empty argument is allowed, in which case no file is ever loaded
* (including the default one), so do nothing now that optionCount
* has been incremented: */
if (arg)
parseConfFile(config, arg, PARSE_REQUIRE_EXIST);
break;
case OPT_DEBUG:
config->debug = true;
break;
case OPT_FOREGROUND:
config->foreground = true;
break;
case OPT_FORWARD_ON_FAIL:
config->fwdOnFail = true;
break;
case OPT_HELP:
if (source == SOURCE_FILE)
{
fprintf(stderr, "The option \"%s\" doesn't make sense in a configuration "
"file\n", options[option].name);
exit(EXIT_FAILURE);
}
printHelp();
dhcpOpt_destroyList(cmdDHCPOptList);
dhcpOpt_destroyList(fileDHCPOptList);
conf_destroy(config);
exit(EXIT_SUCCESS);
break;
case OPT_IGNORE_EXISTING_OPT:
config->ignoreExistOpt = true;
break;
case OPT_PID_FILE:
if (config->pidFile)
break;
{
const char *src = arg ? arg : defaultPIDFilePath;
size_t pidFilePathLen = strlen(src);
config->pidFile = malloc(pidFilePathLen + 1);
if (!config->pidFile)
{
fputs("Could not allocate space for PID file name\n", stderr);
exit(EXIT_FAILURE);
}
// NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.strcpy)
strcpy(config->pidFile, src);
}
break;
case OPT_OPTION:
addDHCPOption(source == SOURCE_FILE ? fileDHCPOptList : cmdDHCPOptList, arg);
break;
case OPT_QUEUE:
if (!arg || parseQueueNum(arg, &config->queue))
{
fprintf(stderr, "Invalid queue number: %s\n", arg);
printUsage();
exit(EXIT_FAILURE);
}
break;
case OPT_REMOVE_EXISTING_OPT:
config->removeExistOpt = true;
break;
case OPT_VERSION:
if (source == SOURCE_FILE)
{
fprintf(stderr, "The option \"%s\" doesn't make sense in a configuration "
"file\n", options[option].name);
exit(EXIT_FAILURE);
}
printVersion();
dhcpOpt_destroyList(cmdDHCPOptList);
dhcpOpt_destroyList(fileDHCPOptList);
conf_destroy(config);
exit(EXIT_SUCCESS);
break;
default:
/* Only valid options are passed to this function */
break;
}
}
static void validateOptionCombinations(void)
{
for (size_t source = 0; source < sizeof(sources)/sizeof(sources[0]); ++source)
for (size_t option = 0; option < OPT_COUNT; ++option)
/* If an option other than --option is passed more than once, freak out: */
if (optionCount[source][option] > 1 && option != OPT_OPTION)
{
fprintf(stderr, "%s%s can only be %s once\n",
source == SOURCE_CMD_LINE ? "Option --" : "Keyword ",
options[option].name,
source == SOURCE_CMD_LINE ? "passed" : "specified");
printUsage();
exit(EXIT_FAILURE);
}
if (!totalOptionCount(OPT_QUEUE))
{
fputs("Queue number required\n", stderr);
printUsage();
exit(EXIT_FAILURE);
}
if (!totalOptionCount(OPT_OPTION))
{
fputs("At least one DHCP option is required\n", stderr);
printUsage();
exit(EXIT_FAILURE);
}
if (totalOptionCount(OPT_IGNORE_EXISTING_OPT) && totalOptionCount(
OPT_REMOVE_EXISTING_OPT))
{
fprintf(stderr, "Both %s%s and %s%s cannot be used at the same time\n",
optionCount[SOURCE_CMD_LINE][OPT_IGNORE_EXISTING_OPT] ? "--" : "",
options[OPT_IGNORE_EXISTING_OPT].name,
optionCount[SOURCE_CMD_LINE][OPT_REMOVE_EXISTING_OPT] ? "--" : "",
options[OPT_REMOVE_EXISTING_OPT].name);
printUsage();
exit(EXIT_FAILURE);
}
}
static unsigned int totalOptionCount(int option)
{
return optionCount[SOURCE_CMD_LINE][option] + optionCount[SOURCE_FILE][option];
}
static char *trim(char *text)
{
if (!*text)
return text;
/* Trim leading and trailing whitespace and quote characters: */
for (char *ch = text + strlen(text) - 1;
isspace((int)*ch) || *ch == '\'' || *ch == '\"'; *ch-- = '\0');
for (; isspace((int)*text) || *text == '\'' || *text == '\"'; *text++ = '\0');
return text;
}
static int parseKeyValue(const char *key, const char *value, const char *filePath,
unsigned lineNo)
{
for (int option = 0; option < OPT_COUNT; ++option)
{
if (strcmp(key, options[option].name))
continue;
if (options[option].has_arg == required_argument && !value)
{
fprintf(stderr, "Failed to parse \"%s\" at line %u: keyword \"%s\" requires an argument\n",
filePath, lineNo, options[option].name);
exit(EXIT_FAILURE);
}
else if (!options[option].has_arg && value)
{
fprintf(stderr, "Failed to parse \"%s\" at line %u: keyword \"%s\" does not take an argument\n",
filePath, lineNo, options[option].name);
exit(EXIT_FAILURE);
}
return option;
}
fprintf(stderr, "Failed to parse \"%s\" at line %u: \"%s\" is not a valid keyword\n",
filePath, lineNo, key);
exit(EXIT_FAILURE);
return -1;
}
dhcpoptinj-0.5.3/src/config.h 0000664 0000000 0000000 00000003465 13522305640 0016076 0 ustar 00root root 0000000 0000000 /*
* Copyright © 2015–2019 Andreas Misje
*
* This file is part of dhcpoptinj.
*
* dhcpoptinj 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.
*
* dhcpoptinj 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 dhcpoptinj. If not, see .
*/
#ifndef DHCPOPTINJ_CONFIG_H
#define DHCPOPTINJ_CONFIG_H
#include
#include
#include
struct Config
{
/* Do not daemonise */
bool foreground;
/* Print a lot of extra information */
bool debug;
/* Absolute path to PID file, or NULL if writing PID is diabled */
char *pidFile;
/* netfilter queue number */
uint16_t queue;
/* DHCP options to be injected in a serialised format */
uint8_t *dhcpOpts;
/* Size of serialised data */
size_t dhcpOptsSize;
/* List of DHCP option codes to be injected */
uint8_t *dhcpOptCodes;
/* Size of DHCP option code array */
size_t dhcpOptCodeCount;
/* (none): Whine and drop packet
* ignore: Ignore existing options and add new options
* remove: Remove all exisiting options and add new options
*/
bool ignoreExistOpt;
bool removeExistOpt;
/* If option injection should fail, forward/accept packet instead of
* dropping it */
bool fwdOnFail;
};
struct Config *conf_parseOpts(int argc, char * const *argv);
void conf_destroy(struct Config *config);
#endif // DHCPOPTINJ_CONFIG_H
dhcpoptinj-0.5.3/src/dhcp.c 0000664 0000000 0000000 00000014325 13522305640 0015537 0 ustar 00root root 0000000 0000000 /*
* Copyright © 2015–2019 Andreas Misje
*
* This file is part of dhcpoptinj.
*
* dhcpoptinj 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.
*
* dhcpoptinj 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 dhcpoptinj. If not, see .
*/
#include "dhcp.h"
const char *dhcp_msgTypeString(uint8_t msgType)
{
switch (msgType)
{
case 1:
return "DHCPDISCOVER";
case 2:
return "DHCPOFFER";
case 3:
return "DHCPREQUEST";
case 4:
return "DHCPDECLINE";
case 5:
return "DHCPACK";
case 6:
return "DHCPNAK";
case 7:
return "DHCPRELEASE";
case 8:
return "DHCPINFORM";
default:
return "??";
}
}
const char *dhcp_optionString(uint8_t option)
{
// From https://www.iana.org/assignments/bootp-dhcp-parameters/bootp-dhcp-parameters.xhtml
static const char * const names[] =
{
[0] = "Pad",
[1] = "Subnet Mask",
[2] = "Time Offset",
[3] = "Router",
[4] = "Time Server",
[5] = "Name Server",
[6] = "Domain Server",
[7] = "Log Server",
[8] = "Quotes Server",
[9] = "LPR Server",
[10] = "Impress Server",
[11] = "RLP Server",
[12] = "Hostname",
[13] = "Boot File Size",
[14] = "Merit Dump File",
[15] = "Domain Name",
[16] = "Swap Server",
[17] = "Root Path",
[18] = "Extension File",
[19] = "Forward On/Off",
[20] = "SrcRte On/Off",
[21] = "Policy Filter",
[22] = "Max DG Assembly",
[23] = "Default IP TTL",
[24] = "MTU Timeout",
[25] = "MTU Plateau",
[26] = "MTU Interface",
[27] = "MTU Subnet",
[28] = "Broadcast Address",
[29] = "Mask Discovery",
[30] = "Mask Supplier",
[31] = "Router Discovery",
[32] = "Router Request",
[33] = "Static Route",
[34] = "Trailers",
[35] = "ARP Timeout",
[36] = "Ethernet",
[37] = "Default TCP TTL",
[38] = "Keepalive Time",
[39] = "Keepalive Data",
[40] = "NIS Domain",
[41] = "NIS Servers",
[42] = "NTP Servers",
[43] = "Vendor Specific",
[44] = "NETBIOS Name Srv",
[45] = "NETBIOS Dist Srv",
[46] = "NETBIOS Node Type",
[47] = "NETBIOS Scope",
[48] = "X Window Font",
[49] = "X Window Manager",
[50] = "Address Request",
[51] = "Address Time",
[52] = "Overload",
[53] = "DHCP Msg Type",
[54] = "DHCP Server Id",
[55] = "Parameter List",
[56] = "DHCP Message",
[57] = "DHCP Max Msg Size",
[58] = "Renewal Time",
[59] = "Rebinding Time",
[60] = "Class Id",
[61] = "Client Id",
[62] = "NetWare/IP Domain",
[63] = "NetWare/IP Option",
[64] = "NIS-Domain-Name",
[65] = "NIS-Server-Addr",
[66] = "Server-Name",
[67] = "Bootfile-Name",
[68] = "Home-Agent-Addrs",
[69] = "SMTP-Server",
[70] = "POP3-Server",
[71] = "NNTP-Server",
[72] = "WWW-Server",
[73] = "Finger-Server",
[74] = "IRC-Server",
[75] = "StreetTalk-Server",
[76] = "STDA-Server",
[77] = "User-Class",
[78] = "Directory Agent",
[79] = "Service Scope",
[80] = "Rapid Commit",
[81] = "Client FQDN",
[82] = "Relay Agent Information",
[83] = "iSNS",
// 84 removed/unassigned
[85] = "NDS Servers",
[86] = "NDS Tree Name",
[87] = "NDS Context",
[88] = "BCMCS Controller Domain Name list",
[89] = "BCMCS Controller IPv4 address option",
[90] = "Authentication",
[91] = "client-last-transaction-time option",
[92] = "associated-ip option",
[93] = "Client System",
[94] = "Client NDI",
[95] = "LDAP",
// 96 removed/unassigned
[97] = "UUID/GUID",
[98] = "User-Auth",
[99] = "GEOCONF_CIVIC",
[100] = "PCode",
[101] = "TCode",
// 102–108 removed/unassigned
[109] = "OPTION_DHCP4O6_S46_SADDR",
// 110 removed/unassigned
// 111 removed/unassigned
[112] = "Netinfo Address",
[113] = "Netinfo Tag",
[114] = "URL",
// 115 removed/unassigned
[116] = "Auto-Config",
[117] = "Name Service Search",
[118] = "Subnet Selection Option",
[119] = "Domain Search",
[120] = "SIP Servers DHCP Option",
[121] = "Classless Static Route Option",
[122] = "CCC",
[123] = "GeoConf Option",
[124] = "V-I Vendor Class",
[125] = "V-I Vendor-Specific Information",
// 126 removed/unassigned
// 127 removed/unassigned
[128] = "PXE / Etherboot signature",
[129] = "PXE / Kernel options / Call Server IP address",
[130] = "PXE / Ethernet interface / Discrimination string",
[131] = "PXE / Remote statistics server IP address",
[132] = "PXE",
[133] = "PXE",
[134] = "PXE",
[135] = "PXE / HTTP Proxy for phone-specific applications",
[136] = "OPTION_PANA_AGENT",
[137] = "OPTION_V4_LOST",
[138] = "OPTION_CAPWAP_AC_V4",
[139] = "OPTION-IPv4_Address-MoS",
[140] = "OPTION-IPv4_FQDN-MoS",
[141] = "SIP UA Configuration Service Domains",
[142] = "OPTION-IPv4_Address-ANDSF",
[143] = "OPTION_V4_SZTP_REDIRECT",
[144] = "GeoLoc",
[145] = "FORCERENEW_NONCE_CAPABLE",
[146] = "RDNSS Selection",
// 147–149 unassigned
[150] = "TFTP server address / Etherboot / GRUB configuration path name",
[151] = "status-code",
[152] = "base-time",
[153] = "start-time-of-state",
[154] = "query-start-time",
[155] = "query-end-time",
[156] = "dhcp-state",
[157] = "data-source",
[158] = "OPTION_V4_PCP_SERVER",
[159] = "OPTION_V4_PORTPARAMS",
[160] = "DHCP Captive-Portal",
[161] = "OPTION_MUD_URL_V4",
// 162–174 unassigned
[175] = "Etherboot",
[176] = "IP Telephone",
[177] = "Etherboot / PacketCable and CableHome",
// 178–207 unassigned
[208] = "PXELINUX Magic",
[209] = "Configuration File",
[210] = "Path Prefix",
[211] = "Reboot Time",
[212] = "OPTION_6RD",
[213] = "OPTION_V4_ACCESS_DOMAIN",
// 214–219 unassigned
[220] = "Subnet Allocation Option",
[221] = "Virtual Subnet Selection (VSS) Option",
// 222–223 unassigned
// 224–254 reserved
[255] = "End",
};
return names[option] ? names[option] : "(unassigned/reserved)";
}
dhcpoptinj-0.5.3/src/dhcp.h 0000664 0000000 0000000 00000002736 13522305640 0015547 0 ustar 00root root 0000000 0000000 /*
* Copyright © 2015–2019 Andreas Misje
*
* This file is part of dhcpoptinj.
*
* dhcpoptinj 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.
*
* dhcpoptinj 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 dhcpoptinj. If not, see .
*/
#ifndef DHCPOPTINJ_DHCP_H
#define DHCPOPTINJ_DHCP_H
#include
#define DHCP_MAGIC_COOKIE 0x63825363
#define DHCPOPT_PAD 0
#define DHCPOPT_END 0xff
#define DHCPOPT_TYPE 0x35
#pragma pack(4)
struct BootP
{
uint8_t op;
uint8_t hwAddrType;
uint8_t hwAddrLen;
uint8_t hops;
uint32_t xID;
uint16_t secs;
uint16_t flags;
uint32_t clientAddr;
uint32_t ownAddr;
uint32_t serverAddr;
uint32_t gwAddr;
uint8_t clientHwAddr[16];
uint8_t serverName[64];
uint8_t file[128];
uint32_t cookie;
// options …
};
#pragma pack()
#pragma pack(1)
struct DHCPOption
{
uint8_t code;
uint8_t length;
uint8_t data[];
};
#pragma pack()
const char *dhcp_msgTypeString(uint8_t msgType);
const char *dhcp_optionString(uint8_t option);
#endif // DHCPOPTINJ_DHCP_H
dhcpoptinj-0.5.3/src/dhcpoptinj.c 0000664 0000000 0000000 00000047341 13522305640 0016767 0 ustar 00root root 0000000 0000000 /*
* Copyright © 2015–2019 Andreas Misje
*
* This file is part of dhcpoptinj.
*
* dhcpoptinj 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.
*
* dhcpoptinj 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 dhcpoptinj. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "config.h"
#include
#include
#include
#include
#include
#include "ipv4.h"
#include "udp.h"
#include "dhcp.h"
#include
#define MIN_BOOTP_SIZE 300
#pragma pack(1)
struct Packet
{
struct IPv4Header ipHeader;
struct UDPHeader udpHeader;
struct BootP bootp;
};
#pragma pack()
enum MangleResult
{
Mangle_OK = 0,
Mangle_mallocFail,
Mangle_optExists,
};
/* Somewhat arbitrary, feel free to change */
#define MAX_PACKET_SIZE 2048
/* The netfilter queue length 20 is also arbitrary. Hopefully it is
* sufficient. */
static const uint32_t maxQueueLen = 20;
static struct Config *config;
static bool daemonised;
static sig_atomic_t escapeMainLoop;
static sig_atomic_t signalCaught;
static int inspectPacket(struct nfq_q_handle *queue, struct nfgenmsg *pktInfo,
struct nfq_data *pktData, void *userData);
static bool packetIsComplete(const uint8_t *data, size_t size);
static bool packetIsDHCP(const uint8_t *data);
/* Inject DHCP options into DHCP packet */
static enum MangleResult manglePacket(const uint8_t *origData, size_t origDataSize,
uint8_t **newData, size_t *newDataSize);
static enum MangleResult mangleOptions(const uint8_t *origData, size_t origDataSize,
uint8_t *newData, size_t *newDataSize);
/* Write a message to syslog or standard stream, depending on whether the
* process is run as a daemon or not */
static void logMessage(int priority, const char *format, ...);
static void simplifyProgramName(char *programName);
static void writePID(void);
static void removePIDFile(void);
static void destroyConfig(void);
static void initSignalHandler(void);
static void setEscapeMainLoopFlag(int signal);
static void initLog(const char *programName);
/* Debug-print all options to inject */
static void debugLogOptions(void);
/* Very simple check of the provided option codes, warning user if something
* looks incorrect */
static void inspectOptions(void);
/* Debug-print packet header */
static void debugLogPacketHeader(const uint8_t *data, size_t size);
/* Debug-print packet's existing DHCP options */
static void debugLogOptionFound(const struct DHCPOption *option);
static void debugLogOption(const char *action, const struct DHCPOption *option);
static void debugLogInjectedOptions(void);
int main(int argc, char *argv[])
{
simplifyProgramName(argv[0]);
config = conf_parseOpts(argc, argv);
initLog(argv[0]);
debugLogOptions();
inspectOptions();
logMessage(LOG_DEBUG, "Initialising netfilter queue\n");
struct nfq_handle *nfq = nfq_open();
if (!nfq)
{
/* Most likely causes are insufficient permissions (missing
* CAP_NET_ADMIN capability) or an another process already bound to the
* same queue. */
logMessage(LOG_ERR, "Failed to initialise netfilter queue library: %s\n",
strerror(errno));
exit(EXIT_FAILURE);
}
nfq_unbind_pf(nfq, AF_INET);
if (nfq_bind_pf(nfq, AF_INET) < 0)
{
logMessage(LOG_ERR, "Failed to bind queue handler to AF_INET: %s\n",
strerror(errno));
exit(EXIT_FAILURE);
}
struct nfq_q_handle *queue = nfq_create_queue(nfq, config->queue, &inspectPacket,
NULL);
if (!queue)
{
logMessage(LOG_ERR, "Failed to create netfilter queue for queue %d: %s\n",
config->queue, strerror(errno));
exit(EXIT_FAILURE);
}
if (nfq_set_mode(queue, NFQNL_COPY_PACKET, MAX_PACKET_SIZE) < 0)
{
logMessage(LOG_ERR, "Failed to set netfilter queue mode: %s\n", strerror(
errno));
exit(EXIT_FAILURE);
}
if (nfq_set_queue_maxlen(queue, maxQueueLen) < 0)
{
logMessage(LOG_ERR, "Failed to set netfilter queue length: %s\n", strerror(
errno));
exit(EXIT_FAILURE);
}
if (!config->foreground)
{
logMessage(LOG_DEBUG, "Daemonising\n");
if (daemon(false, false))
{
logMessage(LOG_ERR, "Failed to daemonise: daemon() failed: %s\n",
strerror(errno));
exit(EXIT_FAILURE);
}
umask(022);
daemonised = true;
}
initSignalHandler();
writePID();
if (config->debug)
logMessage(LOG_DEBUG, "Initialisation completed. Waiting for packets to "
"mangle on queue %" PRIu16 "\n", config->queue);
else
logMessage(LOG_INFO, "Started\n");
int exitCode = EXIT_SUCCESS;
int queueFd = nfq_fd(nfq);
for (; !escapeMainLoop; )
{
char packet[MAX_PACKET_SIZE] __attribute__((aligned));
ssize_t bytes = recv(queueFd, packet, sizeof(packet), 0);
if (bytes < -1)
{
logMessage(LOG_ERR, "Failed to retrieve packet: %s\n", strerror(errno));
exitCode = EXIT_FAILURE;
break;
}
else if (bytes > 0)
{
logMessage(LOG_DEBUG, "Received %zd bytes\n", bytes);
if (nfq_handle_packet(nfq, packet, bytes))
logMessage(LOG_WARNING, "Failed to handle packet: %s\n", strerror(errno));
}
}
if (signalCaught)
{
const char *signalName =
signalCaught == SIGINT ? "SIGINT" :
signalCaught == SIGTERM ? "SIGTERM" :
signalCaught == SIGHUP ? "SIGHUP" : "??";
logMessage(LOG_NOTICE, "Caught signal %s\n", signalName);
}
logMessage(LOG_DEBUG, "Destroying netfilter queue\n");
nfq_destroy_queue(queue);
/* According to libnetfilter_queue's nfqnl_test.c example, nfq_unbind_pf(…)
* should NOT be called during clean up. */
nfq_close(nfq);
logMessage(LOG_NOTICE, "Exiting\n");
removePIDFile();
destroyConfig();
return exitCode;
}
static int inspectPacket(struct nfq_q_handle *queue, struct nfgenmsg *pktInfo,
struct nfq_data *pktData, void *userData)
{
(void)pktInfo;
(void)userData;
uint8_t *packet;
ssize_t size = nfq_get_payload(pktData, &packet);
if (size < 0)
{
logMessage(LOG_WARNING, "Failed to retrieve packet from queue: %s\n",
strerror(errno));
return 1;
}
struct nfqnl_msg_packet_hdr *metaHeader = nfq_get_msg_packet_hdr(pktData);
if (!packetIsComplete(packet, (size_t)size))
{
logMessage(LOG_INFO, "Dropping the packet because it is incomplete\n");
return nfq_set_verdict(queue, ntohl(metaHeader->packet_id), NF_DROP, 0, NULL);
}
if (!packetIsDHCP(packet))
{
logMessage(LOG_DEBUG, "Ignoring non-DHCP packet\n");
return nfq_set_verdict(queue, ntohl(metaHeader->packet_id), NF_ACCEPT, 0, NULL);
}
/* We do not have the logic needed to support fragmented packets: */
if (ipv4_packetFragmented(&((const struct Packet *)packet)->ipHeader))
{
uint32_t verdict = config->fwdOnFail ? NF_ACCEPT : NF_DROP;
if (config->fwdOnFail)
logMessage(LOG_INFO, "Ignoring fragmented packet\n");
else
logMessage(LOG_INFO, "Dropping the packet because it is fragmented\n");
return nfq_set_verdict(queue, ntohl(metaHeader->packet_id), verdict, 0, NULL);
}
if (config->debug)
debugLogPacketHeader(packet, (size_t)size);
logMessage(LOG_INFO, "Mangling packet\n");
uint8_t *mangledData = NULL;
size_t mangledDataSize = 0;
enum MangleResult result = manglePacket(packet, (size_t)size, &mangledData,
&mangledDataSize);
if (result == Mangle_mallocFail)
{
logMessage(LOG_WARNING, "Failed to allocate memory for mangled packet\n");
uint32_t verdict = config->fwdOnFail ? NF_ACCEPT : NF_DROP;
return nfq_set_verdict(queue, ntohl(metaHeader->packet_id), verdict, 0, NULL);
}
else if (result == Mangle_optExists)
{
logMessage(LOG_INFO, "Dropping the packet because option already exists\n");
return nfq_set_verdict(queue, ntohl(metaHeader->packet_id), NF_DROP, 0, NULL);
}
else if (result != Mangle_OK)
{
logMessage(LOG_ERR, "Internal error: unexpected return value from manglePacket(): %d\n",
result);
uint32_t verdict = config->fwdOnFail ? NF_ACCEPT : NF_DROP;
return nfq_set_verdict(queue, ntohl(metaHeader->packet_id), verdict, 0, NULL);
}
if (config->debug)
logMessage(LOG_DEBUG, "Sending mangled packet\n");
int res = nfq_set_verdict(queue, ntohl(metaHeader->packet_id), NF_ACCEPT,
mangledDataSize, mangledData);
free(mangledData);
return res;
}
static bool packetIsComplete(const uint8_t *data, size_t size)
{
if (size < sizeof(struct IPv4Header))
return false;
const struct Packet *packet = (const struct Packet *)data;
return packet->ipHeader.totalLen >= sizeof(*packet);
}
static bool packetIsDHCP(const uint8_t *data)
{
const struct Packet *packet = (const struct Packet *)data;
if (packet->ipHeader.protocol != IPPROTO_UDP)
return false;
uint16_t destPort = ntohs(packet->udpHeader.destPort);
if (!(destPort == 67 || destPort == 68))
return false;
if (packet->udpHeader.length < sizeof(struct UDPHeader) + sizeof(struct BootP))
return false;
const struct BootP *dhcp = &packet->bootp;
if (ntohl(dhcp->cookie) != DHCP_MAGIC_COOKIE)
return false;
return true;
}
static enum MangleResult manglePacket(const uint8_t *origData, size_t origDataSize,
uint8_t **newData, size_t *newDataSize)
{
const struct Packet *origPacket = (const struct Packet *)origData;
size_t ipHdrSize = ipv4_headerLen(&origPacket->ipHeader);
size_t udpHdrSize = sizeof(struct UDPHeader);
size_t headersSize = ipHdrSize + udpHdrSize + sizeof(struct BootP);
/* Allocate size for a new packet, slightly larger than needed in order to
* avoid reallocation.: */
*newDataSize = origDataSize + config->dhcpOptsSize + 1; /* room for padding */
size_t newPayloadSize = *newDataSize - ipHdrSize - udpHdrSize;
/* Ensure that the DHCP packet (the BOOTP header and payload) is at least
* MIN_BOOTP_SIZE bytes long (as per the RFC 1542 requirement): */
if (newPayloadSize < MIN_BOOTP_SIZE)
*newDataSize += MIN_BOOTP_SIZE - newPayloadSize;
*newData = malloc(*newDataSize);
if (!*newData)
return Mangle_mallocFail;
/* Copy 'static' data (everything but the DHCP options) from original
* packet: */
memcpy(*newData, origPacket, headersSize);
enum MangleResult result = mangleOptions(origData, origDataSize, *newData,
newDataSize);
if (result != Mangle_OK)
{
free(*newData);
return result;
}
/* Recalculate actual size (and potential padding) after mangling options
* (the initially calculated size is possibly slightly too large, since it
* could not forsee how many bytes of DHCP options that was going to be
* removed; however, the header size fields need to be correct): */
newPayloadSize = *newDataSize - ipHdrSize - udpHdrSize;
size_t padding = (2 - (newPayloadSize % 2)) % 2;
if (newPayloadSize < MIN_BOOTP_SIZE)
padding = MIN_BOOTP_SIZE - newPayloadSize;
newPayloadSize += padding;
*newDataSize = ipHdrSize + udpHdrSize + newPayloadSize;
struct Packet *newPacket = (struct Packet *)*newData;
struct IPv4Header *ipHeader = &newPacket->ipHeader;
ipHeader->totalLen = htons(*newDataSize);
ipHeader->checksum = 0;
ipHeader->checksum = ipv4_checksum(ipHeader);
struct UDPHeader *udpHeader = &newPacket->udpHeader;
udpHeader->length = htons(udpHdrSize + newPayloadSize);
udpHeader->checksum = 0;
if (padding && config->debug)
logMessage(LOG_DEBUG, "Padding with %zu byte(s) to meet minimal BOOTP payload "
"size\n", padding);
/* Pad to (at least) MIN_BOOTP_SIZE bytes: */
for (size_t i = *newDataSize - padding; i < *newDataSize; ++i)
(*newData)[i] = DHCPOPT_PAD;
return Mangle_OK;
}
static enum MangleResult mangleOptions(const uint8_t *origData, size_t origDataSize,
uint8_t *newData, size_t *newDataSize)
{
/* Start with position of the first DHCP option: */
size_t origOffset = offsetof(struct Packet, bootp) + sizeof(struct BootP);
size_t newOffset = origOffset;
size_t padCount = 0;
while (origOffset < origDataSize)
{
const struct DHCPOption *option = (const struct DHCPOption *)(origData + origOffset);
size_t optSize =
option->code == DHCPOPT_PAD || option->code == DHCPOPT_END ? 1
: sizeof(struct DHCPOption) + option->length;
if (config->debug)
{
if (option->code == DHCPOPT_PAD)
++padCount;
else
{
if (padCount)
logMessage(LOG_DEBUG, "Found %zu PAD options (removing)\n", padCount);
debugLogOptionFound(option);
padCount = 0;
}
}
if (option->code == DHCPOPT_END)
break;
/* If existing options are to be ignored and not removed, just copy
* them: */
else if (config->ignoreExistOpt && !config->removeExistOpt)
{
if (config->debug)
logMessage(LOG_DEBUG, " (copying)\n");
memcpy(newData + newOffset, option, optSize);
newOffset += optSize;
}
/* Otherwise we need to check whether one of the injected options are
* already present: */
else
{
bool optFound = false;
if (option->code != DHCPOPT_END)
for (size_t i = 0; i < config->dhcpOptCodeCount; ++i)
if (option->code == config->dhcpOptCodes[i])
{
optFound = true;
break;
}
/* If the option already exists in original payload, but is not to be
* removed, and ignore command line option is not provided, drop
* packet: */
if (optFound && !config->removeExistOpt && !config->ignoreExistOpt)
{
if (config->debug)
logMessage(LOG_DEBUG, " (conflict)\n");
return Mangle_optExists;
}
/* Copy option if it is not to be removed: */
else if ((optFound && !config->removeExistOpt) || !optFound)
{
if (config->debug)
logMessage(LOG_DEBUG, " (copying)\n");
memcpy(newData + newOffset, option, optSize);
newOffset += optSize;
}
else if (config->debug)
logMessage(LOG_DEBUG, " (removing)\n");
}
origOffset += optSize;
}
if (config->debug)
debugLogInjectedOptions();
/* Inject DHCP options: */
for (size_t i = 0; i < config->dhcpOptsSize; ++i)
newData[newOffset + i] = config->dhcpOpts[i];
newOffset += config->dhcpOptsSize;
if (config->debug)
logMessage(LOG_DEBUG, "Inserting END option\n");
/* Finally insert the END option: */
newData[newOffset++] = DHCPOPT_END;
/* Update (reduce) packet size: */
*newDataSize = newOffset;
return Mangle_OK;
}
/* Instruct clang that "format" is a printf-style format parameter to avoid
* non-literal format string warnings in clang: */
__attribute__((__format__ (__printf__, 2, 0)))
static void logMessage(int priority, const char *format, ...)
{
if (priority == LOG_DEBUG && !config->debug)
return;
va_list args1, args2;
va_start(args1, format);
va_copy(args2, args1);
if (config->foreground || !daemonised)
{
FILE *f = stderr;
if (priority == LOG_NOTICE || priority == LOG_INFO || priority == LOG_DEBUG)
f = stdout;
/* NOLINTNEXTLINE(clang-analyzer-valist.Uninitialized) */
vfprintf(f, format, args1);
}
va_end(args1);
if (!config->foreground)
vsyslog(priority, format, args2);
va_end(args2);
}
static void simplifyProgramName(char *programName)
{
char *simplifiedName = basename(programName);
size_t len = strlen(simplifiedName);
memmove(programName, simplifiedName, len);
programName[len] = '\0';
}
static void writePID(void)
{
if (!config->pidFile)
return;
pid_t pid = getpid();
logMessage(LOG_DEBUG, "Writing PID %ld to %s\n", (long)pid, config->pidFile);
FILE *f = fopen(config->pidFile, "w");
if (!f)
{
logMessage(LOG_ERR, "Failed to write PID to %s: %s\n", config->pidFile,
strerror(errno));
exit(EXIT_FAILURE);
}
fprintf(f, "%ld", (long)pid);
fclose(f);
}
static void removePIDFile(void)
{
if (config->pidFile)
{
logMessage(LOG_DEBUG, "Removing PID file %s\n", config->pidFile);
unlink(config->pidFile);
}
}
static void destroyConfig(void)
{
conf_destroy(config);
}
static void initSignalHandler(void)
{
logMessage(LOG_DEBUG, "Initialising signal handler\n");
struct sigaction sigAction = { .sa_handler = &setEscapeMainLoopFlag };
if (sigaction(SIGTERM, &sigAction, NULL) || sigaction(SIGINT, &sigAction, NULL) ||
sigaction(SIGHUP, &sigAction, NULL))
{
logMessage(LOG_ERR, "Failed to initialise signal handler: %s\n", strerror(
errno));
exit(EXIT_FAILURE);
}
}
static void setEscapeMainLoopFlag(int signal)
{
signalCaught = signal;
escapeMainLoop = true;
}
static void initLog(const char *programName)
{
openlog(programName, 0, LOG_DAEMON);
if (config->debug)
setlogmask(LOG_UPTO(LOG_DEBUG));
else
setlogmask(LOG_UPTO(LOG_INFO));
}
static void debugLogOptions(void)
{
if (!config->debug)
return;
logMessage(LOG_DEBUG, "%zu DHCP option(s) to inject (with a total of %zu bytes): ",
config->dhcpOptCodeCount, config->dhcpOptsSize);
for (size_t i = 0; i < config->dhcpOptCodeCount; ++i)
{
uint8_t code = config->dhcpOptCodes[i];
bool atEnd = i == config->dhcpOptCodeCount - 1;
const char *delim = atEnd ? "\n" : ", ";
logMessage(LOG_DEBUG, "%u (0x%02X) (%s)%s", code, code, dhcp_optionString(
code), delim);
}
logMessage(LOG_DEBUG, "Existing options will be %s\n", config->removeExistOpt ?
"removed" : "left in place");
}
static void inspectOptions(void)
{
size_t nonSpecialOptCount = 0;
for (size_t i = 0; i < config->dhcpOptCodeCount; ++i)
{
uint8_t code = config->dhcpOptCodes[i];
if (code != DHCPOPT_PAD && code != DHCPOPT_END)
++nonSpecialOptCount;
}
if (!nonSpecialOptCount)
logMessage(LOG_WARNING, "Warning: Only padding options added\n");
}
static void debugLogPacketHeader(const uint8_t *data, size_t size)
{
const struct Packet *packet = (const struct Packet *)data;
const uint8_t *mac = packet->bootp.clientHwAddr;
struct IPAddr
{
uint8_t o1;
uint8_t o2;
uint8_t o3;
uint8_t o4;
} __attribute__((packed));
const struct IPAddr *destIP = (const struct IPAddr *)&packet->ipHeader.destAddr;
logMessage(LOG_DEBUG, "Inspecting %zu-byte DHCP packet from "
"%02X:%02X:%02X:%02X:%02X:%02X to %d.%d.%d.%d:%d\n",
size,
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5],
destIP->o1, destIP->o2, destIP->o3, destIP->o4,
ntohs(packet->udpHeader.destPort)
);
}
static void debugLogOptionFound(const struct DHCPOption *option)
{
if (option->code == DHCPOPT_PAD)
return;
else if (option->code == DHCPOPT_END)
logMessage(LOG_DEBUG,"Found END option %s\n", config->dhcpOptCodeCount ?
"(removing)" : "(copying)");
else if (option->code == DHCPOPT_TYPE && option->length == 1)
logMessage(LOG_DEBUG, "Found option % 3hhd (0x%02hhX) (DHCP message type) %s",
option->code, option->code, dhcp_msgTypeString(option->data[0]));
else
debugLogOption("Found", option);
}
static void debugLogOption(const char *action, const struct DHCPOption *option)
{
/* String buffer for hex string (maximum DHCP option length (255) times
* three characters (two digits and a space)) */
char optPayload[UINT8_MAX * 3];
size_t i = 0;
for (; i < option->length; ++i)
sprintf(optPayload + 3*i, "%02X ", option->data[i]);
/* Remove last space: */
if (i)
optPayload[3*i - 1] = '\0';
const char *optName = dhcp_optionString(option->code);
size_t optNameLen = strlen(optName);
const size_t alignedWidth = 24;
logMessage(LOG_DEBUG, "%s option % 3hhd (0x%02hhX) (%s)%*s with % 3d-byte payload %s",
action,
option->code,
option->code,
optName,
(int)(optNameLen > alignedWidth ? 0 : alignedWidth - optNameLen),
"",
option->length,
optPayload);
}
static void debugLogInjectedOptions(void)
{
for (size_t offset = 0; offset < config->dhcpOptsSize;)
{
const struct DHCPOption *option = (const struct DHCPOption *)(&config->dhcpOpts[offset]);
debugLogOption("Injecting", option);
logMessage(LOG_DEBUG, "%s", "\n");
offset += option->code == DHCPOPT_PAD || option->code == DHCPOPT_END ? 1
: sizeof(struct DHCPOption) + option->length;
}
}
dhcpoptinj-0.5.3/src/ipv4.c 0000664 0000000 0000000 00000002766 13522305640 0015511 0 ustar 00root root 0000000 0000000 /*
* Copyright © 2015–2019 Andreas Misje
*
* This file is part of dhcpoptinj.
*
* dhcpoptinj 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.
*
* dhcpoptinj 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 dhcpoptinj. If not, see .
*/
#include "ipv4.h"
#include
#include
uint16_t ipv4_checksum(const struct IPv4Header *ipv4Header)
{
const uint16_t *data = (const uint16_t *)ipv4Header;
size_t len = sizeof(*ipv4Header);
uint32_t checksum = 0;
while (len > 1)
{
checksum += *data++;
len -= 2;
}
if (len > 0)
checksum += *(const uint8_t *)data;
while (checksum >> 16)
checksum = (checksum & 0xffff) + (checksum >> 16);
return ~checksum;
}
size_t ipv4_headerLen(const struct IPv4Header *ipHeader)
{
return (ipHeader->verIHL & 0xf) * 4U;
}
bool ipv4_packetFragmented(const struct IPv4Header *ipHeader)
{
uint16_t field = ntohs(ipHeader->flagsFrag);
bool fragmentsToCome = (field >> 13) & 4;
uint16_t fragmentOffset = field & 0x1fff;
return fragmentsToCome || fragmentOffset;
}
dhcpoptinj-0.5.3/src/ipv4.h 0000664 0000000 0000000 00000002426 13522305640 0015507 0 ustar 00root root 0000000 0000000 /*
* Copyright © 2015–2019 Andreas Misje
*
* This file is part of dhcpoptinj.
*
* dhcpoptinj 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.
*
* dhcpoptinj 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 dhcpoptinj. If not, see .
*/
#ifndef DHCPOPTINJ_IPV4_H
#define DHCPOPTINJ_IPV4_H
#include
#include
#include
#pragma pack(2)
struct IPv4Header
{
uint8_t verIHL;
uint8_t dscpECN;
uint16_t totalLen;
uint16_t id;
uint16_t flagsFrag;
uint8_t ttl;
uint8_t protocol;
uint16_t checksum;
uint32_t sourceAddr;
uint32_t destAddr;
};
#pragma pack()
uint16_t ipv4_checksum(const struct IPv4Header *ipv4Header);
size_t ipv4_headerLen(const struct IPv4Header *ipv4Header);
bool ipv4_packetFragmented(const struct IPv4Header *ipHeader);
#endif // DHCPOPTINJ_IPV4_H
dhcpoptinj-0.5.3/src/options.c 0000664 0000000 0000000 00000007632 13522305640 0016317 0 ustar 00root root 0000000 0000000 /*
* Copyright © 2015–2019 Andreas Misje
*
* This file is part of dhcpoptinj.
*
* dhcpoptinj 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.
*
* dhcpoptinj 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 dhcpoptinj. If not, see .
*/
#include "options.h"
#include
#include
#include "dhcp.h"
/* Just like struct DHCPOption in dhcp.h, but with (fixed) storage for option
* payload) */
struct DHCPOpt
{
uint8_t code;
uint8_t length;
uint8_t data[UINT8_MAX];
};
struct DHCPOptList
{
struct DHCPOpt *options;
size_t count;
size_t capacity;
};
static int resizeList(struct DHCPOptList *list);
/* Total number of bytes needed to serialise list */
static size_t totalSize(const struct DHCPOptList *list);
struct DHCPOptList *dhcpOpt_createList(void)
{
struct DHCPOptList *list = malloc(sizeof(*list));
*list = (struct DHCPOptList){0};
if (resizeList(list))
{
dhcpOpt_destroyList(list);
return NULL;
}
return list;
}
void dhcpOpt_destroyList(struct DHCPOptList *list)
{
free(list->options);
free(list);
}
bool dhcpOpt_optExists(const struct DHCPOptList *list, int code)
{
for (size_t i = 0; i < list->count; ++i)
if (code == list->options[i].code)
return true;
return false;
}
int dhcpOpt_add(struct DHCPOptList *list, int code, const void *data, size_t size)
{
if (resizeList(list))
return 1;
struct DHCPOpt *opt = &list->options[list->count];
opt->code = code;
opt->length = size;
if (data && size)
memcpy(opt->data, data, size);
++list->count;
return 0;
}
size_t dhcpOpt_count(struct DHCPOptList *list)
{
return list->count;
}
int dhcpOpt_serialise(const struct DHCPOptList *list, uint8_t **buffer, size_t *size)
{
*size = totalSize(list);
if (!*size)
return 1;
*buffer = malloc(*size);
if (!*buffer)
{
*size = 0;
return 1;
}
size_t bufI = 0;
for (size_t optI = 0; optI < list->count; ++optI)
{
struct DHCPOpt *opt = &list->options[optI];
(*buffer)[bufI++] = opt->code;
/* Only copy option length and payload if it actually has a payload (the
* special options 'pad' and 'end' are one-byte options) */
if (opt->code != DHCPOPT_PAD && opt->code != DHCPOPT_END)
{
(*buffer)[bufI++] = opt->length;
for (size_t optDataI = 0; optDataI < opt->length; ++optDataI)
(*buffer)[bufI++] = opt->data[optDataI];
}
}
return 0;
}
int dhcpOpt_optCodes(const struct DHCPOptList *list, uint8_t **buffer, size_t *size)
{
*size = list->count;
*buffer = malloc(*size);
if (!*buffer)
{
*size = 0;
return 1;
}
for (size_t i = 0; i < list->count; ++i)
(*buffer)[i] = list->options[i].code;
return 0;
}
static int resizeList(struct DHCPOptList *list)
{
if (list->count < list->capacity)
return 0;
/* Inital capacity of 24 options somewhat arbitrary, but should be
* sufficient for most cases */
size_t newCapacity = list->capacity ? list->capacity * 2 : 24;
struct DHCPOpt *newOptList = realloc(list->options, newCapacity * sizeof(
struct DHCPOpt));
if (!newOptList)
return 1;
list->options = newOptList;
list->capacity = newCapacity;
return 0;
}
static size_t totalSize(const struct DHCPOptList *list)
{
size_t size = 0;
for (size_t i = 0; i < list->count; ++i)
{
struct DHCPOpt *opt = &list->options[i];
/* The special options 'pad' and 'end' are only one byte long, whilst
* other options are minimum two bytes long */
if (opt->code == DHCPOPT_PAD || opt->code == DHCPOPT_END)
++size;
else
size += 2U + list->options[i].length;
}
return size;
}
dhcpoptinj-0.5.3/src/options.h 0000664 0000000 0000000 00000003306 13522305640 0016316 0 ustar 00root root 0000000 0000000 /*
* Copyright © 2015–2019 Andreas Misje
*
* This file is part of dhcpoptinj.
*
* dhcpoptinj 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.
*
* dhcpoptinj 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 dhcpoptinj. If not, see .
*/
/* This is a small help module for creating and extending a list of DHCP
* options. When finished, the list can be serialised to a buffer and added to
* a BOOTP packet, completing a DHCP request.
*/
#ifndef DHCPOPTINJ_OPTIONS_H
#define DHCPOPTINJ_OPTIONS_H
#include
#include
#include
struct DHCPOptList;
struct DHCPOptList *dhcpOpt_createList(void);
void dhcpOpt_destroyList(struct DHCPOptList *list);
bool dhcpOpt_optExists(const struct DHCPOptList *list, int code);
int dhcpOpt_add(struct DHCPOptList *list, int code, const void *data, size_t size);
size_t dhcpOpt_count(struct DHCPOptList *list);
/* Serialise option list to an array (code + length + payload) */
int dhcpOpt_serialise(const struct DHCPOptList *list, uint8_t **buffer, size_t *size);
/* Create an array containg the integer codes of all the DHCP options in the
* list */
int dhcpOpt_optCodes(const struct DHCPOptList *list, uint8_t **buffer, size_t *size);
#endif // DHCPOPTINJ_OPTIONS_H
dhcpoptinj-0.5.3/src/udp.h 0000664 0000000 0000000 00000001707 13522305640 0015416 0 ustar 00root root 0000000 0000000 /*
* Copyright © 2015–2019 Andreas Misje
*
* This file is part of dhcpoptinj.
*
* dhcpoptinj 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.
*
* dhcpoptinj 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 dhcpoptinj. If not, see .
*/
#ifndef DHCPOPTINJ_UDP_H
#define DHCPOPTINJ_UDP_H
#include
#pragma pack(2)
struct UDPHeader
{
uint16_t sourcePort;
uint16_t destPort;
uint16_t length;
uint16_t checksum;
};
#pragma pack()
#endif // DHCPOPTINJ_UDP_H