Thứ Bảy, 25 tháng 10, 2008

JavaCard BK: 6 - Working with APDU

This chapter describes the techiniques of handling Application Protocol Data Units (APDU) in an applet. APDUs are data packets; they are the application-level commutication protocol between the application software ont he card and the application software on the host side. JavaCard technology provides the class javacard.frameworkd.APDU, which defines a powerfull yet simple interface to help applets handle APDUs easily. Therefore, applet developers can concentrate their efforts on processing the contents of APDU messages rather than on the details of how APDUs are constructed and transmitted.
APDU class:
The APDU class in the JavaCard APIs provides a powerfull and flexible interface for handling APDUs whose command and response structures conform to the ISO 7816-4 specification. Two transpot protocols are in primary use with smart card systems today: T=0 and T=1, the new protocol is T=CL is specified for contactless smart cards.
In the JavaCard environment, the APDU object can be viewed as a communication object. The applet do not allow to communicate directly with the application on the host. It interact with the JCRE, which in turn uses serial I/O protocol to communicate with the host. The JCRE will create APDU object that encapsulates APDU message (APDU buffer) to transmit (send request and receive response) the command.

APDU's buffer:
The minimum size of APDU buffer is 37 bytes. It's consists of 5 bytes of header and 32 default bytes is called information field size on card (IFSC). A smart card with more memory can allocate a bigger APDU buffer. The reason of the minimum size of APDU buffer is specified for TPDU T=1 (block-oriented). This buffer will handle all the received bytes, after that, it will be used as a buffer data for sending any result.

Working with APDU in Applets:
The Applet handle APDU object in the "process()" method, the content of the APDU is the command which was requested by the host. And it's all handled in APDU buffer. To retrieve the APDU buffer:
public void process(APDU apdu) {
//retrieve the APDU buffer
byte[] buffer = apdu.getBuffer();
}

This buffer is an array of bytes that holding all the CLA, INS, P1, P2, Lc and all data bytes which were sent from the host. YOur responsibility is only catch it, seperate it out and do you activities.
Note that, the JCRE requires that the reference to the APDU object or the reference to the APDU buffer CANNOT be stored in class variables, instance variables, or array components.
The structure of APDU command in APDU buffer:

take a break for dinner!!!

Thứ Tư, 22 tháng 10, 2008

JavaCard BK: 5 - JavaCard Objects & Properties

Memory Model
ROM: Read only memory. Data are burned during card manufacture.
RAM: Random access memory
EEPROM: Electrically Erasable Programmable Read Only Memory
- Data stored in RAM are lost when power lost or JCSystem.CLEAR_ON_RESET or JCSystem.CLEAR_ON_DESELECT. But Data stored in EEPROM are preserved.
- The write operations to EEPROM are typically 1000 times slower than the write operations to RAM.
- The JavaCard memory model í motivated by the kind ò memory in smart cards and their physical characteristics. A typical JavaCard system places the JCRE code (JCVM, API,..) in ROM. Applet code can also be stored in ROM. RAM is used for temporary storage. The JavaCard runtime stack is allocated in RAM, intermefdiate results, method prarameters, local variables are put on the stack. Native methods, such as those performing cryptographic computations, alse save intermediate result in RAM. Longer-lived data are stored in EEPROM, as are dawnloaded applet calsses.

Persistent Objects
- A persistent object is created by the "new" operator.
- A persistent object holds states and values across CAD sessions.
- Any update to a single field in a persistent object is atomic. If the card loses power or a failure occurs during the update, the field is restored to its previous value.
- A persistent object can be referenced by a field in a transient object. If apersistent object is not referenced by other objects, it should be removed.

Transience Objects
- A transient object is created by invoking the JavaCard APIs.
- A transient object does not hold states and values across CAD session.
- Any update to a single field in a transient object is not atomic.
- A transient object can be referenced by a field in a persistent object.
- A field in a transient object can be reference a persistent object.
- If a transient object is not referenced by other objects, it should be removed.
There are 2 type of transient objects, CLEAR_ON_RESET and CLEAR_ON_DESELECT.
- CLEAR_ON_RESET transient objects are used for maintaining data that need to be preserved acroos applet selections but not across card reset. Example "session key" field and .
- CLEAR_ON_DESELECT transient objects are used for maintaining data that must be preserved as long as an applet is selected, but not across applet selections or card resets. Example "session key" field.

Creating a transient object:
In JC tech, transient objects are created by using one of the factory methods in the JCSystem class:
public static boolean[] makeTransientBooleanArray(short length,
byte event)
throws NegativeArraySizeException,
SystemException
public static byte[] makeTransientByteArray(short length,
byte event)
throws NegativeArraySizeException,
SystemException
public static short[] makeTransientShortArray(short length,
byte event)
throws NegativeArraySizeException,
SystemException
public static Object[] makeTransientObjectArray(short length,
byte event)
throws NegativeArraySizeException,
SystemException
Example: create a transient bytes array[100] with CLEAR_ON_DESELECT type
byte[] buffer = JCSystem.makeTransientByteArray((short) 100,
JCSystem.CLEAR_ON_DESELECT);

JavaCard BK: 4 - JavaCard Virtual Machine

The JavaCard Virtual Machine (JCVM) is implemented as 2 separate pieces: "interpreter" and "converter"
The "converter" - is off-card piece - run on a PC or a workstation. The converter loads and preprocesses the class files that make up a Java package and outputs a CAP file(converted applet). The CAP file is then loaded on a Java smart card and executed by the interpreter. In addition to creating a CAP file, the converter generates an Export file representing the public APIs of the package being converted.
The "interpreter" - performs the following tasks:
• Executes bytecode instructions and ultimately executes applets
• Controls memory allocation and object creation
• Plays a crucial role in ensuring runtime security
Informally, the Java Card virtual machine is defined as the on-card piece of the virtual machine - the interpreter, in our current definition.

JavaCard Basic Knowledge: 3 - Architecture Overview

Smart cards represent one of the smallest computing platforms in use today. The greatest challenge of Java Card technology design is to fit Java system software in a smart card while conserving enough space for applications. The solution is to support only a subset of the features of the Java language and to apply a split model to implement the Java virtual machine - JavaCard virtual machine.
The Java Card virtual machine is split into two part: one that runs off-card and the other that runs on-card. Smart cards differ from desktop computers in several ways. The memory configuration of a smart card might have on the order of 1K of RAM, 16K of EEPROM, and 24K of ROM. In addition to providing Java language support, Java Card technology defines a runtime environment that supports the smart card memory, communication, security, and application execution model. The Java Card runtime environment conforms to the smart card international standard ISO 7816.
Java Card technology essentially defines a platform on which appli-
cations written in the Java programming language can run in smart cards and other
memory-constrained devices. (Applications written for the Java Card platform are
referred to as applets.) Because of the split virtual machine architecture, this plat-
form is distributed between the smart card and desktop environment in both space
and time. It consists of three parts, each defined in a specification.
• The Java Card 2.1 Virtual Machine (JCVM) Specification defines a subset of the Java programming language and virtual machine definition suitable for smart card applications.
• The Java Card 2.1 Runtime Environment (JCRE) Specification precisely describes Java Card runtime behavior, including memory management, applet management, and other runtime features.
• The Java Card 2.1 Application Programming Interface (API) Specification describes the set of core and extension Java packages and classes for programming smart card applications.

Supported and Unsupported features in JavaCard

Thứ Hai, 20 tháng 10, 2008

JavaCard Cơ bản: 2 - Qui trình phát triển một "Cardlet"

Nhúng sâu vào lý thuyết để hiểu tường tận cơ chế. Tiếp theo, mình note thêm về Qui trình phát triển ra một Cardlet (Applet từ đúng kỹ thuật là JavaCard Applet, nhưng nó trùng với Java Web Applet, nên mình thích gọi là cardlet hơn).
Mô hình dưới đây sẽ khái quát qui trình phát triển mã nguồn, thử nghiệm và kết xuất ra đầu cuối cho thiết bị của một applet:
- Step 1: Bằng bất cứ một trình soạn thảo nào bạn cũng có thể tạo ra một applet theo cấu trúc mẫu. Hoặc đơn giản hơn thì có thể dùng các IDE hỗ trợ (eclipse + jcop plugin) để tạo ra một applet bao gồm tập các file .java và dùng trình biên dịch chuẩn build thành các .class file.
- Step 2: Bằng công cụ hỗ trợ (JCOP plugin hoặc JavaCard Develop Environmen - JCDE2) để test, debug trên môi trường ảo do công cụ thiết lập.
- Step 3: Khi tiến hành build applet, bộ công cụ cũng biên tập ra các file .cap và các file .export bằng bộ Java converter. Các file .cap, .export là những tài nguyên sẽ được dùng để cài đặt trực tiếp lên các thẻ thật, thành các applet thật trên chip JavaCard. Mỗi CAP file là thể hiện của một "package" đã được tạo. Nếu cardlet có kết hợp nhiều package, thì mỗi package sẽ convert thành một .cap file và 1 .export file.
- Step 4: Sau khi đã test, debug và kiểm tra cardlet hoàn tất, xem như cardlet đã sẵn sàng để được tải lên card. Tài nguyên là các cap file và export file sẽ được dùng để tải lên card thật.

Thứ Bảy, 18 tháng 10, 2008

JavaCard Cơ bản: 1 - Vòng đời của một "Cardlet"

Kiến thức nền tảng là điều kiện cơ bản để khởi đầu, mình trở lại với lý thuyết một tí.
Theo đặc điểm kỹ thuật, vòng đời của một Applet bắt đầu từ khi "em" được đăng ký vào card với phương thức Applet.register() . JCRE (JavaCard Runtime Environment) sẽ tương tác với applet thông qua các phương thức tĩnh của applet là: install, select, deselect process.

Phương thức install():
Khai báo:
public static void install(
byte[] bArray, short bOffset
, byte bLength )
throws ISOException;
- Khi applet được cài đặt vào JC, phương thức install được thực thi một lần duy nhất cho mỗi thể hiện của applet. Các phương thức khởi dựng không nên được truy cập một cách trực tiếp mà phải thông qua phương thức install. Nhiệm vụ chính của phương thức install là tạo thể hiện của applet thông qua các constructor và đăng ký applet với JCRE thông qua phương thức register(). Chỉ khi được đăng ký thành công, JCRE mới có thể cho phép thao tác lệnh APDU với applet.

Phương thức register(..):
Khai báo:
protected final void register()throws SystemException;
protected final void register(
byte[] bArray,short bOffset
,byte bLength)throws SystemException;
- Phương thức này được dùng để đăng ký một thể hiện của ứng dụng "cardlet" với JCRE với một mã (AID) xác định. Mã AID xác định bởi một chuỗi Hexadecimal, có độ dài trong khoảng 5-11 bytes (1byte = 8bits). Mã AID này là tham số đầu vào cho lệnh Select applet. Thông thường, phương thức register() được gọi từ thân của phương thức install() để applet được đăng ký với JCRE 1 lần cho mỗi card.

Phương thức select():
Khai báo:
public boolean select();
- Phương thức select() cho phép chuyển quyền nhận lệnh cho một thể hiện của Applet. Phương thức select applet được JCRE thực thi khi JCRE nhận được lệnh SELECT FILE APDU cùng một mã Applet từ thiết bị. Việc select Applet sẽ chuyển trạng thái applet từ deselect -> select và cho phép applet nhận các lệnh từ bên ngoài thông qua phương thức process() do JCRE chuyển giao. Tuy nhiên, trước khi select Applet, JCRE sẽ tự động thực hiện hành động deselect() một (hoặc các) applet đã được select trước đó.

Phương thức process():
Khai báo:
public void process(APDU apdu) throws ISOException;
- Sau khi được select(), tất cả các lệnh APDU sẽ được JCRE chuyển cho Applet thông qua phương thước process(). Các nhân xử lý của applet sẽ được thể hiện (hoặc phân hướng xử lý) ở phương thức này. Từ đây, các thao tác dữ liệu, nhận và trả lệnh APDU được thực hiện trên vùng buffer có giới hạn đã được applet đăng ký trong hàm register().

Phương thức deselect():
Khai báo:
public void deselect();
- Phương thức được gọi thực thi bởi JCRE khi có yêu cầu hoặc khi có hành động select một Applet khác. JCRE sẽ tự động thực hiện deselect() Applet hiện tại.
- Khi có lỗi khi thực hiện deselect, JCRE sẽ tiếp nhận lỗi, và tại thời điểm đó, applet đã được deselect.

Kiến thức mình mới đọc và thử nghiệm, có thể hiểu chưa hoàn chỉnh và chính xác. Các bạn có ý kiến đóng góp cho mình chỉnh sửa nha.

Thứ Năm, 16 tháng 10, 2008

Các lỗi thường gặp khi mới bắt đầu với JavaCard - JCOP Tools

Sau một hai buổi mày mò lăn xả với , mình trở về với thân thể trầy xước tả tơi, dưới đấy là vài kinh nhiệm mình gặp phải và cách xử lý

1 - Lỗi upload ".cap" file không thành công.
Lý do:
- Build file cap không thành công, không có file .cap để upload.
Xử lý:
- Từ menu Window->Preferences..-> Java->Compiler
- Hiệu chỉnh "Compiler Complance level" -> 1.5
- Build lại project của bạn và Run.

2 - Lỗi không thể send các command.
Thông báo lỗi:
- "CLA value not supported"
- "INS value not supported"
Lý do:
- process() của bạn hiện tại không bắt, xử lý được với các mã CLA/INS lệnh theo yêu cầu.
Thông báo lỗi:
- "Conditions of use not satisfied"
Lý do: bạn phải /select applet mới có thể bắt đầu truyền các command hoặc applet chưa được xác thực (nếu có)

3 - Lỗi "No precise diagnosis"
Đây là lỗi làm "điên người" nhất mà mình tạm cho 1 lý do tạm là .. trình biên dịch JC còn củ chuối. Khi gặp lỗi này, bạn nên xóa mọi hành động vừa mới làm và bắt đầu cẩn thận lại từ bản backup gần nhất :D, nôm na ra là .. bó hand

Vài lỗi nhỏ trên là cơ bản, sẽ còn lỗi nhiều nữa, mình sẽ liệt kê thêm nếu gặp phải

Thứ Hai, 13 tháng 10, 2008

Làm thế nào để new 1 project JavaCard và build "CAP" file thành công?

Tiếp tục công cuộc mò mẫm về JavaCard. Mình bắt đầu tạo một JavaCard Project
  1. Trong menu New -> Project..
  2. Tại hộp thoại New Project, chọn mục JavaCard Project và chọn Next.
  3. Tại hộp thoại Java Card Project, điền thông tin Project Name và chọn Next.
  4. Tại đây bạn đã có thể chọn Finish. Nhưng mình thì thích đi từng bước hơn.
  5. Nếu chọn Next, bạn sẽ có thể chọn các chuẩn configuration card xác định cho loại project của mình (Java Card 2.2.1, JavaCard 2.1.1, Global Platform, ...)
  6. Chọn Next, chọn mục "Create a JavaCard Application using ...", chọn item "Basic JavaCard applet".
  7. Điền thông tin Package và Applet ClassName. Package là gói chứa đựng các Applet. Applet là gói ứng dụng sẽ được cài lên các chip xử lý.
  8. Chọn Next, điền thông tin PackageAID và AppletAID. Đây là mã xử lý của Package và Applet trên chip. Lưu ý: PackageAID và AppletAID được đặt tên dưới dạng chữ số hexadecimal. Chiều dài cho cả Package AID và AppletAID là 5 bytes. (bạn có thể đọc thêm thông tin trong tài liệu "Smart Card Handbook" để nắm vững hơn)
  9. Chọn Finish.
  10. Tới đây là bước kiểm tra bản quyền của NXP, cử sổ activate code sẽ hiện cho bạn 3 action activate: Đăng ký 1 activate code mới, sử dụng thẻ được cung cấp bới NXP để activate hoặc nhập lại 1 activate code đã được cung cấp bới NXP. Nếu không qua được bước này thì coi như quá trình tìm hiểu JavaCard, cardlet buộc phải chấm dứt.
Xong 9 bước trên vẫn chưa xong, mục đích là phải build được file có đuôi là .cap mới có thể upload vào thẻ. Dưới đây là các bước để Run/Debug project, trong quá trình Run/Debug thành công, file .cap sẽ được build và đặt ở thư mục "../bin" của project.
  1. Trong menu Run -> Open Run/Debug Dialog..
  2. Tạo mới một "JavaCard Application" và đặt các cấu hình phù hợp cho project.
  3. Chọn Run/Debug.
Kết quả trong cửa sổ JCOP Shell:
chú ý dòng : "cm> upload -b 250 .... .cap" là đường dẫn đến file cap đã được build thành công.
"cm> install -i abababab01 -q C9#() abababab00 abababab01"
-
abababab00 là tên packageAID
-
abababab01 là tên appletAID

"cm> card-info" cho thông tin card sau khi upload applet thành công.
Đến đây xem như bạn đã có thể tạo được một applet (.cap). Công việc kế tiếp sẽ còn nhiều cam go, nhưng đến đây mình cần phải dừng lại để suy ngẫm, đúc kết lại những gì mình đã làm được. Làm ly cafe nào.

Cài đặt tool JCOP 3.1. thành công

Khởi đầu một kiến thức mới về lập trình JavaCard với tool JCOP 3.1, mình muốn lưu lại từng bước thực hiện, những trở ngại gặp phải và cách giải quyết. Sau topic này sẽ là những gì mình thu thập được, có gì sai sót các bạn cho góp ý nhe.

Khởi đầu là làm sao để Cài đặt tool JCOP 3.1. thành công

Xin đặt vài dòng giới thiệu ngắn ngủi, JCOP - JavaCard OpenPlatform - khởi nguồn do IBM nghiên cứu - với tên gốc là JavaCard - là một bộ khung lập trình để phát triển cho công nghệ các loại thẻ thông minh (smart card), cho phép lập trình trên các loại thẻ có chip xử lý nhỏ mà ta đã thấy ứng dụng của chúng trong thực tế ngày nay: sim điện thoại, thẻ ngân hàng, thẻ nhân viên thông minh... Nhưng sau năm 2007, IBM ngừng đầu tư và chuyển giao công nghệ cho hãng NXP Semiconductors - một trong những tập đoàn hàng đầu thế giới về công nghệ thẻ bao gồm cả thẻ "không tiếp xúc" (contactless). Từ đó, công cụ này có tên mới là JCOP với các version phát triển 1.0, 2.1 , 3.1, 4.1... Ngày nay, công cụ này không còn được tìm thấy trên mạng, mà nó chỉ được chuyền tay qua các thành viên hoặc được cấp từ chính hãng NXP với điền kiện có đăng ký hợp đồng. Dưới đây mình sẽ liệt kê từng bước cài đặt JCOP 3.1 thành công:
Điều kiện :
- Eclipse IDE từ version 3.2 đến 3.3.1, dùng khác các version này không đảm bảo build CAP file thành công.
- JCOP plugin for Eclipse version 3.2.7 , tool này bạn phải tự tìm hoặc đăng ký với NXP Semiconductors.
Thực hiện:
- Sau khi giải nén và khởi động IDE Eclipse.
  1. Chọn menu Help > Software Updates > Find and Install
  2. Trong hộp thoại Install/Update, chọn Search for new features to install và chọn Next
  3. Chọn nút nhấn New Archived Site . . . và chỉ đường dẫn đến file n
  4. Chọn liên tiếp Open -> OK -> Finish
  5. IDE Eclipse sẽ đòi hỏi khởi động lại.
Sau khi khởi động thành công, trong mục New Project sẽ có thêm cấp project "JavaCard Project". Nếu thấy mục này, coi như bạn đã cài đặt thành công plugin JCOP for Eclipse.

Bước tiếp theo: Làm thế nào để new 1 project JavaCard và build "CAP" file thành công?.