commit 4e5eca192559dd3bd9dffa877919261e9fda5682 Author: Henry-Hiles Date: Thu Dec 3 13:50:41 2026 -0500 initial commit diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9efa6fb --- /dev/null +++ b/LICENSE @@ -0,0 +1,338 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The 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. + + GNU GENERAL PUBLIC LICENSE + 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. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 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, see . + +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. + + , 1 April 1989 + Moe Ghoul, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..99feb43 --- /dev/null +++ b/Makefile @@ -0,0 +1,15 @@ +CC ?= cc +CFLAGS ?= -O2 +PREFIX ?= /usr/local + +qseecom-supplicant: qseecom-supplicant.c + $(CC) $(CFLAGS) -Wall -Wextra -pthread -o $@ $< $(LDFLAGS) + +install: qseecom-supplicant + install -Dm755 qseecom-supplicant -t $(DESTDIR)$(PREFIX)/bin + install -Dm644 qseecom-supplicant.service -t $(DESTDIR)$(PREFIX)/lib/systemd/system + +clean: + rm -f qseecom-supplicant + +.PHONY: install clean diff --git a/README.md b/README.md new file mode 100644 index 0000000..042767c --- /dev/null +++ b/README.md @@ -0,0 +1,61 @@ +# qseecom-supplicant + +What Qualcomm QSEE trusted apps call back into, for Linux's QSEECOM TEE driver +([wrobelda/linux `qcom-qseecom-tee`](https://github.com/wrobelda/linux/tree/qcom-qseecom-tee)). It's +the part of Android's `qseecomd` they need, the way `tee-supplicant` is for OP-TEE. + +Trusted apps reach the normal world through listeners, and this serves three: + +- **10, the file system.** Open, read, write, seek and so on, for the app's Android paths. +- **28672, the GP file system,** where apps keep their sealed objects. +- **8192, RPMB,** the UFS Replay Protected Memory Block. Gatekeeper, in keymaster64, keeps its + password handles and rollback counter there. The secure world MACs every frame, so this only + moves frames between it and the RPMB well-known LUN, with SCSI SECURITY PROTOCOL IN/OUT. + +The Android paths apps ask for are served from below a root directory. It also loads the apps it's +given, and keeps them loaded while it runs. Apps the firmware loads itself, like keymaster64, are +served all the same. + +```sh +qseecom-supplicant [app...] +``` + +An app is loaded as `.mdt` and its `.bNN` segments, from the firmware directory: the kernel +fetches them with `request_firmware()`, so the firmware search path is pointed there while loading. + +It came out of getting the OnePlus 6T's in-display fingerprint sensor working, whose app (gfp9508) +and libfprint driver need it, but nothing in it is specific to that. + +## Using it + +On NixOS, import the flake's module and turn it on: + +```nix +imports = [ qseecom-supplicant.nixosModules.default ]; +services.qseecom-supplicant = { + enable = true; + apps = [ "gfp9508" ]; +}; +``` + +- `root`, where apps keep their data, `/var/lib/qseecom` by default. Under `/var/lib`, it's the + service's state directory. +- `firmwareDirectory`, where the apps are, the system's firmware by default. + +Elsewhere, `make install` installs it and a systemd unit. Set `QSEECOM_APPS` in the unit to the apps +to load, and if they aren't in `/lib/firmware`, change its firmware directory. + +Only one supplicant can run at a time: the driver has one queue of requests, so two would take each +other's. + +## Limitations + +- RPMB is only reached on UFS, through the `/dev/bsg/*:49476` node, with 8192 sectors and one frame + per reliable write, rather than read from the device's descriptors. +- File system operations nothing has asked for yet (`stat`, directories, links, free space) are + refused. + +## License + +GPL-2.0-only. The listeners and the RPMB bridge come from `gfharness` in +[wrobelda/goodix-fp-spi-linux](https://github.com/wrobelda/goodix-fp-spi-linux). diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..a3a284f --- /dev/null +++ b/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1796087880, + "narHash": "sha256-P2MPChVGraSc3Lt8RCUpTwu07reSinLxqmVV/rzq2io=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "c555305170f8bdcc9d420912c04cdf3d6d61d08c", + "type": "github" + }, + "original": { + "owner": "nixos", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..236c069 --- /dev/null +++ b/flake.nix @@ -0,0 +1,23 @@ +{ + inputs.nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; + + outputs = + { self, nixpkgs, ... }: + let + forAllSystems = nixpkgs.lib.genAttrs [ + "x86_64-linux" + "aarch64-linux" + ]; + in + { + overlays.default = final: prev: { + qseecom-supplicant = final.callPackage ./package.nix { }; + }; + + nixosModules.default = ./module.nix; + + packages = forAllSystems (system: { + default = (nixpkgs.legacyPackages.${system}.extend self.overlays.default).qseecom-supplicant; + }); + }; +} diff --git a/module.nix b/module.nix new file mode 100644 index 0000000..10048e0 --- /dev/null +++ b/module.nix @@ -0,0 +1,72 @@ +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.services.qseecom-supplicant; +in +{ + options.services.qseecom-supplicant = { + enable = lib.mkEnableOption "the listeners for Qualcomm QSEE trusted apps, for the QSEECOM TEE driver"; + + package = lib.mkOption { + type = lib.types.package; + default = pkgs.callPackage ./package.nix { }; + defaultText = lib.literalMD "qseecom-supplicant from this flake"; + description = "The qseecom-supplicant package."; + }; + + root = lib.mkOption { + type = lib.types.str; + default = "/var/lib/qseecom"; + description = '' + The directory the apps' Android paths are served from, where they keep their data. + Under /var/lib, it's the service's state directory. + ''; + }; + + firmwareDirectory = lib.mkOption { + type = lib.types.str; + default = "/run/current-system/firmware"; + description = "Where the apps to load are, as `.mdt` and its `.bNN` segments."; + }; + + apps = lib.mkOption { + type = lib.types.listOf lib.types.str; + default = [ ]; + example = [ "gfp9508" ]; + description = '' + The apps to load and keep loaded. Apps the firmware loads itself, like keymaster64, + don't go here, but are served all the same. + ''; + }; + }; + + config = lib.mkIf cfg.enable { + systemd.services.qseecom-supplicant = { + description = "Listeners for QSEE trusted apps"; + wantedBy = [ "multi-user.target" ]; + # Its devices come with modules loaded as they're found, so it keeps + # trying until they're all there + startLimitIntervalSec = 0; + serviceConfig = { + ExecStart = lib.escapeShellArgs ( + [ + (lib.getExe cfg.package) + cfg.root + cfg.firmwareDirectory + ] + ++ cfg.apps + ); + StateDirectory = lib.mkIf (lib.hasPrefix "/var/lib/" cfg.root) ( + lib.removePrefix "/var/lib/" cfg.root + ); + StateDirectoryMode = "0700"; + Restart = "on-failure"; + RestartSec = 5; + }; + }; + }; +} diff --git a/package.nix b/package.nix new file mode 100644 index 0000000..c5e5d47 --- /dev/null +++ b/package.nix @@ -0,0 +1,31 @@ +{ lib, stdenv }: +stdenv.mkDerivation { + pname = "qseecom-supplicant"; + version = "0.1.0"; + + src = lib.fileset.toSource { + root = ./.; + fileset = lib.fileset.unions [ + ./Makefile + ./qseecom-supplicant.c + ./qseecom-supplicant.service + ]; + }; + + makeFlags = [ + "CC=${stdenv.cc.targetPrefix}cc" + "PREFIX=${placeholder "out"}" + ]; + + postInstall = '' + substituteInPlace $out/lib/systemd/system/qseecom-supplicant.service \ + --replace-fail /usr/local/bin/ $out/bin/ + ''; + + meta = { + description = "Listeners for Qualcomm QSEE trusted apps, for Linux's QSEECOM TEE driver"; + license = lib.licenses.gpl2Only; + platforms = lib.platforms.linux; + mainProgram = "qseecom-supplicant"; + }; +} diff --git a/qseecom-supplicant.c b/qseecom-supplicant.c new file mode 100644 index 0000000..5e58264 --- /dev/null +++ b/qseecom-supplicant.c @@ -0,0 +1,611 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * qseecom-supplicant: what Qualcomm QSEE trusted apps call back into, for + * Linux's QSEECOM TEE driver, as qseecomd does on Android. + * + * It serves their listeners: the file system (10), the GP file system where + * they keep sealed objects (28672), and RPMB (8192), which Gatekeeper in + * keymaster64 keeps its state in. Their Android paths are served from below + * a root directory. It also loads the apps named on its command line, from a + * firmware directory, and keeps them loaded while it runs. + * + * qseecom-supplicant [app...] + * + * The listeners and the RPMB bridge come from gfharness in + * wrobelda/goodix-fp-spi-linux. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#define TEE_IMPL_ID_QSEECOM 5 + +#define LOG(...) fprintf(stderr, __VA_ARGS__) + +/* Where the apps' Android paths are served from */ +static const char *fs_root; + +/* ---- TEE ---- */ + +struct shm { + int id; + uint8_t *va; + size_t size; +}; + +static int shm_alloc(int fd, size_t size, struct shm *s) +{ + struct tee_ioctl_shm_alloc_data d = { .size = size }; + int sfd = ioctl(fd, TEE_IOC_SHM_ALLOC, &d); + + if (sfd < 0) + return -1; + s->va = mmap(NULL, d.size, PROT_READ | PROT_WRITE, MAP_SHARED, sfd, 0); + close(sfd); + if (s->va == MAP_FAILED) + return -1; + s->id = d.id; + s->size = d.size; + memset(s->va, 0, s->size); + return 0; +} + +/* The QSEECOM client (teeN) or supplicant (teeprivN) device, by impl id. */ +static int tee_open(const char *base) +{ + struct tee_ioctl_version_data v; + char path[32]; + + for (int i = 0; i < 8; i++) { + int fd; + + snprintf(path, sizeof(path), "/dev/%s%d", base, i); + fd = open(path, O_RDWR | O_CLOEXEC); + if (fd < 0) + continue; + if (!ioctl(fd, TEE_IOC_VERSION, &v) && + v.impl_id == TEE_IMPL_ID_QSEECOM) + return fd; + close(fd); + } + LOG("no QSEECOM %s device\n", base); + return -1; +} + +/* + * Open a session on a trusted app by name. On the supplicant device this + * loads the app, which stays loaded while the session is open. + */ +static int tee_session(int fd, const char *app) +{ + struct { + struct tee_ioctl_open_session_arg arg; + struct tee_ioctl_param params[1]; + } s = {}; + struct tee_ioctl_buf_data bd = { (uintptr_t)&s, sizeof(s) }; + struct shm name; + + if (shm_alloc(fd, 64, &name)) + return -1; + strcpy((char *)name.va, app); + s.arg.num_params = 1; + s.params[0].attr = TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT; + s.params[0].b = strlen(app) + 1; + s.params[0].c = name.id; + if (ioctl(fd, TEE_IOC_OPEN_SESSION, &bd) || s.arg.ret) { + LOG("open session on %s: %s (ret 0x%x)\n", app, + strerror(errno), s.arg.ret); + return -1; + } + return s.arg.session; +} + +/* ---- Listeners the TA calls back into ---- */ + +static int fs_last_errno; + +static void fs_path(char *out, size_t n, const char *req) +{ + snprintf(out, n, "%s%s%s", fs_root, req[0] == '/' ? "" : "/", req); +} + +static void mkparents(const char *path) +{ + char tmp[512]; + + snprintf(tmp, sizeof(tmp), "%s", path); + for (char *p = tmp + 1; *p; p++) { + if (*p != '/') + continue; + *p = '\0'; + mkdir(tmp, 0700); + *p = '/'; + } +} + +/* + * Listener 10, the file system. A request carries an op at +0 and either a + * path at +4 (flags or mode at +260) or an fd at +4 (count or offset at +8, + * whence at +12, write count at +20008). The reply is {op, result} at the + * head of the buffer; a read puts its data at +4 and its count at +20004. + * Failures return -1, and the errno is fetched with its own op. + */ +static void fs_reply(uint8_t *b, uint32_t op, int32_t ret) +{ + if (ret < 0) + fs_last_errno = errno; + memcpy(b, &op, 4); + memcpy(b + 4, &ret, 4); +} + +static int fs_serve(uint8_t *b) +{ + uint32_t op = *(uint32_t *)b, n; + int32_t fd = *(int32_t *)(b + 4); + char path[512] = "", path2[512]; + ssize_t r; + + /* Only these carry a path; for the others +4 on is an fd and data */ + if (op == 0x202 || op == 0x206 || op == 0x20c || op == 0x210 || + op == 0x217) { + b[4 + 255] = '\0'; + fs_path(path, sizeof(path), (const char *)b + 4); + } + + switch (op) { + case 0x202: /* open */ + if (*(uint32_t *)(b + 260) & O_CREAT) + mkparents(path); + fs_reply(b, op, open(path, *(uint32_t *)(b + 260) | O_CLOEXEC, + 0600)); + break; + case 0x206: /* creat */ + mkparents(path); + fs_reply(b, op, open(path, O_CREAT | O_WRONLY | O_TRUNC | + O_CLOEXEC, 0600)); + break; + case 0x207: /* read */ + n = *(uint32_t *)(b + 8); + r = read(fd, b + 4, n > 20000 ? 20000 : n); + if (r < 0) + fs_last_errno = errno; + memcpy(b, &op, 4); + *(int32_t *)(b + 20004) = r; + break; + case 0x208: /* write */ + n = *(uint32_t *)(b + 20008); + fs_reply(b, op, write(fd, b + 8, n > 20000 ? 20000 : n)); + break; + case 0x209: /* close */ + fs_reply(b, op, close(fd)); + break; + case 0x20a: /* lseek */ + fs_reply(b, op, lseek(fd, *(int32_t *)(b + 8), + *(uint32_t *)(b + 12))); + break; + case 0x216: /* fsync */ + fs_reply(b, op, fsync(fd)); + break; + case 0x20c: /* unlink */ + fs_reply(b, op, unlink(path)); + break; + case 0x210: /* mkdir */ + mkparents(path); + r = mkdir(path, 0700); + fs_reply(b, op, r && errno == EEXIST ? 0 : r); + break; + case 0x217: /* rename */ + b[260 + 255] = '\0'; + fs_path(path2, sizeof(path2), (const char *)b + 260); + fs_reply(b, op, rename(path, path2)); + break; + case 0x21c: /* the last errno */ + fs_reply(b, op, fs_last_errno); + break; + case 0x21d: /* shutdown */ + fs_reply(b, op, 0); + break; + default: + LOG("fs: unhandled op 0x%x\n", op); + errno = ENOSYS; + fs_reply(b, op, -1); + } + return 0; +} + +/* + * Listener 28672, the GP file system, where the TA keeps its sealed objects. + * op % 4 picks read, write, delete or rename; op 12 asks the version. Request: + * op +0, name +4, offset (or the new name) +0x104, length +0x108, keep a + * backup +0x10c, data +0x110. Reply: op +0, errno or 0 +4, count +8, data +12. + */ +#define GP_READ_MAX 512000 + +static void copy_file(const char *from, const char *to) +{ + char buf[8192]; + int in = open(from, O_RDONLY | O_CLOEXEC), out; + ssize_t n; + + if (in < 0) + return; + out = open(to, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); + while (out >= 0 && (n = read(in, buf, sizeof(buf))) > 0) + if (write(out, buf, n) != n) + break; + close(in); + if (out >= 0) + close(out); +} + +static int gpfs_serve(uint8_t *b) +{ + uint32_t op = *(uint32_t *)b, len = *(uint32_t *)(b + 0x108); + int32_t off = *(int32_t *)(b + 0x104), ret = 0; + char path[512], path2[512]; + ssize_t n = 0; + int fd; + + b[4 + 255] = '\0'; + fs_path(path, sizeof(path), (const char *)b + 4); + if (len > GP_READ_MAX) + len = GP_READ_MAX; + + if (op == 12) { + ret = 2; + } else if (op > 12) { + ret = -1; + } else if (op % 4 == 0) { + fd = open(path, O_RDONLY | O_CLOEXEC); + n = fd < 0 ? -1 : pread(fd, b + 12, len, off); + if (fd >= 0) + close(fd); + } else if (op % 4 == 1) { + char bak[600]; + + mkparents(path); + if (*(uint32_t *)(b + 0x10c)) { + snprintf(bak, sizeof(bak), "%s.bak", path); + copy_file(path, bak); + } + fd = open(path, O_WRONLY | O_CREAT | O_CLOEXEC, 0600); + n = fd < 0 ? -1 : pwrite(fd, b + 0x110, len, off); + if (n > 0 && off == 0 && ftruncate(fd, n)) + n = -1; + if (fd >= 0) + close(fd); + } else if (op % 4 == 2) { + if (unlink(path) && (errno != EISDIR || rmdir(path))) + ret = errno; + } else { + b[0x104 + 255] = '\0'; + fs_path(path2, sizeof(path2), (const char *)b + 0x104); + mkparents(path2); + if (rename(path, path2)) + ret = errno; + } + if (n < 0) { + ret = errno; + n = 0; + } + memcpy(b, &op, 4); + memcpy(b + 4, &ret, 4); + *(uint32_t *)(b + 8) = n; + return 0; +} + +/* + * Listener 8192, RPMB. Gatekeeper (in keymaster64) keeps its password handles + * and its rollback counter in the UFS Replay Protected Memory Block. The + * secure world MACs every frame; this only moves 512-byte frames between it + * and the RPMB well-known LUN with SCSI SECURITY PROTOCOL IN/OUT, as + * Qualcomm's librpmbservice does. Each command is answered in place, with + * the status in its response struct. + */ +#define RPMB_BLK 512 + +struct __attribute__((packed)) rpmb_init_res { + uint32_t cmd_id, version; + int32_t status; + uint32_t num_sectors, rel_wr_count, dev_type, reserved[4]; +}; +struct __attribute__((packed)) rpmb_rw_req { + uint32_t cmd_id, num_sectors, req_buff_len, req_buff_offset, version, + rel_wr_count; +}; +struct __attribute__((packed)) rpmb_rw_res { + uint32_t cmd_id; + int32_t status; + uint32_t res_buff_len, res_buff_offset, version; +}; + +static int rpmb_fd = -1; + +static int rpmb_open(void) +{ + struct dirent *e; + char path[300]; + DIR *d; + + if (rpmb_fd >= 0) + return 0; + d = opendir("/dev/bsg"); + while (d && (e = readdir(d))) { + size_t l = strlen(e->d_name); + + if (l > 6 && !strcmp(e->d_name + l - 6, ":49476")) { + snprintf(path, sizeof(path), "/dev/bsg/%s", e->d_name); + rpmb_fd = open(path, O_RDWR | O_SYNC | O_CLOEXEC); + break; + } + } + if (d) + closedir(d); + if (rpmb_fd < 0) + LOG("rpmb: no usable UFS RPMB LUN\n"); + return rpmb_fd < 0 ? -1 : 0; +} + +/* One SCSI command on the RPMB LUN, retried once on a UNIT ATTENTION. */ +static int rpmb_scsi(uint8_t *cdb, int cdb_len, void *buf, uint32_t len, + int out) +{ + uint8_t sense[96]; + struct sg_io_v4 io = { + .guard = 'Q', + .protocol = BSG_PROTOCOL_SCSI, + .subprotocol = BSG_SUB_PROTOCOL_SCSI_CMD, + .request_len = cdb_len, + .request = (uintptr_t)cdb, + .response = (uintptr_t)sense, + .max_response_len = sizeof(sense), + }; + + if (out) { + io.dout_xfer_len = len; + io.dout_xferp = (uintptr_t)buf; + } else { + io.din_xfer_len = len; + io.din_xferp = (uintptr_t)buf; + } + for (int i = 0; i < 2; i++) { + memset(sense, 0, sizeof(sense)); + if (ioctl(rpmb_fd, SG_IO, &io)) + break; + if (!io.info) + return 0; + if ((sense[2] & 0xf) != 6) + break; + } + LOG("rpmb: SCSI 0x%02x failed (info 0x%x, sense key %u)\n", cdb[0], + io.info, sense[2] & 0xf); + return -1; +} + +static int rpmb_sec(int in, void *buf, uint32_t len) +{ + uint8_t cdb[12] = { + in ? 0xa2 : 0xb5, 0xec, 0x00, 0x01, 0, 0, + len >> 24, len >> 16, len >> 8, len, 0, 0, + }; + + return rpmb_scsi(cdb, sizeof(cdb), buf, len, !in); +} + +static int rpmb_serve(uint8_t *b) +{ + static uint8_t frames[32 * RPMB_BLK]; + static const uint8_t result_req[RPMB_BLK] = { [511] = 0x05 }; + struct rpmb_rw_req rq; + struct rpmb_rw_res res = { .res_buff_offset = sizeof(res) }; + uint8_t *resp = b + sizeof(res); + uint32_t cmd = *(uint32_t *)b, per, total; + int st = 0; + + switch (cmd) { + case 0x101: { /* init */ + struct rpmb_init_res r = { + .cmd_id = cmd, + .version = *(uint32_t *)(b + 4) >= 2 ? 2 : 1, + .num_sectors = 8192, + .rel_wr_count = 1, + .dev_type = 9, /* UFS */ + }; + uint8_t sense_cdb[6] = { 0x03, 0, 0, 0, 18, 0 }, sense[18]; + + r.status = rpmb_open(); + if (!r.status) /* clears a pending UNIT ATTENTION */ + rpmb_scsi(sense_cdb, sizeof(sense_cdb), sense, + sizeof(sense), 0); + memcpy(b, &r, r.version == 2 ? sizeof(r) : 20); + return 0; + } + case 0x102: /* read: one request frame out, the result in */ + memcpy(&rq, b, sizeof(rq)); + total = rq.num_sectors * RPMB_BLK; + st = rpmb_open() || total > 32 * RPMB_BLK || + rpmb_sec(0, b + rq.req_buff_offset, RPMB_BLK) || + rpmb_sec(1, resp, total) ? -1 : 0; + res.res_buff_len = st ? 0 : total; + break; + case 0x103: /* write: frames out, then read the result register */ + memcpy(&rq, b, sizeof(rq)); + per = rq.rel_wr_count ? rq.rel_wr_count : 1; + total = rq.num_sectors * RPMB_BLK; + if (!total || total > sizeof(frames) || rpmb_open()) { + st = -1; + break; + } + memcpy(frames, b + rq.req_buff_offset, total); + for (uint32_t i = 0; !st && i < rq.num_sectors / per; i++) + st = rpmb_sec(0, frames + i * per * RPMB_BLK, + per * RPMB_BLK) || + rpmb_sec(0, (void *)result_req, RPMB_BLK) || + rpmb_sec(1, resp, RPMB_BLK) ? -1 : 0; + res.res_buff_len = st ? 0 : RPMB_BLK; + break; + case 0x104: /* partitions: none provisioned */ + *(int32_t *)(b + 4) = -1; + *(uint32_t *)(b + 8) = 0; + *(uint32_t *)(b + 12) = 16; + return 0; + default: + LOG("rpmb: unknown command 0x%x\n", cmd); + return -1; + } + res.cmd_id = rq.cmd_id; + res.version = rq.version; + res.status = st; + memcpy(b, &res, sizeof(res)); + return 0; +} + +static struct listener { + uint32_t id, size; + int (*serve)(uint8_t *buf); + struct shm buf; +} listeners[] = { + { .id = 10, .size = 0x5000, .serve = fs_serve }, + { .id = 28672, .size = 0x7e000, .serve = gpfs_serve }, + { .id = 8192, .size = 0x6000, .serve = rpmb_serve }, /* page aligned */ +}; + +static int supp_fd = -1; + +/* Register the listeners; then serve_listeners() answers their requests. */ +static int register_listeners(void) +{ + supp_fd = tee_open("teepriv"); + if (supp_fd < 0) + return -1; + for (size_t i = 0; i < sizeof(listeners) / sizeof(*listeners); i++) { + struct listener *l = &listeners[i]; + struct { + struct tee_ioctl_open_session_arg arg; + struct tee_ioctl_param params[2]; + } s = {}; + struct tee_ioctl_buf_data bd = { (uintptr_t)&s, sizeof(s) }; + + if (shm_alloc(supp_fd, l->size, &l->buf)) + return -1; + s.arg.num_params = 2; + s.params[0].attr = TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INPUT; + s.params[0].a = l->id; + s.params[1].attr = TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT; + s.params[1].b = l->size; + s.params[1].c = l->buf.id; + if (ioctl(supp_fd, TEE_IOC_OPEN_SESSION, &bd)) { + LOG("register listener %u: %s\n", l->id, + strerror(errno)); + return -1; + } + } + return 0; +} + +static void *serve_listeners(void *unused) +{ + (void)unused; + for (;;) { + struct { + struct tee_iocl_supp_recv_arg arg; + struct tee_ioctl_param params[2]; + } recv = { .arg.num_params = 2 }; + struct { + struct tee_iocl_supp_send_arg arg; + struct tee_ioctl_param params[1]; + } send = { .arg.num_params = 1 }; + struct tee_ioctl_buf_data bd = { (uintptr_t)&recv, sizeof(recv) }; + int ok = 0; + + if (ioctl(supp_fd, TEE_IOC_SUPPL_RECV, &bd)) { + LOG("SUPPL_RECV: %s\n", strerror(errno)); + exit(1); + } + for (size_t i = 0; i < sizeof(listeners) / sizeof(*listeners); i++) + if (listeners[i].id == recv.arg.func) + ok = !listeners[i].serve(listeners[i].buf.va); + if (!ok) + LOG("request for listener %u refused\n", recv.arg.func); + + /* Echo the request id, or the answer is taken for a stale one */ + send.arg.ret = !ok; + send.params[0].attr = TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_OUTPUT; + send.params[0].a = recv.params[0].a; + bd = (struct tee_ioctl_buf_data){ (uintptr_t)&send, sizeof(send) }; + if (ioctl(supp_fd, TEE_IOC_SUPPL_SEND, &bd)) { + LOG("SUPPL_SEND: %s\n", strerror(errno)); + exit(1); + } + } + return NULL; +} + +/* + * The app loader fetches the .mdt and its segments with request_firmware(), + * whose search path NixOS sets at boot, so point it at the apps meanwhile. + * Their sessions stay open, keeping them loaded, while this runs. + */ +static int load_apps(const char *dir, char **apps, int n) +{ + const char *param = "/sys/module/firmware_class/parameters/path"; + char old[256] = ""; + int fd = open(param, O_RDWR | O_CLOEXEC), load_fd = tee_open("teepriv"); + int ok = 1; + ssize_t len; + + if (fd < 0 || load_fd < 0) + return -1; + len = read(fd, old, sizeof(old) - 1); + old[len > 0 ? len : 0] = '\0'; + old[strcspn(old, "\n")] = '\0'; + if (pwrite(fd, dir, strlen(dir), 0) < 0) + LOG("set firmware path: %s\n", strerror(errno)); + for (int i = 0; i < n; i++) + if (tee_session(load_fd, apps[i]) < 0) + ok = 0; + /* An empty write is refused, but a lone newline clears it */ + if (pwrite(fd, *old ? old : "\n", *old ? strlen(old) : 1, 0) < 0) + LOG("restore firmware path: %s\n", strerror(errno)); + close(fd); + return ok ? 0 : -1; +} + +int main(int argc, char **argv) +{ + setvbuf(stderr, NULL, _IOLBF, 0); + if (argc < 3) { + LOG("usage: %s [app...]\n", argv[0]); + return 2; + } + fs_root = argv[1]; + mkdir(fs_root, 0700); + + /* The listeners first: loading an app can already call into them */ + if (register_listeners()) + return 1; + { + pthread_t thread; + + if (pthread_create(&thread, NULL, serve_listeners, NULL) || + load_apps(argv[2], argv + 3, argc - 3)) + return 1; + LOG("ready\n"); + pthread_join(thread, NULL); + } + return 1; +} diff --git a/qseecom-supplicant.service b/qseecom-supplicant.service new file mode 100644 index 0000000..608609f --- /dev/null +++ b/qseecom-supplicant.service @@ -0,0 +1,17 @@ +[Unit] +Description=Listeners for QSEE trusted apps +# Its devices come with modules loaded as they're found, so it keeps trying +# until they're all there +StartLimitIntervalSec=0 + +[Service] +# Apps to load: the names of their .mdt files in the firmware directory +Environment=QSEECOM_APPS= +ExecStart=/usr/local/bin/qseecom-supplicant /var/lib/qseecom /lib/firmware $QSEECOM_APPS +StateDirectory=qseecom +StateDirectoryMode=0700 +Restart=on-failure +RestartSec=5 + +[Install] +WantedBy=multi-user.target