├── .gitignore ├── state-model.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitmodules ├── .travis.yml ├── src └── main │ └── java │ └── com │ └── ledger │ └── u2f │ ├── FIDOUtils.java │ ├── FIDOAPI.java │ ├── Secp256r1.java │ ├── FIDOStandalone.java │ └── U2FApplet.java ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | build/ -------------------------------------------------------------------------------- /state-model.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LedgerHQ/ledger-u2f-javacard/HEAD/state-model.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LedgerHQ/ledger-u2f-javacard/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "libs-sdks"] 2 | path = libs-sdks 3 | url = https://github.com/martinpaljak/oracle_javacard_sdks.git 4 | [submodule "libs"] 5 | path = libs 6 | url = https://github.com/J08nY/javacard-libs 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | jdk: 4 | - oraclejdk8 5 | 6 | script: 7 | - ./gradlew check --info 8 | - ./gradlew buildJavaCard --info 9 | - ./gradlew jacocoTestReport 10 | 11 | after_success: 12 | - bash <(curl -s https://codecov.io/bash) 13 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Dec 10 20:07:32 CET 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-all.zip 7 | -------------------------------------------------------------------------------- /src/main/java/com/ledger/u2f/FIDOUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************************* 3 | * FIDO U2F Authenticator 4 | * (c) 2015 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************* 18 | */ 19 | 20 | package com.ledger.u2f; 21 | 22 | /** 23 | * Utlity functions. 24 | */ 25 | public class FIDOUtils { 26 | 27 | /** 28 | * Comparison resistant to timing analysis. 29 | * @param array1 30 | * @param array1Offset 31 | * @param array2 32 | * @param array2Offset 33 | * @param length 34 | * @return true if the indicated number of bytes of the arrays starting at given offsets are equal 35 | */ 36 | public static boolean compareConstantTime(byte[] array1, short array1Offset, byte[] array2, short array2Offset, short length) { 37 | short givenLength = length; 38 | byte status = (byte) 0; 39 | short counter = (short) 0; 40 | 41 | if (length == 0) { 42 | return false; 43 | } 44 | while ((length--) != 0) { 45 | status |= (byte) ((array1[(short) (array1Offset + length)]) ^ (array2[(short) (array2Offset + length)])); 46 | counter++; 47 | } 48 | if (counter != givenLength) { 49 | return false; 50 | } 51 | return (status == 0); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /src/main/java/com/ledger/u2f/FIDOAPI.java: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************************* 3 | * FIDO U2F Authenticator 4 | * (c) 2015 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************* 18 | */ 19 | 20 | package com.ledger.u2f; 21 | 22 | import javacard.security.ECPrivateKey; 23 | 24 | public interface FIDOAPI { 25 | /** 26 | * Generate a new KeyPair over NIST P-256, for application of applicationParameter, export the 27 | * public key into publicKey at publicKeyOffset and export the wrapped private key 28 | * and application parameter into the keyHandle at keyHandleOffset. 29 | * 30 | * @param applicationParameter 31 | * @param applicationParameterOffset 32 | * @param generatedPrivateKey not used 33 | * @param publicKey 34 | * @param publicKeyOffset 35 | * @param keyHandle output array 36 | * @param keyHandleOffset offset into output array 37 | * @return always 64 38 | */ 39 | short generateKeyAndWrap(byte[] applicationParameter, short applicationParameterOffset, ECPrivateKey generatedPrivateKey, byte[] publicKey, short publicKeyOffset, byte[] keyHandle, short keyHandleOffset); 40 | 41 | /** 42 | * Unwrap a keyHandle at keyHandleOffset with keyHandleLength and set 43 | * the unwrapped private key into unwrappedPrivateKey if the unwrapping was successful (if 44 | * applicationParameter at applicationParameterOffset was the same as the unwrapped one). 45 | * 46 | * @param keyHandle 47 | * @param keyHandleOffset 48 | * @param keyHandleLength not used, assumed 64 49 | * @param applicationParameter application to compare with 50 | * @param applicationParameterOffset 51 | * @param unwrappedPrivateKey output variable 52 | * @return true if a valid key belonging to the indicated application is obtained 53 | */ 54 | boolean unwrap(byte[] keyHandle, short keyHandleOffset, short keyHandleLength, byte[] applicationParameter, short applicationParameterOffset, ECPrivateKey unwrappedPrivateKey); 55 | } 56 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Ledger U2F Applet 2 | ================= 3 | 4 | [![Build status](https://travis-ci.org/LedgerHQ/ledger-u2f-javacard.svg?branch=master)](https://travis-ci.org/LedgerHQ/ledger-u2f-javacard) [![Codecov](https://img.shields.io/codecov/c/github/ledgerhq/ledger-u2f-javacard.svg)](https://codecov.io/gh/ledgerhq/ledger-u2f-javacard) 5 | 6 | # Overview 7 | 8 | This applet is a Java Card implementation of the [FIDO Alliance U2F standard](https://fidoalliance.org/) 9 | 10 | It uses no proprietary vendor API and is freely available on [Ledger Unplugged](https://www.ledgerwallet.com/products/6-ledger-unplugged) and for a small fee on other Fidesmo devices through [Fidesmo store](http://www.fidesmo.com/apps/4f97a2e9) 11 | 12 | # Building 13 | 14 | - Set the environment variable `JC_HOME` to the folder containg the [Java Card Development Kit 3.0.2](http://www.oracle.com/technetwork/java/embedded/javacard/downloads/index.html) 15 | - Run `gradlew convertJavacard` 16 | 17 | # Installing 18 | 19 | Either load the CAP file using your favorite third party software or refer to [Fidesmo Gradle Plugin](https://github.com/fidesmo/gradle-javacard) to use on the Fidesmo platform 20 | 21 | 22 | The following install parameters are expected : 23 | 24 | - 1 byte flag : provide 01 to pass the current [Fido NFC interoperability tests](https://github.com/google/u2f-ref-code/tree/master/u2f-tests), or 00 25 | - 2 bytes length (big endian encoded) : length of the attestation certificate to load, supposed to be using a private key on the P-256 curve 26 | - 32 bytes : private key of the attestation certificate 27 | 28 | Before using the applet, the attestation certificate shall be loaded using a proprietary APDU 29 | 30 | | CLA | INS | P1 | P2 | Data | 31 | | --- | --- | ------------- | ------------ | ----------------------- | 32 | | F0 | 01 | offset (high) | offset (low) | Certificate data chunk | 33 | 34 | # Testing on Android 35 | 36 | - Download [Google Authenticator](https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2) 37 | - Test on http://u2fdemo.appspot.com or https://demo.yubico.com/u2f from Chrome 38 | - For additional API reference and implementations, check [the reference code](https://github.com/google/u2f-ref-code), the [beta NFC API](https://github.com/google/u2f-ref-code/blob/no-extension/u2f-gae-demo/war/js/u2f-api.js) and [Yubico guide](https://www.yubico.com/applications/fido/) 39 | 40 | # Certification 41 | 42 | This implementation has been certified FIDO U2F compliant on December 17, 2015 (U2F100020151217001). See tag [u2f-certif-171215](https://github.com/LedgerHQ/ledger-u2f-javacard/tree/u2f-certif-171215) 43 | 44 | # State model 45 | 46 | ![state model diagram](state-model.png) 47 | 48 | # License 49 | 50 | This application is licensed under [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0) 51 | 52 | # Contact 53 | 54 | Please contact hello@ledger.fr for any question 55 | 56 | -------------------------------------------------------------------------------- /src/main/java/com/ledger/u2f/Secp256r1.java: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************************* 3 | * FIDO U2F Authenticator 4 | * (c) 2015 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************* 18 | */ 19 | 20 | package com.ledger.u2f; 21 | 22 | import javacard.security.ECKey; 23 | 24 | public class Secp256r1 { 25 | 26 | // Nice SECp256r1 constants, only available during NIST opening hours 27 | 28 | private static final byte SECP256R1_FP[] = { 29 | (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x00, (byte) 0x00, 30 | (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, 31 | (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, 32 | (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 33 | (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 34 | (byte) 0xff, (byte) 0xff 35 | }; 36 | private static final byte SECP256R1_A[] = { 37 | (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x00, (byte) 0x00, 38 | (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, 39 | (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, 40 | (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 41 | (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 42 | (byte) 0xff, (byte) 0xfc 43 | }; 44 | private static final byte SECP256R1_B[] = { 45 | (byte) 0x5a, (byte) 0xc6, (byte) 0x35, (byte) 0xd8, (byte) 0xaa, (byte) 0x3a, 46 | (byte) 0x93, (byte) 0xe7, (byte) 0xb3, (byte) 0xeb, (byte) 0xbd, (byte) 0x55, 47 | (byte) 0x76, (byte) 0x98, (byte) 0x86, (byte) 0xbc, (byte) 0x65, (byte) 0x1d, 48 | (byte) 0x06, (byte) 0xb0, (byte) 0xcc, (byte) 0x53, (byte) 0xb0, (byte) 0xf6, 49 | (byte) 0x3b, (byte) 0xce, (byte) 0x3c, (byte) 0x3e, (byte) 0x27, (byte) 0xd2, 50 | (byte) 0x60, (byte) 0x4b 51 | }; 52 | private static final byte SECP256R1_G[] = { 53 | (byte) 0x04, 54 | (byte) 0x6b, (byte) 0x17, (byte) 0xd1, (byte) 0xf2, (byte) 0xe1, (byte) 0x2c, 55 | (byte) 0x42, (byte) 0x47, (byte) 0xf8, (byte) 0xbc, (byte) 0xe6, (byte) 0xe5, 56 | (byte) 0x63, (byte) 0xa4, (byte) 0x40, (byte) 0xf2, (byte) 0x77, (byte) 0x03, 57 | (byte) 0x7d, (byte) 0x81, (byte) 0x2d, (byte) 0xeb, (byte) 0x33, (byte) 0xa0, 58 | (byte) 0xf4, (byte) 0xa1, (byte) 0x39, (byte) 0x45, (byte) 0xd8, (byte) 0x98, 59 | (byte) 0xc2, (byte) 0x96, 60 | (byte) 0x4f, (byte) 0xe3, (byte) 0x42, (byte) 0xe2, (byte) 0xfe, (byte) 0x1a, 61 | (byte) 0x7f, (byte) 0x9b, (byte) 0x8e, (byte) 0xe7, (byte) 0xeb, (byte) 0x4a, 62 | (byte) 0x7c, (byte) 0x0f, (byte) 0x9e, (byte) 0x16, (byte) 0x2b, (byte) 0xce, 63 | (byte) 0x33, (byte) 0x57, (byte) 0x6b, (byte) 0x31, (byte) 0x5e, (byte) 0xce, 64 | (byte) 0xcb, (byte) 0xb6, (byte) 0x40, (byte) 0x68, (byte) 0x37, (byte) 0xbf, 65 | (byte) 0x51, (byte) 0xf5 66 | }; 67 | private static final byte SECP256R1_R[] = { 68 | (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x00, (byte) 0x00, 69 | (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 70 | (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xbc, (byte) 0xe6, 71 | (byte) 0xfa, (byte) 0xad, (byte) 0xa7, (byte) 0x17, (byte) 0x9e, (byte) 0x84, 72 | (byte) 0xf3, (byte) 0xb9, (byte) 0xca, (byte) 0xc2, (byte) 0xfc, (byte) 0x63, 73 | (byte) 0x25, (byte) 0x51 74 | }; 75 | private static final byte SECP256R1_K = (byte) 0x01; 76 | 77 | protected static boolean setCommonCurveParameters(ECKey key) { 78 | try { 79 | key.setA(SECP256R1_A, (short) 0, (short) SECP256R1_A.length); 80 | key.setB(SECP256R1_B, (short) 0, (short) SECP256R1_B.length); 81 | key.setFieldFP(SECP256R1_FP, (short) 0, (short) SECP256R1_FP.length); 82 | key.setG(SECP256R1_G, (short) 0, (short) SECP256R1_G.length); 83 | key.setR(SECP256R1_R, (short) 0, (short) SECP256R1_R.length); 84 | key.setK(SECP256R1_K); 85 | return true; 86 | } catch (Exception e) { 87 | return false; 88 | } 89 | 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /src/main/java/com/ledger/u2f/FIDOStandalone.java: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************************* 3 | * FIDO U2F Authenticator 4 | * (c) 2015 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************* 18 | */ 19 | 20 | package com.ledger.u2f; 21 | 22 | import javacard.framework.JCSystem; 23 | import javacard.security.RandomData; 24 | import javacard.framework.Util; 25 | import javacard.security.*; 26 | import javacardx.crypto.Cipher; 27 | 28 | public class FIDOStandalone implements FIDOAPI { 29 | 30 | private KeyPair keyPair; 31 | private AESKey chipKey; 32 | private Cipher cipherEncrypt; 33 | private Cipher cipherDecrypt; 34 | private RandomData random; 35 | private byte[] scratch; 36 | 37 | private static final byte[] IV_ZERO_AES = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 38 | 39 | /** 40 | * Init cipher engines and allocate memory. 41 | */ 42 | public FIDOStandalone() { 43 | scratch = JCSystem.makeTransientByteArray((short) 64, JCSystem.CLEAR_ON_DESELECT); 44 | keyPair = new KeyPair( 45 | (ECPublicKey) KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PUBLIC, KeyBuilder.LENGTH_EC_FP_256, false), 46 | (ECPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PRIVATE, KeyBuilder.LENGTH_EC_FP_256, false)); 47 | Secp256r1.setCommonCurveParameters((ECKey) keyPair.getPrivate()); 48 | Secp256r1.setCommonCurveParameters((ECKey) keyPair.getPublic()); 49 | random = RandomData.getInstance(RandomData.ALG_KEYGENERATION); 50 | // Initialize the unique wrapping key 51 | chipKey = (AESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_AES, KeyBuilder.LENGTH_AES_256, false); 52 | random.nextBytes(scratch, (short) 0, (short) 32); 53 | chipKey.setKey(scratch, (short) 0); 54 | cipherEncrypt = Cipher.getInstance(Cipher.ALG_AES_BLOCK_128_CBC_NOPAD, false); 55 | cipherEncrypt.init(chipKey, Cipher.MODE_ENCRYPT, IV_ZERO_AES, (short) 0, (short) IV_ZERO_AES.length); 56 | cipherDecrypt = Cipher.getInstance(Cipher.ALG_AES_BLOCK_128_CBC_NOPAD, false); 57 | cipherDecrypt.init(chipKey, Cipher.MODE_DECRYPT, IV_ZERO_AES, (short) 0, (short) IV_ZERO_AES.length); 58 | } 59 | 60 | /** 61 | * Interleave two byte arrays into the target one, nibble by nibble. 62 | * Example: 63 | * array1 = [0x12, 0x34] 64 | * array2 = [0xab, 0xcd] 65 | * -> [0x1a, 0x2b, 0x3c, 0x4d] 66 | *

67 | * This is used to interleave the generated private key and the application parameter into two AES-CBC blocks, 68 | * as not doing so would result in the application parameter being encrypted as a block with an all zero IV which 69 | * would always result in the same first block for all generated private keys with the same application parameter 70 | * wrapped under the same wrapping key, which would break privacy of U2F. 71 | * 72 | * @param array1 73 | * @param array1Offset 74 | * @param array2 75 | * @param array2Offset 76 | * @param target 77 | * @param targetOffset 78 | * @param length 79 | */ 80 | private static void interleave(byte[] array1, short array1Offset, byte[] array2, short array2Offset, byte[] target, short targetOffset, short length) { 81 | for (short i = 0; i < length; i++) { 82 | short a = (short) (array1[(short) (array1Offset + i)] & 0xff); 83 | short b = (short) (array2[(short) (array2Offset + i)] & 0xff); 84 | target[(short) (targetOffset + 2 * i)] = (byte) ((short) (a & 0xf0) | (short) (b >> 4)); 85 | target[(short) (targetOffset + 2 * i + 1)] = (byte) ((short) ((a & 0x0f) << 4) | (short) (b & 0x0f)); 86 | } 87 | } 88 | 89 | /** 90 | * Deinterleave a byte array back into two arrays of half size. 91 | * Example: 92 | * src = [0x1a, 0x2b, 0x3c, 0x4d] 93 | * -> [0x12, 0x34] and [0xab, 0xcd] 94 | * 95 | * @param src 96 | * @param srcOffset 97 | * @param array1 98 | * @param array1Offset 99 | * @param array2 100 | * @param array2Offset 101 | * @param length 102 | */ 103 | private static void deinterleave(byte[] src, short srcOffset, byte[] array1, short array1Offset, byte[] array2, short array2Offset, short length) { 104 | for (short i = 0; i < length; i++) { 105 | short a = (short) (src[(short) (srcOffset + 2 * i)] & 0xff); 106 | short b = (short) (src[(short) (srcOffset + 2 * i + 1)] & 0xff); 107 | array1[(short) (array1Offset + i)] = (byte) ((short) (a & 0xf0) | (short) (b >> 4)); 108 | array2[(short) (array2Offset + i)] = (byte) (((short) (a & 0x0f) << 4) | (short) (b & 0x0f)); 109 | } 110 | } 111 | 112 | /* @override */ 113 | public short generateKeyAndWrap(byte[] applicationParameter, short applicationParameterOffset, ECPrivateKey generatedPrivateKey, byte[] publicKey, short publicKeyOffset, byte[] keyHandle, short keyHandleOffset) { 114 | // Generate a new pair 115 | keyPair.genKeyPair(); 116 | // Copy public key 117 | ((ECPublicKey) keyPair.getPublic()).getW(publicKey, publicKeyOffset); 118 | // Wrap keypair and application parameters 119 | ((ECPrivateKey) keyPair.getPrivate()).getS(scratch, (short) 0); 120 | interleave(applicationParameter, applicationParameterOffset, scratch, (short) 0, keyHandle, keyHandleOffset, (short) 32); 121 | cipherEncrypt.doFinal(keyHandle, keyHandleOffset, (short) 64, keyHandle, keyHandleOffset); 122 | Util.arrayFillNonAtomic(scratch, (short) 0, (short) 32, (byte) 0x00); 123 | return (short) 64; 124 | } 125 | 126 | /* @override */ 127 | public boolean unwrap(byte[] keyHandle, short keyHandleOffset, short keyHandleLength, byte[] applicationParameter, short applicationParameterOffset, ECPrivateKey unwrappedPrivateKey) { 128 | // Verify 129 | cipherDecrypt.doFinal(keyHandle, keyHandleOffset, (short) 64, keyHandle, keyHandleOffset); 130 | deinterleave(keyHandle, keyHandleOffset, scratch, (short) 0, scratch, (short) 32, (short) 32); 131 | if (!FIDOUtils.compareConstantTime(applicationParameter, applicationParameterOffset, scratch, (short) 0, (short) 32)) { 132 | Util.arrayFillNonAtomic(scratch, (short) 32, (short) 32, (byte) 0x00); 133 | Util.arrayFillNonAtomic(keyHandle, keyHandleOffset, (short) 64, (byte) 0x00); 134 | return false; 135 | } 136 | Util.arrayFillNonAtomic(keyHandle, keyHandleOffset, (short) 64, (byte) 0x00); 137 | if (unwrappedPrivateKey != null) { 138 | unwrappedPrivateKey.setS(scratch, (short) 32, (short) 32); 139 | } 140 | Util.arrayFillNonAtomic(scratch, (short) 32, (short) 32, (byte) 0x00); 141 | return true; 142 | } 143 | 144 | } 145 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /src/main/java/com/ledger/u2f/U2FApplet.java: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************************* 3 | * FIDO U2F Authenticator 4 | * (c) 2015 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************* 18 | */ 19 | 20 | package com.ledger.u2f; 21 | 22 | import javacard.framework.*; 23 | import javacard.security.CryptoException; 24 | import javacard.security.ECPrivateKey; 25 | import javacard.security.KeyBuilder; 26 | import javacard.security.Signature; 27 | import javacardx.apdu.ExtendedLength; 28 | 29 | /** 30 | * The FIDO U2F applet. 31 | */ 32 | public class U2FApplet extends Applet implements ExtendedLength { 33 | 34 | private byte flags; 35 | private byte[] counter; 36 | private byte[] scratchPersistent; 37 | private byte[] scratch; 38 | private byte[] attestationCertificate; 39 | private boolean attestationCertificateSet; 40 | private ECPrivateKey attestationPrivateKey; 41 | private ECPrivateKey localPrivateKey; 42 | private boolean localPrivateTransient; 43 | private boolean counterOverflowed; 44 | private Signature attestationSignature; 45 | private Signature localSignature; 46 | private FIDOAPI fidoImpl; 47 | 48 | private static final byte VERSION[] = {'U', '2', 'F', '_', 'V', '2'}; 49 | 50 | private static final byte FIDO_CLA = (byte) 0x00; 51 | private static final byte FIDO_INS_ENROLL = (byte) 0x01; 52 | private static final byte FIDO_INS_SIGN = (byte) 0x02; 53 | private static final byte FIDO_INS_VERSION = (byte) 0x03; 54 | private static final byte ISO_INS_GET_DATA = (byte) 0xC0; 55 | 56 | private static final byte PROPRIETARY_CLA = (byte) 0xF0; 57 | private static final byte FIDO_ADM_SET_ATTESTATION_CERT = (byte) 0x01; 58 | 59 | private static final byte SCRATCH_TRANSPORT_STATE = (byte) 0; 60 | private static final byte SCRATCH_CURRENT_OFFSET = (byte) 1; 61 | private static final byte SCRATCH_NONCERT_LENGTH = (byte) 3; 62 | private static final byte SCRATCH_INCLUDE_CERT = (byte) 5; 63 | private static final byte SCRATCH_SIGNATURE_LENGTH = (byte) 6; 64 | private static final byte SCRATCH_FULL_LENGTH = (byte) 8; 65 | private static final byte SCRATCH_PAD = (byte) 10; 66 | // Should hold 1 (version) + 65 (public key) + 1 (key handle length) + L (key handle) + largest signature 67 | private static final short ENROLL_FIXED_RESPONSE_SIZE = (short) (1 + 65 + 1); 68 | private static final short KEYHANDLE_MAX = (short) 64; // Update if you change the KeyHandle encoding implementation 69 | private static final short SIGNATURE_MAX = (short) 72; // DER encoding with negative R and S 70 | private static final short SCRATCH_PAD_SIZE = (short) (ENROLL_FIXED_RESPONSE_SIZE + KEYHANDLE_MAX + SIGNATURE_MAX); 71 | private static final short SCRATCH_PUBLIC_KEY_OFFSET = (short) (SCRATCH_PAD + 1); 72 | private static final short SCRATCH_KEY_HANDLE_LENGTH_OFFSET = (short) (SCRATCH_PAD + 66); 73 | private static final short SCRATCH_KEY_HANDLE_OFFSET = (short) (SCRATCH_PAD + 67); 74 | private static final short SCRATCH_SIGNATURE_OFFSET = (short) (SCRATCH_PAD + ENROLL_FIXED_RESPONSE_SIZE + KEYHANDLE_MAX); 75 | 76 | private static final byte TRANSPORT_NONE = (byte) 0; 77 | private static final byte TRANSPORT_EXTENDED = (byte) 1; 78 | private static final byte TRANSPORT_NOT_EXTENDED = (byte) 2; 79 | private static final byte TRANSPORT_NOT_EXTENDED_CERT = (byte) 3; 80 | private static final byte TRANSPORT_NOT_EXTENDED_SIGNATURE = (byte) 4; 81 | 82 | private static final byte P1_SIGN_OPERATION = (byte) 0x03; 83 | private static final byte P1_SIGN_CHECK_ONLY = (byte) 0x07; 84 | 85 | private static final byte ENROLL_LEGACY_VERSION = (byte) 0x05; 86 | private static final byte RFU_ENROLL_SIGNED_VERSION[] = {(byte) 0x00}; 87 | 88 | private static final short ENROLL_PUBLIC_KEY_OFFSET = (short) 1; 89 | private static final short ENROLL_KEY_HANDLE_LENGTH_OFFSET = (short) 66; 90 | private static final short ENROLL_KEY_HANDLE_OFFSET = (short) 67; 91 | private static final short APDU_CHALLENGE_OFFSET = (short) 0; 92 | private static final short APDU_APPLICATION_PARAMETER_OFFSET = (short) 32; 93 | 94 | private static final byte FLAG_USER_PRESENCE_VERIFIED = (byte) 0x01; 95 | 96 | private static final short FIDO_SW_TEST_OF_PRESENCE_REQUIRED = ISO7816.SW_CONDITIONS_NOT_SATISFIED; 97 | private static final short FIDO_SW_INVALID_KEY_HANDLE = ISO7816.SW_WRONG_DATA; 98 | 99 | private static final byte INSTALL_FLAG_DISABLE_USER_PRESENCE = (byte) 0x01; 100 | 101 | /** 102 | * Applet setup which sets flags, attestation certificate length and private attestation key. 103 | * Structure of the parameters array (starting at parametersOffset): 104 | * flags (1 byte), length of attestation certificate (2 bytes big endian short), private attestation key (32 bytes). 105 | * @param parameters 106 | * @param parametersOffset 107 | * @param parametersLength always 35 108 | */ 109 | public U2FApplet(byte[] parameters, short parametersOffset, byte parametersLength) { 110 | if (parametersLength != 35) { 111 | ISOException.throwIt(ISO7816.SW_WRONG_DATA); 112 | } 113 | counter = new byte[4]; 114 | scratchPersistent = JCSystem.makeTransientByteArray((short) 1, JCSystem.CLEAR_ON_RESET); 115 | scratch = JCSystem.makeTransientByteArray((short) (SCRATCH_PAD + SCRATCH_PAD_SIZE), JCSystem.CLEAR_ON_DESELECT); 116 | try { 117 | // ok, let's save RAM 118 | localPrivateKey = (ECPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PRIVATE_TRANSIENT_DESELECT, KeyBuilder.LENGTH_EC_FP_256, false); 119 | localPrivateTransient = true; 120 | } catch (CryptoException e) { 121 | try { 122 | // ok, let's save a bit less RAM 123 | localPrivateKey = (ECPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PRIVATE_TRANSIENT_RESET, KeyBuilder.LENGTH_EC_FP_256, false); 124 | localPrivateTransient = true; 125 | } catch (CryptoException e1) { 126 | // ok, let's test the flash wear leveling \o/ 127 | localPrivateKey = (ECPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PRIVATE, KeyBuilder.LENGTH_EC_FP_256, false); 128 | Secp256r1.setCommonCurveParameters(localPrivateKey); 129 | } 130 | } 131 | attestationSignature = Signature.getInstance(Signature.ALG_ECDSA_SHA_256, false); 132 | localSignature = Signature.getInstance(Signature.ALG_ECDSA_SHA_256, false); 133 | flags = parameters[parametersOffset]; 134 | attestationCertificate = new byte[Util.getShort(parameters, (short) (parametersOffset + 1))]; 135 | attestationPrivateKey = (ECPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PRIVATE, KeyBuilder.LENGTH_EC_FP_256, false); 136 | Secp256r1.setCommonCurveParameters(attestationPrivateKey); 137 | attestationPrivateKey.setS(parameters, (short) (parametersOffset + 3), (short) 32); 138 | attestationSignature.init(attestationPrivateKey, Signature.MODE_SIGN); 139 | fidoImpl = new FIDOStandalone(); 140 | } 141 | 142 | /** 143 | * Handle the customs attestation cert command. 144 | * After it is all set, switch the flag that it is. 145 | * 146 | * @param apdu 147 | * @throws ISOException 148 | */ 149 | private void handleSetAttestationCert(APDU apdu) throws ISOException { 150 | byte[] buffer = apdu.getBuffer(); 151 | short len = apdu.setIncomingAndReceive(); 152 | short dataOffset = apdu.getOffsetCdata(); 153 | short copyOffset = Util.makeShort(buffer[ISO7816.OFFSET_P1], buffer[ISO7816.OFFSET_P2]); 154 | if ((short) (copyOffset + len) > (short) attestationCertificate.length) { 155 | ISOException.throwIt(ISO7816.SW_WRONG_DATA); 156 | } 157 | Util.arrayCopy(buffer, dataOffset, attestationCertificate, copyOffset, len); 158 | if ((short) (copyOffset + len) == (short) attestationCertificate.length) { 159 | attestationCertificateSet = true; 160 | } 161 | } 162 | 163 | /** 164 | * Handle U2F_REGISTER. 165 | * 166 | * @param apdu 167 | * @throws ISOException 168 | */ 169 | private void handleEnroll(APDU apdu) throws ISOException { 170 | byte[] buffer = apdu.getBuffer(); 171 | short len = apdu.setIncomingAndReceive(); 172 | short dataOffset = apdu.getOffsetCdata(); 173 | boolean extendedLength = (dataOffset != ISO7816.OFFSET_CDATA); 174 | short outOffset; 175 | // Enroll should be exactly 64 bytes 176 | if (len != 64) { 177 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 178 | } 179 | // Deny if user presence cannot be validated 180 | if ((flags & INSTALL_FLAG_DISABLE_USER_PRESENCE) == 0) { 181 | if (scratchPersistent[0] != 0) { 182 | ISOException.throwIt(FIDO_SW_TEST_OF_PRESENCE_REQUIRED); 183 | } 184 | } 185 | // Check if the counter overflowed 186 | if (counterOverflowed) { 187 | ISOException.throwIt(ISO7816.SW_FILE_FULL); 188 | } 189 | // Set user presence 190 | scratchPersistent[0] = (byte) 1; 191 | // Generate the key pair 192 | if (localPrivateTransient) { 193 | Secp256r1.setCommonCurveParameters(localPrivateKey); 194 | } 195 | short keyHandleLength = fidoImpl.generateKeyAndWrap(buffer, (short) (dataOffset + APDU_APPLICATION_PARAMETER_OFFSET), localPrivateKey, scratch, SCRATCH_PUBLIC_KEY_OFFSET, scratch, SCRATCH_KEY_HANDLE_OFFSET); 196 | scratch[SCRATCH_PAD] = ENROLL_LEGACY_VERSION; 197 | scratch[SCRATCH_KEY_HANDLE_LENGTH_OFFSET] = (byte) keyHandleLength; 198 | // Prepare the attestation 199 | attestationSignature.update(RFU_ENROLL_SIGNED_VERSION, (short) 0, (short) 1); 200 | attestationSignature.update(buffer, (short) (dataOffset + APDU_APPLICATION_PARAMETER_OFFSET), (short) 32); 201 | attestationSignature.update(buffer, (short) (dataOffset + APDU_CHALLENGE_OFFSET), (short) 32); 202 | attestationSignature.update(scratch, SCRATCH_KEY_HANDLE_OFFSET, keyHandleLength); 203 | attestationSignature.update(scratch, SCRATCH_PUBLIC_KEY_OFFSET, (short) 65); 204 | outOffset = (short) (ENROLL_PUBLIC_KEY_OFFSET + 65 + 1 + keyHandleLength); 205 | if (extendedLength) { 206 | // If using extended length, the message can be completed and sent immediately 207 | scratch[SCRATCH_TRANSPORT_STATE] = TRANSPORT_EXTENDED; 208 | outOffset = Util.arrayCopyNonAtomic(scratch, SCRATCH_PAD, buffer, (short) 0, outOffset); 209 | outOffset = Util.arrayCopyNonAtomic(attestationCertificate, (short) 0, buffer, outOffset, (short) attestationCertificate.length); 210 | short signatureSize = attestationSignature.sign(buffer, (short) 0, (short) 0, buffer, outOffset); 211 | outOffset += signatureSize; 212 | apdu.setOutgoingAndSend((short) 0, outOffset); 213 | } else { 214 | // Otherwise, keep the signature and proceed to send the first chunk 215 | short signatureSize = attestationSignature.sign(buffer, (short) 0, (short) 0, scratch, SCRATCH_SIGNATURE_OFFSET); 216 | scratch[SCRATCH_TRANSPORT_STATE] = TRANSPORT_NOT_EXTENDED; 217 | Util.setShort(scratch, SCRATCH_CURRENT_OFFSET, (short) 0); 218 | Util.setShort(scratch, SCRATCH_SIGNATURE_LENGTH, signatureSize); 219 | Util.setShort(scratch, SCRATCH_NONCERT_LENGTH, outOffset); 220 | Util.setShort(scratch, SCRATCH_FULL_LENGTH, (short) (outOffset + attestationCertificate.length + signatureSize)); 221 | scratch[SCRATCH_INCLUDE_CERT] = (byte) 1; 222 | handleGetData(apdu); 223 | } 224 | } 225 | 226 | /** 227 | * Handle U2F_AUTHENTICATE. 228 | * 229 | * @param apdu 230 | * @throws ISOException 231 | */ 232 | private void handleSign(APDU apdu) throws ISOException { 233 | byte[] buffer = apdu.getBuffer(); 234 | short len = apdu.setIncomingAndReceive(); 235 | short dataOffset = apdu.getOffsetCdata(); 236 | byte p1 = buffer[ISO7816.OFFSET_P1]; 237 | boolean sign = false; 238 | short keyHandleLength; 239 | boolean extendedLength = (dataOffset != ISO7816.OFFSET_CDATA); 240 | short outOffset = SCRATCH_PAD; 241 | if (len < 65) { 242 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 243 | } 244 | switch (p1) { 245 | case P1_SIGN_OPERATION: 246 | sign = true; 247 | break; 248 | case P1_SIGN_CHECK_ONLY: 249 | break; 250 | default: 251 | ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2); 252 | } 253 | // Check if the counter overflowed 254 | if (counterOverflowed) { 255 | ISOException.throwIt(ISO7816.SW_FILE_FULL); 256 | } 257 | // Verify key handle 258 | if (localPrivateTransient) { 259 | Secp256r1.setCommonCurveParameters(localPrivateKey); 260 | } 261 | keyHandleLength = (short) (buffer[(short) (dataOffset + 64)] & 0xff); 262 | if (!fidoImpl.unwrap(buffer, (short) (dataOffset + 65), keyHandleLength, buffer, (short) (dataOffset + APDU_APPLICATION_PARAMETER_OFFSET), (sign ? localPrivateKey : null))) { 263 | ISOException.throwIt(FIDO_SW_INVALID_KEY_HANDLE); 264 | } 265 | // If not signing, return with the "correct" exception 266 | if (!sign) { 267 | ISOException.throwIt(FIDO_SW_TEST_OF_PRESENCE_REQUIRED); 268 | } 269 | // If signing, only proceed if user presence can be validated 270 | if ((flags & INSTALL_FLAG_DISABLE_USER_PRESENCE) == 0) { 271 | if (scratchPersistent[0] != 0) { 272 | ISOException.throwIt(FIDO_SW_TEST_OF_PRESENCE_REQUIRED); 273 | } 274 | } 275 | scratchPersistent[0] = (byte) 1; 276 | // Increase the counter 277 | boolean carry = false; 278 | JCSystem.beginTransaction(); 279 | for (byte i = 0; i < 4; i++) { 280 | short addValue = (i == 0 ? (short) 1 : (short) 0); 281 | short val = (short) ((short) (counter[(short) (4 - 1 - i)] & 0xff) + addValue); 282 | if (carry) { 283 | val++; 284 | } 285 | carry = (val > 255); 286 | counter[(short) (4 - 1 - i)] = (byte) val; 287 | } 288 | JCSystem.commitTransaction(); 289 | if (carry) { 290 | // Game over 291 | counterOverflowed = true; 292 | ISOException.throwIt(ISO7816.SW_FILE_FULL); 293 | } 294 | // Prepare reply 295 | scratch[outOffset++] = FLAG_USER_PRESENCE_VERIFIED; 296 | outOffset = Util.arrayCopyNonAtomic(counter, (short) 0, scratch, outOffset, (short) 4); 297 | localSignature.init(localPrivateKey, Signature.MODE_SIGN); 298 | localSignature.update(buffer, (short) (dataOffset + APDU_APPLICATION_PARAMETER_OFFSET), (short) 32); 299 | localSignature.update(scratch, SCRATCH_PAD, (short) 5); 300 | outOffset += localSignature.sign(buffer, (short) (dataOffset + APDU_CHALLENGE_OFFSET), (short) 32, scratch, outOffset); 301 | if (extendedLength) { 302 | // If using extended length, the message can be completed and sent immediately 303 | scratch[SCRATCH_TRANSPORT_STATE] = TRANSPORT_EXTENDED; 304 | Util.arrayCopyNonAtomic(scratch, SCRATCH_PAD, buffer, (short) 0, outOffset); 305 | apdu.setOutgoingAndSend((short) 0, (short) (outOffset - SCRATCH_PAD)); 306 | } else { 307 | // Otherwise send the first chunk 308 | scratch[SCRATCH_TRANSPORT_STATE] = TRANSPORT_NOT_EXTENDED; 309 | Util.setShort(scratch, SCRATCH_CURRENT_OFFSET, (short) 0); 310 | Util.setShort(scratch, SCRATCH_SIGNATURE_LENGTH, (short) 0); 311 | Util.setShort(scratch, SCRATCH_NONCERT_LENGTH, (short) (outOffset - SCRATCH_PAD)); 312 | Util.setShort(scratch, SCRATCH_FULL_LENGTH, (short) (outOffset - SCRATCH_PAD)); 313 | scratch[SCRATCH_INCLUDE_CERT] = (byte) 0; 314 | handleGetData(apdu); 315 | } 316 | } 317 | 318 | /** 319 | * Handle U2F_GET_VERSION. 320 | * 321 | * @param apdu 322 | * @throws ISOException 323 | */ 324 | private void handleVersion(APDU apdu) throws ISOException { 325 | byte[] buffer = apdu.getBuffer(); 326 | Util.arrayCopyNonAtomic(VERSION, (short) 0, buffer, (short) 0, (short) VERSION.length); 327 | apdu.setOutgoingAndSend((short) 0, (short) VERSION.length); 328 | } 329 | 330 | /** 331 | * Handle the ISO7816 GET_DATA command. 332 | * Either send data from enrollment or authentication, what was last. 333 | * 334 | * @param apdu 335 | * @throws ISOException 336 | */ 337 | private void handleGetData(APDU apdu) throws ISOException { 338 | byte[] buffer = apdu.getBuffer(); 339 | short currentOffset = Util.getShort(scratch, SCRATCH_CURRENT_OFFSET); 340 | short fullLength = Util.getShort(scratch, SCRATCH_FULL_LENGTH); 341 | switch (scratch[SCRATCH_TRANSPORT_STATE]) { 342 | case TRANSPORT_NOT_EXTENDED: 343 | case TRANSPORT_NOT_EXTENDED_CERT: 344 | case TRANSPORT_NOT_EXTENDED_SIGNATURE: 345 | break; 346 | default: 347 | ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); 348 | } 349 | short requestedSize = apdu.setOutgoing(); 350 | short outOffset = (short) 0; 351 | if (scratch[SCRATCH_TRANSPORT_STATE] == TRANSPORT_NOT_EXTENDED) { 352 | short dataSize = Util.getShort(scratch, SCRATCH_NONCERT_LENGTH); 353 | short blockSize = ((short) (dataSize - currentOffset) > requestedSize ? requestedSize : (short) (dataSize - currentOffset)); 354 | Util.arrayCopyNonAtomic(scratch, (short) (SCRATCH_PAD + currentOffset), buffer, outOffset, blockSize); 355 | outOffset += blockSize; 356 | currentOffset += blockSize; 357 | fullLength -= blockSize; 358 | if (currentOffset == dataSize) { 359 | if (scratch[SCRATCH_INCLUDE_CERT] == (byte) 1) { 360 | scratch[SCRATCH_TRANSPORT_STATE] = TRANSPORT_NOT_EXTENDED_CERT; 361 | currentOffset = (short) 0; 362 | requestedSize -= blockSize; 363 | } else { 364 | scratch[SCRATCH_TRANSPORT_STATE] = TRANSPORT_NONE; 365 | } 366 | } 367 | } 368 | if ((scratch[SCRATCH_TRANSPORT_STATE] == TRANSPORT_NOT_EXTENDED_CERT) && (requestedSize != (short) 0)) { 369 | short blockSize = ((short) (attestationCertificate.length - currentOffset) > requestedSize ? requestedSize : (short) (attestationCertificate.length - currentOffset)); 370 | Util.arrayCopyNonAtomic(attestationCertificate, currentOffset, buffer, outOffset, blockSize); 371 | outOffset += blockSize; 372 | currentOffset += blockSize; 373 | fullLength -= blockSize; 374 | if (currentOffset == (short) attestationCertificate.length) { 375 | if (Util.getShort(scratch, SCRATCH_SIGNATURE_LENGTH) != (short) 0) { 376 | scratch[SCRATCH_TRANSPORT_STATE] = TRANSPORT_NOT_EXTENDED_SIGNATURE; 377 | currentOffset = (short) 0; 378 | requestedSize -= blockSize; 379 | } else { 380 | scratch[SCRATCH_TRANSPORT_STATE] = TRANSPORT_NONE; 381 | } 382 | } 383 | } 384 | if ((scratch[SCRATCH_TRANSPORT_STATE] == TRANSPORT_NOT_EXTENDED_SIGNATURE) && (requestedSize != (short) 0)) { 385 | short signatureSize = Util.getShort(scratch, SCRATCH_SIGNATURE_LENGTH); 386 | short blockSize = ((short) (signatureSize - currentOffset) > requestedSize ? requestedSize : (short) (signatureSize - currentOffset)); 387 | Util.arrayCopyNonAtomic(scratch, (short) (SCRATCH_SIGNATURE_OFFSET + currentOffset), buffer, outOffset, blockSize); 388 | outOffset += blockSize; 389 | currentOffset += blockSize; 390 | fullLength -= blockSize; 391 | } 392 | apdu.setOutgoingLength(outOffset); 393 | apdu.sendBytes((short) 0, outOffset); 394 | Util.setShort(scratch, SCRATCH_CURRENT_OFFSET, currentOffset); 395 | Util.setShort(scratch, SCRATCH_FULL_LENGTH, fullLength); 396 | if (fullLength > 256) { 397 | ISOException.throwIt(ISO7816.SW_BYTES_REMAINING_00); 398 | } else if (fullLength != 0) { 399 | ISOException.throwIt((short) (ISO7816.SW_BYTES_REMAINING_00 + fullLength)); 400 | } 401 | } 402 | 403 | /* @override */ 404 | public void process(APDU apdu) throws ISOException { 405 | byte[] buffer = apdu.getBuffer(); 406 | if (selectingApplet()) { 407 | if (attestationCertificateSet) { 408 | Util.arrayCopyNonAtomic(VERSION, (short) 0, buffer, (short) 0, (short) VERSION.length); 409 | apdu.setOutgoingAndSend((short) 0, (short) VERSION.length); 410 | } 411 | return; 412 | } 413 | if (buffer[ISO7816.OFFSET_CLA] == PROPRIETARY_CLA) { 414 | if (attestationCertificateSet) { 415 | ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); 416 | } 417 | switch (buffer[ISO7816.OFFSET_INS]) { 418 | case FIDO_ADM_SET_ATTESTATION_CERT: 419 | handleSetAttestationCert(apdu); 420 | break; 421 | default: 422 | ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); 423 | } 424 | } else if (buffer[ISO7816.OFFSET_CLA] == FIDO_CLA) { 425 | if (!attestationCertificateSet) { 426 | ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); 427 | } 428 | switch (buffer[ISO7816.OFFSET_INS]) { 429 | case FIDO_INS_ENROLL: 430 | handleEnroll(apdu); 431 | break; 432 | case FIDO_INS_SIGN: 433 | handleSign(apdu); 434 | break; 435 | case FIDO_INS_VERSION: 436 | handleVersion(apdu); 437 | break; 438 | case ISO_INS_GET_DATA: 439 | handleGetData(apdu); 440 | break; 441 | default: 442 | ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); 443 | } 444 | } else { 445 | ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); 446 | } 447 | } 448 | 449 | /* @override */ 450 | public static void install(byte bArray[], short bOffset, byte bLength) throws ISOException { 451 | short offset = bOffset; 452 | offset += (short) (bArray[offset] + 1); // instance 453 | offset += (short) (bArray[offset] + 1); // privileges 454 | new U2FApplet(bArray, (short) (offset + 1), bArray[offset]).register(bArray, (short) (bOffset + 1), bArray[bOffset]); 455 | } 456 | } 457 | 458 | --------------------------------------------------------------------------------