pax_global_header 0000666 0000000 0000000 00000000064 15142051300 0014501 g ustar 00root root 0000000 0000000 52 comment=ae50ff5a86b248af8ea81b368e25bc3931b72312
ceccomp-4.0/ 0000775 0000000 0000000 00000000000 15142051300 0012755 5 ustar 00root root 0000000 0000000 ceccomp-4.0/.clang-format 0000664 0000000 0000000 00000000022 15142051300 0015322 0 ustar 00root root 0000000 0000000 BasedOnStyle: GNU
ceccomp-4.0/.github/ 0000775 0000000 0000000 00000000000 15142051300 0014315 5 ustar 00root root 0000000 0000000 ceccomp-4.0/.github/workflows/ 0000775 0000000 0000000 00000000000 15142051300 0016352 5 ustar 00root root 0000000 0000000 ceccomp-4.0/.github/workflows/new-release.yml 0000664 0000000 0000000 00000001727 15142051300 0021313 0 ustar 00root root 0000000 0000000 name: New Release
on:
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Find the latest tag
run: |
git fetch --tags
LATEST_TAG=$(git describe --tags $(git rev-list --tags --max-count=1))
echo "The latest tag is:" $LATEST_TAG
echo "LATEST_TAG=$LATEST_TAG" >> $GITHUB_ENV
- name: Generate Changelog
run: |
echo "# What changed" > ${{ github.workspace }}-CHANGELOG.md
python3 scripts/release-changelog.py $LATEST_TAG >> ${{ github.workspace }}-CHANGELOG.md
- name: Preview Changelog
run: cat ${{ github.workspace }}-CHANGELOG.md
- name: Release
uses: softprops/action-gh-release@v2
with:
body_path: ${{ github.workspace }}-CHANGELOG.md
repository: dbgbgtf1/Ceccomp
tag_name: ${{ env.LATEST_TAG }}
token: ${{ secrets.GITHUB_TOKEN }}
ceccomp-4.0/.gitignore 0000664 0000000 0000000 00000000437 15142051300 0014751 0 ustar 00root root 0000000 0000000 build/
__pycache__
compile_commands.json
a.out
Test
result*
*.gdb_history
*.cache/
CeccompBuild/
diff_result
/Makefile
po/*.po~
SOURCES.txt
include/config.h
py-temp/dist/
py-temp/build/
py-temp/ceccomp.egg-info/
py-temp/wheelhouse
py-temp/ceccomp/ceccomp
test_prog
text
gdb_scripts
*.mo
ceccomp-4.0/CHANGELOG.md 0000664 0000000 0000000 00000015516 15142051300 0014576 0 ustar 00root root 0000000 0000000 # CHANGELOG
Items marked with :star: is the major change why we release a new version.
## 4.1 (INCOMING)
## 4.0
* **BREAKING** :star: :fire: **We aggressively refactored our code and the asm grammar is a bit different from v3. Please refer to documentation for new grammar.** :fire:
* :star: Add seize subfunction in trace pid :link: [#23]
* :star: Remove `-mno-omit-leaf-frame-pointer` flag if not supported by cc
* :star: Fix asm and disasm endianness problems :link: [#22]
* :star: Handle '>=' '>' '<=' '<' correctly :link: [#25]
* :star: Find python by `env` for compatibility in `configure` :heart: [@tesuji] :link: [!19]
* :star: Migrate to pytest for testing
* :star: Migrate to po4a for documentation translation
* Print messages in dynamic tests
* Add `-q` for trace to suppress `[INFO]` output
* Reject text that are error ones for kernel :link: [#17]
* Print info when trace found failed seccomp syscall
* Support `-` to refer to stdin or stdout
* Allow returning numbers or `$A`
* Fixed a typo in README :heart: [@k4lizen] :link: [!28]
[#22]: https://github.com/dbgbgtf1/Ceccomp/issues/22
[#25]: https://github.com/dbgbgtf1/Ceccomp/issues/25
[#23]: https://github.com/dbgbgtf1/Ceccomp/issues/23
[#17]: https://github.com/dbgbgtf1/Ceccomp/issues/17
[@tesuji]: https://github.com/tesuji
[!19]: https://github.com/dbgbgtf1/Ceccomp/pulls/19
[@k4lizen]: https://github.com/k4lizen
[!28]: https://github.com/dbgbgtf1/Ceccomp/pulls/28
## 3.5
* **BREAKING** :star: Now `trace` and `probe` no more accepts `-a`; arch is automatically retrieved via ptrace
* :star: Add `i686` arch support
* :star: Handle unknown system arch
* Fix 32-bit ceccomp `strtol` error
* Generalize test script to for different archs
* `trace` now follows tracee's arch instead of system's
* Fix Makefile implicit rules
## 3.4
* :star: Fix cross arch trace problems :link: [#16]
* :star: Add support for NO_COLOR env check :link: [#15]
* :star: Fix heap oob write if `goto` exceeds bpf range
* :star: Correctly kill children processes when recved signals
* :star: Fix potential invalid `%s` access in `ALU` and `ST_STX`
* Fix ambiguous `idx` in `ST_STX`
* Fix color display in emu
* Use `git describe --long` to have unified name pattern in `configure` devmode
* Add more tests to check ceccomp behaviour
[#15]: https://github.com/dbgbgtf1/Ceccomp/issues/15
[#16]: https://github.com/dbgbgtf1/Ceccomp/issues/16
## 3.3
* :star: Add `--enable-static` in `configure` to build statically
* Portable release in pip, for x86_64, i386, aarch64, armhf, riscv64
* Fix not-null-terminated argp option array
* Fix copyright as GPLv3 or later
## 3.2
* **BREAKING** :star: Enhance arch/syscall prediction :link: [#12]
* :star: Add support for Debian build system :link: [#13]
* :star: Improve syntax highlighting
* Hide unused bpf operation in emu :link: [#14]
* Fix `CECCOMP_USAGE` warning as it's a function call
* Add a dark-mode css for html doc
* Sort source object for reproducible build
[#13]: https://github.com/dbgbgtf1/Ceccomp/issues/13
[#12]: https://github.com/dbgbgtf1/Ceccomp/issues/12
[#14]: https://github.com/dbgbgtf1/Ceccomp/issues/14
## 3.1
* **BREAKING** :star: Add support for multiple process tracing :link: [#3]
* :star: Cover all cases of trace pid errors :link: [#11]
* :star: Add support for internationalization/localization :link: [#1]
* :star: Fix `ld` error when compiling on Kali Linux
* Fix potential misuse of `Info` in trace
* Improve log system and related color management
* Fix output file may not be opened correctly
* Add a GitHub action to issue new release easily
[#3]: https://github.com/dbgbgtf1/Ceccomp/issues/3
[#11]: https://github.com/dbgbgtf1/Ceccomp/issues/11
[#1]: https://github.com/dbgbgtf1/Ceccomp/issues/1
## 3.0
* **BREAKING** Remove `-o FILE` for `trace` pid mode
* :star: Add doc system powered by *asciidoc* :link: [#2]
* :star: Add signal forwarding to `trace` in expected way :link: [#5]
* :star: Add subcommand description :link: [#7]
* :star: Add color option, can be set to always, auto, never :link: [#10]
* :star: Add Python-version configure script :link: [#9]
* Warn invalid seccomp filter instead of refuse directly :link: [#4]
* Raise errors on corrupted TEXT in `emu`
* Suppress printing function if not debugging
* Set `$?` to 1 when failed to parse args
* Limit truncating file on `-o` flag by checking subcommand
* Update color in `return $A` BPF OP for better visual effect
* Implement assigning `len(struct seccomp_data)` to `A` or `X`
* Implement uninstall operation and verbose control in Makefile
[#2]: https://github.com/dbgbgtf1/Ceccomp/issues/2
[#5]: https://github.com/dbgbgtf1/Ceccomp/issues/5
[#7]: https://github.com/dbgbgtf1/Ceccomp/issues/7
[#10]: https://github.com/dbgbgtf1/Ceccomp/issues/10
[#4]: https://github.com/dbgbgtf1/Ceccomp/issues/4
[#9]: https://github.com/dbgbgtf1/Ceccomp/issues/9
## 2.9
* :star: Fix Makefile compatibility among shells :link: [#6]
* Add git-hook to remind dev to update version string
* Update color in `return` BPF OP for better visual effect
[#6]: https://github.com/dbgbgtf1/Ceccomp/issues/6
## 2.8
* :star: Improve compatibility among compilers
* :star: Add Kbuild-like build prompt with progress
* Improve logging implementation
## 2.7
* :star: Fix `trace` and `probe` foreground interaction issue
* Refactor method to terminate children
## 2.6
* :star: Fix Makefile link order (should be put in the end of line)
* Suppress compiler warning by `// fall through`
* Applying more checks on `asm`
## 2.5
* :star: Add parentheses for `TRAP` as it has `ret_data`, but *libseccomp* hasn't implement it :link: [seccomp/libseccomp#466]
* Add check script
* Fix uninitialized memory access
[seccomp/libseccomp#466]: https://github.com/seccomp/libseccomp/issues/466
## 2.4
* :star: Port kernel filter check
* Add some logging functions
## 2.3
* Fix `asm` lacking `ALU_NEG` operation
* Fix `asm` hanging if
## 2.2
* Fix `emu` emulates wrong ALU operations
* Better help message
## 2.1
* Remove `CXX` in Makefile, now it's purely in C
* Fix Makefile typo
## 2.0
* :star: Turn to `argp` to parse arguments
* :star: Add `-o` mode to output filters
* :star: Use C to implement `parsefilter`
## 1.5
* :star: New probe mode to test common syscalls instantly
* Adapt completion script to latest code base
## 1.4
* Fix lacking `\n` in trace
## 1.3
* `trace` now accept pid to grab filters
* Zsh completion script is capable of completing pid
## 1.2
* :star: Ready for PKGBUILD to build package
* Fix zsh completion script
## 1.1
* First release version
* Add basic zsh completion script
ceccomp-4.0/CONTRIBUTING.md 0000664 0000000 0000000 00000001766 15142051300 0015220 0 ustar 00root root 0000000 0000000 # Contribute to ceccomp
## Found a bug
Raise an issue directly, write your expected behavior and what was wrong in ceccomp.
Attach a minimum reproducible input and your version information (ceccomp and libseccomp).
We may close your issue if the bug is not reproducible.
## Want a new feature
Raise an issue to tell us what you want. You may write your expected output.
Please wait patiently as we may not have spare time to implement it and may close it.
We are glad to see your Pull Request :smile:.
## New pull request
If you are able to fix some bugs or import some new features, you could open a new pull
request. As for new feature, it's recommend to open an issue first to confirm your feature
is reasonable. NOTE, don't write code with AI completely, we may close it directly.
Run `clang-format` to format your code. The config is under repo root and should be recognized
by `clang-format` automatically.
Once your pull request is merged, you know that your code is licensed under GPL v3 or later.
ceccomp-4.0/LICENSE 0000664 0000000 0000000 00000104515 15142051300 0013770 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
.
ceccomp-4.0/Makefile.in 0000664 0000000 0000000 00000020073 15142051300 0015024 0 ustar 00root root 0000000 0000000 ifneq ($(words $(MAKECMDGOALS)),1) # if no argument was given to make...
.DEFAULT_GOAL = all
%: # define a last resort default rule
@$(MAKE) $@ --no-print-directory -rRf $(firstword $(MAKEFILE_LIST)) # recursive make call,
else
ifndef ECHO
T := $(shell $(MAKE) $(MAKECMDGOALS) --no-print-directory \
-nrRf $(firstword $(MAKEFILE_LIST)) \
ECHO="COUNTTHIS" | grep -c "COUNTTHIS")
L := $(shell echo -n $T | wc -m)
ifeq ($(NO_COLOR),)
GREEN := $(shell printf '\033[32m')
RESET := $(shell printf '\033[0m')
endif
ECHO_NOPROG = printf " $(1)\t$(2)\n"
ECHO = printf " %-12s[%$Ld/%$Ld]\t$(2)\n" \
$(1) \
$(shell SHELL=$(SHELL) flock $(LOCK) -c 'read n < $(MARK); echo $$n; echo $$((n+1)) > $(MARK)') \
$T
endif
# end for progress block, but not for else in line 5
V := {{VERBOSE}}
ifeq ($V,1)
Q :=
ECHO :=
ECHO_NOPROG :=
else
Q := @
endif
VERSION := {{VERSION}}
TAG_TIME := {{TAG_TIME}}
ARCH := $(shell uname -m)
TARGET := ceccomp test
SRC_DIR := src
INC_DIR := include
TEST_DIR := test
BUILD_DIR := build
BUILD_UTIL := $(BUILD_DIR)/utils
BUILD_LEXICAL := $(BUILD_DIR)/lexical
BUILD_RESOLVER := $(BUILD_DIR)/resolver
BUILD_DECODER := $(BUILD_DIR)/decoder
LOCK := $(BUILD_DIR)/lock
MARK := $(BUILD_DIR)/progress
C_SRCS := $(shell find $(SRC_DIR) ! -name 'ceccomp.c' -name '*.c' -or -name '*.s' | LC_ALL=C sort)
INC_SRCS := $(shell find $(INC_DIR) -name '*.h' | LC_ALL=C sort)
TEST_SRCS := $(TEST_DIR)/unit_test.c
OBJS := $(patsubst $(SRC_DIR)/%.c,$(BUILD_DIR)/%.c.o,$(C_SRCS))
TEST_OBJS := $(patsubst $(TEST_DIR)/%.c,$(BUILD_DIR)/%.c.o,$(TEST_SRCS))
{{DOC_IF}}
DOC_DIR := docs
IMG_DIR := images
SRC_IMG_DIR := $(DOC_DIR)/$(IMG_DIR)
BUILD_IMG_DIR := $(BUILD_DIR)/$(IMG_DIR)
IMG_SRCS := $(shell find $(SRC_IMG_DIR) -name "*.webp")
{{DOC_ENDIF}}
CECCOMP_MAIN := $(BUILD_DIR)/ceccomp.c.o
CECCOMP_C := $(SRC_DIR)/ceccomp.c
CC := {{CC}}
LOCALE_DIR := {{LOCALEDIR}}
CFLAGS := -fpie -fstack-protector -Wall -Wextra {{SYS_INC_DIR}} {{EXTRA_CFLAGS}}
LDFLAGS := -z now -z noexecstack -fpie -fstack-protector -Wall -Wextra {{SYS_LIB_DIR}} -lseccomp {{LIBARGP}} {{EXTRA_LDFLAGS}}
DEBUG := {{DEBUG_LEVEL}}
ifdef DEBUG
ifeq ($(DEBUG),1)
CFLAGS += -g -O2 -fno-omit-frame-pointer {{ARCH_PRESERVE_FP}}
LDFLAGS += -g -O2
else ifeq ($(DEBUG),2)
CFLAGS += -g3 -O0 -DDEBUG # O0 preserve fp by default
LDFLAGS += -g3 -O0
endif
else
CFLAGS += -O2
LDFLAGS += -O2 -s
endif
STATIC := {{IS_STATIC}}
ifeq ($(STATIC), 1)
CFLAGS += -static
LDFLAGS += -static
endif
all: ceccomp {{DOC_IF}}doc{{DOC_ENDIF}} {{I18N_IF}}mo{{I18N_ENDIF}}
{{I18N_IF}}
##### INTERNATIONALIZATION
I18N_DIR := po
PO_ZHCN := $(I18N_DIR)/zh_CN.po
MO_ZHCN := $(patsubst $(I18N_DIR)/%.po,$(BUILD_DIR)/%.mo,$(PO_ZHCN))
update-po:
$Q$(MAKE) -C $(I18N_DIR) --no-print-directory Q=$Q
$(MO_ZHCN): $(PO_ZHCN) | $(BUILD_DIR) $(MARK)
$Q$(call ECHO,MSGFMT,$@)
$Qmsgfmt -o $@ $<
mo: $(MO_ZHCN)
$Q$(call ECHO_NOPROG,$(GREEN)BUILT,mo$(RESET))
.PHONY: update-po mo
{{I18N_ENDIF}}
##### DOCUMENTATION PART #####
{{DOC_IF}}
MAN_OBJ := $(BUILD_DIR)/ceccomp.1
MAN_CHN := $(BUILD_DIR)/cn/ceccomp.1
HTML_OBJ := $(BUILD_DIR)/ceccomp.html
HTML_CHN := $(BUILD_DIR)/ceccomp-cn.html
ASCIIDOC := {{ASCIIDOC}}
doc: doc_html doc_man
doc_man: $(MAN_OBJ) $(MAN_CHN)
$Q$(call ECHO_NOPROG,$(GREEN)BUILT,man doc$(RESET))
doc_html: $(HTML_OBJ) $(HTML_CHN)
$Q$(call ECHO_NOPROG,$(GREEN)BUILT,html doc$(RESET))
$(MAN_OBJ): $(DOC_DIR)/ceccomp.adoc | $(BUILD_DIR) $(MARK)
$Q$(call ECHO,ADOC,$@)
$Q$(ASCIIDOC) -b manpage $< -a VERSION=$(VERSION) -a ARCH=$(ARCH) -a TAG_TIME=$(TAG_TIME) -o $@
$(MAN_CHN): $(DOC_DIR)/ceccomp.zh_CN.adoc | $(BUILD_DIR) $(MARK)
$Q$(call ECHO,ADOC,$@)
$Q$(ASCIIDOC) -b manpage $< -a VERSION=$(VERSION) -a ARCH=$(ARCH) -a TAG_TIME=$(TAG_TIME) -o $@
$(HTML_OBJ): $(DOC_DIR)/ceccomp.adoc | $(BUILD_DIR) $(MARK)
$Q$(call ECHO,ADOC,$@)
$Q$(ASCIIDOC) -b html5 $< -a VERSION=$(VERSION) -a ARCH=$(ARCH) -a TAG_TIME=$(TAG_TIME) -o $@
$(HTML_CHN): $(DOC_DIR)/ceccomp.zh_CN.adoc | $(BUILD_DIR) $(MARK)
$Q$(call ECHO,ADOC,$@)
$Q$(ASCIIDOC) -b html5 $< -a VERSION=$(VERSION) -a ARCH=$(ARCH) -a TAG_TIME=$(TAG_TIME) -o $@
.PHONY: doc doc_man doc_html
{{DOC_ENDIF}}
##### INSTALL CECCOMP #####
DESTDIR := {{DESTDIR}}
PREFIX := {{PREFIX}}
BIN_DIR := {{BINDIR}}
ZSH_FPATH := {{ZSH_FPATH}}
ZSH_SRC := completions
install: bin_install zsh_cmp_install {{DOC_IF}}doc_install{{DOC_ENDIF}} {{I18N_IF}}mo_install{{I18N_ENDIF}}
bin_install: ceccomp $(BUILD_DIR)/ceccomp
$Q$(call ECHO_NOPROG,INSTALL,$< $(BIN_DIR))
$Qinstall -Dt $(DESTDIR)$(BIN_DIR) $(BUILD_DIR)/ceccomp
zsh_cmp_install: $(ZSH_SRC)/_ceccomp
$Q$(call ECHO_NOPROG,INSTALL,$< $(ZSH_FPATH))
$Qinstall -Dm 0644 -t $(DESTDIR)$(ZSH_FPATH) $<
.PHONY: bin_install zsh_cmp_install install
{{DOC_IF}}
MAN_DIR := {{MANDIR}}
MAN_DST := $(MAN_DIR)/man1
MAN_CHN_DST := $(MAN_DIR)/zh_CN/man1
DOC_INSTALL_DIR := {{DOCDIR}}
HTML_DST := $(DOC_INSTALL_DIR)/html
doc_install: doc doc_man_install doc_html_install {{I18N_IF}}doc_man_cn_install{{I18N_ENDIF}} doc_images_install
$Q$(call ECHO_NOPROG,INSTALL,README.md $(DOC_INSTALL_DIR))
$Qinstall -Dm 0644 -t $(DESTDIR)$(DOC_INSTALL_DIR) README.md
doc_man_install: $(MAN_OBJ)
$Q$(call ECHO_NOPROG,INSTALL,$< $(MAN_DST))
$Qinstall -Dm 0644 -t $(DESTDIR)$(MAN_DST) $<
doc_man_cn_install: $(MAN_CHN)
$Q$(call ECHO_NOPROG,INSTALL,$< $(MAN_CHN_DST))
$Qinstall -Dm 0644 -t $(DESTDIR)$(MAN_CHN_DST) $<
doc_html_install: $(HTML_OBJ) $(HTML_CHN)
$Q$(call ECHO_NOPROG,INSTALL,$< $(HTML_DST))
$Qinstall -Dm 0644 -t $(DESTDIR)$(HTML_DST) $^
doc_images_install: $(IMG_SRCS)
$Q$(call ECHO_NOPROG,INSTALL,images $(HTML_DST))
$Qinstall -Dm 0644 -t $(DESTDIR)$(HTML_DST)/images $^
.PHONY: doc_man_install doc_html_install doc_man_cn_install doc_images_install doc_install
{{DOC_ENDIF}}
{{I18N_IF}}
mo_install: $(MO_ZHCN)
$Q$(call ECHO_NOPROG,INSTALL,$< $(LOCALE_DIR))
$Qinstall -Dm 0644 $< $(patsubst $(BUILD_DIR)/%.mo,$(DESTDIR)$(LOCALE_DIR)/%/LC_MESSAGES/ceccomp.mo,$<)
.PHONY: mo_install
{{I18N_ENDIF}}
UNINSTALL = test -f $(1) && rm -f $(1) || :
UNINSTALL_RECURSIVE = test -d $(1) && rm -rf $(1) || :
uninstall:
$Q$(call ECHO_NOPROG,UNINSTALL,$(BIN_DIR)/ceccomp)
$Q$(call UNINSTALL,$(DESTDIR)$(BIN_DIR)/ceccomp)
$Q$(call ECHO_NOPROG,UNINSTALL,$(ZSH_FPATH)/_ceccomp)
$Q$(call UNINSTALL,$(DESTDIR)$(ZSH_FPATH)/_ceccomp)
{{DOC_IF}}
$Q$(call ECHO_NOPROG,UNINSTALL,$(MAN_DIR)/man1/ceccomp.1)
$Q$(call UNINSTALL,$(DESTDIR)$(MAN_DIR)/man1/ceccomp.1)
$Q$(call ECHO_NOPROG,UNINSTALL,$(MAN_DIR)/zh_CN/man1/ceccomp.1)
$Q$(call UNINSTALL,$(DESTDIR)$(MAN_DIR)/zh_CN/man1/ceccomp.1)
$Q$(call ECHO_NOPROG,UNINSTALL,$(DOC_INSTALL_DIR))
$Q$(call UNINSTALL_RECURSIVE,$(DESTDIR)$(DOC_INSTALL_DIR)/../ceccomp) # in case DOC_INSTALL_DIR is not set...
{{DOC_ENDIF}}
.PHONY: uninstall
#### C OBJECTS ###
CONFIG_HEADER := $(INC_DIR)/config.h
$(CONFIG_HEADER): Makefile | $(MARK)
$Q$(call ECHO,SED,$@)
$Qsed 's/@@VERSION@@/$(VERSION)/;s/@@TAG_TIME@@/$(TAG_TIME)/;s/@@BUILDER@@/{{BUILDER}}/;{{LOCALE_SED}}' \
$(CONFIG_HEADER).in > $(CONFIG_HEADER)
ceccomp: $(BUILD_DIR)/ceccomp
$Q$(call ECHO_NOPROG,$(GREEN)BUILT,$@$(RESET))
$(BUILD_DIR)/ceccomp: $(OBJS) $(CECCOMP_MAIN) | $(MARK)
$Q$(call ECHO,LD,$@)
$Q$(CC) $^ -o $@ $(LDFLAGS)
test: $(BUILD_DIR)/test
$Q$(call ECHO_NOPROG,$(GREEN)BUILT,$@$(RESET))
$(BUILD_DIR)/test: $(TEST_OBJS) | $(MARK)
$Q$(call ECHO,LD,$@)
$Q$(CC) $^ -o $@ $(LDFLAGS)
$(BUILD_DIR)/ceccomp.c.o: $(SRC_DIR)/ceccomp.c $(CONFIG_HEADER) | $(BUILD_DIR) $(MARK)
$Q$(call ECHO,CC,$@)
$Q$(CC) -I$(INC_DIR) $(CFLAGS) $< -c -o $@
$(BUILD_DIR)/%.c.o: $(SRC_DIR)/%.c | $(BUILD_DIR) $(MARK) $(CONFIG_HEADER)
$Q$(call ECHO,CC,$@)
$Q$(CC) -I$(INC_DIR) $(CFLAGS) $< -c -o $@
$(BUILD_DIR)/%.c.o: $(TEST_DIR)/%.c | $(BUILD_DIR) $(MARK)
$Q$(call ECHO,CC,$@)
$Q$(CC) -I$(INC_DIR) $(CFLAGS) $< -c -o $@
$(BUILD_DIR):
$Q$(call ECHO_NOPROG,MKDIR,$(BUILD_DIR))
$Qmkdir -p $(BUILD_DIR) $(BUILD_UTIL) $(BUILD_LEXICAL) $(BUILD_RESOLVER) $(BUILD_TEST) $(BUILD_IMG_DIR) $(BUILD_DECODER)
FORCE:
$(MARK): FORCE | $(BUILD_DIR)
$Qecho 1 > $(MARK)
.PHONY: clean all ceccomp test
clean:
$Q$(call ECHO_NOPROG,RM,$(BUILD_DIR))
$Qrm -rf $(BUILD_DIR)
$Q$(call ECHO_NOPROG,RM,$(CONFIG_HEADER))
$Qrm $(CONFIG_HEADER)
endif
ceccomp-4.0/README.md 0000664 0000000 0000000 00000007140 15142051300 0014236 0 ustar 00root root 0000000 0000000 # Ceccomp
A tool to analyze seccomp filters like `seccomp-tools`, written in C
## Features
- :gear: Robust assembler and disassembler
- :blue_book: Complete documentation
- :1234: Various architecture support powered by libseccomp
- :globe_with_meridians: Multi-language support
- :feather: Minimum build depencies for core binary
- :paintbrush: Enhanced syntax highlighting
- :100: Informational error messages
- :shell: Powerful Zshell completion
- :no_entry_sign: Pure C without LLM-generated garbage
## Doc & Screenshots
[English Version](docs/ceccomp.adoc) | [中文文档](docs/ceccomp.zh_CN.adoc)
## Install
- Arch Linux users:
Install via AUR, build `ceccomp` package ⇒ [](https://repology.org/project/ceccomp/versions)
Or install via `archlinuxcn` repo if you have it set in you `pacman.conf`.
- Debian, Ubuntu or Kali users:
ceccomp is available with `apt` now if you are using distros below:
[](https://repology.org/project/ceccomp/versions)
[](https://repology.org/project/ceccomp/versions)
[](https://repology.org/project/ceccomp/versions)
[](https://repology.org/project/ceccomp/versions)
- NixOS users:
@tesuji helps us submit a PR at NixOS, but it's blocked as nobody cares... If you
like our software, please :+1: in NixOS/nixpkgs#462592 to help ceccomp into nixpkgs!
- Stable installation:
Clone the whole repo, then run `./configure`. Add `--without-doc` flag if you don't have `asciidoctor`,
and add `--without-i18n` flag if you don't have `gettext` package.
```sh
git clone https://github.com/dbgbgtf1/Ceccomp.git
cd Ceccomp
./configure
./configure # run this again if Makefile is not generated
make
make install # install at /usr/bin
```
- Testing installation:
Clone the whole repo, and then run `./configure --devmode`.
```sh
git clone https://github.com/dbgbgtf1/Ceccomp.git
cd Ceccomp
./configure --devmode
make
```
## Run Test
Run configure and make, then invoke `pytest test` from repo root. Trace pid case will be skipped if no
CAP_SYS_ADMIN. If you find some checks failed, please submit an issue to report your case.
To run the test, you need 2 extra packages: `pkgconf` (required by `pkg-config`) and `python-pytest`
(required by `pytest`).
## CheatSheet
## Credits
- [seccomp-tools](https://github.com/david942j/seccomp-tools): The tool in Ruby inspires us to write ceccomp
- [Bootswatch](https://bootswatch.com/slate/): Provides awesome css for html doc under MIT
- [Linux kernel](https://github.com/torvalds/linux): Port some bpf checks
- [Verstable](https://github.com/JacksonAllan/Verstable): High-performance hash table implementation in C
- [a5hash](https://github.com/avaneev/a5hash): High-performance hash implementation for short strings in C
Any Issue or PR are welcome! :heart: Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details.
## License
Copyright (C) 2025-present, ceccomp contributors, distributed under GNU General Public License v3.0 or Later
ceccomp-4.0/SECURITY.md 0000664 0000000 0000000 00000001445 15142051300 0014552 0 ustar 00root root 0000000 0000000 # Security Policy
## Reporting a Vulnerability
If you found a severe bug, for instance, hijack user's computer via a bpf filter,
please send emails to both of us (ma2014119@outlook.com and dudududumaxver@outlook.com).
If we don't reply to you in 3 days, you could find us via Discord (@rocketmadev and @dbgbgtf)
in `pwndbg` server, please dm to us directly. If neither of us don't reply back in 2 weeks,
just open an issue.
When sending us your bug report, please confirm that the severe bug you found is reproducible
and survive in latest version of ceccomp. Then write about how to trigger the bug (a PoC).
We will contact you later.
NOTE that if you are sending us AI-generated bug report without check or spams, we may refuse
your request.
Once we confirm your bug, we may help you issue a CVE.
ceccomp-4.0/completions/ 0000775 0000000 0000000 00000000000 15142051300 0015311 5 ustar 00root root 0000000 0000000 ceccomp-4.0/completions/_ceccomp 0000664 0000000 0000000 00000011257 15142051300 0017012 0 ustar 00root root 0000000 0000000 #compdef ceccomp
# Zsh completion script for ceccomp
local -a subcmd options expl arch_compstr output_compstr
local state
local archs=(
'x86_64' 'i386' 'x32' 'aarch64' 'arm' 'loongarch64' 'm68k' 'mips' 'mipsel'
'mips64' 'mipsel64' 'mips64n32' 'mipsel64n32' 'parisc' 'parisc64' 'ppc64' 'ppc64le'
'ppc' 's390x' 's390' 'riscv64'
)
arch_compstr=(
'(-a --arch)'{-a,--arch}"[Target BPF architecture]:ARCH:($archs)"
)
color_compstr=(
'(-c --color)'{-c,--color}'[When to display in color]:WHEN:(always auto never)'
)
output_compstr=(
'(-o --output)'{-o,--output}'[Print to file to avoid mixing tracee output]:FILE:_files'
)
local syscalls=(
'open' 'read' 'write' 'close' 'mmap' 'mprotect' 'execve' 'execveat' 'pread64'
'readv' 'writev' 'preadv' 'preadv2' 'openat' 'openat2' 'sendfile64' 'send'
'sendto' 'sendmsg' 'recv' 'recvfrom' 'recvmsg' 'io_uring_setup' 'io_uring_enter'
'io_uring_register' 'ptrace'
)
if (( CURRENT == 2 )) {
subcmd=(
'asm:Assemble bpf text to raw bytes'
'disasm:Disassemble raw bytes to bpf text'
'trace:Run program or trace pid, extract bpf filter and then print to text'
'emu:Emulate bpf program with given syscall and bpf text'
'probe:Trace the program for the first filter and emulate common syscalls'
'help:Display ceccomp help information'
'version:Display ceccomp version'
)
_describe 'subcmd' subcmd
return
} elif (( CURRENT > 2 )) {
case $words[2] {
(asm)
_arguments \
$arch_compstr \
$color_compstr \
'(-f --fmt)'{-f,--fmt}'[Output format of BPF]:FMT:(raw hexline hexfmt)' \
'2:BPF:_files' \
'*: :'
;;
(disasm)
_arguments \
$arch_compstr \
$color_compstr \
'2:RAW:_files' \
'*: :'
;;
(trace)
_arguments -C \
$color_compstr \
'(-p --pid)'{-p,--pid}'[Attach to which process to extract its filters]:PID:->getpid' \
'(-q --quiet)'{-q,--quiet}'[Print warning and error messages only]' \
'(-s --seize)'{-s,--seize}'[Follow pid to trace load-filter operation (pid mode)]' \
$output_compstr \
'*:arguments:_files'
# complete non-kernel pids like kill
if [[ $state == 'getpid' ]] {
local line pids lines
pids=()
# extract command output line by line
lines=("${(@f)$(ps --ppid 2 -p 2 -N -o pid=,tty=,user=,comm=)}")
for line ($lines) {
pids+=${line[(w)1]} # extract first word (pid)
}
_wanted nonk-pids expl 'non-kernel process ID' \
compadd -o nosort -ld lines -a pids
}
;;
(probe)
_arguments -C \
$color_compstr \
$output_compstr \
'(-q --quiet)'{-q,--quiet}'[Print warning and error messages only]' \
'*:arguments:_files'
;;
(emu)
_arguments -C \
$arch_compstr \
$color_compstr \
'(-q --quiet)'{-q,--quiet}'[Print return value only]' \
'2:BPF:_files' \
':NR:->syscall_nr' \
':ARGV0:->argv0' \
':ARGV1:->argv1' \
':ARGV2:->argv2' \
':ARGV3:->argv3' \
':ARGV4:->argv4' \
':ARGV5:->argv5' \
':IP:->ip' \
'*: :'
case $state {
(syscall_nr)
_message -r 'Hint: syscall_nr or syscall_name (to name but a few)'
_values SYSCALL $syscalls
;;
(argv0)
_message -r 'Hint: u64 for argv[0]'
;;
(argv1)
_message -r 'Hint: u64 for argv[1]'
;;
(argv2)
_message -r 'Hint: u64 for argv[2]'
;;
(argv3)
_message -r 'Hint: u64 for argv[3]'
;;
(argv4)
_message -r 'Hint: u64 for argv[4]'
;;
(argv5)
_message -r 'Hint: u64 for argv[5]'
;;
(ip)
_message -r 'Hint: u64 for instruction pointer'
;;
}
;;
(*)
# help and version has no completion available
return
;;
}
}
ceccomp-4.0/configure 0000775 0000000 0000000 00000063116 15142051300 0014673 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
import datetime
import argparse
import subprocess
import os
import sys
import shutil
from collections.abc import Callable
from dataclasses import dataclass
# constants
VERSION = '4.0'
TAG_TIME = '2026-2-8'
# color escape code definition
if not os.getenv('NO_COLOR'):
def TXT_RED(s): return f'\x1b[31m{s}\x1b[0m'
def TXT_GREEN(s): return f'\x1b[32m{s}\x1b[0m'
def TXT_YELLOW(s): return f'\x1b[33m{s}\x1b[0m'
def TXT_BLUE(s): return f'\x1b[34m{s}\x1b[0m'
def TXT_MAGENTA(s): return f'\x1b[35m{s}\x1b[0m'
def TXT_CYAN(s): return f'\x1b[36m{s}\x1b[0m'
def TXT_GRAY(s): return f'\x1b[90m{s}\x1b[0m'
else:
def TXT_RED(s): return s
def TXT_GREEN(s): return s
def TXT_YELLOW(s): return s
def TXT_BLUE(s): return s
def TXT_MAGENTA(s): return s
def TXT_CYAN(s): return s
def TXT_GRAY(s): return s
# error handling
def warn(msg: any):
print(TXT_YELLOW(f'[WARN] {msg}'), flush=True, file=sys.stderr)
def error(msg: any):
print(TXT_RED(f'[ERR!] {msg}'), file=sys.stderr)
sys.exit(1)
# build option parsing
class GNUStyleHelpFormatter(argparse.RawDescriptionHelpFormatter):
"""Custom help formatter that forces --opt=VALUE style"""
def _format_action_invocation(self, action):
# only long options, no short option
if not action.option_strings:
return super()._format_action_invocation(action)
return ', '.join(f'{opt}={action.metavar}' if action.metavar else opt
for opt in action.option_strings)
def parse_args() -> tuple[argparse.Namespace, list[str]]:
epilog = '''Some influential environment variables:
CC C compiler command
CFLAGS Extra C compiler flags
LDFLAGS Extra linker flags
ASCIIDOC Asciidoc document compiler
Please report bug at https://github.com/dbgbgtf1/Ceccomp
Copyright (C) 2025-present, distributed under GPLv3 or later
'''
parser = argparse.ArgumentParser(
prog='configure.py',
description='Configure build flags for Ceccomp, written in Python',
epilog=epilog,
formatter_class=GNUStyleHelpFormatter,
)
config_grp = parser.add_argument_group('Configure-time options (fixed once Makefile is generated)')
config_grp.add_argument('--enable-verbose', action='store_true', help='Enable verbose output')
config_grp.add_argument('--without-doc', action='store_true', help='Do not install documentation')
config_grp.add_argument('--without-i18n', action='store_true', help='Do not generate locale mo files')
config_grp.add_argument('--devmode', action='store_true', help='Allow you to compile against any commit (only work in git mode)')
config_grp.add_argument('--packager', type=str, metavar='BY', default='manual', help='Who build the package (default: manual)')
config_grp.add_argument('--disable-option-checking', action='store_true', help='Whether to throw an error when unknown options found')
config_grp.add_argument('--build', type=str, metavar='TARGET',
help='Which target to build against, optional. For instance, x86_64-linux-gnu')
config_grp.add_argument('--includedir', type=str, metavar='DIR', help='Optional system include directory')
config_grp.add_argument('--libdir', type=str, metavar='DIR', help='Optional system library directory')
# argp is dynamically tested
make_grp = parser.add_argument_group('Make-time options (can be overridden by make cli) [make var]')
make_grp.add_argument('--prefix', type=str, metavar='PREFIX', default='/usr',
help='Installation prefix (default: /usr) [PREFIX]')
make_grp.add_argument('--bindir', type=str, metavar='DIR',
help='User executables directory (default: PREFIX/bin) [BIN_DIR]')
make_grp.add_argument('--zshfpath', type=str, metavar='DIR',
help='Zsh functions path (default: PREFIX/share/zsh/site-functions) [ZSH_FPATH]')
make_grp.add_argument('--docdir', type=str, metavar='DIR',
help='Documentation directory (default: PREFIX/share/doc/ceccomp) [DOC_DIR]')
make_grp.add_argument('--mandir', type=str, metavar='DIR',
help='Man pages directory (default: PREFIX/share/man) [MAN_DIR]')
make_grp.add_argument('--localedir', type=str, metavar='DIR',
help='Localization directory (default: PREFIX/share/locale) [LOCALE_DIR]')
make_grp.add_argument('--destdir', type=str, metavar='DIR',
help='Optional dir to install software, useful for package managers [DESTDIR]')
make_grp.add_argument('--debug-level', type=int, metavar='LEVEL', default=1,
help='Set debug symbol level (0: -O2 -s|1: -O2 -g, default|2: -O0 -g3 -DDEBUG) [DEBUG]')
make_grp.add_argument('--version', type=str, metavar='VER',
help=f'Set ceccomp version (default: {VERSION}) [VERSION]')
make_grp.add_argument('--tag-time', type=str, metavar='TIME',
help=f'Set the time of current tag. Use "CONFIG" for the time when running configure; or write in YYYY-mm-dd like default value {TAG_TIME} [TAG_TIME]')
make_grp.add_argument('--enable-static', action='store_true', help='Enable static build [STATIC]')
return parser.parse_known_args()
@dataclass
class BuildOptions:
prefix: str
bindir: str
zshfpath: str
docdir: str
mandir: str
localedir: str
destdir: str
debug_level: int
version: str
tag_time: str
is_static: bool
verbose: bool
doc: bool
i18n: bool
devmode: bool
builder: str
check_option: bool
target: str
sys_includedir: str
sys_libdir: str
cc: str | None
asciidoc: str | None
cflags: str
ldflags: str
unknown_options: list[str]
git_install: bool = True
def __post_init__(self):
if self.bindir is None:
self.bindir = os.path.join(self.prefix, 'bin')
if self.zshfpath is None:
self.zshfpath = os.path.join(self.prefix, 'share', 'zsh', 'site-functions')
if self.docdir is None:
self.docdir = os.path.join(self.prefix, 'share', 'doc', 'ceccomp')
if self.mandir is None:
self.mandir = os.path.join(self.prefix, 'share', 'man')
if self.localedir is None:
self.localedir = os.path.join(self.prefix, 'share', 'locale')
def replace_prefix(dirent: str | None) -> str:
return dirent.replace('${prefix}', self.prefix) if dirent else ''
self.bindir = replace_prefix(self.bindir)
self.zshfpath = replace_prefix(self.zshfpath)
self.docdir = replace_prefix(self.docdir)
self.mandir = replace_prefix(self.mandir)
self.localedir = replace_prefix(self.localedir)
self.destdir = replace_prefix(self.destdir)
self.sys_includedir = replace_prefix(self.sys_includedir)
self.sys_libdir = replace_prefix(self.sys_libdir)
if self.debug_level not in (0, 1, 2):
error('debug_level option can only be 0, 1 or 2!')
def check_cmd(env: str, *candidates: list[str]) -> str | None:
"""enumerate available command in system"""
var = getattr(self, env)
if var is not None:
if shutil.which(var) is None:
error(f'{var} provided by environment {env.upper()} is not runnable!')
else:
return var
# no such environment variable
for candidate in candidates:
if shutil.which(candidate) is not None:
return candidate
return None
# the None value will be processed in check
if self.target:
self.cc = check_cmd('cc', f'{self.target}-cc', f'{self.target}-gcc', f'{self.target}-clang')
if not self.cc:
warn(f'No C compiler with prefix {self.target} found')
self.cc = check_cmd('cc', 'cc', 'gcc', 'clang')
else: # cc may be passed from environ, so we shall not merge the logic
self.cc = check_cmd('cc', 'cc', 'gcc', 'clang')
self.asciidoc = check_cmd('asciidoc', 'asciidoctor')
if self.cflags is None:
self.cflags = ''
if self.ldflags is None:
self.ldflags = ''
if self.tag_time == 'CONFIG':
self.tag_time = datetime.datetime.today().strftime('%Y-%m-%d')
elif self.tag_time:
try:
datetime.datetime.strptime(self.tag_time, '%Y-%m-%d')
except ValueError:
error(f'Invalid tag-time {self.tag_time}, format is YYYY-mm-dd')
# check the options
if self.unknown_options:
if self.check_option:
error(f'Unrecognized options: {" ".join(self.unknown_options)}, please pass --help to see correct options!')
else:
for opt in self.unknown_options:
print(TXT_GRAY(f'Ignoring unknown option {opt}'))
warn(f'Discarding {len(self.unknown_options)} unknown options!')
args, unknown = parse_args()
buildopts = BuildOptions(
prefix=args.prefix,
bindir=args.bindir,
zshfpath=args.zshfpath,
docdir=args.docdir,
mandir=args.mandir,
localedir=args.localedir,
destdir=args.destdir,
debug_level=args.debug_level,
version=args.version,
tag_time=args.tag_time,
is_static=args.enable_static,
verbose=args.enable_verbose,
doc=not args.without_doc,
i18n=not args.without_i18n,
devmode=args.devmode,
builder=args.packager,
check_option=not args.disable_option_checking,
target=args.build,
sys_includedir=args.includedir,
sys_libdir=args.libdir,
cc=os.getenv('CC'),
asciidoc=os.getenv('ASCIIDOC'),
cflags=os.getenv('CFLAGS'),
ldflags=os.getenv('LDFLAGS'),
unknown_options=unknown,
)
del args, unknown
# gathering system information and check
@dataclass
class Makefile:
s: str
def inject(self, placeholder: str, filler: str | list[str] | bool) -> None:
if isinstance(filler, str):
self.s = self.s.replace(f'{{{{{placeholder}}}}}', filler) # {{PLACEHOLDER}}
return
if isinstance(filler, bool):
# automatically loop from 0 to perform substitution
keep = filler
i = 0
while True:
if self.s.find(f'{{{{{placeholder}_IF}}}}') == -1:
break
if keep:
self.s = self.s.replace(f'{{{{{placeholder}_IF}}}}', '') # {{PLACEHOLDER_IF}}
self.s = self.s.replace(f'{{{{{placeholder}_ENDIF}}}}', '')
else:
begin = self.s.find(f'{{{{{placeholder}_IF}}}}')
end = self.s.find(f'{{{{{placeholder}_ENDIF}}}}')
assert begin != -1
assert end != -1
end += len(f'{{{{{placeholder}_ENDIF}}}}')
self.s = self.s[:begin] + self.s[end:]
i += 1
return
for i, e in enumerate(filler):
self.s = self.s.replace(f'{{{{{placeholder}{i}}}}}', e) # {{PLACEHOLDER0}}
class TaskManager:
tasks: list[Callable[[Makefile], None]]
makefile: Makefile
def __init__(self, makefile_name: str) -> None:
self.tasks = []
if not os.path.isfile(makefile_name):
error(f'Reading Makefile {makefile_name}, but it\'s not a file!')
try:
with open(makefile_name) as file:
self.makefile = Makefile(file.read())
except OSError as e:
error(f'Can not open Makefile: {e}')
def run_tasks(self):
width = len(str(len(self.tasks)))
total = len(self.tasks)
for seq, handler in enumerate(self.tasks, start=1):
# no need to flush as stdout will be flushed in handler
print(f'[{seq:>{width}}/{total}] ', end='')
handler(self.makefile)
def add_task(self, handler: Callable[[Makefile], None]):
self.tasks.append(handler)
taskmgr = TaskManager('Makefile.in')
def pcheck(txt: str):
print(f'Checking {txt}... ', end='', flush=True)
def run_command(argv: list[str], stdin: str | None=None, push_sys_dir: bool=False) -> tuple[int, str, str]:
"""
Run command with given argv and input, return process returncode, stdout and stderr
Return -1, '', exception message if exception raised is known, or else return -2, '', message.
"""
try:
argv[0] = shutil.which(argv[0])
if push_sys_dir: # using C compiler!
if buildopts.sys_includedir: # in case some include/lib is not accessible for current compiler
argv.append(f'-I{buildopts.sys_includedir}')
if buildopts.sys_libdir:
argv.append(f'-L{buildopts.sys_libdir}')
if buildopts.is_static:
argv.append('-static')
proc = subprocess.run(argv, input=stdin, capture_output=True, text=True)
except subprocess.SubprocessError as e:
return -1, '', str(e)
except UnicodeDecodeError as e:
return -1, '', 'UnicodeDecodeError: program output contains non-utf-8 bytes'
except Exception as e:
return -2, '', str(e)
else:
return proc.returncode, proc.stdout, proc.stderr
def new_task(func: Callable) -> Callable:
taskmgr.add_task(func)
return func
# color definition:
# green: well-tested
# cyan: should work
# blue: not work and have to take fallback choice
# magenta: unexpected or no fallback choice
@new_task
def check_platform(_: str):
pcheck('system platform')
if sys.platform == 'linux':
print(TXT_GREEN('linux'))
elif sys.platform == 'android':
print(TXT_CYAN('android'))
else:
print(TXT_MAGENTA(sys.platform))
error(f'Ceccomp only support Linux!')
@new_task
def check_flock(makefile: Makefile):
pcheck('if flock in system')
if shutil.which('flock') is None:
makefile.inject('VERBOSE', '1')
print(TXT_BLUE('no'))
warn('flock not found in system, Makefile verbose is set to true. You may need util-linux package')
else:
makefile.inject('VERBOSE', '1' if buildopts.verbose else '0')
print(TXT_GREEN('yes'))
@new_task
def check_i18n(makefile: Makefile):
pcheck('internationalization support')
if not buildopts.i18n:
makefile.inject('I18N', False)
makefile.inject('LOCALEDIR', buildopts.localedir)
makefile.inject('LOCALE_SED', 's|@@LOCALEDIR@@||')
print(TXT_BLUE('no'))
return
if shutil.which('xgettext') is None:
print(TXT_MAGENTA('no gettext'))
error('xgettext and other tools not found, pass --without-i18n to disable l10n generation or install gettext package!')
makefile.inject('I18N', True)
makefile.inject('LOCALEDIR', buildopts.localedir)
makefile.inject('LOCALE_SED', f's|@@LOCALEDIR@@|#define LOCALEDIR "{buildopts.localedir}"|')
print(TXT_GREEN('yes'))
@new_task
def check_doc(makefile: Makefile):
pcheck('documentation settings')
if not buildopts.doc:
makefile.inject('DOC', False)
print(TXT_BLUE('no doc'))
return
if buildopts.asciidoc is None:
print(TXT_MAGENTA('no asciidoc found'))
error('Asciidoc compiler not found, pass --without-doc to disable documentation generation or install asciidoctor package!')
makefile.inject('DOC', True)
makefile.inject('ASCIIDOC', buildopts.asciidoc)
if 'asciidoctor' in buildopts.asciidoc:
print(TXT_GREEN(buildopts.asciidoc))
else:
print(TXT_CYAN(buildopts.asciidoc))
warn(f'Your asciidoc compiler {buildopts.asciidoc} is not tested and may fail to generate docs')
standard_c = '''
#include
void leaf(void) {}
int main() {
puts("");
leaf();
return 0;
}
'''
@new_task
def check_cc(makefile: Makefile):
pcheck('C compiler')
if buildopts.cc is None:
print(TXT_MAGENTA('no cc found'))
error('C compiler command not found in system!')
code, _, stderr = run_command([buildopts.cc, '-x', 'c', '-', '-o', '/dev/null'], standard_c)
if code:
print(TXT_MAGENTA(buildopts.cc))
if code == -1:
error(f'C compiler is not working: {stderr}')
if code == -2:
error(f'Unexpected error: {stderr}')
print(f'Compiler returned non-zero returncode with message:\n{stderr}', end='')
error(f'C compiler can not compile minimum C unit')
# code == 0
makefile.inject('CC', buildopts.cc)
print(TXT_GREEN(buildopts.cc))
linux_headers = '''
#include
#include
#include
int main() {
struct sock_fprog *addr = (struct sock_fprog *)mmap(NULL, 0x1000, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
*addr = (struct sock_fprog){ .len = 0, .filter = NULL };
return 0;
}
'''
@new_task
def check_linux_headers(_: Makefile):
pcheck('Linux-related headers')
code, _, stderr = run_command([buildopts.cc, '-x', 'c', '-', '-o', '/dev/null'], linux_headers, push_sys_dir=True)
if code:
print(TXT_MAGENTA('no'))
if code == -1:
error(f'C compiler is not working: {stderr}')
if code == -2:
error(f'Unexpected error: {stderr}')
print(f'Compiler returned non-zero returncode with message:\n{stderr}', end='')
error(f'Can not compile Linux-related unit, you may install linux-headers package')
print(TXT_GREEN('yes'))
libseccomp = '''
#include
#include
int main() {
printf("%d", seccomp_version()->major);
return 0;
}
'''
@new_task
def check_libseccomp(_: Makefile):
pcheck('libseccomp')
code, _, stderr = run_command([buildopts.cc, '-x', 'c', '-', '-lseccomp', '-o', '/dev/null'], libseccomp, push_sys_dir=True)
if code:
print(TXT_MAGENTA('no'))
if code == -1:
error(f'C compiler is not working: {stderr}')
if code == -2:
error(f'Unexpected error: {stderr}')
print(f'Compiler returned non-zero returncode with message:\n{stderr}', end='')
error(f'Can not compile libseccomp unit, you may install libseccomp package')
print(TXT_GREEN('yes'))
argp = '''
#include
int main(int argc, char **argv) {
return argp_parse(0, argc, argv, 0, 0, 0);
}
'''
@new_task
def check_argp(makefile: Makefile):
pcheck('argp parser')
code, _, stderr = run_command([buildopts.cc, '-x', 'c', '-', '-o', '/dev/null'], argp, push_sys_dir=True)
if code:
if code == -1:
print(TXT_MAGENTA('no'))
error(f'C compiler is not working: {stderr}')
if code == -2:
print(TXT_MAGENTA('no'))
error(f'Unexpected error: {stderr}')
# code > 0
# some system need external argp package, so we try to link
code, _, stderr = run_command([buildopts.cc, '-x', 'c', '-', '-largp', '-o', '/dev/null'], argp)
if code:
print(TXT_MAGENTA('no'))
if code == -1:
print(TXT_MAGENTA('no'))
error(f'C compiler is not working: {stderr}')
if code == -2:
print(TXT_MAGENTA('no'))
error(f'Unexpected error: {stderr}')
print(f'Compiler returned non-zero returncode with message:\n{stderr}', end='')
error(f'Can not compile argp unit, you may install argp package')
# code == 0 and link argp
makefile.inject('LIBARGP', '-largp')
print(TXT_CYAN('external'))
return
# code == 0
makefile.inject('LIBARGP', '')
print(TXT_GREEN('builtin'))
@new_task
def check_source(_: Makefile):
pcheck('source code type')
if os.path.isdir('.git'):
buildopts.git_install = True
print(TXT_GREEN('git install'))
else:
buildopts.git_install = False
print(TXT_CYAN('tarball install'))
@new_task
def check_version(makefile: Makefile):
pcheck('target version')
if buildopts.git_install:
if not buildopts.devmode:
code, stdout, stderr = run_command(['git', 'describe', '--exact-match'])
if code < 0:
print(TXT_MAGENTA('git failed'))
print(f'Git not accessible? {stderr}')
error('Can not run git, you may install git package')
elif code == 0: # we are at a tag, adopt it
tag = stdout.strip()
buildopts.version = tag if not tag.startswith('v') else tag[1:]
code, stdout, _ = run_command(['git', 'log', '-1', '--format=format:%as', tag])
if code:
print(TXT_MAGENTA('get tag time failed'))
print(stderr, end='' if stderr[-1] == '\n' else '\n')
error('Can not get tag-time for the latest tag')
buildopts.tag_time = stdout.strip()
else: # we are not at a tag, try to go to a tag
code, stdout, _ = run_command(['git', 'rev-list', '--tags', '--max-count=1'])
if code:
print(TXT_MAGENTA('git failed'))
print(stderr, end='' if stderr[-1] == '\n' else '\n')
error('Can not determine the latest tag by git, to build from git, you need to pull the whole repo!')
code, stdout, _ = run_command(['git', 'describe', '--tags', stdout.strip()])
if code:
print(TXT_MAGENTA('git failed'))
print(stderr, end='' if stderr[-1] == '\n' else '\n')
error('Can not determine the latest tag by git')
tag = stdout.strip()
code, stdout, _ = run_command(['git', 'checkout', tag]) # checkout to that tag
if code:
print(TXT_MAGENTA('checkout failed'))
print(stderr, end='' if stderr[-1] == '\n' else '\n')
error('Can not checkout the latest tag')
print(TXT_CYAN(tag))
warn('Checked out to new tag, please rerun me to build stable version of ceccomp!')
sys.exit(0)
else: # devmode is True
code, stdout, stderr = run_command(['git', 'describe', '--long'])
if code < 0:
print(TXT_MAGENTA('git failed'))
print(f'Git not accessible? {stderr}')
error('Can not run git, you may install git package')
elif code == 0: # current commit get correctly resolved (tag-rev-gcommit or tag)
# --long mode display in TAG-COMMITS-gCOMMIT
tag, revision, commit = stdout.strip().split('-')
ver = tag if not tag.startswith('v') else tag[1:]
buildopts.version = f'{ver}.r{revision}_{commit[1:]}' # skip g
code, stdout, _ = run_command(['git', 'log', '-1', '--format=format:%as'])
if code:
print(TXT_MAGENTA('get tag time failed'))
print(stderr, end='' if stderr[-1] == '\n' else '\n')
error('Can not get tag-time for the latest tag')
buildopts.tag_time = stdout.strip()
else: # git failed to describe
print(TXT_MAGENTA('describe failed'))
print(stderr, end='' if stderr[-1] == '\n' else '\n')
error('Can not determine the latest tag by git, to build from git, you need to pull the whole repo!')
else: # tarball install
if not buildopts.version:
buildopts.version = VERSION
if not buildopts.tag_time:
buildopts.tag_time = TAG_TIME
makefile.inject('VERSION', buildopts.version)
makefile.inject('TAG_TIME', buildopts.tag_time)
if buildopts.git_install and not buildopts.devmode:
print(TXT_GREEN(buildopts.version))
elif buildopts.git_install and buildopts.devmode:
print(TXT_BLUE(buildopts.version))
else:
print(TXT_CYAN(buildopts.version))
@new_task
def check_builder_name(makefile: Makefile):
pcheck('if builder name is valid')
if '/' in buildopts.builder:
error(f'Found \'/\' in builder name {buildopts.builder}, which is not allowed.')
makefile.inject('BUILDER', buildopts.builder)
print(TXT_GREEN('yes'))
@new_task
def check_omit_leaf_frame_pointer_flag(makefile: Makefile):
pcheck('if compiler support -mno-omit-leaf-frame-pointer')
code, _, _ = run_command([buildopts.cc, '-x', 'c', '-Werror', '-',
'-mno-omit-leaf-frame-pointer', '-o', '/dev/null'],
standard_c, push_sys_dir=True)
if code:
print(TXT_CYAN('no'))
makefile.inject('ARCH_PRESERVE_FP', '')
else:
print(TXT_GREEN('yes'))
makefile.inject('ARCH_PRESERVE_FP', '-mno-omit-leaf-frame-pointer')
taskmgr.run_tasks()
# vars not injected: EXTRA_CFLAGS EXTRA_LDFLAGS DEBUG_LEVEL PREFIX BINDIR ZSH_FPATH MANDIR DOCDIR DESTDIR SYS_INC_DIR SYS_LIB_DIR IS_STATIC
taskmgr.makefile.inject('EXTRA_CFLAGS', buildopts.cflags)
taskmgr.makefile.inject('EXTRA_LDFLAGS', buildopts.ldflags)
taskmgr.makefile.inject('DEBUG_LEVEL', str(buildopts.debug_level))
taskmgr.makefile.inject('PREFIX', buildopts.prefix)
taskmgr.makefile.inject('BINDIR', buildopts.bindir)
taskmgr.makefile.inject('ZSH_FPATH', buildopts.zshfpath)
taskmgr.makefile.inject('MANDIR', buildopts.mandir)
taskmgr.makefile.inject('DOCDIR', buildopts.docdir)
taskmgr.makefile.inject('DESTDIR', buildopts.destdir)
taskmgr.makefile.inject('IS_STATIC', '1' if buildopts.is_static else '0')
taskmgr.makefile.inject('SYS_INC_DIR', f'-I{buildopts.sys_includedir}' if buildopts.sys_includedir else '')
taskmgr.makefile.inject('SYS_LIB_DIR', f'-L{buildopts.sys_libdir}' if buildopts.sys_libdir else '')
assert taskmgr.makefile.s.find('{{') == -1
print('Writting back to Makefile... ', end='', flush=True)
try:
with open('Makefile', 'w') as f:
f.write(taskmgr.makefile.s)
except Exception as e:
print(TXT_RED('failed'))
error(f'Unexpected error when write back: {e}')
else:
print(TXT_GREEN('ok'))
ceccomp-4.0/docs/ 0000775 0000000 0000000 00000000000 15142051300 0013705 5 ustar 00root root 0000000 0000000 ceccomp-4.0/docs/.gitignore 0000664 0000000 0000000 00000000005 15142051300 0015670 0 ustar 00root root 0000000 0000000 *.mo
ceccomp-4.0/docs/Makefile 0000664 0000000 0000000 00000000146 15142051300 0015346 0 ustar 00root root 0000000 0000000 # NOTE: Don't edit translated adoc directly! They are automatically generated.
update:
po4a po4a.cfg
ceccomp-4.0/docs/boot-slate.css 0000664 0000000 0000000 00000012651 15142051300 0016475 0 ustar 00root root 0000000 0000000 /* SPDX-License-Identifier: MIT */
/* Based on Slate from Bootswatch (https://bootswatch.com/slate/) */
/* This style sheet is distributed under MIT License */
/* document body (contains all content) */
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.42857143;
color: #c8c8c8;
background-color: #272b30;
margin-left: 10%;
margin-right: 10%;
}
/* document header (contains title etc) */
#header {
width: 100%;
}
#header>h1 {
border-bottom: 1px solid #ddddd8;
padding-bottom: 8px;
}
/* headings */
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 500;
line-height: 1.1;
color: inherit;
}
h1,
h2,
h3 {
margin-top: 20px;
margin-bottom: 10px;
}
h4,
h5,
h6 {
margin-top: 10px;
margin-bottom: 10px;
}
h1 {
font-size: 4em;
/* font-size: 36px; */
}
h2 {
font-size: 30px;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 18px;
}
h5 {
font-size: 14px;
}
h6 {
font-size: 12px;
}
/* plain paragraph text */
.paragraph {
/* font-family: sans-serif; */
margin: 0 0 10px;
}
p {
/* font-family: sans-serif; */
margin: 0 0 10px;
}
/* blockquote text */
.quoteblock {
font-style: italic;
}
blockquote {
padding: 10px 20px;
margin: 0 0 20px;
font-size: 17.5px;
border-left: 5px solid #7a8288;
}
blockquote p:last-child,
blockquote ul:last-child,
blockquote ol:last-child {
margin-bottom: 0;
}
.blockquote-reverse,
blockquote.pull-right {
padding-right: 15px;
padding-left: 0;
border-right: 5px solid #7a8288;
border-left: 0;
text-align: right;
}
.blockquote-reverse footer:before,
blockquote.pull-right footer:before,
.blockquote-reverse small:before,
blockquote.pull-right small:before,
.blockquote-reverse .small:before,
blockquote.pull-right .small:before {
content: '';
}
.blockquote-reverse footer:after,
blockquote.pull-right footer:after,
.blockquote-reverse small:after,
blockquote.pull-right small:after,
.blockquote-reverse .small:after,
blockquote.pull-right .small:after {
content: '\00A0 \2014';
}
/* blockquote attribution text */
.attribution,
.cite,
blockquote footer,
blockquote small,
blockquote .small {
display: block;
line-height: 1.42857143;
color: #7a8288;
}
.attribution:before,
blockquote footer:before,
blockquote small:before,
blockquote .small:before {
content: '\2014 \00A0';
}
/* unordered list */
ul, ol {
margin-top: 0;
margin-bottom: 10px;
}
ul ul,
ol ul,
ul ol,
ol ol {
margin-bottom: 0;
}
/* links */
a {
color: #ffffff;
text-decoration: none;
}
a:hover,
a:focus {
color: #ffffff;
text-decoration: underline;
}
a:focus {
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
/* horizontal rules */
hr {
margin-top: 20px;
margin-bottom: 20px;
border: 0;
border-top: 1px solid #1c1e22;
}
/* table */
table {
background-color: transparent;
width: 100%;
max-width: 100%;
margin-bottom: 21px;
border-collapse: collapse;
}
table col[class*="col-"] {
position: static;
float: none;
display: table-column;
}
table td[class*="col-"],
table th[class*="col-"] {
position: static;
float: none;
display: table-cell;
}
/* table caption */
caption {
padding-top: 8px;
padding-bottom: 8px;
color: #7a8288;
text-align: left;
}
/* table header row */
thead {
border-bottom: 2px solid #1c1e22;
}
/* table header cell */
th {
text-align: left;
padding-left: 8px;
}
/* table footer */
tfoot {
color: #807F81;
border-top: 1px solid #1c1e22;
}
/* table cell */
td {
border-top: 1px solid #1c1e22;
}
td p {
margin: auto;
padding: 8px;
}
/* table body */
tbody > tr:nth-of-type(odd) {
background-color: #353a41;
}
tbody > tr:hover {
background-color: #49515a;
}
/* inline code */
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
code {
padding: 2px 4px;
font-size: 90%;
color: #e3c7d2;
background-color: #444951;
border-radius: 4px;
}
kbd {
padding: 2px 4px;
font-size: 90%;
color: #ffffff;
background-color: #333333;
border-radius: 3px;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.25);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.25);
}
kbd kbd {
padding: 0;
font-size: 100%;
font-weight: bold;
-webkit-box-shadow: none;
box-shadow: none;
}
pre {
display: block;
padding: 9.5px;
margin: 0 0 10px;
font-size: 13px;
line-height: 1.42857143;
word-break: break-all;
word-wrap: break-word;
color: #dcc1cc;
background-color: #33373d;
border: 1px solid #cccccc;
border-radius: 4px;
}
pre code {
padding: 0;
font-size: inherit;
color: inherit;
white-space: pre-wrap;
background-color: transparent;
border-radius: 0;
}
/* image */
img {
max-width: 100%;
vertical-align: middle;
}
/* footer section */
#footer {
margin-top: 22px;
padding: 14px 16px;
background-color: #3a3f44;
}
/* responsiveness fixes */
video {
max-width: 100%;
}
/* table of Contents sidebar */
#toctitle {
color: #272b30;
}
#toc ul {
display: inline;
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
}
#toc li {
display: block;
}
#toc a {
background-color: #3a3f44;
float: left;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
#toc li a:hover {
background-color: #272b2e;
text-decoration: none;
}
#toc:after {
content: " ";
visibility: hidden;
display: block;
height: 0;
clear: both;
}
@media all and (max-width: 600px) {
table {
width: 55vw!important;
font-size: 3vw;
}
}
ceccomp-4.0/docs/ceccomp.adoc 0000664 0000000 0000000 00000040445 15142051300 0016155 0 ustar 00root root 0000000 0000000 = ceccomp(1)
dbgbgtf ; RocketDev
:doctype: manpage
:docdatetime: {TAG_TIME}
:manmanual: Ceccomp Manual
:mansource: ceccomp {VERSION}
:manversion: {VERSION}
:imagesdir: images/
:stylesheet: boot-slate.css
== NAME
ceccomp - A tool to analyze seccomp filters
== SYNOPSIS
usage: ceccomp [FILE] [-q|--quiet]
[-f|--format FMT] [-a|--arch ARCH] [-p|--pid PID] [-s|--seize]
[-o|--output FILE] [-c|--color WHEN] ...
== CONCEPT
Kernel use BPF filters to limit syscall rules, applied via `seccomp` or `prctl`
syscall. For example, down below is a simple filter to block `execve` syscall in
hex format:
1: 20 00 00 00 00 00 00 00 $A = $syscall_nr
2: 15 00 00 01 3b 00 00 00 if ($A != execve) goto 4
3: 06 00 00 00 00 00 00 00 return KILL
4: 06 00 00 00 00 00 ff 7f return ALLOW
The part presented in hex is what kernel received, and `ceccomp` take it to
disassemble back to human readable text. For instance the *lineno* in the left
and *statement* in the right.
IMPORTANT: Later I'll use _TEXT_ in short for BPF human readable text, and use
_RAW_ in short for BPF raw format, please keep that in mind.
== DESCRIPTION
`ceccomp` have 5 main functions, basically it's a C version of `seccomp-tools`,
however, there are some breaking changes you need to know, which will be
highlighted in each subcommand section.
=== asm - ASSEMBLE
ceccomp asm [-c WHEN] [-a ARCH] [-f FMT] [TEXT]
Assemble _TEXT_ to _RAW_. Use it to embed hand written filter rules into C code
or to see the original code of some _TEXT_.
WHEN::
Determines when to display warnings and errors in color. If the value is _auto_,
ceccomp will display color when the output target is a "tty". Can be _auto_, _never_ or
_always_. The default value is _auto_.
ARCH::
Set to any architecture libseccomp supports. Will be used to determine
the actual syscall number behind the name (for example, on x86_64, you could write
`"execve"` instead of `59` like the basic example above). Your system arch will be
taken if not set via `uname`. The default value on your system is {ARCH}.
NOTE: Since _version 4.0_, endianness is considered. If target endianness *ARCH* is
different from machine endianness, the filters will be reversed (CODE and K) before
outputting.
FMT::
Determines how `ceccomp` produces binary-format bpf code. Can be _hexfmt_,
_hexline_ or _raw_. You could find sample output in <> section.
The default value is _hexline_.
TEXT::
Take a optional filename to determine which file containing _TEXT_ will
be assembled. Will read from _stdin_ if not set. `-` is treated as _stdin_.
IMPORTANT: The assembly syntax was changed greatly since _version 4.0_,
please checkout grammar reference below!
Please check out <> section to see how to write a rule by
hand. Some examples will be displayed in <> section.
|===
|Command|Difference
|`seccomp-tools asm`
|Use its own grammar to assemble, a bit script like; can assemble invalid _TEXT_
which will be rejected by kernel
|`ceccomp asm`
|You can just take `disasm` output to `asm`, no new grammar is needed to learn;
take `stdin` as input by default
|===
=== disasm - DISASSEMBLE
ceccomp disasm [-c WHEN] [-a ARCH] [RAW]
Disassemble _RAW_ to _TEXT_. Use it to see what does a filter do if you could not
access filter via `trace` and have to manually extract the filter out.
WHEN::
Argument description can be found in <> section. `disasm` may print
more text in color including syntax highlighting for _TEXT_.
ARCH::
Set to any architecture libseccomp supports. Will be used to determine
how filtered syscall number in _RAW_ filter is translated to syscall name (for example,
on x86_64, the number `0x3b` is translated to `execve` if is comparing syscall_nr, see
the basic example above). The default value on your system is {ARCH}.
RAW::
A binary file with raw BPF codes. Takes _stdin_ as input if not set. Treat `-` as _stdin_.
The file is arch-revelent, so it may not be portable on different archs.
NOTE: Since _version 4.0_, endianness is considered. If target endianness *ARCH* is
different from machine endianness, the filters will be reversed (CODE and K) before
decoding.
NOTE: ceccomp will try to resolve syscall number under an arch ONLY IF that at that line,
arch can be determined. On foreign arch (not equal to the arch you set), the foreign arch
will be prepended to syscall name. You may notice that in some cases, seccomp-tools is able
to resolve the name while ceccomp is not, that may be intended as the arch is not determined.
|===
|Command|Difference
|`seccomp-tools disasm`
|Disassembles in its format; never check if the filter is valid
|`ceccomp disasm`
|Disassembles in ceccomp format, and takes `stdin` as input by default; check arch strictly
and always display foreign arch name
|===
=== emu - EMULATE
ceccomp emu [-c WHEN] [-a ARCH] [-q] TEXT SYSCALL_NAME/SYSCALL_NR [ARGS[0] ARGS[1] ... ARGS[5] PC]
Emulate what will happen if `syscall(SYSCALL_NR, ARGS[0], ARGS[1], ..., ARGS[5])`
from `PC` is called following rules described in _TEXT_. Use it to see the result
without actually running it in program or you don't want to examine the filter rule
manually. This subcommand can be used to automatically examining a filter.
WHEN::
Argument description can be found in <> section. `emu` may print
more text in color including syntax highlighting for _TEXT_ and skipped statements.
SYSCALL_NAME/SYSCALL_NR::
If you set *SYSCALL_NAME* (like `execve`), it will be translated to *SYSCALL_NR*
under *ARCH* first. Or else set *SYSCALL_NR* directly (like `59`). Then the nr
will be tested against the bpf filter to see the result of that syscall. This
argument is NOT optional.
ARGS[0-5] and PC::
Register values when calling syscall. For example,
on x86_64, these are equivalent to `rdi`, `rsi`, `rdx`, `r10`, `r8`, `r9` and
`rip`. Their default value is 0.
ARCH::
Argument description can be found in <> section.
TEXT::
Take a filename to determine which file containing _TEXT_ rule will be tested.
Note that filename CAN NOT be ignored as ceccomp can not determine if a
positional argument is syscall or filename. Use `-` to refer to _stdin_.
-q, --quiet::
Only print the eval result of the filter. For example, if last statement emulated
is `return KILL`, then `KILL` is printed.
|===
|Command|Difference
|`seccomp-tools emu`
|Take a _RAW_ as input
|`ceccomp emu`
|Take a _TEXT_ as input and take `stdin` as input by default; set *PC* is
possible
|===
=== trace - TRACE FILTER IN RUNTIME
ceccomp trace [-c WHEN] [-q] [-o FILE] PROGRAM [program-args]
[-c WHEN] [-q] -p PID [-s]
The first line captures filters *PROGRAM* loads in runtime by tracing it;
the second line extract seccomp filters from *PID*, or trace *PID* to capture
subsequent seccomp filters; once fetched filters, print them in _TEXT_.
You can only choose one of the two formats above. Use this if running the
program is the simplest way to fetch bpf filters or a program with seccomp
filters installed is waiting for input.
WHEN::
Argument description can be found in <> section. `trace` may print
more text in color including syntax highlighting for _TEXT_.
FILE::
May be useful when *PROGRAM* produces quite a lot output in _stderr_.
`ceccomp` allow user to close _stdin_ and _stdout_ to limit *PROGRAM*
input and output, so `ceccomp` use _stderr_ to print messages when running *PROGRAM*,
set *FILE* if you want to see _TEXT_ in some other file. Treat `-` as _stdout_.
PROGRAM::
Set to the program you want to run, and *program-args* are its
arguments just like running shell command `exec PROGRAM program-args`.
PID::
Set to the pid you want to inspect. *PID* is conflict with *PROGRAM*;
you could either run a program dynamically or examine a pid in one command.
Without `-s` flag, trace pid will try to extract seccomp filter in *PID* via
`ptrace(PTRACE_SECCOMP_GET_FILTER)`, which may not be available in some systems.
-s, --seize::
*ONLY AVAILABLE FOR TRACE PID MODE.* Set this flag will override trace pid
behavior to attach to *PID* and keep tracing for seccomp filter loading like
trace prog mode. _This flag was introduced in version 4.0._
-q, --quiet::
Set to suppress the extra *[INFO]* prints when detect process forking, exiting or
seccomp filter loading. _This flag was introduced in version 4.0._
NOTE: To extract filters from *PID*, `CAP_SYS_ADMIN` is needed (without `-s` flag)
and `CAP_SYS_PTRACE` may also be needed, the easiest way to acquire
them is calling `ceccomp` with `sudo`.
NOTE: Since _version 3.1_, multiple process tracing is introduced, and when tracee
forking/resolving/exiting, an extra INFO message is printed. You can discard
it by running command like `ceccomp trace -q PROG 2>/dev/null`.
|===
|Command|Difference
|`seccomp-tools dump`
|Setting output format is possible; each filter can be output to a different
file; killing *PROGRAM* once *LIMIT* times of filters loaded; wrapping *PROGRAM*
in `sh -c`
|`ceccomp trace`
|All filters are output to a single file; never kill *PROGRAM*; *PROGRAM* is
launched directly, so `./` is not needed; explicitly print when forking;
able to attach to pid for dynamic seccomp filter capturing
|===
=== probe - TEST COMMON SYSCALLS INSTANTLY
ceccomp probe [-c WHEN] [-o FILE] [-q] PROGRAM [program-args]
Run *PROGRAM* with *program-args* to captures *FIRST* seccomp filter, and then
kill all children. Use it when a quick check against a program is needed,
and detect potential seccomp rule issues.
All argument descriptions can be found in <> section.
The output for this subcommand is the emulating result of common syscalls
like `execve`, `open` and so on. If the filter itself is not capable of
blocking syscalls, you could know that with a glance.
Typical output for this subcommand is described below, more detailed example
could be found in <> section.
open -> ALLOW
read -> ALLOW
write -> ALLOW
execve -> KILL
execveat -> KILL
mmap -> ALLOW
mprotect -> ALLOW
openat -> ALLOW
sendfile -> ALLOW
ptrace -> ERRNO(1)
fork -> ALLOW
NOTE: `seccomp-tools` don't have this subcommand.
== TEXT GRAMMAR REFERENCE
IMPORTANT: The grammar changed greatly since _version 4.0_ as we
refactored lexer for better human readability. The wrapper now prefixed by
`#` as it's a comment now. And _line_ is replaced by _label_, so now lexer
depends on label declaration to decide where to jump, instead of lineno in
_TEXT_ file.
A valid _TEXT_ format is described in EBNF-like declaration here:
https://github.com/dbgbgtf1/Ceccomp/issues/17#issuecomment-3610531705.
If you have no interest to know what EBNF is, please keep reading for
examples.
BPF ops which are not described below are banned by kernel.
=== Comment and Label
`ceccomp disasm` displays a lot of things, but some of them are optional
for asm.
#Label CODE JT JF K
#---------------------------------
L0001: 0x06 0x00 0x00 0x7fff0000 return ALLOW
#---------------------------------
Any text after `#` will be discarded by asm like some script languages.
Empty lines are accepted.
Label declaration is an identifier at the beginning of line and suffixed
by `:` like `L0001`. An identifier is a string starts with alpha and contains with
only alphanumeric characters and underscore `_`. Label is only necessary if
it's the destination of `goto`, these redundant labels added by disasm are for
readability. E.g. in `if ($A == 0) goto somewhere`, `somewhere` is a label and
must be declared after the statement. Label declaration can take a line separately,
or be put in front of statement.
The `CODE`, `JT`, `JF` and `K` value generated by disasm will be discarded by asm,
asm only parse the effective statement after `K`.
NOTE: There are some slight difference between `ceccomp disasm` and
`seccomp-tools disasm`, down below is a general example. And some
statements are different, so don't pipe seccomp-tools output to ceccomp
blindly.
line CODE JT JF K
=================================
0000: 0x06 0x00 0x00 0x7fff0000 return ALLOW
=== Assignment
`A` can be set to seccomp attributes directly. But `X` can not be assigned with
seccomp attributes directly due to kernel limit.
$A = $arch
$A = $syscall_nr
To assign `A` with those 64-bit long fields, `low_` or `high_` prefix is needed.
$A = $low_pc
$A = $high_pc
$A = $low_args[0]
$A = $high_args[0]
...
$A = $low_args[5]
$A = $high_args[5]
A special attribute is `sizeof(struct seccomp_data)`, that can be assigned to
`A` or `X` directly.
$A = $scmp_data_len
$X = $scmp_data_len
Temporary memory is 32-bit, to access them, you could use hex or dec as index.
Both `A` and `X` is assignable. Assigning immediate values to `A` or `X` accepts
any format of number if you imply the correct base by "0x" or "0b".
$X = $mem[0]
$A = $mem[0xf]
$A = $mem[15] # both hex and dec index are OK
$A = 0
$X = 0x3b
$A = 0b1111
$A = 0333
You could also assign `X` to `A` or in the reverse order. Assign `X` or `A` to
temporary memory is definitely okay.
$A = $X
$X = $A
$mem[3] = $X
$mem[0x4] = $A
=== Arithmetic Operations
Various operations can be applied to `A`.
$A += 30
$A -= 4
$A *= 9
$A /= 1
$A &= 7
$A >>= 6
The right value can be `X`.
$A &= $X
$A |= $X
$A ^= $X
$A <<= $X
And there is a way to negativate `A`.
$A = -$A
=== Jump Downwards If ...
Unconditional jump:
goto L3
Jump if:
if ($A == execve) goto L3
if ($A != 1234) goto L4
if ($A & $X) goto L5
if !($A & 7) goto L6
if ($A <= $X) goto L7
If true jump to ... if false jump to...:
if ($A > $X) goto L3, else goto L4
if ($A >= 4567) goto L5, else goto L6
ONLY in conditions, you CAN replace number with syscall name or arch name.
In example above, `0x3b` is replaced by `execve`. All the syscall name will be
resolved to syscall number under your selected arch. If you want to resolve
a syscall name in foreign arch (not equal to your selected arch), please
prepend a arch and dot. For example, your arch is x86_64, and you are writing
_aarch64_ rules, then please write like:
if ($A == aarch64.read) goto 5
Note that if you manually set arch to _aarch64_ with `-a aarch64`,
you can omit `aarch64.` in statement.
=== Return Code
Return value of register `A`:
return $A
Or return a immediate value, with extra field in `()`. Actions including
`TRACE`, `TRAP` and `ERRNO` accept an extra field, without `()`, they are
treated as `action(0)`.
return 0x13371337
return KILL
return KILL_PROCESS
return TRAP(123)
return ERRNO(0)
return TRACE
return TRACE(3)
return LOG
return NOTIFY
=== Short Example
The following _TEXT_ is valid for asm, which blocks `execve` and `execveat`
for amd64 syscalls:
$A = $syscall_nr
if ($A == execve) goto forbid
if ($A == execveat) goto forbid
return ALLOW
forbid: return KILL
== RESTRICTIONS
Ceccomp asm put some restrictions on _TEXT_ for better performance.
1. `'\0'` must not be found in _TEXT_ since it's a text file.
2. A line must be shorter than 384 *bytes*.
3. A _TEXT_ file must have less than 4096 lines.
4. A _TEXT_ file must be smaller than 1 MiB.
And for both asm and disasm, effective statements (that can be encoded or decoded
into BPF) must be less or equal than 1024, this is enforced by kernel.
A fun fact about ceccomp asm: any basic ANSI color in _TEXT_ file,
e.g., `\x1b[31m`, will be discarded when processing.
== EXAMPLES
ifdef::backend-manpage[]
Manpage can not display images, so please check out html version of
this page to see examples.
endif::[]
ifndef::backend-manpage[]
=== asm example
image::asm.webp[]
=== disasm example
image::disasm.webp[]
=== emu example
image::emu.webp[]
=== trace example
Running program:
image::trace.webp[]
If set `-o FILE`:
image::output_trick.webp[]
Trace pid mode:
image::trace_pid.webp[]
Seize pid mode:
image::trace_seize.webp[]
Completion for pid mode is available under zsh:
image::trace_completion.webp[]
=== probe example
image::probe.webp[]
endif::[]
== REPO
Visit https://github.com/dbgbgtf1/Ceccomp to find the code.
Pull Requests and Issues are welcome!
Copyright (C) 2025-present, distributed under GPLv3 or later.
ceccomp-4.0/docs/ceccomp.zh_CN.adoc 0000664 0000000 0000000 00000041457 15142051300 0017161 0 ustar 00root root 0000000 0000000 = ceccomp(1)
dbgbgtf ; RocketDev
:doctype: manpage
:docdatetime: {TAG_TIME}
:manmanual: Ceccomp Manual
:mansource: ceccomp {VERSION}
:manversion: {VERSION}
:imagesdir: images/
:stylesheet: boot-slate.css
== 名称
ceccomp - 一个分析安全计算 (seccomp) 过滤器的工具
== 大纲
usage: ceccomp [FILE] [-q|--quiet]
[-f|--format FMT] [-a|--arch ARCH] [-p|--pid PID] [-s|--seize]
[-o|--output FILE] [-c|--color WHEN] ...
== 概念
内核使用BPF过滤器来限制系统调用规则,并使用 `seccomp` 和 `prctl` 两个系统调用来安装过滤器。以下是一个以十六进制表示的限制 `execve` 系统调用的简单过滤器:
1: 20 00 00 00 00 00 00 00 $A = $syscall_nr
2: 15 00 00 01 3b 00 00 00 if ($A != execve) goto 4
3: 06 00 00 00 00 00 00 00 return KILL
4: 06 00 00 00 00 00 ff 7f return ALLOW
以上十六进制的部分就是内核收到的过滤器,而 `ceccomp` 负责把它拿来反汇编为人类可读的文本。 例如左侧的 *行号* 和右侧的 *伪代码* 。
IMPORTANT: 之后我会使用 _TEXT_ 作为BPF过滤器人类可读文本(伪代码)的缩写, 使用 _RAW_ 作为BPF过滤器原始格式的缩写,请记住这个约定。
== 描述
`ceccomp` 有5个主要的功能,它基本上是C版本的 `seccomp-tools` ,然而, 有一些不同的地方你需要知道,它们会在在每个子命令的章节中被注明。
=== asm - 汇编
ceccomp asm [-c WHEN] [-a ARCH] [-f FMT] [TEXT]
将 _TEXT_ 汇编为 _RAW_ 。适用于将手写的过滤器规则嵌入到C代码中, 或希望观察一些 _TEXT_ 对应的原始字节码。
WHEN::
决定了 `ceccomp` 何时输出有颜色的文本。当设置为 _auto_ 时, `ceccomp` 会在输出目标是一个“tty”时打印颜色。可以是 _auto_ 、 _never_ 或者 _always_ 。 默认值是 _auto_ 。
ARCH::
可以设置为任何 libseccomp 支持的架构。它将被用于决定系统调用名称对应的系统调用号。 例如,在 x86_64 上,就像上面的基本示例,你可以写 `"execve"` 而不是数字 `59` 指代系统调用号。如果不设置这个参数,则通过 `uname` 提取当前系统的架构。 你的系统上的默认值是 {ARCH} 。
NOTE: 从 _4.0 版本_ 开始考虑端序。如果目标架构 *ARCH* 的端序与机器端序不同,则会在输出前反转过滤器(CODE 和 K)。
FMT::
决定了 `ceccomp` 如何输出二进制格式的BPF字节码。可以是 _hexfmt_ 、 _hexline_ 或者 _raw_ 。你可以在 <> 节中找到示例输出。默认值是 _hexline_ 。
TEXT::
一个可选的文件名,其中存放了需要被汇编的 _TEXT_ 。不设置则从 _标准输入_ 中读取。`-` 被视作 _标准输入_。
IMPORTANT: _4.0 版本_ 大幅修改了汇编的语法,请查阅下面的语法参考!
查看 <> 一节可以找到如何手写规则。一些示例会在 <> 一节中展示。
|===
|命令|差别
|`seccomp-tools asm`
|使用它自己的语法汇编,有点像脚本;可以汇编会被内核拒绝的错误 _TEXT_
|`ceccomp asm`
|你可以直接拿着 `disasm` 的输出来汇编,不需要学习新语法;默认使用 _标准输入_ 作为输入
|===
=== disasm - 反汇编
ceccomp disasm [-c WHEN] [-a ARCH] [RAW]
反汇编 _RAW_ 为 _TEXT_ 。适用于当你无法使用 `trace` 看到过滤器时,必须手动提取过滤器, 然后检查其含义。
WHEN::
参数描述可以在 <> 一节中找到。 `disasm` 可能会打印更多有颜色的文本,包括针对 _TEXT_ 的语法高亮。
ARCH::
可以设置为任何 libseccomp 支持的架构。它将被用于决定 _RAW_ 中的系统调用号如何被翻译为系统调用名。 例如,在 x86_64 上,在比较系统调用号时,数字 `0x3b` 将被翻译为 `execve` ,可以看上面的基本示例。 你的系统上的默认值是 {ARCH} 。
RAW::
包含原始 BPF 代码的二进制文件。如果不设置则将 _标准输入_ 作为输入。`-` 被视作 _标准输入_。这个文件是与架构有关的,所以它在不同架构之间可能不是通用的。
NOTE: 从 _4.0 版本_ 开始考虑端序。如果目标架构 *ARCH* 的端序与机器端序不同,则会在解码前反转过滤器(CODE 和 K)。
NOTE: 当且仅当在某一行的架构可以被确定时,ceccomp 才会尝试用那个架构解析那个系统调用号。 如果是外部架构(不等于你设置的架构),它会被附加到系统调用名前。你可能会注意到在一些情况下, seccomp-tools 能解析一些系统调用名,而 ceccomp 不能,这可能是因为此时架构不能被确定。
|===
|命令|差别
|`seccomp-tools disasm`
|用它自己的语法反汇编;永远不会检查 _RAW_ 是否合法
|`ceccomp disasm`
|用 ceccomp 语法反汇编,并且默认将 _标准输入_ 作为输入;严格检查架构,
并且永远打印外部架构名
|===
=== emu - 模拟
ceccomp emu [-c WHEN] [-a ARCH] [-q] TEXT SYSCALL_NAME/SYSCALL_NR [ARGS[0] ARGS[1] ... ARGS[5] PC]
按照 _TEXT_ 中描述的规则,模拟从 `PC` 调用 `syscall(SYSCALL_NR, ARGS[0], ARGS[1], ..., ARGS[5])` 的结果。适用于在不实际运行程序或不想手动检查规则时,查看触发系统调用的结果。 这个子命令适合用来自动检测一个过滤器。
WHEN::
参数描述可以在 <> 一节中找到。 `emu` 可能会打印更多有颜色的文本,包括针对 _TEXT_ 的语法高亮以及跳过的伪代码。
SYSCALL_NAME/SYSCALL_NR::
如果你设置了 *SYSCALL_NAME* (比如 `execve` ),那么它会基于 *ARCH* 先被翻译为对应的 *SYSCALL_NR* 。或者你可以直接设置 *SYSCALL_NR* (例如 `59` )。然后会测试这个系统调用号经过 BPF 过滤器处理后的输出并打印出来。这个参数是必填的。
ARGS[0-5] 和 PC::
当调用系统调用时对应寄存器的值。例如,在 x86_64 上,它们分别对应了 `rdi` 、 `rsi` 、 `rdx` 、 `r10` 、 `r8` 、 `r9` 和 `rip` 。它们的默认值都是0。
ARCH::
参数描述可以在 <> 一节中找到。
TEXT::
一个文件名,其中存放了需要被测试的 _TEXT_ 规则。注意文件名 不能 被忽略,因为 ceccomp 无法判断一个位置参数是系统调用号还是文件名。使用 `-` 可以指代 _标准输入_。
-q, --quiet::
只打印过滤器的模拟结果。例如,最后一行模拟的伪代码是 `return KILL`,那么将会打印 `KILL`。
|===
|命令|差别
|`seccomp-tools emu`
|用 _RAW_ 作为输入
|`ceccomp emu`
|用 _TEXT_ 作为输入,并默认将 _标准输入_ 作为输入;可以设置 *PC*
|===
=== trace - 运行时捕获过滤器
ceccomp trace [-c WHEN] [-o FILE] PROGRAM [program-args]
[-c WHEN] -p PID [-s]
使用第一行的命令可以利用调试在 *PROGRAM* 运行中加载过滤器时动态捕获过滤器; 第二行的命令可以从 *PID* 对应的进程中提取出 seccomp 过滤器,或通过调试 *PID* 捕获后续的 seccomp 过滤器;一旦捕获到了过滤器, 将会以 _TEXT_ 的格式将它打印出来。你可以从两个格式中选择一个使用。 适用于运行一个程序是捕获BPF过滤器最简单的方式或者一个安装了 seccomp 过滤器的程序正在等待输入。
WHEN::
参数描述可以在 <> 一节中找到。 `trace` 可能会打印更多有颜色的文本,包括针对 _TEXT_ 的语法高亮。
FILE::
当 *PROGRAM* 会产生很多输出到 _标准错误_ 时可能很有用。 `ceccomp` 允许用户关闭 _标准输入_ 和 _标准输出_ 来限制 *PROGRAM* 的输入和输出,所以 当运行 *PROGRAM* 时 `ceccomp` 使用 _标准错误_ 来打印消息。如果你想在别的文件中看见 _TEXT_ 的话请设置 *FILE* 。`-` 被视作 _标准输出_。
PROGRAM::
设置为你想运行的程序,并且 *program-args* 将作为它的参数, 就像运行 shell 命令 `exec PROGRAM program-args` 。
PID::
设置为你想检查的 pid。 *PID* 和 *PROGRAM* 相冲突;你只能在一条命令中动态运行一个程序, 或者检查一个 pid。没有 `-s` 标志,trace pid 会尝试使用 `ptrace(PTRACE_SECCOMP_GET_FILTER)` 从 *PID* 中提取 seccomp 过滤器,这个操作在一些系统上可能不可用。
-s, --seize::
*只适用于 TRACE PID 模式。* 设置这个标志将会覆盖 trace pid 的行为为像 trace prog 模式一样把调试器挂到 *PID* 上并持续跟踪 seccomp 过滤器的加载。_这个标志引入于 4.0 版本。_
-q, --quiet::
设置这个标志将会在检测到进程分叉、退出或加载 seccomp 过滤器时抑制多余的 *[INFO]* 输出。 _这个标志引入于 4.0 版本。_
NOTE: 要想从 *PID* 中提取过滤器,你需要 `CAP_SYS_ADMIN` (没有 `-s` 标志),同时还可能需要 `CAP_SYS_PTRACE` ,最简单的获取它们的方法是用 `sudo` 运行 `ceccomp` 。
NOTE: 从 _3.1 版本_ 开始引入了多进程支持,并且当被调试进程 fork/resolve/exit 时,将会打印一条额外的 INFO 信息。你可以使用像 `ceccomp trace -q PROG 2>/dev/null` 这样的命令丢弃它。
|===
|命令|差别
|`seccomp-tools dump`
|可以设置输出格式;每一个过滤器可以输出到不同的文件;当 *PROGRAM*
加载了 *LIMIT* 个过滤器后就杀死程序;将 *PROGRAM* 包装在 `sh -c` 中运行
|`ceccomp trace`
|所有过滤器被输出到同一个文件;永远不会杀死 *PROGRAM* ; *PROGRAM* 是直接被执行的,
所以不需要 `./` ;当 fork 时,显式打印事件;能够附加调试器到 pid 上动态捕捉 seccomp 过滤器
|===
=== probe - 快速测试常见的系统调用
ceccomp probe [-c WHEN] [-o FILE] [-q] PROGRAM [program-args]
以 *program-args* 为参数运行 *PROGRAM* 来捕获 *第一个* seccomp 过滤器, 然后杀死所有子进程。适用于快速测试一个程序的规则并检测潜在的 seccomp 规则问题。
所有参数描述都可以在 <> 一节中找到。
这个子命令的输出是一系列常见的系统调用的模拟结果,例如 `execve` 、 `open` 等。 如果过滤器本身并不能阻拦系统调用,那你一眼就能看出来。
这个子命令的典型输出如下所示,更多完整的实例可以在 <> 一节中找到。
open -> ALLOW
read -> ALLOW
write -> ALLOW
execve -> KILL
execveat -> KILL
mmap -> ALLOW
mprotect -> ALLOW
openat -> ALLOW
sendfile -> ALLOW
ptrace -> ERRNO(1)
fork -> ALLOW
NOTE: `seccomp-tools` 没有等价的子命令。
== TEXT 语法参考
IMPORTANT: _4.0 版本_ 提高了词法分析器代码的可读性,伴随着大幅修改的语法。前缀为 `#` 的行现在是注释了。同时 _行号_ 被替换为 _标签_,现在词法分析器根据标签定义来决定跳转到哪里,而不是根据 _TEXT_ 文件中的行号。
这里有正确的 _TEXT_ 格式,以类 EBNF 语法描述:https://github.com/dbgbgtf1/Ceccomp/issues/17#issuecomment-3610531705。 没兴趣了解 EBNF?请继续阅读以下的例子。
其余未描述到的BPF操作都被内核禁止了。
=== 注释与标签
`ceccomp disasm` 展示了很多东西,但对于 asm 来说有些是可选的。
#Label CODE JT JF K
#---------------------------------
L0001: 0x06 0x00 0x00 0x7fff0000 return ALLOW
#---------------------------------
任何在 `#` 之后的文本将被 asm 丢弃,就像一些脚本语言一样。
允许空行。
标签声明是一个从行首开始并以 `:` 结尾的标识符,例如 `L0001`。标识符是一个以字母为首,中间只包含字母、数字和下划线 `_` 的字符串。标签只在它是 `goto` 的目标时才是必要的,由 disasm 添加的多余的标签知识为了可读性。例如在 `if ($A == 0) goto somewhere` 中,`somewhere` 是一个标签并且必须在这行伪代码后声明。标签声明可以单独占据一行,也可以放置在伪代码的前面。
由 disasm 生成的 `CODE`、`JT`、`JF` 和 `K` 值会被 asm 丢弃,asm 之解析 `K` 之后的有效伪代码。
NOTE: `ceccomp disasm` 和 `seccomp-tools disasm` 的输出之间有很多细微的差别, 以下是一个典型的输出示例。同时有些伪代码是不同的,所以不要盲目将 seccomp-tools 的输出管道给 ceccomp。
line CODE JT JF K
=================================
0000: 0x06 0x00 0x00 0x7fff0000 return ALLOW
=== 赋值
`A` 可以直接赋值为 seccomp 属性。由于内核限制, `X` 不能直接赋值为 seccomp 属性。
$A = $arch
$A = $syscall_nr
要给 `A` 赋值为这些64位长的字段,必须使用 `low_` 或者 `high_` 的前缀。
$A = $low_pc
$A = $high_pc
$A = $low_args[0]
$A = $high_args[0]
...
$A = $low_args[5]
$A = $high_args[5]
一个特殊的属性是 `sizeof(struct seccomp_data)` ,它可以直接赋值给 `A` 或 `X` 。
$A = $scmp_data_len
$X = $scmp_data_len
临时内存是32位的,要想访问它们,你可以使用十六进制或者十进制的索引。 `A` 和 `X` 都是可赋值的。给 `A` 或 `X` 赋值为立即数接受任意格式的数字,只要你使用 "0x" 或者 "0b" 等前缀正确表达数字是几进制的。
$X = $mem[0]
$A = $mem[0xf]
$A = $mem[15] # both hex and dec index are OK
$A = 0
$X = 0x3b
$A = 0b1111
$A = 0333
你还可以将 `X` 赋值给 `A` 或者反过来。将 `X` 或 `A` 赋值给临时内存当然可以。
$A = $X
$X = $A
$mem[3] = $X
$mem[0x4] = $A
=== 数学运算
你可以以多种方式操作 `A` 。
$A += 30
$A -= 4
$A *= 9
$A /= 1
$A &= 7
$A >>= 6
右值也可以是 `X` 。
$A &= $X
$A |= $X
$A ^= $X
$A <<= $X
想要对 `A` 取反可以这么做。
$A = -$A
=== 当...时向下跳转
无条件跳转:
goto L3
当...跳转:
if ($A == execve) goto L3
if ($A != 1234) goto L4
if ($A & $X) goto L5
if !($A & 7) goto L6
if ($A <= $X) goto L7
当条件为真时跳转到...,条件为假时跳转到...:
if ($A > $X) goto L3, else goto L4
if ($A >= 4567) goto L5, else goto L6
*只有* 在做条件判断时,你才能将数字替换为系统调用号或架构名。在以上的例子中, `0x3b` 被 `execve` 替换。所有系统调用名将会以你设置的架构解析为系统调用号。 如果你希望解析外部架构(不等于你设置的架构)的系统调用名, 请在前面附加架构名和一个点。例如,你设置的架构是 x86_64,并且你正在写 _aarch64_ 架构的规则,请这样写:
if ($A == aarch64.read) goto 5
注意当你手动使用 `-a aarch64` 将架构设置为 _aarch64_ 时, 你可以在伪代码中忽略 `aarch64.` 。
=== 返回码
返回寄存器 `A` 的值:
return $A
或者返回一个立即数,多余的字段放在 `()` 里。 `TRACE` 、 `TRAP` 和 `ERRNO` 接受一个额外的字段,如果没有 `()` ,它们将被视为 `行为(0)` 。
return 0x13371337
return KILL
return KILL_PROCESS
return TRAP(123)
return ERRNO(0)
return TRACE
return TRACE(3)
return LOG
return NOTIFY
=== 简短的例子
下面的 _TEXT_ 对与 asm 来说是正确的,这段 _TEXT_ 阻止了 amd64 的 `execve` 和 `execveat` 系统调用:
$A = $syscall_nr
if ($A == execve) goto forbid
if ($A == execveat) goto forbid
return ALLOW
forbid: return KILL
== 限制
为了更好的性能,Ceccomp asm 对 _TEXT_ 有一些限制。
1. 由于 _TEXT_ 是个文本文件,`'\0'` 不能出现在 _TEXT_ 中。
2. 一行必须短于 384 *字节*。
3. 一个 _TEXT_ 文件必须短于 4096 行。
4. 一个 _TEXT_ 文家必须小于 1 MiB。
并且对于 asm 和 disasm 来说,有效的伪代码(能被编码或解码为 BPF 的)必须少于等于 1024 条,这是内核规定的。
一个关于 ceccomp asm 有趣的知识:任何在 _TEXT_ 文件中基本的 ANSI 颜色,例如 `\x1b[31m`,会在处理时被丢弃。
== ceccomp 示例
ifdef::backend-manpage[]
手册不能显示图片,因此如果想看示例请参阅html版本。
endif::[]
ifndef::backend-manpage[]
=== asm 示例
image::asm.webp[]
=== disasm 示例
image::disasm.webp[]
=== emu 示例
image::emu.webp[]
=== trace 示例
运行程序:
image::trace.webp[]
如果设置了 `-o FILE` :
image::output_trick.webp[]
PID 模式:
image::trace_pid.webp[]
跟踪 PID 模式:
image::trace_seize.webp[]
zsh下PID模式可以使用补全:
image::trace_completion.webp[]
=== probe 示例
image::probe.webp[]
endif::[]
== 仓库
在 https://github.com/dbgbgtf1/Ceccomp 可以找到源代码。 欢迎提交 Pull Requests 和 Issues !
Copyright (C) 2025-现在,基于 GPLv3 或更新版本分发。
ceccomp-4.0/docs/images/ 0000775 0000000 0000000 00000000000 15142051300 0015152 5 ustar 00root root 0000000 0000000 ceccomp-4.0/docs/images/asm.webp 0000664 0000000 0000000 00000165704 15142051300 0016626 0 ustar 00root root 0000000 0000000 RIFF WEBPVP8 0*>m0F#"!+kȀ
gn_S\8?_'+:ʧq~?گP~{B~{_`?z c#p?"߈~{kG_c}Gm
7?X~/O&_?mwۯ~co߷~A&e~K3{OO|/O{T?Os7f?`?O~ iG?_??/???k S1gA$0/^iS.vRb':pA9{T\d
red)T}Ӣn,J^1пyX{lL-'inv26LNZI *"灚Q=leъDz(c ^D!cԦWmeYM#*|ĉMEzXw䕙GVcN&9_ُi+JpE =ܛfK41.:Sa*E4:5p5ӢaxdKo">өHT(qڝ3=Kd\{w^4K|B|+d?SjPh9㤔HkRAf5b;@c\N2WXKX,<뭙7K[<1ea| WĩQ=>y\'k{/b*WbJ6ǫg5n
!@)\VV)H>+ &=kf{WNjI/Al^r7K{wRiuOlրu ?A&&:GWP?qyB\K.Eǔ!V"YӾ~ XL{aƉn[")zM6Z ,PEHHZ}$@O~kE4qٰ *k5B Ujh~+Ghγ:+f{z4ͣG}?-)dZt5\yR:69FSCAT 8Y G[l^fHŽcQwhY>l.Yu=#p2&