├── .gitmodules ├── utils └── iscctl │ ├── Pipfile │ ├── Pipfile.lock │ └── iscctl.py ├── .classpath ├── .project ├── .github └── workflows │ └── ant.yml ├── .gitignore ├── README.md ├── src └── main │ └── javacard │ └── illegal │ └── security │ └── chip │ ├── JediIdentity.java │ └── ISCApplet.java └── LICENSE.md /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "ext/sdks"] 2 | path = ext/sdks 3 | url = https://github.com/martinpaljak/oracle_javacard_sdks.git 4 | -------------------------------------------------------------------------------- /utils/iscctl/Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | name = "pypi" 3 | url = "https://pypi.org/simple" 4 | verify_ssl = true 5 | 6 | [dev-packages] 7 | 8 | [packages] 9 | pyscard = "*" 10 | pycryptodome = "*" 11 | 12 | [requires] 13 | python_version = "3.9" 14 | -------------------------------------------------------------------------------- /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | IllegalSecurityChip 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /.github/workflows/ant.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Ant 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-ant 3 | 4 | name: Java CI 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | pull_request: 10 | branches: [ "master" ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: 'Checkout' 19 | uses: actions/checkout@v3 20 | with: 21 | submodules: 'recursive' 22 | - name: Set up JDK 8 23 | uses: actions/setup-java@v3 24 | with: 25 | java-version: '8' 26 | distribution: 'temurin' 27 | - name: Build with Ant 28 | run: ant -noinput -buildfile build.xml 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.toptal.com/developers/gitignore/api/eclipse,java 2 | # Edit at https://www.toptal.com/developers/gitignore?templates=eclipse,java 3 | 4 | ### Eclipse ### 5 | .metadata 6 | bin/ 7 | tmp/ 8 | *.tmp 9 | *.bak 10 | *.swp 11 | *~.nib 12 | local.properties 13 | .settings/ 14 | .loadpath 15 | .recommenders 16 | 17 | # External tool builders 18 | .externalToolBuilders/ 19 | 20 | # Locally stored "Eclipse launch configurations" 21 | *.launch 22 | 23 | # PyDev specific (Python IDE for Eclipse) 24 | *.pydevproject 25 | 26 | # CDT-specific (C/C++ Development Tooling) 27 | .cproject 28 | 29 | # CDT- autotools 30 | .autotools 31 | 32 | # Java annotation processor (APT) 33 | .factorypath 34 | 35 | # PDT-specific (PHP Development Tools) 36 | .buildpath 37 | 38 | # sbteclipse plugin 39 | .target 40 | 41 | # Tern plugin 42 | .tern-project 43 | 44 | # TeXlipse plugin 45 | .texlipse 46 | 47 | # STS (Spring Tool Suite) 48 | .springBeans 49 | 50 | # Code Recommenders 51 | .recommenders/ 52 | 53 | # Annotation Processing 54 | .apt_generated/ 55 | .apt_generated_test/ 56 | 57 | # Scala IDE specific (Scala & Java development for Eclipse) 58 | .cache-main 59 | .scala_dependencies 60 | .worksheet 61 | 62 | # Uncomment this line if you wish to ignore the project description file. 63 | # Typically, this file would be tracked if it contains build/dependency configurations: 64 | #.project 65 | 66 | ### Eclipse Patch ### 67 | # Spring Boot Tooling 68 | .sts4-cache/ 69 | 70 | ### Java ### 71 | # Compiled class file 72 | *.class 73 | 74 | # Log file 75 | *.log 76 | 77 | # BlueJ files 78 | *.ctxt 79 | 80 | # Mobile Tools for Java (J2ME) 81 | .mtj.tmp/ 82 | 83 | # Package Files # 84 | *.jar 85 | *.war 86 | *.nar 87 | *.ear 88 | *.zip 89 | *.tar.gz 90 | *.rar 91 | 92 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 93 | hs_err_pid* 94 | 95 | # End of https://www.toptal.com/developers/gitignore/api/eclipse,java 96 | 97 | IllegalSecurityChip.cap 98 | ext/ant-javacard.jar 99 | -------------------------------------------------------------------------------- /utils/iscctl/Pipfile.lock: -------------------------------------------------------------------------------- 1 | { 2 | "_meta": { 3 | "hash": { 4 | "sha256": "5b34d3e209904ae1f9cb8a377ac8c571dc34bdb136ce75bdcb92253c7ff79ff2" 5 | }, 6 | "pipfile-spec": 6, 7 | "requires": { 8 | "python_version": "3.9" 9 | }, 10 | "sources": [ 11 | { 12 | "name": "pypi", 13 | "url": "https://pypi.org/simple", 14 | "verify_ssl": true 15 | } 16 | ] 17 | }, 18 | "default": { 19 | "pycryptodome": { 20 | "hashes": [ 21 | "sha256:19cb674df6c74a14b8b408aa30ba8a89bd1c01e23505100fb45f930fbf0ed0d9", 22 | "sha256:1cfdb92dca388e27e732caa72a1cc624520fe93752a665c3b6cd8f1a91b34916", 23 | "sha256:27397aee992af69d07502126561d851ba3845aa808f0e55c71ad0efa264dd7d4", 24 | "sha256:28f75e58d02019a7edc7d4135203d2501dfc47256d175c72c9798f9a129a49a7", 25 | "sha256:2a68df525b387201a43b27b879ce8c08948a430e883a756d6c9e3acdaa7d7bd8", 26 | "sha256:411745c6dce4eff918906eebcde78771d44795d747e194462abb120d2e537cd9", 27 | "sha256:46e96aeb8a9ca8b1edf9b1fd0af4bf6afcf3f1ca7fa35529f5d60b98f3e4e959", 28 | "sha256:4ed27951b0a17afd287299e2206a339b5b6d12de9321e1a1575261ef9c4a851b", 29 | "sha256:50826b49fbca348a61529693b0031cdb782c39060fb9dca5ac5dff858159dc5a", 30 | "sha256:5598dc6c9dbfe882904e54584322893eff185b98960bbe2cdaaa20e8a437b6e5", 31 | "sha256:5c3c4865730dfb0263f822b966d6d58429d8b1e560d1ddae37685fd9e7c63161", 32 | "sha256:5f19e6ef750f677d924d9c7141f54bade3cd56695bbfd8a9ef15d0378557dfe4", 33 | "sha256:60febcf5baf70c566d9d9351c47fbd8321da9a4edf2eff45c4c31c86164ca794", 34 | "sha256:62c488a21c253dadc9f731a32f0ac61e4e436d81a1ea6f7d1d9146ed4d20d6bd", 35 | "sha256:6d3baaf82681cfb1a842f1c8f77beac791ceedd99af911e4f5fabec32bae2259", 36 | "sha256:6e4227849e4231a3f5b35ea5bdedf9a82b3883500e5624f00a19156e9a9ef861", 37 | "sha256:6e89bb3826e6f84501e8e3b205c22595d0c5492c2f271cbb9ee1c48eb1866645", 38 | "sha256:70d807d11d508433daf96244ec1c64e55039e8a35931fc5ea9eee94dbe3cb6b5", 39 | "sha256:76b1a34d74bb2c91bce460cdc74d1347592045627a955e9a252554481c17c52f", 40 | "sha256:7798e73225a699651888489fbb1dbc565e03a509942a8ce6194bbe6fb582a41f", 41 | "sha256:834b790bbb6bd18956f625af4004d9c15eed12d5186d8e57851454ae76d52215", 42 | "sha256:843e5f10ecdf9d307032b8b91afe9da1d6ed5bb89d0bbec5c8dcb4ba44008e11", 43 | "sha256:8f9f84059039b672a5a705b3c5aa21747867bacc30a72e28bf0d147cc8ef85ed", 44 | "sha256:9000877383e2189dafd1b2fc68c6c726eca9a3cfb6d68148fbb72ccf651959b6", 45 | "sha256:910e202a557e1131b1c1b3f17a63914d57aac55cf9fb9b51644962841c3995c4", 46 | "sha256:946399d15eccebafc8ce0257fc4caffe383c75e6b0633509bd011e357368306c", 47 | "sha256:a199e9ca46fc6e999e5f47fce342af4b56c7de85fae893c69ab6aa17531fb1e1", 48 | "sha256:a3d8a9efa213be8232c59cdc6b65600276508e375e0a119d710826248fd18d37", 49 | "sha256:a4599c0ca0fc027c780c1c45ed996d5bef03e571470b7b1c7171ec1e1a90914c", 50 | "sha256:b4e6b269a8ddaede774e5c3adbef6bf452ee144e6db8a716d23694953348cd86", 51 | "sha256:b68794fba45bdb367eeb71249c26d23e61167510a1d0c3d6cf0f2f14636e62ee", 52 | "sha256:d7ec2bd8f57c559dd24e71891c51c25266a8deb66fc5f02cc97c7fb593d1780a", 53 | "sha256:e15bde67ccb7d4417f627dd16ffe2f5a4c2941ce5278444e884cb26d73ecbc61", 54 | "sha256:eb01f9997e4d6a8ec8a1ad1f676ba5a362781ff64e8189fe2985258ba9cb9706", 55 | "sha256:faa682c404c218e8788c3126c9a4b8fbcc54dc245b5b6e8ea5b46f3b63bd0c84" 56 | ], 57 | "index": "pypi", 58 | "version": "==3.9.9" 59 | }, 60 | "pyscard": { 61 | "hashes": [ 62 | "sha256:2abc34387ce5d1567a1052edc47797c1288739b51b664468d34ca77c9a3b05c2", 63 | "sha256:59cb506e8e793c397f3014f0933752df8d00c97c9f3a3385698e77213423962f", 64 | "sha256:60dbc52f00da90e3428e987679723588598579a7c3c757e9937cecd6e381ddd2", 65 | "sha256:6d6ddcf57f97b0899b952c1c0746177c4b4b52af2ca47eb4d6bd0b9096530181", 66 | "sha256:73945cd5a8c6e2e4982ba24d70fdba9e1b4ca68b82169337f4733823f7b49fb6", 67 | "sha256:852a4e354bb82cc1f68afb204349ca68ea6c5332242644a80651a5c62bb1ab5f", 68 | "sha256:b364d9d9186e793c1c4709eb72a4d29e09067d36ca463b2c2abd995bd1055779" 69 | ], 70 | "index": "pypi", 71 | "version": "==2.0.0" 72 | } 73 | }, 74 | "develop": {} 75 | } 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Illegal Security Chip 2 | 3 | This is super illegal even without a proper key. Please **DO NOT** use it. Otherwise $\*\*y will definitely sue you to death **IMMEDIATELY**!!!!!!!!!!!!111!!!! 4 | 5 | -- S** FUDs 6 | 7 | (LOL we somehow got mentioned on psxhax https://www.psxhax.com/threads/ps5tools-added-to-ps5-github-repository-by-skfu-invites-contributors.8264/) 8 | 9 | ## WTF? 10 | 11 | This is a JavaCard applet that emulates the [A7105 security chip](https://gist.github.com/dogtopus/dae307c7773e792150990a06e79583d0) found in PS4 licensed controllers (at APDU level). It signs random challenges (nonce) sent from the host using an on-card RSA 2048 key (DS4Key). When sending the signature back, it also presents some identifying information and the public key (both combined forms DS4ID) to the host. 12 | 13 | **LIABILITY NOTICE**: This applet enables **NEITHER** controller counterfeiting nor circumventing the PS4 peripheral authentication by default. It is **NOT** intended to be used for any illegal activities. The word "Illegal" in the project name is a joke in case you didn't get it already. No keys are provided for obvious reasons. Also I am not responsible for anything you will do with this applet. 14 | 15 | ## Card Requirements 16 | 17 | The card must satisfy all of the following in order to be able to install and run IllegalSecurityChip: 18 | 19 | - JavaCard API >= 3.0.1 (for `Signature.ALG_RSA_SHA_256_PKCS1_PSS`) 20 | - Properly implements `Signature.ALG_RSA_SHA_256_PKCS1_PSS` (Rare! Most random 3.0.1+ cards don't have this!) 21 | - Applet installation will fail with random error code (e.g. Applet installation error, unspecified error, condition not satisfied, or the "intended error code" function not supported) depending on the JavaCard implementation if this is not supported. 22 | - If the card does not support RSA 2048, it might fail with the same "function not supported". However this is much rarer (like who tf still make JavaCards that don't support RSA 2048 in 2020). 23 | - Approx. 512 bytes of transient memory. (Can be shrunk to just approx. 256 by merging the buffer used in `JediIdentity` with the top-level applet one) 24 | 25 | The only card I came across that has `Signature.ALG_RSA_SHA_256_PKCS1_PSS` implemented is J3H145, which seems to run JCOP 3.x. However I believe that JCOP 2.4.2 cards like J2D081 should also work since the original A7105 security chip seem to run the exact same OS and also conveniently offers JavaCard API 3.0.1. 26 | 27 | It should also be possible to install and run IllegalSecurityChip on a blank JCOP A710x (i.e. A710xCG). However I am unable to source such chip in manageable quantities and thus unable to test. 28 | 29 | In short, devices that work and are tested: 30 | 31 | - J3H145 from [SmartcardFocus](https://www.smartcardfocus.com/shop/ilp/id~879/nxp-j3h145-dual-interface-java-card-144k/p/index.shtml) 32 | 33 | Devices that might work but are untested: 34 | 35 | - J3D081 from ~~[SmartcardFocus](https://www.smartcardfocus.com/shop/ilp/id~688/j3d081-80k/p/index.shtml)~~ (No longer available on SmartcardFocus) 36 | - J2D081 (SIM cut) from Aliexpress (if properly pre-personalized which they don't always do. Always ask!) or [Futako (T=0)](https://www.javacardsdk.com/product/j2d081simt0/) 37 | - [Fidesmo Card v1.0](https://shop.fidesmo.com/products/fidesmo-card) (J3D145 NFC only) and [Fidesmo Card v2.0](https://shop.fidesmo.com/products/fidesmo-card-2-0) (J3H145 NFC only) 38 | - NXP A710xCG (e.g. on [Digi-key](https://www.digikey.com/en/products/detail/nxp-usa-inc/A7101CGTK2-T0B040X/7645426)) 39 | - G\&D SmartCafe Expert 7.0 Card/Security Dongle 40 | - https://www.commoncriteriaportal.org/files/epfiles/1028b_pdf.pdf section 8.1.1.2, FCS\_COP.1.1/RSA-CRT-SIGN: "The TSF shall perform signature generation in accordance with a specified cryptographic algorithm RSA-CRT and cryptographic key sizes 512 up to 4096 bit that meet the following: scheme 1 of \[ISO9796-2\] chapter 8, \[RSA\] (RSASSAPKCS1-v15) chapter 8, **\[RSASSA-PSS\]** and \[RSA-SHA-RFC2409\].") 41 | - J3R180 from [Futako](https://www.javacardsdk.com/product/j3r180sim/) and potentially other places. 42 | 43 | ## Building and Usage 44 | 45 | Simply run `ant` to build after checking out the submodules with `git submodule update --init --recursive` 46 | 47 | To install the applet with GlobalPlatformPro, use: 48 | 49 | ```sh 50 | gp --install IllegalSecurityChip.cap 51 | ``` 52 | 53 | ### Personalization Script 54 | 55 | IllegalSecurityChip comes with a personalization script under [utils/iscctl/](./utils/iscctl/). To use it, run 56 | 57 | ```sh 58 | pipenv install 59 | ``` 60 | 61 | then 62 | 63 | ```sh 64 | pipenv run ./iscctl.py --help 65 | ``` 66 | 67 | Refer to the built-in help for detailed usage. 68 | 69 | **NOTE**: This applet does not support atomic operations. That is, interrupting all operations that write data to the card (i.e. updating DS4ID/DS4Key and any of their parts) can corrupt the data and make the applet unusable. In this case you might need to run `nuke` command or reinstantiate the applet via GlobalPlatform. All data saved on the card that belong to this applet will be deleted permanently. 70 | 71 | #### Generating keys on-card 72 | 73 | ```sh 74 | pipenv run ./iscctl.py gen-key 75 | ``` 76 | 77 | #### Importing existing DS4Key 78 | 79 | ```sh 80 | pipenv run ./iscctl.py import-ds4key 81 | ``` 82 | 83 | **NOTE**: For those who are curious, DS4Key is basically the same format as `jedi_cert.bin`. Speaking more and the "Illegal" word in our name will no longer be a joke ;-). 84 | 85 | #### Testing authentication 86 | 87 | ```sh 88 | pipenv run ./iscctl.py test-auth [-c path-to-ca] [-p page-size] 89 | ``` 90 | 91 | This command should also work on A7105 security chip given proper bridge hardware between CCID over USB (or other protocol over other link supported by Microsoft Smart Card Base or pcsclite) and NXP SCI2C. 92 | 93 | If `page-size` is 0, iscctl will try to send/receive the whole challenge/response block in one single extended length APDU. Otherwise it will send/receive in chunks of `page-size` bytes. It is unknown whether extended length APDU or 0 `page-size` is actually supported by A7105 security chip so be careful when setting `page-size` to 0 when running `test-auth` on A7105. `page-size` is set to 0x80 by default. 94 | 95 | You can optionally specify the Jedi CA with the `-c` parameter so that iscctl will validate the signature of DS4ID on the card as well. 96 | 97 | #### Changing the DS4ID serial number 98 | 99 | ```sh 100 | pipenv run ./iscctl.py set-serial 101 | ``` 102 | 103 | Note that changing the serial number will void the signature and it needs to be re-signed before any future authentications. 104 | 105 | #### DS4ID signing using test CA 106 | 107 | If this is not obvious enough: Test CA is only for testing and will NOT work on real PS4 without the 8-minute timeout. 108 | 109 | First make sure that you generate the test CA key pair (no certificates needed, just the keys). The keys can be generated by using e.g. OpenSSL and they need to be encoded in plaintext PEM or DER format. Only RSA 2048 is supported since that is what $**y's DS4 authentication scheme was built on. 110 | 111 | To sign the DS4ID using the test CA, use 112 | 113 | ```sh 114 | pipenv run ./iscctl.py sign-ds4id -c 115 | ``` 116 | -------------------------------------------------------------------------------- /src/main/javacard/illegal/security/chip/JediIdentity.java: -------------------------------------------------------------------------------- 1 | package illegal.security.chip; 2 | 3 | import javacard.framework.ISO7816; 4 | import javacard.framework.ISOException; 5 | import javacard.framework.JCSystem; 6 | import javacard.framework.Util; 7 | import javacard.security.CryptoException; 8 | import javacard.security.KeyBuilder; 9 | import javacard.security.KeyPair; 10 | import javacard.security.RSAPrivateCrtKey; 11 | import javacard.security.RSAPublicKey; 12 | 13 | 14 | public class JediIdentity { 15 | private static final byte OFFSET_TMP_KEY = (byte) 0; 16 | private static final byte OFFSET_FLAG_TMP_KEY_TYPE = (byte) 1; 17 | 18 | private static final byte LEN_TMP = (byte) 2; 19 | 20 | public static final short RSA2048_INT_SIZE = (short) 0x100; 21 | public static final short RSA2048_E_SIZE_COMPAT = (short) 0x4; 22 | public static final short RSA2048_PQ_SIZE = (short) 0x80; 23 | 24 | public static final short LEN_ID_SERIAL = (short) 0x10; 25 | public static final short LEN_ID_PUB_N = RSA2048_INT_SIZE; 26 | public static final short LEN_ID_PUB_E = RSA2048_INT_SIZE; 27 | public static final short LEN_ID_PUB_E_COMPAT = RSA2048_E_SIZE_COMPAT; 28 | public static final short LEN_ID_SIG = RSA2048_INT_SIZE; 29 | 30 | public static final short KEY_TYPE_UNSPECIFIED = (short) 0; 31 | public static final short KEY_TYPE_PUB_N = (short) 1; 32 | public static final short KEY_TYPE_PUB_E = (short) 2; 33 | public static final short KEY_TYPE_PUB_SIG = (short) 3; 34 | public static final short KEY_TYPE_PRIV_P = (short) 4; 35 | public static final short KEY_TYPE_PRIV_Q = (short) 5; 36 | public static final short KEY_TYPE_PRIV_PQ = (short) 6; 37 | public static final short KEY_TYPE_PRIV_DP1 = (short) 7; 38 | public static final short KEY_TYPE_PRIV_DQ1 = (short) 8; 39 | public static final short KEY_TYPE_EXPORT_PUB_N = (short) 9; 40 | public static final short KEY_TYPE_EXPORT_PUB_E = (short) 10; 41 | public static final short KEY_TYPE_EXPORT_PUB_E_COMPAT = (short) 12; 42 | 43 | /** 44 | * Serial number of the security chip. 45 | */ 46 | private final byte[] serialNumber; 47 | /** 48 | * Controller-unique public key. 49 | */ 50 | private final RSAPublicKey cukPub; 51 | /** 52 | * Controller-unique private key. 53 | */ 54 | private final RSAPrivateCrtKey cukPriv; 55 | /** 56 | * Signature of the public identity block. 57 | */ 58 | private final byte[] idSig; 59 | /** 60 | * Transient state array. 61 | */ 62 | private final short[] tmp; 63 | /** 64 | * Transient buffer for receiving key blocks or other large objects. 65 | */ 66 | private final byte[] keyScratchPad; 67 | 68 | public JediIdentity() { 69 | this.serialNumber = new byte[LEN_ID_SERIAL]; 70 | this.idSig = new byte[RSA2048_INT_SIZE]; 71 | this.tmp = JCSystem.makeTransientShortArray(LEN_TMP, JCSystem.CLEAR_ON_DESELECT); 72 | this.keyScratchPad = JCSystem.makeTransientByteArray(RSA2048_INT_SIZE, JCSystem.CLEAR_ON_DESELECT); 73 | this.cukPub = (RSAPublicKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PUBLIC, KeyBuilder.LENGTH_RSA_2048, false); 74 | this.cukPriv = (RSAPrivateCrtKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_CRT_PRIVATE, KeyBuilder.LENGTH_RSA_2048, false); 75 | this.reset(); 76 | } 77 | 78 | /** 79 | * Resets the object to uninitialized state. 80 | * 81 | * In this state, all key blocks are reset to uninitialized state and other data are filled with 0x00. 82 | * All transient states are also cleared. 83 | */ 84 | public void nuke() { 85 | this.reset(); 86 | this.cukPub.clearKey(); 87 | this.cukPriv.clearKey(); 88 | Util.arrayFillNonAtomic(this.serialNumber, (short) 0, (short) this.serialNumber.length, (byte) 0); 89 | Util.arrayFillNonAtomic(this.idSig, (short) 0, (short) this.idSig.length, (byte) 0); 90 | } 91 | 92 | /** 93 | * Resets all transient states 94 | */ 95 | public void reset() { 96 | this.setTmpKeyOffset((short) 0); 97 | this.setTmpKeyTypeFlag(KEY_TYPE_UNSPECIFIED); 98 | this.clearScratchPad(); 99 | } 100 | 101 | private void setTmpKeyOffset(short off) { 102 | this.tmp[OFFSET_TMP_KEY] = off; 103 | } 104 | 105 | private void incTmpKeyOffset(short inc) { 106 | this.tmp[OFFSET_TMP_KEY] += inc; 107 | } 108 | 109 | private short getTmpKeyOffset() { 110 | return this.tmp[OFFSET_TMP_KEY]; 111 | } 112 | 113 | private void setTmpKeyTypeFlag(short flag) { 114 | this.tmp[OFFSET_FLAG_TMP_KEY_TYPE] = flag; 115 | } 116 | 117 | private short getTmpKeyTypeFlag() { 118 | return this.tmp[OFFSET_FLAG_TMP_KEY_TYPE]; 119 | } 120 | 121 | private void clearScratchPad() { 122 | Util.arrayFillNonAtomic(this.keyScratchPad, (short) 0, (short) this.keyScratchPad.length, (byte) 0); 123 | } 124 | 125 | /** 126 | * Import a single key object. Supports buffering for non-extended length APDU. 127 | * @param buffer Buffer that holds the data. 128 | * @param offset Offset that the data starts. 129 | * @param len Length available. 130 | * @param keyType Type of key. Must be consistent between imports. 131 | * @throws ISOException {@link ISO7816#SW_CONDITIONS_NOT_SATISFIED ISO7816.SW_CONDITIONS_NOT_SATISFIED} when switching type between imports. 132 | * @return Length consumed. 133 | */ 134 | private short putKeyObject(final byte[] buffer, short offset, short len, short keyType) throws ISOException { 135 | short actual; 136 | 137 | // Determine bounds based on object type 138 | short bounds = 0; 139 | switch (keyType) { 140 | case KEY_TYPE_PUB_N: 141 | case KEY_TYPE_PUB_E: 142 | case KEY_TYPE_PUB_SIG: 143 | bounds = JediIdentity.RSA2048_INT_SIZE; 144 | break; 145 | case KEY_TYPE_PRIV_P: 146 | case KEY_TYPE_PRIV_Q: 147 | case KEY_TYPE_PRIV_PQ: 148 | case KEY_TYPE_PRIV_DP1: 149 | case KEY_TYPE_PRIV_DQ1: 150 | bounds = JediIdentity.RSA2048_PQ_SIZE; 151 | break; 152 | default: 153 | ISOException.throwIt((short) 0x6f00); 154 | return (short) 0; 155 | } 156 | 157 | if (this.getTmpKeyTypeFlag() == KEY_TYPE_UNSPECIFIED) { 158 | this.setTmpKeyTypeFlag(keyType); 159 | } else if (this.getTmpKeyTypeFlag() != keyType) { 160 | ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); 161 | return (short) 0; 162 | } 163 | 164 | short remaining = (short) (bounds - this.getTmpKeyOffset()); 165 | if (remaining < 0) { 166 | return (short) 0; 167 | } 168 | if (len > remaining) { 169 | actual = remaining; 170 | } else { 171 | actual = len; 172 | } 173 | Util.arrayCopyNonAtomic(buffer, offset, this.keyScratchPad, this.getTmpKeyOffset(), actual); 174 | this.incTmpKeyOffset(actual); 175 | if (this.getTmpKeyOffset() == bounds) { 176 | switch (keyType) { 177 | case KEY_TYPE_PUB_N: 178 | this.cukPub.setModulus(this.keyScratchPad, (short) 0, JediIdentity.RSA2048_INT_SIZE); 179 | break; 180 | case KEY_TYPE_PUB_E: 181 | this.cukPub.setExponent(this.keyScratchPad, (short) 0, JediIdentity.RSA2048_INT_SIZE); 182 | break; 183 | case KEY_TYPE_PUB_SIG: 184 | Util.arrayCopyNonAtomic(this.keyScratchPad, (short) 0, this.idSig, (short) 0, (short) this.idSig.length); 185 | break; 186 | case KEY_TYPE_PRIV_P: 187 | this.cukPriv.setP(this.keyScratchPad, (short) 0, JediIdentity.RSA2048_PQ_SIZE); 188 | break; 189 | case KEY_TYPE_PRIV_Q: 190 | this.cukPriv.setQ(this.keyScratchPad, (short) 0, JediIdentity.RSA2048_PQ_SIZE); 191 | break; 192 | case KEY_TYPE_PRIV_PQ: 193 | this.cukPriv.setPQ(this.keyScratchPad, (short) 0, JediIdentity.RSA2048_PQ_SIZE); 194 | break; 195 | case KEY_TYPE_PRIV_DP1: 196 | this.cukPriv.setDP1(this.keyScratchPad, (short) 0, JediIdentity.RSA2048_PQ_SIZE); 197 | break; 198 | case KEY_TYPE_PRIV_DQ1: 199 | this.cukPriv.setDQ1(this.keyScratchPad, (short) 0, JediIdentity.RSA2048_PQ_SIZE); 200 | break; 201 | default: 202 | ISOException.throwIt((short) 0x6f00); 203 | return (short) 0; 204 | } 205 | this.setTmpKeyTypeFlag(KEY_TYPE_UNSPECIFIED); 206 | this.setTmpKeyOffset((short) 0); 207 | } 208 | return actual; 209 | } 210 | 211 | /** 212 | * Generates controller-unique RSA keypair. 213 | * @throws ISOException 214 | */ 215 | public void genKeyPair() throws ISOException { 216 | KeyPair kp = null; 217 | // Check for hw capabilities 218 | try { 219 | kp = new KeyPair(this.cukPub, this.cukPriv); 220 | } catch (CryptoException e) { 221 | // RSA 2048 is not supported 222 | if (e.getReason() == CryptoException.NO_SUCH_ALGORITHM) { 223 | ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); 224 | } else { 225 | ISOException.throwIt(ISO7816.SW_UNKNOWN); 226 | } 227 | } 228 | 229 | // Actually generate the key 230 | kp.genKeyPair(); 231 | } 232 | 233 | /** 234 | * Import private factor P. 235 | * @param buffer Buffer that holds the data. 236 | * @param offset Offset that the data starts. 237 | * @param len Length available. 238 | * @return Length consumed. 239 | */ 240 | public short putPrivateKeyP(final byte[] buffer, short offset, short len) throws ISOException { 241 | return this.putKeyObject(buffer, offset, len, KEY_TYPE_PRIV_P); 242 | } 243 | 244 | /** 245 | * Import private factor Q. 246 | * @param buffer Buffer that holds the data. 247 | * @param offset Offset that the data starts. 248 | * @param len Length available. 249 | * @return Length consumed. 250 | */ 251 | public short putPrivateKeyQ(final byte[] buffer, short offset, short len) throws ISOException { 252 | return this.putKeyObject(buffer, offset, len, KEY_TYPE_PRIV_Q); 253 | } 254 | 255 | /** 256 | * Import private factor PQ. 257 | * @param buffer Buffer that holds the data. 258 | * @param offset Offset that the data starts. 259 | * @param len Length available. 260 | * @return Length consumed. 261 | */ 262 | public short putPrivateKeyPQ(final byte[] buffer, short offset, short len) throws ISOException { 263 | return this.putKeyObject(buffer, offset, len, KEY_TYPE_PRIV_PQ); 264 | } 265 | 266 | /** 267 | * Import private factor DP1. 268 | * @param buffer Buffer that holds the data. 269 | * @param offset Offset that the data starts. 270 | * @param len Length available. 271 | * @return Length consumed. 272 | */ 273 | public short putPrivateKeyDP1(final byte[] buffer, short offset, short len) throws ISOException { 274 | return this.putKeyObject(buffer, offset, len, KEY_TYPE_PRIV_DP1); 275 | } 276 | 277 | /** 278 | * Import private factor DQ1. 279 | * @param buffer Buffer that holds the data. 280 | * @param offset Offset that the data starts. 281 | * @param len Length available. 282 | * @return Length consumed. 283 | */ 284 | public short putPrivateKeyDQ1(final byte[] buffer, short offset, short len) throws ISOException { 285 | return this.putKeyObject(buffer, offset, len, KEY_TYPE_PRIV_DQ1); 286 | } 287 | 288 | /** 289 | * Copies the serial number from a buffer into the object. 290 | * Note that the length must be equal to the size of the serial number or it will be rejected with 291 | * {@link ISO7816#SW_WRONG_LENGTH ISO7816.SW_WRONG_LENGTH}. Therefore the input must NOT be split 292 | * into chunks/pages. 293 | * @param buffer The buffer that contains the serial number. 294 | * @param boffset Offset where the serial number is located. 295 | * @param len Number of bytes to copy. 296 | * @return Number of bytes copied. 297 | */ 298 | public short putSerialNumber(final byte[] buffer, short boffset, short len) throws ISOException { 299 | short sz; 300 | if (len != this.serialNumber.length) { 301 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 302 | return 0; 303 | } 304 | sz = Util.arrayCopyNonAtomic(buffer, boffset, this.serialNumber, (short) 0, len); 305 | return sz; 306 | } 307 | 308 | public final byte[] getSerialNumber() { 309 | return this.serialNumber; 310 | } 311 | 312 | public short putPublicKeyN(final byte[] buffer, short offset, short len) throws ISOException { 313 | return this.putKeyObject(buffer, offset, len, KEY_TYPE_PUB_N); 314 | } 315 | 316 | public short putPublicKeyE(final byte[] buffer, short offset, short len) throws ISOException { 317 | return this.putKeyObject(buffer, offset, len, KEY_TYPE_PUB_E); 318 | } 319 | 320 | public short putPublicKeyEDirect(final byte[] buffer, short offset, short len) throws ISOException { 321 | this.cukPub.setExponent(buffer, offset, len); 322 | return len; 323 | } 324 | 325 | public short putIdSig(final byte[] buffer, short offset, short len) throws ISOException { 326 | return this.putKeyObject(buffer, offset, len, KEY_TYPE_PUB_SIG); 327 | } 328 | 329 | public final RSAPublicKey getPublicKey() { 330 | return this.cukPub; 331 | } 332 | 333 | public final byte[] exportPublicKeyN() { 334 | this.setTmpKeyTypeFlag(KEY_TYPE_EXPORT_PUB_N); 335 | this.getPublicKey().getModulus(this.keyScratchPad, (short) 0); 336 | return this.keyScratchPad; 337 | } 338 | 339 | private final byte[] exportPublicKeyE(short eSize) { 340 | short len = this.getPublicKey().getExponent(this.keyScratchPad, (short) 0); 341 | short offset = (short) (eSize - len); 342 | if (offset > 0) { 343 | this.clearScratchPad(); 344 | this.getPublicKey().getExponent(this.keyScratchPad, offset); 345 | } 346 | return this.keyScratchPad; 347 | } 348 | 349 | public final byte[] exportPublicKeyE() { 350 | this.setTmpKeyTypeFlag(KEY_TYPE_EXPORT_PUB_E); 351 | return this.exportPublicKeyE(LEN_ID_PUB_E); 352 | } 353 | 354 | public final byte[] exportPublicKeyECompat() { 355 | this.setTmpKeyTypeFlag(KEY_TYPE_EXPORT_PUB_E_COMPAT); 356 | return this.exportPublicKeyE(LEN_ID_PUB_E_COMPAT); 357 | } 358 | 359 | public void finishExport() { 360 | this.setTmpKeyTypeFlag(KEY_TYPE_UNSPECIFIED); 361 | } 362 | 363 | public final RSAPrivateCrtKey getPrivateKey() { 364 | return this.cukPriv; 365 | } 366 | 367 | public final byte[] getIdSig() { 368 | return this.idSig; 369 | } 370 | 371 | /** 372 | * Returns the readiness of the object. 373 | * 374 | * Note that this only checks if the private and public keys are initialized. 375 | * Unsigned key blocks will still pass the test. 376 | * @return true if ready. 377 | */ 378 | public boolean isReady() { 379 | return this.cukPriv.isInitialized() && this.cukPub.isInitialized(); 380 | } 381 | 382 | public short getCurentImport() { 383 | return this.getTmpKeyTypeFlag(); 384 | } 385 | 386 | public short getCurrentImportOffset() { 387 | return this.getTmpKeyOffset(); 388 | } 389 | } 390 | -------------------------------------------------------------------------------- /src/main/javacard/illegal/security/chip/ISCApplet.java: -------------------------------------------------------------------------------- 1 | package illegal.security.chip; 2 | 3 | import javacard.framework.APDU; 4 | import javacard.framework.Applet; 5 | import javacard.framework.ISO7816; 6 | import javacard.framework.ISOException; 7 | import javacard.framework.JCSystem; 8 | import javacard.framework.Util; 9 | import javacard.security.CryptoException; 10 | import javacard.security.Signature; 11 | import javacardx.apdu.ExtendedLength; 12 | 13 | public class ISCApplet extends Applet implements ExtendedLength { 14 | // The version string. Format is 111e9a15ec + short applet_version + short protocol_version + byte applet_type. 15 | // applet_type 0x04 means PS4. 16 | private static final byte[] VERSION = {0x11, 0x1e, (byte) 0x9a, 0x15, (byte) 0xec, 0x01, 0x01, 0x01, 0x01, 0x04}; 17 | private static final short LEN_TEMP_STATES = (short) 0x1; 18 | private static final short LEN_DS4RESP_SIG = JediIdentity.RSA2048_INT_SIZE; 19 | // Offsets 20 | private static final short OFFSET_TS_SIG_READ_PROT = (short) 0x0; 21 | 22 | private static final short OFFSET_DS4RESP_SIG = (short) 0x0; 23 | private static final short OFFSET_DS4RESP_ID_SERIAL = OFFSET_DS4RESP_SIG + LEN_DS4RESP_SIG; 24 | private static final short OFFSET_DS4RESP_ID_PUB_N = OFFSET_DS4RESP_ID_SERIAL + JediIdentity.LEN_ID_SERIAL; 25 | private static final short OFFSET_DS4RESP_ID_PUB_E = OFFSET_DS4RESP_ID_PUB_N + JediIdentity.LEN_ID_PUB_N; 26 | private static final short OFFSET_DS4RESP_ID_SIG = OFFSET_DS4RESP_ID_PUB_E + JediIdentity.LEN_ID_PUB_E; 27 | 28 | private static final short LEN_DS4RESP = OFFSET_DS4RESP_ID_SIG + JediIdentity.LEN_ID_SIG; 29 | 30 | // APDU classes 31 | // https://cardwerk.com/smart-card-standard-iso7816-4-section-5-basic-organizations/ 32 | private static final byte CLA_AUTH = (byte) 0x80; 33 | private static final byte CLA_CONFIG = (byte) 0x90; 34 | 35 | // APDU commands for CLA_AUTH 36 | private static final byte INS_AUTH_SET_CHALLENGE = (byte) 0x44; 37 | private static final byte INS_AUTH_GET_RESPONSE = (byte) 0x46; 38 | private static final byte INS_AUTH_RESET = (byte) 0x48; 39 | 40 | // APDU commands for CLA_CONFIG 41 | // NOTE: Odd INSes had special meaning in the past (i.e. pre-90s cards) but newer cards 42 | // that support javacard 3.0.1 shouldn't have this limitation. Therefore it's safe to 43 | // use odd INSes here. 44 | // 45 | // https://stackoverflow.com/questions/30162045/iso7816-odd-ins-codes 46 | // General management 47 | private static final byte INS_CONFIG_GET_VERSION = (byte) 0x00; 48 | private static final byte INS_CONFIG_GET_STATUS = (byte) 0x01; 49 | private static final byte INS_CONFIG_RESET = (byte) 0x0f; 50 | // Import pages 51 | private static final byte INS_CONFIG_IMPORT = (byte) 0x10; 52 | // Export public pages 53 | private static final byte INS_CONFIG_EXPORT = (byte) 0x20; 54 | // Destructive operations. Think twice before proceeding! 55 | private static final byte INS_CONFIG_GEN_KEYS = (byte) 0xfd; 56 | private static final byte INS_CONFIG_ENTER_STEALTH_MODE = (byte) 0xfe; 57 | private static final byte INS_CONFIG_NUKE = (byte) 0xff; 58 | 59 | // P1 for import/export. (Export only applicable to type 0X i.e. public pages) 60 | // bit 7 = no paging support. 61 | private static final byte P1_SERIAL = (byte) 0x80; 62 | private static final byte P1_PUB_N = (byte) 0x01; 63 | private static final byte P1_PUB_E = (byte) 0x02; 64 | private static final byte P1_PUB_E_COMPAT = (byte) 0x83; 65 | private static final byte P1_SIG_ID = (byte) 0x04; 66 | private static final byte P1_PRIV_P = (byte) 0x10; 67 | private static final byte P1_PRIV_Q = (byte) 0x11; 68 | private static final byte P1_PRIV_PQ = (byte) 0x12; 69 | private static final byte P1_PRIV_DP1 = (byte) 0x13; 70 | private static final byte P1_PRIV_DQ1 = (byte) 0x14; 71 | 72 | private final Signature sigChallenge; 73 | private final JediIdentity id; 74 | private final short[] tempStates; 75 | private final byte[] signature; 76 | private boolean stealthMode; 77 | 78 | public ISCApplet() { 79 | try { 80 | this.sigChallenge = Signature.getInstance(Signature.ALG_RSA_SHA_256_PKCS1_PSS, false); 81 | } catch (CryptoException e) { 82 | // RSA-PSS is not supported 83 | if (e.getReason() == CryptoException.NO_SUCH_ALGORITHM) { 84 | ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); 85 | } else { 86 | ISOException.throwIt(ISO7816.SW_UNKNOWN); 87 | } 88 | // Satisfy javac since it doesn't like ISOException :(. 89 | // This should never get executed. 90 | throw (e); 91 | } 92 | this.id = new JediIdentity(); 93 | this.tempStates = JCSystem.makeTransientShortArray(LEN_TEMP_STATES, JCSystem.CLEAR_ON_DESELECT); 94 | this.signature = JCSystem.makeTransientByteArray(JediIdentity.RSA2048_INT_SIZE, JCSystem.CLEAR_ON_DESELECT); 95 | this.stealthMode = false; 96 | } 97 | 98 | public static void install(byte[] bArray, short bOffset, byte bLength) 99 | throws ISOException { 100 | ISCApplet app = new ISCApplet(); 101 | app.register(bArray, (short) (bOffset + 1), bArray[bOffset]); 102 | } 103 | 104 | /** 105 | * Reset authentication-related states. 106 | */ 107 | private void reset() { 108 | this.sigChallenge.init(this.id.getPrivateKey(), Signature.MODE_SIGN); 109 | this.signatureSetReadProtect(true); 110 | Util.arrayFillNonAtomic(this.signature, (short) 0, (short) this.signature.length, (byte) 0); 111 | } 112 | 113 | /** 114 | * Returns the signature buffer's read protection status. 115 | * @return Whether or not read protection is enabled. 116 | */ 117 | private boolean signatureIsReadProtect() { 118 | return this.tempStates[OFFSET_TS_SIG_READ_PROT] != 0; 119 | } 120 | 121 | /** 122 | * Sets the signature buffer's read protection status. 123 | * @param val New state. 124 | */ 125 | private void signatureSetReadProtect(boolean val) { 126 | this.tempStates[OFFSET_TS_SIG_READ_PROT] = (short) (val ? 1 : 0); 127 | } 128 | 129 | /** 130 | * Returns the smaller one of the 2 numbers. 131 | * @param a One number. 132 | * @param b Another number. 133 | * @return The smaller number. 134 | */ 135 | private static short min(short a, short b) { 136 | if (a > b) { 137 | return b; 138 | } else { 139 | return a; 140 | } 141 | } 142 | 143 | /** 144 | * Reset the authenticator. 145 | * @param apdu APDU context. Not used here. 146 | * @throws ISOException 147 | */ 148 | private void processAuthReset(APDU apdu) throws ISOException { 149 | this.reset(); 150 | } 151 | 152 | /** 153 | *

154 | * Handles the request of SetChallenge. Response will be generated after writing to the last byte. 155 | * Note that P1 and P2 are only used for calculating 156 | * the offset so that the whole challenge can be written in a single extended length APDU 157 | * (by e.g. setting both P1 and P2 to 0). It is also possible to change the block size 158 | * during the transaction. 159 | *

160 | * 161 | *

162 | * Setting offset to be out-of-bound will result in {@link ISOException ISOException} with the SW 163 | * {@link ISO7816#SW_WRONG_P1P2 SW_WRONG_P1P2}. Out-of-bound writes will be ignored. 164 | *

165 | * 166 | * @param apdu The APDU context. 167 | * @throws ISOException 168 | */ 169 | private void processAuthSetChallenge(APDU apdu) throws ISOException { 170 | // Immediately read protect the signature area 171 | this.signatureSetReadProtect(true); 172 | 173 | byte[] buf = apdu.getBuffer(); 174 | short rectifiedP1, rectifiedP2; 175 | 176 | // Rectify P1 and P2 177 | rectifiedP1 = (short) (buf[ISO7816.OFFSET_P1] & 0xff); 178 | rectifiedP2 = (short) (buf[ISO7816.OFFSET_P2] & 0xff); 179 | 180 | // Calculate and validate offset 181 | short offset = (short) (rectifiedP1 * rectifiedP2); 182 | if (offset < 0 || offset >= this.signature.length) { 183 | // Offset is out of bound. Panic. 184 | ISOException.throwIt(ISO7816.SW_WRONG_P1P2); 185 | return; 186 | } 187 | 188 | // Get number of total incoming bytes 189 | short total = apdu.getIncomingLength(); 190 | 191 | // Calculate and validate available space for write 192 | short totalWritable = (short) (this.signature.length - offset); 193 | if (totalWritable < total) { 194 | total = totalWritable; 195 | } 196 | 197 | // Start reading data to the buffer 198 | short remaining = total; 199 | short bytes = apdu.setIncomingAndReceive(); 200 | short offsetCdata = apdu.getOffsetCdata(); 201 | while (bytes > 0) { 202 | if (remaining < bytes) { 203 | // Clamp bytes to the remaining value that we decided. 204 | bytes = remaining; 205 | } 206 | if (remaining > 0) { 207 | // Copy this chunk 208 | offset += Util.arrayCopyNonAtomic(buf, offsetCdata, this.signature, offset, bytes); 209 | remaining -= bytes; 210 | } 211 | // Receive next chunk (or discard overflowing data) 212 | bytes = apdu.receiveBytes(offsetCdata); 213 | } 214 | 215 | // Just finished writing the last page. Sign the buffered pages. 216 | if (totalWritable == total) { 217 | // From JavaCard doc: The input and output buffer data may overlap. 218 | this.sigChallenge.sign(this.signature, (short) 0, (short) this.signature.length, this.signature, (short) 0); 219 | this.signatureSetReadProtect(false); 220 | } 221 | } 222 | 223 | /** 224 | * Handles the request of GetResponse. Note that P1 and P2 are only used for calculating 225 | * the offset so that the whole response can be read in a single extended length APDU 226 | * (by e.g. setting both P1 and P2 to 0). It is also possible to change the block size 227 | * during the transaction. 228 | * 229 | * @param apdu The APDU context. 230 | * @throws ISOException 231 | */ 232 | private void processAuthGetResponse(APDU apdu) throws ISOException { 233 | byte[] buf = apdu.getBuffer(); 234 | 235 | // Rectify P1 and P2 236 | short rectifiedP1, rectifiedP2; 237 | rectifiedP1 = (short) (buf[ISO7816.OFFSET_P1] & 0xff); 238 | rectifiedP2 = (short) (buf[ISO7816.OFFSET_P2] & 0xff); 239 | 240 | // Calculate and validate offset 241 | short offset = (short) (rectifiedP1 * rectifiedP2); 242 | if (offset < 0 || offset >= LEN_DS4RESP) { 243 | ISOException.throwIt(ISO7816.SW_WRONG_P1P2); 244 | return; 245 | } 246 | 247 | // Determine actual response size. 248 | // Accept response size set by the host but only send until the end of the response. 249 | short remaining = apdu.setOutgoing(); 250 | remaining = min(remaining, (short) (LEN_DS4RESP - offset)); 251 | apdu.setOutgoingLength(remaining); 252 | 253 | // Send until we have nothing to send 254 | while (remaining > 0) { 255 | // Counter for total number of data written (actual chunk size) 256 | short chunkUsed = 0; 257 | // Determine chunk size 258 | short chunkFree = min((short) buf.length, remaining); 259 | 260 | // fill the buffer 261 | while (chunkFree > 0) { 262 | short copySize = 0; 263 | if (offset >= OFFSET_DS4RESP_SIG && offset < OFFSET_DS4RESP_ID_SERIAL) { 264 | // Relative offset 265 | short relOffset = (short) (offset - OFFSET_DS4RESP_SIG); 266 | copySize = (short) (LEN_DS4RESP_SIG - relOffset); 267 | 268 | // Calculate copy size (total bytes available for chunk or payload size, whichever smaller) 269 | copySize = min(chunkFree, copySize); 270 | 271 | // Populate the buffer with payload 272 | if (this.signatureIsReadProtect()) { 273 | Util.arrayFillNonAtomic(buf, chunkUsed, copySize, (byte) 0); 274 | } else { 275 | Util.arrayCopyNonAtomic(this.signature, relOffset, buf, chunkUsed, copySize); 276 | } 277 | } else if (offset >= OFFSET_DS4RESP_ID_SERIAL && offset < OFFSET_DS4RESP_ID_PUB_N) { 278 | // Relative offset 279 | short relOffset = (short) (offset - OFFSET_DS4RESP_ID_SERIAL); 280 | copySize = (short) (JediIdentity.LEN_ID_SERIAL - relOffset); 281 | 282 | // Calculate copy size (total bytes available for chunk or payload size, whichever smaller) 283 | copySize = min(chunkFree, copySize); 284 | 285 | // Populate the buffer with payload 286 | Util.arrayCopyNonAtomic(this.id.getSerialNumber(), relOffset, buf, chunkUsed, copySize); 287 | } else if (offset >= OFFSET_DS4RESP_ID_PUB_N && offset < OFFSET_DS4RESP_ID_PUB_E) { 288 | // Relative offset 289 | short relOffset = (short) (offset - OFFSET_DS4RESP_ID_PUB_N); 290 | copySize = (short) (JediIdentity.LEN_ID_PUB_N - relOffset); 291 | 292 | // Calculate copy size (total bytes available for chunk or payload size, whichever smaller) 293 | copySize = min(chunkFree, copySize); 294 | 295 | // Populate the buffer with payload 296 | Util.arrayCopyNonAtomic(this.id.exportPublicKeyN(), relOffset, buf, chunkUsed, copySize); 297 | this.id.finishExport(); 298 | } else if (offset >= OFFSET_DS4RESP_ID_PUB_E && offset < OFFSET_DS4RESP_ID_SIG) { 299 | // Relative offset 300 | short relOffset = (short) (offset - OFFSET_DS4RESP_ID_PUB_E); 301 | 302 | copySize = (short) (JediIdentity.LEN_ID_PUB_E - relOffset); 303 | 304 | // Calculate copy size (total bytes available for chunk or payload size, whichever smaller) 305 | copySize = min(chunkFree, copySize); 306 | 307 | // Populate the buffer with payload 308 | Util.arrayCopyNonAtomic(this.id.exportPublicKeyE(), relOffset, buf, chunkUsed, copySize); 309 | this.id.finishExport(); 310 | } else if (offset >= OFFSET_DS4RESP_ID_SIG && offset < LEN_DS4RESP) { 311 | // Relative offset 312 | short relOffset = (short) (offset - OFFSET_DS4RESP_ID_SIG); 313 | copySize = (short) (JediIdentity.LEN_ID_SIG - relOffset); 314 | 315 | // Calculate copy size (total bytes available for chunk or payload size, whichever smaller) 316 | copySize = min(chunkFree, copySize); 317 | 318 | // Populate the buffer with payload 319 | Util.arrayCopyNonAtomic(this.id.getIdSig(), relOffset, buf, chunkUsed, copySize); 320 | } 321 | // Increment chunk size counter 322 | chunkUsed += copySize; 323 | // Update free space available for the chunk 324 | chunkFree -= copySize; 325 | 326 | // Update remaining bytes to send 327 | remaining -= copySize; 328 | // Update offset 329 | offset += copySize; 330 | } 331 | // Send the chunk when it's ready 332 | apdu.sendBytes((short) 0, chunkUsed); 333 | } 334 | } 335 | 336 | /** 337 | * Handles the request of Config.GetVersion. Returns the applet version and type. 338 | * @param apdu The APDU context. 339 | */ 340 | private void processGetVersion(APDU apdu) { 341 | byte[] buf = apdu.getBuffer(); 342 | Util.arrayCopyNonAtomic(VERSION, (short) 0, buf, (short) 0, (short) VERSION.length); 343 | apdu.setOutgoingAndSend((short) 0, (short) VERSION.length); 344 | } 345 | 346 | /** 347 | * Handles the request of Config.GetStatus. Returns the personalization status of the applet. 348 | * @param apdu The APDU context. 349 | */ 350 | private void processGetStatus(APDU apdu) { 351 | byte[] buf = apdu.getBuffer(); 352 | buf[0] = (byte) (this.id.isReady() ? 1 : 0); 353 | apdu.setOutgoingAndSend((short) 0, (short) 1); 354 | } 355 | 356 | /** 357 | * Handles the request of Config.Import. Imports a public or private object over APDU. 358 | * @param apdu The APDU context. 359 | */ 360 | private void processImport(APDU apdu) { 361 | byte[] buf = apdu.getBuffer(); 362 | byte importType; 363 | 364 | importType = buf[ISO7816.OFFSET_P1]; 365 | 366 | // Get number of total incoming bytes 367 | short total = apdu.getIncomingLength(); 368 | 369 | // Start reading data to the buffer 370 | short bytes = apdu.setIncomingAndReceive(); 371 | short offsetCdata = apdu.getOffsetCdata(); 372 | while (bytes > 0) { 373 | switch (importType) { 374 | case P1_SERIAL: 375 | if (total >= JediIdentity.LEN_ID_SERIAL && bytes >= JediIdentity.LEN_ID_SERIAL) { 376 | this.id.putSerialNumber(buf, offsetCdata, JediIdentity.LEN_ID_SERIAL); 377 | return; 378 | } else { 379 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 380 | } 381 | break; 382 | case P1_PUB_N: 383 | this.id.putPublicKeyN(buf, offsetCdata, bytes); 384 | break; 385 | case P1_PUB_E: 386 | this.id.putPublicKeyE(buf, offsetCdata, bytes); 387 | break; 388 | case P1_PUB_E_COMPAT: 389 | if (total >= JediIdentity.LEN_ID_PUB_E_COMPAT && bytes >= JediIdentity.LEN_ID_PUB_E_COMPAT) { 390 | this.id.putPublicKeyEDirect(buf, offsetCdata, JediIdentity.LEN_ID_PUB_E_COMPAT); 391 | return; 392 | } else { 393 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 394 | } 395 | break; 396 | case P1_SIG_ID: 397 | this.id.putIdSig(buf, offsetCdata, bytes); 398 | break; 399 | case P1_PRIV_P: 400 | this.id.putPrivateKeyP(buf, offsetCdata, bytes); 401 | break; 402 | case P1_PRIV_Q: 403 | this.id.putPrivateKeyQ(buf, offsetCdata, bytes); 404 | break; 405 | case P1_PRIV_PQ: 406 | this.id.putPrivateKeyPQ(buf, offsetCdata, bytes); 407 | break; 408 | case P1_PRIV_DP1: 409 | this.id.putPrivateKeyDP1(buf, offsetCdata, bytes); 410 | break; 411 | case P1_PRIV_DQ1: 412 | this.id.putPrivateKeyDQ1(buf, offsetCdata, bytes); 413 | break; 414 | default: 415 | ISOException.throwIt(ISO7816.SW_WRONG_P1P2); 416 | return; 417 | } 418 | // Receive next chunk (or discard overflowing data) 419 | bytes = apdu.receiveBytes(offsetCdata); 420 | } 421 | } 422 | 423 | /** 424 | * Handles the request of Config.Export. Exports a public object over APDU. 425 | * @param apdu The APDU context. 426 | */ 427 | private void processExport(APDU apdu) { 428 | byte[] buf = apdu.getBuffer(); 429 | 430 | byte exportType = buf[ISO7816.OFFSET_P1]; 431 | if (exportType == P1_SERIAL) { 432 | Util.arrayCopyNonAtomic(this.id.getSerialNumber(), (short) 0, buf, (short) 0, JediIdentity.LEN_ID_SERIAL); 433 | apdu.setOutgoingAndSend((short) 0, JediIdentity.LEN_ID_SERIAL); 434 | return; 435 | } else if (exportType == P1_PUB_E_COMPAT) { 436 | Util.arrayCopyNonAtomic(this.id.exportPublicKeyECompat(), (short) 0, buf, (short) 0, JediIdentity.LEN_ID_PUB_E_COMPAT); 437 | this.id.finishExport(); 438 | apdu.setOutgoingAndSend((short) 0, JediIdentity.LEN_ID_PUB_E_COMPAT); 439 | return; 440 | } 441 | 442 | short expected = apdu.setOutgoing(); 443 | // All data sent below have the size of JediIdentity.RSA2048_INT_SIZE. Hardcode it here. 444 | short remaining = JediIdentity.RSA2048_INT_SIZE; 445 | 446 | if (expected < remaining) { 447 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 448 | return; 449 | } 450 | apdu.setOutgoingLength(remaining); 451 | byte[] exportBuffer = null; 452 | switch (exportType) { 453 | case P1_PUB_N: 454 | exportBuffer = this.id.exportPublicKeyN(); 455 | break; 456 | case P1_PUB_E: 457 | exportBuffer = this.id.exportPublicKeyE(); 458 | break; 459 | case P1_SIG_ID: 460 | exportBuffer = this.id.getIdSig(); 461 | break; 462 | default: 463 | ISOException.throwIt(ISO7816.SW_WRONG_P1P2); 464 | return; 465 | } 466 | 467 | try { 468 | while (remaining > 0) { 469 | // Counter for total number of data written (actual chunk size) 470 | short chunkUsed = 0; 471 | // Determine chunk size 472 | short chunkFree = min((short) buf.length, remaining); 473 | while (chunkFree > 0) { 474 | short copySize = min(chunkFree, remaining); 475 | Util.arrayCopyNonAtomic(exportBuffer, (short) (JediIdentity.RSA2048_INT_SIZE-remaining), buf, chunkUsed, copySize); 476 | // Increment chunk size counter 477 | chunkUsed += copySize; 478 | // Update free space available for the chunk 479 | chunkFree -= copySize; 480 | 481 | // Update remaining bytes to send 482 | remaining -= copySize; 483 | } 484 | apdu.sendBytes((short) 0, chunkUsed); 485 | } 486 | } finally { 487 | this.id.finishExport(); 488 | } 489 | } 490 | 491 | public void process(APDU apdu) throws ISOException { 492 | byte[] buf = apdu.getBuffer(); 493 | if (apdu.isISOInterindustryCLA()) { 494 | if (this.selectingApplet()) { 495 | return; 496 | } else { 497 | ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); 498 | return; 499 | } 500 | } 501 | switch (buf[ISO7816.OFFSET_CLA]) { 502 | case CLA_AUTH: 503 | if (!this.id.isReady()) { 504 | ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); 505 | return; 506 | } 507 | switch (buf[ISO7816.OFFSET_INS]) { 508 | case INS_AUTH_RESET: 509 | this.processAuthReset(apdu); 510 | break; 511 | case INS_AUTH_SET_CHALLENGE: 512 | this.processAuthSetChallenge(apdu); 513 | break; 514 | case INS_AUTH_GET_RESPONSE: 515 | this.processAuthGetResponse(apdu); 516 | break; 517 | default: 518 | ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); 519 | } 520 | break; 521 | case CLA_CONFIG: 522 | if (this.stealthMode) { 523 | ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); 524 | break; 525 | } 526 | switch (buf[ISO7816.OFFSET_INS]) { 527 | case INS_CONFIG_GET_VERSION: 528 | this.processGetVersion(apdu); 529 | break; 530 | case INS_CONFIG_GET_STATUS: 531 | this.processGetStatus(apdu); 532 | break; 533 | case INS_CONFIG_RESET: 534 | this.id.reset(); 535 | break; 536 | case INS_CONFIG_IMPORT: 537 | this.processImport(apdu); 538 | break; 539 | case INS_CONFIG_EXPORT: 540 | this.processExport(apdu); 541 | break; 542 | case INS_CONFIG_GEN_KEYS: 543 | this.id.genKeyPair(); 544 | break; 545 | // Enter stealth mode. The config interface will be locked out and can only be reset by reinstalling the applet. 546 | case INS_CONFIG_ENTER_STEALTH_MODE: 547 | this.stealthMode = true; 548 | break; 549 | case INS_CONFIG_NUKE: 550 | this.reset(); 551 | this.id.nuke(); 552 | break; 553 | default: 554 | ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); 555 | } 556 | break; 557 | default: 558 | ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); 559 | } 560 | } 561 | 562 | } // ISCApplet 563 | -------------------------------------------------------------------------------- /utils/iscctl/iscctl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import enum 5 | import functools 6 | import io 7 | import os 8 | 9 | from ctypes import * 10 | from contextlib import contextmanager 11 | 12 | import smartcard.System as scsys 13 | from smartcard.CardConnectionObserver import ConsoleCardConnectionObserver 14 | from smartcard.sw.ISO7816_4ErrorChecker import ISO7816_4ErrorChecker 15 | 16 | from Crypto.Hash import SHA256 17 | from Crypto.PublicKey import RSA 18 | from Crypto.Signature import pss 19 | from Crypto.Math.Numbers import Integer 20 | from Crypto.Util.number import bytes_to_long 21 | 22 | JEDI_CA_PUBKEY_FINGERPRINT = b'\xe5\xe0\x95\xe6C\xb5h\x8b@\x0cu{LD\xef\xac\xc2\x93aH\xe5\xce\xbdlmA\x0fT\xf1H\x7fI' 23 | 24 | AID = bytes.fromhex('f50111e9a15ec400') 25 | 26 | ISC_MAGIC = bytes.fromhex('111e9a15ec') 27 | 28 | _check_error = ISO7816_4ErrorChecker() 29 | 30 | ISOCLA = 0x00 31 | ISOINS_SELECT = 0xa4 32 | ISOP1_SELECT_BY_DF_NAME = 0x04 33 | ISOP2_FIRST_RECORD = 0x04 34 | 35 | class ISCAuthProtocol(enum.IntEnum): 36 | ps4 = 0x4 37 | 38 | 39 | class ISCCLA(enum.IntEnum): 40 | auth = 0x80 41 | config = 0x90 42 | 43 | 44 | class ISCAuthINS(enum.IntEnum): 45 | set_challenge = 0x44 46 | get_response = 0x46 47 | reset = 0x48 48 | 49 | 50 | class ISCConfigINS(enum.IntEnum): 51 | get_version = 0x00 52 | get_status = 0x01 53 | reset = 0x0f 54 | 55 | import_ = 0x10 56 | export = 0x20 57 | 58 | gen_keys = 0xfd 59 | enter_stealth_mode = 0xfe 60 | nuke = 0xff 61 | 62 | class ISCImportType(enum.IntEnum): 63 | serial = 0x80 64 | pub_n = 0x01 65 | pub_e = 0x02 66 | pub_e_compat = 0x83 67 | sig_id = 0x04 68 | priv_p = 0x10 69 | priv_q = 0x11 70 | priv_pq = 0x12 71 | priv_dp1 = 0x13 72 | priv_dq1 = 0x14 73 | 74 | class APDU: 75 | def __init__(self, cla, ins, p1, p2, payload=None, le=0, force_extended=False): 76 | # Initialize all fields 77 | self.cla = cla 78 | self.ins = ins 79 | self.p1 = p1 80 | self.p2 = p2 81 | self.payload = payload 82 | self.le = le 83 | self.force_extended = force_extended 84 | 85 | def serialize(self, mutable_factory=bytearray): 86 | # Set Lc to the length of payload, or 0 if payload is empty or None. 87 | lc = len(self.payload) if self.payload is not None else 0 88 | # If one of them needs upgrade, upgrade all. 89 | # If forcing extended, upgrade when Lc or Le is not zero. 90 | extended = ( 91 | (self.force_extended and (lc > 0 or self.le > 0)) or (lc > 0xff or self.le > 0x100) 92 | ) 93 | header = (val & 0xff for val in (self.cla, self.ins, self.p1, self.p2)) 94 | length_field_size = 2 if extended else 1 95 | length_mask = 0xffff if extended else 0xff 96 | 97 | buf = mutable_factory() 98 | buf.extend(header) 99 | if extended: 100 | buf.append(0x00) 101 | if self.payload is not None and len(self.payload) > 0: 102 | buf.extend(int.to_bytes(lc & length_mask, length_field_size, 'big')) 103 | buf.extend(self.payload) 104 | if self.le > 0: 105 | buf.extend(int.to_bytes(self.le & length_mask, length_field_size, 'big')) 106 | return buf 107 | 108 | def __bytes__(self): 109 | return bytes(self.serialize()) 110 | 111 | def to_list(self): 112 | return self.serialize(list) 113 | 114 | def to_bytes(self): 115 | return bytes(self) 116 | 117 | class DS4IdentityBlock(LittleEndianStructure): 118 | _pack_ = 1 119 | _fields_ = ( 120 | ('serial', c_uint8 * 0x10), 121 | ('modulus', c_uint8 * 0x100), 122 | ('exponent', c_uint8 * 0x100), 123 | ) 124 | 125 | class DS4PrivateKeyBlock(LittleEndianStructure): 126 | _pack_ = 1 127 | _fields_ = ( 128 | ('p', c_uint8 * 0x80), 129 | ('q', c_uint8 * 0x80), 130 | ('dp1', c_uint8 * 0x80), 131 | ('dq1', c_uint8 * 0x80), 132 | ('pq', c_uint8 * 0x80), 133 | ) 134 | 135 | class DS4SignedIdentityBlock(LittleEndianStructure): 136 | _pack_ = 1 137 | _fields_ = ( 138 | ('identity', DS4IdentityBlock), 139 | ('sig_identity', c_uint8 * 0x100), 140 | ) 141 | 142 | class DS4FullKeyBlock(LittleEndianStructure): 143 | _pack_ = 1 144 | _fields_ = ( 145 | ('identity', DS4IdentityBlock), 146 | ('sig_identity', c_uint8 * 0x100), 147 | ('private_key', DS4PrivateKeyBlock), 148 | ) 149 | 150 | class DS4Response(LittleEndianStructure): 151 | _pack_ = 1 152 | _fields_ = ( 153 | ('sig', c_uint8 * 0x100), 154 | ('signed_identity', DS4SignedIdentityBlock), 155 | ) 156 | 157 | @contextmanager 158 | def disconnectable(thing): 159 | try: 160 | yield thing 161 | finally: 162 | thing.disconnect() 163 | 164 | autobase = functools.partial(int, base=0) 165 | 166 | def parse_args(): 167 | p = argparse.ArgumentParser() 168 | sps = p.add_subparsers(dest='action', required=True) 169 | 170 | mex_reader = p.add_mutually_exclusive_group() 171 | mex_reader.add_argument('-r', '--reader-index', type=int, dest='reader', default=None, metavar='IDX', help='Reader index shown on list-readers.') 172 | mex_reader.add_argument('-n', '--reader-name', dest='reader', default=None, metavar='NAME', help='Reader name (can be partial).') 173 | p.add_argument('-a', '--aid', type=bytes.fromhex, default=AID, help='Custom AID.') 174 | p.add_argument('-d', '--debug', action='store_true', help='Print protocol trace.') 175 | p.add_argument('-y', '--yes', action='store_true', help='Automatically answer yes on confirm.') 176 | 177 | sp = sps.add_parser('list-readers', 178 | help='List available readers.') 179 | 180 | sp = sps.add_parser('applet-info', 181 | help='Get applet info.') 182 | 183 | sp = sps.add_parser('is-ready', 184 | help='Check whether or not the card is ready.') 185 | 186 | sp = sps.add_parser('test-auth', 187 | help='Run the whole challenge-response sequence.') 188 | sp.add_argument('-c', '--jedi-ca-pubkey', 189 | help='Location of Jedi CA public key (default: jedi.pub)', 190 | default='jedi.pub') 191 | sp.add_argument('-i', '--id-verification', 192 | choices=('skip', 'warn', 'strict'), 193 | help='ID verification level. skip: No verification at all. warn: Display verification result but do not panic when verification fails. strict: Panics when verification fails and skips response verification.', 194 | default='warn') 195 | sp.add_argument('-p', '--page-size', type=autobase, default=0x80, 196 | help='Page size. Use 0 to send/receive all data with a single request.') 197 | 198 | sp = sps.add_parser('import-ds4key', 199 | help='Import DS4Key to the card.') 200 | sp.add_argument('ds4key_file', 201 | help='Path to DS4Key file') 202 | sp.add_argument('--allow-oversized-exponent', 203 | action='store_true', 204 | help='Allow public exponent to be larger than 32-bit. Not all JavaCard implementation supports this so it might not work.') 205 | 206 | sp = sps.add_parser('export-ds4id', 207 | help='Export DS4ID and the signature from the card.') 208 | sp.add_argument('ds4id_file', 209 | help='Path to DS4ID file') 210 | 211 | sp = sps.add_parser('set-serial', 212 | help='Set the 16 bytes serial number in DS4ID. Doing so will require re-signing the DS4ID.') 213 | sp.add_argument('serial', 214 | type=bytes.fromhex, 215 | help='New serial number in hex format (e.g. 000000000000000000010001deadbeef).') 216 | 217 | sp = sps.add_parser('sign-ds4id', 218 | help='Sign DS4ID on card with Jedi CA or upload existing signature binary.') 219 | mex = sp.add_mutually_exclusive_group(required=True) 220 | mex.add_argument('-c', '--jedi-ca-privkey', 221 | help='Location of Jedi CA PRIVATE key.') 222 | mex.add_argument('-s', '--sig-binary', 223 | help='Location of signature binary file.') 224 | 225 | sp = sps.add_parser('gen-key', 226 | help='Generate new keys.') 227 | 228 | sp = sps.add_parser('enter-stealth-mode', 229 | help='Enter stealth mode (disable the configuration interface).') 230 | 231 | sp = sps.add_parser('nuke', 232 | help='Reset the applet to uninitialized state.') 233 | 234 | return p, p.parse_args() 235 | 236 | def _ds4id_to_key(ds4id): 237 | key = RSA.construct((bytes_to_long(bytes(ds4id.modulus)), bytes_to_long(bytes(ds4id.exponent))), consistency_check=True) 238 | return key 239 | 240 | def _load_ds4key_and_check(ds4keyfile, allow_oversized_e=False): 241 | ds4key = DS4FullKeyBlock() 242 | oversized_e = False 243 | with open(ds4keyfile, 'rb') as f: 244 | actual = f.readinto(ds4key) 245 | if actual != sizeof(DS4FullKeyBlock): 246 | raise ValueError('DS4Key too small.') 247 | 248 | # TODO check signature? 249 | n = bytes_to_long(bytes(ds4key.identity.modulus)) 250 | e = bytes_to_long(bytes(ds4key.identity.exponent)) 251 | p = bytes_to_long(bytes(ds4key.private_key.p)) 252 | q = bytes_to_long(bytes(ds4key.private_key.q)) 253 | dp1 = bytes_to_long(bytes(ds4key.private_key.dp1)) 254 | dq1 = bytes_to_long(bytes(ds4key.private_key.dq1)) 255 | pq = bytes_to_long(bytes(ds4key.private_key.pq)) 256 | 257 | if e > 0xffffffff: 258 | if not allow_oversized_e: 259 | raise ValueError('Public exponent is oversized') 260 | else: 261 | oversized_e = True 262 | 263 | d = Integer(e).inverse((p-1) * (q-1)) 264 | pq_from_pq = Integer(q).inverse(p) 265 | dp1_from_pq = Integer(d) % (p-1) 266 | dq1_from_pq = Integer(d) % (q-1) 267 | if Integer(pq) != pq_from_pq or Integer(dp1) != dp1_from_pq or Integer(dq1) != dq1_from_pq: 268 | raise ValueError('Bad key block (CRT factors inconsistent with P and Q)') 269 | 270 | key = RSA.construct((n, e, d, p, q), consistency_check=True) 271 | fppub = SHA256.new(key.publickey().exportKey('DER')).digest() 272 | fppriv = SHA256.new(key.exportKey('DER')).digest() 273 | return ds4key, fppub, fppriv, oversized_e 274 | 275 | def _load_key_and_check(keyfile, expected_fingerprint): 276 | if os.path.isfile(keyfile): 277 | with open(keyfile, 'rb') as f: 278 | key = RSA.importKey(f.read()) 279 | else: 280 | print('WARNING: Jedi CA does not exist. ID check will not be performed.') 281 | return None, False 282 | fingerprint_match = SHA256.new(key.exportKey('DER')).digest() == expected_fingerprint 283 | return key, fingerprint_match 284 | 285 | def _select(conn, aid): 286 | resp, sw1, sw2 = conn.transmit(APDU(cla=ISOCLA, ins=ISOINS_SELECT, p1=ISOP1_SELECT_BY_DF_NAME, p2=ISOP2_FIRST_RECORD, payload=aid).to_list()) 287 | _check_error(resp, sw1, sw2) 288 | 289 | def _do_connect_and_select(p, args): 290 | readers = scsys.readers() 291 | if len(readers) == 0: 292 | p.error('No readers found.') 293 | reader = None 294 | if args.reader is None: 295 | reader = readers[0] 296 | elif isinstance(args.reader, int): 297 | if args.reader >= len(reader): 298 | p.error(f'Invalid reader index {args.reader}') 299 | return None 300 | reader = readers[args.reader] 301 | else: 302 | for r in readers: 303 | if str(r).beginswith(args.reader): 304 | reader = r 305 | break 306 | if reader is None: 307 | p.error(f'Reader name {repr(args.reader)} does not match any connected readers.') 308 | assert reader is not None 309 | conn = reader.createConnection() 310 | if args.debug: 311 | observer = ConsoleCardConnectionObserver() 312 | conn.addObserver(observer) 313 | conn.connect() 314 | 315 | _select(conn, args.aid) 316 | return conn 317 | 318 | def _do_export_ds4id(conn): 319 | ds4id_signed = DS4SignedIdentityBlock() 320 | 321 | field_types = ( 322 | (ISCImportType.serial, sizeof(ds4id_signed.identity.serial)), 323 | (ISCImportType.pub_n, sizeof(ds4id_signed.identity.modulus)), 324 | (ISCImportType.pub_e, sizeof(ds4id_signed.identity.exponent)), 325 | (ISCImportType.sig_id, sizeof(ds4id_signed.sig_identity)), 326 | ) 327 | 328 | fields = [] 329 | 330 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.reset, 0x00, 0x00).to_list()) 331 | _check_error(resp, sw1, sw2) 332 | 333 | for type_, le in field_types: 334 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.export, type_, 0x00, le=le).to_list()) 335 | fields.extend(resp) 336 | _check_error(resp, sw1, sw2) 337 | 338 | if len(fields) != sizeof(DS4SignedIdentityBlock): 339 | raise ValueError('Unexpected length for DS4ID block.') 340 | 341 | memmove(addressof(ds4id_signed), bytes(fields), sizeof(DS4SignedIdentityBlock)) 342 | return ds4id_signed 343 | 344 | def do_list_readers(p, args): 345 | readers = scsys.readers() 346 | if len(readers) == 0: 347 | print('No readers found.') 348 | else: 349 | for i, r in enumerate(readers): 350 | print(f'#{i}: {str(r)}') 351 | 352 | def do_applet_info(p, args): 353 | with disconnectable(_do_connect_and_select(p, args)) as conn: 354 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.reset, 0x00, 0x00).to_list()) 355 | _check_error(resp, sw1, sw2) 356 | 357 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.get_version, 0x00, 0x00).to_list()) 358 | _check_error(resp, sw1, sw2) 359 | resp = bytes(resp) 360 | if len(resp) < len(ISC_MAGIC) + 2: 361 | raise ValueError(f'Unexpected response size {len(resp)} for GET_VERSION. Wrong applet?') 362 | elif resp[:len(ISC_MAGIC)] != ISC_MAGIC: 363 | raise ValueError(f'Invalid magic for GET_VERSION response. Wrong applet?') 364 | config_protocol_version = (resp[len(ISC_MAGIC)], resp[len(ISC_MAGIC)+1]) 365 | if config_protocol_version == (1, 0): 366 | applet_version = (1, 0) 367 | auth_protocol_type = ISCAuthProtocol.ps4 368 | elif config_protocol_version == (1, 1): 369 | applet_version = (resp[len(ISC_MAGIC)+2], resp[len(ISC_MAGIC)+3]) 370 | auth_protocol_type = ISCAuthProtocol(resp[len(ISC_MAGIC)+4]) 371 | else: 372 | print(f'WARNING: Unsupported protocol version {config_protocol_version[0]}.{config_protocol_version[1]}. Things might break.') 373 | applet_version = (resp[len(ISC_MAGIC)+2], resp[len(ISC_MAGIC)+3]) 374 | auth_protocol_type = ISCAuthProtocol(resp[len(ISC_MAGIC)+4]) 375 | print(f'Found IllegalSecurityChip applet version {applet_version[0]}.{applet_version[1]}') 376 | print(f'Config protocol version: {config_protocol_version[0]}.{config_protocol_version[1]}') 377 | print(f'Auth protocol type: {auth_protocol_type.name}') 378 | 379 | def do_gen_key(p, args): 380 | if not args.yes and input('WARNING: Old keys will be overwritten. Type all capital YES and press Enter to confirm or just press Enter to abort. ').strip() != 'YES': 381 | print('Aborted.') 382 | return 383 | with disconnectable(_do_connect_and_select(p, args)) as conn: 384 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.reset, 0x00, 0x00).to_list()) 385 | _check_error(resp, sw1, sw2) 386 | 387 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.gen_keys, 0x00, 0x00).to_list()) 388 | _check_error(resp, sw1, sw2) 389 | 390 | def do_is_ready(p, args): 391 | with disconnectable(_do_connect_and_select(p, args)) as conn: 392 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.reset, 0x00, 0x00).to_list()) 393 | _check_error(resp, sw1, sw2) 394 | 395 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.get_status, 0x00, 0x00).to_list()) 396 | _check_error(resp, sw1, sw2) 397 | print(f'Card is {"NOT " if resp[0] == 0x00 else ""}ready') 398 | 399 | def do_nuke(p, args): 400 | if not args.yes and input('WARNING: All data including secret keys will be permanently deleted. Type all capital YES and press Enter to confirm or just press Enter to abort. ').strip() != 'YES': 401 | print('Aborted.') 402 | return 403 | with disconnectable(_do_connect_and_select(p, args)) as conn: 404 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.nuke, 0x00, 0x00).to_list()) 405 | _check_error(resp, sw1, sw2) 406 | 407 | def do_test_auth(p, args): 408 | ca = None 409 | ca_pss = None 410 | id_verification = args.id_verification 411 | if id_verification != 'skip': 412 | ca, is_official = _load_key_and_check(args.jedi_ca_pubkey, JEDI_CA_PUBKEY_FINGERPRINT) 413 | if ca is None: 414 | id_verification = 'skip' 415 | else: 416 | if not is_official: 417 | print('Jedi CA is not official.') 418 | ca_pss = pss.new(ca) 419 | 420 | with disconnectable(_do_connect_and_select(p, args)) as conn: 421 | print('Resetting auth handler...') 422 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.auth, ISCAuthINS.reset, 0x00, 0x00).to_list()) 423 | _check_error(resp, sw1, sw2) 424 | 425 | nonce = os.urandom(0x100) 426 | sha_nonce = SHA256.new(nonce) 427 | 428 | print(f'Using nonce {nonce.hex()}') 429 | # TODO support for paging 430 | print(f'Sending nonce...') 431 | 432 | nonce_io = io.BytesIO(nonce) 433 | all_at_once = args.page_size == 0 434 | page = 0 435 | 436 | while nonce_io.tell() != len(nonce): 437 | if all_at_once: 438 | chunk = nonce_io.read() 439 | else: 440 | chunk = nonce_io.read(args.page_size) 441 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.auth, ISCAuthINS.set_challenge, args.page_size, page, payload=chunk).to_list()) 442 | _check_error(resp, sw1, sw2) 443 | page += 1 444 | print(f'Receiving response...') 445 | chunks = [] 446 | page = 0 447 | while len(chunks) < sizeof(DS4Response): 448 | if all_at_once: 449 | le = sizeof(DS4Response) 450 | else: 451 | le = min(sizeof(DS4Response) - len(chunks), args.page_size) 452 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.auth, ISCAuthINS.get_response, args.page_size, page, le=le).to_list()) 453 | chunks.extend(resp) 454 | _check_error(resp, sw1, sw2) 455 | page += 1 456 | full_response = bytes(chunks) 457 | 458 | if len(full_response) != sizeof(DS4Response): 459 | raise ValueError(f'Unexpected response size {len(full_response)} for GET_RESPONSE.') 460 | response_obj = DS4Response() 461 | memmove(addressof(response_obj), full_response, sizeof(DS4Response)) 462 | ds4id = response_obj.signed_identity.identity 463 | cuk_pub = _ds4id_to_key(ds4id) 464 | print('serial =', bytes(ds4id.serial).hex()) 465 | print('n =', bytes(ds4id.modulus).hex()) 466 | print('e =', bytes(ds4id.exponent).hex()) 467 | print('fp =', SHA256.new(cuk_pub.exportKey('DER')).hexdigest()) 468 | print() 469 | print('Begin verification.') 470 | # Verify the signature 471 | if id_verification != 'skip': 472 | sha_id = SHA256.new(bytes(ds4id)) 473 | try: 474 | ca_pss.verify(sha_id, bytes(response_obj.signed_identity.sig_identity)) 475 | except ValueError: 476 | print('ID NG.') 477 | if id_verification == 'strict': 478 | return 479 | else: 480 | print('ID OK.') 481 | # Verify the response 482 | sig = response_obj.sig 483 | cuk_pss = pss.new(cuk_pub) 484 | try: 485 | cuk_pss.verify(sha_nonce, bytes(sig)) 486 | except ValueError: 487 | print('Response NG.') 488 | else: 489 | print('Response OK.') 490 | 491 | def do_import_ds4key(p, args): 492 | ds4key, fp_pub, fp_priv, oversized_e = _load_ds4key_and_check(args.ds4key_file, args.allow_oversized_exponent) 493 | print('fp_pub =', fp_pub.hex()) 494 | print('fp_priv =', fp_priv.hex()) 495 | 496 | if not args.yes and input('WARNING: Any installed keys will be overwritten. Type all capital YES and press Enter to confirm or just press Enter to abort. ').strip() != 'YES': 497 | print('Aborted.') 498 | return 499 | with disconnectable(_do_connect_and_select(p, args)) as conn: 500 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.reset, 0x00, 0x00).to_list()) 501 | _check_error(resp, sw1, sw2) 502 | 503 | print('Uploading DS4Key...') 504 | 505 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.import_, ISCImportType.serial, 0x00, payload=ds4key.identity.serial).to_list()) 506 | _check_error(resp, sw1, sw2) 507 | 508 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.import_, ISCImportType.pub_n, 0x00, payload=ds4key.identity.modulus).to_list()) 509 | _check_error(resp, sw1, sw2) 510 | 511 | if oversized_e: 512 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.import_, ISCImportType.pub_e, 0x00, payload=ds4key.identity.exponent).to_list()) 513 | else: 514 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.import_, ISCImportType.pub_e_compat, 0x00, payload=ds4key.identity.exponent[-4:]).to_list()) 515 | _check_error(resp, sw1, sw2) 516 | 517 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.import_, ISCImportType.sig_id, 0x00, payload=ds4key.sig_identity).to_list()) 518 | _check_error(resp, sw1, sw2) 519 | 520 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.import_, ISCImportType.priv_p, 0x00, payload=ds4key.private_key.p).to_list()) 521 | _check_error(resp, sw1, sw2) 522 | 523 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.import_, ISCImportType.priv_q, 0x00, payload=ds4key.private_key.q).to_list()) 524 | _check_error(resp, sw1, sw2) 525 | 526 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.import_, ISCImportType.priv_pq, 0x00, payload=ds4key.private_key.pq).to_list()) 527 | _check_error(resp, sw1, sw2) 528 | 529 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.import_, ISCImportType.priv_dp1, 0x00, payload=ds4key.private_key.dp1).to_list()) 530 | _check_error(resp, sw1, sw2) 531 | 532 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.import_, ISCImportType.priv_dq1, 0x00, payload=ds4key.private_key.dq1).to_list()) 533 | _check_error(resp, sw1, sw2) 534 | 535 | def do_export_ds4id(p, args): 536 | with disconnectable(_do_connect_and_select(p, args)) as conn: 537 | ds4id_signed = _do_export_ds4id(conn) 538 | 539 | with open(args.ds4id_file, 'wb') as f: 540 | f.write(ds4id_signed.identity) 541 | with open(f'{args.ds4id_file}.sig', 'wb') as f: 542 | f.write(ds4id_signed.sig_identity) 543 | 544 | def do_set_serial(p, args): 545 | if len(args.serial) != 16: 546 | raise ValueError('Serial number is not 16 bytes long.') 547 | 548 | with disconnectable(_do_connect_and_select(p, args)) as conn: 549 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.import_, ISCImportType.serial, 0x00, payload=args.serial).to_list()) 550 | _check_error(resp, sw1, sw2) 551 | 552 | def do_sign_ds4id(p, args): 553 | ca_pss = None 554 | 555 | if args.jedi_ca_privkey is not None: 556 | ca, _ = _load_key_and_check(args.jedi_ca_privkey, JEDI_CA_PUBKEY_FINGERPRINT) 557 | ca_pss = pss.new(ca) 558 | if not ca_pss.can_sign(): 559 | raise TypeError('Jedi CA private key not present in the key file.') 560 | 561 | with disconnectable(_do_connect_and_select(p, args)) as conn: 562 | if ca_pss is not None: 563 | print('Exporting DS4ID from card...') 564 | ds4id_signed = _do_export_ds4id(conn) 565 | 566 | sha_id = SHA256.new(bytes(ds4id_signed.identity)) 567 | sig = ca_pss.sign(sha_id) 568 | else: 569 | assert args.sig_binary is not None 570 | with open(args.sig_binary, 'rb') as f: 571 | sig = f.read() 572 | if len(sig) != 0x100: 573 | raise TypeError('Wrong signature file size.') 574 | 575 | print('Importing new signature...') 576 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.import_, ISCImportType.sig_id, 0x00, payload=sig).to_list()) 577 | _check_error(resp, sw1, sw2) 578 | 579 | def do_enter_stealth_mode(p, args): 580 | if not args.yes and input('WARNING: Entering stealth mode will permanently disable the configuration interface for the rest of the applet life-cycle. This cannot be undone without reinstalling the applet. Type all capital YES and press Enter to confirm or just press Enter to abort. ').strip() != 'YES': 581 | print('Aborted.') 582 | return 583 | with disconnectable(_do_connect_and_select(p, args)) as conn: 584 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.reset, 0x00, 0x00).to_list()) 585 | _check_error(resp, sw1, sw2) 586 | resp, sw1, sw2 = conn.transmit(APDU(ISCCLA.config, ISCConfigINS.enter_stealth_mode, 0x00, 0x00).to_list()) 587 | _check_error(resp, sw1, sw2) 588 | 589 | ACTIONS = { 590 | 'list-readers': do_list_readers, 591 | 'applet-info': do_applet_info, 592 | 'is-ready': do_is_ready, 593 | 'test-auth': do_test_auth, 594 | 'import-ds4key': do_import_ds4key, 595 | 'export-ds4id': do_export_ds4id, 596 | 'set-serial': do_set_serial, 597 | 'sign-ds4id': do_sign_ds4id, 598 | 'gen-key': do_gen_key, 599 | 'enter-stealth-mode': do_enter_stealth_mode, 600 | 'nuke': do_nuke, 601 | } 602 | 603 | if __name__ == '__main__': 604 | p, args = parse_args() 605 | action = ACTIONS.get(args.action) 606 | if action is None: 607 | raise NotImplemented(f'Action {args.action} is not implemented.') 608 | action(p, args) 609 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | ### GNU GENERAL PUBLIC LICENSE 2 | 3 | Version 3, 29 June 2007 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. 6 | 7 | 8 | Everyone is permitted to copy and distribute verbatim copies of this 9 | license document, but changing it is not allowed. 10 | 11 | ### Preamble 12 | 13 | The GNU General Public License is a free, copyleft license for 14 | software and other kinds of works. 15 | 16 | The licenses for most software and other practical works are designed 17 | to take away your freedom to share and change the works. By contrast, 18 | the GNU General Public License is intended to guarantee your freedom 19 | to share and change all versions of a program--to make sure it remains 20 | free software for all its users. We, the Free Software Foundation, use 21 | the GNU General Public License for most of our software; it applies 22 | also to any other work released this way by its authors. You can apply 23 | it to your programs, too. 24 | 25 | When we speak of free software, we are referring to freedom, not 26 | price. Our General Public Licenses are designed to make sure that you 27 | have the freedom to distribute copies of free software (and charge for 28 | them if you wish), that you receive source code or can get it if you 29 | want it, that you can change the software or use pieces of it in new 30 | free programs, and that you know you can do these things. 31 | 32 | To protect your rights, we need to prevent others from denying you 33 | these rights or asking you to surrender the rights. Therefore, you 34 | have certain responsibilities if you distribute copies of the 35 | software, or if you modify it: responsibilities to respect the freedom 36 | of others. 37 | 38 | For example, if you distribute copies of such a program, whether 39 | gratis or for a fee, you must pass on to the recipients the same 40 | freedoms that you received. You must make sure that they, too, receive 41 | or can get the source code. And you must show them these terms so they 42 | know their rights. 43 | 44 | Developers that use the GNU GPL protect your rights with two steps: 45 | (1) assert copyright on the software, and (2) offer you this License 46 | giving you legal permission to copy, distribute and/or modify it. 47 | 48 | For the developers' and authors' protection, the GPL clearly explains 49 | that there is no warranty for this free software. For both users' and 50 | authors' sake, the GPL requires that modified versions be marked as 51 | changed, so that their problems will not be attributed erroneously to 52 | authors of previous versions. 53 | 54 | Some devices are designed to deny users access to install or run 55 | modified versions of the software inside them, although the 56 | manufacturer can do so. This is fundamentally incompatible with the 57 | aim of protecting users' freedom to change the software. The 58 | systematic pattern of such abuse occurs in the area of products for 59 | individuals to use, which is precisely where it is most unacceptable. 60 | Therefore, we have designed this version of the GPL to prohibit the 61 | practice for those products. If such problems arise substantially in 62 | other domains, we stand ready to extend this provision to those 63 | domains in future versions of the GPL, as needed to protect the 64 | freedom of users. 65 | 66 | Finally, every program is threatened constantly by software patents. 67 | States should not allow patents to restrict development and use of 68 | software on general-purpose computers, but in those that do, we wish 69 | to avoid the special danger that patents applied to a free program 70 | could make it effectively proprietary. To prevent this, the GPL 71 | assures that patents cannot be used to render the program non-free. 72 | 73 | The precise terms and conditions for copying, distribution and 74 | modification follow. 75 | 76 | ### TERMS AND CONDITIONS 77 | 78 | #### 0. Definitions. 79 | 80 | "This License" refers to version 3 of the GNU General Public License. 81 | 82 | "Copyright" also means copyright-like laws that apply to other kinds 83 | of works, such as semiconductor masks. 84 | 85 | "The Program" refers to any copyrightable work licensed under this 86 | License. Each licensee is addressed as "you". "Licensees" and 87 | "recipients" may be individuals or organizations. 88 | 89 | To "modify" a work means to copy from or adapt all or part of the work 90 | in a fashion requiring copyright permission, other than the making of 91 | an exact copy. The resulting work is called a "modified version" of 92 | the earlier work or a work "based on" the earlier work. 93 | 94 | A "covered work" means either the unmodified Program or a work based 95 | on the Program. 96 | 97 | To "propagate" a work means to do anything with it that, without 98 | permission, would make you directly or secondarily liable for 99 | infringement under applicable copyright law, except executing it on a 100 | computer or modifying a private copy. Propagation includes copying, 101 | distribution (with or without modification), making available to the 102 | public, and in some countries other activities as well. 103 | 104 | To "convey" a work means any kind of propagation that enables other 105 | parties to make or receive copies. Mere interaction with a user 106 | through a computer network, with no transfer of a copy, is not 107 | conveying. 108 | 109 | An interactive user interface displays "Appropriate Legal Notices" to 110 | the extent that it includes a convenient and prominently visible 111 | feature that (1) displays an appropriate copyright notice, and (2) 112 | tells the user that there is no warranty for the work (except to the 113 | extent that warranties are provided), that licensees may convey the 114 | work under this License, and how to view a copy of this License. If 115 | the interface presents a list of user commands or options, such as a 116 | menu, a prominent item in the list meets this criterion. 117 | 118 | #### 1. Source Code. 119 | 120 | The "source code" for a work means the preferred form of the work for 121 | making modifications to it. "Object code" means any non-source form of 122 | a work. 123 | 124 | A "Standard Interface" means an interface that either is an official 125 | standard defined by a recognized standards body, or, in the case of 126 | interfaces specified for a particular programming language, one that 127 | is widely used among developers working in that language. 128 | 129 | The "System Libraries" of an executable work include anything, other 130 | than the work as a whole, that (a) is included in the normal form of 131 | packaging a Major Component, but which is not part of that Major 132 | Component, and (b) serves only to enable use of the work with that 133 | Major Component, or to implement a Standard Interface for which an 134 | implementation is available to the public in source code form. A 135 | "Major Component", in this context, means a major essential component 136 | (kernel, window system, and so on) of the specific operating system 137 | (if any) on which the executable work runs, or a compiler used to 138 | produce the work, or an object code interpreter used to run it. 139 | 140 | The "Corresponding Source" for a work in object code form means all 141 | the source code needed to generate, install, and (for an executable 142 | work) run the object code and to modify the work, including scripts to 143 | control those activities. However, it does not include the work's 144 | System Libraries, or general-purpose tools or generally available free 145 | programs which are used unmodified in performing those activities but 146 | which are not part of the work. For example, Corresponding Source 147 | includes interface definition files associated with source files for 148 | the work, and the source code for shared libraries and dynamically 149 | linked subprograms that the work is specifically designed to require, 150 | such as by intimate data communication or control flow between those 151 | subprograms and other parts of the work. 152 | 153 | The Corresponding Source need not include anything that users can 154 | regenerate automatically from other parts of the Corresponding Source. 155 | 156 | The Corresponding Source for a work in source code form is that same 157 | work. 158 | 159 | #### 2. Basic Permissions. 160 | 161 | All rights granted under this License are granted for the term of 162 | copyright on the Program, and are irrevocable provided the stated 163 | conditions are met. This License explicitly affirms your unlimited 164 | permission to run the unmodified Program. The output from running a 165 | covered work is covered by this License only if the output, given its 166 | content, constitutes a covered work. This License acknowledges your 167 | rights of fair use or other equivalent, as provided by copyright law. 168 | 169 | You may make, run and propagate covered works that you do not convey, 170 | without conditions so long as your license otherwise remains in force. 171 | You may convey covered works to others for the sole purpose of having 172 | them make modifications exclusively for you, or provide you with 173 | facilities for running those works, provided that you comply with the 174 | terms of this License in conveying all material for which you do not 175 | control copyright. Those thus making or running the covered works for 176 | you must do so exclusively on your behalf, under your direction and 177 | control, on terms that prohibit them from making any copies of your 178 | copyrighted material outside their relationship with you. 179 | 180 | Conveying under any other circumstances is permitted solely under the 181 | conditions stated below. Sublicensing is not allowed; section 10 makes 182 | it unnecessary. 183 | 184 | #### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 185 | 186 | No covered work shall be deemed part of an effective technological 187 | measure under any applicable law fulfilling obligations under article 188 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 189 | similar laws prohibiting or restricting circumvention of such 190 | measures. 191 | 192 | When you convey a covered work, you waive any legal power to forbid 193 | circumvention of technological measures to the extent such 194 | circumvention is effected by exercising rights under this License with 195 | respect to the covered work, and you disclaim any intention to limit 196 | operation or modification of the work as a means of enforcing, against 197 | the work's users, your or third parties' legal rights to forbid 198 | circumvention of technological measures. 199 | 200 | #### 4. Conveying Verbatim Copies. 201 | 202 | You may convey verbatim copies of the Program's source code as you 203 | receive it, in any medium, provided that you conspicuously and 204 | appropriately publish on each copy an appropriate copyright notice; 205 | keep intact all notices stating that this License and any 206 | non-permissive terms added in accord with section 7 apply to the code; 207 | keep intact all notices of the absence of any warranty; and give all 208 | recipients a copy of this License along with the Program. 209 | 210 | You may charge any price or no price for each copy that you convey, 211 | and you may offer support or warranty protection for a fee. 212 | 213 | #### 5. Conveying Modified Source Versions. 214 | 215 | You may convey a work based on the Program, or the modifications to 216 | produce it from the Program, in the form of source code under the 217 | terms of section 4, provided that you also meet all of these 218 | conditions: 219 | 220 | - a) The work must carry prominent notices stating that you modified 221 | it, and giving a relevant date. 222 | - b) The work must carry prominent notices stating that it is 223 | released under this License and any conditions added under 224 | section 7. This requirement modifies the requirement in section 4 225 | to "keep intact all notices". 226 | - c) You must license the entire work, as a whole, under this 227 | License to anyone who comes into possession of a copy. This 228 | License will therefore apply, along with any applicable section 7 229 | additional terms, to the whole of the work, and all its parts, 230 | regardless of how they are packaged. This License gives no 231 | permission to license the work in any other way, but it does not 232 | invalidate such permission if you have separately received it. 233 | - d) If the work has interactive user interfaces, each must display 234 | Appropriate Legal Notices; however, if the Program has interactive 235 | interfaces that do not display Appropriate Legal Notices, your 236 | work need not make them do so. 237 | 238 | A compilation of a covered work with other separate and independent 239 | works, which are not by their nature extensions of the covered work, 240 | and which are not combined with it such as to form a larger program, 241 | in or on a volume of a storage or distribution medium, is called an 242 | "aggregate" if the compilation and its resulting copyright are not 243 | used to limit the access or legal rights of the compilation's users 244 | beyond what the individual works permit. Inclusion of a covered work 245 | in an aggregate does not cause this License to apply to the other 246 | parts of the aggregate. 247 | 248 | #### 6. Conveying Non-Source Forms. 249 | 250 | You may convey a covered work in object code form under the terms of 251 | sections 4 and 5, provided that you also convey the machine-readable 252 | Corresponding Source under the terms of this License, in one of these 253 | ways: 254 | 255 | - a) Convey the object code in, or embodied in, a physical product 256 | (including a physical distribution medium), accompanied by the 257 | Corresponding Source fixed on a durable physical medium 258 | customarily used for software interchange. 259 | - b) Convey the object code in, or embodied in, a physical product 260 | (including a physical distribution medium), accompanied by a 261 | written offer, valid for at least three years and valid for as 262 | long as you offer spare parts or customer support for that product 263 | model, to give anyone who possesses the object code either (1) a 264 | copy of the Corresponding Source for all the software in the 265 | product that is covered by this License, on a durable physical 266 | medium customarily used for software interchange, for a price no 267 | more than your reasonable cost of physically performing this 268 | conveying of source, or (2) access to copy the Corresponding 269 | Source from a network server at no charge. 270 | - c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | - d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | - e) Convey the object code using peer-to-peer transmission, 288 | provided you inform other peers where the object code and 289 | Corresponding Source of the work are being offered to the general 290 | public at no charge under subsection 6d. 291 | 292 | A separable portion of the object code, whose source code is excluded 293 | from the Corresponding Source as a System Library, need not be 294 | included in conveying the object code work. 295 | 296 | A "User Product" is either (1) a "consumer product", which means any 297 | tangible personal property which is normally used for personal, 298 | family, or household purposes, or (2) anything designed or sold for 299 | incorporation into a dwelling. In determining whether a product is a 300 | consumer product, doubtful cases shall be resolved in favor of 301 | coverage. For a particular product received by a particular user, 302 | "normally used" refers to a typical or common use of that class of 303 | product, regardless of the status of the particular user or of the way 304 | in which the particular user actually uses, or expects or is expected 305 | to use, the product. A product is a consumer product regardless of 306 | whether the product has substantial commercial, industrial or 307 | non-consumer uses, unless such uses represent the only significant 308 | mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to 312 | install and execute modified versions of a covered work in that User 313 | Product from a modified version of its Corresponding Source. The 314 | information must suffice to ensure that the continued functioning of 315 | the modified object code is in no case prevented or interfered with 316 | solely because modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or 331 | updates for a work that has been modified or installed by the 332 | recipient, or for the User Product in which it has been modified or 333 | installed. Access to a network may be denied when the modification 334 | itself materially and adversely affects the operation of the network 335 | or violates the rules and protocols for communication across the 336 | network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | #### 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders 364 | of that material) supplement the terms of this License with terms: 365 | 366 | - a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | - b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | - c) Prohibiting misrepresentation of the origin of that material, 372 | or requiring that modified versions of such material be marked in 373 | reasonable ways as different from the original version; or 374 | - d) Limiting the use for publicity purposes of names of licensors 375 | or authors of the material; or 376 | - e) Declining to grant rights under trademark law for use of some 377 | trade names, trademarks, or service marks; or 378 | - f) Requiring indemnification of licensors and authors of that 379 | material by anyone who conveys the material (or modified versions 380 | of it) with contractual assumptions of liability to the recipient, 381 | for any liability that these contractual assumptions directly 382 | impose on those licensors and authors. 383 | 384 | All other non-permissive additional terms are considered "further 385 | restrictions" within the meaning of section 10. If the Program as you 386 | received it, or any part of it, contains a notice stating that it is 387 | governed by this License along with a term that is a further 388 | restriction, you may remove that term. If a license document contains 389 | a further restriction but permits relicensing or conveying under this 390 | License, you may add to a covered work material governed by the terms 391 | of that license document, provided that the further restriction does 392 | not survive such relicensing or conveying. 393 | 394 | If you add terms to a covered work in accord with this section, you 395 | must place, in the relevant source files, a statement of the 396 | additional terms that apply to those files, or a notice indicating 397 | where to find the applicable terms. 398 | 399 | Additional terms, permissive or non-permissive, may be stated in the 400 | form of a separately written license, or stated as exceptions; the 401 | above requirements apply either way. 402 | 403 | #### 8. Termination. 404 | 405 | You may not propagate or modify a covered work except as expressly 406 | provided under this License. Any attempt otherwise to propagate or 407 | modify it is void, and will automatically terminate your rights under 408 | this License (including any patent licenses granted under the third 409 | paragraph of section 11). 410 | 411 | However, if you cease all violation of this License, then your license 412 | from a particular copyright holder is reinstated (a) provisionally, 413 | unless and until the copyright holder explicitly and finally 414 | terminates your license, and (b) permanently, if the copyright holder 415 | fails to notify you of the violation by some reasonable means prior to 416 | 60 days after the cessation. 417 | 418 | Moreover, your license from a particular copyright holder is 419 | reinstated permanently if the copyright holder notifies you of the 420 | violation by some reasonable means, this is the first time you have 421 | received notice of violation of this License (for any work) from that 422 | copyright holder, and you cure the violation prior to 30 days after 423 | your receipt of the notice. 424 | 425 | Termination of your rights under this section does not terminate the 426 | licenses of parties who have received copies or rights from you under 427 | this License. If your rights have been terminated and not permanently 428 | reinstated, you do not qualify to receive new licenses for the same 429 | material under section 10. 430 | 431 | #### 9. Acceptance Not Required for Having Copies. 432 | 433 | You are not required to accept this License in order to receive or run 434 | a copy of the Program. Ancillary propagation of a covered work 435 | occurring solely as a consequence of using peer-to-peer transmission 436 | to receive a copy likewise does not require acceptance. However, 437 | nothing other than this License grants you permission to propagate or 438 | modify any covered work. These actions infringe copyright if you do 439 | not accept this License. Therefore, by modifying or propagating a 440 | covered work, you indicate your acceptance of this License to do so. 441 | 442 | #### 10. Automatic Licensing of Downstream Recipients. 443 | 444 | Each time you convey a covered work, the recipient automatically 445 | receives a license from the original licensors, to run, modify and 446 | propagate that work, subject to this License. You are not responsible 447 | for enforcing compliance by third parties with this License. 448 | 449 | An "entity transaction" is a transaction transferring control of an 450 | organization, or substantially all assets of one, or subdividing an 451 | organization, or merging organizations. If propagation of a covered 452 | work results from an entity transaction, each party to that 453 | transaction who receives a copy of the work also receives whatever 454 | licenses to the work the party's predecessor in interest had or could 455 | give under the previous paragraph, plus a right to possession of the 456 | Corresponding Source of the work from the predecessor in interest, if 457 | the predecessor has it or can get it with reasonable efforts. 458 | 459 | You may not impose any further restrictions on the exercise of the 460 | rights granted or affirmed under this License. For example, you may 461 | not impose a license fee, royalty, or other charge for exercise of 462 | rights granted under this License, and you may not initiate litigation 463 | (including a cross-claim or counterclaim in a lawsuit) alleging that 464 | any patent claim is infringed by making, using, selling, offering for 465 | sale, or importing the Program or any portion of it. 466 | 467 | #### 11. Patents. 468 | 469 | A "contributor" is a copyright holder who authorizes use under this 470 | License of the Program or a work on which the Program is based. The 471 | work thus licensed is called the contributor's "contributor version". 472 | 473 | A contributor's "essential patent claims" are all patent claims owned 474 | or controlled by the contributor, whether already acquired or 475 | hereafter acquired, that would be infringed by some manner, permitted 476 | by this License, of making, using, or selling its contributor version, 477 | but do not include claims that would be infringed only as a 478 | consequence of further modification of the contributor version. For 479 | purposes of this definition, "control" includes the right to grant 480 | patent sublicenses in a manner consistent with the requirements of 481 | this License. 482 | 483 | Each contributor grants you a non-exclusive, worldwide, royalty-free 484 | patent license under the contributor's essential patent claims, to 485 | make, use, sell, offer for sale, import and otherwise run, modify and 486 | propagate the contents of its contributor version. 487 | 488 | In the following three paragraphs, a "patent license" is any express 489 | agreement or commitment, however denominated, not to enforce a patent 490 | (such as an express permission to practice a patent or covenant not to 491 | sue for patent infringement). To "grant" such a patent license to a 492 | party means to make such an agreement or commitment not to enforce a 493 | patent against the party. 494 | 495 | If you convey a covered work, knowingly relying on a patent license, 496 | and the Corresponding Source of the work is not available for anyone 497 | to copy, free of charge and under the terms of this License, through a 498 | publicly available network server or other readily accessible means, 499 | then you must either (1) cause the Corresponding Source to be so 500 | available, or (2) arrange to deprive yourself of the benefit of the 501 | patent license for this particular work, or (3) arrange, in a manner 502 | consistent with the requirements of this License, to extend the patent 503 | license to downstream recipients. "Knowingly relying" means you have 504 | actual knowledge that, but for the patent license, your conveying the 505 | covered work in a country, or your recipient's use of the covered work 506 | in a country, would infringe one or more identifiable patents in that 507 | country that you have reason to believe are valid. 508 | 509 | If, pursuant to or in connection with a single transaction or 510 | arrangement, you convey, or propagate by procuring conveyance of, a 511 | covered work, and grant a patent license to some of the parties 512 | receiving the covered work authorizing them to use, propagate, modify 513 | or convey a specific copy of the covered work, then the patent license 514 | you grant is automatically extended to all recipients of the covered 515 | work and works based on it. 516 | 517 | A patent license is "discriminatory" if it does not include within the 518 | scope of its coverage, prohibits the exercise of, or is conditioned on 519 | the non-exercise of one or more of the rights that are specifically 520 | granted under this License. You may not convey a covered work if you 521 | are a party to an arrangement with a third party that is in the 522 | business of distributing software, under which you make payment to the 523 | third party based on the extent of your activity of conveying the 524 | work, and under which the third party grants, to any of the parties 525 | who would receive the covered work from you, a discriminatory patent 526 | license (a) in connection with copies of the covered work conveyed by 527 | you (or copies made from those copies), or (b) primarily for and in 528 | connection with specific products or compilations that contain the 529 | covered work, unless you entered into that arrangement, or that patent 530 | license was granted, prior to 28 March 2007. 531 | 532 | Nothing in this License shall be construed as excluding or limiting 533 | any implied license or other defenses to infringement that may 534 | otherwise be available to you under applicable patent law. 535 | 536 | #### 12. No Surrender of Others' Freedom. 537 | 538 | If conditions are imposed on you (whether by court order, agreement or 539 | otherwise) that contradict the conditions of this License, they do not 540 | excuse you from the conditions of this License. If you cannot convey a 541 | covered work so as to satisfy simultaneously your obligations under 542 | this License and any other pertinent obligations, then as a 543 | consequence you may not convey it at all. For example, if you agree to 544 | terms that obligate you to collect a royalty for further conveying 545 | from those to whom you convey the Program, the only way you could 546 | satisfy both those terms and this License would be to refrain entirely 547 | from conveying the Program. 548 | 549 | #### 13. Use with the GNU Affero General Public License. 550 | 551 | Notwithstanding any other provision of this License, you have 552 | permission to link or combine any covered work with a work licensed 553 | under version 3 of the GNU Affero General Public License into a single 554 | combined work, and to convey the resulting work. The terms of this 555 | License will continue to apply to the part which is the covered work, 556 | but the special requirements of the GNU Affero General Public License, 557 | section 13, concerning interaction through a network will apply to the 558 | combination as such. 559 | 560 | #### 14. Revised Versions of this License. 561 | 562 | The Free Software Foundation may publish revised and/or new versions 563 | of the GNU General Public License from time to time. Such new versions 564 | will be similar in spirit to the present version, but may differ in 565 | detail to address new problems or concerns. 566 | 567 | Each version is given a distinguishing version number. If the Program 568 | specifies that a certain numbered version of the GNU General Public 569 | License "or any later version" applies to it, you have the option of 570 | following the terms and conditions either of that numbered version or 571 | of any later version published by the Free Software Foundation. If the 572 | Program does not specify a version number of the GNU General Public 573 | License, you may choose any version ever published by the Free 574 | Software Foundation. 575 | 576 | If the Program specifies that a proxy can decide which future versions 577 | of the GNU General Public License can be used, that proxy's public 578 | statement of acceptance of a version permanently authorizes you to 579 | choose that version for the Program. 580 | 581 | Later license versions may give you additional or different 582 | permissions. However, no additional obligations are imposed on any 583 | author or copyright holder as a result of your choosing to follow a 584 | later version. 585 | 586 | #### 15. Disclaimer of Warranty. 587 | 588 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 589 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 590 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 591 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT 592 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 593 | A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 594 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 595 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 596 | CORRECTION. 597 | 598 | #### 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR 602 | CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 603 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES 604 | ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT 605 | NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR 606 | LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM 607 | TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER 608 | PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 609 | 610 | #### 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | ### How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these 626 | terms. 627 | 628 | To do so, attach the following notices to the program. It is safest to 629 | attach them to the start of each source file to most effectively state 630 | the exclusion of warranty; and each file should have at least the 631 | "copyright" line and a pointer to where the full notice is found. 632 | 633 | 634 | Copyright (C) 635 | 636 | This program is free software: you can redistribute it and/or modify 637 | it under the terms of the GNU General Public License as published by 638 | the Free Software Foundation, either version 3 of the License, or 639 | (at your option) any later version. 640 | 641 | This program is distributed in the hope that it will be useful, 642 | but WITHOUT ANY WARRANTY; without even the implied warranty of 643 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 644 | GNU General Public License for more details. 645 | 646 | You should have received a copy of the GNU General Public License 647 | along with this program. If not, see . 648 | 649 | Also add information on how to contact you by electronic and paper 650 | mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands \`show w' and \`show c' should show the 661 | appropriate parts of the General Public License. Of course, your 662 | program's commands might be different; for a GUI interface, you would 663 | use an "about box". 664 | 665 | You should also get your employer (if you work as a programmer) or 666 | school, if any, to sign a "copyright disclaimer" for the program, if 667 | necessary. For more information on this, and how to apply and follow 668 | the GNU GPL, see . 669 | 670 | The GNU General Public License does not permit incorporating your 671 | program into proprietary programs. If your program is a subroutine 672 | library, you may consider it more useful to permit linking proprietary 673 | applications with the library. If this is what you want to do, use the 674 | GNU Lesser General Public License instead of this License. But first, 675 | please read . 676 | --------------------------------------------------------------------------------