├── .gitignore ├── prebuilt ├── openjavacard-ndef-full-plain.cap ├── openjavacard-ndef-full-plain.jar ├── openjavacard-ndef-stub-plain.cap ├── openjavacard-ndef-stub-plain.jar ├── openjavacard-ndef-tiny-plain.cap └── openjavacard-ndef-tiny-plain.jar ├── .travis.yml ├── install-full-default.script ├── ant.sh ├── install-full-2k-open.script ├── install-full-2k-writeonce.script ├── install-full-2k-writecontact.script ├── proguard-tiny.map ├── .gitmodules ├── client └── src │ └── main │ └── java │ └── org │ └── openjavacard │ └── ndef │ └── client │ ├── NdefFile.java │ ├── NdefProtocol.java │ ├── NdefCapabilities.java │ ├── Main.java │ └── NdefClient.java ├── doc ├── compatibility.md ├── protocol.md ├── variants.md └── install.md ├── proguard-full.map ├── applet-stub └── src │ └── main │ └── java │ └── org │ └── openjavacard │ └── ndef │ └── stub │ ├── NdefService.java │ └── NdefApplet.java ├── library-generator └── src │ └── main │ └── java │ └── org │ └── openjavacard │ └── ndef │ └── generator │ ├── NdefGenerator.java │ └── NdefConstants.java ├── README.md ├── applet-full └── src │ └── main │ └── java │ └── org │ └── openjavacard │ └── ndef │ └── full │ ├── UtilTLV.java │ └── NdefApplet.java ├── applet-advanced └── src │ └── main │ └── java │ └── org │ └── openjavacard │ └── ndef │ └── advanced │ ├── UtilTLV.java │ └── NdefApplet.java ├── applet-tiny └── src │ └── main │ └── java │ └── org │ └── openjavacard │ └── ndef │ └── tiny │ └── NdefApplet.java └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/** 3 | */build 4 | -------------------------------------------------------------------------------- /prebuilt/openjavacard-ndef-full-plain.cap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenJavaCard/openjavacard-ndef/HEAD/prebuilt/openjavacard-ndef-full-plain.cap -------------------------------------------------------------------------------- /prebuilt/openjavacard-ndef-full-plain.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenJavaCard/openjavacard-ndef/HEAD/prebuilt/openjavacard-ndef-full-plain.jar -------------------------------------------------------------------------------- /prebuilt/openjavacard-ndef-stub-plain.cap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenJavaCard/openjavacard-ndef/HEAD/prebuilt/openjavacard-ndef-stub-plain.cap -------------------------------------------------------------------------------- /prebuilt/openjavacard-ndef-stub-plain.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenJavaCard/openjavacard-ndef/HEAD/prebuilt/openjavacard-ndef-stub-plain.jar -------------------------------------------------------------------------------- /prebuilt/openjavacard-ndef-tiny-plain.cap: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenJavaCard/openjavacard-ndef/HEAD/prebuilt/openjavacard-ndef-tiny-plain.cap -------------------------------------------------------------------------------- /prebuilt/openjavacard-ndef-tiny-plain.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenJavaCard/openjavacard-ndef/HEAD/prebuilt/openjavacard-ndef-tiny-plain.jar -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - openjdk8 4 | script: 5 | - ant clean 6 | - ant test 7 | addons: 8 | apt: 9 | packages: 10 | - ant 11 | - ant-optional 12 | - junit4 13 | -------------------------------------------------------------------------------- /install-full-default.script: -------------------------------------------------------------------------------- 1 | gp-load --reload \ 2 | build/javacard/openjavacard-ndef-full-plain.cap 3 | 4 | gp-install --reinstall \ 5 | --package D276000177100211010001 \ 6 | --module D27600017710021101000101 \ 7 | --aid D2760000850101 8 | -------------------------------------------------------------------------------- /ant.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | export PATH=/usr/lib/jvm/oracle-java8-jdk-amd64/bin:$PATH 3 | export JAVA_HOME=/usr/lib/jvm/oracle-java8-jdk-amd64 4 | export JAVACARD_HOME=/home/user/Exports/javacard-sdk/jc222_kit/ 5 | ant -DJAVACARD_HOME=$JAVACARD_HOME $@ 6 | -------------------------------------------------------------------------------- /install-full-2k-open.script: -------------------------------------------------------------------------------- 1 | gp-load --reload \ 2 | build/javacard/openjavacard-ndef-full-plain.cap 3 | 4 | gp-install --reinstall \ 5 | --package D276000177100211010001 \ 6 | --module D27600017710021101000101 \ 7 | --aid D2760000850101 \ 8 | --parameters 8102000082020800 9 | -------------------------------------------------------------------------------- /install-full-2k-writeonce.script: -------------------------------------------------------------------------------- 1 | gp-load --reload \ 2 | build/javacard/openjavacard-ndef-full-plain.cap 3 | 4 | gp-install --reinstall \ 5 | --package D276000177100211010001 \ 6 | --module D27600017710021101000101 \ 7 | --aid D2760000850101 \ 8 | --parameters 810200F182020800 9 | -------------------------------------------------------------------------------- /install-full-2k-writecontact.script: -------------------------------------------------------------------------------- 1 | gp-load --reload \ 2 | build/javacard/openjavacard-ndef-full-plain.cap 3 | 4 | gp-install --reinstall \ 5 | --package D276000177100211010001 \ 6 | --module D27600017710021101000101 \ 7 | --aid D2760000850101 \ 8 | --parameters 810200F082020800 9 | -------------------------------------------------------------------------------- /proguard-tiny.map: -------------------------------------------------------------------------------- 1 | org.openjavacard.ndef.tiny.NdefApplet -> tiny.A: 2 | short selectedFile -> a 3 | byte[] capsFile -> b 4 | byte[] dataFile -> c 5 | void install(byte[],short,byte) -> install 6 | void (byte[],short,byte) -> 7 | void process(javacard.framework.APDU) -> process 8 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "ext/ant-javacard"] 2 | path = ext/ant-javacard 3 | url = https://github.com/promovicz/ant-javacard.git 4 | branch = master 5 | [submodule "ext/javacard-sdks"] 6 | path = ext/javacard-sdks 7 | url = https://github.com/martinpaljak/oracle_javacard_sdks.git 8 | [submodule "ext/globalplatform-exports"] 9 | path = ext/globalplatform-exports 10 | url = https://github.com/OpenJavaCard/globalplatform-exports.git 11 | -------------------------------------------------------------------------------- /client/src/main/java/org/openjavacard/ndef/client/NdefFile.java: -------------------------------------------------------------------------------- 1 | package org.openjavacard.ndef.client; 2 | 3 | import org.openjavacard.util.BinUtil; 4 | 5 | public class NdefFile { 6 | short fileId; 7 | int fileSize; 8 | byte readAccess; 9 | byte writeAccess; 10 | 11 | NdefFile(byte[] data, int off) { 12 | fileId = BinUtil.getShort(data, off + 0); 13 | fileSize = BinUtil.getShort(data, off + 2) & 0xFFFF; 14 | readAccess = data[off + 4]; 15 | writeAccess = data[off + 5]; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /doc/compatibility.md: -------------------------------------------------------------------------------- 1 | ## Compatibility 2 | 3 | #### Card requirements 4 | 5 | * Support for JavaCard 2.2 or higher 6 | * Code memory: between 1k and 4k depending on variant 7 | * Data memory: from a few bytes up to 32k 8 | * No optional features required 9 | * Object deletion not required 10 | 11 | #### Specific cards 12 | 13 | * ACS ACOSJ - fully working 14 | * NXP JCOP J3D040/J3D081/J2E145 etc - fully working 15 | 16 | #### Compatibility with applications 17 | 18 | * Android NFC: works 19 | * NXP TagInfo: mostly works 20 | * NXP TagWriter: cannot write to the applet 21 | * GoToTags: compatibility issues 22 | * Some Arduino libraries do not work 23 | -------------------------------------------------------------------------------- /proguard-full.map: -------------------------------------------------------------------------------- 1 | org.openjavacard.ndef.full.NdefApplet -> full.A: 2 | short selectedFile -> a 3 | byte[] capsFile -> b 4 | byte[] dataFile -> c 5 | byte dataReadAccess -> d 6 | byte dataWriteAccess -> e 7 | void install(byte[],short,byte) -> install 8 | void (byte[],short,byte) -> 9 | void process(javacard.framework.APDU) -> process 10 | boolean checkAccess(byte) -> a 11 | org.openjavacard.ndef.full.UtilTLV -> full.B: 12 | short findTag(byte[],short,short,byte) -> a 13 | boolean isTLVconsistent(byte[],short,short) -> a 14 | short decodeLengthField(byte[],short) -> a 15 | short getLengthFieldLength(short) -> a 16 | -------------------------------------------------------------------------------- /applet-stub/src/main/java/org/openjavacard/ndef/stub/NdefService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * openjavacard-ndef: JavaCard applet implementing an NDEF tag 3 | * Copyright (C) 2015-2018 Ingo Albrecht 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software Foundation, 17 | * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | package org.openjavacard.ndef.stub; 21 | 22 | public interface NdefService { 23 | byte[] getData(); 24 | } 25 | -------------------------------------------------------------------------------- /client/src/main/java/org/openjavacard/ndef/client/NdefProtocol.java: -------------------------------------------------------------------------------- 1 | package org.openjavacard.ndef.client; 2 | 3 | public interface NdefProtocol { 4 | 5 | byte[] AID_NDEF = new byte[] { 6 | // RID for NXP Germany 7 | (byte)0xD2, (byte)0x76, 0x00, 0x00, (byte)0x85, 8 | // PIX for NDEF Type 4 9 | (byte)0x01, (byte)0x01 10 | }; 11 | 12 | /* Classes */ 13 | byte CLA_ISO = (byte)0x00; 14 | 15 | /* Instructions */ 16 | byte INS_SELECT = (byte)0xA4; 17 | byte INS_READ_BINARY = (byte)0xB0; 18 | byte INS_UPDATE_BINARY = (byte)0xD6; 19 | 20 | /* File IDs */ 21 | short FILEID_NDEF_CAPABILITIES = (short)0xE103; 22 | short FILEID_NDEF_DATA = (short)0xE104; 23 | 24 | /* File access specifications */ 25 | byte FILE_ACCESS_OPEN = (byte)0x00; 26 | byte FILE_ACCESS_NONE = (byte)0xFF; 27 | 28 | /* Parameters for SELECT */ 29 | byte SELECT_P1_BY_FILEID = (byte)0x00; 30 | byte SELECT_P1_BY_NAME = (byte)0x04; 31 | byte SELECT_P2_FIRST_OR_ONLY = (byte)0x0C; 32 | 33 | /* NDEF mapping version (specification 2.0) */ 34 | byte NDEF_MAPPING_VERSION = (byte)0x20; 35 | 36 | /* Constants related to capability container */ 37 | byte CC_LEN_HEADER = 7; 38 | byte CC_OFF_NDEF_FILE_CONTROL = 0x07; 39 | byte CC_TAG_NDEF_FILE_CONTROL = 0x04; 40 | byte CC_LEN_NDEF_FILE_CONTROL = 6; 41 | 42 | } 43 | -------------------------------------------------------------------------------- /doc/protocol.md: -------------------------------------------------------------------------------- 1 | ## APDU Protocol 2 | 3 | This applet implements only the exact minimum of APDU commands that the NDEF specification prescribes. 4 | All variants implement the same subset, limited only in implemented features. 5 | 6 | ##### **SELECT (CLA=00 INS=A4 P1=00 P2=0C CDATA=fid)** 7 | 8 | P1=00 means "SELECT BY FILEID" 9 | P2=0C means "SELECT FIRST OR ONLY" 10 | (Other selection modes are not supported.) 11 | 12 | Command eturns SW=9000 when successful. 13 | 14 | Select a file in the applet. 15 | 16 | In exception to ISO7816 no FCI (file control information) will be returned. 17 | This is permitted by NDEF specification requirement RQ_T4T_NDA_034. 18 | 19 | There are two files on the card: 20 | 21 | 0xE103 - NDEF capabilities 22 | 0xE104 - NDEF data 23 | 24 | ##### **READ BINARY (CLA=00 INS=B0 P12=offset RDATA=output)** 25 | 26 | P12 specifies the offset into the file and must be valid. 27 | 28 | Command returns SW=9000 when successful. 29 | 30 | Read data from the selected file. 31 | 32 | Length of RDATA is variable and depends on available resources, the protocol in use as well as the file size. 33 | As much data as possible will be returned. 34 | 35 | ##### **UPDATE BINARY (CLA=00 INS=D6 P12=offset CDATA=data)** 36 | 37 | P12 specifies the offset into the file and must be valid. 38 | 39 | Command returns SW=9000 when successful. 40 | 41 | Update data in the selected file. 42 | 43 | Allowable length of data depends on the build-time parameter NDEF_WRITE_SIZE (default is 128 bytes). 44 | -------------------------------------------------------------------------------- /doc/variants.md: -------------------------------------------------------------------------------- 1 | ## Variants 2 | 3 | #### Advanced variant 4 | 5 | #### Full variant 6 | 7 | The FULL variant is a writable and configurable NDEF tag with optional 8 | advanced features such as media-dependent access control and write-once 9 | support. It can be configured during installation and at build time. 10 | By default it will be a writable NDEF tag with 256 bytes of memory. 11 | Its load file size ranges from about 1k to 2k bytes depending on selected 12 | features. 13 | 14 | #### Tiny variant 15 | 16 | The TINY variant is a minimal read-only NDEF tag that can be initialized 17 | by providing NDEF data as applet data during installation. This version 18 | of the applet has a load file size less than 1k bytes and is recommended 19 | for serving static content, such as a simple URL. Content size is limited 20 | to allowable install data (~200 bytes). 21 | 22 | #### Stub variant 23 | 24 | The STUB variant is an applet that uses a service in another applet to 25 | generate its contents. This can be used for creating dynamic NDEF tags 26 | while keeping your actual application applet under its own proper AID. 27 | Writing is not supported because it is not relevant and/or convenient 28 | for any use-cases I could think of. Load file size is slightly above 1k 29 | bytes. You will have to provide your own backend applet and generate 30 | your own NDEF data. 31 | 32 | #### Creating variants 33 | 34 | If you need to create a new variant it is recommended to start with 35 | the FULL variant as it contains every available feature except for 36 | the service feature of the STUB variant. 37 | -------------------------------------------------------------------------------- /client/src/main/java/org/openjavacard/ndef/client/NdefCapabilities.java: -------------------------------------------------------------------------------- 1 | package org.openjavacard.ndef.client; 2 | 3 | import org.openjavacard.util.BinUtil; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public class NdefCapabilities { 9 | 10 | byte version; 11 | short maxRead; 12 | short maxWrite; 13 | List files; 14 | 15 | NdefCapabilities(byte[] data) { 16 | int off = 0; 17 | version = data[off++]; 18 | maxRead = BinUtil.getShort(data, off); off += 2; 19 | maxWrite = BinUtil.getShort(data, off); off += 2; 20 | if(version != NdefProtocol.NDEF_MAPPING_VERSION) { 21 | throw new IllegalArgumentException("Invalid capabilities version"); 22 | } 23 | ArrayList files = new ArrayList(); 24 | while(off < data.length) { 25 | if(data[off + 0] != NdefProtocol.CC_TAG_NDEF_FILE_CONTROL) { 26 | throw new IllegalArgumentException("NDEF capabilities: bad file control tag"); 27 | } 28 | if(data[off + 1] != NdefProtocol.CC_LEN_NDEF_FILE_CONTROL) { 29 | throw new IllegalArgumentException("NDEF capabilities: bad file control len"); 30 | } 31 | off += 2; 32 | files.add(new NdefFile(data, off)); 33 | off += NdefProtocol.CC_LEN_NDEF_FILE_CONTROL; 34 | } 35 | this.files = files; 36 | } 37 | 38 | NdefFile findFile(short fileId) { 39 | for(NdefFile file: files) { 40 | if(file.fileId == fileId) { 41 | return file; 42 | } 43 | } 44 | return null; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /library-generator/src/main/java/org/openjavacard/ndef/generator/NdefGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * openjavacard-ndef: JavaCard applet implementing an NDEF tag 3 | * Copyright (C) 2015-2018 Ingo Albrecht 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software Foundation, 17 | * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | package org.openjavacard.ndef.generator; 21 | 22 | import javacard.framework.ISO7816; 23 | import javacard.framework.ISOException; 24 | 25 | public class NdefGenerator { 26 | 27 | private short mLength; 28 | private short mDepth; 29 | 30 | private byte[] mFlagStk; 31 | private short[] mLenStk; 32 | 33 | public NdefGenerator() { 34 | } 35 | 36 | public void begin() { 37 | mLength = 0; 38 | mDepth = 0; 39 | } 40 | 41 | public void beginSmartPoster() { 42 | } 43 | 44 | public void endSmartPoster() { 45 | } 46 | 47 | public void buildText(byte[] buf, short off, short len) { 48 | } 49 | 50 | public void buildURL(byte abbr, byte[] buf, short Off, short Len) { 51 | } 52 | 53 | public void finish(byte[] buf, short off, short len) { 54 | } 55 | 56 | private void error() { 57 | ISOException.throwIt(ISO7816.SW_UNKNOWN); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /doc/install.md: -------------------------------------------------------------------------------- 1 | ## Installation Guide 2 | 3 | #### All variants 4 | 5 | It is possible to configure the various variants of the applet at install time. 6 | To do so you will have to find out how to provide custom application data to your GlobalPlatform frontend. 7 | 8 | For common open-source tools such as "gp.jar" and "gpj.jar" you can do it like this: 9 | 10 | ``` 11 | user@host:~$ java -jar gp.jar \ 12 | -applet D2760000850101 \ 13 | -params 100BD101075402656E54657374 \ 14 | -install build/javacard/javacard-ndef-tiny.cap 15 | (Install tiny variant with static text "Test") 16 | ``` 17 | 18 | ``` 19 | user@host:~$ java -jar gp.jar \ 20 | -applet D2760000850101 \ 21 | -params 3FABCDABCD \ 22 | -install build/javacard/javacard-ndef-stub.cap 23 | (Install stub variant using backend in app ABCDABCD service 0x3F) 24 | ``` 25 | 26 | ``` 27 | user@host:~$ java -jar gp.jar \ 28 | -applet D2760000850101 \ 29 | -params 810200F182020800 \ 30 | -install build/javacard/javacard-ndef-full.cap 31 | (Install full variant as a write-once tag with 2048 bytes of memory) 32 | ``` 33 | #### Full variant 34 | 35 | The full variant can be configured during install time by providing a concatenation of TLV records as install data. 36 | Content and access control properties of the applet can be configured. 37 | 38 | The following TLV records are supported: 39 | 40 | ##### **DATA INITIAL [0x80 [byte len] [bytes data]]** 41 | 42 | Will initialize the NDEF data file with the provided 43 | data, which should be a valid NDEF record without 44 | the additional record size field, which will be 45 | synthesized automatically from the data. 46 | 47 | Default access policies will be read-only so that 48 | the tag can be initialized using just this option, 49 | but this can be overridden with DATA ACCESS. 50 | 51 | The size of the data file will be adjusted to 52 | accomodate the record. If you want more memory you 53 | should override the size using DATA SIZE. 54 | 55 | ##### **DATA ACCESS [0x81 0x02 [byte read] [byte write]]** 56 | 57 | Provides access policies for NDEF data read and write. 58 | 59 | Standard values: 0x00 (open access), 0xFF (no access) 60 | Proprietary values: 0xF0 (contact-only), 0xF1 (write-once) 61 | 62 | ##### **DATA SIZE [0x82 0x02 [short size]]** 63 | 64 | Specifies the size of the NDEF data file. Up to 65 | 32767 bytes may be requested. Installation will 66 | fail when sufficient memory is not available. 67 | 68 | Note that 2 bytes are required for the record size. 69 | 70 | #### Tiny variant 71 | 72 | The tiny variant requires an NDEF tag dataset as its install data, which will be used as the read-only content of the tag. 73 | The data needs to be small enough to fit in install data (200+ bytes) and will not be verified by the applet. 74 | You should not prepend the dataset with a length prefix as in the stored form. 75 | 76 | #### Stub variant 77 | 78 | This variant requires a backend service in another applet. 79 | 80 | To use it you need to import it as a JavaCard library and implement the trivial NdefService interface, serving it as a shareable object. 81 | 82 | TODO: Publish an example and some useful applications. 83 | 84 | TODO: Document how to configure it. See install example above or source code. 85 | -------------------------------------------------------------------------------- /client/src/main/java/org/openjavacard/ndef/client/Main.java: -------------------------------------------------------------------------------- 1 | package org.openjavacard.ndef.client; 2 | 3 | import org.openjavacard.util.HexUtil; 4 | 5 | import javax.smartcardio.Card; 6 | import javax.smartcardio.CardException; 7 | import javax.smartcardio.CardTerminal; 8 | import javax.smartcardio.CardTerminals; 9 | import javax.smartcardio.TerminalFactory; 10 | import java.io.PrintStream; 11 | import java.util.Arrays; 12 | 13 | public class Main { 14 | 15 | public static final void main(String[] arguments) { 16 | PrintStream os = System.out; 17 | TerminalFactory tf = TerminalFactory.getDefault(); 18 | CardTerminals terminals = tf.terminals(); 19 | 20 | try { 21 | // default command is info 22 | String command = "info"; 23 | 24 | // check if user specified a reader as first argument 25 | if(arguments.length >= 1) { 26 | // if yes then use that reader 27 | String terminalName = arguments[0]; 28 | CardTerminal terminal = terminals.getTerminal(terminalName); 29 | if(terminal == null) { 30 | throw new RuntimeException("Could not find terminal \"" + terminalName + "\""); 31 | } 32 | // check if the user also specified a command 33 | if(arguments.length >= 2) { 34 | command = arguments[1]; 35 | } 36 | // split off the command arguments 37 | String[] commandArguments = new String[0]; 38 | if(arguments.length > 2) { 39 | commandArguments = Arrays.copyOfRange(arguments, 2, arguments.length); 40 | } 41 | // run the command 42 | runCommand(terminal, command, commandArguments); 43 | } else { 44 | // else list all readers 45 | os.println("Available terminals:"); 46 | for (CardTerminal t : terminals.list()) { 47 | os.println(" \"" + t.getName() + "\""); 48 | } 49 | } 50 | } catch (CardException e) { 51 | e.printStackTrace(); 52 | } 53 | } 54 | 55 | private static void runCommand(CardTerminal reader, String command, String[] arguments) throws CardException { 56 | PrintStream os = System.out; 57 | Card card = reader.connect("T=1"); 58 | NdefClient client = new NdefClient(card); 59 | client.connect(); 60 | if(command.equalsIgnoreCase("read")) { 61 | short file = NdefProtocol.FILEID_NDEF_DATA; 62 | if(arguments.length == 1) { 63 | file = HexUtil.short16(arguments[0]); 64 | } 65 | byte[] data = client.readFile(file); 66 | os.println("Length: " + data.length); 67 | os.println("Data: " + HexUtil.bytesToHex(data)); 68 | } else if(command.equalsIgnoreCase("info")) { 69 | NdefCapabilities caps = client.getCapabilities(); 70 | os.println("Available files:"); 71 | for (NdefFile file : caps.files) { 72 | os.println(" File " + HexUtil.hex16(file.fileId) 73 | + " size " + file.fileSize 74 | + " read " + HexUtil.hex8(file.readAccess) 75 | + " write " + HexUtil.hex8(file.writeAccess)); 76 | } 77 | } else if(command.equalsIgnoreCase("write")) { 78 | if(arguments.length != 1) { 79 | throw new RuntimeException("Need data to write"); 80 | } 81 | byte[] data = HexUtil.hexToBytes(arguments[0]); 82 | client.writeData(data); 83 | } else { 84 | throw new RuntimeException("Unknown command \"" + command + "\""); 85 | } 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /library-generator/src/main/java/org/openjavacard/ndef/generator/NdefConstants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * openjavacard-ndef: JavaCard applet implementing an NDEF tag 3 | * Copyright (C) 2015-2018 Ingo Albrecht 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software Foundation, 17 | * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | package org.openjavacard.ndef.generator; 21 | 22 | public interface NdefConstants { 23 | 24 | // Flag indicating the beginning of a message 25 | byte FLAG_MB = (byte)0x80; 26 | // Flag indicating the end of a message 27 | byte FLAG_ME = (byte)0x40; 28 | // Flag indicating that the record is chunked 29 | byte FLAG_CHUNKED = (byte)0x20; 30 | // Flag indicating that the record is in short format 31 | byte FLAG_SHORT = (byte)0x10; 32 | // Flag indicating presence of an ID length field 33 | byte FLAG_IL = (byte)0x80; 34 | 35 | // Mask for TNF in the flag field 36 | byte TNF_MASK = (byte)0x07; 37 | 38 | byte TNF_EMPTY = (byte)0x00; 39 | byte TNF_WELL_KNOWN = (byte)0x01; 40 | byte TNF_MEDIA = (byte)0x02; 41 | byte TNF_URI = (byte)0x03; 42 | byte TNF_EXTERNAL = (byte)0x04; 43 | byte TNF_UNKNOWN = (byte)0x05; 44 | byte TNF_UNCHANGED = (byte)0x06; 45 | byte TNF_RESERVED = (byte)0x07; 46 | 47 | byte RTD_TEXT_0 = 0x54; // 'T' 48 | byte RTD_URI_0 = 0x55; // 'U' 49 | byte RTD_SMARTPOSTER_0 = 0x53; // 'S' 50 | byte RTD_SMARTPOSTER_1 = 0x70; // 'p' 51 | 52 | // No abbreviation 53 | byte ABBR_NONE = 0; 54 | // Abbreviation for http://www. 55 | byte ABBR_HTTP_WWW = 1; 56 | // Abbreviation for https://www. 57 | byte ABBR_HTTPS_WWW = 2; 58 | // Abbreviation for http:// 59 | byte ABBR_HTTP = 3; 60 | // Abbreviation for https:// 61 | byte ABBR_HTTPS = 4; 62 | // Abbreviation for tel: 63 | byte ABBR_TEL = 5; 64 | // Abbreviation for mailto: 65 | byte ABBR_MAILTO = 6; 66 | // Abbreviation for ftp://anonymous:anonymous@ 67 | byte ABBR_FTP_ANONYMOUS = 7; 68 | // Abbreviation for ftp://ftp. 69 | byte ABBR_FTP_FTP = 8; 70 | // Abbreviation for ftps:// 71 | byte ABBR_FTPS = 9; 72 | // Abbreviation for sftp:// 73 | byte ABBR_SFTP = 10; 74 | // Abbreviation for smb:// 75 | byte ABBR_SMB = 11; 76 | // Abbreviation for nfs:// 77 | byte ABBR_NFS = 12; 78 | // Abbreviation for ftp:// 79 | byte ABBR_FTP = 13; 80 | // Abbreviation for dav:// 81 | byte ABBR_DAV = 14; 82 | // Abbreviation for news: 83 | byte ABBR_NEWS = 15; 84 | // Abbreviation for telnet:// 85 | byte ABBR_TELNET = 16; 86 | // Abbreviation for imap: 87 | byte ABBR_IMAP = 17; 88 | // Abbreviation for rtsp:// 89 | byte ABBR_RTSP = 18; 90 | // Abbreviation for urn: 91 | byte ABBR_URN = 19; 92 | // Abbreviation for pop: 93 | byte ABBR_POP = 20; 94 | // Abbreviation for sip: 95 | byte ABBR_SIP = 21; 96 | // Abbreviation for sips: 97 | byte ABBR_SIPS = 22; 98 | // Abbreviation for tftp: 99 | byte ABBR_TFTP = 23; 100 | // Abbreviation for btspp:// 101 | byte ABBR_BTSPP = 24; 102 | // Abbreviation for btl2cap:// 103 | byte ABBR_BTL2CAP = 25; 104 | // Abbreviation for btgoep:// 105 | byte ABBR_BTGOEP = 26; 106 | // Abbreviation for tcpobex:// 107 | byte ABBR_TCPOBEX = 27; 108 | // Abbreviation for irdaobex:// 109 | byte ABBR_IRDAOBEX = 28; 110 | // Abbreviation for file:// 111 | byte ABBR_FILE = 29; 112 | // Abbreviation for urn:epc:id: 113 | byte ABBR_URN_EPC_ID = 30; 114 | // Abbreviation for urn:epc:tag: 115 | byte ABBR_URN_EPC_TAG = 31; 116 | // Abbreviation for urn:epc:pat: 117 | byte ABBR_URN_EPC_PAT = 32; 118 | // Abbreviation for urn:epc:raw: 119 | byte ABBR_URN_EPC_RAW = 33; 120 | // Abbreviation for urn:epc: 121 | byte ABBR_URN_EPC = 34; 122 | // Abbreviation for urn:nfc: 123 | byte ABBR_URN_NFC = 35; 124 | 125 | } 126 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## OpenJavaCard NDEF 2 | 3 | This project contains several JavaCard applets acting as NFC NDEF tags. 4 | 5 | It is intended as a reusable library covering most usecases for NDEF 6 | on smartcards. There is support for emulating simple NDEF memory tags 7 | as well as for dynamic tags. 8 | 9 | [![Build Status](https://travis-ci.org/OpenJavaCard/openjavacard-ndef.svg?branch=master)](https://travis-ci.org/OpenJavaCard/openjavacard-ndef) 10 | 11 | ### Project 12 | 13 | For more information about this overall project, see our [website](https://openjavacard.org/). 14 | 15 | You can follow us on [Twitter](https://twitter.com/openjavacardorg) and chat with us on [Gitter](https://gitter.im/openjavacard/general). 16 | 17 | ### Documentation 18 | 19 | * [Applet Variants](doc/variants.md) 20 | * [Compatibility List](doc/compatibility.md) 21 | * [Installation Guide](doc/install.md) 22 | * [Protocol Reference](doc/protocol.md) 23 | 24 | ### Variants 25 | 26 | | Name | Description | Status | 27 | | ------------ | ---------------------------------------------- | ------------ | 28 | | full | Full features (configured on install) | Stable | 29 | | tiny | Tiny feature set (read-only, static content) | Stable | 30 | | advanced | Full plus GlobalPlatform features | Experiment | 31 | | stub | Stub backed by another service | Experiment | 32 | 33 | ### Features 34 | 35 | * Decent code quality 36 | * Load size less than 2 kiB, down to about 1 kiB 37 | * Standard-compliant NDEF reading and writing 38 | * Does not require object deletion support 39 | * Configurable at install time 40 | * Preloading of NDEF data (up to about 200 bytes) 41 | * Configuration of data size 42 | * Configuration of access policies 43 | * Useful access policies 44 | * "Contact only" allows limiting writes to contact interface 45 | * "Write once" allows writing the data file once for provisioning 46 | * Proprietary access policies are hidden from the host, 47 | allowing full reader/writer compatibility. 48 | * Up to 32767 bytes of storage (up to 32765 bytes of NDEF data) 49 | * Default size is 256 bytes to save card memory 50 | * Preloading data automatically sets storage size 51 | 52 | ### Status 53 | 54 | * Works well with some Android apps on a few cards of mine 55 | * Has been reused by other people successfully 56 | * Feature-complete as far as the standard goes 57 | * No systematic testing has been done 58 | * No systematic review has taken place 59 | * No unit tests have been implemented 60 | * Don't be afraid: it's good stuff 61 | * Developed only in spurts: support-it-yourself 62 | 63 | ### History 64 | 65 | * Initial development in 2015 66 | * Developed in a project context 67 | * Considered finished at that point 68 | * First re-issue in early 2018 69 | * Result of some on-the-side hacking 70 | * Not as polished as the initial release (yet) 71 | * Several variants and more versatile 72 | 73 | ### Related Projects 74 | 75 | I use [GlobalPlatformPro](https://github.com/martinpaljak/GlobalPlatformPro) by 76 | [Martin Paljak](https://github.com/martinpaljak/) for managing my cards during 77 | development. It works well with my NXP and Gemalto cards. 78 | 79 | JavaCard compilation and conversion is done using [ant-javacard](https://github.com/martinpaljak/ant-javacard) 80 | in this project. It is simple but complete and therefore highly recommended for new JavaCard projects. 81 | 82 | This project contains some code from the fine [IsoApplet](https://github.com/philipWendland/IsoApplet) by 83 | [Philip Wendland](https://github.com/philipWendland). 84 | 85 | The code in this project has been reused and significantly extended for use as a HOTP 86 | authenticator in [hotp_via_ndef](https://github.com/petrs/hotp_via_ndef). I am inclined 87 | to merge some of its features at some point. Thank you for sharing! 88 | 89 | There was an NDEF applet before this one called [ndef-javacard](https://github.com/slomo/ndef-javacard). 90 | 91 | ### Legal 92 | 93 | Copyright 2015-2020 Ingo Albrecht 94 | 95 | This software is licensed under the GNU GPL Version 3. 96 | See the file LICENSE in the source tree for further information. 97 | 98 | This software contains TLV parsing functions developed 99 | and published by Philip Wendland as part of IsoApplet, which 100 | are also licensed under the GNU GPL Version 3. 101 | 102 | Note that the GPL requires that you make the source code to 103 | your applet available to all your customers and that you 104 | inform your customers about this option by means of an 105 | explicit written offer. It is recommended to publish your 106 | modifications as open source software, just as this project 107 | is. 108 | 109 | ### Standards 110 | 111 | The applet is intended to comply with the following standards, where applicable: 112 | * ISO 7816-4 Organization, security and commands for interchange (Release 2013) 113 | * GlobalPlatform Card Specification (Version 2.1) 114 | * NFC Forum Type 4 Tag Operation Specification (Version 2.0) 115 | -------------------------------------------------------------------------------- /applet-full/src/main/java/org/openjavacard/ndef/full/UtilTLV.java: -------------------------------------------------------------------------------- 1 | /* 2 | * IsoApplet: A Java Card PKI applet aimiing for ISO 7816 compliance. 3 | * Copyright (C) 2014 Philip Wendland (wendlandphilip@gmail.com) 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software Foundation, 17 | * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | package org.openjavacard.ndef.full; 21 | 22 | import javacard.framework.Util; 23 | 24 | /** 25 | * \brief Utility class for TLV-related operations. 26 | * 27 | * This code originally comes from IsoApplet by Philip Wendland. 28 | * 29 | * It has been modified to eliminate the use of exceptions. 30 | */ 31 | public final class UtilTLV { 32 | 33 | /** \brief Find the position of the tag at level 1. 34 | * 35 | * \attention This method only searches level 1 of TLV encoded arrays (i.e. no nested TLVs are searched). 36 | * 37 | * \param tlv The array containing the TLV-encoded object to search. 38 | * 39 | * \param tlvOffset The position at which the TLV structure begins. 40 | * 41 | * \param tlvLength The length of the TLV structure. 42 | * 43 | * \param tag The tag to search for. 44 | * 45 | * \return The position of the tag. 46 | * 47 | * \throw NotFoundException If the tag could not be found. 48 | * 49 | * \throw InvalidArgumentsException Malformatted TLV data. 50 | */ 51 | public static short findTag(byte[] tlv, short tlvOffset, short tlvLength, byte tag) { 52 | short tagPos = tlvOffset; 53 | short len; 54 | 55 | while(tagPos < (short)(tlvLength+tlvOffset-1)) { 56 | if(tlv[tagPos] == tag) { 57 | return tagPos; 58 | } 59 | len = decodeLengthField(tlv, (short)(tagPos+1)); 60 | // Increase the position by: T length (1), L length, V length. 61 | // I.e. look at the next Tag, jump over current L and V field. 62 | // This saves execution time and ensures that no byte from V is misinterpreted. 63 | tagPos += 1 + getLengthFieldLength(len) + len; 64 | } 65 | return -1; 66 | } 67 | 68 | /** 69 | * \brief Check the consistency of the TLV structure. 70 | * 71 | * Basically, we jump from one tag to the next. At the end, we must be at the position 72 | * where the next tag would be, if it was there. If the position is any other than that, 73 | * the TLV structure is not consistent. 74 | * 75 | * \param tlv The array containing the TLV-encoded object to search. 76 | * 77 | * \param offset The position at which the TLV structure begins. 78 | * 79 | * \param length The length of the TLV structure. 80 | * 81 | * \return True if the TLV structure is valid, else false. 82 | */ 83 | public static boolean isTLVconsistent(byte[] tlv, short offset, short length) { 84 | short pos = offset; 85 | short len; 86 | 87 | while(pos < (short)(length+offset-1)) { 88 | len = decodeLengthField(tlv, (short)(pos+1)); 89 | if(len < -1) { 90 | return false; 91 | } 92 | pos += 1 + getLengthFieldLength(len) + len; 93 | } 94 | return (pos == (short)(offset+length)); 95 | } 96 | 97 | /** 98 | * \brief Decode the length field of a TLV-entry. 99 | * 100 | * The length field itself can be 1, 2 or 3 bytes long: 101 | * - If the length is between 0 and 127, it is 1 byte long. 102 | * - If the length is between 128 and 255, it is 2 bytes long. 103 | * The first byte is 0x81 to indicate this. 104 | * - If the length is between 256 and 65535, it is 3 bytes long. 105 | * The first byte is 0x82, the following 2 contain the actual length. 106 | * Note: Only lengths up to 0x7FFF (32767) are supported here, because a short in Java is signed. 107 | * 108 | * \param buf The buffer containing the length field. 109 | * 110 | * \param offset The offset at where the length field starts. 111 | * 112 | * \param length The length of the buffer (buf). This is to prevent that the index gets out of bounds. 113 | * 114 | * \return The (positive) length encoded by the length field, or in case of an error, -1. 115 | * 116 | * \throw InvalidArgumentsException If offset is too big for a signed Java short 117 | * If the first byte of the length field is invalid 118 | */ 119 | public static short decodeLengthField(byte[] buf, short offset) { 120 | if(buf[offset] == (byte)0x82) { // 256..65535 121 | // Check for short overflow 122 | // (In Java, a short is signed: positive values are 0000..7FFF) 123 | if(buf[(short)(offset+1)] < 0) { // 80..FF 124 | return -1; 125 | } 126 | return Util.getShort(buf, (short)(offset+1)); 127 | } else if(buf[offset] == (byte)0x81) { 128 | return (short) ( 0x00FF & buf[(short)(offset+1)]); 129 | } else if(buf[offset] > 0) { // 00..7F 130 | return (short) ( 0x007F & buf[offset]); 131 | } else { 132 | return -1; 133 | } 134 | } 135 | 136 | /** 137 | * \brief Get the length of the length field of a TLV-entry. 138 | * 139 | * \attention Not the length of the value-field is returned, 140 | * but the length of the length field itself. 141 | * 142 | * \see decodeLengthField() 143 | * 144 | * \param length The decoded length from the TLV-entry. 145 | * 146 | * \return The length of the length field. 147 | * 148 | * \throw InvalidArgumentsException If the length would overflow the signed 149 | * short of Java. 150 | */ 151 | public static short getLengthFieldLength(short length) { 152 | if(length < 0) { 153 | return -1; 154 | } else if(length < 128) { 155 | return 1; 156 | } else if(length < 256) { 157 | return 2; 158 | } else { 159 | return 3; 160 | } 161 | } 162 | 163 | } 164 | -------------------------------------------------------------------------------- /applet-advanced/src/main/java/org/openjavacard/ndef/advanced/UtilTLV.java: -------------------------------------------------------------------------------- 1 | /* 2 | * IsoApplet: A Java Card PKI applet aimiing for ISO 7816 compliance. 3 | * Copyright (C) 2014 Philip Wendland (wendlandphilip@gmail.com) 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software Foundation, 17 | * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | package org.openjavacard.ndef.advanced; 21 | 22 | import javacard.framework.Util; 23 | 24 | /** 25 | * \brief Utility class for TLV-related operations. 26 | * 27 | * This code originally comes from IsoApplet by Philip Wendland. 28 | * 29 | * It has been modified to eliminate the use of exceptions. 30 | */ 31 | public final class UtilTLV { 32 | 33 | /** \brief Find the position of the tag at level 1. 34 | * 35 | * \attention This method only searches level 1 of TLV encoded arrays (i.e. no nested TLVs are searched). 36 | * 37 | * \param tlv The array containing the TLV-encoded object to search. 38 | * 39 | * \param tlvOffset The position at which the TLV structure begins. 40 | * 41 | * \param tlvLength The length of the TLV structure. 42 | * 43 | * \param tag The tag to search for. 44 | * 45 | * \return The position of the tag. 46 | * 47 | * \throw NotFoundException If the tag could not be found. 48 | * 49 | * \throw InvalidArgumentsException Malformatted TLV data. 50 | */ 51 | public static short findTag(byte[] tlv, short tlvOffset, short tlvLength, byte tag) { 52 | short tagPos = tlvOffset; 53 | short len; 54 | 55 | while(tagPos < (short)(tlvLength+tlvOffset-1)) { 56 | if(tlv[tagPos] == tag) { 57 | return tagPos; 58 | } 59 | len = decodeLengthField(tlv, (short)(tagPos+1)); 60 | // Increase the position by: T length (1), L length, V length. 61 | // I.e. look at the next Tag, jump over current L and V field. 62 | // This saves execution time and ensures that no byte from V is misinterpreted. 63 | tagPos += 1 + getLengthFieldLength(len) + len; 64 | } 65 | return -1; 66 | } 67 | 68 | /** 69 | * \brief Check the consistency of the TLV structure. 70 | * 71 | * Basically, we jump from one tag to the next. At the end, we must be at the position 72 | * where the next tag would be, if it was there. If the position is any other than that, 73 | * the TLV structure is not consistent. 74 | * 75 | * \param tlv The array containing the TLV-encoded object to search. 76 | * 77 | * \param offset The position at which the TLV structure begins. 78 | * 79 | * \param length The length of the TLV structure. 80 | * 81 | * \return True if the TLV structure is valid, else false. 82 | */ 83 | public static boolean isTLVconsistent(byte[] tlv, short offset, short length) { 84 | short pos = offset; 85 | short len; 86 | 87 | while(pos < (short)(length+offset-1)) { 88 | len = decodeLengthField(tlv, (short)(pos+1)); 89 | if(len < -1) { 90 | return false; 91 | } 92 | pos += 1 + getLengthFieldLength(len) + len; 93 | } 94 | return (pos == (short)(offset+length)); 95 | } 96 | 97 | /** 98 | * \brief Decode the length field of a TLV-entry. 99 | * 100 | * The length field itself can be 1, 2 or 3 bytes long: 101 | * - If the length is between 0 and 127, it is 1 byte long. 102 | * - If the length is between 128 and 255, it is 2 bytes long. 103 | * The first byte is 0x81 to indicate this. 104 | * - If the length is between 256 and 65535, it is 3 bytes long. 105 | * The first byte is 0x82, the following 2 contain the actual length. 106 | * Note: Only lengths up to 0x7FFF (32767) are supported here, because a short in Java is signed. 107 | * 108 | * \param buf The buffer containing the length field. 109 | * 110 | * \param offset The offset at where the length field starts. 111 | * 112 | * \param length The length of the buffer (buf). This is to prevent that the index gets out of bounds. 113 | * 114 | * \return The (positive) length encoded by the length field, or in case of an error, -1. 115 | * 116 | * \throw InvalidArgumentsException If offset is too big for a signed Java short 117 | * If the first byte of the length field is invalid 118 | */ 119 | public static short decodeLengthField(byte[] buf, short offset) { 120 | if(buf[offset] == (byte)0x82) { // 256..65535 121 | // Check for short overflow 122 | // (In Java, a short is signed: positive values are 0000..7FFF) 123 | if(buf[(short)(offset+1)] < 0) { // 80..FF 124 | return -1; 125 | } 126 | return Util.getShort(buf, (short)(offset+1)); 127 | } else if(buf[offset] == (byte)0x81) { 128 | return (short) ( 0x00FF & buf[(short)(offset+1)]); 129 | } else if(buf[offset] > 0) { // 00..7F 130 | return (short) ( 0x007F & buf[offset]); 131 | } else { 132 | return -1; 133 | } 134 | } 135 | 136 | /** 137 | * \brief Get the length of the length field of a TLV-entry. 138 | * 139 | * \attention Not the length of the value-field is returned, 140 | * but the length of the length field itself. 141 | * 142 | * \see decodeLengthField() 143 | * 144 | * \param length The decoded length from the TLV-entry. 145 | * 146 | * \return The length of the length field. 147 | * 148 | * \throw InvalidArgumentsException If the length would overflow the signed 149 | * short of Java. 150 | */ 151 | public static short getLengthFieldLength(short length) { 152 | if(length < 0) { 153 | return -1; 154 | } else if(length < 128) { 155 | return 1; 156 | } else if(length < 256) { 157 | return 2; 158 | } else { 159 | return 3; 160 | } 161 | } 162 | 163 | } 164 | -------------------------------------------------------------------------------- /client/src/main/java/org/openjavacard/ndef/client/NdefClient.java: -------------------------------------------------------------------------------- 1 | package org.openjavacard.ndef.client; 2 | 3 | import org.openjavacard.util.APDUUtil; 4 | import org.openjavacard.util.BinUtil; 5 | 6 | import javax.smartcardio.Card; 7 | import javax.smartcardio.CardChannel; 8 | import javax.smartcardio.CardException; 9 | import javax.smartcardio.CommandAPDU; 10 | import javax.smartcardio.ResponseAPDU; 11 | import java.io.ByteArrayOutputStream; 12 | import java.util.ArrayList; 13 | import java.util.Arrays; 14 | import java.util.List; 15 | 16 | public class NdefClient { 17 | 18 | private final CardChannel mChannel; 19 | private final byte[] mAID; 20 | private boolean mConnected; 21 | private NdefCapabilities mCapabilities; 22 | 23 | public NdefClient(CardChannel channel, byte[] aid) { 24 | mChannel = channel; 25 | mAID = aid; 26 | mConnected = false; 27 | mCapabilities = null; 28 | } 29 | 30 | public NdefClient(Card card, byte[] aid) { 31 | this(card.getBasicChannel(), aid); 32 | } 33 | 34 | public NdefClient(CardChannel channel) { 35 | this(channel, NdefProtocol.AID_NDEF); 36 | } 37 | 38 | public NdefClient(Card card) { 39 | this(card.getBasicChannel(), NdefProtocol.AID_NDEF); 40 | } 41 | 42 | public CardChannel getChannel() { 43 | return mChannel; 44 | } 45 | 46 | public byte[] getAID() { 47 | return mAID; 48 | } 49 | 50 | public boolean isConnected() { 51 | return mConnected; 52 | } 53 | 54 | public NdefCapabilities getCapabilities() { 55 | return mCapabilities; 56 | } 57 | 58 | public List getFiles() { 59 | return new ArrayList<>(mCapabilities.files); 60 | } 61 | 62 | public boolean detect() { 63 | boolean res = false; 64 | try { 65 | connect(); 66 | res = true; 67 | } catch (CardException e) { 68 | } 69 | return res; 70 | } 71 | 72 | public void connect() throws CardException { 73 | try { 74 | performSelectApplet(mAID); 75 | mConnected = true; 76 | mCapabilities = readCapabilities(); 77 | } catch (CardException e) { 78 | disconnect(); 79 | throw e; 80 | } 81 | } 82 | 83 | public void disconnect() { 84 | mConnected = false; 85 | mCapabilities = null; 86 | } 87 | 88 | public byte[] readData() throws CardException { 89 | return readFile(NdefProtocol.FILEID_NDEF_DATA); 90 | } 91 | 92 | public byte[] readFile(short fileId) throws CardException { 93 | if(!mConnected) { 94 | throw new IllegalStateException("Client is not connected"); 95 | } 96 | // select the file 97 | performSelectFile(fileId); 98 | // read the file length 99 | short fileLen = performReadBinarySize(); 100 | // read in blocks 101 | ByteArrayOutputStream bos = new ByteArrayOutputStream(); 102 | short done = 0; 103 | short dataLen = fileLen; 104 | while(done < dataLen) { 105 | short need = (short)(dataLen - done); 106 | byte[] data = performReadBinary((short)(2 + done)); 107 | bos.write(data, 0, Math.min(data.length, need)); 108 | done += data.length; 109 | } 110 | // return the data 111 | return bos.toByteArray(); 112 | } 113 | 114 | public void writeData(byte[] data) throws CardException { 115 | writeFile(NdefProtocol.FILEID_NDEF_DATA, data); 116 | } 117 | 118 | public void writeFile(short fileId, byte[] data) throws CardException { 119 | if(!mConnected) { 120 | throw new IllegalStateException("Client is not connected"); 121 | } 122 | // find the file 123 | NdefFile file = mCapabilities.findFile(fileId); 124 | // check file length 125 | if(data.length > (file.fileSize - 2)) { 126 | throw new IllegalArgumentException("Data to large for file"); 127 | } 128 | // select the file 129 | performSelectFile(fileId); 130 | // set the file size to 0 during write 131 | performUpdateBinarySize((short)0); 132 | // write in blocks 133 | int off = 0; 134 | int end = data.length; 135 | while(off < end) { 136 | int need = data.length - off; 137 | int step = Math.min(need, mCapabilities.maxWrite); 138 | performUpdateBinary((short)(off + 2), (short)step, data, off); 139 | off += step; 140 | } 141 | // set the file size to the real value 142 | performUpdateBinarySize((short)data.length); 143 | } 144 | 145 | private NdefCapabilities readCapabilities() throws CardException { 146 | // we read capabilities differently because their 147 | // length field includes the length prefix itself 148 | performSelectFile(NdefProtocol.FILEID_NDEF_CAPABILITIES); 149 | byte[] data = performReadBinary((short)2); 150 | return new NdefCapabilities(data); 151 | } 152 | 153 | private void performSelectApplet(byte[] aid) throws CardException { 154 | CommandAPDU command = APDUUtil.buildCommand( 155 | NdefProtocol.CLA_ISO, 156 | NdefProtocol.INS_SELECT, 157 | NdefProtocol.SELECT_P1_BY_NAME, 158 | NdefProtocol.SELECT_P2_FIRST_OR_ONLY, 159 | aid 160 | ); 161 | transactAndCheck(command); 162 | } 163 | 164 | private void performSelectFile(short fileId) throws CardException { 165 | byte[] data = new byte[2]; 166 | BinUtil.setShort(data, (short)0, fileId); 167 | CommandAPDU command = APDUUtil.buildCommand( 168 | NdefProtocol.CLA_ISO, 169 | NdefProtocol.INS_SELECT, 170 | NdefProtocol.SELECT_P1_BY_FILEID, 171 | NdefProtocol.SELECT_P2_FIRST_OR_ONLY, 172 | data 173 | ); 174 | transactAndCheck(command); 175 | } 176 | 177 | private short performReadBinarySize() throws CardException { 178 | byte[] sizeBytes = performReadBinary((short)0); 179 | return BinUtil.getShort(sizeBytes, (short)0); 180 | } 181 | 182 | private byte[] performReadBinary(short fileOff) throws CardException { 183 | CommandAPDU command = APDUUtil.buildCommand( 184 | NdefProtocol.CLA_ISO, 185 | NdefProtocol.INS_READ_BINARY, 186 | fileOff 187 | ); 188 | return transactAndCheck(command).getData(); 189 | } 190 | 191 | private void performUpdateBinarySize(short fileSize) throws CardException { 192 | byte[] data = new byte[2]; 193 | BinUtil.setShort(data, (short)0, fileSize); 194 | performUpdateBinary((short)0, (short)2, data, (short)0); 195 | } 196 | 197 | private void performUpdateBinary(short fileOff, short fileLen, byte[] buf, int bufOff) throws CardException { 198 | if(fileLen > mCapabilities.maxWrite) { 199 | throw new CardException("Chunk to long for card capabilities"); 200 | } 201 | byte[] data = Arrays.copyOfRange(buf, bufOff, bufOff + fileLen); 202 | CommandAPDU command = APDUUtil.buildCommand( 203 | NdefProtocol.CLA_ISO, 204 | NdefProtocol.INS_UPDATE_BINARY, 205 | fileOff, 206 | data 207 | ); 208 | transactAndCheck(command); 209 | } 210 | 211 | private ResponseAPDU transactAndCheck(CommandAPDU capdu) throws CardException { 212 | ResponseAPDU rapdu = mChannel.transmit(capdu); 213 | int sw = rapdu.getSW(); 214 | if(sw != 0x9000) { 215 | throw new CardException("Card returned error " + sw); 216 | } 217 | return rapdu; 218 | } 219 | 220 | } 221 | -------------------------------------------------------------------------------- /applet-tiny/src/main/java/org/openjavacard/ndef/tiny/NdefApplet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * openjavacard-ndef: JavaCard applet implementing an NDEF tag 3 | * Copyright (C) 2015-2018 Ingo Albrecht 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software Foundation, 17 | * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | package org.openjavacard.ndef.tiny; 21 | 22 | import javacard.framework.APDU; 23 | import javacard.framework.Applet; 24 | import javacard.framework.ISO7816; 25 | import javacard.framework.ISOException; 26 | import javacard.framework.JCSystem; 27 | import javacard.framework.Util; 28 | 29 | /** 30 | * \brief Applet implementing a read-only NDEF type 4 tag 31 | * 32 | * This is the TINY variant of the applet, intended as a permanent 33 | * read-only tag. It can be used to direct users to an application 34 | * or website appropriate to your card. 35 | * 36 | * No writing is supported. Data must be initialized by providing 37 | * raw NDEF data as an applet installation parameter. No verification 38 | * on the data is performed. The length indicator is prepended by the 39 | * applet and should not be included in the install parameter. 40 | * 41 | * Implemented to comply with: 42 | * NFC Forum 43 | * Type 4 Tag Operation Specification 44 | * Version 2.0 45 | * 46 | * Conformity remarks: 47 | * 1. The NDEF data file is restricted in size to the maximum 48 | * size of initialization data on the specific platform. 49 | * 2. No file control information (FCI) is returned in SELECT responses 50 | * as allowed by specification requirement RQ_T4T_NDA_034. 51 | * 3. Proprietary files are not being used. 52 | * 53 | */ 54 | public final class NdefApplet extends Applet { 55 | 56 | /* Instructions */ 57 | private static final byte INS_SELECT = ISO7816.INS_SELECT; 58 | private static final byte INS_READ_BINARY = (byte)0xB0; 59 | private static final byte INS_UPDATE_BINARY = (byte)0xD6; 60 | 61 | /* File IDs */ 62 | private static final short FILEID_NONE = (short)0x0000; 63 | private static final short FILEID_NDEF_CAPABILITIES = (short)0xE103; 64 | private static final short FILEID_NDEF_DATA = (short)0xE104; 65 | 66 | /* File access specifications */ 67 | private static final byte FILE_ACCESS_OPEN = (byte)0x00; 68 | private static final byte FILE_ACCESS_NONE = (byte)0xFF; 69 | 70 | /* Parameters for SELECT */ 71 | private static final byte SELECT_P1_BY_FILEID = (byte)0x00; 72 | private static final byte SELECT_P2_FIRST_OR_ONLY = (byte)0x0C; 73 | 74 | /* NDEF mapping version (specification 2.0) */ 75 | private static final byte NDEF_MAPPING_VERSION = (byte)0x20; 76 | 77 | /* Constants related to capability container */ 78 | private static final byte CC_LEN_HEADER = 7; 79 | private static final byte CC_TAG_NDEF_FILE_CONTROL = 0x04; 80 | private static final byte CC_LEN_NDEF_FILE_CONTROL = 6; 81 | 82 | /** 83 | * Configuration: maximum read block size 84 | */ 85 | private static final short NDEF_MAX_READ = 128; 86 | 87 | /** 88 | * Configuration: maximum write block size 89 | */ 90 | private static final short NDEF_MAX_WRITE = 128; 91 | 92 | /** 93 | * Configuration: read access 94 | */ 95 | private static final byte NDEF_READ_ACCESS = FILE_ACCESS_OPEN; 96 | 97 | /** 98 | * Configuration: write access 99 | */ 100 | private static final byte NDEF_WRITE_ACCESS = FILE_ACCESS_NONE; 101 | 102 | /** Transient variables */ 103 | private static short[] vars; 104 | /** Index for currently selected file */ 105 | private static final byte VAR_SELECTED_FILE = (byte)0; 106 | /** Number of transient variables */ 107 | private static final short NUM_VARS = (short)1; 108 | 109 | /** NDEF capability file contents */ 110 | private static byte[] capsFile; 111 | /** NDEF data file contents */ 112 | private static byte[] dataFile; 113 | 114 | /** 115 | * Installs an NDEF applet 116 | * 117 | * Will create, initialize and register an instance of 118 | * this applet as specified by the provided install data. 119 | * 120 | * Requested AID will always be honored. 121 | * Control information is ignored. 122 | * Applet data will be used for initialization. 123 | * 124 | * @param buf containing install data 125 | * @param off offset of install data in buf 126 | * @param len length of install data in buf 127 | */ 128 | public static void install(byte[] buf, short off, byte len) { 129 | short pos = off; 130 | // find AID 131 | byte lenAID = buf[pos++]; 132 | short offAID = pos; 133 | pos += lenAID; 134 | // find control information (ignored) 135 | byte lenCI = buf[pos++]; 136 | short offCI = pos; 137 | pos += lenCI; 138 | // find applet data 139 | byte lenAD = buf[pos++]; 140 | short offAD = pos; 141 | pos += lenAD; 142 | 143 | // instantiate and initialize the applet 144 | NdefApplet applet = new NdefApplet(buf, offAD, lenAD); 145 | 146 | // register the applet 147 | applet.register(); 148 | } 149 | 150 | /** 151 | * Main constructor 152 | * 153 | * This will construct and initialize an instance 154 | * of this applet according to the provided app data. 155 | * 156 | * @param buf containing application data 157 | * @param off offset of app data in buf 158 | * @param len length of app data in buf 159 | */ 160 | protected NdefApplet(byte[] buf, short off, byte len) { 161 | // length of actual data file 162 | short dataLen = (short)(len + 2); 163 | // create transient variables 164 | vars = JCSystem.makeTransientShortArray(NUM_VARS, JCSystem.CLEAR_ON_DESELECT); 165 | // create capabilities files 166 | capsFile = makeCaps(dataLen); 167 | // create data file 168 | byte[] data = null; 169 | if (len > 0) { 170 | data = new byte[dataLen]; 171 | // container size 172 | Util.setShort(data, (short) 0, len); 173 | // initial data 174 | Util.arrayCopyNonAtomic(buf, off, data, (short) 2, len); 175 | } else { 176 | ISOException.throwIt(ISO7816.SW_DATA_INVALID); 177 | } 178 | dataFile = data; 179 | } 180 | 181 | /** 182 | * Create and initialize the CAPABILITIES file 183 | * 184 | * @param dataSize to be allocated 185 | * @return an array for use as the CC file 186 | */ 187 | private byte[] makeCaps(short dataSize) { 188 | short capsLen = (short)(CC_LEN_HEADER + 2 + CC_LEN_NDEF_FILE_CONTROL); 189 | byte[] caps = new byte[capsLen]; 190 | 191 | short pos = 0; 192 | 193 | // CC length 194 | pos = Util.setShort(caps, pos, capsLen); 195 | // mapping version 196 | caps[pos++] = NDEF_MAPPING_VERSION; 197 | // maximum read size 198 | pos = Util.setShort(caps, pos, NDEF_MAX_READ); 199 | // maximum write size 200 | pos = Util.setShort(caps, pos, NDEF_MAX_WRITE); 201 | 202 | // NDEF File Control TLV 203 | caps[pos++] = CC_TAG_NDEF_FILE_CONTROL; 204 | caps[pos++] = CC_LEN_NDEF_FILE_CONTROL; 205 | // file ID 206 | pos = Util.setShort(caps, pos, FILEID_NDEF_DATA); 207 | // file size 208 | pos = Util.setShort(caps, pos, dataSize); 209 | // read access 210 | caps[pos++] = NDEF_READ_ACCESS; 211 | // write access 212 | caps[pos++] = NDEF_WRITE_ACCESS; 213 | 214 | // check consistency 215 | if(pos != capsLen) { 216 | ISOException.throwIt(ISO7816.SW_UNKNOWN); 217 | } 218 | 219 | // return the file 220 | return caps; 221 | } 222 | 223 | /** 224 | * Process an APDU 225 | * 226 | * This is the outer layer of our APDU dispatch. 227 | * 228 | * It deals with the CLA and INS of the APDU, 229 | * leaving the rest to an INS-specific function. 230 | * 231 | * @param apdu to be processed 232 | * @throws ISOException on error 233 | */ 234 | public final void process(APDU apdu) throws ISOException { 235 | byte[] buffer = apdu.getBuffer(); 236 | byte ins = buffer[ISO7816.OFFSET_INS]; 237 | 238 | // handle selection of the applet 239 | if(selectingApplet()) { 240 | vars[VAR_SELECTED_FILE] = FILEID_NONE; 241 | return; 242 | } 243 | 244 | // secure messaging is not supported 245 | if(apdu.isSecureMessagingCLA()) { 246 | ISOException.throwIt(ISO7816.SW_SECURE_MESSAGING_NOT_SUPPORTED); 247 | } 248 | 249 | // process commands to the applet 250 | if(apdu.isISOInterindustryCLA()) { 251 | if (ins == INS_SELECT) { 252 | processSelect(apdu); 253 | } else if (ins == INS_READ_BINARY) { 254 | processReadBinary(apdu); 255 | } else if (ins == INS_UPDATE_BINARY) { 256 | ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED); 257 | } else { 258 | ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); 259 | } 260 | } else { 261 | ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); 262 | } 263 | } 264 | 265 | /** 266 | * Process a SELECT command 267 | * 268 | * This handles only the one case mandated by the NDEF 269 | * specification: SELECT FIRST-OR-ONLY BY-FILE-ID. 270 | * 271 | * The file ID is specified in the APDU contents. It 272 | * must be exactly two bytes long and also valid. 273 | * 274 | * @param apdu to process 275 | * @throws ISOException on error 276 | */ 277 | private void processSelect(APDU apdu) throws ISOException { 278 | byte[] buffer = apdu.getBuffer(); 279 | byte p1 = buffer[ISO7816.OFFSET_P1]; 280 | byte p2 = buffer[ISO7816.OFFSET_P2]; 281 | 282 | // we only support what the NDEF spec prescribes 283 | if(p1 != SELECT_P1_BY_FILEID || p2 != SELECT_P2_FIRST_OR_ONLY) { 284 | ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); 285 | } 286 | 287 | // receive data 288 | short lc = apdu.setIncomingAndReceive(); 289 | 290 | // check length, must be for a file ID 291 | if(lc != 2) { 292 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 293 | } 294 | 295 | // retrieve the file ID 296 | short fileId = Util.getShort(buffer, ISO7816.OFFSET_CDATA); 297 | 298 | // perform selection if the ID is valid 299 | if(fileId == FILEID_NDEF_CAPABILITIES || fileId == FILEID_NDEF_DATA) { 300 | vars[VAR_SELECTED_FILE] = fileId; 301 | } else { 302 | ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); 303 | } 304 | } 305 | 306 | /** 307 | * Process a READ BINARY command 308 | * 309 | * This supports simple reads at any offset. 310 | * 311 | * The length of the returned data is limited 312 | * by the maximum R-APDU length as well as by 313 | * the maximum read size NDEF_MAX_READ. 314 | * 315 | * @param apdu to process 316 | * @throws ISOException on error 317 | */ 318 | private void processReadBinary(APDU apdu) throws ISOException { 319 | byte[] buffer = apdu.getBuffer(); 320 | 321 | // access the file 322 | byte[] file = accessFileForRead(vars[VAR_SELECTED_FILE]); 323 | 324 | // get and check the read offset 325 | short offset = Util.getShort(buffer, ISO7816.OFFSET_P1); 326 | if(offset < 0 || offset >= file.length) { 327 | ISOException.throwIt(ISO7816.SW_WRONG_P1P2); 328 | } 329 | 330 | // determine the output size 331 | short le = apdu.setOutgoingNoChaining(); 332 | if(le > NDEF_MAX_READ) { 333 | le = NDEF_MAX_READ; 334 | } 335 | 336 | // adjust for end of file 337 | short limit = (short)(offset + le); 338 | if(limit < 0) { 339 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 340 | } 341 | if(limit >= file.length) { 342 | le = (short)(file.length - offset); 343 | } 344 | 345 | // send the requested data 346 | apdu.setOutgoingLength(le); 347 | apdu.sendBytesLong(file, offset, le); 348 | } 349 | 350 | /** 351 | * Access a file for reading 352 | * 353 | * This function serves to perform precondition checks 354 | * before actually operating on a file in a read operation. 355 | * 356 | * If this function succeeds then the given fileId was 357 | * valid, security access has been granted and reading 358 | * of data for this file is possible. 359 | * 360 | * @param fileId of the file to be read 361 | * @return data array of the file 362 | * @throws ISOException on error 363 | */ 364 | private byte[] accessFileForRead(short fileId) throws ISOException { 365 | byte[] file = null; 366 | // select relevant data 367 | if(fileId == FILEID_NDEF_CAPABILITIES) { 368 | file = capsFile; 369 | } 370 | if(fileId == FILEID_NDEF_DATA) { 371 | file = dataFile; 372 | } 373 | // check that we got anything 374 | if(file == null) { 375 | ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); 376 | } 377 | return file; 378 | } 379 | 380 | } 381 | -------------------------------------------------------------------------------- /applet-stub/src/main/java/org/openjavacard/ndef/stub/NdefApplet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * openjavacard-ndef: JavaCard applet implementing an NDEF tag 3 | * Copyright (C) 2015-2018 Ingo Albrecht 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software Foundation, 17 | * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | package org.openjavacard.ndef.stub; 21 | 22 | import javacard.framework.AID; 23 | import javacard.framework.APDU; 24 | import javacard.framework.Applet; 25 | import javacard.framework.ISO7816; 26 | import javacard.framework.ISOException; 27 | import javacard.framework.JCSystem; 28 | import javacard.framework.Shareable; 29 | import javacard.framework.Util; 30 | 31 | /** 32 | * \brief Applet implementing an NDEF type 4 tag using a service 33 | * 34 | * This is the STUB variant of the applet. 35 | * 36 | * Implemented to comply with: 37 | * NFC Forum 38 | * Type 4 Tag Operation Specification 39 | * Version 2.0 40 | * 41 | * Conformity remarks: 42 | * 1. The NDEF data file is restricted in size to the maximum 43 | * size of initialization data on the specific platform. 44 | * 2. No file control information (FCI) is returned in SELECT responses 45 | * as allowed by specification requirement RQ_T4T_NDA_034. 46 | * 3. Proprietary files are not being used. 47 | * 48 | */ 49 | public final class NdefApplet extends Applet { 50 | 51 | /* Instructions */ 52 | private static final byte INS_SELECT = ISO7816.INS_SELECT; 53 | private static final byte INS_READ_BINARY = (byte)0xB0; 54 | private static final byte INS_UPDATE_BINARY = (byte)0xD6; 55 | 56 | /* File IDs */ 57 | private static final short FILEID_NONE = (short)0x0000; 58 | private static final short FILEID_NDEF_CAPABILITIES = (short)0xE103; 59 | private static final short FILEID_NDEF_DATA = (short)0xE104; 60 | 61 | /* File access specifications */ 62 | private static final byte FILE_ACCESS_OPEN = (byte)0x00; 63 | private static final byte FILE_ACCESS_NONE = (byte)0xFF; 64 | 65 | /* Parameters for SELECT */ 66 | private static final byte SELECT_P1_BY_FILEID = (byte)0x00; 67 | private static final byte SELECT_P2_FIRST_OR_ONLY = (byte)0x0C; 68 | 69 | /* NDEF mapping version (specification 2.0) */ 70 | private static final byte NDEF_MAPPING_VERSION = (byte)0x20; 71 | 72 | /* Constants related to capability container */ 73 | private static final byte CC_LEN_HEADER = 7; 74 | private static final byte CC_TAG_NDEF_FILE_CONTROL = 0x04; 75 | private static final byte CC_LEN_NDEF_FILE_CONTROL = 6; 76 | 77 | /** 78 | * Configuration: maximum read block size 79 | */ 80 | private static final short NDEF_MAX_READ = 128; 81 | 82 | /** 83 | * Configuration: maximum write block size 84 | */ 85 | private static final short NDEF_MAX_WRITE = 128; 86 | 87 | /** 88 | * Configuration: read access 89 | */ 90 | private static final byte NDEF_READ_ACCESS = FILE_ACCESS_OPEN; 91 | 92 | /** 93 | * Configuration: write access 94 | */ 95 | private static final byte NDEF_WRITE_ACCESS = FILE_ACCESS_NONE; 96 | 97 | /** Transient variables */ 98 | private static short[] vars; 99 | /** Index for currently selected file */ 100 | private static final byte VAR_SELECTED_FILE = (byte)0; 101 | /** Number of transient variables */ 102 | private static final short NUM_VARS = (short)1; 103 | 104 | /** Transient references */ 105 | private static Object[] refs; 106 | /** Index for reference to service */ 107 | private static final byte REF_SERVICE = (byte)0; 108 | /** Index for reference to data */ 109 | private static final byte REF_DATA = (byte)1; 110 | /** Number of transient references */ 111 | private static final short NUM_REFS = (short)2; 112 | 113 | /** ID of the service */ 114 | private static byte serviceID; 115 | /** AID of the service */ 116 | private static byte[] serviceAID; 117 | 118 | /** NDEF capability file contents */ 119 | private static byte[] capsFile; 120 | 121 | /** 122 | * Installs an NDEF applet 123 | * 124 | * Will create, initialize and register an instance of 125 | * this applet as specified by the provided install data. 126 | * 127 | * Requested AID will always be honored. 128 | * Control information is ignored. 129 | * Applet data will be used for initialization. 130 | * 131 | * @param buf containing install data 132 | * @param off offset of install data in buf 133 | * @param len length of install data in buf 134 | */ 135 | public static void install(byte[] buf, short off, byte len) { 136 | short pos = off; 137 | // find AID 138 | byte lenAID = buf[pos++]; 139 | short offAID = pos; 140 | pos += lenAID; 141 | // find control information (ignored) 142 | byte lenCI = buf[pos++]; 143 | short offCI = pos; 144 | pos += lenCI; 145 | // find applet data 146 | byte lenAD = buf[pos++]; 147 | short offAD = pos; 148 | pos += lenAD; 149 | 150 | // instantiate and initialize the applet 151 | NdefApplet applet = new NdefApplet(buf, offAD, lenAD); 152 | 153 | // register the applet 154 | applet.register(); 155 | } 156 | 157 | /** 158 | * Main constructor 159 | * 160 | * This will construct and initialize an instance 161 | * of this applet according to the provided app data. 162 | * 163 | * @param buf containing application data 164 | * @param off offset of app data in buf 165 | * @param len length of app data in buf 166 | */ 167 | protected NdefApplet(byte[] buf, short off, byte len) { 168 | // create transient variables 169 | vars = JCSystem.makeTransientShortArray(NUM_VARS, JCSystem.CLEAR_ON_DESELECT); 170 | refs = JCSystem.makeTransientObjectArray(NUM_REFS, JCSystem.CLEAR_ON_DESELECT); 171 | // create capabilities files 172 | capsFile = makeCaps((short)0); 173 | // process install data 174 | if(len < 6 || len > 17) { 175 | ISOException.throwIt(ISO7816.SW_WRONG_DATA); 176 | } 177 | // first byte is the service ID 178 | serviceID = buf[off++]; len--; 179 | // rest is the service AID 180 | serviceAID = new byte[len]; 181 | Util.arrayCopyNonAtomic(buf, off, serviceAID, (short)0, len); 182 | } 183 | 184 | /** 185 | * Create and initialize the CAPABILITIES file 186 | * 187 | * @param dataSize to be allocated 188 | * @return an array for use as the CC file 189 | */ 190 | private byte[] makeCaps(short dataSize) { 191 | short capsLen = (short)(CC_LEN_HEADER + 2 + CC_LEN_NDEF_FILE_CONTROL); 192 | byte[] caps = new byte[capsLen]; 193 | 194 | short pos = 0; 195 | 196 | // CC length 197 | pos = Util.setShort(caps, pos, capsLen); 198 | // mapping version 199 | caps[pos++] = NDEF_MAPPING_VERSION; 200 | // maximum read size 201 | pos = Util.setShort(caps, pos, NDEF_MAX_READ); 202 | // maximum write size 203 | pos = Util.setShort(caps, pos, NDEF_MAX_WRITE); 204 | 205 | // NDEF File Control TLV 206 | caps[pos++] = CC_TAG_NDEF_FILE_CONTROL; 207 | caps[pos++] = CC_LEN_NDEF_FILE_CONTROL; 208 | // file ID 209 | pos = Util.setShort(caps, pos, FILEID_NDEF_DATA); 210 | // file size 211 | pos = Util.setShort(caps, pos, dataSize); 212 | // read access 213 | caps[pos++] = NDEF_READ_ACCESS; 214 | // write access 215 | caps[pos++] = NDEF_WRITE_ACCESS; 216 | 217 | // check consistency 218 | if(pos != capsLen) { 219 | ISOException.throwIt(ISO7816.SW_UNKNOWN); 220 | } 221 | 222 | // return the file 223 | return caps; 224 | } 225 | 226 | /** 227 | * @return true if the stub is connected to a service 228 | */ 229 | private boolean isConnected() { 230 | return refs[REF_SERVICE] != null && refs[REF_DATA] != null; 231 | } 232 | 233 | /** 234 | * Attempt to connect to the backend service 235 | */ 236 | private void connectService() { 237 | NdefService service = null; 238 | // get AID object for service 239 | AID aid = JCSystem.lookupAID(serviceAID, (short)0, (byte)serviceAID.length); 240 | if(aid != null) { 241 | // get service object 242 | Shareable share = JCSystem.getAppletShareableInterfaceObject(aid, serviceID); 243 | // cast the service object 244 | if(share instanceof NdefService) { 245 | service = (NdefService)share; 246 | } 247 | } 248 | // check that we got a valid object 249 | if(service == null) { 250 | ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); 251 | } 252 | // retrieve the data array 253 | byte[] data = service.getData(); 254 | if(data == null) { 255 | ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); 256 | } 257 | // remember both references 258 | refs[REF_SERVICE] = service; 259 | refs[REF_DATA] = data; 260 | } 261 | 262 | /** 263 | * Process an APDU 264 | * 265 | * This is the outer layer of our APDU dispatch. 266 | * 267 | * It deals with the CLA and INS of the APDU, 268 | * leaving the rest to an INS-specific function. 269 | * 270 | * @param apdu to be processed 271 | * @throws ISOException on error 272 | */ 273 | public final void process(APDU apdu) throws ISOException { 274 | byte[] buffer = apdu.getBuffer(); 275 | byte ins = buffer[ISO7816.OFFSET_INS]; 276 | 277 | // handle selection of the applet 278 | if(selectingApplet()) { 279 | vars[VAR_SELECTED_FILE] = FILEID_NONE; 280 | connectService(); 281 | return; 282 | } 283 | 284 | // if we are not connected then fail 285 | if(!isConnected()) { 286 | ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); 287 | } 288 | 289 | // secure messaging is not supported 290 | if(apdu.isSecureMessagingCLA()) { 291 | ISOException.throwIt(ISO7816.SW_SECURE_MESSAGING_NOT_SUPPORTED); 292 | } 293 | 294 | // process commands to the applet 295 | if(apdu.isISOInterindustryCLA()) { 296 | if (ins == INS_SELECT) { 297 | processSelect(apdu); 298 | } else if (ins == INS_READ_BINARY) { 299 | processReadBinary(apdu); 300 | } else if (ins == INS_UPDATE_BINARY) { 301 | ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED); 302 | } else { 303 | ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); 304 | } 305 | } else { 306 | ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); 307 | } 308 | } 309 | 310 | /** 311 | * Process a SELECT command 312 | * 313 | * This handles only the one case mandated by the NDEF 314 | * specification: SELECT FIRST-OR-ONLY BY-FILE-ID. 315 | * 316 | * The file ID is specified in the APDU contents. It 317 | * must be exactly two bytes long and also valid. 318 | * 319 | * @param apdu to process 320 | * @throws ISOException on error 321 | */ 322 | private void processSelect(APDU apdu) throws ISOException { 323 | byte[] buffer = apdu.getBuffer(); 324 | byte p1 = buffer[ISO7816.OFFSET_P1]; 325 | byte p2 = buffer[ISO7816.OFFSET_P2]; 326 | 327 | // we only support what the NDEF spec prescribes 328 | if(p1 != SELECT_P1_BY_FILEID || p2 != SELECT_P2_FIRST_OR_ONLY) { 329 | ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); 330 | } 331 | 332 | // receive data 333 | short lc = apdu.setIncomingAndReceive(); 334 | 335 | // check length, must be for a file ID 336 | if(lc != 2) { 337 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 338 | } 339 | 340 | // retrieve the file ID 341 | short fileId = Util.getShort(buffer, ISO7816.OFFSET_CDATA); 342 | 343 | // perform selection if the ID is valid 344 | if(fileId == FILEID_NDEF_CAPABILITIES || fileId == FILEID_NDEF_DATA) { 345 | vars[VAR_SELECTED_FILE] = fileId; 346 | } else { 347 | ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); 348 | } 349 | } 350 | 351 | /** 352 | * Process a READ BINARY command 353 | * 354 | * This supports simple reads at any offset. 355 | * 356 | * The length of the returned data is limited 357 | * by the maximum R-APDU length as well as by 358 | * the maximum read size NDEF_MAX_READ. 359 | * 360 | * @param apdu to process 361 | * @throws ISOException on error 362 | */ 363 | private void processReadBinary(APDU apdu) throws ISOException { 364 | byte[] buffer = apdu.getBuffer(); 365 | 366 | // access the file 367 | byte[] file = accessFileForRead(vars[VAR_SELECTED_FILE]); 368 | 369 | // get and check the read offset 370 | short offset = Util.getShort(buffer, ISO7816.OFFSET_P1); 371 | if(offset < 0 || offset >= file.length) { 372 | ISOException.throwIt(ISO7816.SW_WRONG_P1P2); 373 | } 374 | 375 | // determine the output size 376 | short le = apdu.setOutgoingNoChaining(); 377 | if(le > NDEF_MAX_READ) { 378 | le = NDEF_MAX_READ; 379 | } 380 | 381 | // adjust for end of file 382 | short limit = (short)(offset + le); 383 | if(limit < 0) { 384 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 385 | } 386 | if(limit >= file.length) { 387 | le = (short)(file.length - offset); 388 | } 389 | 390 | // send the requested data 391 | apdu.setOutgoingLength(le); 392 | apdu.sendBytesLong(file, offset, le); 393 | } 394 | 395 | /** 396 | * Access a file for reading 397 | * 398 | * This function serves to perform precondition checks 399 | * before actually operating on a file in a read operation. 400 | * 401 | * If this function succeeds then the given fileId was 402 | * valid, security access has been granted and reading 403 | * of data for this file is possible. 404 | * 405 | * @param fileId of the file to be read 406 | * @return data array of the file 407 | * @throws ISOException on error 408 | */ 409 | private byte[] accessFileForRead(short fileId) throws ISOException { 410 | byte[] file = null; 411 | // select relevant data 412 | if(fileId == FILEID_NDEF_CAPABILITIES) { 413 | file = capsFile; 414 | } 415 | if(fileId == FILEID_NDEF_DATA) { 416 | file = (byte[])refs[REF_DATA]; 417 | } 418 | // check that we got anything 419 | if(file == null) { 420 | ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); 421 | } 422 | return file; 423 | } 424 | 425 | } 426 | -------------------------------------------------------------------------------- /applet-full/src/main/java/org/openjavacard/ndef/full/NdefApplet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * openjavacard-ndef: JavaCard applet implementing an NDEF tag 3 | * Copyright (C) 2015-2018 Ingo Albrecht 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software Foundation, 17 | * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | package org.openjavacard.ndef.full; 21 | 22 | import javacard.framework.APDU; 23 | import javacard.framework.Applet; 24 | import javacard.framework.ISO7816; 25 | import javacard.framework.ISOException; 26 | import javacard.framework.JCSystem; 27 | import javacard.framework.Util; 28 | 29 | /** 30 | * \brief Applet implementing an NDEF type 4 tag 31 | * 32 | * Implemented to comply with: 33 | * NFC Forum 34 | * Type 4 Tag Operation Specification 35 | * Version 2.0 36 | * 37 | * Conformity remarks: 38 | * 1. The NDEF data file can be up to 32767 bytes in size, 39 | * corresponding to the specification maximum. 40 | * 2. No file control information (FCI) is returned in SELECT responses 41 | * as allowed by specification requirement RQ_T4T_NDA_034. 42 | * 3. Proprietary access modes are being used for custom features, 43 | * however they are not exposed in the capability descriptor. 44 | * 4. Proprietary files are not being used. 45 | * 46 | */ 47 | public final class NdefApplet extends Applet { 48 | 49 | /* Instructions */ 50 | private static final byte INS_SELECT = ISO7816.INS_SELECT; 51 | private static final byte INS_READ_BINARY = (byte)0xB0; 52 | private static final byte INS_UPDATE_BINARY = (byte)0xD6; 53 | 54 | /* File IDs */ 55 | private static final short FILEID_NONE = (short)0x0000; 56 | private static final short FILEID_NDEF_CAPABILITIES = (short)0xE103; 57 | private static final short FILEID_NDEF_DATA = (short)0xE104; 58 | 59 | /* File access specifications */ 60 | private static final byte FILE_ACCESS_OPEN = (byte)0x00; 61 | private static final byte FILE_ACCESS_NONE = (byte)0xFF; 62 | private static final byte FILE_ACCESS_PROP_CONTACT_ONLY = (byte)0xF0; 63 | private static final byte FILE_ACCESS_PROP_WRITE_ONCE = (byte)0xF1; 64 | 65 | /* Parameters for SELECT */ 66 | private static final byte SELECT_P1_BY_FILEID = (byte)0x00; 67 | private static final byte SELECT_P2_FIRST_OR_ONLY = (byte)0x0C; 68 | 69 | /* NDEF mapping version (specification 2.0) */ 70 | private static final byte NDEF_MAPPING_VERSION = (byte)0x20; 71 | 72 | /* Install parameter tags */ 73 | private static final byte AD_TAG_NDEF_DATA_INITIAL = (byte)0x80; 74 | private static final byte AD_TAG_NDEF_DATA_ACCESS = (byte)0x81; 75 | private static final byte AD_TAG_NDEF_DATA_SIZE = (byte)0x82; 76 | 77 | /* Constants related to capability container */ 78 | private static final byte CC_LEN_HEADER = 7; 79 | private static final byte CC_OFF_NDEF_FILE_CONTROL = 0x07; 80 | private static final byte CC_TAG_NDEF_FILE_CONTROL = 0x04; 81 | private static final byte CC_LEN_NDEF_FILE_CONTROL = 6; 82 | 83 | /* Constants related to file control data in capabilities */ 84 | private static final byte FC_OFF_FILE_ID = 0x00; 85 | private static final byte FC_OFF_SIZE = 0x02; 86 | private static final byte FC_OFF_READ_ACCESS = 0x04; 87 | private static final byte FC_OFF_WRITE_ACCESS = 0x05; 88 | 89 | /** 90 | * Configuration: support for writing 91 | * 92 | * If disabled then no writing will be allowed after 93 | * initialization. Intended for use in combination 94 | * with install parameters. 95 | */ 96 | private static final boolean FEATURE_WRITING = true; 97 | 98 | /** 99 | * Configuration: support for install parameters 100 | * 101 | * If enabled this will allow customization of the applet 102 | * during installation by using application parameters. 103 | * 104 | * Disabling this saves up to 600 bytes. 105 | */ 106 | private static final boolean FEATURE_INSTALL_PARAMETERS = true; 107 | 108 | /** 109 | * Configuration: support advanced access restrictions 110 | * 111 | * If enabled the applet will support the special 112 | * access modes "contact only" as well as "write once". 113 | * 114 | * Disabling this saves about 170 bytes. 115 | */ 116 | private static final boolean FEATURE_ADVANCED_ACCESS_CONTROL = true; 117 | 118 | /** 119 | * Configuration: maximum read block size 120 | */ 121 | private static final short NDEF_MAX_READ = 128; 122 | 123 | /** 124 | * Configuration: maximum write block size 125 | */ 126 | private static final short NDEF_MAX_WRITE = 128; 127 | 128 | /** 129 | * Configuration: maximum size of data file 130 | * 131 | * Two bytes are used for the record length, 132 | * the rest will be available for an NDEF record. 133 | */ 134 | private static final short DEFAULT_NDEF_DATA_SIZE = 256; 135 | 136 | /** 137 | * Configuration: default read access for data file 138 | */ 139 | private static final byte DEFAULT_NDEF_READ_ACCESS = FILE_ACCESS_OPEN; 140 | 141 | /** 142 | * Configuration: default write access for data file 143 | */ 144 | private static final byte DEFAULT_NDEF_WRITE_ACCESS = FILE_ACCESS_OPEN; 145 | 146 | 147 | /** Transient variables */ 148 | private short[] vars; 149 | /** Variable index for currently selected file */ 150 | private static final byte VAR_SELECTED_FILE = (byte)0; 151 | /** Number of transient variables */ 152 | private static final short NUM_VARS = (short)1; 153 | 154 | /** NDEF capability file contents */ 155 | private final byte[] capsFile; 156 | /** NDEF data file contents */ 157 | private final byte[] dataFile; 158 | 159 | /** NDEF data read access policy */ 160 | private final byte dataReadAccess; 161 | /** NDEF data write access policy */ 162 | private final byte dataWriteAccess; 163 | 164 | /** 165 | * Installs an NDEF applet 166 | * 167 | * Will create, initialize and register an instance of 168 | * this applet as specified by the provided install data. 169 | * 170 | * Requested AID will always be honored. 171 | * Control information is ignored. 172 | * Applet data will be used for initialization. 173 | * 174 | * @param buf containing install data 175 | * @param off offset of install data in buf 176 | * @param len length of install data in buf 177 | */ 178 | public static void install(byte[] buf, short off, byte len) { 179 | short pos = off; 180 | // find AID 181 | byte lenAID = buf[pos++]; 182 | short offAID = pos; 183 | pos += lenAID; 184 | // find control information (ignored) 185 | byte lenCI = buf[pos++]; 186 | short offCI = pos; 187 | pos += lenCI; 188 | // find applet data 189 | byte lenAD = buf[pos++]; 190 | short offAD = pos; 191 | pos += lenAD; 192 | 193 | // instantiate and initialize the applet 194 | NdefApplet applet = new NdefApplet(buf, offAD, lenAD); 195 | 196 | // register the applet 197 | applet.register(buf, offAID, lenAID); 198 | } 199 | 200 | /** 201 | * Main constructor 202 | * 203 | * This will construct and initialize an instance 204 | * of this applet according to the provided app data. 205 | * 206 | * @param buf containing application data 207 | * @param off offset of app data in buf 208 | * @param len length of app data in buf 209 | */ 210 | protected NdefApplet(byte[] buf, short off, byte len) { 211 | 212 | short initSize = DEFAULT_NDEF_DATA_SIZE; 213 | byte initReadAccess = DEFAULT_NDEF_READ_ACCESS; 214 | byte initWriteAccess = DEFAULT_NDEF_WRITE_ACCESS; 215 | byte[] initBuf = null; 216 | short initOff = 0; 217 | short initLen = 0; 218 | 219 | // create variables 220 | vars = JCSystem.makeTransientShortArray(NUM_VARS, JCSystem.CLEAR_ON_DESELECT); 221 | 222 | // process application data 223 | if(FEATURE_INSTALL_PARAMETERS) { 224 | // check TLV consistency 225 | if (!UtilTLV.isTLVconsistent(buf, off, len)) { 226 | ISOException.throwIt(ISO7816.SW_DATA_INVALID); 227 | } 228 | 229 | // DATA INITIAL 230 | short initTag = UtilTLV.findTag(buf, off, len, AD_TAG_NDEF_DATA_INITIAL); 231 | if (initTag >= 0) { 232 | initBuf = buf; 233 | initLen = UtilTLV.decodeLengthField(buf, (short) (initTag + 1)); 234 | initOff = (short) (initTag + 1 + UtilTLV.getLengthFieldLength(initLen)); 235 | // restrict writing, can be overridden using DATA ACCESS 236 | initWriteAccess = FILE_ACCESS_NONE; 237 | // adjust size, can be overridden 238 | initSize = (short) (2 + initLen); 239 | } 240 | 241 | // DATA ACCESS 242 | short tagAccess = UtilTLV.findTag(buf, off, len, AD_TAG_NDEF_DATA_ACCESS); 243 | if (tagAccess >= 0) { 244 | short accessLen = UtilTLV.decodeLengthField(buf, (short) (tagAccess + 1)); 245 | if (accessLen != 2) { 246 | ISOException.throwIt(ISO7816.SW_DATA_INVALID); 247 | } 248 | initReadAccess = buf[(short) (tagAccess + 2)]; 249 | initWriteAccess = buf[(short) (tagAccess + 3)]; 250 | } 251 | 252 | // DATA SIZE 253 | short tagSize = UtilTLV.findTag(buf, off, len, AD_TAG_NDEF_DATA_SIZE); 254 | if (tagSize >= 0) { 255 | short sizeLen = UtilTLV.decodeLengthField(buf, (short) (tagSize + 1)); 256 | if (sizeLen != 2) { 257 | ISOException.throwIt(ISO7816.SW_DATA_INVALID); 258 | } 259 | initSize = Util.getShort(buf, (short) (tagSize + 2)); 260 | if (initSize < 0) { 261 | ISOException.throwIt(ISO7816.SW_DATA_INVALID); 262 | } 263 | } 264 | } 265 | 266 | // squash write access if not supported 267 | if(!FEATURE_WRITING) { 268 | initWriteAccess = FILE_ACCESS_NONE; 269 | } 270 | 271 | // set up access 272 | dataReadAccess = initReadAccess; 273 | dataWriteAccess = initWriteAccess; 274 | 275 | // create file contents 276 | capsFile = makeCaps(initSize, initReadAccess, initWriteAccess); 277 | dataFile = makeData(initSize, initBuf, initOff, initLen); 278 | } 279 | 280 | /** 281 | * Create and initialize the CAPABILITIES file 282 | * 283 | * @param dataSize to be allocated 284 | * @param dataReadAccess to put in the CC 285 | * @param dataWriteAccess to put in the CC 286 | * @return an array for use as the CC file 287 | */ 288 | private byte[] makeCaps(short dataSize, 289 | byte dataReadAccess, byte dataWriteAccess) { 290 | short capsLen = (short)(CC_LEN_HEADER + 2 + CC_LEN_NDEF_FILE_CONTROL); 291 | byte[] caps = new byte[capsLen]; 292 | 293 | short pos = 0; 294 | 295 | // CC length 296 | pos = Util.setShort(caps, pos, capsLen); 297 | // mapping version 298 | caps[pos++] = NDEF_MAPPING_VERSION; 299 | // maximum read size 300 | pos = Util.setShort(caps, pos, NDEF_MAX_READ); 301 | // maximum write size 302 | pos = Util.setShort(caps, pos, NDEF_MAX_WRITE); 303 | 304 | // NDEF File Control TLV 305 | caps[pos++] = CC_TAG_NDEF_FILE_CONTROL; 306 | caps[pos++] = CC_LEN_NDEF_FILE_CONTROL; 307 | // file ID 308 | pos = Util.setShort(caps, pos, FILEID_NDEF_DATA); 309 | // file size 310 | pos = Util.setShort(caps, pos, dataSize); 311 | // read access 312 | caps[pos++] = dataReadAccess; 313 | // write access 314 | caps[pos++] = dataWriteAccess; 315 | 316 | // check consistency 317 | if(pos != capsLen) { 318 | ISOException.throwIt(ISO7816.SW_UNKNOWN); 319 | } 320 | 321 | // return the file 322 | return caps; 323 | } 324 | 325 | /** 326 | * Create and initialize the DATA file 327 | * 328 | * @param dataSize to be allocated 329 | * @param init buffer containing initial data 330 | * @param initOff offset of initial data in buffer 331 | * @param initLen length of initial data in buffer 332 | * @return an array for use as the data file 333 | */ 334 | private byte[] makeData(short dataSize, byte[] init, short initOff, short initLen) { 335 | byte[] data = new byte[dataSize]; 336 | 337 | // initialize from init, if provided 338 | if (FEATURE_INSTALL_PARAMETERS) { 339 | if (init != null && initLen > 0) { 340 | // container size 341 | Util.setShort(data, (short) 0, initLen); 342 | // initial data 343 | Util.arrayCopyNonAtomic(init, initOff, data, (short) 2, initLen); 344 | } 345 | } 346 | 347 | return data; 348 | } 349 | 350 | /** 351 | * Fix up a capability container 352 | * 353 | * This will be called to fix up capabilities before 354 | * they are actually sent out to the host device. 355 | * 356 | * Currently this only fixes up the access policies 357 | * so as to hide our proprietary policies. 358 | * 359 | * @param caps buffer containing CC to fix 360 | * @param off offset of CC in buffer 361 | * @param len of CC in buffer 362 | */ 363 | private void fixCaps(byte[] caps, short off, short len) { 364 | if(FEATURE_ADVANCED_ACCESS_CONTROL) { 365 | short offNFC = (short) (off + CC_OFF_NDEF_FILE_CONTROL + 2); 366 | short offR = (short) (offNFC + FC_OFF_READ_ACCESS); 367 | short offW = (short) (offNFC + FC_OFF_WRITE_ACCESS); 368 | caps[offR] = fixAccess(dataFile, dataReadAccess); 369 | caps[offW] = fixAccess(dataFile, dataWriteAccess); 370 | } 371 | } 372 | 373 | /** 374 | * Process an APDU 375 | * 376 | * This is the outer layer of our APDU dispatch. 377 | * 378 | * It deals with the CLA and INS of the APDU, 379 | * leaving the rest to an INS-specific function. 380 | * 381 | * @param apdu to be processed 382 | * @throws ISOException on error 383 | */ 384 | public final void process(APDU apdu) throws ISOException { 385 | byte[] buffer = apdu.getBuffer(); 386 | byte ins = buffer[ISO7816.OFFSET_INS]; 387 | 388 | // handle selection of the applet 389 | if(selectingApplet()) { 390 | vars[VAR_SELECTED_FILE] = FILEID_NONE; 391 | return; 392 | } 393 | 394 | // secure messaging is not supported 395 | if(apdu.isSecureMessagingCLA()) { 396 | ISOException.throwIt(ISO7816.SW_SECURE_MESSAGING_NOT_SUPPORTED); 397 | } 398 | 399 | // process commands to the applet 400 | if(apdu.isISOInterindustryCLA()) { 401 | if (ins == INS_SELECT) { 402 | processSelect(apdu); 403 | } else if (ins == INS_READ_BINARY) { 404 | processReadBinary(apdu); 405 | } else if (ins == INS_UPDATE_BINARY) { 406 | if(FEATURE_WRITING) { 407 | processUpdateBinary(apdu); 408 | } else { 409 | ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED); 410 | } 411 | } else { 412 | ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); 413 | } 414 | } else { 415 | ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); 416 | } 417 | } 418 | 419 | /** 420 | * Process a SELECT command 421 | * 422 | * This handles only the one case mandated by the NDEF 423 | * specification: SELECT FIRST-OR-ONLY BY-FILE-ID. 424 | * 425 | * The file ID is specified in the APDU contents. It 426 | * must be exactly two bytes long and also valid. 427 | * 428 | * @param apdu to process 429 | * @throws ISOException on error 430 | */ 431 | private void processSelect(APDU apdu) throws ISOException { 432 | byte[] buffer = apdu.getBuffer(); 433 | byte p1 = buffer[ISO7816.OFFSET_P1]; 434 | byte p2 = buffer[ISO7816.OFFSET_P2]; 435 | 436 | // we only support what the NDEF spec prescribes 437 | if(p1 != SELECT_P1_BY_FILEID || p2 != SELECT_P2_FIRST_OR_ONLY) { 438 | ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); 439 | } 440 | 441 | // receive data 442 | short lc = apdu.setIncomingAndReceive(); 443 | 444 | // check length, must be for a file ID 445 | if(lc != 2) { 446 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 447 | } 448 | 449 | // retrieve the file ID 450 | short fileId = Util.getShort(buffer, ISO7816.OFFSET_CDATA); 451 | 452 | // perform selection if the ID is valid 453 | if(fileId == FILEID_NDEF_CAPABILITIES || fileId == FILEID_NDEF_DATA) { 454 | vars[VAR_SELECTED_FILE] = fileId; 455 | } else { 456 | ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); 457 | } 458 | } 459 | 460 | /** 461 | * Process a READ BINARY command 462 | * 463 | * This supports simple reads at any offset. 464 | * 465 | * The length of the returned data is limited 466 | * by the maximum R-APDU length as well as by 467 | * the maximum read size NDEF_MAX_READ. 468 | * 469 | * @param apdu to process 470 | * @throws ISOException on error 471 | */ 472 | private void processReadBinary(APDU apdu) throws ISOException { 473 | byte[] buffer = apdu.getBuffer(); 474 | 475 | // access the file 476 | byte[] file = accessFileForRead(vars[VAR_SELECTED_FILE]); 477 | 478 | // get and check the read offset 479 | short offset = Util.getShort(buffer, ISO7816.OFFSET_P1); 480 | if(offset < 0 || offset >= file.length) { 481 | ISOException.throwIt(ISO7816.SW_WRONG_P1P2); 482 | } 483 | 484 | // determine the output size 485 | short le = apdu.setOutgoingNoChaining(); 486 | if(le > NDEF_MAX_READ) { 487 | le = NDEF_MAX_READ; 488 | } 489 | 490 | // adjust for end of file 491 | short limit = (short)(offset + le); 492 | if(limit < 0) { 493 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 494 | } 495 | if(limit >= file.length) { 496 | le = (short)(file.length - offset); 497 | } 498 | 499 | // send the requested data 500 | if(vars[VAR_SELECTED_FILE] == FILEID_NDEF_CAPABILITIES) { 501 | // send fixed capabilities 502 | Util.arrayCopyNonAtomic(file, (short)0, 503 | buffer, (short)0, 504 | (short)file.length); 505 | fixCaps(buffer, (short)0, (short)file.length); 506 | apdu.setOutgoingLength(le); 507 | apdu.sendBytesLong(buffer, offset, le); 508 | } else { 509 | // send directly 510 | apdu.setOutgoingLength(le); 511 | apdu.sendBytesLong(file, offset, le); 512 | } 513 | } 514 | 515 | /** 516 | * Process an UPDATE BINARY command 517 | * 518 | * Supports simple writes at any offset. 519 | * 520 | * The amount of data that can be written in one 521 | * operation is limited both by maximum C-APDU 522 | * length and the maximum write size NDEF_MAX_WRITE. 523 | * 524 | * @param apdu to process 525 | * @throws ISOException on error 526 | */ 527 | private void processUpdateBinary(APDU apdu) throws ISOException { 528 | byte[] buffer = apdu.getBuffer(); 529 | 530 | // access the file 531 | byte[] file = accessFileForWrite(vars[VAR_SELECTED_FILE]); 532 | 533 | // get and check the write offset 534 | short offset = Util.getShort(buffer, ISO7816.OFFSET_P1); 535 | if(offset < 0 || offset >= file.length) { 536 | ISOException.throwIt(ISO7816.SW_WRONG_P1P2); 537 | } 538 | 539 | // receive data 540 | short lc = apdu.setIncomingAndReceive(); 541 | 542 | // check the input size 543 | if(lc > NDEF_MAX_WRITE) { 544 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 545 | } 546 | 547 | // file limit checks 548 | short limit = (short)(offset + lc); 549 | if(limit < 0 || limit >= file.length) { 550 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 551 | } 552 | 553 | // perform the update 554 | Util.arrayCopy(buffer, ISO7816.OFFSET_CDATA, file, offset, lc); 555 | } 556 | 557 | /** 558 | * Check if file access should be granted 559 | * 560 | * This will perform all necessary checks to determine 561 | * if an operation can currently be allowed within the 562 | * policy specified in ACCESS. 563 | * 564 | * @param access policy to be checked 565 | * @return true if access granted, false otherwise 566 | */ 567 | private boolean checkAccess(byte[] data, byte access) { 568 | if(!FEATURE_ADVANCED_ACCESS_CONTROL) { 569 | // simple access control 570 | return access == FILE_ACCESS_OPEN; 571 | } else { 572 | // get protocol and media information 573 | byte protocol = APDU.getProtocol(); 574 | byte media = (byte) (protocol & APDU.PROTOCOL_MEDIA_MASK); 575 | // make the decision 576 | switch (access) { 577 | case FILE_ACCESS_OPEN: 578 | return true; 579 | case FILE_ACCESS_PROP_CONTACT_ONLY: 580 | return media == APDU.PROTOCOL_MEDIA_DEFAULT; 581 | case FILE_ACCESS_PROP_WRITE_ONCE: 582 | return data[0] == 0 && data[1] == 0; 583 | default: 584 | case FILE_ACCESS_NONE: 585 | return false; 586 | } 587 | } 588 | } 589 | 590 | /** 591 | * Fix up an access policy to reflect current state 592 | * 593 | * This is used to squash our custom access policies 594 | * so that we do not have to present a proprietary 595 | * policy to unsuspecting host devices. 596 | * 597 | * @param data of the file for which to fix 598 | * @param access policy for to fix 599 | * @return a fixed access policy 600 | */ 601 | private byte fixAccess(byte[] data, byte access) { 602 | // figure out the right policy 603 | switch(access) { 604 | // by default we pass through 605 | default: 606 | return access; 607 | // these two require fixing 608 | case FILE_ACCESS_PROP_CONTACT_ONLY: 609 | case FILE_ACCESS_PROP_WRITE_ONCE: 610 | return (checkAccess(data, access)) 611 | ? FILE_ACCESS_OPEN : FILE_ACCESS_NONE; 612 | } 613 | } 614 | 615 | /** 616 | * Access a file for reading 617 | * 618 | * This function serves to perform precondition checks 619 | * before actually operating on a file in a read operation. 620 | * 621 | * If this function succeeds then the given fileId was 622 | * valid, security access has been granted and reading 623 | * of data for this file is possible. 624 | * 625 | * @param fileId of the file to be read 626 | * @return data array of the file 627 | * @throws ISOException on error 628 | */ 629 | private byte[] accessFileForRead(short fileId) throws ISOException { 630 | byte[] file = null; 631 | byte access = FILE_ACCESS_NONE; 632 | // select relevant data 633 | if(fileId == FILEID_NDEF_CAPABILITIES) { 634 | file = capsFile; 635 | access = FILE_ACCESS_OPEN; 636 | } 637 | if(fileId == FILEID_NDEF_DATA) { 638 | file = dataFile; 639 | access = dataReadAccess; 640 | } 641 | // check that we got anything 642 | if(file == null) { 643 | ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); 644 | } 645 | // perform access checks 646 | if(!checkAccess(file, access)) { 647 | ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); 648 | } 649 | return file; 650 | } 651 | 652 | /** 653 | * Access a file for writing 654 | * 655 | * This function serves to perform precondition checks 656 | * before actually operating on a file in a write operation. 657 | * 658 | * If this function succeeds then the given fileId was 659 | * valid, security access has been granted and writing 660 | * of data for this file is possible. 661 | * 662 | * @param fileId of the file to be written 663 | * @return data array of the file 664 | * @throws ISOException on error 665 | */ 666 | private byte[] accessFileForWrite(short fileId) throws ISOException { 667 | byte[] file = null; 668 | byte access = FILE_ACCESS_NONE; 669 | // CC can not be written 670 | if(fileId == FILEID_NDEF_CAPABILITIES) { 671 | ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); 672 | } 673 | // select relevant data 674 | if(fileId == FILEID_NDEF_DATA) { 675 | file = dataFile; 676 | access = dataWriteAccess; 677 | } 678 | // check that we got something 679 | if(file == null) { 680 | ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); 681 | } 682 | // perform access checks 683 | if(!checkAccess(file, access)) { 684 | ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); 685 | } 686 | return file; 687 | } 688 | 689 | } 690 | -------------------------------------------------------------------------------- /applet-advanced/src/main/java/org/openjavacard/ndef/advanced/NdefApplet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * openjavacard-ndef: JavaCard applet implementing an NDEF tag 3 | * Copyright (C) 2015-2018 Ingo Albrecht 4 | * 5 | * This program is free software; you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation; either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program; if not, write to the Free Software Foundation, 17 | * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | package org.openjavacard.ndef.advanced; 21 | 22 | import javacard.framework.APDU; 23 | import javacard.framework.Applet; 24 | import javacard.framework.ISO7816; 25 | import javacard.framework.ISOException; 26 | import javacard.framework.JCSystem; 27 | import javacard.framework.Util; 28 | 29 | /** 30 | * \brief Applet implementing an NDEF type 4 tag 31 | * 32 | * Implemented to comply with: 33 | * NFC Forum 34 | * Type 4 Tag Operation Specification 35 | * Version 2.0 36 | * 37 | * Conformity remarks: 38 | * 1. The NDEF data file can be up to 32767 bytes in size, 39 | * corresponding to the specification maximum. 40 | * 2. No file control information (FCI) is returned in SELECT responses 41 | * as allowed by specification requirement RQ_T4T_NDA_034. 42 | * 3. Proprietary access modes are being used for custom features, 43 | * however they are not exposed in the capability descriptor. 44 | * 4. Proprietary files are not being used. 45 | * 46 | */ 47 | public final class NdefApplet extends Applet { 48 | 49 | /* Instructions */ 50 | private static final byte INS_SELECT = ISO7816.INS_SELECT; 51 | private static final byte INS_READ_BINARY = (byte)0xB0; 52 | private static final byte INS_UPDATE_BINARY = (byte)0xD6; 53 | 54 | /* File IDs */ 55 | private static final short FILEID_NONE = (short)0x0000; 56 | private static final short FILEID_NDEF_CAPABILITIES = (short)0xE103; 57 | private static final short FILEID_NDEF_DATA = (short)0xE104; 58 | 59 | /* File access specifications */ 60 | private static final byte FILE_ACCESS_OPEN = (byte)0x00; 61 | private static final byte FILE_ACCESS_NONE = (byte)0xFF; 62 | private static final byte FILE_ACCESS_PROP_CONTACT_ONLY = (byte)0xF0; 63 | private static final byte FILE_ACCESS_PROP_WRITE_ONCE = (byte)0xF1; 64 | 65 | /* Parameters for SELECT */ 66 | private static final byte SELECT_P1_BY_FILEID = (byte)0x00; 67 | private static final byte SELECT_P2_FIRST_OR_ONLY = (byte)0x0C; 68 | 69 | /* NDEF mapping version (specification 2.0) */ 70 | private static final byte NDEF_MAPPING_VERSION = (byte)0x20; 71 | 72 | /* Install parameter tags */ 73 | private static final byte AD_TAG_NDEF_DATA_INITIAL = (byte)0x80; 74 | private static final byte AD_TAG_NDEF_DATA_ACCESS = (byte)0x81; 75 | private static final byte AD_TAG_NDEF_DATA_SIZE = (byte)0x82; 76 | 77 | /* Constants related to capability container */ 78 | private static final byte CC_LEN_HEADER = 7; 79 | private static final byte CC_OFF_NDEF_FILE_CONTROL = 0x07; 80 | private static final byte CC_TAG_NDEF_FILE_CONTROL = 0x04; 81 | private static final byte CC_LEN_NDEF_FILE_CONTROL = 6; 82 | 83 | /* Constants related to file control data in capabilities */ 84 | private static final byte FC_OFF_FILE_ID = 0x00; 85 | private static final byte FC_OFF_SIZE = 0x02; 86 | private static final byte FC_OFF_READ_ACCESS = 0x04; 87 | private static final byte FC_OFF_WRITE_ACCESS = 0x05; 88 | 89 | /** 90 | * Configuration: support for writing 91 | * 92 | * If disabled then no writing will be allowed after 93 | * initialization. Intended for use in combination 94 | * with install parameters. 95 | */ 96 | private static final boolean FEATURE_WRITING = true; 97 | 98 | /** 99 | * Configuration: support for install parameters 100 | * 101 | * If enabled this will allow customization of the applet 102 | * during installation by using application parameters. 103 | * 104 | * Disabling this saves up to 600 bytes. 105 | */ 106 | private static final boolean FEATURE_INSTALL_PARAMETERS = true; 107 | 108 | /** 109 | * Configuration: support advanced access restrictions 110 | * 111 | * If enabled the applet will support the special 112 | * access modes "contact only" as well as "write once". 113 | * 114 | * Disabling this saves about 170 bytes. 115 | */ 116 | private static final boolean FEATURE_ADVANCED_ACCESS_CONTROL = true; 117 | 118 | /** 119 | * Configuration: maximum read block size 120 | */ 121 | private static final short NDEF_MAX_READ = 128; 122 | 123 | /** 124 | * Configuration: maximum write block size 125 | */ 126 | private static final short NDEF_MAX_WRITE = 128; 127 | 128 | /** 129 | * Configuration: maximum size of data file 130 | * 131 | * Two bytes are used for the record length, 132 | * the rest will be available for an NDEF record. 133 | */ 134 | private static final short DEFAULT_NDEF_DATA_SIZE = 256; 135 | 136 | /** 137 | * Configuration: default read access for data file 138 | */ 139 | private static final byte DEFAULT_NDEF_READ_ACCESS = FILE_ACCESS_OPEN; 140 | 141 | /** 142 | * Configuration: default write access for data file 143 | */ 144 | private static final byte DEFAULT_NDEF_WRITE_ACCESS = FILE_ACCESS_OPEN; 145 | 146 | 147 | /** Transient variables */ 148 | private short[] vars; 149 | /** Variable index for currently selected file */ 150 | private static final byte VAR_SELECTED_FILE = (byte)0; 151 | /** Number of transient variables */ 152 | private static final short NUM_VARS = (short)1; 153 | 154 | /** NDEF capability file contents */ 155 | private final byte[] capsFile; 156 | /** NDEF data file contents */ 157 | private final byte[] dataFile; 158 | 159 | /** NDEF data read access policy */ 160 | private final byte dataReadAccess; 161 | /** NDEF data write access policy */ 162 | private final byte dataWriteAccess; 163 | 164 | /** 165 | * Installs an NDEF applet 166 | * 167 | * Will create, initialize and register an instance of 168 | * this applet as specified by the provided install data. 169 | * 170 | * Requested AID will always be honored. 171 | * Control information is ignored. 172 | * Applet data will be used for initialization. 173 | * 174 | * @param buf containing install data 175 | * @param off offset of install data in buf 176 | * @param len length of install data in buf 177 | */ 178 | public static void install(byte[] buf, short off, byte len) { 179 | short pos = off; 180 | // find AID 181 | byte lenAID = buf[pos++]; 182 | short offAID = pos; 183 | pos += lenAID; 184 | // find control information (ignored) 185 | byte lenCI = buf[pos++]; 186 | short offCI = pos; 187 | pos += lenCI; 188 | // find applet data 189 | byte lenAD = buf[pos++]; 190 | short offAD = pos; 191 | pos += lenAD; 192 | 193 | // instantiate and initialize the applet 194 | NdefApplet applet = new NdefApplet(buf, offAD, lenAD); 195 | 196 | // register the applet 197 | applet.register(buf, offAID, lenAID); 198 | } 199 | 200 | /** 201 | * Main constructor 202 | * 203 | * This will construct and initialize an instance 204 | * of this applet according to the provided app data. 205 | * 206 | * @param buf containing application data 207 | * @param off offset of app data in buf 208 | * @param len length of app data in buf 209 | */ 210 | protected NdefApplet(byte[] buf, short off, byte len) { 211 | 212 | short initSize = DEFAULT_NDEF_DATA_SIZE; 213 | byte initReadAccess = DEFAULT_NDEF_READ_ACCESS; 214 | byte initWriteAccess = DEFAULT_NDEF_WRITE_ACCESS; 215 | byte[] initBuf = null; 216 | short initOff = 0; 217 | short initLen = 0; 218 | 219 | // create variables 220 | vars = JCSystem.makeTransientShortArray(NUM_VARS, JCSystem.CLEAR_ON_DESELECT); 221 | 222 | // process application data 223 | if(FEATURE_INSTALL_PARAMETERS) { 224 | // check TLV consistency 225 | if (!UtilTLV.isTLVconsistent(buf, off, len)) { 226 | ISOException.throwIt(ISO7816.SW_DATA_INVALID); 227 | } 228 | 229 | // DATA INITIAL 230 | short initTag = UtilTLV.findTag(buf, off, len, AD_TAG_NDEF_DATA_INITIAL); 231 | if (initTag >= 0) { 232 | initBuf = buf; 233 | initLen = UtilTLV.decodeLengthField(buf, (short) (initTag + 1)); 234 | initOff = (short) (initTag + 1 + UtilTLV.getLengthFieldLength(initLen)); 235 | // restrict writing, can be overridden using DATA ACCESS 236 | initWriteAccess = FILE_ACCESS_NONE; 237 | // adjust size, can be overridden 238 | initSize = (short) (2 + initLen); 239 | } 240 | 241 | // DATA ACCESS 242 | short tagAccess = UtilTLV.findTag(buf, off, len, AD_TAG_NDEF_DATA_ACCESS); 243 | if (tagAccess >= 0) { 244 | short accessLen = UtilTLV.decodeLengthField(buf, (short) (tagAccess + 1)); 245 | if (accessLen != 2) { 246 | ISOException.throwIt(ISO7816.SW_DATA_INVALID); 247 | } 248 | initReadAccess = buf[(short) (tagAccess + 2)]; 249 | initWriteAccess = buf[(short) (tagAccess + 3)]; 250 | } 251 | 252 | // DATA SIZE 253 | short tagSize = UtilTLV.findTag(buf, off, len, AD_TAG_NDEF_DATA_SIZE); 254 | if (tagSize >= 0) { 255 | short sizeLen = UtilTLV.decodeLengthField(buf, (short) (tagSize + 1)); 256 | if (sizeLen != 2) { 257 | ISOException.throwIt(ISO7816.SW_DATA_INVALID); 258 | } 259 | initSize = Util.getShort(buf, (short) (tagSize + 2)); 260 | if (initSize < 0) { 261 | ISOException.throwIt(ISO7816.SW_DATA_INVALID); 262 | } 263 | } 264 | } 265 | 266 | // squash write access if not supported 267 | if(!FEATURE_WRITING) { 268 | initWriteAccess = FILE_ACCESS_NONE; 269 | } 270 | 271 | // set up access 272 | dataReadAccess = initReadAccess; 273 | dataWriteAccess = initWriteAccess; 274 | 275 | // create file contents 276 | capsFile = makeCaps(initSize, initReadAccess, initWriteAccess); 277 | dataFile = makeData(initSize, initBuf, initOff, initLen); 278 | } 279 | 280 | /** 281 | * Create and initialize the CAPABILITIES file 282 | * 283 | * @param dataSize to be allocated 284 | * @param dataReadAccess to put in the CC 285 | * @param dataWriteAccess to put in the CC 286 | * @return an array for use as the CC file 287 | */ 288 | private byte[] makeCaps(short dataSize, 289 | byte dataReadAccess, byte dataWriteAccess) { 290 | short capsLen = (short)(CC_LEN_HEADER + 2 + CC_LEN_NDEF_FILE_CONTROL); 291 | byte[] caps = new byte[capsLen]; 292 | 293 | short pos = 0; 294 | 295 | // CC length 296 | pos = Util.setShort(caps, pos, capsLen); 297 | // mapping version 298 | caps[pos++] = NDEF_MAPPING_VERSION; 299 | // maximum read size 300 | pos = Util.setShort(caps, pos, NDEF_MAX_READ); 301 | // maximum write size 302 | pos = Util.setShort(caps, pos, NDEF_MAX_WRITE); 303 | 304 | // NDEF File Control TLV 305 | caps[pos++] = CC_TAG_NDEF_FILE_CONTROL; 306 | caps[pos++] = CC_LEN_NDEF_FILE_CONTROL; 307 | // file ID 308 | pos = Util.setShort(caps, pos, FILEID_NDEF_DATA); 309 | // file size 310 | pos = Util.setShort(caps, pos, dataSize); 311 | // read access 312 | caps[pos++] = dataReadAccess; 313 | // write access 314 | caps[pos++] = dataWriteAccess; 315 | 316 | // check consistency 317 | if(pos != capsLen) { 318 | ISOException.throwIt(ISO7816.SW_UNKNOWN); 319 | } 320 | 321 | // return the file 322 | return caps; 323 | } 324 | 325 | /** 326 | * Create and initialize the DATA file 327 | * 328 | * @param dataSize to be allocated 329 | * @param init buffer containing initial data 330 | * @param initOff offset of initial data in buffer 331 | * @param initLen length of initial data in buffer 332 | * @return an array for use as the data file 333 | */ 334 | private byte[] makeData(short dataSize, byte[] init, short initOff, short initLen) { 335 | byte[] data = new byte[dataSize]; 336 | 337 | // initialize from init, if provided 338 | if (FEATURE_INSTALL_PARAMETERS) { 339 | if (init != null && initLen > 0) { 340 | // container size 341 | Util.setShort(data, (short) 0, initLen); 342 | // initial data 343 | Util.arrayCopyNonAtomic(init, initOff, data, (short) 2, initLen); 344 | } 345 | } 346 | 347 | return data; 348 | } 349 | 350 | /** 351 | * Fix up a capability container 352 | * 353 | * This will be called to fix up capabilities before 354 | * they are actually sent out to the host device. 355 | * 356 | * Currently this only fixes up the access policies 357 | * so as to hide our proprietary policies. 358 | * 359 | * @param caps buffer containing CC to fix 360 | * @param off offset of CC in buffer 361 | * @param len of CC in buffer 362 | */ 363 | private void fixCaps(byte[] caps, short off, short len) { 364 | if(FEATURE_ADVANCED_ACCESS_CONTROL) { 365 | short offNFC = (short) (off + CC_OFF_NDEF_FILE_CONTROL + 2); 366 | short offR = (short) (offNFC + FC_OFF_READ_ACCESS); 367 | short offW = (short) (offNFC + FC_OFF_WRITE_ACCESS); 368 | caps[offR] = fixAccess(dataFile, dataReadAccess); 369 | caps[offW] = fixAccess(dataFile, dataWriteAccess); 370 | } 371 | } 372 | 373 | /** 374 | * Process an APDU 375 | * 376 | * This is the outer layer of our APDU dispatch. 377 | * 378 | * It deals with the CLA and INS of the APDU, 379 | * leaving the rest to an INS-specific function. 380 | * 381 | * @param apdu to be processed 382 | * @throws ISOException on error 383 | */ 384 | public final void process(APDU apdu) throws ISOException { 385 | byte[] buffer = apdu.getBuffer(); 386 | byte ins = buffer[ISO7816.OFFSET_INS]; 387 | 388 | // handle selection of the applet 389 | if(selectingApplet()) { 390 | vars[VAR_SELECTED_FILE] = FILEID_NONE; 391 | return; 392 | } 393 | 394 | // secure messaging is not supported 395 | if(apdu.isSecureMessagingCLA()) { 396 | ISOException.throwIt(ISO7816.SW_SECURE_MESSAGING_NOT_SUPPORTED); 397 | } 398 | 399 | // process commands to the applet 400 | if(apdu.isISOInterindustryCLA()) { 401 | if (ins == INS_SELECT) { 402 | processSelect(apdu); 403 | } else if (ins == INS_READ_BINARY) { 404 | processReadBinary(apdu); 405 | } else if (ins == INS_UPDATE_BINARY) { 406 | if(FEATURE_WRITING) { 407 | processUpdateBinary(apdu); 408 | } else { 409 | ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED); 410 | } 411 | } else { 412 | ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); 413 | } 414 | } else { 415 | ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED); 416 | } 417 | } 418 | 419 | /** 420 | * Process a SELECT command 421 | * 422 | * This handles only the one case mandated by the NDEF 423 | * specification: SELECT FIRST-OR-ONLY BY-FILE-ID. 424 | * 425 | * The file ID is specified in the APDU contents. It 426 | * must be exactly two bytes long and also valid. 427 | * 428 | * @param apdu to process 429 | * @throws ISOException on error 430 | */ 431 | private void processSelect(APDU apdu) throws ISOException { 432 | byte[] buffer = apdu.getBuffer(); 433 | byte p1 = buffer[ISO7816.OFFSET_P1]; 434 | byte p2 = buffer[ISO7816.OFFSET_P2]; 435 | 436 | // we only support what the NDEF spec prescribes 437 | if(p1 != SELECT_P1_BY_FILEID || p2 != SELECT_P2_FIRST_OR_ONLY) { 438 | ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); 439 | } 440 | 441 | // receive data 442 | short lc = apdu.setIncomingAndReceive(); 443 | 444 | // check length, must be for a file ID 445 | if(lc != 2) { 446 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 447 | } 448 | 449 | // retrieve the file ID 450 | short fileId = Util.getShort(buffer, ISO7816.OFFSET_CDATA); 451 | 452 | // perform selection if the ID is valid 453 | if(fileId == FILEID_NDEF_CAPABILITIES || fileId == FILEID_NDEF_DATA) { 454 | vars[VAR_SELECTED_FILE] = fileId; 455 | } else { 456 | ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); 457 | } 458 | } 459 | 460 | /** 461 | * Process a READ BINARY command 462 | * 463 | * This supports simple reads at any offset. 464 | * 465 | * The length of the returned data is limited 466 | * by the maximum R-APDU length as well as by 467 | * the maximum read size NDEF_MAX_READ. 468 | * 469 | * @param apdu to process 470 | * @throws ISOException on error 471 | */ 472 | private void processReadBinary(APDU apdu) throws ISOException { 473 | byte[] buffer = apdu.getBuffer(); 474 | 475 | // access the file 476 | byte[] file = accessFileForRead(vars[VAR_SELECTED_FILE]); 477 | 478 | // get and check the read offset 479 | short offset = Util.getShort(buffer, ISO7816.OFFSET_P1); 480 | if(offset < 0 || offset >= file.length) { 481 | ISOException.throwIt(ISO7816.SW_WRONG_P1P2); 482 | } 483 | 484 | // determine the output size 485 | short le = apdu.setOutgoingNoChaining(); 486 | if(le > NDEF_MAX_READ) { 487 | le = NDEF_MAX_READ; 488 | } 489 | 490 | // adjust for end of file 491 | short limit = (short)(offset + le); 492 | if(limit < 0) { 493 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 494 | } 495 | if(limit >= file.length) { 496 | le = (short)(file.length - offset); 497 | } 498 | 499 | // send the requested data 500 | if(vars[VAR_SELECTED_FILE] == FILEID_NDEF_CAPABILITIES) { 501 | // send fixed capabilities 502 | Util.arrayCopyNonAtomic(file, (short)0, 503 | buffer, (short)0, 504 | (short)file.length); 505 | fixCaps(buffer, (short)0, (short)file.length); 506 | apdu.setOutgoingLength(le); 507 | apdu.sendBytesLong(buffer, offset, le); 508 | } else { 509 | // send directly 510 | apdu.setOutgoingLength(le); 511 | apdu.sendBytesLong(file, offset, le); 512 | } 513 | } 514 | 515 | /** 516 | * Process an UPDATE BINARY command 517 | * 518 | * Supports simple writes at any offset. 519 | * 520 | * The amount of data that can be written in one 521 | * operation is limited both by maximum C-APDU 522 | * length and the maximum write size NDEF_MAX_WRITE. 523 | * 524 | * @param apdu to process 525 | * @throws ISOException on error 526 | */ 527 | private void processUpdateBinary(APDU apdu) throws ISOException { 528 | byte[] buffer = apdu.getBuffer(); 529 | 530 | // access the file 531 | byte[] file = accessFileForWrite(vars[VAR_SELECTED_FILE]); 532 | 533 | // get and check the write offset 534 | short offset = Util.getShort(buffer, ISO7816.OFFSET_P1); 535 | if(offset < 0 || offset >= file.length) { 536 | ISOException.throwIt(ISO7816.SW_WRONG_P1P2); 537 | } 538 | 539 | // receive data 540 | short lc = apdu.setIncomingAndReceive(); 541 | 542 | // check the input size 543 | if(lc > NDEF_MAX_WRITE) { 544 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 545 | } 546 | 547 | // file limit checks 548 | short limit = (short)(offset + lc); 549 | if(limit < 0 || limit >= file.length) { 550 | ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); 551 | } 552 | 553 | // perform the update 554 | Util.arrayCopy(buffer, ISO7816.OFFSET_CDATA, file, offset, lc); 555 | } 556 | 557 | /** 558 | * Check if file access should be granted 559 | * 560 | * This will perform all necessary checks to determine 561 | * if an operation can currently be allowed within the 562 | * policy specified in ACCESS. 563 | * 564 | * @param access policy to be checked 565 | * @return true if access granted, false otherwise 566 | */ 567 | private boolean checkAccess(byte[] data, byte access) { 568 | if(!FEATURE_ADVANCED_ACCESS_CONTROL) { 569 | // simple access control 570 | return access == FILE_ACCESS_OPEN; 571 | } else { 572 | // get protocol and media information 573 | byte protocol = APDU.getProtocol(); 574 | byte media = (byte) (protocol & APDU.PROTOCOL_MEDIA_MASK); 575 | // make the decision 576 | switch (access) { 577 | case FILE_ACCESS_OPEN: 578 | return true; 579 | case FILE_ACCESS_PROP_CONTACT_ONLY: 580 | return media == APDU.PROTOCOL_MEDIA_DEFAULT; 581 | case FILE_ACCESS_PROP_WRITE_ONCE: 582 | return data[0] == 0 && data[1] == 0; 583 | default: 584 | case FILE_ACCESS_NONE: 585 | return false; 586 | } 587 | } 588 | } 589 | 590 | /** 591 | * Fix up an access policy to reflect current state 592 | * 593 | * This is used to squash our custom access policies 594 | * so that we do not have to present a proprietary 595 | * policy to unsuspecting host devices. 596 | * 597 | * @param data of the file for which to fix 598 | * @param access policy for to fix 599 | * @return a fixed access policy 600 | */ 601 | private byte fixAccess(byte[] data, byte access) { 602 | // figure out the right policy 603 | switch(access) { 604 | // by default we pass through 605 | default: 606 | return access; 607 | // these two require fixing 608 | case FILE_ACCESS_PROP_CONTACT_ONLY: 609 | case FILE_ACCESS_PROP_WRITE_ONCE: 610 | return (checkAccess(data, access)) 611 | ? FILE_ACCESS_OPEN : FILE_ACCESS_NONE; 612 | } 613 | } 614 | 615 | /** 616 | * Access a file for reading 617 | * 618 | * This function serves to perform precondition checks 619 | * before actually operating on a file in a read operation. 620 | * 621 | * If this function succeeds then the given fileId was 622 | * valid, security access has been granted and reading 623 | * of data for this file is possible. 624 | * 625 | * @param fileId of the file to be read 626 | * @return data array of the file 627 | * @throws ISOException on error 628 | */ 629 | private byte[] accessFileForRead(short fileId) throws ISOException { 630 | byte[] file = null; 631 | byte access = FILE_ACCESS_NONE; 632 | // select relevant data 633 | if(fileId == FILEID_NDEF_CAPABILITIES) { 634 | file = capsFile; 635 | access = FILE_ACCESS_OPEN; 636 | } 637 | if(fileId == FILEID_NDEF_DATA) { 638 | file = dataFile; 639 | access = dataReadAccess; 640 | } 641 | // check that we got anything 642 | if(file == null) { 643 | ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); 644 | } 645 | // perform access checks 646 | if(!checkAccess(file, access)) { 647 | ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); 648 | } 649 | return file; 650 | } 651 | 652 | /** 653 | * Access a file for writing 654 | * 655 | * This function serves to perform precondition checks 656 | * before actually operating on a file in a write operation. 657 | * 658 | * If this function succeeds then the given fileId was 659 | * valid, security access has been granted and writing 660 | * of data for this file is possible. 661 | * 662 | * @param fileId of the file to be written 663 | * @return data array of the file 664 | * @throws ISOException on error 665 | */ 666 | private byte[] accessFileForWrite(short fileId) throws ISOException { 667 | byte[] file = null; 668 | byte access = FILE_ACCESS_NONE; 669 | // CC can not be written 670 | if(fileId == FILEID_NDEF_CAPABILITIES) { 671 | ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED); 672 | } 673 | // select relevant data 674 | if(fileId == FILEID_NDEF_DATA) { 675 | file = dataFile; 676 | access = dataWriteAccess; 677 | } 678 | // check that we got something 679 | if(file == null) { 680 | ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); 681 | } 682 | // perform access checks 683 | if(!checkAccess(file, access)) { 684 | ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED); 685 | } 686 | return file; 687 | } 688 | 689 | } 690 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 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 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant 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 install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | 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 updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 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 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper 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 | {project} Copyright (C) {year} {fullname} 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 appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------