Zum Inhalt springen

Die Entwickler-Doku gibt es nur auf Englisch.

Hardening your integration

Noctix keeps the authority on the server: the client only checks short-lived, signed proofs. No client-side measure replaces that. The measures below raise the cost of bypassing the local check. Each is honest about its limits, especially since the SDKs are open source. Combine them.

See the internal concept in ../hardening.md (German) for the full attacker model.

Bind value to the license (M2)

A patcher who only has to flip one if (licensed) { ... } branch to true wins cheaply. Take the branch away: make a real asset open only with a key that the server hands out for a valid, device-bound license. Flipping the branch then gains nothing, because the key is still missing.

Noctix already encrypts release files and assets (protocol sections 6.12 and 6.14). The signing service wraps each asset's content key with HPKE for a key your device makes for the one download, so only this device, under a valid license, receives a key that opens the asset. The SDK unwraps it for you; you never touch HPKE. request_asset_download keeps that key inside the download handle, and a convenience call opens a sealed asset you already hold with it.

When to use it

  • Ship the asset encrypted inside your app, or serve it yourself, and decrypt it at runtime only after request_asset_download returns a key.
  • Best for content that is valuable on its own and that you can rotate often or encrypt per device: level packs, models, premium media, paid modules.
  • Not a fit for logic you cannot move off the binary, or for a one-off asset that never changes — see the limit below.

Rust

use sdk_core::asset;

// A valid, device-bound license answer carries the key; without one there is
// nothing to open.
let download = client
    .request_asset_download("level-pack-3")?
    .ok_or("the license may not fetch this asset")?;

// `sealed` is the encrypted asset your app already holds (bundled or fetched
// earlier). The key inside `download` opens it; a wrong or missing key fails.
let plain = asset::open_sealed_asset_bytes(&download, sealed_bytes)?;

// Or stream a large asset from one file to another:
let mut input = std::io::BufReader::new(std::fs::File::open("level-pack-3.sealed")?);
let mut output = std::fs::File::create("level-pack-3")?;
asset::open_sealed_asset(&download, &mut input, &mut output)?;

Python

download = client.request_asset_download("level-pack-3")
if download is None:
    raise RuntimeError("the license may not fetch this asset")
with download:
    # Decrypts the sealed file the app already holds with the device-bound key.
    download.open_sealed("level-pack-3.sealed", "level-pack-3")

C

struct lsdk_asset_download *download = NULL;
struct lsdk_error *err =
    lsdk_client_request_asset_download(client, "level-pack-3", &download);
/* handle err; download stays NULL if the license may not fetch the asset */

err = lsdk_asset_download_open_sealed(download, "level-pack-3.sealed", "level-pack-3");
/* config_invalid: not encrypted; token_mismatch: wrong key or changed data */
lsdk_asset_download_free(download);

How it fails

Opening is designed to fail closed, never to fall back to the plaintext:

  • no key (the asset is not encrypted, or there is no valid device-bound answer): error code config_invalid;
  • a wrong key, or sealed data that was changed or cut off: error code token_mismatch;
  • a file that cannot be read or written: error code storage_failed.

The honest limit

Once an asset is decrypted on the device, it can be copied. This measure does not stop that; it stops a patched binary from reaching the plaintext at all without a real license. It pays off most when the asset is worthless once stale — rotate it often, or encrypt it per device — so a leaked copy ages out instead of unlocking the product forever. It does nothing for a product whose value is purely local logic; for that, keep value on the server (M1).

Spread your checks (M4)

A single license check is a single place to patch. An attacker who finds one if licensed { ... } and forces it to true unlocks the whole program. The guard API lets you place many small, independent checks throughout your program instead, so an attacker has to find and remove every one.

Each check is cheap and local: it reads the stored, signed token and asks whether the license, or a named entitlement, is in force right now. No network, no secret on the device. Put the checks where the gated features actually run, not only at startup, and word them differently so they are not one search away from each other.

The guard API

Create one Guard per client and call it from many places. It exposes the current, locally verified token state:

  • a plain "is the license usable now?" check (fresh, or in grace within the offline tolerance), and
  • entitlement checks: a flag is set, a limit is at least some value, a variant equals some value.

On top of the local checks the guard keeps a timer for an occasional online re-check with a signed challenge. The re-check renews the token through the server (validate), so the server's fresh signature confirms the license. A purely local patch cannot forge that signature. Do the local checks often and the online re-check rarely, so the program keeps working offline within the plan's tolerance.

Rust:

use std::sync::Arc;
use sdk_core::guard::Guard;

let guard = Guard::new(Arc::clone(&client));

// At the point where a gated feature runs:
match guard.require_flag("pro") {
    Ok(status) => run_pro_feature(&status),
    Err(e) => return Err(format!("feature locked: {}", e.code())),
}

// Elsewhere, on a timer, re-check online now and then:
if let Some(result) = guard.recheck_if_due(now) {
    let _ = result; // server_unreachable keeps the token usable offline
}

Python:

guard = client.guard(recheck_after=3600)

# A local checkpoint where a gated feature runs:
try:
    status = guard.require_flag("pro")
except LicenseError as e:
    raise RuntimeError(f"feature locked: {e.code}")

# Occasionally, re-check online with a signed challenge:
if guard.recheck_due():
    try:
        guard.recheck()
    except LicenseError:
        pass  # offline: the stored token stays usable within tolerance

The C interface (lsdk_guard_new, lsdk_guard_licensed, lsdk_guard_recheck, lsdk_guard_recheck_due, lsdk_guard_last_online) carries the same calls; the C++, C#, Java, Kotlin and Swift wrappers pass them through.

Couple each check to real value (M2)

Spreading checks only multiplies the work of patching; a patient attacker still finds them all, and the SDK source is public. The measure is worth most when each check gates something the attacker cannot fake. Prefer to gate a feature on a value that only a valid license yields: an asset decrypted with a key bound to the token (M2), a server computation, or an update. Then removing the check does not help, because the value is still missing. A bare guard.require_flag(...) that only toggles a UI element is the weakest form; use it together with token-bound value.

Report tampering (M5)

A check that blocks is one an attacker can patch out. A check whose failure, or suspicious absence, is reported to the server (M5) turns a bypass into a signal the server can act on. Combine the local checks here with the tamper signals of M5 so that removing a checkpoint is itself visible.

Limits

  • This raises cost; it is not a proof. Against a fully rewritten client only the missing value on the device and attestation help.
  • The checks live in open-source SDK code, so they are removable; their value is in their number, in the value they gate (M2), and in the server's view (M5), not in secrecy.
  • A check that blocks can also hit an honest customer (a flaky disk, a clock skew). Keep the offline tolerance generous and fail toward the local token state, not toward a network call.

Let the server know about tampering (M5)

A local check can be bypassed, but the call to the server cannot be made to lie about everything at once: a copied token alone will not produce a signed, device-bound request. So let the SDK report what it observed about its own run and let the server decide. The SDK sends the findings as a signed integrity field on activate and heartbeat (protocol section 6.20); the server turns each one into a detection signal that flags the license, or suspends it when you list the signal under the product's auto_suspend_signals. Even when the attacker skips the local check, the server sees the anomaly — and the absence of expected signals stands out too.

The built-in detectors are a debugger check (Linux and Android) and, once you set the running build hash, whether it deviates from what you shipped. The findings the server understands are debugger, hooking, root_jailbreak, emulator and build_mismatch; you can report the others from your own platform-specific checks.

When to use it

  • Turn it on whenever you ship a real binary to end users. It costs one call setting and pairs well with approved builds (build_check) and attestation.
  • Decide per product what a finding does: leave it at flag (the default) to watch, or add the signal to auto_suspend_signals to suspend on it.
  • Pair it with attestation (protocol section 6.7) where you can: an attacker cannot forge that, so it anchors the signals the attacker could forge.

Rust

// Report the build hash so build_mismatch can be detected, and turn on the
// built-in integrity checks. Only findings that are present are ever sent.
let client = Client::new(config)?
    .with_build(sdk_core::current_build_digest()?)
    .with_integrity_checks()
    // Optional: honor a server "terminate" directive (see below).
    .on_terminate(|message| {
        eprintln!("{message}");
        std::process::exit(70);
    });

C

lsdk_config_set_integrity_checks(config, true);

/* Optional: honor a server "terminate" directive. */
struct lsdk_terminate_handler handler = {0};
handler.user_data = NULL;
handler.notify = on_terminate; /* void on_terminate(void*, const char* message) */
lsdk_config_set_terminate_handler(config, handler);

The opt-in that ends the app

Reporting is the measure; ending the app is an extra, opt-in step that is never silent and never forced. Set the product's tamper_response to terminate (the default is report, which only raises the signals; off ignores integrity entirely). On a reported finding the server then answers with a signal directive carrying a message, and the SDK calls the handler you set with on_terminate so your app can show the message and exit. Without a handler the app keeps running: honoring the directive is always the app's own choice, because the server cannot enforce it on the client.

The honest limit

The findings are the device's word. An attacker who controls the client can withhold or forge them, so treat them as a signal, never as proof — the measure that does not depend on the client is the signal on the server (flag or suspend), together with attestation the attacker cannot forge. The built-in debugger check covers Linux and Android; add your own checks for other platforms and for hooking, root_jailbreak and emulator, and report them through the same field.

Check your own binary (M6)

This is about your own finished binary — the program you ship with the SDK compiled in — not the SDK source, which is open and buildable with every check removed. A runtime self-check asks: has my own code been patched in memory or on disk since I built it? A positive answer makes an in-memory patch cost more.

Noctix ships no self-integrity check inside the SDK. In an open-source SDK such a check is one the attacker reads and deletes in the same pass as the license branch, so it buys nothing and only slows honest builds. It pays off only in the binary you build and statically link, where the attacker has to find and remove it in your specific artifact. So M6 is guidance for your pipeline, not an SDK call — the same stance as build hardening (M8).

The server already carries the part that does not depend on the client: set the running build hash with with_build and the SDK reports a build_mismatch finding when the binary deviates from what you shipped (M5, protocol section 6.20). Treat the measures below as the local complement to that server signal, never as a replacement for it.

What to do in your binary

  • Let the platform verify the signature first. This is the strongest and cheapest layer because the OS enforces it, not your code.
    • Apple (macOS, iOS): sign and notarize, enable the hardened runtime, and ship with library validation so only your signed code loads. The App Store and Gatekeeper reject a tampered bundle before it runs.
    • Windows: Authenticode-sign the executable; optionally check your own signature at startup with WinVerifyTrust.
    • Android: verify the installer and your signing certificate through PackageManager (signature scheme v2/v3). Do not hash the whole APK — Google Play re-signs your upload, so compare the signing certificate identity, not the file bytes.
  • Add a runtime self-hash only in your own code. Hash your code section (or a known read-only region) at build time, embed the expected digest, and recompute it at startup. Keep the expected value and the comparison out of one obvious function (see M8: strip symbols, LTO, static linking).
  • On a mismatch, report — do not crash silently. Feed the finding through the same integrity channel as the built-in detectors (M5): report it so the server flags or suspends the license, and, if you opted into terminate, let the server-driven handler end the app with a message. A silent abort() just tells the attacker exactly which byte to flip next.

The pitfalls that bite

  • Updates change the binary. A self-hash is tied to one exact build, so it must travel with each release. Driving it from the same build hash you report with with_build keeps it in step and reuses the build_mismatch signal instead of inventing a second source of truth.
  • Store re-signing and fat binaries. Re-signing, universal binaries and per-architecture slices all change file bytes without tampering. Check the signature identity, or hash only your own code section, never the whole file.
  • The check is in the binary too. Whoever can patch the license branch can patch the self-check. That is why the finding goes to the server: a removed check shows up as the expected signal going missing, which the server can also notice.

The honest limit

In the open-source SDK this protection is trivially removed, which is why it is not there. Even in your own binary a determined attacker strips it; it only raises the cost for the casual patcher. It is worth doing only alongside the measures that do not sit on the client — the server signal (flag or suspend) and attestation (protocol section 6.7), which the attacker cannot forge. Keep value on the server (M1); a self-check that guards a purely local if is still a one-line patch once found.

Detect debuggers and instrumentation (M7)

A debugger or an instrumentation framework like Frida attached to your running app is a strong sign someone is studying or rewriting it. The SDK can notice some of this and report it through the integrity channel (M5) — it never blocks or ends the app itself on such a finding. Reporting is the whole behavior; ending the app is your opt-in through tamper_response (see M5), never forced and never silent. Blocking inside an open-source SDK would be useless against an attacker, who deletes the check, and harmful to honest users, who do not.

The built-in detectors, all behind with_integrity_checks and off by default:

  • debugger — Linux and Android read TracerPid in /proc/self/status; Windows calls IsDebuggerPresent and CheckRemoteDebuggerPresent. (M5 already ships the Linux and Android check; M7 adds Windows.)
  • hooking — Linux and Android look for a Frida agent or gadget mapped into the process (/proc/self/maps) and its gum-js-loop thread. No socket is opened and no network state is read.

A macOS and iOS debugger check (sysctl with P_TRACED) and hooking detection on other platforms are not built in yet; add your own and report debugger or hooking through the same field.

When to use it

  • Turn it on (with_integrity_checks) when you ship a real binary to end users, together with the build-hash report (with_build) and attestation.
  • Leave the response at the default (flag) to watch, or add debugger or hooking to the product's auto_suspend_signals to suspend on them — but weigh the false positives below before you suspend.
  • Decide separately, per product, whether a finding also ends the app, through tamper_response: terminate. It is the same opt-in, vendor-handler path as every other finding.

The false positives are real

An honest user debugging your app, a profiler, an accessibility tool that attaches to processes, or a CI or sandbox environment can all set these off. That is exactly why the SDK only reports and never blocks, why the detectors are off by default, and why you should prefer flagging over suspending unless attestation backs the signal. Document for your own support team that a debugger or hooking finding is a signal to look at, not proof of abuse.

The honest limit

In the open-source SDK these checks are trivially removed, and detection is cat-and-mouse: new tools evade the markers, and an attacker who controls the client withholds the finding. Treat it as one more signal that stands out (especially its absence, next to attestation), never as the protection itself. The protection that does not sit on the client is the server signal and attestation (protocol section 6.7) — and value the server withholds without a valid license (M1, M2).

Harden your build (M8)

This section is about your own binary — the program you ship, with the SDK compiled into it. It is not about the SDK source: that is open source under MIT or Apache-2.0, so anyone can read it and build a copy with every check removed. Obfuscating the SDK source therefore buys you nothing. Hardening your build only raises the cost of reading and patching the specific binary you hand to users, and it only matters together with real protection: value the server withholds without a valid license, checks bound to that value, and tamper signals the server acts on. The guiding principle stands: protection comes from the server and from cryptography, not from hiding. Treat everything here as a speed bump for the casual patcher, never as a wall.

What helps, and how far

Strip symbols from the shipped binary. Names of functions and variables are the fastest way for someone to find the license check in a disassembler. A stripped release build hides them. Keep the unstripped build and its debug information in your pipeline — do not throw it away (see "Do not break crash reports" below).

  • Rust: a release profile with strip = "symbols" (or strip = true), and panic = "abort" if you do not need unwinding, which also removes panic message machinery.
  • C and C++: compile without -g for the release artifact, or run strip (on Apple targets strip -x) as a separate step after you have saved the debug file.

Hide plain strings. Error text, URLs, flag names and log messages printed near a check point to it. Keep user-facing strings in your normal translation files, but avoid leaving internal markers like license_valid or if entitlement as literals in the binary. Do not invent a home-grown "string encryption" scheme and believe it protects anything: a string decrypted at runtime is readable at runtime. The point is only to remove the free signposts, not to make the data secret.

Link time optimization (LTO) and static linking. Building the SDK statically into your binary with LTO inlines and reorders code across the boundary, so there is no separate, cleanly named license_sdk shared library to hook or replace, and the check does not sit behind one obvious call. This is the single most useful step, because it removes the easy seam, and it has no downside for honest users.

  • Rust: lto = true (or "fat") and codegen-units = 1 in the release profile; the SDK is already a static rlib.
  • C and C++: link liblicense_sdk as a static archive and enable your toolchain's LTO (-flto). The generated header is sdks/c/include/license_sdk.h.

Optional: control-flow obfuscation. Tools exist that flatten control flow or insert bogus branches (for example an LLVM obfuscation pass in your own build). This is the weakest and most expensive option, and the one most in tension with the principle above. It raises the bar for static analysis only, a determined analyst defeats it, and it carries real cost: slower code, harder debugging, and a binary that differs every build. Reach for it last, if at all, and only on the parts of your own code that gate a feature — never expect it to protect anything the server does not already protect.

Do not break crash reports

Stripping symbols from the shipped binary is compatible with Noctix crash reports (#506 ff.), but only if you keep the symbols and upload them. The native crash handler sends frames by module build ID and offset, not by name; the dashboard resolves them to function, file and line from the Breakpad symbol file you upload for that exact build. See Crash and error reports. So the order is: build, save the unstripped binary and generate its symbol file, strip the artifact you ship, then upload the symbols. If you strip and discard the debug information, your crash reports stay unreadable forever — you lose support visibility and gain nothing an attacker could not recover anyway.

Do not break reproducible builds

A reproducible build lets you and others confirm that a published binary was built from the published source, which is part of how Noctix ships SDKs (release process). Some hardening steps fight this: control-flow obfuscation that injects randomness, timestamps embedded by the linker, or a build that is different every time. If you want reproducibility, pin your toolchain, set SOURCE_DATE_EPOCH, avoid non-deterministic obfuscation passes, and verify that two clean builds of the same source produce the same bytes. Stripping, LTO and static linking are all deterministic and do not conflict with reproducibility; only the optional obfuscation layer does.

What not to do

  • Do not rely on build hardening instead of binding value to the license (see "Bind value to the license" above). A binary with nothing worth unlocking locally is the real protection; a well-obfuscated binary that gates a purely local if is still a one-line patch once found.
  • Do not obfuscate the SDK source and expect protection from it. It is public.
  • Do not ship a binary you cannot debug or whose crashes you cannot read. The cost lands on you and your honest users long before it inconveniences an attacker.

Noctix ships no obfuscation tool or CI template today; this is guidance for your own pipeline. If that changes it will be recorded in ../decisions.md first.