# Code signing a QPKG

App Center checks a package's code signature when it installs it. A package without a valid one installs only on
a NAS whose owner allows apps without a valid digital signature. **Never advise turning that setting on.** Sign the
package, or say plainly that it is unsigned and what follows from that.

## The certificate

Signing needs a code-signing certificate, bought from a certificate authority or issued to you by QNAP. It comes
in one of two forms:

- **as files**: the certificate, its private key and the chain (case 1);
- **with the key on a USB token or an HSM**: the private key never leaves the device, and software reaches it
  through PKCS#11 (case 2).

Two checks read the signature, each against its own list of certificate authorities:

- **QDK's `qbuild`**, right after it signs and with `qbuild --verify-code-signing`, checks against QNAP's own
  certificate authorities (files QDK ships), then against `/etc/ssl/certs` of the computer or environment it runs
  in. It says which: "verification successful (QNAP-issued certificate)" or "(non QNAP-issued certificate)".
- **App Center on the NAS**, when it installs the package, checks a QNAP-issued certificate against QNAP's
  certificate authorities and any other against the ones the NAS trusts in `/etc/ssl/certs`. Measured on QTS 6.1:
  a package signed with a test chain whose root was not in the NAS's `/etc/ssl/certs` was not installed (`qpkg_cli
  -m` ended with `st_code` 5, and `/mnt/HDA_ROOT/.logs/codesigning/cs_qdaemon_v2.log` said `cert_status=-1`); the
  same package installed while its root was there.

So a bought certificate works when the root of its chain is among the NAS's trusted roots. QTS 6.1 and QuTS hero
6.1 carry the common public roots (DigiCert Trusted Root G4 among them); check yours on the NAS with
`ls /etc/ssl/certs | grep -i <the root's name>`. A root you copy into `/etc/ssl/certs` yourself is gone at the next
restart (the root file system is a RAM disk) and exists only on that NAS: it is no way to publish a package.

## The three cases

| Case | What you have | With QDK's `qbuild` on your own computer | What happens in Bucket & Code Server IDE |
|---|---|---|---|
| 1 | the certificate as files: `certificate`, `private_key`, optionally `ca_certs` (the chain) | supported: `qbuild` signs the package | supported: `bvs qbuild` signs the package, and the package repository takes it |
| 2 | the key on a USB token or an HSM, reached through PKCS#11 | supported by QDK: `certificate_hsm` beside `qpkg.cfg` and the key's place in variables (below); tried with a software token | from 1.0.0-73 (x86_64): `bvs qbuild` and a project's Build sign with a token plugged into the NAS (below); 1.0.0-72 and earlier refuse `certificate_hsm` |
| 3 | no certificate | the package is built unsigned | the package is built unsigned. The repository refuses it unless an admin allows unsigned packages |

App Center on another NAS installs an unsigned package only if its owner allows unsigned apps.

`bvs qbuild` names the case on its first line, before QDK's `qbuild` runs, for example
`bvs: code signing, case 1 (a certificate as files): …`. The App Builder's **Export as QPKG** is always case 3, and
its job log says so.

## Case 1: a certificate as files

QDK 2.5.0's `qbuild` signs when files named `certificate` and `private_key` lie in the folder it builds (next to
`qpkg.cfg`), with `ca_certs` as the chain when present. It signs with `openssl cms`, then reads the signature back
with `/usr/bin/hexdump` and deletes the package when either step fails. So the computer or environment where it
runs needs `openssl` and `hexdump` (Debian and Ubuntu package `bsdextrautils`).

Keep the three files out of git: add them to `.gitignore`. Bucket & Code Server IDE's QPKG template lists them
already; its repositories live in Forgejo, where others may read them. Check a package's signature with QDK in a folder that has a `qpkg.cfg` (QDK's `qbuild` does not start
without one): `qbuild --verify-code-signing <file>.qpkg`.

### On your own computer

`apt-get install ./qdk_2.5.0_amd64.deb` brings `openssl` and `bsdextrautils` with QDK ([qpkg.md](qpkg.md)); with
another install, add them yourself.

```sh
cp /path/outside/git/{certificate,private_key,ca_certs} .   # next to qpkg.cfg
qbuild
rm -f certificate private_key ca_certs
qbuild --verify-code-signing build/<file>.qpkg
```

Packages signed this way with QDK 2.5.0 on Ubuntu 24.04 install as signed on QTS 6.1 and QuTS hero 6.1 units.

### In Bucket & Code Server IDE

`bvs qbuild` checks for `openssl` and `hexdump` in the environment and names the command that installs them:

```sh
bvs env run ubuntu2404-builder -- apt-get install -y openssl bsdextrautils
cp /path/outside/git/{certificate,private_key,ca_certs} .   # next to qpkg.cfg
bvs qbuild
rm -f certificate private_key ca_certs
```

- A signed `bvs qbuild` has been run in a Debian 12 environment on a build computer, and QDK's own check of the
  result read "Code signing digital signature verification successful (QNAP-issued certificate)". A signed
  `bvs qbuild` has not yet run on a NAS.
- `bvs qbuild` refuses a folder with only one of `certificate` and `private_key` (QDK's `qbuild` would warn and
  build an unsigned package) and one where either file is empty.
- In CI, keep them as the repository's Actions secrets `QPKG_CERTIFICATE`, `QPKG_PRIVATE_KEY` and `QPKG_CA_CERTS`
  (the chain, optional), each the file's PEM text or its base64. The workflows of the QPKG template and of the
  examples that publish a package write them for the build step only (D370): with umask 077, beside `qpkg.cfg` for
  `bvs qbuild` (a packer gets a folder of the step's own in `QPKG_CERT_DIR`), removed by an `EXIT` trap. Only one of
  the first two set, or a value that is no PEM file, stops the step with an `::error::` line naming the secret;
  neither set builds unsigned (case 3). The QPKG template's version, shortened:

```yaml
      - run: |
          sign_dir=.
          trap 'rm -f certificate private_key ca_certs' EXIT
          case "${QPKG_CERTIFICATE:+c}${QPKG_PRIVATE_KEY:+k}" in
            c | k)
              echo "::error::set both QPKG_CERTIFICATE and QPKG_PRIVATE_KEY, or neither to build unsigned"
              exit 1
              ;;
            ck)
              mask=$(umask)
              umask 077
              for s in certificate:QPKG_CERTIFICATE private_key:QPKG_PRIVATE_KEY ca_certs:QPKG_CA_CERTS; do
                f=$sign_dir/${s%%:*} n=${s#*:}
                [ -n "${!n}" ] || continue
                case ${!n} in
                  *-----BEGIN*) printf '%s\n' "${!n}" ;;
                  *) printf '%s' "${!n}" | base64 -d ;;
                esac >"$f" 2>/dev/null || :
                grep -q -e '-----BEGIN' "$f" || {
                  echo "::error::the secret $n is neither a PEM file's text nor its base64"
                  exit 1
                }
              done
              umask "$mask"
              ;;
          esac
          bvs qbuild
        env:
          QPKG_CERTIFICATE: ${{ secrets.QPKG_CERTIFICATE }}
          QPKG_PRIVATE_KEY: ${{ secrets.QPKG_PRIVATE_KEY }}
          QPKG_CA_CERTS: ${{ secrets.QPKG_CA_CERTS }}
```

## Case 2: a key on a USB token or an HSM

QDK's `qbuild` (its public source, `shared/bin/qbuild` in github.com/qnap-dev/QDK) signs with a key on a token
when a file named `certificate_hsm` lies beside `qpkg.cfg` (and neither `certificate` nor `private_key` does):

- `certificate_hsm` is the signing certificate in PEM, with no file extension; `ca_certs_hsm` beside it, optional,
  holds the intermediate certificates;
- `HSM_SLOT` is the token's PKCS#11 slot id in decimal (0 when unset), and `HSM_KEY_ID` (the key's `CKA_ID` in hex)
  or else `HSM_KEY_LABEL` names the key; without either `qbuild` stops;
- `qbuild` then runs `openssl cms -engine pkcs11 -keyform engine -sign … -signer certificate_hsm -inkey
  <HSM_SLOT>:<HSM_KEY_ID>` (or `slot_<HSM_SLOT>-label_<HSM_KEY_LABEL>`), with `-certfile ca_certs_hsm` when that
  file is there. The token makes the signature; the key never leaves it.

To sign a package that is already built, `qbuild --add-code-signing <file>.qpkg --code-signing-cfg <cfg>` does the
same in place: the cfg file is read as shell and sets `QNAP_CERT_HSM` (the certificate file) and optionally
`CA_CERTS_HSM` (the chain); `HSM_SLOT` and the key's id or label come from the environment, and openssl's messages
go to `qnap_hsm.log` in the current folder.

### On your own computer

1. Install `openssl`, libp11's OpenSSL engine (Debian and Ubuntu: `libengine-pkcs11-openssl`), a PKCS#11 module for
   the token, and for a USB token `pcscd` with the CCID reader driver. The module is the token maker's own, or
   OpenSC's `opensc-pkcs11.so`: OpenSC's idprime driver has handled SafeNet eToken 5110 tokens since OpenSC 0.24.0
   (Ubuntu 24.04 ships 0.25; Debian 12's 0.23 is older).
2. Look at the token without a PIN: `pkcs11-tool --module <module> --list-slots` prints each slot's position and,
   in brackets, its id in hex (`Slot 0 (0x739a27d0)`): `HSM_SLOT` takes that id in decimal (1939482576 here), not
   the position. `pkcs11-tool --module <module> --slot <id> --list-objects` lists the certificates and public keys
   with their `ID:` (the `HSM_KEY_ID`) and labels.
3. Write the certificate of the key as `certificate_hsm`:
   `pkcs11-tool --module <module> --slot <id> --read-object --type cert --id <key id> --output-file cert.der`,
   then `openssl x509 -inform DER -in cert.der -out certificate_hsm`. Put the intermediate certificates into
   `ca_certs_hsm` the same way.
4. Give the engine its module in an `openssl.cnf` of its own, named by `OPENSSL_CONF` for the build only:

   ```ini
   openssl_conf = openssl_init

   [openssl_init]
   engines = engine_section

   [engine_section]
   pkcs11 = pkcs11_section

   [pkcs11_section]
   engine_id = pkcs11
   dynamic_path = /usr/lib/x86_64-linux-gnu/engines-3/pkcs11.so
   MODULE_PATH = /usr/lib/x86_64-linux-gnu/opensc-pkcs11.so
   PIN = $ENV::HSM_PIN
   ```

   OpenSSL reads the PIN from the variable `HSM_PIN` when it loads the file, so the file never holds it. Without
   the `PIN` line the engine asks for the PIN on the terminal at each signature. With the line, an unset `HSM_PIN`
   makes OpenSSL refuse the whole file.
5. Build: `HSM_SLOT=<id> HSM_KEY_ID=<key id> HSM_PIN=<pin> OPENSSL_CONF=$PWD/pkcs11.cnf qbuild`, and look for
   "Creating code signing digital signature using HSM..." and "verification successful".

- `qbuild` sends openssl's errors to `/dev/null`: a wrong PIN, a wrong slot or a missing engine shows only as
  "Error reading SMIME Content Info" and "verification failed", and the package it leaves in `build/` has no valid
  signature. Delete it and build again.
- A token locks after a few wrong PINs. `pkcs11-tool --list-slots` shows the token's flags: "user PIN count low"
  (a wrong PIN was typed), "final user PIN try" and "user PIN locked". Check them before a build, and never put
  the PIN into a script that retries.
- Tried with a software token: on Ubuntu 24.04 with QDK 2.5.0, a SoftHSM 2 token holding a test key signed through
  this engine, in the folder and with `--add-code-signing`, and both read "verification successful (non
  QNAP-issued certificate)" once the test root was in `/etc/ssl/certs`. No USB token was used for these
  measurements.

### In Bucket & Code Server IDE

From 1.0.0-73 the x86_64 package carries its own token tools in `/usr/bin/bucketvs/token`: pcscd with the CCID reader
driver, OpenSC 0.27.1 (its idprime driver covers the SafeNet eToken 5110), libp11's engine, SoftHSM 2 and the openssl
they belong to. The token is plugged into the NAS; the key never leaves it.

- **`bvs token list`** (root, in the editor's terminal or over SSH) starts pcscd for the look and stops it after, and
  prints every reader and token with its slot id (`HSM_SLOT`), the token's flags, and the certificates and keys it
  shows without a PIN (their ids are `HSM_KEY_ID`). `bvs token run pkcs11-tool …` runs OpenSC's tool the same way.
- **`bvs qbuild`** in a folder with `certificate_hsm` signs through the token: set `HSM_KEY_ID` (or `HSM_KEY_LABEL`),
  `HSM_SLOT` when the slot id is not 0, and `HSM_PIN`; without `HSM_PIN` in a terminal, the engine asks for the PIN.
  Before it builds, it looks at the token without the PIN: the slot holds the token, the token's PIN is not locked or
  at its final try, and `certificate_hsm` is the token's certificate for that key. It uses the PIN once. When
  `qbuild` fails, it deletes the package it wrote. The environment needs glibc 2.34 or newer (2.36 for SoftHSM):
  `ubuntu2404-builder` and `debian12-builder` have it.
- **A project's Build** signs with a token when its Settings card's Code signing is set to the USB token: the
  panel reads the certificate and its chain from the token (or takes them pasted) and keeps a copy for the Build,
  finds the token by its serial number, and keeps the PIN in bvsd's memory only, until Bucket & Code restarts.
- **In CI**, keep the PIN as the repository's Actions secret and give the job the key's place:

```yaml
      - run: bvs qbuild
        env:
          HSM_SLOT: "0"
          HSM_KEY_ID: "7b0f360b775f76c94a12ca48445aa2d2a875701c"
          HSM_PIN: ${{ secrets.QPKG_TOKEN_PIN }}
```

  `certificate_hsm` and `ca_certs_hsm` hold only certificates, so they may be committed.
- Tried with a SoftHSM 2 token through this same path on QTS 6.1 and QuTS hero 6.1 units, from `bvs qbuild` and from
  a project's Build to an App Center install. A USB token was not part of these tests.
- 1.0.0-72 and earlier refuse a folder with `certificate_hsm`: there, build unsigned and sign on a computer that
  holds the token with `qbuild --add-code-signing` as above.

## Case 3: no certificate

- The package builds, and on the author's own NAS it can be installed for a test. On a QTS 6.1 unit, `qpkg_cli -m`
  of an unsigned package exited 0 and installed nothing, while `sh <file>.qpkg` in a shared folder installed and
  started it.
- The package repository of Bucket & Code Server IDE refuses it ("carries no code signature") unless an admin turns
  on `repo.accept_unsigned` on the Packages page, an explicit, labelled choice. Then every NAS that added the
  repository can install it as root, and App Center there installs it only if that NAS's owner allows apps without
  a valid digital signature. Do not recommend either setting.
- The App Builder's exports are always unsigned: the NAS holds no code-signing certificate.

## What does not count as a code signature

- `qbuild --sign` adds a GnuPG signature in another area of the package (QDK's area 1). App Center and the package
  repository read the code-signing block (area 254); a package with only a GnuPG signature is unsigned to them.
- `QNAP_CODE_SIGNING=1` in `qpkg.cfg` makes `qbuild` ask QNAP's own signing server. QDK's template says this can be
  done only inside QNAP; `bvs qbuild` names it when a `qpkg.cfg` sets it.

## What the package repository reads

The repository takes a package as signed when its code-signing block is a PKCS#7 SignedData with a certificate and
a signer, and lists its signature in `repo.xml` as the last 32 base64 characters of that block. It does not check
the signature or its chain; App Center does that when it installs the package (The certificate, above).

## Sources

Signing on your own computer was measured while building QPKGs with QDK 2.5.0 on Ubuntu 24.04 for QTS 6.1 and QuTS
hero 6.1 units, and with a SoftHSM 2 software token for case 2; App Center's check of a non-QNAP chain was measured
on a QTS 6.1 unit. QDK's `qbuild` script (github.com/qnap-dev/QDK, `shared/bin/qbuild`; `usr/share/QDK/bin/qbuild`
in QDK 2.5.0's Debian package: `add_qpkg_signature`, `add_code_signing`, `verify_code_signing_offline`, the help
text) and its `qpkg.cfg` template, read for this page; OpenSC's release notes
([NEWS](https://github.com/OpenSC/OpenSC/blob/master/NEWS): 0.24.0 added the SafeNet eToken 5110), libp11's
[README](https://github.com/OpenSC/libp11) (the engine's `openssl.cnf` section) and engine source
(`src/eng_front.c`: the `PIN` control) and OpenSSL's [config](https://docs.openssl.org/3.0/man5/config/) manual
(`$ENV::name`); Bucket & Code Server IDE's user guide (`bvs guide`, "Building a QPKG with bvs qbuild" and "Package
repository").
