diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..dadba56 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,17 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space + +[*.{java,kt,kts}] +indent_size = 4 + +[*.{xml,yml,yaml}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..3fe6277 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,32 @@ +name: build + +on: + pull_request: + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Check out source + uses: actions/checkout@v4 + + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Build and test + run: ./gradlew build --no-daemon + + - name: Upload test reports on failure + if: failure() + uses: actions/upload-artifact@v4 + with: + name: test-reports + path: lib/build/reports/tests/test/ + retention-days: 7 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e417945 --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +# Gradle +.gradle/ +build/ +out/ + +# IDE +.idea/ +*.iml +*.ipr +*.iws +.classpath +.project +.settings/ +.vscode/ + +# OS +.DS_Store +Thumbs.db + +# Logs +*.log diff --git a/README.md b/README.md new file mode 100644 index 0000000..5bc75ac --- /dev/null +++ b/README.md @@ -0,0 +1,25 @@ +# JavaSake + +Java port of the SAKE handshake protocol used by 700-series Medtronic pumps. + +Mirrors the public surface of [PythonSake](https://github.com/OpenMinimed/PythonSake) +so it can be consumed by the [JavaPumpConnector](https://github.com/OpenMinimed/JavaPumpConnector) +Android application (and any other JVM project that needs to drive a SAKE handshake). + +## Build + +```sh +./gradlew build +``` + +## Test + +```sh +./gradlew test +``` + +Requires JDK 11 or later. + +## License + +GPL-3.0. See [`LICENSE`](LICENSE). diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..0cda148 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,2 @@ +// Root project intentionally has no plugins applied. +// See `lib/build.gradle.kts` for the library configuration. diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..2934ae5 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.parallel=true +org.gradle.caching=true +org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..75ed71f --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,15 @@ +[versions] +junit = "5.11.3" +junitPlatform = "1.11.3" +bouncycastle = "1.79" +spotless = "6.25.0" +googleJavaFormat = "1.22.0" + +[libraries] +junit-jupiter-api = { group = "org.junit.jupiter", name = "junit-jupiter-api", version.ref = "junit" } +junit-jupiter-engine = { group = "org.junit.jupiter", name = "junit-jupiter-engine", version.ref = "junit" } +junit-platform-launcher = { group = "org.junit.platform", name = "junit-platform-launcher", version.ref = "junitPlatform" } +bouncycastle = { group = "org.bouncycastle", name = "bcprov-jdk18on", version.ref = "bouncycastle" } + +[plugins] +spotless = { id = "com.diffplug.spotless", version.ref = "spotless" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..8bdaf60 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..6a38a8c --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=a17ddd85a26b6a7f5ddb71ff8b05fc5104c0202c6e64782429790c933686c806 +distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..ef07e01 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..5eed7ee --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lib/build.gradle.kts b/lib/build.gradle.kts new file mode 100644 index 0000000..92818a2 --- /dev/null +++ b/lib/build.gradle.kts @@ -0,0 +1,42 @@ +plugins { + `java-library` + alias(libs.plugins.spotless) +} + +group = "org.openminimed" +version = "0.1.0-SNAPSHOT" + +java { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + withSourcesJar() +} + +repositories { + mavenCentral() +} + +dependencies { + implementation(libs.bouncycastle) + + testImplementation(libs.junit.jupiter.api) + testRuntimeOnly(libs.junit.jupiter.engine) + testRuntimeOnly(libs.junit.platform.launcher) +} + +tasks.test { + useJUnitPlatform() + testLogging { + events("passed", "skipped", "failed") + } +} + +spotless { + java { + target("src/**/*.java") + googleJavaFormat(libs.versions.googleJavaFormat.get()).aosp() + removeUnusedImports() + trimTrailingWhitespace() + endWithNewline() + } +} diff --git a/lib/src/main/java/org/openminimed/sake/Constants.java b/lib/src/main/java/org/openminimed/sake/Constants.java new file mode 100644 index 0000000..da3e45c --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/Constants.java @@ -0,0 +1,68 @@ +package org.openminimed.sake; + +import java.util.Collections; +import java.util.List; + +/** + * Pre-baked key databases used by SAKE peers. + * + *

These are the three databases shipped with the reference Python implementation in {@code + * pysake/constants.py}. The hex strings are reproduced verbatim and parsed at class-init time. + * + *

The byte sequences here are shared SAKE protocol constants extracted from pump + * firmware: a real 780-series pump contains the same values internally and uses them to + * authenticate any phone-side application it pairs with. They are not session secrets and they are + * not unique per device, so embedding them in source is correct (and necessary; the protocol is not + * negotiable without them). + */ +public final class Constants { + + /** Glucose sensor (G4 family) key database. Display-side. */ + public static final KeyDatabase KEYDB_G4_CGM = + parse( + "5fe5928308010230f0b50df613f2e429c8c5e8713854add1a69b837235a3e974" + + "304d8055ccb397838b90823c73236d6a83dcc9db3a2a939ff16145ca4169ef93" + + "a7fa39b20962b05e57413bff8b3d61fce0dfef2c43b326"); + + /** Insulin pump database recovered from real pump firmware. Mobile-app-side. */ + public static final KeyDatabase KEYDB_PUMP_EXTRACTED = + parse( + "f75995e70401011bc1bf7cbf36fa1e2367d795ff09211903da6afbe986b650f1" + + "4179c0e6852e0ce393781078ffc6f51919e2eaefbde69b8eca21e41ab59b881a" + + "0bea0286ea91dc7582a86a714e1737f558f0d66dc1895c"); + + /** Insulin pump database with hard-coded test keys. Mobile-app-side. */ + public static final KeyDatabase KEYDB_PUMP_HARDCODED = + parse( + "c2cdfdd1040101fce36ed66ef21def3b0763975494b239038ebe8606f79a9bf0" + + "0d9f11b6db04c7c0434787cbf00d5476289c22288e2105ae40e01391837f9476" + + "fa5003895c5a1afe35662a2a6211826af016eebe30e4ba"); + + /** Databases available for production handshakes. */ + public static final List AVAILABLE_KEYS = + Collections.unmodifiableList( + java.util.Arrays.asList( + KEYDB_G4_CGM, KEYDB_PUMP_EXTRACTED, KEYDB_PUMP_HARDCODED)); + + private Constants() {} + + private static KeyDatabase parse(String hex) { + return KeyDatabase.fromBytes(decode(hex)); + } + + private static byte[] decode(String hex) { + if ((hex.length() & 1) != 0) { + throw new IllegalArgumentException("Hex string has odd length"); + } + byte[] out = new byte[hex.length() / 2]; + for (int i = 0; i < out.length; i++) { + int high = Character.digit(hex.charAt(2 * i), 16); + int low = Character.digit(hex.charAt(2 * i + 1), 16); + if (high < 0 || low < 0) { + throw new IllegalArgumentException("Invalid hex character"); + } + out[i] = (byte) ((high << 4) | low); + } + return out; + } +} diff --git a/lib/src/main/java/org/openminimed/sake/DeviceType.java b/lib/src/main/java/org/openminimed/sake/DeviceType.java new file mode 100644 index 0000000..9e08abd --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/DeviceType.java @@ -0,0 +1,48 @@ +package org.openminimed.sake; + +/** + * Type of device participating in a SAKE handshake. + * + *

The numeric values are wire-stable: they are serialized into the key-database header and into + * handshake messages. + */ +public enum DeviceType { + INSULIN_PUMP(0x1), + GLUCOSE_SENSOR(0x2), + BLOOD_GLUCOSE_METER(0x3), + MOBILE_APPLICATION(0x4), + CARE_LINK_UPLOAD_APPLICATION(0x5), + FIRMWARE_UPDATE_APPLICATION(0x6), + DIAGNOSTIC_APPLICATION(0x7), + PRIMARY_DISPLAY(0x8); + + /** Alias: secondary display devices share the same wire value as mobile applications. */ + public static final DeviceType SECONDARY_DISPLAY = MOBILE_APPLICATION; + + private final int value; + + DeviceType(int value) { + this.value = value; + } + + /** + * @return the wire value (1 byte, unsigned). + */ + public int value() { + return value; + } + + /** + * Resolve a device type from its wire value. + * + * @throws IllegalArgumentException if no device type matches. + */ + public static DeviceType fromValue(int value) { + for (DeviceType type : values()) { + if (type.value == value) { + return type; + } + } + throw new IllegalArgumentException("Unknown device type value: " + value); + } +} diff --git a/lib/src/main/java/org/openminimed/sake/KeyDatabase.java b/lib/src/main/java/org/openminimed/sake/KeyDatabase.java new file mode 100644 index 0000000..12479b0 --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/KeyDatabase.java @@ -0,0 +1,173 @@ +package org.openminimed.sake; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.zip.CRC32; + +/** + * Database of static keys shared between one local device and any number of remote devices. + * + *

The on-wire layout is: + * + *

+ *   [ 4 B CRC32 big-endian over everything that follows ]
+ *   [ 1 B local device type ]
+ *   [ 1 B n = remote-device count ]
+ *   n * { [ 1 B remote device type ][ 80 B StaticKeys ] }
+ * 
+ * + *

Each entry following the header is therefore 81 bytes and the total serialized length is + * {@code 6 + 81 * n} bytes. + */ +public final class KeyDatabase { + + private static final int CRC_SIZE = 4; + private static final int HEADER_SIZE = 6; + private static final int ENTRY_SIZE = 1 + StaticKeys.SERIALIZED_SIZE; + + private final DeviceType localDeviceType; + private final Map remoteDevices; + private final byte[] crc; + + /** Maximum number of remote-device entries: the wire format encodes the count in one byte. */ + public static final int MAX_REMOTE_DEVICES = 0xFF; + + public KeyDatabase( + DeviceType localDeviceType, Map remoteDevices, byte[] crc) { + this.localDeviceType = Objects.requireNonNull(localDeviceType, "localDeviceType"); + Objects.requireNonNull(remoteDevices, "remoteDevices"); + Objects.requireNonNull(crc, "crc"); + if (crc.length != CRC_SIZE) { + throw new IllegalArgumentException("crc must be " + CRC_SIZE + " bytes"); + } + if (remoteDevices.size() > MAX_REMOTE_DEVICES) { + throw new IllegalArgumentException( + "remoteDevices size " + + remoteDevices.size() + + " exceeds wire-format limit " + + MAX_REMOTE_DEVICES); + } + this.remoteDevices = Collections.unmodifiableMap(new LinkedHashMap<>(remoteDevices)); + this.crc = crc.clone(); + } + + /** + * Parse a key database from its serialized form. + * + * @throws IllegalArgumentException if the buffer is malformed or the CRC does not match. + */ + public static KeyDatabase fromBytes(byte[] data) { + Objects.requireNonNull(data, "data"); + if (data.length < HEADER_SIZE) { + throw new IllegalArgumentException("Buffer is shorter than the database header"); + } + + byte[] storedCrc = new byte[CRC_SIZE]; + System.arraycopy(data, 0, storedCrc, 0, CRC_SIZE); + + byte[] payload = new byte[data.length - CRC_SIZE]; + System.arraycopy(data, CRC_SIZE, payload, 0, payload.length); + + byte[] computedCrc = computeCrc(payload); + if (!java.util.Arrays.equals(storedCrc, computedCrc)) { + throw new IllegalArgumentException( + "CRC mismatch: stored=" + hex(storedCrc) + " computed=" + hex(computedCrc)); + } + + DeviceType localDeviceType = DeviceType.fromValue(payload[0] & 0xFF); + int n = payload[1] & 0xFF; + if (payload.length != 2 + ENTRY_SIZE * n) { + throw new IllegalArgumentException( + "Invalid database length for n=" + n + ": " + payload.length); + } + + Map remotes = new LinkedHashMap<>(); + for (int i = 0; i < n; i++) { + int base = 2 + i * ENTRY_SIZE; + DeviceType remoteType = DeviceType.fromValue(payload[base] & 0xFF); + byte[] keys = new byte[StaticKeys.SERIALIZED_SIZE]; + System.arraycopy(payload, base + 1, keys, 0, StaticKeys.SERIALIZED_SIZE); + remotes.put(remoteType, StaticKeys.fromBytes(keys)); + } + + return new KeyDatabase(localDeviceType, remotes, storedCrc); + } + + /** + * @return the serialized database with a freshly computed CRC. + */ + public byte[] toBytes() { + byte[] payload = payloadBytes(); + byte[] crcBytes = computeCrc(payload); + byte[] out = new byte[CRC_SIZE + payload.length]; + System.arraycopy(crcBytes, 0, out, 0, CRC_SIZE); + System.arraycopy(payload, 0, out, CRC_SIZE, payload.length); + return out; + } + + /** + * Return a new database with the local/remote roles swapped. + * + *

Requires exactly one remote device. + * + * @throws IllegalStateException if this database does not contain exactly one remote device. + */ + public KeyDatabase reverse() { + if (remoteDevices.size() != 1) { + throw new IllegalStateException("reverse() requires exactly one remote device"); + } + Map.Entry only = remoteDevices.entrySet().iterator().next(); + Map reversed = new LinkedHashMap<>(); + reversed.put(localDeviceType, only.getValue()); + KeyDatabase placeholder = new KeyDatabase(only.getKey(), reversed, new byte[CRC_SIZE]); + byte[] newCrc = computeCrc(placeholder.payloadBytes()); + return new KeyDatabase(only.getKey(), reversed, newCrc); + } + + public DeviceType localDeviceType() { + return localDeviceType; + } + + public Map remoteDevices() { + return remoteDevices; + } + + public byte[] crc() { + return crc.clone(); + } + + private byte[] payloadBytes() { + byte[] out = new byte[2 + ENTRY_SIZE * remoteDevices.size()]; + out[0] = (byte) localDeviceType.value(); + out[1] = (byte) remoteDevices.size(); + int offset = 2; + for (Map.Entry entry : remoteDevices.entrySet()) { + out[offset] = (byte) entry.getKey().value(); + byte[] keys = entry.getValue().toBytes(); + System.arraycopy(keys, 0, out, offset + 1, keys.length); + offset += ENTRY_SIZE; + } + return out; + } + + private static byte[] computeCrc(byte[] payload) { + CRC32 crc32 = new CRC32(); + crc32.update(payload); + return ByteBuffer.allocate(CRC_SIZE) + .order(ByteOrder.BIG_ENDIAN) + .putInt((int) crc32.getValue()) + .array(); + } + + private static String hex(byte[] data) { + StringBuilder sb = new StringBuilder(data.length * 2); + for (byte b : data) { + sb.append(String.format("%02x", b & 0xFF)); + } + return sb.toString(); + } +} diff --git a/lib/src/main/java/org/openminimed/sake/MacFailureException.java b/lib/src/main/java/org/openminimed/sake/MacFailureException.java new file mode 100644 index 0000000..1fd9f11 --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/MacFailureException.java @@ -0,0 +1,11 @@ +package org.openminimed.sake; + +/** Thrown when a CMAC trailer does not match the computed value during decryption. */ +public class MacFailureException extends Exception { + + private static final long serialVersionUID = 1L; + + public MacFailureException(String message) { + super(message); + } +} diff --git a/lib/src/main/java/org/openminimed/sake/Peer.java b/lib/src/main/java/org/openminimed/sake/Peer.java new file mode 100644 index 0000000..f1c92e1 --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/Peer.java @@ -0,0 +1,21 @@ +package org.openminimed.sake; + +/** + * Base class for {@link SakeServer} and {@link SakeClient}: tracks the handshake stage. + * + *

Stage progression for a server: 0 → 1 → 3 → 5 → 6. + * + *

Stage progression for a client: 0 → 2 → 4 → 6. + */ +public abstract class Peer { + + private int stage = 0; + + public final int getStage() { + return stage; + } + + protected final void incrementStage() { + stage++; + } +} diff --git a/lib/src/main/java/org/openminimed/sake/RngSource.java b/lib/src/main/java/org/openminimed/sake/RngSource.java new file mode 100644 index 0000000..af44135 --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/RngSource.java @@ -0,0 +1,18 @@ +package org.openminimed.sake; + +/** + * Source of random bytes used to populate handshake fields the server / client are expected to + * choose freshly per session. + * + *

Production implementations should be backed by {@link java.security.SecureRandom}; see {@link + * SecureRandomRngSource}. Tests can substitute a deterministic source to drive a server or client + * against a captured packet trace. + */ +public interface RngSource { + + /** + * @param n the number of bytes to return. Must be non-negative. + * @return a freshly allocated array of {@code n} random bytes. + */ + byte[] nextBytes(int n); +} diff --git a/lib/src/main/java/org/openminimed/sake/SakeClient.java b/lib/src/main/java/org/openminimed/sake/SakeClient.java new file mode 100644 index 0000000..a6417ca --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/SakeClient.java @@ -0,0 +1,141 @@ +package org.openminimed.sake; + +import java.util.Arrays; +import java.util.Objects; +import org.openminimed.sake.crypto.AesCmac; + +/** + * Client-side wrapper around {@link Session}. + * + *

Stage progression: 0 (consume server msg0, emit msg1) → 2 (consume msg2, emit msg3) → 4 + * (consume msg4, emit msg5) → 6 (done). + */ +public final class SakeClient extends Peer { + + /** Constant pad byte appended to the client's encrypted permit (msg5) plaintext. */ + static final byte DEFAULT_MSG5_PAD = (byte) 0x00; + + private final Session session; + private final DeviceType localDeviceType; + private final RngSource rng; + private byte msg5Pad = DEFAULT_MSG5_PAD; + + public SakeClient(KeyDatabase keyDb) { + this(keyDb, DeviceType.PRIMARY_DISPLAY, new SecureRandomRngSource()); + } + + public SakeClient(KeyDatabase keyDb, DeviceType localDeviceType) { + this(keyDb, localDeviceType, new SecureRandomRngSource()); + } + + public SakeClient(KeyDatabase keyDb, DeviceType localDeviceType, RngSource rng) { + Objects.requireNonNull(keyDb, "keyDb"); + Objects.requireNonNull(localDeviceType, "localDeviceType"); + Objects.requireNonNull(rng, "rng"); + this.session = new Session(keyDb, null); + this.localDeviceType = localDeviceType; + this.rng = rng; + } + + /** + * Drive the handshake one step. + * + * @param input the 20-byte message just received from the server. + * @return the 20-byte message to send back to the server. + * @throws MacFailureException if any CMAC verification fails. + */ + public byte[] handshake(byte[] input) throws MacFailureException { + Session.checkLen(input); + + int stage = getStage(); + if (stage == 0) { + session.handshake0S(input); + incrementStage(); + + byte[] msg1 = buildHandshake1C(); + session.handshake1C(msg1); + incrementStage(); + return msg1; + } + + if (stage == 2) { + session.handshake2S(input); + incrementStage(); + + byte[] msg3 = buildHandshake3C(); + session.handshake3C(msg3); + incrementStage(); + return msg3; + } + + if (stage == 4) { + boolean ok = session.handshake4S(input); + if (!ok) { + throw new MacFailureException("Permit verification failed at stage 4"); + } + incrementStage(); + + byte[] msg5 = buildHandshake5C(); + incrementStage(); + return msg5; + } + + throw new IllegalStateException("Invalid stage for SakeClient.handshake(): " + stage); + } + + public Session session() { + return session; + } + + public DeviceType localDeviceType() { + return localDeviceType; + } + + void setMsg5Pad(byte value) { + this.msg5Pad = value; + } + + private byte[] buildHandshake1C() { + byte[] key = rng.nextBytes(8); + byte[] nonce = rng.nextBytes(4); + + byte[] msg = new byte[Session.MESSAGE_SIZE]; + System.arraycopy(key, 0, msg, 0, 8); + msg[8] = (byte) localDeviceType.value(); + System.arraycopy(nonce, 0, msg, 9, 4); + // Bytes 13..19 remain zero, matching the reference Python implementation. + return msg; + } + + private byte[] buildHandshake3C() { + AesCmac auth1 = + Session.cmac8( + session.clientKeyMaterial(), + session.serverKeyMaterial(), + session.derivationKey(), + session.handshakeAuthKey()); + byte[] auth1Tag = auth1.digest(); + + byte[] inner = new byte[8 + 8 + 16]; + System.arraycopy(auth1Tag, 0, inner, 0, 8); + System.arraycopy(session.serverKeyMaterial(), 0, inner, 8, 8); + System.arraycopy(session.derivationKey(), 0, inner, 16, 16); + + AesCmac auth2 = new AesCmac(session.handshakeAuthKey(), 8); + auth2.update(inner); + byte[] prefix = auth2.digest(); + + byte[] filler = rng.nextBytes(12); + byte[] out = new byte[Session.MESSAGE_SIZE]; + System.arraycopy(prefix, 0, out, 0, 8); + System.arraycopy(filler, 0, out, 8, 12); + return out; + } + + private byte[] buildHandshake5C() { + byte[] payload = session.clientStaticKeys().handshakePayload(); + byte[] plaintext = Arrays.copyOf(payload, 17); + plaintext[16] = msg5Pad; + return session.clientCrypt().encrypt(plaintext); + } +} diff --git a/lib/src/main/java/org/openminimed/sake/SakeServer.java b/lib/src/main/java/org/openminimed/sake/SakeServer.java new file mode 100644 index 0000000..398d642 --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/SakeServer.java @@ -0,0 +1,151 @@ +package org.openminimed.sake; + +import java.util.Arrays; +import java.util.Objects; +import org.openminimed.sake.crypto.AesCmac; + +/** + * Server-side wrapper around {@link Session}: drives the handshake state machine and builds + * outgoing messages from the running state. + * + *

Stage progression: 0 (consume 20 zero bytes, emit msg0) → 1 (consume msg1, emit msg2) → 3 + * (consume msg3, emit msg4) → 5 (consume msg5, emit {@code null} to signal completion) → 6 (done). + */ +public final class SakeServer extends Peer { + + /** Constant pad byte appended to the server's encrypted permit (msg4) plaintext. */ + static final byte DEFAULT_MSG4_PAD = (byte) 0x69; + + private final Session session; + private final DeviceType localDeviceType; + private final RngSource rng; + private byte msg4Pad = DEFAULT_MSG4_PAD; + + public SakeServer(KeyDatabase keyDb) { + this(keyDb, DeviceType.MOBILE_APPLICATION, new SecureRandomRngSource()); + } + + public SakeServer(KeyDatabase keyDb, DeviceType localDeviceType) { + this(keyDb, localDeviceType, new SecureRandomRngSource()); + } + + public SakeServer(KeyDatabase keyDb, DeviceType localDeviceType, RngSource rng) { + Objects.requireNonNull(keyDb, "keyDb"); + Objects.requireNonNull(localDeviceType, "localDeviceType"); + Objects.requireNonNull(rng, "rng"); + this.session = new Session(null, keyDb); + this.localDeviceType = localDeviceType; + this.rng = rng; + } + + /** + * Drive the handshake one step. + * + * @param input the 20-byte message just received from the client. At stage 0 this must be 20 + * zero bytes (the wake-up frame sent over the SAKE characteristic when the peripheral + * subscribes to notifications). + * @return the 20-byte message to send back to the client, or {@code null} once the handshake + * completes at stage 5. + * @throws MacFailureException if any CMAC verification fails. + */ + public byte[] handshake(byte[] input) throws MacFailureException { + Session.checkLen(input); + + int stage = getStage(); + if (stage == 0) { + for (byte b : input) { + if (b != 0) { + throw new IllegalArgumentException("Stage 0 expects 20 zero bytes"); + } + } + byte[] msg0 = buildHandshake0S(); + session.handshake0S(msg0); + incrementStage(); + return msg0; + } + + if (stage == 1) { + session.handshake1C(input); + incrementStage(); + + byte[] msg2 = buildHandshake2S(); + session.handshake2S(msg2); + incrementStage(); + return msg2; + } + + if (stage == 3) { + session.handshake3C(input); + incrementStage(); + + byte[] msg4 = buildHandshake4S(); + incrementStage(); + return msg4; + } + + if (stage == 5) { + boolean ok = session.handshake5C(input); + if (!ok) { + throw new MacFailureException("Permit verification failed at stage 5"); + } + incrementStage(); + + // Reset server_crypt.rx_seq so subsequent session traffic is decoded + // with the right starting sequence number. + session.setServerCryptRxSeq(2L); + return null; + } + + throw new IllegalStateException("Handshake already complete (stage " + stage + ")"); + } + + public Session session() { + return session; + } + + public DeviceType localDeviceType() { + return localDeviceType; + } + + /** + * Override the msg4 pad byte. Package-private; only the parity tests use this to reproduce a + * captured packet trace bit-for-bit. + */ + void setMsg4Pad(byte value) { + this.msg4Pad = value; + } + + private byte[] buildHandshake0S() { + byte[] msg = new byte[Session.MESSAGE_SIZE]; + msg[0] = (byte) localDeviceType.value(); + msg[1] = 0x01; + byte[] filler = rng.nextBytes(Session.MESSAGE_SIZE - 2); + System.arraycopy(filler, 0, msg, 2, filler.length); + return msg; + } + + private byte[] buildHandshake2S() { + byte[] serverKm = rng.nextBytes(8); + byte[] serverNonce = rng.nextBytes(4); + AesCmac auth = + Session.cmac8( + session.clientKeyMaterial(), + serverKm, + session.derivationKey(), + session.handshakeAuthKey()); + byte[] prefix = auth.digest(); + + byte[] out = new byte[Session.MESSAGE_SIZE]; + System.arraycopy(prefix, 0, out, 0, 8); + System.arraycopy(serverKm, 0, out, 8, 8); + System.arraycopy(serverNonce, 0, out, 16, 4); + return out; + } + + private byte[] buildHandshake4S() { + byte[] payload = session.serverStaticKeys().handshakePayload(); + byte[] plaintext = Arrays.copyOf(payload, 17); + plaintext[16] = msg4Pad; + return session.serverCrypt().encrypt(plaintext); + } +} diff --git a/lib/src/main/java/org/openminimed/sake/SecureRandomRngSource.java b/lib/src/main/java/org/openminimed/sake/SecureRandomRngSource.java new file mode 100644 index 0000000..673a996 --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/SecureRandomRngSource.java @@ -0,0 +1,16 @@ +package org.openminimed.sake; + +import java.security.SecureRandom; + +/** Default {@link RngSource} backed by {@link SecureRandom}. */ +public final class SecureRandomRngSource implements RngSource { + + private final SecureRandom rng = new SecureRandom(); + + @Override + public byte[] nextBytes(int n) { + byte[] out = new byte[n]; + rng.nextBytes(out); + return out; + } +} diff --git a/lib/src/main/java/org/openminimed/sake/SeqCrypt.java b/lib/src/main/java/org/openminimed/sake/SeqCrypt.java new file mode 100644 index 0000000..e7039bb --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/SeqCrypt.java @@ -0,0 +1,179 @@ +package org.openminimed.sake; + +import java.util.Arrays; +import java.util.Objects; +import org.openminimed.sake.crypto.AesCmac; +import org.openminimed.sake.crypto.AesCtr; + +/** + * Sequence-numbered AES-CTR stream cipher with a CMAC trailer. + * + *

Each direction of the SAKE session is one {@code SeqCrypt} instance with its own sequence + * counter. The encrypted form of a message is {@code ciphertext || trailer} where {@code trailer} + * is three bytes: + * + *

+ *   [ (seq >> 1) & 0xFF ][ CMAC4(nonce.padTo16 || ciphertext)[0..1] ]
+ * 
+ * + *

The receiver reconstructs the full sequence from its local {@code rxSeq} and the 1-byte field + * in the trailer, tolerating an 8-bit wrap-around. Deltas larger than {@link #MAX_RX_DELTA} are + * rejected to bound the damage from a forged but MAC-valid packet. + * + *

The two-byte trailer MAC is dictated by the SAKE wire protocol: it is a sixteen-bit + * authentication tag, not a full-strength MAC, and reflects the protocol's defence-in-depth + * trade-off between packet size and forgery resistance. + * + *

The IV layout stores the sequence as five big-endian bytes followed by the eight-byte nonce + * and three zero counter bytes. The five-byte sequence field bounds {@code txSeq} to less than + * {@link #MAX_SEQ}; encryption past that point would silently truncate the sequence and risk IV + * reuse, so {@link #encrypt(byte[])} rejects it. + * + *

Instances are not thread-safe. External synchronisation is required if a single instance is + * shared across threads. + */ +public final class SeqCrypt { + + private static final int TRAILER_SIZE = 3; + private static final int SEQ_PREFIX_SIZE = 5; + private static final int NONCE_SIZE = 8; + private static final int MAC_SIZE = 4; + private static final int IV_SIZE = 16; + + /** Exclusive upper bound on {@code txSeq}: 2^40, matching the 5-byte sequence prefix. */ + public static final long MAX_SEQ = 1L << 40; + + /** + * Maximum accepted delta (in trailer-byte units) between an incoming packet's sequence and the + * receiver's tracked {@code rxSeq}. A delta of {@value} corresponds to skipping 256 packets + * forward; larger jumps are treated as forgery attempts. + */ + public static final int MAX_RX_DELTA = 128; + + private final byte[] key; + private final byte[] nonce; + private long txSeq; + private long rxSeq; + + public SeqCrypt(byte[] key, byte[] nonce, long initialSeq) { + Objects.requireNonNull(key, "key"); + Objects.requireNonNull(nonce, "nonce"); + if (key.length != IV_SIZE) { + throw new IllegalArgumentException("key must be " + IV_SIZE + " bytes"); + } + if (nonce.length != NONCE_SIZE) { + throw new IllegalArgumentException("nonce must be " + NONCE_SIZE + " bytes"); + } + this.key = key.clone(); + this.nonce = nonce.clone(); + this.txSeq = initialSeq; + this.rxSeq = initialSeq; + } + + public byte[] encrypt(byte[] plaintext) { + Objects.requireNonNull(plaintext, "plaintext"); + long seq = txSeq; + if (seq < 0 || seq >= MAX_SEQ) { + throw new IllegalStateException("txSeq " + seq + " exceeds the 2^40 IV sequence bound"); + } + byte[] iv = buildIv(seq); + byte[] ciphertext = AesCtr.crypt(key, iv, plaintext); + byte[] tagPrefix = computeTagPrefix(seq, ciphertext); + + byte[] out = new byte[ciphertext.length + TRAILER_SIZE]; + System.arraycopy(ciphertext, 0, out, 0, ciphertext.length); + out[ciphertext.length] = (byte) ((seq >>> 1) & 0xFF); + out[ciphertext.length + 1] = tagPrefix[0]; + out[ciphertext.length + 2] = tagPrefix[1]; + + txSeq = seq + 2; + return out; + } + + /** + * Decrypt and authenticate a message. + * + * @throws IllegalArgumentException if the buffer is shorter than the trailer. + * @throws MacFailureException if the trailer MAC does not match the computed value. + */ + public byte[] decrypt(byte[] message) throws MacFailureException { + Objects.requireNonNull(message, "message"); + if (message.length < TRAILER_SIZE) { + throw new IllegalArgumentException("Message shorter than trailer"); + } + + int seqByte = message[message.length - TRAILER_SIZE] & 0xFF; + int delta = (seqByte - (int) ((rxSeq >>> 1) & 0xFF)) & 0xFF; + if (delta > MAX_RX_DELTA) { + throw new MacFailureException( + "Sequence delta " + delta + " exceeds reorder window of " + MAX_RX_DELTA); + } + long seq = rxSeq + 2L * delta; + + int ciphertextLen = message.length - TRAILER_SIZE; + byte[] ciphertext = Arrays.copyOfRange(message, 0, ciphertextLen); + byte[] tagPrefix = computeTagPrefix(seq, ciphertext); + + if ((tagPrefix[0] != message[ciphertextLen + 1]) + || (tagPrefix[1] != message[ciphertextLen + 2])) { + throw new MacFailureException("MAC verification failed at seq=" + seq); + } + + byte[] iv = buildIv(seq); + byte[] plaintext = AesCtr.crypt(key, iv, ciphertext); + rxSeq = seq + 2; + return plaintext; + } + + public byte[] key() { + return key.clone(); + } + + public byte[] nonce() { + return nonce.clone(); + } + + public long getTxSeq() { + return txSeq; + } + + public long getRxSeq() { + return rxSeq; + } + + public void setTxSeq(long value) { + this.txSeq = value; + } + + public void setRxSeq(long value) { + this.rxSeq = value; + } + + private byte[] buildIv(long seq) { + byte[] iv = new byte[IV_SIZE]; + iv[0] = (byte) ((seq >>> 32) & 0xFF); + iv[1] = (byte) ((seq >>> 24) & 0xFF); + iv[2] = (byte) ((seq >>> 16) & 0xFF); + iv[3] = (byte) ((seq >>> 8) & 0xFF); + iv[4] = (byte) (seq & 0xFF); + System.arraycopy(nonce, 0, iv, SEQ_PREFIX_SIZE, NONCE_SIZE); + // Trailing 3 bytes remain zero (counter region for AES-CTR). + return iv; + } + + private byte[] computeTagPrefix(long seq, byte[] ciphertext) { + byte[] cmacInput = new byte[IV_SIZE + ciphertext.length]; + cmacInput[0] = (byte) ((seq >>> 32) & 0xFF); + cmacInput[1] = (byte) ((seq >>> 24) & 0xFF); + cmacInput[2] = (byte) ((seq >>> 16) & 0xFF); + cmacInput[3] = (byte) ((seq >>> 8) & 0xFF); + cmacInput[4] = (byte) (seq & 0xFF); + System.arraycopy(nonce, 0, cmacInput, SEQ_PREFIX_SIZE, NONCE_SIZE); + // Bytes 13..15 are the zero-padding to 16 (`ljust` in the Python). + System.arraycopy(ciphertext, 0, cmacInput, IV_SIZE, ciphertext.length); + + AesCmac cmac = new AesCmac(key, MAC_SIZE); + cmac.update(cmacInput); + return cmac.digest(); + } +} diff --git a/lib/src/main/java/org/openminimed/sake/Session.java b/lib/src/main/java/org/openminimed/sake/Session.java new file mode 100644 index 0000000..9c25f7a --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/Session.java @@ -0,0 +1,276 @@ +package org.openminimed.sake; + +import java.util.Arrays; +import java.util.Objects; +import org.openminimed.sake.crypto.AesCmac; +import org.openminimed.sake.crypto.AesEcb; + +/** + * Holds the cryptographic state of a single SAKE handshake. + * + *

Exactly one of {@code clientKeyDb} or {@code serverKeyDb} must be supplied at construction + * time: the absent side will be unable to perform the cryptographic permit check on its inbound + * permit message and will simply log the payload comparison instead. + * + *

Method names match the reference Python implementation ({@code pysake/session.py}). The + * trailing {@code S} / {@code C} marks which side the message originated from (server vs client), + * not which side is calling the method. + */ +public final class Session { + + /** Required length in bytes of every handshake message. */ + public static final int MESSAGE_SIZE = 20; + + private static final int KEY_MATERIAL_SIZE = 8; + private static final int NONCE_SIZE = 4; + private static final int PERMIT_SIZE = 16; + private static final int CMAC8_SIZE = 8; + + private final KeyDatabase clientKeyDb; + private final KeyDatabase serverKeyDb; + + private DeviceType serverDeviceType; + private DeviceType clientDeviceType; + + private byte[] clientKeyMaterial; + private byte[] clientNonce; + + private byte[] serverKeyMaterial; + private byte[] serverNonce; + + private byte[] derivationKey; + private byte[] handshakeAuthKey; + + private StaticKeys clientStaticKeys; + private StaticKeys serverStaticKeys; + + private SeqCrypt clientCrypt; + private SeqCrypt serverCrypt; + + public Session(KeyDatabase clientKeyDb, KeyDatabase serverKeyDb) { + int provided = (clientKeyDb != null ? 1 : 0) + (serverKeyDb != null ? 1 : 0); + if (provided != 1) { + throw new IllegalArgumentException( + "Exactly one of clientKeyDb or serverKeyDb is required, got " + provided); + } + this.clientKeyDb = clientKeyDb; + this.serverKeyDb = serverKeyDb; + } + + public void handshake0S(byte[] msg) { + checkLen(msg); + if (msg[1] != 0x01) { + throw new IllegalArgumentException("Unexpected byte at offset 1: " + (msg[1] & 0xFF)); + } + this.serverDeviceType = DeviceType.fromValue(msg[0] & 0xFF); + } + + public void handshake1C(byte[] msg) { + checkLen(msg); + this.clientKeyMaterial = Arrays.copyOfRange(msg, 0, 8); + this.clientDeviceType = DeviceType.fromValue(msg[8] & 0xFF); + this.clientNonce = Arrays.copyOfRange(msg, 9, 13); + + int cdt = clientDeviceType.value(); + int sdt = serverDeviceType.value(); + + StaticKeys staticKeys = null; + if (clientKeyDb != null && clientKeyDb.localDeviceType().value() == cdt) { + staticKeys = clientKeyDb.remoteDevices().get(DeviceType.fromValue(sdt)); + this.clientStaticKeys = staticKeys; + } + if (serverKeyDb != null && serverKeyDb.localDeviceType().value() == sdt) { + staticKeys = serverKeyDb.remoteDevices().get(DeviceType.fromValue(cdt)); + this.serverStaticKeys = staticKeys; + } + if (staticKeys == null) { + throw new IllegalStateException( + "No keys available for client device type " + + cdt + + " and server device type " + + sdt); + } + + this.derivationKey = staticKeys.derivationKey(); + this.handshakeAuthKey = staticKeys.handshakeAuthKey(); + } + + public void handshake2S(byte[] msg) throws MacFailureException { + checkLen(msg); + byte[] received = Arrays.copyOfRange(msg, 0, CMAC8_SIZE); + byte[] serverKm = Arrays.copyOfRange(msg, 8, 16); + byte[] serverN = Arrays.copyOfRange(msg, 16, 20); + + AesCmac auth = cmac8(clientKeyMaterial, serverKm, derivationKey, handshakeAuthKey); + if (!auth.verify(received)) { + throw new MacFailureException("handshake2S CMAC8 verification failed"); + } + + this.serverKeyMaterial = serverKm; + this.serverNonce = serverN; + } + + public void handshake3C(byte[] msg) throws MacFailureException { + checkLen(msg); + byte[] received = Arrays.copyOfRange(msg, 0, CMAC8_SIZE); + + AesCmac auth1 = + cmac8(clientKeyMaterial, serverKeyMaterial, derivationKey, handshakeAuthKey); + byte[] auth1Tag = auth1.digest(); + + byte[] inner = new byte[CMAC8_SIZE + KEY_MATERIAL_SIZE + AesCmac.BLOCK_SIZE]; + System.arraycopy(auth1Tag, 0, inner, 0, CMAC8_SIZE); + System.arraycopy(serverKeyMaterial, 0, inner, CMAC8_SIZE, KEY_MATERIAL_SIZE); + System.arraycopy( + derivationKey, 0, inner, CMAC8_SIZE + KEY_MATERIAL_SIZE, AesCmac.BLOCK_SIZE); + + AesCmac auth2 = new AesCmac(handshakeAuthKey, CMAC8_SIZE); + auth2.update(inner); + if (!auth2.verify(received)) { + throw new MacFailureException("handshake3C CMAC8 verification failed"); + } + + createCrypts(); + } + + public boolean handshake4S(byte[] msg) throws MacFailureException { + checkLen(msg); + byte[] decrypted = serverCrypt.decrypt(msg); + byte[] payload = Arrays.copyOfRange(decrypted, 0, PERMIT_SIZE); + return checkPermit(payload, clientStaticKeys, serverStaticKeys, serverDeviceType.value()); + } + + public boolean handshake5C(byte[] msg) throws MacFailureException { + checkLen(msg); + byte[] decrypted = clientCrypt.decrypt(msg); + // pysake takes plaintext[:-1] but the permit body is exactly 16 bytes (PERMIT_SIZE). + byte[] payload = Arrays.copyOfRange(decrypted, 0, PERMIT_SIZE); + return checkPermit(payload, serverStaticKeys, clientStaticKeys, clientDeviceType.value()); + } + + /** + * Compute the 8-byte CMAC over {@code serverKm || clientKm || derivationKey}. + * + * @return a primed {@link AesCmac} ready to {@link AesCmac#digest()} or {@link + * AesCmac#verify(byte[])}. + */ + public static AesCmac cmac8( + byte[] clientKm, byte[] serverKm, byte[] derivationKey, byte[] handshakeAuthKey) { + byte[] msg = new byte[32]; + System.arraycopy(serverKm, 0, msg, 0, KEY_MATERIAL_SIZE); + System.arraycopy(clientKm, 0, msg, KEY_MATERIAL_SIZE, KEY_MATERIAL_SIZE); + System.arraycopy(derivationKey, 0, msg, 2 * KEY_MATERIAL_SIZE, AesCmac.BLOCK_SIZE); + AesCmac cmac = new AesCmac(handshakeAuthKey, CMAC8_SIZE); + cmac.update(msg); + return cmac; + } + + /** + * @throws IllegalArgumentException if {@code msg} is not exactly {@value #MESSAGE_SIZE} bytes. + */ + public static void checkLen(byte[] msg) { + Objects.requireNonNull(msg, "msg"); + if (msg.length != MESSAGE_SIZE) { + throw new IllegalArgumentException( + "Invalid message length: " + msg.length + ", expected " + MESSAGE_SIZE); + } + } + + private void createCrypts() { + byte[] kmConcat = new byte[2 * KEY_MATERIAL_SIZE]; + System.arraycopy(serverKeyMaterial, 0, kmConcat, 0, KEY_MATERIAL_SIZE); + System.arraycopy(clientKeyMaterial, 0, kmConcat, KEY_MATERIAL_SIZE, KEY_MATERIAL_SIZE); + byte[] sessionKey = AesEcb.encryptBlock(derivationKey, kmConcat); + + byte[] sessionNonce = new byte[2 * NONCE_SIZE]; + System.arraycopy(clientNonce, 0, sessionNonce, 0, NONCE_SIZE); + System.arraycopy(serverNonce, 0, sessionNonce, NONCE_SIZE, NONCE_SIZE); + + this.clientCrypt = new SeqCrypt(sessionKey, sessionNonce, 0L); + this.serverCrypt = new SeqCrypt(sessionKey, sessionNonce, 1L); + } + + private boolean checkPermit( + byte[] payload, + StaticKeys verifierStaticKeys, + StaticKeys proverStaticKeys, + int proverDeviceType) + throws MacFailureException { + if (verifierStaticKeys == null) { + return false; + } + byte[] plain = AesEcb.decryptBlock(verifierStaticKeys.permitDecryptKey(), payload); + AesCmac auth = new AesCmac(verifierStaticKeys.permitAuthKey(), 4); + auth.update(Arrays.copyOfRange(plain, 0, 12)); + if (!auth.verify(Arrays.copyOfRange(plain, 12, 16))) { + throw new MacFailureException("Permit auth tag verification failed"); + } + return plain[0] == 0 && (plain[1] & 0xFF) == proverDeviceType; + } + + public DeviceType serverDeviceType() { + return serverDeviceType; + } + + public DeviceType clientDeviceType() { + return clientDeviceType; + } + + public byte[] clientKeyMaterial() { + return clientKeyMaterial == null ? null : clientKeyMaterial.clone(); + } + + public byte[] clientNonce() { + return clientNonce == null ? null : clientNonce.clone(); + } + + public byte[] serverKeyMaterial() { + return serverKeyMaterial == null ? null : serverKeyMaterial.clone(); + } + + public byte[] serverNonce() { + return serverNonce == null ? null : serverNonce.clone(); + } + + public byte[] derivationKey() { + return derivationKey == null ? null : derivationKey.clone(); + } + + public byte[] handshakeAuthKey() { + return handshakeAuthKey == null ? null : handshakeAuthKey.clone(); + } + + public StaticKeys clientStaticKeys() { + return clientStaticKeys; + } + + public StaticKeys serverStaticKeys() { + return serverStaticKeys; + } + + /** + * Returns the live {@link SeqCrypt} used for messages originating from the client. The + * reference is intentional: {@link SakeServer} and {@link SakeClient} drive the sequence + * counter forward by calling {@link SeqCrypt#encrypt(byte[])} / {@link + * SeqCrypt#decrypt(byte[])} directly on this instance. Callers outside the handshake should + * treat the returned object as read-only. + */ + public SeqCrypt clientCrypt() { + return clientCrypt; + } + + /** + * Returns the live {@link SeqCrypt} used for messages originating from the server. See {@link + * #clientCrypt()} for the rationale on returning the reference directly. + */ + public SeqCrypt serverCrypt() { + return serverCrypt; + } + + /** Package-private setter used by {@code SakeServer} to apply post-handshake adjustments. */ + void setServerCryptRxSeq(long value) { + if (serverCrypt != null) { + serverCrypt.setRxSeq(value); + } + } +} diff --git a/lib/src/main/java/org/openminimed/sake/StaticKeys.java b/lib/src/main/java/org/openminimed/sake/StaticKeys.java new file mode 100644 index 0000000..b9a0838 --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/StaticKeys.java @@ -0,0 +1,107 @@ +package org.openminimed.sake; + +import java.util.Arrays; +import java.util.Objects; + +/** + * Five 16-byte keys shared between two specific devices, plus an opaque 16-byte handshake payload. + * + *

The on-wire form is the concatenation, in declaration order, of: + * + *

    + *
  1. {@code derivationKey} + *
  2. {@code handshakeAuthKey} + *
  3. {@code permitDecryptKey} + *
  4. {@code permitAuthKey} + *
  5. {@code handshakePayload} + *
+ */ +public final class StaticKeys { + + /** Size in bytes of each of the five fields. */ + public static final int FIELD_SIZE = 16; + + /** Total size in bytes of the serialized form. */ + public static final int SERIALIZED_SIZE = 5 * FIELD_SIZE; + + private final byte[] derivationKey; + private final byte[] handshakeAuthKey; + private final byte[] permitDecryptKey; + private final byte[] permitAuthKey; + private final byte[] handshakePayload; + + public StaticKeys( + byte[] derivationKey, + byte[] handshakeAuthKey, + byte[] permitDecryptKey, + byte[] permitAuthKey, + byte[] handshakePayload) { + this.derivationKey = requireExactSize("derivationKey", derivationKey); + this.handshakeAuthKey = requireExactSize("handshakeAuthKey", handshakeAuthKey); + this.permitDecryptKey = requireExactSize("permitDecryptKey", permitDecryptKey); + this.permitAuthKey = requireExactSize("permitAuthKey", permitAuthKey); + this.handshakePayload = requireExactSize("handshakePayload", handshakePayload); + } + + /** + * Parse a {@link StaticKeys} from exactly {@value #SERIALIZED_SIZE} bytes. + * + * @throws IllegalArgumentException if the buffer is not exactly {@value #SERIALIZED_SIZE} + * bytes. + */ + public static StaticKeys fromBytes(byte[] data) { + Objects.requireNonNull(data, "data"); + if (data.length != SERIALIZED_SIZE) { + throw new IllegalArgumentException( + "StaticKeys requires " + SERIALIZED_SIZE + " bytes, got " + data.length); + } + return new StaticKeys( + Arrays.copyOfRange(data, 0 * FIELD_SIZE, 1 * FIELD_SIZE), + Arrays.copyOfRange(data, 1 * FIELD_SIZE, 2 * FIELD_SIZE), + Arrays.copyOfRange(data, 2 * FIELD_SIZE, 3 * FIELD_SIZE), + Arrays.copyOfRange(data, 3 * FIELD_SIZE, 4 * FIELD_SIZE), + Arrays.copyOfRange(data, 4 * FIELD_SIZE, 5 * FIELD_SIZE)); + } + + /** + * @return a new {@value #SERIALIZED_SIZE}-byte buffer containing the serialized form. + */ + public byte[] toBytes() { + byte[] out = new byte[SERIALIZED_SIZE]; + System.arraycopy(derivationKey, 0, out, 0 * FIELD_SIZE, FIELD_SIZE); + System.arraycopy(handshakeAuthKey, 0, out, 1 * FIELD_SIZE, FIELD_SIZE); + System.arraycopy(permitDecryptKey, 0, out, 2 * FIELD_SIZE, FIELD_SIZE); + System.arraycopy(permitAuthKey, 0, out, 3 * FIELD_SIZE, FIELD_SIZE); + System.arraycopy(handshakePayload, 0, out, 4 * FIELD_SIZE, FIELD_SIZE); + return out; + } + + public byte[] derivationKey() { + return derivationKey.clone(); + } + + public byte[] handshakeAuthKey() { + return handshakeAuthKey.clone(); + } + + public byte[] permitDecryptKey() { + return permitDecryptKey.clone(); + } + + public byte[] permitAuthKey() { + return permitAuthKey.clone(); + } + + public byte[] handshakePayload() { + return handshakePayload.clone(); + } + + private static byte[] requireExactSize(String name, byte[] data) { + Objects.requireNonNull(data, name); + if (data.length != FIELD_SIZE) { + throw new IllegalArgumentException( + name + " must be " + FIELD_SIZE + " bytes, got " + data.length); + } + return data.clone(); + } +} diff --git a/lib/src/main/java/org/openminimed/sake/crypto/AesCmac.java b/lib/src/main/java/org/openminimed/sake/crypto/AesCmac.java new file mode 100644 index 0000000..305cc18 --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/crypto/AesCmac.java @@ -0,0 +1,81 @@ +package org.openminimed.sake.crypto; + +import java.util.Arrays; +import java.util.Objects; +import org.bouncycastle.crypto.engines.AESEngine; +import org.bouncycastle.crypto.macs.CMac; +import org.bouncycastle.crypto.params.KeyParameter; + +/** + * Stateful AES-CMAC over a 16-byte AES-128 key with a configurable truncation length. + * + *

The handshake uses both {@code macLen=8} (handshake CMAC chain) and {@code macLen=4} (permit + * auth, SeqCrypt trailer prefix). BouncyCastle always produces a 16-byte tag; we truncate to {@code + * macLen} bytes to match the PyCryptodome {@code mac_len} parameter. + * + *

State accumulates across {@link #update(byte[])} calls. Calling {@link #digest()} or {@link + * #verify(byte[])} computes the tag and resets the underlying {@code CMac}, leaving the instance + * ready to receive {@code update} calls for a fresh message. + * + *

Instances are not thread-safe. + */ +public final class AesCmac { + + /** AES block size and full MAC length in bytes. */ + public static final int BLOCK_SIZE = 16; + + private final CMac mac; + private final int macLen; + + public AesCmac(byte[] key, int macLen) { + Objects.requireNonNull(key, "key"); + if (key.length != BLOCK_SIZE) { + throw new IllegalArgumentException("AES-128 key must be " + BLOCK_SIZE + " bytes"); + } + if (macLen < 1 || macLen > BLOCK_SIZE) { + throw new IllegalArgumentException("macLen must be 1.." + BLOCK_SIZE); + } + this.mac = new CMac(AESEngine.newInstance()); + this.mac.init(new KeyParameter(key)); + this.macLen = macLen; + } + + public AesCmac update(byte[] data) { + Objects.requireNonNull(data, "data"); + mac.update(data, 0, data.length); + return this; + } + + /** + * Compute the truncated MAC over all data accumulated since construction (or the previous + * {@code digest}/{@code verify} call). The underlying state is reset; further {@link + * #update(byte[])} calls begin a new message. + */ + public byte[] digest() { + byte[] full = new byte[mac.getMacSize()]; + mac.doFinal(full, 0); + if (macLen == full.length) { + return full; + } + return Arrays.copyOf(full, macLen); + } + + /** + * Constant-time comparison against an expected tag. Internally calls {@link #digest()} and + * therefore resets the underlying MAC state. + * + * @return true if the computed digest matches {@code expected}, byte-for-byte. + */ + public boolean verify(byte[] expected) { + Objects.requireNonNull(expected, "expected"); + byte[] actual = digest(); + if (actual.length != expected.length) { + return false; + } + int diff = 0; + for (int i = 0; i < actual.length; i++) { + diff |= actual[i] ^ expected[i]; + } + return diff == 0; + } +} diff --git a/lib/src/main/java/org/openminimed/sake/crypto/AesCtr.java b/lib/src/main/java/org/openminimed/sake/crypto/AesCtr.java new file mode 100644 index 0000000..61fb697 --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/crypto/AesCtr.java @@ -0,0 +1,50 @@ +package org.openminimed.sake.crypto; + +import java.security.GeneralSecurityException; +import java.util.Objects; +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +/** + * AES-128 CTR stream encryption. + * + *

The 16-byte IV is passed unchanged to the JDK's {@code AES/CTR/NoPadding} cipher, which treats + * it as a 128-bit initial counter and increments the whole thing by one per block. + * + *

The (key, IV) pair must be unique per encryption. Reusing the same key with the same IV + * for two different plaintexts completely breaks CTR-mode confidentiality and authenticity. Callers + * are responsible for assembling the IV so that (a) it differs across every encryption performed + * under a given key, and (b) the per-block counter increments never wrap into the bits that carry + * the unique nonce or sequence number. See {@link org.openminimed.sake.SeqCrypt} for the SAKE + * session's IV construction. + * + *

CTR is symmetric so the same method is used to encrypt and decrypt. + */ +public final class AesCtr { + + /** AES block size and IV length in bytes. */ + public static final int BLOCK_SIZE = 16; + + private AesCtr() {} + + public static byte[] crypt(byte[] key, byte[] iv, byte[] data) { + Objects.requireNonNull(key, "key"); + Objects.requireNonNull(iv, "iv"); + Objects.requireNonNull(data, "data"); + if (key.length != BLOCK_SIZE) { + throw new IllegalArgumentException("AES-128 key must be " + BLOCK_SIZE + " bytes"); + } + if (iv.length != BLOCK_SIZE) { + throw new IllegalArgumentException("IV must be " + BLOCK_SIZE + " bytes"); + } + try { + Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); + cipher.init( + Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); + return cipher.doFinal(data); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("AES/CTR/NoPadding unavailable", e); + } + } +} diff --git a/lib/src/main/java/org/openminimed/sake/crypto/AesEcb.java b/lib/src/main/java/org/openminimed/sake/crypto/AesEcb.java new file mode 100644 index 0000000..0913440 --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/crypto/AesEcb.java @@ -0,0 +1,45 @@ +package org.openminimed.sake.crypto; + +import java.security.GeneralSecurityException; +import java.util.Objects; +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; + +/** + * Single-block AES-128 ECB encrypt / decrypt. + * + *

Used by the handshake exclusively on 16-byte blocks; this class does not accept anything else. + */ +public final class AesEcb { + + /** AES block size in bytes. */ + public static final int BLOCK_SIZE = 16; + + private AesEcb() {} + + public static byte[] encryptBlock(byte[] key, byte[] block) { + return process(key, block, Cipher.ENCRYPT_MODE); + } + + public static byte[] decryptBlock(byte[] key, byte[] block) { + return process(key, block, Cipher.DECRYPT_MODE); + } + + private static byte[] process(byte[] key, byte[] block, int mode) { + Objects.requireNonNull(key, "key"); + Objects.requireNonNull(block, "block"); + if (key.length != BLOCK_SIZE) { + throw new IllegalArgumentException("AES-128 key must be " + BLOCK_SIZE + " bytes"); + } + if (block.length != BLOCK_SIZE) { + throw new IllegalArgumentException("Block must be " + BLOCK_SIZE + " bytes"); + } + try { + Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); + cipher.init(mode, new SecretKeySpec(key, "AES")); + return cipher.doFinal(block); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("AES/ECB/NoPadding unavailable", e); + } + } +} diff --git a/lib/src/main/java/org/openminimed/sake/crypto/package-info.java b/lib/src/main/java/org/openminimed/sake/crypto/package-info.java new file mode 100644 index 0000000..08036cd --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/crypto/package-info.java @@ -0,0 +1,12 @@ +/** + * Thin AES primitive wrappers used by the SAKE handshake. + * + *

AES-ECB and AES-CTR are served by the JDK's JCE provider. AES-CMAC is implemented via + * BouncyCastle as the JDK does not ship it. + * + *

AES-ECB is intentionally limited to single sixteen-byte operations on freshly random or + * uniquely-derived inputs (the permit-block decrypt step and the session-key derivation step). It + * is never used to encrypt multi-block or structured plaintext, where ECB's deterministic block + * mapping would leak structure. + */ +package org.openminimed.sake.crypto; diff --git a/lib/src/main/java/org/openminimed/sake/package-info.java b/lib/src/main/java/org/openminimed/sake/package-info.java new file mode 100644 index 0000000..eb93c40 --- /dev/null +++ b/lib/src/main/java/org/openminimed/sake/package-info.java @@ -0,0 +1,7 @@ +/** + * Java port of the SAKE handshake protocol used by 700-series Medtronic pumps. + * + *

This package mirrors the public surface of the reference Python implementation at PythonSake. + */ +package org.openminimed.sake; diff --git a/lib/src/test/java/org/openminimed/sake/ConstantsTest.java b/lib/src/test/java/org/openminimed/sake/ConstantsTest.java new file mode 100644 index 0000000..a655750 --- /dev/null +++ b/lib/src/test/java/org/openminimed/sake/ConstantsTest.java @@ -0,0 +1,38 @@ +package org.openminimed.sake; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +class ConstantsTest { + + @Test + void g4CgmLocalIsPrimaryDisplay() { + assertEquals(DeviceType.PRIMARY_DISPLAY, Constants.KEYDB_G4_CGM.localDeviceType()); + assertNotNull(Constants.KEYDB_G4_CGM.remoteDevices().get(DeviceType.GLUCOSE_SENSOR)); + } + + @Test + void pumpExtractedLocalIsMobileApplication() { + assertEquals( + DeviceType.MOBILE_APPLICATION, Constants.KEYDB_PUMP_EXTRACTED.localDeviceType()); + assertNotNull(Constants.KEYDB_PUMP_EXTRACTED.remoteDevices().get(DeviceType.INSULIN_PUMP)); + } + + @Test + void pumpHardcodedLocalIsMobileApplication() { + assertEquals( + DeviceType.MOBILE_APPLICATION, Constants.KEYDB_PUMP_HARDCODED.localDeviceType()); + assertNotNull(Constants.KEYDB_PUMP_HARDCODED.remoteDevices().get(DeviceType.INSULIN_PUMP)); + } + + @Test + void availableKeysExposesAllThreeDatabases() { + assertEquals(3, Constants.AVAILABLE_KEYS.size()); + assertTrue(Constants.AVAILABLE_KEYS.contains(Constants.KEYDB_G4_CGM)); + assertTrue(Constants.AVAILABLE_KEYS.contains(Constants.KEYDB_PUMP_EXTRACTED)); + assertTrue(Constants.AVAILABLE_KEYS.contains(Constants.KEYDB_PUMP_HARDCODED)); + } +} diff --git a/lib/src/test/java/org/openminimed/sake/DeviceTypeTest.java b/lib/src/test/java/org/openminimed/sake/DeviceTypeTest.java new file mode 100644 index 0000000..4f8531a --- /dev/null +++ b/lib/src/test/java/org/openminimed/sake/DeviceTypeTest.java @@ -0,0 +1,40 @@ +package org.openminimed.sake; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class DeviceTypeTest { + + @Test + void wireValuesAreStable() { + assertEquals(0x1, DeviceType.INSULIN_PUMP.value()); + assertEquals(0x2, DeviceType.GLUCOSE_SENSOR.value()); + assertEquals(0x3, DeviceType.BLOOD_GLUCOSE_METER.value()); + assertEquals(0x4, DeviceType.MOBILE_APPLICATION.value()); + assertEquals(0x5, DeviceType.CARE_LINK_UPLOAD_APPLICATION.value()); + assertEquals(0x6, DeviceType.FIRMWARE_UPDATE_APPLICATION.value()); + assertEquals(0x7, DeviceType.DIAGNOSTIC_APPLICATION.value()); + assertEquals(0x8, DeviceType.PRIMARY_DISPLAY.value()); + } + + @Test + void secondaryDisplayIsAliasForMobileApplication() { + assertSame(DeviceType.MOBILE_APPLICATION, DeviceType.SECONDARY_DISPLAY); + assertEquals(0x4, DeviceType.SECONDARY_DISPLAY.value()); + } + + @Test + void fromValueResolvesEachWireValue() { + for (DeviceType type : DeviceType.values()) { + assertSame(type, DeviceType.fromValue(type.value())); + } + } + + @Test + void fromValueRejectsUnknownValue() { + assertThrows(IllegalArgumentException.class, () -> DeviceType.fromValue(0xFF)); + } +} diff --git a/lib/src/test/java/org/openminimed/sake/Hex.java b/lib/src/test/java/org/openminimed/sake/Hex.java new file mode 100644 index 0000000..1604ba9 --- /dev/null +++ b/lib/src/test/java/org/openminimed/sake/Hex.java @@ -0,0 +1,33 @@ +package org.openminimed.sake; + +public final class Hex { + + private Hex() {} + + public static byte[] decode(String hex) { + if ((hex.length() & 1) != 0) { + throw new IllegalArgumentException("Hex string has odd length: " + hex.length()); + } + byte[] out = new byte[hex.length() / 2]; + for (int i = 0; i < out.length; i++) { + int high = Character.digit(hex.charAt(2 * i), 16); + int low = Character.digit(hex.charAt(2 * i + 1), 16); + if (high < 0) { + throw new IllegalArgumentException("Invalid hex character at index " + (2 * i)); + } + if (low < 0) { + throw new IllegalArgumentException("Invalid hex character at index " + (2 * i + 1)); + } + out[i] = (byte) ((high << 4) | low); + } + return out; + } + + public static String encode(byte[] data) { + StringBuilder sb = new StringBuilder(data.length * 2); + for (byte b : data) { + sb.append(String.format("%02x", b & 0xFF)); + } + return sb.toString(); + } +} diff --git a/lib/src/test/java/org/openminimed/sake/HexTest.java b/lib/src/test/java/org/openminimed/sake/HexTest.java new file mode 100644 index 0000000..70486b4 --- /dev/null +++ b/lib/src/test/java/org/openminimed/sake/HexTest.java @@ -0,0 +1,42 @@ +package org.openminimed.sake; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** Tests for the test-only {@link Hex} helper, including its diagnostic error indices. */ +class HexTest { + + @Test + void roundTripIsLossless() { + byte[] data = {0x00, 0x12, (byte) 0xAB, (byte) 0xFF}; + assertArrayEquals(data, Hex.decode(Hex.encode(data))); + } + + @Test + void rejectsOddLength() { + assertThrows(IllegalArgumentException.class, () -> Hex.decode("abc")); + } + + @Test + void invalidHighNibbleErrorReportsHighIndex() { + IllegalArgumentException ex = + assertThrows(IllegalArgumentException.class, () -> Hex.decode("gf")); + assertTrue( + ex.getMessage().contains("index 0"), + "expected high-nibble error to name index 0, got: " + ex.getMessage()); + } + + @Test + void invalidLowNibbleErrorReportsLowIndex() { + IllegalArgumentException ex = + assertThrows(IllegalArgumentException.class, () -> Hex.decode("fg")); + assertEquals( + "Invalid hex character at index 1", + ex.getMessage(), + "low-nibble error must point at the offending second character"); + } +} diff --git a/lib/src/test/java/org/openminimed/sake/KeyDatabaseTest.java b/lib/src/test/java/org/openminimed/sake/KeyDatabaseTest.java new file mode 100644 index 0000000..ae0ec58 --- /dev/null +++ b/lib/src/test/java/org/openminimed/sake/KeyDatabaseTest.java @@ -0,0 +1,118 @@ +package org.openminimed.sake; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class KeyDatabaseTest { + + /** + * The three baked-in key databases from the reference Python implementation + * (pysake/constants.py). They are the canonical round-trip vectors for this parser: any change + * to the serialization must keep these byte-identical. + */ + private static final String HEX_G4_CGM = + "5fe5928308010230f0b50df613f2e429c8c5e8713854add1a69b837235a3e974" + + "304d8055ccb397838b90823c73236d6a83dcc9db3a2a939ff16145ca4169ef93" + + "a7fa39b20962b05e57413bff8b3d61fce0dfef2c43b326"; + + private static final String HEX_PUMP_EXTRACTED = + "f75995e70401011bc1bf7cbf36fa1e2367d795ff09211903da6afbe986b650f1" + + "4179c0e6852e0ce393781078ffc6f51919e2eaefbde69b8eca21e41ab59b881a" + + "0bea0286ea91dc7582a86a714e1737f558f0d66dc1895c"; + + private static final String HEX_PUMP_HARDCODED = + "c2cdfdd1040101fce36ed66ef21def3b0763975494b239038ebe8606f79a9bf0" + + "0d9f11b6db04c7c0434787cbf00d5476289c22288e2105ae40e01391837f9476" + + "fa5003895c5a1afe35662a2a6211826af016eebe30e4ba"; + + @Test + void parsesG4Cgm() { + KeyDatabase db = KeyDatabase.fromBytes(Hex.decode(HEX_G4_CGM)); + assertEquals(DeviceType.PRIMARY_DISPLAY, db.localDeviceType()); + assertEquals(1, db.remoteDevices().size()); + assertNotNull(db.remoteDevices().get(DeviceType.GLUCOSE_SENSOR)); + } + + @Test + void parsesPumpExtracted() { + KeyDatabase db = KeyDatabase.fromBytes(Hex.decode(HEX_PUMP_EXTRACTED)); + assertEquals(DeviceType.MOBILE_APPLICATION, db.localDeviceType()); + assertEquals(1, db.remoteDevices().size()); + assertNotNull(db.remoteDevices().get(DeviceType.INSULIN_PUMP)); + } + + @Test + void parsesPumpHardcoded() { + KeyDatabase db = KeyDatabase.fromBytes(Hex.decode(HEX_PUMP_HARDCODED)); + assertEquals(DeviceType.MOBILE_APPLICATION, db.localDeviceType()); + assertEquals(1, db.remoteDevices().size()); + assertNotNull(db.remoteDevices().get(DeviceType.INSULIN_PUMP)); + } + + @Test + void roundTripIsByteIdentical() { + for (String hex : new String[] {HEX_G4_CGM, HEX_PUMP_EXTRACTED, HEX_PUMP_HARDCODED}) { + byte[] original = Hex.decode(hex); + byte[] roundTripped = KeyDatabase.fromBytes(original).toBytes(); + assertArrayEquals( + original, + roundTripped, + "Round trip differed for " + hex.substring(0, 16) + "..."); + } + } + + @Test + void rejectsCrcMismatch() { + byte[] corrupt = Hex.decode(HEX_PUMP_EXTRACTED); + corrupt[0] ^= (byte) 0x01; + assertThrows(IllegalArgumentException.class, () -> KeyDatabase.fromBytes(corrupt)); + } + + @Test + void rejectsTruncatedBuffer() { + byte[] truncated = new byte[] {0x00, 0x00, 0x00, 0x00, 0x04}; + assertThrows(IllegalArgumentException.class, () -> KeyDatabase.fromBytes(truncated)); + } + + @Test + void constructorRejectsRemoteDeviceCountAboveWireLimit() { + // DeviceType only has eight enum values, so we cannot actually fill 256 entries. + // Use a size-only Map view to drive the constructor down the size-validation branch. + java.util.Map oversize = + new java.util.AbstractMap<>() { + @Override + public java.util.Set> entrySet() { + return java.util.Set.of(); + } + + @Override + public int size() { + return KeyDatabase.MAX_REMOTE_DEVICES + 1; + } + }; + assertThrows( + IllegalArgumentException.class, + () -> new KeyDatabase(DeviceType.MOBILE_APPLICATION, oversize, new byte[4])); + } + + @Test + void reverseProducesValidDatabase() { + for (String hex : new String[] {HEX_G4_CGM, HEX_PUMP_EXTRACTED, HEX_PUMP_HARDCODED}) { + KeyDatabase original = KeyDatabase.fromBytes(Hex.decode(hex)); + KeyDatabase reversed = original.reverse(); + assertEquals( + original.remoteDevices().keySet().iterator().next(), + reversed.localDeviceType()); + assertEquals(1, reversed.remoteDevices().size()); + assertNotNull(reversed.remoteDevices().get(original.localDeviceType())); + + byte[] reversedBytes = reversed.toBytes(); + KeyDatabase reparsed = KeyDatabase.fromBytes(reversedBytes); + assertEquals(reversed.localDeviceType(), reparsed.localDeviceType()); + } + } +} diff --git a/lib/src/test/java/org/openminimed/sake/QueuedRngSource.java b/lib/src/test/java/org/openminimed/sake/QueuedRngSource.java new file mode 100644 index 0000000..99a2533 --- /dev/null +++ b/lib/src/test/java/org/openminimed/sake/QueuedRngSource.java @@ -0,0 +1,37 @@ +package org.openminimed.sake; + +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.Deque; + +/** + * Deterministic {@link RngSource} that returns pre-queued byte arrays in order. + * + *

Used by parity tests to drive {@link SakeServer} / {@link SakeClient} through a captured + * packet trace. + */ +final class QueuedRngSource implements RngSource { + + private final Deque queue; + + QueuedRngSource(byte[]... values) { + this.queue = new ArrayDeque<>(Arrays.asList(values)); + } + + @Override + public byte[] nextBytes(int n) { + byte[] next = queue.pollFirst(); + if (next == null) { + throw new IllegalStateException( + "QueuedRngSource is empty (caller asked for " + n + " bytes)"); + } + if (next.length != n) { + throw new IllegalStateException( + "QueuedRngSource size mismatch: caller asked for " + + n + + " bytes but next queued value is " + + next.length); + } + return next.clone(); + } +} diff --git a/lib/src/test/java/org/openminimed/sake/SakeClientTest.java b/lib/src/test/java/org/openminimed/sake/SakeClientTest.java new file mode 100644 index 0000000..3fa354b --- /dev/null +++ b/lib/src/test/java/org/openminimed/sake/SakeClientTest.java @@ -0,0 +1,102 @@ +package org.openminimed.sake; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** + * End-to-end tests for {@link SakeClient}: driving a fresh client against a fresh server using a + * matched pair of custom key databases generated by {@code test_key_db_gen.py} in the reference + * Python implementation. + * + *

The two databases share the same derivation key, handshake auth key and permit key set; + * together they form a complete two-sided test pair, the smallest configuration that lets both + * permit checks succeed. + */ +class SakeClientTest { + + private static final String KEYDB_CUSTOM_SERVER_HEX = + "b079cdc504010144455249564154494f4e5f5f5f4b4559484e4453484b455f41" + + "5554485f4b455950484f4e455f5045524d49545f454e4350484f4e455f5045" + + "524d49545f4d4143ad14ad2780437db892d5650567d491b9"; + + private static final String KEYDB_CUSTOM_CLIENT_HEX = + "db8c1f2801010444455249564154494f4e5f5f5f4b4559484e4453484b455f41" + + "5554485f4b455950554d505f5045524d49545f454e435250554d505f504552" + + "4d49545f434d4143f2f8dbbb51563d4fa98fdaff0042a432"; + + private static KeyDatabase serverKeyDb() { + return KeyDatabase.fromBytes(Hex.decode(KEYDB_CUSTOM_SERVER_HEX)); + } + + private static KeyDatabase clientKeyDb() { + return KeyDatabase.fromBytes(Hex.decode(KEYDB_CUSTOM_CLIENT_HEX)); + } + + @Test + void clientAndServerCompleteHandshakeAgainstEachOther() throws Exception { + SakeServer server = new SakeServer(serverKeyDb(), DeviceType.MOBILE_APPLICATION); + SakeClient client = new SakeClient(clientKeyDb(), DeviceType.INSULIN_PUMP); + + byte[] msg0 = server.handshake(new byte[20]); + assertNotNull(msg0); + assertEquals(1, server.getStage()); + + byte[] msg1 = client.handshake(msg0); + assertNotNull(msg1); + assertEquals(2, client.getStage()); + + byte[] msg2 = server.handshake(msg1); + assertNotNull(msg2); + assertEquals(3, server.getStage()); + + byte[] msg3 = client.handshake(msg2); + assertNotNull(msg3); + assertEquals(4, client.getStage()); + + byte[] msg4 = server.handshake(msg3); + assertNotNull(msg4); + assertEquals(5, server.getStage()); + + byte[] msg5 = client.handshake(msg4); + assertNotNull(msg5); + assertEquals(6, client.getStage()); + + byte[] done = server.handshake(msg5); + assertEquals(6, server.getStage()); + assertEquals(null, done); + } + + @Test + void handshakeProducesUsableSessionState() throws Exception { + SakeServer server = new SakeServer(serverKeyDb(), DeviceType.MOBILE_APPLICATION); + SakeClient client = new SakeClient(clientKeyDb(), DeviceType.INSULIN_PUMP); + + byte[] msg0 = server.handshake(new byte[20]); + byte[] msg1 = client.handshake(msg0); + byte[] msg2 = server.handshake(msg1); + byte[] msg3 = client.handshake(msg2); + byte[] msg4 = server.handshake(msg3); + byte[] msg5 = client.handshake(msg4); + server.handshake(msg5); + + // Both peers must agree on the derived session key. + assertArrayEquals( + server.session().clientCrypt().key(), + client.session().clientCrypt().key(), + "client_crypt key must match across peers"); + assertArrayEquals( + server.session().serverCrypt().key(), + client.session().serverCrypt().key(), + "server_crypt key must match across peers"); + assertArrayEquals( + server.session().clientCrypt().nonce(), + client.session().clientCrypt().nonce(), + "session nonce must match across peers"); + + assertTrue(server.getStage() == 6 && client.getStage() == 6); + } +} diff --git a/lib/src/test/java/org/openminimed/sake/SakeServerTest.java b/lib/src/test/java/org/openminimed/sake/SakeServerTest.java new file mode 100644 index 0000000..05d83ca --- /dev/null +++ b/lib/src/test/java/org/openminimed/sake/SakeServerTest.java @@ -0,0 +1,117 @@ +package org.openminimed.sake; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +/** + * End-to-end parity tests for {@link SakeServer} against the captured 780G pairing pcap embedded in + * {@code pysake/constants.py} ({@code __PUMP_TEST_MSGS_1}). + * + *

The server is driven with a deterministic {@link QueuedRngSource} that replays the random + * fields chosen during the original pcap (server msg0 filler, server key material, server nonce) + * and with the same {@code 0xf7} pad byte for msg4. Under those inputs the server must emit exactly + * the bytes recorded in the pcap. + */ +class SakeServerTest { + + private static final String PUMP_KEYDB_HEX = + "f75995e70401011bc1bf7cbf36fa1e2367d795ff09211903da6afbe986b650f1" + + "4179c0e6852e0ce393781078ffc6f51919e2eaefbde69b8eca21e41ab59b881a" + + "0bea0286ea91dc7582a86a714e1737f558f0d66dc1895c"; + + private static final byte[][] PUMP_TEST_MSGS = + new byte[][] { + Hex.decode("0401e2f09017a98f9f01cc56492fbacd4576e92b"), + Hex.decode("42060e9f344e9312016ee8854d357f659b6b00ba"), + Hex.decode("fdeeb13d04c3f18d272630ebeabe7c3a4d4d27b9"), + Hex.decode("c02cec4ffb99affcb553a10fa6c55bb13d9fbacf"), + Hex.decode("157d8e90214418a0e3d5f0517eebf4a82e00c02e"), + Hex.decode("9b36f393b296fa84a757809859fc84a5c300d59b"), + }; + + /** + * Pad byte for the msg4 plaintext that reproduces the captured pcap. Recovered from the + * keystream as {@code captured[16] XOR keystream[16]} at tx_seq=1. + */ + private static final byte CAPTURED_MSG4_PAD = (byte) 0xf7; + + private static SakeServer captureMatchingServer() { + QueuedRngSource rng = + new QueuedRngSource( + Arrays.copyOfRange(PUMP_TEST_MSGS[0], 2, 20), + Arrays.copyOfRange(PUMP_TEST_MSGS[2], 8, 16), + Arrays.copyOfRange(PUMP_TEST_MSGS[2], 16, 20)); + SakeServer server = + new SakeServer( + KeyDatabase.fromBytes(Hex.decode(PUMP_KEYDB_HEX)), + DeviceType.MOBILE_APPLICATION, + rng); + server.setMsg4Pad(CAPTURED_MSG4_PAD); + return server; + } + + @Test + void endToEndMatchesCapturedPumpTrace() throws Exception { + SakeServer server = captureMatchingServer(); + + byte[] out0 = server.handshake(new byte[20]); + assertArrayEquals(PUMP_TEST_MSGS[0], out0, "msg0 must match captured pcap"); + assertEquals(1, server.getStage()); + + byte[] out2 = server.handshake(PUMP_TEST_MSGS[1]); + assertArrayEquals(PUMP_TEST_MSGS[2], out2, "msg2 must match captured pcap"); + assertEquals(3, server.getStage()); + + byte[] out4 = server.handshake(PUMP_TEST_MSGS[3]); + assertArrayEquals(PUMP_TEST_MSGS[4], out4, "msg4 must match captured pcap"); + assertEquals(5, server.getStage()); + + byte[] out5 = server.handshake(PUMP_TEST_MSGS[5]); + assertNull(out5, "stage 5 returns null to signal completion"); + assertEquals(6, server.getStage()); + + // After completion the server_crypt.rx_seq has been reset to 2 so that + // subsequent session traffic decodes against the right starting seq. + assertEquals(2L, server.session().serverCrypt().getRxSeq()); + } + + @Test + void msg0IsEmittedAtStageZero() throws Exception { + SakeServer server = captureMatchingServer(); + byte[] out0 = server.handshake(new byte[20]); + assertNotNull(out0); + assertEquals(DeviceType.MOBILE_APPLICATION.value(), out0[0] & 0xFF); + assertEquals(0x01, out0[1]); + } + + @Test + void stageZeroRejectsNonZeroInput() { + SakeServer server = new SakeServer(KeyDatabase.fromBytes(Hex.decode(PUMP_KEYDB_HEX))); + byte[] notZero = new byte[20]; + notZero[5] = 0x01; + assertThrows(IllegalArgumentException.class, () -> server.handshake(notZero)); + } + + @Test + void handshakeRejectsWrongLength() { + SakeServer server = new SakeServer(KeyDatabase.fromBytes(Hex.decode(PUMP_KEYDB_HEX))); + assertThrows(IllegalArgumentException.class, () -> server.handshake(new byte[19])); + } + + @Test + void handshakeRejectsAdditionalInputAfterCompletion() throws Exception { + SakeServer server = captureMatchingServer(); + server.handshake(new byte[20]); + server.handshake(PUMP_TEST_MSGS[1]); + server.handshake(PUMP_TEST_MSGS[3]); + server.handshake(PUMP_TEST_MSGS[5]); + assertEquals(6, server.getStage()); + assertThrows(IllegalStateException.class, () -> server.handshake(new byte[20])); + } +} diff --git a/lib/src/test/java/org/openminimed/sake/SeqCryptTest.java b/lib/src/test/java/org/openminimed/sake/SeqCryptTest.java new file mode 100644 index 0000000..d89bdbc --- /dev/null +++ b/lib/src/test/java/org/openminimed/sake/SeqCryptTest.java @@ -0,0 +1,132 @@ +package org.openminimed.sake; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +/** + * Parity tests against the reference Python implementation ({@code pysake/seqcrypt.py}). + * + *

The captured ciphertexts below were generated by running the Python SeqCrypt with the same + * key, nonce and starting sequence values as the test setup here. Any divergence between Java and + * Python output for the same inputs would cause an assertion to fail. + */ +class SeqCryptTest { + + private static final byte[] KEY = Hex.decode("00112233445566778899aabbccddeeff"); + private static final byte[] NONCE = Hex.decode("a1b2c3d4e5f60718"); + + private static final byte[] PLAIN_0 = Hex.decode("00000000000000000000000000000000ff"); + private static final byte[] PLAIN_1 = Hex.decode("48656c6c6f2c2053414b65212121212121"); + private static final byte[] PLAIN_2 = Hex.decode("deadbeef"); + + private static final byte[] CIPHER_SEQ0_0 = + Hex.decode("7680ea16798357df88b11466330e24d3f200b0e6"); + private static final byte[] CIPHER_SEQ0_1 = + Hex.decode("9b92fdd551a0cbfc63b5fae41e888ca53c011265"); + private static final byte[] CIPHER_SEQ0_2 = Hex.decode("60c26e3b02e1a3"); + private static final byte[] CIPHER_SEQ1 = + Hex.decode("28b3469d0ece854f9760df0c7be2e79d93006a3d"); + + @Test + void encryptMatchesPythonAtSeqZero() { + SeqCrypt sc = new SeqCrypt(KEY, NONCE, 0L); + assertArrayEquals(CIPHER_SEQ0_0, sc.encrypt(PLAIN_0)); + assertEquals(2L, sc.getTxSeq()); + assertArrayEquals(CIPHER_SEQ0_1, sc.encrypt(PLAIN_1)); + assertEquals(4L, sc.getTxSeq()); + assertArrayEquals(CIPHER_SEQ0_2, sc.encrypt(PLAIN_2)); + assertEquals(6L, sc.getTxSeq()); + } + + @Test + void encryptMatchesPythonAtSeqOne() { + SeqCrypt sc = new SeqCrypt(KEY, NONCE, 1L); + assertArrayEquals(CIPHER_SEQ1, sc.encrypt(PLAIN_1)); + assertEquals(3L, sc.getTxSeq()); + } + + @Test + void decryptRoundTripsThreeMessages() throws Exception { + SeqCrypt sc = new SeqCrypt(KEY, NONCE, 0L); + assertArrayEquals(PLAIN_0, sc.decrypt(CIPHER_SEQ0_0)); + assertEquals(2L, sc.getRxSeq()); + assertArrayEquals(PLAIN_1, sc.decrypt(CIPHER_SEQ0_1)); + assertEquals(4L, sc.getRxSeq()); + assertArrayEquals(PLAIN_2, sc.decrypt(CIPHER_SEQ0_2)); + assertEquals(6L, sc.getRxSeq()); + } + + @Test + void decryptRejectsTamperedMac() { + SeqCrypt sc = new SeqCrypt(KEY, NONCE, 0L); + byte[] corrupt = CIPHER_SEQ0_0.clone(); + corrupt[corrupt.length - 1] ^= (byte) 0x01; + assertThrows(MacFailureException.class, () -> sc.decrypt(corrupt)); + } + + @Test + void decryptRejectsTamperedCiphertext() { + SeqCrypt sc = new SeqCrypt(KEY, NONCE, 0L); + byte[] corrupt = CIPHER_SEQ0_0.clone(); + corrupt[0] ^= (byte) 0x01; + assertThrows(MacFailureException.class, () -> sc.decrypt(corrupt)); + } + + @Test + void encryptDecryptRoundTripIsInverse() throws Exception { + SeqCrypt tx = new SeqCrypt(KEY, NONCE, 42L); + SeqCrypt rx = new SeqCrypt(KEY, NONCE, 42L); + byte[] cipher = tx.encrypt(PLAIN_1); + byte[] recovered = rx.decrypt(cipher); + assertArrayEquals(PLAIN_1, recovered); + assertEquals(tx.getTxSeq(), rx.getRxSeq()); + } + + /** + * The 1-byte sequence field in the trailer wraps every 256 messages (since it is {@code (seq + * >>> 1) & 0xFF}). The receiver must reconstruct the full 32-bit sequence using its locally + * tracked {@code rxSeq} as the base and a delta in [0, 255]. This test exercises the wrap by + * sending a single message at {@code seq = 512} (trailer byte 0) to a receiver that still + * tracks {@code rxSeq = 510}. + */ + @Test + void decryptHandlesEightBitSequenceWrap() throws Exception { + SeqCrypt tx = new SeqCrypt(KEY, NONCE, 512L); + byte[] cipher = tx.encrypt(PLAIN_1); + assertEquals( + 0, + cipher[cipher.length - 3] & 0xFF, + "trailer byte should be 0 at seq=512 (wrap-around point)"); + + SeqCrypt rx = new SeqCrypt(KEY, NONCE, 510L); + byte[] recovered = rx.decrypt(cipher); + assertArrayEquals(PLAIN_1, recovered); + assertEquals(514L, rx.getRxSeq()); + } + + /** + * The receiver must reject incoming sequences that imply a forward jump beyond the configured + * reorder window. A forged-but-MAC-valid packet at a far-future sequence number could otherwise + * permanently desync rxSeq. + */ + @Test + void decryptRejectsDeltaBeyondReorderWindow() { + SeqCrypt tx = new SeqCrypt(KEY, NONCE, 2L * (SeqCrypt.MAX_RX_DELTA + 1)); + byte[] cipher = tx.encrypt(PLAIN_2); + SeqCrypt rx = new SeqCrypt(KEY, NONCE, 0L); + assertThrows(MacFailureException.class, () -> rx.decrypt(cipher)); + } + + /** + * Encrypting past the 2^40 sequence boundary would silently truncate the sequence in the five + * IV prefix bytes and risk IV reuse. {@link SeqCrypt#encrypt(byte[])} must reject it. + */ + @Test + void encryptRejectsSequenceAtFortyBitBoundary() { + SeqCrypt sc = new SeqCrypt(KEY, NONCE, SeqCrypt.MAX_SEQ); + assertThrows(IllegalStateException.class, () -> sc.encrypt(PLAIN_2)); + } +} diff --git a/lib/src/test/java/org/openminimed/sake/SessionTest.java b/lib/src/test/java/org/openminimed/sake/SessionTest.java new file mode 100644 index 0000000..8d24553 --- /dev/null +++ b/lib/src/test/java/org/openminimed/sake/SessionTest.java @@ -0,0 +1,158 @@ +package org.openminimed.sake; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** + * Parity tests for {@link Session} driven by the captured pump pairing pcap embedded in {@code + * pysake/constants.py} as {@code __PUMP_TEST_MSGS_1}. + * + *

The expected per-checkpoint state was captured from a harness driving {@link Session} in the + * reference Python implementation against the same key database and message sequence. Any + * divergence in any derived field causes an assertion to fail and points at the responsible step. + */ +class SessionTest { + + private static final String KEY_DB_HEX = + "f75995e70401011bc1bf7cbf36fa1e2367d795ff09211903da6afbe986b650f1" + + "4179c0e6852e0ce393781078ffc6f51919e2eaefbde69b8eca21e41ab59b881a" + + "0bea0286ea91dc7582a86a714e1737f558f0d66dc1895c"; + + private static final byte[][] PUMP_TEST_MSGS = + new byte[][] { + Hex.decode("0401e2f09017a98f9f01cc56492fbacd4576e92b"), + Hex.decode("42060e9f344e9312016ee8854d357f659b6b00ba"), + Hex.decode("fdeeb13d04c3f18d272630ebeabe7c3a4d4d27b9"), + Hex.decode("c02cec4ffb99affcb553a10fa6c55bb13d9fbacf"), + Hex.decode("157d8e90214418a0e3d5f0517eebf4a82e00c02e"), + Hex.decode("9b36f393b296fa84a757809859fc84a5c300d59b"), + }; + + private static KeyDatabase keyDb() { + return KeyDatabase.fromBytes(Hex.decode(KEY_DB_HEX)); + } + + @Test + void rejectsConstructionWithNeitherKeyDb() { + assertThrows(IllegalArgumentException.class, () -> new Session(null, null)); + } + + @Test + void rejectsConstructionWithBothKeyDbs() { + assertThrows(IllegalArgumentException.class, () -> new Session(keyDb(), keyDb())); + } + + @Test + void rejectsWrongMessageLength() { + Session sess = new Session(null, keyDb()); + assertThrows(IllegalArgumentException.class, () -> sess.handshake0S(new byte[19])); + } + + @Test + void handshake0SCapturesServerDeviceType() { + Session sess = new Session(null, keyDb()); + sess.handshake0S(PUMP_TEST_MSGS[0]); + assertEquals(DeviceType.MOBILE_APPLICATION, sess.serverDeviceType()); + } + + @Test + void handshake1CDerivesKeysFromKeyDb() { + Session sess = new Session(null, keyDb()); + sess.handshake0S(PUMP_TEST_MSGS[0]); + sess.handshake1C(PUMP_TEST_MSGS[1]); + + assertEquals(DeviceType.INSULIN_PUMP, sess.clientDeviceType()); + assertArrayEquals(Hex.decode("42060e9f344e9312"), sess.clientKeyMaterial()); + assertArrayEquals(Hex.decode("6ee8854d"), sess.clientNonce()); + assertArrayEquals(Hex.decode("1bc1bf7cbf36fa1e2367d795ff092119"), sess.derivationKey()); + assertArrayEquals(Hex.decode("03da6afbe986b650f14179c0e6852e0c"), sess.handshakeAuthKey()); + assertNotNull(sess.serverStaticKeys()); + } + + @Test + void handshake2SVerifiesAndCapturesServerKeyMaterial() throws Exception { + Session sess = new Session(null, keyDb()); + sess.handshake0S(PUMP_TEST_MSGS[0]); + sess.handshake1C(PUMP_TEST_MSGS[1]); + sess.handshake2S(PUMP_TEST_MSGS[2]); + + assertArrayEquals(Hex.decode("272630ebeabe7c3a"), sess.serverKeyMaterial()); + assertArrayEquals(Hex.decode("4d4d27b9"), sess.serverNonce()); + } + + @Test + void handshake3CCreatesSeqCryptsWithDerivedKey() throws Exception { + Session sess = new Session(null, keyDb()); + sess.handshake0S(PUMP_TEST_MSGS[0]); + sess.handshake1C(PUMP_TEST_MSGS[1]); + sess.handshake2S(PUMP_TEST_MSGS[2]); + sess.handshake3C(PUMP_TEST_MSGS[3]); + + byte[] expectedKey = Hex.decode("99ab5c7c113f85eefeb921da4094a886"); + byte[] expectedNonce = Hex.decode("6ee8854d4d4d27b9"); + + assertArrayEquals(expectedKey, sess.clientCrypt().key()); + assertArrayEquals(expectedNonce, sess.clientCrypt().nonce()); + assertEquals(0L, sess.clientCrypt().getTxSeq()); + assertEquals(0L, sess.clientCrypt().getRxSeq()); + + assertArrayEquals(expectedKey, sess.serverCrypt().key()); + assertEquals(1L, sess.serverCrypt().getTxSeq()); + assertEquals(1L, sess.serverCrypt().getRxSeq()); + } + + @Test + void handshake4SDecryptsAndReturnsFalseWithoutClientKeyDb() throws Exception { + Session sess = new Session(null, keyDb()); + sess.handshake0S(PUMP_TEST_MSGS[0]); + sess.handshake1C(PUMP_TEST_MSGS[1]); + sess.handshake2S(PUMP_TEST_MSGS[2]); + sess.handshake3C(PUMP_TEST_MSGS[3]); + boolean ok = sess.handshake4S(PUMP_TEST_MSGS[4]); + assertFalse(ok, "server-only session has no verifier keys for handshake_4_s"); + assertEquals(3L, sess.serverCrypt().getRxSeq()); + } + + @Test + void handshake5CVerifiesClientPermit() throws Exception { + Session sess = new Session(null, keyDb()); + sess.handshake0S(PUMP_TEST_MSGS[0]); + sess.handshake1C(PUMP_TEST_MSGS[1]); + sess.handshake2S(PUMP_TEST_MSGS[2]); + sess.handshake3C(PUMP_TEST_MSGS[3]); + sess.handshake4S(PUMP_TEST_MSGS[4]); + boolean ok = sess.handshake5C(PUMP_TEST_MSGS[5]); + assertTrue(ok, "client permit must verify against server static keys"); + assertEquals(2L, sess.clientCrypt().getRxSeq()); + } + + @Test + void fullHandshakeMatchesCapturedFinalState() throws Exception { + Session sess = new Session(null, keyDb()); + sess.handshake0S(PUMP_TEST_MSGS[0]); + sess.handshake1C(PUMP_TEST_MSGS[1]); + sess.handshake2S(PUMP_TEST_MSGS[2]); + sess.handshake3C(PUMP_TEST_MSGS[3]); + assertFalse(sess.handshake4S(PUMP_TEST_MSGS[4])); + assertTrue(sess.handshake5C(PUMP_TEST_MSGS[5])); + + assertEquals(2L, sess.clientCrypt().getRxSeq()); + assertEquals(3L, sess.serverCrypt().getRxSeq()); + } + + @Test + void handshake2SThrowsOnTamperedMac() throws Exception { + Session sess = new Session(null, keyDb()); + sess.handshake0S(PUMP_TEST_MSGS[0]); + sess.handshake1C(PUMP_TEST_MSGS[1]); + byte[] tampered = PUMP_TEST_MSGS[2].clone(); + tampered[0] ^= (byte) 0x01; + assertThrows(MacFailureException.class, () -> sess.handshake2S(tampered)); + } +} diff --git a/lib/src/test/java/org/openminimed/sake/crypto/AesCmacTest.java b/lib/src/test/java/org/openminimed/sake/crypto/AesCmacTest.java new file mode 100644 index 0000000..2c6e9d5 --- /dev/null +++ b/lib/src/test/java/org/openminimed/sake/crypto/AesCmacTest.java @@ -0,0 +1,103 @@ +package org.openminimed.sake.crypto; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.openminimed.sake.Hex; + +/** Known-answer tests from RFC 4493 (AES-CMAC) Appendix. */ +class AesCmacTest { + + private static final byte[] KEY = Hex.decode("2b7e151628aed2a6abf7158809cf4f3c"); + + @Test + void rfc4493ExampleEmpty() { + byte[] expected = Hex.decode("bb1d6929e95937287fa37d129b756746"); + AesCmac cmac = new AesCmac(KEY, 16); + cmac.update(new byte[0]); + assertArrayEquals(expected, cmac.digest()); + } + + @Test + void rfc4493ExampleOneBlock() { + byte[] msg = Hex.decode("6bc1bee22e409f96e93d7e117393172a"); + byte[] expected = Hex.decode("070a16b46b4d4144f79bdd9dd04a287c"); + AesCmac cmac = new AesCmac(KEY, 16); + cmac.update(msg); + assertArrayEquals(expected, cmac.digest()); + } + + @Test + void rfc4493ExampleFortyBytes() { + byte[] msg = + Hex.decode( + "6bc1bee22e409f96e93d7e117393172a" + + "ae2d8a571e03ac9c9eb76fac45af8e51" + + "30c81c46a35ce411"); + byte[] expected = Hex.decode("dfa66747de9ae63030ca32611497c827"); + AesCmac cmac = new AesCmac(KEY, 16); + cmac.update(msg); + assertArrayEquals(expected, cmac.digest()); + } + + @Test + void rfc4493ExampleSixtyFourBytes() { + byte[] msg = + Hex.decode( + "6bc1bee22e409f96e93d7e117393172a" + + "ae2d8a571e03ac9c9eb76fac45af8e51" + + "30c81c46a35ce411e5fbc1191a0a52ef" + + "f69f2445df4f9b17ad2b417be66c3710"); + byte[] expected = Hex.decode("51f0bebf7e3b9d92fc49741779363cfe"); + AesCmac cmac = new AesCmac(KEY, 16); + cmac.update(msg); + assertArrayEquals(expected, cmac.digest()); + } + + @Test + void truncationToFourBytes() { + byte[] msg = Hex.decode("6bc1bee22e409f96e93d7e117393172a"); + byte[] full = Hex.decode("070a16b46b4d4144f79bdd9dd04a287c"); + AesCmac cmac = new AesCmac(KEY, 4); + cmac.update(msg); + byte[] truncated = cmac.digest(); + assertEquals(4, truncated.length); + for (int i = 0; i < 4; i++) { + assertEquals(full[i], truncated[i]); + } + } + + @Test + void truncationToEightBytes() { + byte[] msg = Hex.decode("6bc1bee22e409f96e93d7e117393172a"); + byte[] full = Hex.decode("070a16b46b4d4144f79bdd9dd04a287c"); + AesCmac cmac = new AesCmac(KEY, 8); + cmac.update(msg); + byte[] truncated = cmac.digest(); + assertEquals(8, truncated.length); + for (int i = 0; i < 8; i++) { + assertEquals(full[i], truncated[i]); + } + } + + @Test + void verifyAcceptsMatchingTag() { + byte[] msg = Hex.decode("6bc1bee22e409f96e93d7e117393172a"); + byte[] tag = Hex.decode("070a16b46b4d4144"); + AesCmac cmac = new AesCmac(KEY, 8); + cmac.update(msg); + assertTrue(cmac.verify(tag)); + } + + @Test + void verifyRejectsTamperedTag() { + byte[] msg = Hex.decode("6bc1bee22e409f96e93d7e117393172a"); + byte[] tag = Hex.decode("070a16b46b4d4145"); + AesCmac cmac = new AesCmac(KEY, 8); + cmac.update(msg); + assertFalse(cmac.verify(tag)); + } +} diff --git a/lib/src/test/java/org/openminimed/sake/crypto/AesCtrTest.java b/lib/src/test/java/org/openminimed/sake/crypto/AesCtrTest.java new file mode 100644 index 0000000..d5ccaed --- /dev/null +++ b/lib/src/test/java/org/openminimed/sake/crypto/AesCtrTest.java @@ -0,0 +1,60 @@ +package org.openminimed.sake.crypto; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; +import org.openminimed.sake.Hex; + +/** Known-answer tests from NIST SP 800-38A Appendix F.5 (AES-128 CTR). */ +class AesCtrTest { + + private static final byte[] KEY = Hex.decode("2b7e151628aed2a6abf7158809cf4f3c"); + private static final byte[] INITIAL_COUNTER = Hex.decode("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"); + + @Test + void encryptsNistMultiBlockStream() { + byte[] plain = + Hex.decode( + "6bc1bee22e409f96e93d7e117393172a" + + "ae2d8a571e03ac9c9eb76fac45af8e51" + + "30c81c46a35ce411e5fbc1191a0a52ef" + + "f69f2445df4f9b17ad2b417be66c3710"); + byte[] expected = + Hex.decode( + "874d6191b620e3261bef6864990db6ce" + + "9806f66b7970fdff8617187bb9fffdff" + + "5ae4df3edbd5d35e5b4f09020db03eab" + + "1e031dda2fbe03d1792170a0f3009cee"); + assertArrayEquals(expected, AesCtr.crypt(KEY, INITIAL_COUNTER, plain)); + } + + @Test + void encryptDecryptIsSymmetric() { + byte[] plain = Hex.decode("6bc1bee22e409f96e93d7e117393172a"); + byte[] cipher = AesCtr.crypt(KEY, INITIAL_COUNTER, plain); + byte[] recovered = AesCtr.crypt(KEY, INITIAL_COUNTER, cipher); + assertArrayEquals(plain, recovered); + } + + @Test + void encryptsPartialBlock() { + byte[] plain = Hex.decode("6bc1bee22e409f96e93d7e1173"); + byte[] cipher = AesCtr.crypt(KEY, INITIAL_COUNTER, plain); + byte[] recovered = AesCtr.crypt(KEY, INITIAL_COUNTER, cipher); + assertArrayEquals(plain, recovered); + } + + @Test + void rejectsWrongIvLength() { + assertThrows( + IllegalArgumentException.class, () -> AesCtr.crypt(KEY, new byte[15], new byte[0])); + } + + @Test + void rejectsWrongKeyLength() { + assertThrows( + IllegalArgumentException.class, + () -> AesCtr.crypt(new byte[24], INITIAL_COUNTER, new byte[0])); + } +} diff --git a/lib/src/test/java/org/openminimed/sake/crypto/AesEcbTest.java b/lib/src/test/java/org/openminimed/sake/crypto/AesEcbTest.java new file mode 100644 index 0000000..e8b42e4 --- /dev/null +++ b/lib/src/test/java/org/openminimed/sake/crypto/AesEcbTest.java @@ -0,0 +1,46 @@ +package org.openminimed.sake.crypto; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; +import org.openminimed.sake.Hex; + +/** Known-answer tests from NIST SP 800-38A Appendix F.1 (AES-128 ECB). */ +class AesEcbTest { + + private static final byte[] KEY = Hex.decode("2b7e151628aed2a6abf7158809cf4f3c"); + + @Test + void encryptsFirstNistBlock() { + byte[] plain = Hex.decode("6bc1bee22e409f96e93d7e117393172a"); + byte[] expected = Hex.decode("3ad77bb40d7a3660a89ecaf32466ef97"); + assertArrayEquals(expected, AesEcb.encryptBlock(KEY, plain)); + } + + @Test + void encryptsSecondNistBlock() { + byte[] plain = Hex.decode("ae2d8a571e03ac9c9eb76fac45af8e51"); + byte[] expected = Hex.decode("f5d3d58503b9699de785895a96fdbaaf"); + assertArrayEquals(expected, AesEcb.encryptBlock(KEY, plain)); + } + + @Test + void decryptsFirstNistBlock() { + byte[] cipher = Hex.decode("3ad77bb40d7a3660a89ecaf32466ef97"); + byte[] expected = Hex.decode("6bc1bee22e409f96e93d7e117393172a"); + assertArrayEquals(expected, AesEcb.decryptBlock(KEY, cipher)); + } + + @Test + void rejectsWrongKeyLength() { + byte[] plain = new byte[16]; + assertThrows( + IllegalArgumentException.class, () -> AesEcb.encryptBlock(new byte[15], plain)); + } + + @Test + void rejectsWrongBlockLength() { + assertThrows(IllegalArgumentException.class, () -> AesEcb.encryptBlock(KEY, new byte[15])); + } +} diff --git a/lib/src/test/java/org/openminimed/sake/package-info.java b/lib/src/test/java/org/openminimed/sake/package-info.java new file mode 100644 index 0000000..3862efc --- /dev/null +++ b/lib/src/test/java/org/openminimed/sake/package-info.java @@ -0,0 +1,2 @@ +/** Unit tests for the SAKE handshake state machine. */ +package org.openminimed.sake; diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..74a9e59 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,3 @@ +rootProject.name = "JavaSake" + +include(":lib")