From 96e038df538c97aacc1347233c6338523645175b Mon Sep 17 00:00:00 2001 From: Henrick Mello Date: Tue, 11 Aug 2026 20:19:37 -0300 Subject: [PATCH] Add secure seamless Debian package installation --- .github/dependabot.yml | 7 + .github/workflows/ci.yml | 52 ++ .gitignore | 9 + ARCHITECTURE.md | 39 +- Cargo.lock | 2 +- Cargo.toml | 6 +- LICENSE | 117 ++++ README.md | 63 +- SECURITY.md | 38 ++ assets/io.github.devnvll.Debforge.desktop | 15 + assets/io.github.devnvll.Debforge.svg | 20 + assets/org.devnvll.debforge.policy | 20 + packaging/.SRCINFO | 26 + packaging/PKGBUILD | 52 ++ packaging/PKGBUILD.local | 56 ++ scripts/install-system.sh | 21 + scripts/install-user.sh | 17 + src/bin/debforge-helper.rs | 11 + src/cli.rs | 91 ++- src/compatibility.rs | 678 ++++++++++++++++++++++ src/digest.rs | 46 ++ src/installer.rs | 509 ++++++++++++++++ src/lib.rs | 4 + src/main.rs | 32 +- src/package.rs | 20 + src/privileged.rs | 350 +++++++++++ src/scripts.rs | 34 +- 27 files changed, 2295 insertions(+), 40 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml create mode 100644 LICENSE create mode 100644 SECURITY.md create mode 100644 assets/io.github.devnvll.Debforge.desktop create mode 100644 assets/io.github.devnvll.Debforge.svg create mode 100644 assets/org.devnvll.debforge.policy create mode 100644 packaging/.SRCINFO create mode 100644 packaging/PKGBUILD create mode 100644 packaging/PKGBUILD.local create mode 100755 scripts/install-system.sh create mode 100644 src/bin/debforge-helper.rs create mode 100644 src/compatibility.rs create mode 100644 src/digest.rs create mode 100644 src/installer.rs create mode 100644 src/privileged.rs diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..8004983 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,7 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + open-pull-requests-limit: 5 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..a412a16 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,52 @@ +name: CI + +on: + push: + pull_request: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + validate: + runs-on: ubuntu-latest + container: archlinux:base-devel + timeout-minutes: 20 + + steps: + - name: Check out the source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + + - name: Install test tools + run: >- + pacman -Syu --noconfirm --needed + desktop-file-utils + libarchive + libxml2 + rust + shellcheck + zstd + + - name: Check Rust formatting + run: cargo fmt --all -- --check + + - name: Run Clippy + run: cargo clippy --all-targets --locked -- -D warnings + + - name: Run tests + run: cargo test --all-targets --locked + + - name: Check shell scripts + run: | + bash -n scripts/*.sh + shellcheck scripts/*.sh + + - name: Check desktop and XML files + run: | + desktop-file-validate assets/io.github.devnvll.Debforge.desktop + xmllint --noout assets/io.github.devnvll.Debforge.svg + xmllint --noout assets/org.devnvll.debforge.policy diff --git a/.gitignore b/.gitignore index bf47e4b..dc5e79a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,12 @@ /target/ /*.pkg.tar.* /.debtap-rs-* +/packaging/pkg/ +/packaging/src/ +/packaging/*.pkg.tar.* +*.deb +.env +.env.* +!.env.example +*.key +*.pem diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 2226a06..de15b02 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -17,7 +17,7 @@ The first release has these targets: ## Pipeline -The converter has five stages. +The converter has six stages. 1. **Read** - Validate the `!` Debian archive signature. @@ -36,13 +36,20 @@ The converter has five stages. - Merge Debian multiarch library directories into the Arch library layout. - Preserve modes, symbolic links, hard links, and extended archive metadata. -4. **Describe** +4. **Inspect** + - Parse ELF headers and dynamic tables in Rust. + - Reject a definite CPU architecture mismatch. + - Reject device nodes, sockets, and other unsupported special files. + - Report missing interpreters, missing shared libraries, privileged modes, + and Debian multiarch runtime paths. + +5. **Describe** - Generate `.PKGINFO` directly from the parsed control data. - Generate `.MTREE` with SHA-256 file data unless the user disables it. - Use the installed Pacman hooks for standard cache updates. - Never copy Debian `apt`, repository, `dpkg`, or service-control code into the default install script. -5. **Write** +6. **Write** - Stream one `bsdtar` process into one parallel `zstd` process. - Use Zstandard level 3 by default. - Write to a partial file and rename it only after both processes succeed. @@ -55,24 +62,30 @@ package for a full Namcap shared-library scan. The cost grows with the number of dependencies and payload files. `debtap-rs` uses a constant number of process starts for normal conversion. It -reads the local Arch package-name set once. Dependency resolution is then an -in-memory set lookup. It does not inspect every ELF file. Extraction and output -compression remain disk-bound and run through libarchive and parallel Zstandard. +reads the local Arch package-name set once. Dependency resolution and ELF +inspection are then in-memory operations. Extraction and output compression +remain disk-bound and run through libarchive and parallel Zstandard. ## Module boundaries - `cli`: command-line compatibility and option validation. - `control`: Deb822 parsing and Debian version and architecture conversion. - `dependency`: relation parsing, alias mapping, and alternative selection. +- `compatibility`: ELF and special-file inspection. - `workspace`: private work directories and cleanup. - `archive`: Debian member extraction, payload extraction, MTREE generation, and package output. - `transform`: filesystem layout changes and installed-size calculation. - `scripts`: safe hook generation and explicit raw-script translation. - `package`: Arch metadata and PKGBUILD generation. - `process`: checked child-process execution and pipelines. +- `installer`: unprivileged review, authorization, and receipts. +- `privileged`: fixed root helper interface, secure staging, and Pacman execution. -No module can install a package. Installation remains a separate, authorized -`pacman -U` step in the desktop handler. +The converter cannot install a package. The installer is a separate +unprivileged flow. It creates a private conversion, shows a transaction review, +and sends only the reviewed package path and digest to a small Polkit helper. +The helper copies the same open file into a root-only directory, checks the +digest again, validates it, and starts `pacman -U`. ## Dependency policy @@ -88,9 +101,10 @@ resolution uses the built-in mapping and keeps valid same-name dependencies. ## Maintainer-script policy -The default `safe` policy generates hooks only from payload types that need a -cache refresh. Examples are desktop files, MIME data, icon themes, GLib schemas, -systemd units, and tmpfiles rules. +The default `safe` policy omits Debian maintainer code. Standard Pacman +transaction hooks handle desktop files, MIME data, icon themes, GLib schemas, +systemd units, and tmpfiles rules when their owning Arch packages provide those +hooks. Debforge records omitted scripts and Debian triggers as review warnings. The `none` policy writes no `.INSTALL` file. @@ -106,6 +120,9 @@ scripts can call Debian-only commands or change repository settings. - An unknown dependency name is kept after safe name normalization and produces a warning. - Existing output is not replaced unless `--force` is present. - Partial output always uses a separate file name. +- A special payload file or definite ELF architecture mismatch stops conversion. +- The root helper refuses links, wrong owners, changed hashes, relative paths, + unexpected arguments, and packages larger than its fixed safety limit. ## Compatibility diff --git a/Cargo.lock b/Cargo.lock index 9466b40..361ad1c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,4 +4,4 @@ version = 4 [[package]] name = "debtap-rs" -version = "0.1.0" +version = "0.2.0" diff --git a/Cargo.toml b/Cargo.toml index 657b014..9399395 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "debtap-rs" -version = "0.1.0" +version = "0.2.0" edition = "2024" rust-version = "1.85" description = "A fast and safe Debian-to-Arch package converter" @@ -11,6 +11,10 @@ repository = "https://github.com/DevNvll/debforge" name = "debtap-rs" path = "src/main.rs" +[[bin]] +name = "debforge-helper" +path = "src/bin/debforge-helper.rs" + [profile.release] codegen-units = 1 lto = "thin" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..17cb286 --- /dev/null +++ b/LICENSE @@ -0,0 +1,117 @@ +GNU GENERAL PUBLIC LICENSE +Version 2, June 1991 + +Copyright (C) 1989, 1991 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) 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 this service 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. 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. + +We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. + +Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. + +1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. + + c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. + +4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. + +6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. + +7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. + +10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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. + +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 convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author + + 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 2 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author Gnomovision 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, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. + +signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice diff --git a/README.md b/README.md index cb7abf8..007fcfa 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # Debforge -Debforge is a fast Debian-to-Arch package converter written in Rust. Its -command-line program is `debtap-rs`. It is a clean rewrite of the main Debtap -conversion workflow. +Debforge is a fast Debian-to-Arch package converter and reviewed desktop +installer written in Rust. The compatible converter command is `debtap-rs`. +The system package also provides the shorter `debforge` command. The converter removes the main Debtap performance problem. It does not scan large Debian and Ubuntu `Contents` files once for each dependency. It reads the @@ -23,6 +23,7 @@ maintainer behavior. Review warnings before you install the result. - `bsdtar` - `zstd` - `pacman` for dependency selection and output validation +- `sha256sum` for source and installation integrity There are no third-party Rust dependencies. @@ -32,14 +33,28 @@ There are no third-party Rust dependencies. cargo build --release --locked --offline ``` -The output binary is `target/release/debtap-rs`. +The output binaries are `target/release/debtap-rs` and +`target/release/debforge-helper`. -To install it for the current user: +For secure desktop integration, build and install the local Arch package: + +```sh +./scripts/install-system.sh +``` + +This installs the converter, root-owned helper, Polkit policy, desktop file, +and icon. It also makes Debforge the default `.deb` application for the current +user. + +To install only the converter for the current user: ```sh ./scripts/install-user.sh ``` +The user-only installation cannot install packages until the secure system +helper is installed. + ## Use ```sh @@ -48,6 +63,23 @@ debtap-rs --output /path/to/output application.deb debtap-rs --compression-level 7 application.deb ``` +To convert, review, authorize, and install a package: + +```sh +debforge install application.deb +``` + +The review shows Pacman metadata, the planned transaction, file count, native +package name conflicts, installed versions, and all conversion warnings. The +root helper copies the reviewed package into a root-only directory and checks +its SHA-256 value again before Pacman reads it. + +To restore the file association later: + +```sh +debforge register-handler +``` + The default Zstandard level is 3. A higher value makes a smaller package and uses more CPU time. @@ -98,6 +130,27 @@ This rule stops foreign root code such as these operations: `--scripts raw` wraps the original scripts in Arch install functions. This mode is unsafe and is only for manual review. The command prints a warning. +Debian `triggers` data is never executed. Safe mode records its omission in the +generated package so that the installation review can show it. + +## Compatibility inspection + +Normal conversion scans ELF files without starting one process per file. It +checks CPU architecture, ELF class, byte order, interpreter paths, required +shared-library names, Debian multiarch runtime paths, setuid and setgid modes, +and unsupported special files. A definite architecture mismatch or special +file stops conversion. Missing runtime items become installation warnings. + +The scan does not prove complete ABI compatibility. A vendor package can still +require newer GLIBC or GLIBCXX symbol versions than the system provides. + +## Installation receipts + +Successful desktop installations write a private receipt below +`$XDG_STATE_HOME/debforge/receipts`, or `~/.local/state/debforge/receipts`. +Each receipt records source and converted-package hashes, the package version, +the Debforge version, and installation time. + ## Output validation Every normal conversion validates the result with `pacman -Qp` when Pacman is diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..6607ec5 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,38 @@ +# Security policy + +## Supported versions + +Security fixes apply to the current release line. + +| Version | Supported | +| --- | --- | +| 0.2.x | Yes | +| 0.1.x | No | + +## Report a vulnerability + +Use the **Report a vulnerability** button on the GitHub Security page for this +repository. This method creates a private report for the project owner. + +Do not open a public issue for a vulnerability that is not fixed. + +Include this information when it is available: + +- The affected Debforge version. +- The Arch Linux and Pacman versions. +- Steps that reproduce the problem. +- The expected result and the actual result. +- A small test package or proof of concept that does not contain private data. +- Your proposed fix, if you have one. + +## Security boundary + +Treat each Debian package as untrusted input. Debforge converts package content, +shows a Pacman review, and asks for authorization before installation. The root +helper accepts one fixed command form. It checks the package owner and SHA-256 +value, copies the same open file into a root-only directory, validates the copy, +and then starts Pacman. + +The default script policy does not copy Debian maintainer scripts. It does not +make all third-party package content safe. Review the package source and the +Debforge warnings before you authorize installation. diff --git a/assets/io.github.devnvll.Debforge.desktop b/assets/io.github.devnvll.Debforge.desktop new file mode 100644 index 0000000..8131c78 --- /dev/null +++ b/assets/io.github.devnvll.Debforge.desktop @@ -0,0 +1,15 @@ +[Desktop Entry] +Type=Application +Version=1.5 +Name=Install Debian Package +GenericName=Package Installer +Comment=Review, convert, and install a Debian package on Arch Linux +Icon=io.github.devnvll.Debforge +Exec=debforge install %f +TryExec=debforge +Terminal=true +NoDisplay=false +StartupNotify=true +Categories=System; +Keywords=deb;debian;package;installer;arch; +MimeType=application/vnd.debian.binary-package;application/x-deb; diff --git a/assets/io.github.devnvll.Debforge.svg b/assets/io.github.devnvll.Debforge.svg new file mode 100644 index 0000000..dd2378b --- /dev/null +++ b/assets/io.github.devnvll.Debforge.svg @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/assets/org.devnvll.debforge.policy b/assets/org.devnvll.debforge.policy new file mode 100644 index 0000000..f5c3ca8 --- /dev/null +++ b/assets/org.devnvll.debforge.policy @@ -0,0 +1,20 @@ + + + + Debforge + https://github.com/DevNvll/debforge + io.github.devnvll.Debforge + + + Install a converted Debian package + Authentication is required to install this converted package + + no + no + auth_admin + + /usr/lib/debforge/debforge-helper + + diff --git a/packaging/.SRCINFO b/packaging/.SRCINFO new file mode 100644 index 0000000..e753ffd --- /dev/null +++ b/packaging/.SRCINFO @@ -0,0 +1,26 @@ +pkgbase = debforge + pkgdesc = Fast and safe Debian-to-Arch package converter and desktop installer + pkgver = 0.2.0 + pkgrel = 1 + url = https://github.com/DevNvll/debforge + arch = x86_64 + arch = aarch64 + license = GPL-2.0-or-later + makedepends = cargo + makedepends = git + depends = binutils + depends = coreutils + depends = desktop-file-utils + depends = hicolor-icon-theme + depends = libarchive + depends = pacman + depends = polkit + depends = shared-mime-info + depends = xdg-utils + depends = zstd + optdepends = libnotify: desktop installation notifications + options = !debug + source = git+https://github.com/DevNvll/debforge.git#tag=v0.2.0 + sha256sums = SKIP + +pkgname = debforge diff --git a/packaging/PKGBUILD b/packaging/PKGBUILD new file mode 100644 index 0000000..517bc98 --- /dev/null +++ b/packaging/PKGBUILD @@ -0,0 +1,52 @@ +pkgname=debforge +pkgver=0.2.0 +pkgrel=1 +pkgdesc='Fast and safe Debian-to-Arch package converter and desktop installer' +arch=('x86_64' 'aarch64') +url='https://github.com/DevNvll/debforge' +license=('GPL-2.0-or-later') +depends=( + 'binutils' + 'coreutils' + 'desktop-file-utils' + 'hicolor-icon-theme' + 'libarchive' + 'pacman' + 'polkit' + 'shared-mime-info' + 'xdg-utils' + 'zstd' +) +makedepends=('cargo' 'git') +optdepends=('libnotify: desktop installation notifications') +options=('!debug') +source=("git+$url.git#tag=v$pkgver") +sha256sums=('SKIP') + +build() { + cd "$pkgname" + cargo build --release --locked --offline +} + +check() { + cd "$pkgname" + cargo test --locked --offline +} + +package() { + cd "$pkgname" + + install -Dm0755 target/release/debtap-rs "$pkgdir/usr/bin/debtap-rs" + ln -s debtap-rs "$pkgdir/usr/bin/debforge" + install -Dm0755 target/release/debforge-helper \ + "$pkgdir/usr/lib/debforge/debforge-helper" + install -Dm0644 assets/io.github.devnvll.Debforge.desktop \ + "$pkgdir/usr/share/applications/io.github.devnvll.Debforge.desktop" + install -Dm0644 assets/io.github.devnvll.Debforge.svg \ + "$pkgdir/usr/share/icons/hicolor/scalable/apps/io.github.devnvll.Debforge.svg" + install -Dm0644 assets/org.devnvll.debforge.policy \ + "$pkgdir/usr/share/polkit-1/actions/org.devnvll.debforge.policy" + install -Dm0644 README.md "$pkgdir/usr/share/doc/debforge/README.md" + install -Dm0644 ARCHITECTURE.md "$pkgdir/usr/share/doc/debforge/ARCHITECTURE.md" + install -Dm0644 LICENSE "$pkgdir/usr/share/licenses/debforge/LICENSE" +} diff --git a/packaging/PKGBUILD.local b/packaging/PKGBUILD.local new file mode 100644 index 0000000..33939fa --- /dev/null +++ b/packaging/PKGBUILD.local @@ -0,0 +1,56 @@ +pkgname=debforge +pkgver=0.2.0 +pkgrel=1 +pkgdesc='Fast and safe Debian-to-Arch package converter and desktop installer' +arch=('x86_64' 'aarch64') +url='https://github.com/DevNvll/debforge' +license=('GPL-2.0-or-later') +depends=( + 'binutils' + 'coreutils' + 'desktop-file-utils' + 'hicolor-icon-theme' + 'libarchive' + 'pacman' + 'polkit' + 'shared-mime-info' + 'xdg-utils' + 'zstd' +) +makedepends=('cargo') +optdepends=('libnotify: desktop installation notifications') +options=('!debug') +source=() +sha256sums=() + +build() { + cd "$startdir/.." + "${CARGO:-cargo}" build --release --locked --offline +} + +check() { + cd "$startdir/.." + "${CARGO:-cargo}" test --locked --offline +} + +package() { + local project_dir="$startdir/.." + + install -Dm0755 "$project_dir/target/release/debtap-rs" \ + "$pkgdir/usr/bin/debtap-rs" + ln -s debtap-rs "$pkgdir/usr/bin/debforge" + install -Dm0755 "$project_dir/target/release/debforge-helper" \ + "$pkgdir/usr/lib/debforge/debforge-helper" + install -Dm0644 "$project_dir/assets/io.github.devnvll.Debforge.desktop" \ + "$pkgdir/usr/share/applications/io.github.devnvll.Debforge.desktop" + install -Dm0644 "$project_dir/assets/io.github.devnvll.Debforge.svg" \ + "$pkgdir/usr/share/icons/hicolor/scalable/apps/io.github.devnvll.Debforge.svg" + install -Dm0644 "$project_dir/assets/org.devnvll.debforge.policy" \ + "$pkgdir/usr/share/polkit-1/actions/org.devnvll.debforge.policy" + install -Dm0644 "$project_dir/README.md" \ + "$pkgdir/usr/share/doc/debforge/README.md" + install -Dm0644 "$project_dir/ARCHITECTURE.md" \ + "$pkgdir/usr/share/doc/debforge/ARCHITECTURE.md" + install -Dm0644 "$project_dir/LICENSE" \ + "$pkgdir/usr/share/licenses/debforge/LICENSE" +} diff --git a/scripts/install-system.sh b/scripts/install-system.sh new file mode 100755 index 0000000..0d2306a --- /dev/null +++ b/scripts/install-system.sh @@ -0,0 +1,21 @@ +#!/usr/bin/bash + +set -euo pipefail + +script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +project_dir=$(cd -- "$script_dir/.." && pwd) +packaging_dir="$project_dir/packaging" + +cd -- "$packaging_dir" +makepkg --cleanbuild --clean --force --noconfirm -p PKGBUILD.local +package_path=$(makepkg --packagelist -p PKGBUILD.local) + +if [[ ! -f "$package_path" ]]; then + printf 'The Debforge package was not created: %s\n' "$package_path" >&2 + exit 1 +fi + +pkexec /usr/bin/pacman -U --needed --noconfirm -- "$package_path" +/usr/bin/debtap-rs register-handler + +printf 'Installed Debforge and registered the .deb file handler.\n' diff --git a/scripts/install-user.sh b/scripts/install-user.sh index e4ec42b..9b71716 100755 --- a/scripts/install-user.sh +++ b/scripts/install-user.sh @@ -13,3 +13,20 @@ cargo build --release --locked --offline "$install_dir/debtap-rs" printf 'Installed %s\n' "$install_dir/debtap-rs" + +if [[ -x /usr/lib/debforge/debforge-helper ]]; then + applications_dir="${XDG_DATA_HOME:-$HOME/.local/share}/applications" + icons_dir="${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor/scalable/apps" + /usr/bin/install -Dm0644 \ + "$project_dir/assets/io.github.devnvll.Debforge.desktop" \ + "$applications_dir/io.github.devnvll.Debforge.desktop" + /usr/bin/install -Dm0644 \ + "$project_dir/assets/io.github.devnvll.Debforge.svg" \ + "$icons_dir/io.github.devnvll.Debforge.svg" + if command -v update-desktop-database >/dev/null 2>&1; then + update-desktop-database "$applications_dir" + fi + "$install_dir/debtap-rs" register-handler +else + printf 'The converter is ready. Run scripts/install-system.sh for secure desktop installation.\n' +fi diff --git a/src/bin/debforge-helper.rs b/src/bin/debforge-helper.rs new file mode 100644 index 0000000..7966ccf --- /dev/null +++ b/src/bin/debforge-helper.rs @@ -0,0 +1,11 @@ +use std::process::ExitCode; + +fn main() -> ExitCode { + match debtap_rs::privileged::run(std::env::args_os().skip(1)) { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("Error: {error}"); + ExitCode::FAILURE + } + } +} diff --git a/src/cli.rs b/src/cli.rs index bcc4f8a..ff5382b 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -31,9 +31,17 @@ pub struct ConvertOptions { pub source_date_epoch: Option, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InstallOptions { + pub input: PathBuf, + pub assume_yes: bool, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub enum Action { Convert(ConvertOptions), + Install(InstallOptions), + RegisterHandler, Help, Version, Update, @@ -49,6 +57,18 @@ where S: Into, { let arguments: Vec = arguments.into_iter().map(Into::into).collect(); + if arguments.first().and_then(|value| value.to_str()) == Some("install") { + return parse_install(arguments.into_iter().skip(1)); + } + if arguments.first().and_then(|value| value.to_str()) == Some("register-handler") { + if arguments.len() != 1 { + return Err(AppError::new( + "register-handler does not accept additional arguments.", + )); + } + return Ok(Action::RegisterHandler); + } + let mut input: Option = None; let mut output_dir = None; let mut compression_level = 3_u8; @@ -179,6 +199,41 @@ where })) } +fn parse_install(arguments: I) -> Result +where + I: IntoIterator, +{ + let mut input = None; + let mut assume_yes = false; + let mut positional_only = false; + + for argument in arguments { + if positional_only || !is_option(&argument) { + set_input(&mut input, &argument)?; + continue; + } + + if argument == "--" { + positional_only = true; + continue; + } + + let text = argument + .to_str() + .ok_or_else(|| AppError::new("An install option is not valid UTF-8."))?; + match text { + "-y" | "--yes" => assume_yes = true, + "-h" | "--help" => return Ok(Action::Help), + _ => return Err(AppError::new(format!("Unknown install option: {text}"))), + } + } + + let input = input.ok_or_else(|| { + AppError::new("No Debian package was given. Use debtap-rs install package.deb.") + })?; + Ok(Action::Install(InstallOptions { input, assume_yes })) +} + fn is_option(argument: &OsStr) -> bool { argument.as_encoded_bytes().first() == Some(&b'-') } @@ -290,6 +345,8 @@ pub fn help() -> &'static str { \n\ Usage:\n\ debtap-rs [options] package.deb\n\ + debtap-rs install [--yes] package.deb\n\ + debtap-rs register-handler\n\ debtap-rs --update\n\ \n\ Compatible options:\n\ @@ -311,7 +368,12 @@ Additional options:\n\ --source-date-epoch N Set a deterministic build time\n\ --no-mtree Do not add .MTREE\n\ --keep-work Keep the private work directory\n\ - --force Replace an existing output package\n" + --force Replace an existing output package\n\ +\n\ +Install commands:\n\ + install FILE Convert, review, authorize, and install FILE\n\ + install --yes FILE Skip the text confirmation (authorization remains)\n\ + register-handler Make Debforge the default .deb file handler\n" } #[cfg(test)] @@ -370,5 +432,32 @@ mod tests { assert!(error.to_string().contains("1 through 19")); } + #[test] + fn parses_install_and_handler_actions() { + let action = parse_from(["install", "--yes", "/tmp/app name.deb"]) + .expect("install arguments must parse"); + let Action::Install(options) = action else { + panic!("install action expected"); + }; + assert!(options.assume_yes); + assert_eq!(options.input, PathBuf::from("/tmp/app name.deb")); + + assert_eq!( + parse_from(["register-handler"]).expect("handler action"), + Action::RegisterHandler + ); + } + + #[test] + fn rejects_unknown_install_options_and_extra_handler_arguments() { + let error = parse_from(["install", "--force", "app.deb"]) + .expect_err("install must reject converter options"); + assert!(error.to_string().contains("Unknown install option")); + + let error = parse_from(["register-handler", "extra"]) + .expect_err("handler action must reject arguments"); + assert!(error.to_string().contains("does not accept")); + } + use std::path::PathBuf; } diff --git a/src/compatibility.rs b/src/compatibility.rs new file mode 100644 index 0000000..fabd4d4 --- /dev/null +++ b/src/compatibility.rs @@ -0,0 +1,678 @@ +use std::collections::{BTreeSet, HashSet}; +use std::fs::{self, File}; +use std::io::{Read, Seek, SeekFrom}; +use std::os::unix::fs::{FileTypeExt, MetadataExt}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +use crate::archive; +use crate::error::{AppError, Context, Result}; +use crate::process; + +const ELF_MAGIC: &[u8; 4] = b"\x7fELF"; +const PT_LOAD: u32 = 1; +const PT_DYNAMIC: u32 = 2; +const PT_INTERP: u32 = 3; +const DT_NULL: i64 = 0; +const DT_NEEDED: i64 = 1; +const DT_STRTAB: i64 = 5; +const DT_STRSZ: i64 = 10; +const DT_RPATH: i64 = 15; +const DT_RUNPATH: i64 = 29; +const MAX_PROGRAM_HEADERS: usize = 4096; +const MAX_DYNAMIC_ENTRIES: usize = 65_536; +const MAX_STRING_TABLE_BYTES: u64 = 16 * 1024 * 1024; + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct CompatibilityReport { + pub elf_files: usize, + pub foreign_elf_files: Vec, + pub privileged_files: Vec, + pub missing_interpreters: Vec, + pub missing_libraries: Vec, + pub risky_runtime_paths: Vec, +} + +impl CompatibilityReport { + pub fn warnings(&self) -> Vec { + let mut warnings = Vec::new(); + if !self.privileged_files.is_empty() { + warnings.push(format!( + "The payload contains {} setuid or setgid file(s); review their privileged modes before installation.", + self.privileged_files.len() + )); + } + if !self.foreign_elf_files.is_empty() { + warnings.push(format!( + "The payload contains {} bundled ELF file(s) for another architecture; host executables were checked separately.", + self.foreign_elf_files.len() + )); + } + if !self.missing_interpreters.is_empty() { + warnings.push(format!( + "ELF interpreters are not present on this system: {}.", + self.missing_interpreters.join(", ") + )); + } + if !self.missing_libraries.is_empty() { + warnings.push(format!( + "Shared libraries are not present before the Pacman transaction: {}.", + self.missing_libraries.join(", ") + )); + } + if !self.risky_runtime_paths.is_empty() { + warnings.push(format!( + "ELF runtime paths still use Debian multiarch locations: {}.", + self.risky_runtime_paths.join(", ") + )); + } + warnings + } +} + +#[derive(Debug, Clone)] +struct ParsedElf { + class: ElfClass, + little_endian: bool, + machine: u16, + interpreter: Option, + needed: Vec, + runtime_paths: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ElfClass { + Elf32, + Elf64, +} + +#[derive(Debug, Clone, Copy)] +struct LoadSegment { + offset: u64, + virtual_address: u64, + file_size: u64, +} + +#[derive(Debug, Clone, Copy)] +struct ExpectedElf { + class: ElfClass, + little_endian: bool, + machine: u16, +} + +pub fn inspect_payload(root: &Path, architecture: &str) -> Result { + let expected = expected_elf(architecture); + let mut parsed = Vec::new(); + let mut report = CompatibilityReport::default(); + let mut provided_names = HashSet::new(); + + for relative in archive::collect_sorted_file_list(root)? { + let relative = relative.strip_prefix("./").unwrap_or(&relative); + if relative.as_os_str().is_empty() { + continue; + } + let path = root.join(relative); + let metadata = fs::symlink_metadata(&path) + .context(format!("Cannot inspect payload path {}", path.display()))?; + let file_type = metadata.file_type(); + if file_type.is_block_device() + || file_type.is_char_device() + || file_type.is_fifo() + || file_type.is_socket() + { + return Err(AppError::new(format!( + "The Debian payload contains an unsupported special file: {}", + relative.display() + ))); + } + if !file_type.is_file() { + continue; + } + + if metadata.mode() & 0o6000 != 0 { + report.privileged_files.push(relative.to_path_buf()); + } + if let Some(name) = relative.file_name().and_then(|value| value.to_str()) { + provided_names.insert(name.to_string()); + } + + let Some(elf) = parse_elf(&path)? else { + continue; + }; + report.elf_files += 1; + let architecture_matches = expected.is_some_and(|expected| { + elf.class == expected.class + && elf.little_endian == expected.little_endian + && elf.machine == expected.machine + }); + if !architecture_matches { + if elf.interpreter.is_some() || is_command_path(relative) { + return Err(AppError::new(format!( + "ELF architecture mismatch in executable {}: machine {}, class {:?}.", + relative.display(), + elf.machine, + elf.class + ))); + } + report.foreign_elf_files.push(relative.to_path_buf()); + continue; + } + parsed.push(elf); + } + + let system_libraries = system_library_names(); + let mut missing_interpreters = BTreeSet::new(); + let mut missing_libraries = BTreeSet::new(); + let mut risky_runtime_paths = BTreeSet::new(); + for elf in parsed { + if let Some(interpreter) = elf.interpreter { + let payload_interpreter = interpreter + .strip_prefix('/') + .map(|value| root.join(value)) + .is_some_and(|value| value.exists()); + if !payload_interpreter && !Path::new(&interpreter).exists() { + missing_interpreters.insert(interpreter); + } + } + for library in elf.needed { + if !provided_names.contains(&library) && !system_libraries.contains(&library) { + missing_libraries.insert(library); + } + } + for runtime_path in elf.runtime_paths { + for entry in runtime_path.split(':') { + if entry.contains("linux-gnu") { + risky_runtime_paths.insert(entry.to_string()); + } + } + } + } + report.missing_interpreters = missing_interpreters.into_iter().collect(); + report.missing_libraries = missing_libraries.into_iter().collect(); + report.risky_runtime_paths = risky_runtime_paths.into_iter().collect(); + Ok(report) +} + +fn is_command_path(path: &Path) -> bool { + path.starts_with("usr/bin") || path.starts_with("bin") || path.starts_with("usr/sbin") +} + +fn parse_elf(path: &Path) -> Result> { + let mut file = + File::open(path).context(format!("Cannot open ELF candidate {}", path.display()))?; + let file_size = file + .metadata() + .context(format!("Cannot inspect ELF candidate {}", path.display()))? + .len(); + let mut header = [0_u8; 64]; + let read = file + .read(&mut header) + .context(format!("Cannot read ELF candidate {}", path.display()))?; + if read < ELF_MAGIC.len() || &header[..ELF_MAGIC.len()] != ELF_MAGIC { + return Ok(None); + } + if read < 52 { + return Err(AppError::new(format!( + "Truncated ELF header in {}", + path.display() + ))); + } + + let class = match header[4] { + 1 => ElfClass::Elf32, + 2 => ElfClass::Elf64, + value => { + return Err(AppError::new(format!( + "Unsupported ELF class {value} in {}", + path.display() + ))); + } + }; + let little_endian = match header[5] { + 1 => true, + 2 => false, + value => { + return Err(AppError::new(format!( + "Unsupported ELF byte order {value} in {}", + path.display() + ))); + } + }; + let machine = read_u16(&header, 18, little_endian)?; + let (program_offset, program_entry_size, program_count) = match class { + ElfClass::Elf32 => ( + u64::from(read_u32(&header, 28, little_endian)?), + usize::from(read_u16(&header, 42, little_endian)?), + usize::from(read_u16(&header, 44, little_endian)?), + ), + ElfClass::Elf64 => { + if read < 64 { + return Err(AppError::new(format!( + "Truncated 64-bit ELF header in {}", + path.display() + ))); + } + ( + read_u64(&header, 32, little_endian)?, + usize::from(read_u16(&header, 54, little_endian)?), + usize::from(read_u16(&header, 56, little_endian)?), + ) + } + }; + let minimum_entry_size = match class { + ElfClass::Elf32 => 32, + ElfClass::Elf64 => 56, + }; + if program_count > MAX_PROGRAM_HEADERS + || (program_count > 0 && program_entry_size < minimum_entry_size) + { + return Err(AppError::new(format!( + "Invalid ELF program-header table in {}", + path.display() + ))); + } + let table_size = program_entry_size + .checked_mul(program_count) + .and_then(|value| u64::try_from(value).ok()) + .ok_or_else(|| AppError::new("ELF program-header table is too large."))?; + if program_offset + .checked_add(table_size) + .is_none_or(|end| end > file_size) + { + return Err(AppError::new(format!( + "ELF program-header table is outside {}", + path.display() + ))); + } + + let mut loads = Vec::new(); + let mut dynamic = None; + let mut interpreter = None; + for index in 0..program_count { + let offset = program_offset + u64::try_from(index * program_entry_size).unwrap_or(u64::MAX); + let entry = read_at(&mut file, offset, program_entry_size)?; + let kind = read_u32(&entry, 0, little_endian)?; + let (segment_offset, virtual_address, file_bytes) = match class { + ElfClass::Elf32 => ( + u64::from(read_u32(&entry, 4, little_endian)?), + u64::from(read_u32(&entry, 8, little_endian)?), + u64::from(read_u32(&entry, 16, little_endian)?), + ), + ElfClass::Elf64 => ( + read_u64(&entry, 8, little_endian)?, + read_u64(&entry, 16, little_endian)?, + read_u64(&entry, 32, little_endian)?, + ), + }; + validate_file_range(segment_offset, file_bytes, file_size, path)?; + match kind { + PT_LOAD => loads.push(LoadSegment { + offset: segment_offset, + virtual_address, + file_size: file_bytes, + }), + PT_DYNAMIC => dynamic = Some((segment_offset, file_bytes)), + PT_INTERP => { + if file_bytes == 0 || file_bytes > 4096 { + return Err(AppError::new(format!( + "Invalid ELF interpreter path in {}", + path.display() + ))); + } + let bytes = read_at( + &mut file, + segment_offset, + usize::try_from(file_bytes).map_err(|_| { + AppError::new("ELF interpreter path is too large for this system.") + })?, + )?; + interpreter = Some(read_c_string(&bytes, 0)?); + } + _ => {} + } + } + + let (needed, runtime_paths) = match dynamic { + Some((offset, size)) => parse_dynamic( + &mut file, + class, + little_endian, + offset, + size, + &loads, + file_size, + )?, + None => (Vec::new(), Vec::new()), + }; + Ok(Some(ParsedElf { + class, + little_endian, + machine, + interpreter, + needed, + runtime_paths, + })) +} + +fn parse_dynamic( + file: &mut File, + class: ElfClass, + little_endian: bool, + offset: u64, + size: u64, + loads: &[LoadSegment], + file_size: u64, +) -> Result<(Vec, Vec)> { + let entry_size = match class { + ElfClass::Elf32 => 8_u64, + ElfClass::Elf64 => 16_u64, + }; + let entry_count = usize::try_from(size / entry_size) + .unwrap_or(usize::MAX) + .min(MAX_DYNAMIC_ENTRIES); + let mut needed_offsets = Vec::new(); + let mut path_offsets = Vec::new(); + let mut string_address = None; + let mut string_size = None; + for index in 0..entry_count { + let entry_offset = offset + .checked_add(u64::try_from(index).unwrap_or(u64::MAX) * entry_size) + .ok_or_else(|| AppError::new("ELF dynamic table offset overflowed."))?; + let entry = read_at(file, entry_offset, entry_size as usize)?; + let (tag, value) = match class { + ElfClass::Elf32 => ( + i64::from(i32::from_ne_bytes(endian_array_4( + &entry, + 0, + little_endian, + )?)), + u64::from(read_u32(&entry, 4, little_endian)?), + ), + ElfClass::Elf64 => ( + i64::from_ne_bytes(endian_array_8(&entry, 0, little_endian)?), + read_u64(&entry, 8, little_endian)?, + ), + }; + match tag { + DT_NULL => break, + DT_NEEDED => needed_offsets.push(value), + DT_STRTAB => string_address = Some(value), + DT_STRSZ => string_size = Some(value), + DT_RPATH | DT_RUNPATH => path_offsets.push(value), + _ => {} + } + } + + if needed_offsets.is_empty() && path_offsets.is_empty() { + return Ok((Vec::new(), Vec::new())); + } + let address = string_address + .ok_or_else(|| AppError::new("ELF dynamic strings have no string-table address."))?; + let size = string_size + .ok_or_else(|| AppError::new("ELF dynamic strings have no string-table size."))?; + if size == 0 || size > MAX_STRING_TABLE_BYTES { + return Err(AppError::new( + "ELF dynamic string table has an invalid size.", + )); + } + let string_offset = virtual_to_file_offset(address, loads) + .ok_or_else(|| AppError::new("ELF dynamic string table is not in a load segment."))?; + validate_file_range(string_offset, size, file_size, Path::new("ELF file"))?; + let strings = read_at( + file, + string_offset, + usize::try_from(size) + .map_err(|_| AppError::new("ELF string table is too large for this system."))?, + )?; + let needed = needed_offsets + .into_iter() + .map(|value| read_c_string(&strings, value)) + .collect::>>()?; + let runtime_paths = path_offsets + .into_iter() + .map(|value| read_c_string(&strings, value)) + .collect::>>()?; + Ok((needed, runtime_paths)) +} + +fn virtual_to_file_offset(address: u64, loads: &[LoadSegment]) -> Option { + loads.iter().find_map(|segment| { + let difference = address.checked_sub(segment.virtual_address)?; + (difference < segment.file_size) + .then(|| segment.offset.checked_add(difference)) + .flatten() + }) +} + +fn system_library_names() -> HashSet { + let mut libraries = HashSet::new(); + if let Some(ldconfig) = process::find_tool("ldconfig") { + if let Ok(output) = + process::capture_text(Command::new(ldconfig).arg("-p").stdin(Stdio::null())) + { + for line in output.lines() { + if let Some(name) = line.split_whitespace().next() { + if name.contains(".so") { + libraries.insert(name.to_string()); + } + } + } + } + } + for directory in ["/usr/lib", "/usr/lib32"] { + if let Ok(entries) = fs::read_dir(directory) { + for entry in entries.flatten() { + if let Some(name) = entry.file_name().to_str() { + if name.contains(".so") { + libraries.insert(name.to_string()); + } + } + } + } + } + libraries +} + +fn expected_elf(architecture: &str) -> Option { + match architecture { + "x86_64" => Some(ExpectedElf { + class: ElfClass::Elf64, + little_endian: true, + machine: 62, + }), + "i686" => Some(ExpectedElf { + class: ElfClass::Elf32, + little_endian: true, + machine: 3, + }), + "aarch64" => Some(ExpectedElf { + class: ElfClass::Elf64, + little_endian: true, + machine: 183, + }), + "arm" | "armv7h" => Some(ExpectedElf { + class: ElfClass::Elf32, + little_endian: true, + machine: 40, + }), + "ppc64le" => Some(ExpectedElf { + class: ElfClass::Elf64, + little_endian: true, + machine: 21, + }), + "ppc64" => Some(ExpectedElf { + class: ElfClass::Elf64, + little_endian: false, + machine: 21, + }), + "riscv64" => Some(ExpectedElf { + class: ElfClass::Elf64, + little_endian: true, + machine: 243, + }), + "s390x" => Some(ExpectedElf { + class: ElfClass::Elf64, + little_endian: false, + machine: 22, + }), + _ => None, + } +} + +fn read_at(file: &mut File, offset: u64, size: usize) -> Result> { + file.seek(SeekFrom::Start(offset)) + .context("Cannot seek in ELF file")?; + let mut bytes = vec![0_u8; size]; + file.read_exact(&mut bytes) + .context("Cannot read ELF file data")?; + Ok(bytes) +} + +fn validate_file_range(offset: u64, size: u64, file_size: u64, path: &Path) -> Result<()> { + if offset.checked_add(size).is_none_or(|end| end > file_size) { + Err(AppError::new(format!( + "ELF segment is outside {}", + path.display() + ))) + } else { + Ok(()) + } +} + +fn read_c_string(strings: &[u8], offset: u64) -> Result { + let offset = usize::try_from(offset) + .map_err(|_| AppError::new("ELF string offset is too large for this system."))?; + let tail = strings + .get(offset..) + .ok_or_else(|| AppError::new("ELF string offset is outside its string table."))?; + let end = tail + .iter() + .position(|byte| *byte == 0) + .unwrap_or(tail.len()); + if end == 0 { + return Err(AppError::new("ELF dynamic string is empty.")); + } + String::from_utf8(tail[..end].to_vec()) + .map_err(|_| AppError::new("ELF dynamic string is not valid UTF-8.")) +} + +fn read_u16(bytes: &[u8], offset: usize, little: bool) -> Result { + let array = bytes + .get(offset..offset + 2) + .and_then(|value| <[u8; 2]>::try_from(value).ok()) + .ok_or_else(|| AppError::new("ELF integer is outside the available data."))?; + Ok(if little { + u16::from_le_bytes(array) + } else { + u16::from_be_bytes(array) + }) +} + +fn read_u32(bytes: &[u8], offset: usize, little: bool) -> Result { + let array = bytes + .get(offset..offset + 4) + .and_then(|value| <[u8; 4]>::try_from(value).ok()) + .ok_or_else(|| AppError::new("ELF integer is outside the available data."))?; + Ok(if little { + u32::from_le_bytes(array) + } else { + u32::from_be_bytes(array) + }) +} + +fn read_u64(bytes: &[u8], offset: usize, little: bool) -> Result { + let array = bytes + .get(offset..offset + 8) + .and_then(|value| <[u8; 8]>::try_from(value).ok()) + .ok_or_else(|| AppError::new("ELF integer is outside the available data."))?; + Ok(if little { + u64::from_le_bytes(array) + } else { + u64::from_be_bytes(array) + }) +} + +fn endian_array_4(bytes: &[u8], offset: usize, little: bool) -> Result<[u8; 4]> { + let mut array = bytes + .get(offset..offset + 4) + .and_then(|value| <[u8; 4]>::try_from(value).ok()) + .ok_or_else(|| AppError::new("ELF integer is outside the available data."))?; + if little != cfg!(target_endian = "little") { + array.reverse(); + } + Ok(array) +} + +fn endian_array_8(bytes: &[u8], offset: usize, little: bool) -> Result<[u8; 8]> { + let mut array = bytes + .get(offset..offset + 8) + .and_then(|value| <[u8; 8]>::try_from(value).ok()) + .ok_or_else(|| AppError::new("ELF integer is outside the available data."))?; + if little != cfg!(target_endian = "little") { + array.reverse(); + } + Ok(array) +} + +#[cfg(test)] +mod tests { + use std::fs; + use std::os::unix::net::UnixListener; + + use super::{ElfClass, inspect_payload, parse_elf}; + + fn test_root(name: &str) -> std::path::PathBuf { + let path = std::env::temp_dir().join(format!( + "debforge-compatibility-{name}-{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("test root"); + path + } + + fn minimal_x86_64_elf() -> Vec { + let mut bytes = vec![0_u8; 64]; + bytes[..4].copy_from_slice(b"\x7fELF"); + bytes[4] = 2; + bytes[5] = 1; + bytes[6] = 1; + bytes[16..18].copy_from_slice(&2_u16.to_le_bytes()); + bytes[18..20].copy_from_slice(&62_u16.to_le_bytes()); + bytes[20..24].copy_from_slice(&1_u32.to_le_bytes()); + bytes[52..54].copy_from_slice(&64_u16.to_le_bytes()); + bytes[54..56].copy_from_slice(&56_u16.to_le_bytes()); + bytes + } + + #[test] + fn reads_a_minimal_elf_header_and_rejects_wrong_architecture() { + let root = test_root("architecture"); + let path = root.join("usr/bin/program"); + fs::create_dir_all(path.parent().expect("parent")).expect("bin"); + fs::write(&path, minimal_x86_64_elf()).expect("ELF"); + let elf = parse_elf(&path).expect("parse").expect("ELF"); + assert_eq!(elf.class, ElfClass::Elf64); + assert_eq!(elf.machine, 62); + assert!(inspect_payload(&root, "x86_64").is_ok()); + assert!(inspect_payload(&root, "aarch64").is_err()); + fs::remove_dir_all(root).expect("cleanup"); + } + + #[test] + fn rejects_special_payload_files() { + let root = test_root("special"); + let socket = root.join("control.sock"); + let _listener = match UnixListener::bind(&socket) { + Ok(listener) => listener, + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + fs::remove_dir_all(root).expect("cleanup"); + return; + } + Err(error) => panic!("socket: {error}"), + }; + let error = inspect_payload(&root, "x86_64").expect_err("special file"); + assert!(error.to_string().contains("special file")); + fs::remove_dir_all(root).expect("cleanup"); + } +} diff --git a/src/digest.rs b/src/digest.rs new file mode 100644 index 0000000..ed79060 --- /dev/null +++ b/src/digest.rs @@ -0,0 +1,46 @@ +use std::path::Path; +use std::process::Command; + +use crate::error::{AppError, Result}; +use crate::process; + +pub const SHA256_HEX_LENGTH: usize = 64; + +pub fn sha256_file(path: &Path) -> Result { + let sha256sum = process::require_tool("sha256sum")?; + sha256_file_with_tool(path, &sha256sum) +} + +pub fn sha256_file_with_tool(path: &Path, sha256sum: &Path) -> Result { + let output = process::capture_text(Command::new(sha256sum).arg("--").arg(path))?; + let digest = output + .split_whitespace() + .next() + .ok_or_else(|| AppError::new("sha256sum did not return a digest."))?; + normalize_sha256(digest) +} + +pub fn normalize_sha256(value: &str) -> Result { + if value.len() != SHA256_HEX_LENGTH || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(AppError::new( + "The SHA-256 value must contain exactly 64 hexadecimal characters.", + )); + } + Ok(value.to_ascii_lowercase()) +} + +#[cfg(test)] +mod tests { + use super::normalize_sha256; + + #[test] + fn validates_and_normalizes_sha256_text() { + let uppercase = "A".repeat(64); + assert_eq!( + normalize_sha256(&uppercase).expect("digest"), + "a".repeat(64) + ); + assert!(normalize_sha256("abc").is_err()); + assert!(normalize_sha256(&"x".repeat(64)).is_err()); + } +} diff --git a/src/installer.rs b/src/installer.rs new file mode 100644 index 0000000..94b6fd0 --- /dev/null +++ b/src/installer.rs @@ -0,0 +1,509 @@ +use std::env; +use std::ffi::OsStr; +use std::fs::{self, OpenOptions}; +use std::io::{self, IsTerminal, Write}; +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use crate::cli::InstallOptions; +use crate::digest; +use crate::error::{AppError, Context, Result}; +use crate::process; +use crate::workspace::Workspace; + +pub const DESKTOP_FILE_ID: &str = "io.github.devnvll.Debforge.desktop"; +pub const PRIVILEGED_HELPER: &str = "/usr/lib/debforge/debforge-helper"; +const DEB_MIME_TYPES: [&str; 2] = ["application/vnd.debian.binary-package", "application/x-deb"]; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InstallReceipt { + pub package_name: String, + pub package_version: String, + pub source_path: PathBuf, + pub source_sha256: String, + pub converted_sha256: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +struct PackageAnnotations { + source_sha256: Option, + warnings: Vec, +} + +pub fn install(options: &InstallOptions) -> Result<()> { + let input = fs::canonicalize(&options.input).context(format!( + "Cannot resolve Debian package {}", + options.input.display() + ))?; + if !input.is_file() { + return Err(AppError::new(format!( + "The selected Debian package is not a regular file: {}", + input.display() + ))); + } + + verify_helper()?; + process::require_tools(&["pacman", "pkexec", "bsdtar", "sha256sum"])?; + let source_sha256 = digest::sha256_file(&input)?; + let workspace = Workspace::create(false)?; + convert_for_install(&input, workspace.output_dir())?; + let package = find_converted_package(workspace.output_dir())?; + let converted_sha256 = digest::sha256_file(&package)?; + + let (package_name, package_version) = query_package_identity(&package)?; + let annotations = read_annotations(&package)?; + if annotations.source_sha256.as_deref() != Some(source_sha256.as_str()) { + return Err(AppError::new( + "The converted package does not contain the expected Debian source digest.", + )); + } + + show_review( + &input, + &package, + &package_name, + &package_version, + &source_sha256, + &annotations, + )?; + if !options.assume_yes && !confirm_installation()? { + println!("Installation canceled. No system files were changed."); + return Ok(()); + } + + run_privileged_install(&package, &converted_sha256)?; + verify_installed(&package_name, &package_version)?; + let receipt = InstallReceipt { + package_name, + package_version, + source_path: input, + source_sha256, + converted_sha256, + }; + match write_receipt(&receipt) { + Ok(receipt_path) => println!("Installation receipt: {}", receipt_path.display()), + Err(error) => { + eprintln!("Warning: The package was installed, but its receipt failed: {error}") + } + } + notify_success(&receipt); + Ok(()) +} + +pub fn register_handler() -> Result<()> { + let xdg_mime = process::require_tool("xdg-mime")?; + for mime_type in DEB_MIME_TYPES { + process::run_checked( + Command::new(&xdg_mime) + .args(["default", DESKTOP_FILE_ID, mime_type]) + .stdin(Stdio::null()), + )?; + let selected = process::capture_text( + Command::new(&xdg_mime) + .args(["query", "default", mime_type]) + .stdin(Stdio::null()), + )?; + if selected.trim() != DESKTOP_FILE_ID { + return Err(AppError::new(format!( + "The desktop did not select Debforge for MIME type {mime_type}." + ))); + } + } + println!("Debforge is now the default application for .deb files."); + Ok(()) +} + +fn verify_helper() -> Result<()> { + let path = Path::new(PRIVILEGED_HELPER); + let metadata = fs::symlink_metadata(path).context(format!( + "The secure installation helper is not installed at {PRIVILEGED_HELPER}. Install the Debforge system package first." + ))?; + if metadata.file_type().is_symlink() || !metadata.is_file() { + return Err(AppError::new(format!( + "The secure installation helper is not a regular file: {PRIVILEGED_HELPER}" + ))); + } + use std::os::unix::fs::MetadataExt; + if metadata.uid() != 0 || metadata.gid() != 0 || metadata.mode() & 0o022 != 0 { + return Err(AppError::new( + "The secure installation helper must have root ownership and must not be writable by other users.", + )); + } + Ok(()) +} + +fn convert_for_install(input: &Path, output: &Path) -> Result<()> { + let converter = env::current_exe().context("Cannot find the running Debforge executable")?; + println!("Converting {}...", input.display()); + let status = Command::new(converter) + .args(["--Quiet", "--scripts", "safe", "--output"]) + .arg(output) + .arg(input) + .stdin(Stdio::null()) + .status() + .context("Cannot start the Debforge converter")?; + if status.success() { + Ok(()) + } else { + Err(AppError::new(format!( + "Debforge could not convert the selected package (status {status})." + ))) + } +} + +fn find_converted_package(output: &Path) -> Result { + let mut packages = fs::read_dir(output) + .context(format!( + "Cannot read conversion output {}", + output.display() + ))? + .filter_map(|entry| entry.ok()) + .map(|entry| entry.path()) + .filter(|path| { + path.file_name() + .and_then(OsStr::to_str) + .is_some_and(|name| name.contains(".pkg.tar.") && !name.contains(".partial.")) + && path.is_file() + }) + .collect::>(); + packages.sort(); + match packages.as_slice() { + [package] => Ok(package.clone()), + [] => Err(AppError::new( + "The conversion did not create an installable Arch package.", + )), + _ => Err(AppError::new( + "The conversion created more than one Arch package. Installation stopped.", + )), + } +} + +fn query_package_identity(package: &Path) -> Result<(String, String)> { + let pacman = process::require_tool("pacman")?; + let identity = process::capture_text( + Command::new(pacman) + .args(["-Qp", "--"]) + .arg(package) + .stdin(Stdio::null()), + )?; + let mut fields = identity.split_whitespace(); + let name = fields + .next() + .filter(|value| is_safe_package_component(value)) + .ok_or_else(|| AppError::new("Pacman returned an invalid package name."))?; + let version = fields + .next() + .filter(|value| !value.is_empty() && !value.contains(['\n', '\r'])) + .ok_or_else(|| AppError::new("Pacman returned an invalid package version."))?; + if fields.next().is_some() { + return Err(AppError::new( + "Pacman returned an invalid package identity.", + )); + } + Ok((name.to_string(), version.to_string())) +} + +fn read_annotations(package: &Path) -> Result { + let bsdtar = process::require_tool("bsdtar")?; + let pkginfo = process::capture_text( + Command::new(bsdtar) + .args(["-xOf"]) + .arg(package) + .arg(".PKGINFO") + .stdin(Stdio::null()), + )?; + parse_annotations(&pkginfo) +} + +fn parse_annotations(pkginfo: &str) -> Result { + let mut annotations = PackageAnnotations::default(); + for line in pkginfo.lines() { + let Some(value) = line.strip_prefix("xdata = ") else { + continue; + }; + if let Some(digest) = value.strip_prefix("debian-sha256=") { + annotations.source_sha256 = Some(digest::normalize_sha256(digest)?); + } else if let Some(warning) = value.strip_prefix("debforge-warning=") { + if !warning.trim().is_empty() + && !annotations.warnings.iter().any(|item| item == warning) + { + annotations.warnings.push(warning.to_string()); + } + } + } + Ok(annotations) +} + +fn show_review( + input: &Path, + package: &Path, + package_name: &str, + package_version: &str, + source_sha256: &str, + annotations: &PackageAnnotations, +) -> Result<()> { + let pacman = process::require_tool("pacman")?; + let details = process::capture_text( + Command::new(&pacman) + .args(["-Qip", "--"]) + .arg(package) + .stdin(Stdio::null()), + )?; + let files = process::capture_text( + Command::new(&pacman) + .args(["-Qlp", "--"]) + .arg(package) + .stdin(Stdio::null()), + )?; + let transaction = process::capture_text( + Command::new(&pacman) + .args([ + "-U", + "--print", + "--print-format", + "%n %v [%a] %s bytes", + "--", + ]) + .arg(package) + .stdin(Stdio::null()), + )?; + + println!("\nDebforge installation review"); + println!("Source : {}", input.display()); + println!("Source SHA-256: {source_sha256}"); + println!("Package : {package_name} {package_version}"); + println!("Package files: {}", files.lines().count()); + println!("\nPacman package information:\n{}", details.trim()); + println!("\nPlanned transaction:\n{}", transaction.trim()); + + if command_succeeds(Command::new(&pacman).args(["-Si", "--", package_name])) { + println!( + "\nWarning: The configured Arch repositories contain a native package named '{package_name}'." + ); + } + if let Ok(installed) = process::capture_text( + Command::new(&pacman) + .args(["-Q", "--", package_name]) + .stdin(Stdio::null()), + ) { + println!("Installed now: {}", installed.trim()); + } + if !annotations.warnings.is_empty() { + println!("\nConversion warnings:"); + for warning in &annotations.warnings { + println!(" - {warning}"); + } + } + Ok(()) +} + +fn command_succeeds(command: &mut Command) -> bool { + command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|status| status.success()) +} + +fn confirm_installation() -> Result { + if !io::stdin().is_terminal() { + return Err(AppError::new( + "Installation needs a terminal confirmation. Use --yes only after you review the package separately.", + )); + } + print!("\nInstall this package? [y/N] "); + io::stdout() + .flush() + .context("Cannot display the confirmation")?; + let mut answer = String::new(); + io::stdin() + .read_line(&mut answer) + .context("Cannot read the installation confirmation")?; + Ok(is_affirmative(&answer)) +} + +fn is_affirmative(value: &str) -> bool { + matches!(value.trim().to_ascii_lowercase().as_str(), "y" | "yes") +} + +fn run_privileged_install(package: &Path, expected_sha256: &str) -> Result<()> { + let pkexec = process::require_tool("pkexec")?; + println!("\nRequesting permission for the Pacman transaction..."); + let status = Command::new(pkexec) + .arg(PRIVILEGED_HELPER) + .args(["--sha256", expected_sha256, "--"]) + .arg(package) + .status() + .context("Cannot start the secure installation helper")?; + match status.code() { + Some(0) => Ok(()), + Some(126) => Err(AppError::new("Authorization was canceled.")), + Some(127) => Err(AppError::new("Authorization was not available.")), + _ => Err(AppError::new(format!( + "The Pacman transaction failed with status {status}." + ))), + } +} + +fn verify_installed(package_name: &str, expected_version: &str) -> Result<()> { + let pacman = process::require_tool("pacman")?; + let installed = process::capture_text( + Command::new(pacman) + .args(["-Q", "--", package_name]) + .stdin(Stdio::null()), + )?; + let actual_version = installed.split_whitespace().nth(1).unwrap_or_default(); + if actual_version != expected_version { + return Err(AppError::new(format!( + "Pacman installed version '{actual_version}', but Debforge expected '{expected_version}'." + ))); + } + println!("Installed: {package_name} {expected_version}"); + Ok(()) +} + +fn write_receipt(receipt: &InstallReceipt) -> Result { + let source_path = receipt.source_path.to_string_lossy(); + if source_path.contains(['\n', '\r']) { + return Err(AppError::new("The Debian source path contains a new line.")); + } + let state_root = state_home()?.join("debforge").join("receipts"); + fs::create_dir_all(&state_root).context(format!( + "Cannot create receipt directory {}", + state_root.display() + ))?; + fs::set_permissions(&state_root, fs::Permissions::from_mode(0o700)).context(format!( + "Cannot protect receipt directory {}", + state_root.display() + ))?; + + let final_path = state_root.join(format!("{}.receipt", receipt.package_name)); + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| AppError::new(format!("The system clock is before 1970: {error}")))? + .as_nanos(); + let temporary = state_root.join(format!( + ".{}.receipt.{}.{nonce}.partial", + receipt.package_name, + std::process::id(), + )); + let mut temporary_guard = ReceiptGuard::new(temporary.clone()); + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&temporary) + .context(format!("Cannot create receipt {}", temporary.display()))?; + let installed_at = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| AppError::new(format!("The system clock is before 1970: {error}")))? + .as_secs(); + writeln!(file, "format=1").context("Cannot write receipt")?; + writeln!(file, "package={}", receipt.package_name).context("Cannot write receipt")?; + writeln!(file, "version={}", receipt.package_version).context("Cannot write receipt")?; + writeln!(file, "source={source_path}").context("Cannot write receipt")?; + writeln!(file, "source_sha256={}", receipt.source_sha256).context("Cannot write receipt")?; + writeln!(file, "converted_sha256={}", receipt.converted_sha256) + .context("Cannot write receipt")?; + writeln!(file, "debforge_version={}", env!("CARGO_PKG_VERSION")) + .context("Cannot write receipt")?; + writeln!(file, "installed_at={installed_at}").context("Cannot write receipt")?; + file.sync_all().context("Cannot synchronize receipt")?; + fs::rename(&temporary, &final_path).context(format!( + "Cannot publish installation receipt {}", + final_path.display() + ))?; + temporary_guard.disarm(); + Ok(final_path) +} + +struct ReceiptGuard { + path: PathBuf, + armed: bool, +} + +impl ReceiptGuard { + fn new(path: PathBuf) -> Self { + Self { path, armed: true } + } + + fn disarm(&mut self) { + self.armed = false; + } +} + +impl Drop for ReceiptGuard { + fn drop(&mut self) { + if self.armed { + let _ = fs::remove_file(&self.path); + } + } +} + +fn state_home() -> Result { + if let Some(path) = env::var_os("XDG_STATE_HOME").map(PathBuf::from) { + if path.is_absolute() { + return Ok(path); + } + } + env::var_os("HOME") + .map(PathBuf::from) + .filter(|path| path.is_absolute()) + .map(|path| path.join(".local/state")) + .ok_or_else(|| AppError::new("Cannot find an absolute XDG_STATE_HOME or HOME directory.")) +} + +fn is_safe_package_component(value: &str) -> bool { + !value.is_empty() + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.' | b'_')) +} + +fn notify_success(receipt: &InstallReceipt) { + let Some(notify_send) = process::find_tool("notify-send") else { + return; + }; + let _ = Command::new(notify_send) + .args([ + "--app-name=Debforge", + "--icon=io.github.devnvll.Debforge", + "Package installed", + &format!("{} {}", receipt.package_name, receipt.package_version), + ]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); +} + +#[cfg(test)] +mod tests { + use super::{PackageAnnotations, is_affirmative, parse_annotations}; + + #[test] + fn reads_debforge_annotations() { + let digest = "a".repeat(64); + let source = format!( + "pkgname = demo\nxdata = debian-sha256={digest}\nxdata = debforge-warning=Review this.\nxdata = debforge-warning=Review this.\n" + ); + assert_eq!( + parse_annotations(&source).expect("annotations"), + PackageAnnotations { + source_sha256: Some(digest), + warnings: vec!["Review this.".to_string()], + } + ); + } + + #[test] + fn confirmation_is_explicit() { + assert!(is_affirmative("y\n")); + assert!(is_affirmative("YES")); + assert!(!is_affirmative("")); + assert!(!is_affirmative("sure")); + } +} diff --git a/src/lib.rs b/src/lib.rs index d60fe47..8ade5f3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,9 +1,13 @@ pub mod archive; pub mod cli; +pub mod compatibility; pub mod control; pub mod dependency; +pub mod digest; pub mod error; +pub mod installer; pub mod package; +pub mod privileged; pub mod process; pub mod scripts; pub mod transform; diff --git a/src/main.rs b/src/main.rs index 43585de..6a26872 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,14 +1,17 @@ use std::collections::BTreeSet; use std::fs; use std::path::{Path, PathBuf}; -use std::process::{Command, ExitCode}; +use std::process::ExitCode; use std::time::{Instant, SystemTime, UNIX_EPOCH}; use debtap_rs::archive::{self, PackageOptions}; use debtap_rs::cli::{self, Action, ConvertOptions, PkgbuildMode}; +use debtap_rs::compatibility; use debtap_rs::control::{ArchVersion, DebianControl, DebianMetadata, RelationField}; use debtap_rs::dependency::{DependencyResolver, PackageCatalog, RelationSet, Resolution}; +use debtap_rs::digest; use debtap_rs::error::{AppError, Context, Result}; +use debtap_rs::installer; use debtap_rs::package::{self, ArchPackageMetadata, PkgbuildSpec}; use debtap_rs::process; use debtap_rs::scripts; @@ -35,6 +38,8 @@ fn run() -> Result<()> { println!("debtap-rs {}", cli::VERSION); Ok(()) } + Action::Install(options) => installer::install(&options), + Action::RegisterHandler => installer::register_handler(), Action::Update => update_catalog(), Action::Convert(options) => convert(options), } @@ -128,12 +133,21 @@ fn convert(options: ConvertOptions) -> Result<()> { )?; warnings.extend(transform.warnings); + progress( + &options, + "Checking ELF and privileged-file compatibility...", + ); + let compatibility = + compatibility::inspect_payload(workspace.payload_dir(), &debian.architecture)?; + warnings.extend(compatibility.warnings()); + let script_output = scripts::generate_install_script(options.script_policy, workspace.control_dir())?; warnings.extend(script_output.warnings); let arch_version = ArchVersion::from_debian(&debian.debian_version)?; let builddate = build_timestamp(options.source_date_epoch)?; + let source_sha256 = digest::sha256_file(&input)?; let metadata = ArchPackageMetadata { pkgname: debian.name.clone(), pkgbase: debian.source.clone(), @@ -157,6 +171,8 @@ fn convert(options: ConvertOptions) -> Result<()> { debian_package: debian.name.clone(), debian_version: debian.debian_version.clone(), debian_architecture: debian.debian_architecture.clone(), + debian_sha256: source_sha256.clone(), + conversion_warnings: warnings.clone(), }; metadata.validate()?; @@ -212,7 +228,6 @@ fn convert(options: ConvertOptions) -> Result<()> { pkgbuild_directory.display() ))?; } - let hash = sha256_file(&input)?; let data_member = deb_archive .data_member_name .to_str() @@ -223,7 +238,7 @@ fn convert(options: ConvertOptions) -> Result<()> { metadata: &metadata, source_deb: &input, data_member, - sha256: &hash, + sha256: &source_sha256, }, )?; generated.push(path); @@ -403,17 +418,6 @@ fn parse_licenses(source: Option<&str>) -> Vec { .collect() } -fn sha256_file(path: &Path) -> Result { - let sha256sum = process::require_tool("sha256sum")?; - let output = process::capture_text(Command::new(sha256sum).arg("--").arg(path))?; - output - .split_whitespace() - .next() - .filter(|value| value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit())) - .map(str::to_string) - .ok_or_else(|| AppError::new("sha256sum returned an invalid digest.")) -} - fn progress(options: &ConvertOptions, message: &str) { if !options.quiet { println!("==> {message}"); diff --git a/src/package.rs b/src/package.rs index 6f6ea03..c3a2a1c 100644 --- a/src/package.rs +++ b/src/package.rs @@ -2,6 +2,7 @@ use std::fs; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; +use crate::digest; use crate::error::{AppError, Context, Result}; #[derive(Debug, Clone, PartialEq, Eq)] @@ -28,6 +29,8 @@ pub struct ArchPackageMetadata { pub debian_package: String, pub debian_version: String, pub debian_architecture: String, + pub debian_sha256: String, + pub conversion_warnings: Vec, } impl ArchPackageMetadata { @@ -41,6 +44,7 @@ impl ArchPackageMetadata { ("Debian package", self.debian_package.as_str()), ("Debian version", self.debian_version.as_str()), ("Debian architecture", self.debian_architecture.as_str()), + ("Debian SHA-256", self.debian_sha256.as_str()), ] { validate_value(name, value)?; } @@ -49,6 +53,10 @@ impl ArchPackageMetadata { "The package version and architecture must not be empty.", )); } + digest::normalize_sha256(&self.debian_sha256)?; + for warning in &self.conversion_warnings { + validate_value("conversion warning", warning)?; + } Ok(()) } @@ -73,6 +81,14 @@ impl ArchPackageMetadata { "xdata", &format!("debian-architecture={}", self.debian_architecture), )?; + write_value( + &mut output, + "xdata", + &format!("debian-sha256={}", self.debian_sha256), + )?; + for warning in sorted_unique(&self.conversion_warnings) { + write_value(&mut output, "xdata", &format!("debforge-warning={warning}"))?; + } write_value(&mut output, "pkgver", &self.full_version)?; if let Some(description) = self .description @@ -356,6 +372,8 @@ mod tests { debian_package: "chatgpt".to_string(), debian_version: "26.803.81509".to_string(), debian_architecture: "amd64".to_string(), + debian_sha256: "a".repeat(64), + conversion_warnings: vec!["A review warning.".to_string()], } } @@ -367,6 +385,8 @@ mod tests { assert!(output.contains("size = 1312001200\n")); assert!(output.contains("xdata = pkgtype=pkg\n")); assert!(output.contains("xdata = debian-version=26.803.81509\n")); + assert!(output.contains(&format!("xdata = debian-sha256={}\n", "a".repeat(64)))); + assert!(output.contains("xdata = debforge-warning=A review warning.\n")); assert!(output.contains("depend = glibc\n")); } diff --git a/src/privileged.rs b/src/privileged.rs new file mode 100644 index 0000000..b422700 --- /dev/null +++ b/src/privileged.rs @@ -0,0 +1,350 @@ +use std::env; +use std::ffi::{OsStr, OsString}; +use std::fs::{self, DirBuilder, File, OpenOptions}; +use std::io::{self, Read, Write}; +use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +use crate::digest; +use crate::error::{AppError, Context, Result}; + +const STAGING_PARENT: &str = "/var/tmp"; +const SYSTEM_SHA256SUM: &str = "/usr/bin/sha256sum"; +const MAX_PACKAGE_BYTES: u64 = 64 * 1024 * 1024 * 1024; +const O_NOFOLLOW: i32 = 0o400000; +const O_CLOEXEC: i32 = 0o2000000; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InstallRequest { + pub expected_sha256: String, + pub package: PathBuf, +} + +pub struct StagedPackage { + root: PathBuf, + path: PathBuf, +} + +impl StagedPackage { + pub fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for StagedPackage { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.root); + } +} + +pub fn run(arguments: I) -> Result<()> +where + I: IntoIterator, + S: Into, +{ + let request = parse_request(arguments)?; + let caller_uid = verify_execution_context()?; + let staged = stage_verified_package( + &request.package, + &request.expected_sha256, + caller_uid, + Path::new(STAGING_PARENT), + )?; + validate_and_install(staged.path()) +} + +pub fn parse_request(arguments: I) -> Result +where + I: IntoIterator, + S: Into, +{ + let arguments = arguments.into_iter().map(Into::into).collect::>(); + if arguments.len() != 4 || arguments[0] != "--sha256" || arguments[2] != "--" { + return Err(AppError::new( + "Usage: debforge-helper --sha256 DIGEST -- PACKAGE", + )); + } + let digest_text = arguments[1] + .to_str() + .ok_or_else(|| AppError::new("The expected SHA-256 value is not valid UTF-8."))?; + let expected_sha256 = digest::normalize_sha256(digest_text)?; + let package = PathBuf::from(&arguments[3]); + if !package.is_absolute() { + return Err(AppError::new("The package path must be absolute.")); + } + Ok(InstallRequest { + expected_sha256, + package, + }) +} + +fn verify_execution_context() -> Result { + let status = fs::read_to_string("/proc/self/status") + .context("Cannot read the process identity from /proc/self/status")?; + let effective_uid = status + .lines() + .find_map(|line| line.strip_prefix("Uid:")) + .and_then(|value| value.split_whitespace().nth(1)) + .and_then(|value| value.parse::().ok()) + .ok_or_else(|| AppError::new("Cannot determine the effective user ID."))?; + if effective_uid != 0 { + return Err(AppError::new( + "The secure Debforge helper must run as root through Polkit.", + )); + } + + let caller_uid = env::var("PKEXEC_UID") + .context("PKEXEC_UID is absent. Start the helper through pkexec.")? + .parse::() + .context("PKEXEC_UID is not a valid user ID")?; + if caller_uid == 0 { + return Err(AppError::new( + "The Debforge helper requires a non-root desktop caller.", + )); + } + Ok(caller_uid) +} + +pub fn stage_verified_package( + source_path: &Path, + expected_sha256: &str, + caller_uid: u32, + staging_parent: &Path, +) -> Result { + let expected_sha256 = digest::normalize_sha256(expected_sha256)?; + let mut source_options = OpenOptions::new(); + source_options + .read(true) + .custom_flags(O_NOFOLLOW | O_CLOEXEC); + let mut source = source_options.open(source_path).context(format!( + "Cannot securely open converted package {}", + source_path.display() + ))?; + let source_metadata = source.metadata().context(format!( + "Cannot inspect converted package {}", + source_path.display() + ))?; + if !source_metadata.is_file() { + return Err(AppError::new( + "The converted package is not a regular file.", + )); + } + if source_metadata.uid() != caller_uid { + return Err(AppError::new( + "The converted package is not owned by the authorizing user.", + )); + } + if source_metadata.len() == 0 || source_metadata.len() > MAX_PACKAGE_BYTES { + return Err(AppError::new( + "The converted package size is outside the supported range.", + )); + } + + let root = create_private_staging(staging_parent)?; + let mut guard = StagingGuard::new(root.clone()); + let staged_path = root.join("package.pkg.tar.zst"); + let mut staged = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(O_CLOEXEC) + .open(&staged_path) + .context(format!( + "Cannot create secure package copy {}", + staged_path.display() + ))?; + let copied = io::copy(&mut source, &mut staged).context("Cannot copy the converted package")?; + if copied != source_metadata.len() { + return Err(AppError::new( + "The converted package changed while the secure copy was created.", + )); + } + staged + .flush() + .context("Cannot flush the secure package copy")?; + staged + .sync_all() + .context("Cannot synchronize the secure package copy")?; + drop(staged); + + let actual_sha256 = digest::sha256_file_with_tool(&staged_path, Path::new(SYSTEM_SHA256SUM))?; + if actual_sha256 != expected_sha256 { + return Err(AppError::new( + "The converted package changed after the installation review.", + )); + } + + guard.disarm(); + Ok(StagedPackage { + root, + path: staged_path, + }) +} + +fn create_private_staging(parent: &Path) -> Result { + let parent_metadata = fs::metadata(parent).context(format!( + "Cannot inspect staging parent {}", + parent.display() + ))?; + if !parent_metadata.is_dir() { + return Err(AppError::new(format!( + "The staging parent is not a directory: {}", + parent.display() + ))); + } + + for _ in 0..32 { + let nonce = random_nonce()?; + let candidate = parent.join(format!("debforge-install-{nonce}")); + match DirBuilder::new().mode(0o700).create(&candidate) { + Ok(()) => return Ok(candidate), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => { + return Err(AppError::new(format!( + "Cannot create secure staging directory {}: {error}", + candidate.display() + ))); + } + } + } + Err(AppError::new( + "Cannot allocate a unique secure staging directory.", + )) +} + +fn random_nonce() -> Result { + let mut random = File::open("/dev/urandom").context("Cannot open /dev/urandom")?; + let mut bytes = [0_u8; 16]; + random + .read_exact(&mut bytes) + .context("Cannot read a secure random value")?; + let mut output = String::with_capacity(bytes.len() * 2); + for byte in bytes { + use std::fmt::Write as _; + write!(&mut output, "{byte:02x}").expect("writing to a string cannot fail"); + } + Ok(output) +} + +fn validate_and_install(package: &Path) -> Result<()> { + let pacman = Path::new("/usr/bin/pacman"); + if !pacman.is_file() { + return Err(AppError::new("Pacman is not installed at /usr/bin/pacman.")); + } + + let validation = Command::new(pacman) + .args([OsStr::new("-Qp"), OsStr::new("--")]) + .arg(package) + .stdin(Stdio::null()) + .status() + .context("Cannot start Pacman package validation")?; + if !validation.success() { + return Err(AppError::new(format!( + "Pacman rejected the secure package copy (status {validation})." + ))); + } + + let installation = Command::new(pacman) + .args([ + OsStr::new("-U"), + OsStr::new("--needed"), + OsStr::new("--noconfirm"), + OsStr::new("--"), + ]) + .arg(package) + .status() + .context("Cannot start the Pacman transaction")?; + if installation.success() { + Ok(()) + } else { + Err(AppError::new(format!( + "Pacman could not install the package (status {installation})." + ))) + } +} + +struct StagingGuard { + path: PathBuf, + armed: bool, +} + +impl StagingGuard { + fn new(path: PathBuf) -> Self { + Self { path, armed: true } + } + + fn disarm(&mut self) { + self.armed = false; + } +} + +impl Drop for StagingGuard { + fn drop(&mut self) { + if self.armed { + let _ = fs::remove_dir_all(&self.path); + } + } +} + +#[cfg(test)] +mod tests { + use std::ffi::OsString; + use std::fs; + use std::os::unix::fs::{MetadataExt, symlink}; + + use super::{parse_request, stage_verified_package}; + use crate::digest; + + fn test_root(name: &str) -> std::path::PathBuf { + let path = + std::env::temp_dir().join(format!("debforge-helper-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir(&path).expect("test root"); + path + } + + #[test] + fn parses_only_the_fixed_helper_interface() { + let digest = "a".repeat(64); + let request = parse_request([ + OsString::from("--sha256"), + OsString::from(digest.clone()), + OsString::from("--"), + OsString::from("/tmp/package.pkg.tar.zst"), + ]) + .expect("request"); + assert_eq!(request.expected_sha256, digest); + assert!(parse_request([OsString::from("/tmp/package")]).is_err()); + assert!( + parse_request([ + OsString::from("--sha256"), + OsString::from("bad"), + OsString::from("--"), + OsString::from("/tmp/package"), + ]) + .is_err() + ); + } + + #[test] + fn stages_one_verified_regular_file_and_rejects_a_link() { + let root = test_root("stage"); + let source = root.join("source.pkg.tar.zst"); + fs::write(&source, b"verified package bytes").expect("source"); + let digest = digest::sha256_file(&source).expect("digest"); + let uid = fs::metadata(&source).expect("metadata").uid(); + { + let staged = stage_verified_package(&source, &digest, uid, &root).expect("stage"); + assert_eq!( + fs::read(staged.path()).expect("staged bytes"), + b"verified package bytes" + ); + } + + let link = root.join("link.pkg.tar.zst"); + symlink(&source, &link).expect("link"); + assert!(stage_verified_package(&link, &digest, uid, &root).is_err()); + fs::remove_dir_all(root).expect("cleanup"); + } +} diff --git a/src/scripts.rs b/src/scripts.rs index 0c74291..b108afa 100644 --- a/src/scripts.rs +++ b/src/scripts.rs @@ -46,6 +46,7 @@ struct MaintainerScripts { postinst: Option, prerm: Option, postrm: Option, + triggers: Option, } impl MaintainerScripts { @@ -55,10 +56,19 @@ impl MaintainerScripts { postinst: read_optional(control_dir, "postinst")?, prerm: read_optional(control_dir, "prerm")?, postrm: read_optional(control_dir, "postrm")?, + triggers: read_optional(control_dir, "triggers")?, }) } fn present_names(&self) -> Vec<&'static str> { + let mut names = self.present_script_names(); + if self.triggers.is_some() { + names.push("triggers"); + } + names + } + + fn present_script_names(&self) -> Vec<&'static str> { let mut names = Vec::new(); if self.preinst.is_some() { names.push("preinst"); @@ -113,6 +123,13 @@ fn generate_safe_output(scripts: &MaintainerScripts) -> ScriptOutput { .collect::>() .join("\n"); + if scripts.triggers.is_some() { + warnings.push( + "Debian dpkg triggers were not copied; Pacman transaction hooks will handle only standard cache updates." + .to_string(), + ); + } + for (needle, message) in [ ("/etc/apt", "Debian repository changes were not copied."), ( @@ -170,19 +187,20 @@ fn generate_raw_output(scripts: &MaintainerScripts) -> ScriptOutput { append_function(&mut output, "post_remove", &["remove"], body); } - let install = if scripts.present_names().is_empty() { + let install = if scripts.present_script_names().is_empty() { None } else { Some(output) }; - ScriptOutput { - install, - warnings: vec![ - "Raw script mode can run Debian-only commands as root.".to_string(), - "Upgrade script arguments are an approximation and require review.".to_string(), - ], + let mut warnings = vec![ + "Raw script mode can run Debian-only commands as root.".to_string(), + "Upgrade script arguments are an approximation and require review.".to_string(), + ]; + if scripts.triggers.is_some() { + warnings.push("Raw mode cannot translate Debian dpkg triggers.".to_string()); } + ScriptOutput { install, warnings } } fn append_function(output: &mut String, function: &str, arguments: &[&str], body: &str) { @@ -248,12 +266,14 @@ mod tests { "#!/bin/sh\nset -e\napt-get update\nmkdir -p /etc/apt/sources.list.d\nupdate-alternatives --install /usr/bin/x x /opt/x 1\n", ) .expect("script"); + fs::write(directory.join("triggers"), "interest update-mime\n").expect("triggers"); let result = generate_install_script(ScriptPolicy::Safe, &directory).expect("output"); assert!(result.install.is_none()); let warnings = result.warnings.join(" "); assert!(warnings.contains("repository")); assert!(warnings.contains("alternatives")); + assert!(warnings.contains("dpkg triggers")); fs::remove_dir_all(directory).expect("cleanup"); }