Webcard a Java Card web server

Webcard a Java Card web server

2023年7月23日发(作者:)

CITI Technical Report 99-3Webcard: a Java Card web serverJim ReesPeter Honeymaninfo@TRACTWebcard is a TCP/IP stack and web server written in Java that runs on a SchlumbergerCyberflex Access smartcard. In this report, we describe the architecture and implemen-tation of Webcard and the constaints and assumptions that influenced its design. We alsoinclude complete sources for the application and its supporting ber 23, 1999Center for Information Technology IntegrationUniversity of Michigan519 W. William Arbor, MI 48103-4943Webcard: a Java Card web serverJim ReesPeter Honeymaninfo@uctionThe Program for Smartcard Technology at theUniversity of Michigan’s Center for InformationTechnology Integration (CITI) is a research part-nership with Schlumberger’s Austin ProductCenter. The Program is actively engaged in re-search projects that enhance and extend the ca-pabilities of smartcards. Among CITI’s goals inthe Program, two stand out:• innovative computer security applications ofsmartcards, and• new models of interaction with this report, we describe Webcard, a webserver that is entirely contained in a commercial,off-the-shelf d accomplishes both of CITI’s objectivesin the categories of research stated d takes advantage of the inherent securityproperties of smartcards, such as tamper resis-tance and a programming interface appropriatefor security applications. While smartcards havetraditionally suffered from arcane, operatingsystem dependent applications, Webcard alsooffers a radically new mode of interacting withsmartcards, one that is enabled by any Internet-capable web cal detailsWebcard is a web server running on a

Schlumber-ger

Cyberflex Access Java Card [Cyberflex]. Thecard is programmed by the manufacturer to im-plement a Java virtual machine (JVM), recog-nizing a sizable subset of the Java programminglanguage. Specifically, Cyberflex implementsthe Java Card 2.0 specification [JavaCard]. JavaCard is intended to support multiple applicationson a single card, as described in ISO 7816-4[ISO 7816]and EMV 96 [EMV 96]. Webcard iswritten as a single Java Card application (vari-ously called applets or cardlets).The Cyberflex Access card has 16 KB ofEEPROM and about 1.2 Kbytes of RAM. Theselimited resources make it very difficult to im-plement a full, standards-compliant version ofTCP/IP [RFC 791, RFC 793]. While that is ourultimate goal, we must also accommodate thesize limitations imposed by current smartcards;we find it useful and interesting to see how muchwe can accomplish in as little space as a first step toward implementing a standardscompliant TCP/IP stack, we elected to imple-ment a minimal, functional server. Our main“robustness” criterion is to produce a server thatresponds to valid inputs and does not crash whenpresented with [RFC 1945], TCP, and IP specify manyrequirements, many of which are rarely or neverused in practice. For our first implementation,we elected to leave out those specifications thatare not required in normal operation. To deter-mine which parts of the protocol are actuallyused, we captured tcpdump traces of HTTPtransactions from several different clients againstan existing server. The assumptions describedbelow are based on the observed Connection at a TimeThe Webcard server is simplified by making theassumption that only one connection is active atany time. This allows the server to preserve statefor a single connection until a new request comesin. This also eliminates the need to time out de-funct connections and to respond to most statechange requests. However, most web browsersrun requests in parallel, so the server must notreturn pages with inline content such as should not be difficult to relax this only connection state kept by the Webcard isthe file name; TCP state, which is rememberedbut never used; and TCP port, to enforce the oneconnection restriction. Connections can be dis-carded in LRU order as new connection requestsarrive, eliminating the need for a timer, which isunavailable on the Cyberflex Access e server speaks a subset of the HTTP 1.0 pro-tocol, which is simpler and easier to implementthan HTTP 1.1 or later. Earlier versions ofHTTP, such as HTTP 0.9, are unable to commu-nicate with Webcard, but these clients are now- 1 -very rare. Modern web clients implement HTTP1.1 or later, which are required to be backwardscompatible with HTTP request is handled as an individual TCPconnection. The HTTP status line, “HTTP/1.0200 OK”, and the HTTP headers are stored in thefiles being served, so the server itself does notgenerate any headers or send any data other thanwhat is in the HTTP 1.0 GET request consists of the string“GET” followed by a single space character,followed by a server-relative URL. (Webcarddoes not support any other methods, such asHEAD, POST, or PUT.) For now, URLs areassumed to be three characters, with the last twocharacters being the file name. (ISO 7816-4 filenames are two bytes.)When the server receives a request, it selects therequested file. It does not store any other statethat reflects the identity of the requested implies that only a single HTTP connectioncan be active at any time, as described server has no configuration network connection is point-to-point, so allincoming packets are assumed to be addressed tothe server. The TCP stack simply swaps thesource and destination addresses when it con-structs a reply packet. No subnet or routing in-formation is d discards any packets not addressed tothe HTTP port (TCP port 80). Any TCP optionsare TCP state machine only has three states:LISTEN, ESTABLISHED, and FIN-WAIT-1. Itis incapable of initiating a connection, and doesnot have the corresponding SYN-SENT state. Italso does not have a CLOSED state. AlthoughWebcard keeps track of the TCP state, it makesno use of this TCP stack never retransmits. This elimi-nates the need for timers, which are unavailableanyway, and for keeping track of (most) TCPstate. We assume the TCP peer retransmits whennecessary. In practice, packets are state machine responds to four types ofpackets. A SYN elicits a SYN ACK reply andtransitions to ESTABLISHED, without waitingfor the peer to ACK the SYN. We assume thatthe SYN ACK will not be dropped and willeventually arrive. This assumption is benign: ifSYN ACK does get dropped, the peer will re-transmit the SYN, allowing connection estab-lishment to 1.0 allows only one line of text to be sentto the server; following our restrictions to HTTP1.0 described above, any packet with data is as-sumed to be a complete HTTP GET d URLs are exactly three bytes. We as-sume that the seven bytes in a GET URL requestarrive in a single, unfragmented TCP server extracts the URL from this requestand selects the given file in the ISO 7816-4 filesystem. If the file does not exist, the server se-lects a file named “nf”, which contains a “404Not Found” error message. The data packetelicits an ACK of the client's sequence number.A FIN elicits an ACK and transitions the TCPstate machine to LISTEN. HTTP clients alwayswait for the server to close the connection, sothere is no CLOSE-WAIT or LAST-ACK the client does try to close the connection pre-maturely, it will wait in vain for FIN from theWebcard and will be stuck in FIN-WAIT-2 in-definitely. Most TCP clients eventually recoverfrom ACK with no data attached elicits data fromthe currently selected file. There is no window-ing -- data is sent when the ACK for the previoussegment arrives. Webcard sequence numbersalways start at zero, so the client's ACK numbergives the offset into the d does not check the client's checksumand ignores the offered window, urgent flag andpointer, and push flag. RST packets are ng packets always offer a small fixedwindow. The actual size of this window is un-important -- we assume the client will neverwant to send more than 17 ming packets are assumed to contain no IPoptions. It would not be difficult to ignore op-tions, but in practice IP options are never IP header checksum must be done with 16bit arithmetic because the card does not imple-ment 32 bit arithmetic, but the checksum routinecan be simplified by noting that an IP header isnever long enough to overflow a 16 bit MRU (incoming MTU) is limited by theISO interface to slightly less than 256 d does not implement IP reassembly,- 2 -because the only important incoming informa-tion is the URL, which fits in the first 17 t detailsCyberflex extends Java Card in a number ofways. Cyberflex cardlets contain a main methodin addition to the Java Card methods. This al-lows them to function as standalone programs,but Webcard does not depend on this feature.A cardlet must have at least three methods, “in-stall,” “select,” and “process.” The installmethod is invoked once at the time the card isinitialized. It creates and initializes the objectsneeded by the applet. The select method is in-voked at the time the cardlet is selected, usuallyvia the “select” application protocol data unit (orAPDU). A cardlet can be set as the default forthe card, in which case that cardlet is implicitlyselected whenever the card is process method does all the work. When anAPDU is sent to the card, that APDU is passedto the process method of the currently selectedcardlet. IP packets are sent to the Webcard en-capsulated in an APDU that gets passed to theprocess reset, the Cyberflex Access default loaderwaits for an incoming APDU and passes it to theip7816 cardlet. If the APDU is an IP packet(INS=0x12), the cardlet processes the APDU;otherwise the cardlet passes the APDU back tothe default Webcard cardlet extracts the data length,destination port, and several other fields from theIP and TCP headers, then enters the TCP statemachine. It then constructs a reply packet ifneeded, optionally attaches outgoing data to it,computes TCP and IP checksums, and sends thereply packet as outgoing 7816 several points in this process the cardlet tension() to send a 7816 no-op to the card terminal. This prevents the termi-nal from timing out while the card is Webcard cardlet is about 1200 bytes of Javabyte code, leaving about 14 Kbytes of space forweb ManagementContent is loaded onto the Webcard using SCFS[Itoi], CITI’s extension to the UNIX operatingsystem, which mounts any ISO 7816-4 smartcardfile system into the UNIX file system ts can be written in any Java developmentenvironment; we tend to use standard UNIXeditors and Sun Microsystem’s JDK [JDK] forcompiling into byte code. A Cyberflex-specifictool called MakeSolo converts the class file intoa cardlet ready for downloading with anothertool from the Cyberflex developers InterfaceThe Cyberflex Access card includes an ISO7816-3 interface. We use this framing protocolinstead of implementing a more conventionalserial protocol such as SLIP or PPP. IP packetsare encapsulated in a 7816 APDU, with no addi-tional headers. The maximum size of an APDUis 256 bytes. A simple daemon running onOpenBSD (or potentially any system with a tun-nel device) forwards packets to the card. Thedaemon does not implement IP fragmentation,and truncates any packet too big to fit in anAPDU. The source code for the OpenBSD tun-nel device is included in an incoming packet results in at most one re-ply packet. Cyberflex Access supports 7816-3T=0 protocol, so the reply packet is retrieved bythe daemon with a “get response” g packets to the Webcard requires externaladvertisement of the existence of the tunnel. AtCITI, we assign the Webcard an otherwise un-used IP address from the local subnet’s addressspace and install a static route on our upstreamrouter. On the host to which the card reader isattached, we configure with the following com-mands:#configurethetunnelifconfigtun0141.211.169.2smarty#routethroughthetunnelrouteaddsmarty141.211.169.2#al CharacteristicsThe physical dimensions of Webcard correspondto ISO 7810 ID-1: 85.6 x 54 x .76 mm. Of this,roughly 10 x 12 mm is chip carrier. The chipitself is less than 25 square mm. in sionWebcard performance is less than spectacular:approximately 130 bytes per second. We believethis can be accounted for in the main by codepath through the JVM. We plan to address per-formance issues when we are satisfied withfunctionality.- 3 -We intend to extend the functionality ofWebcard in many directions, but are mostly con-cerned with providing better HTTP, TCP, and IPcompliance. Our first priority is to address“hosts requirements” such as ICMP functional-ity, which proves useful in remotely diagnosingproblems with a more functional TCP/IP stack in hand, weplan to investigate the potential of remotemethod invocations from host applications. Weare also interested in investigating IPv6 and mo-bile IP for the flexibility they offer to the highlymobile computers embedded in nces[Cyberflex]Schlumberger, Inc., “CyberflexAccess Programmer’s Guide” (1998).[EMV 96]Europay International S.A.,MasterCard International Inc., and Visa Interna-tional Service Assoc., “EMV ’96 – IntegratedCircuit Card Specification for Payment Systems”(May 1998).[ISO7816]International Organization forStandardization, “International StandardISO/IEC 7816: Integrated circuit(s) cards withcontacts.”[Itoi]N. Itoi, P. Honeyman, and J. Rees,“SCFS: A UNIX Filesystem for Smartcards,” inProc. USENIX Workshop on Smartcard Tech-nology, Chicago (May 1999).[JavaCard]Sun Microsystems, “Java Card2.0 Programming Concepts” (October 1997).[JDK]Sun Microsystems, “Java Card AppletDeveloper’s Guide” (July 1998).[RFC 791]J. Postel (ed.), “Internet Proto-col – DARPA Internet Program Protocol Speci-fication,” USC Information Sciences Institute(September 1981).[RFC 793]J. Postel (ed.), “TransmissionControl Protocol – DARPA Internet ProgramProtocol Specification,” USC Information Sci-ences Institute (September 1981).[RFC 1945] T. Berners-Lee, R. Fielding, and k, “Hypertext Transfer Protocol –HTTP/1.0,” USC Information Sciences Institute(May 1996).- 4 -Appendix: Webcard sources//Copyright(c)1999//TheRegentsofTheUniversityofMichigan//Allrightsreserved//////////////////////////////////////Permissionisgrantedtouse,copyandredistributethissoftwarefornoncommercialeducationandresearchpurposes,solongasnofeeischarged,andsolongasthecopyrightnoticeabove,thisgrantofpermission,andthedisclaimerbelowappearinallcopiesmade;andsolongasthenameofTheUniversityofMichiganisnotusedinanyadvertisingorpublicitypertainingtotheuseordistributionofthissoftwarewithoutspecific,siontomftwareisprovidedasis,withoutrepresentationastoitsfitnessforanypurpose,andwithoutwarrantyofanykind,eitherexpressorimplied,includingwithoutlimitationtheimentsofTheUniversityofMichiganshallnotbeliableforanydamages,includingspecial,indirect,incidental,orconsequentialdamages,withrespecttoanyclaimarisingoutoforinconnectionwiththeuseofthesoftware,evenifithasbeenorishereafteradvisedofthepossibilityofsuchdamages.//Contact:info@//Averysmalltork.*;ork.*;publicclassip7816extendsApplet{staticfinalbyteCMD_IP=(byte)0x12;staticstaticstaticstaticstaticstaticstaticstaticstaticfinalfinalfinalfinalfinalfinalfinalfinalfinalbytebytebytebytebytebytebytebytebyteFL_ACKFL_PSHFL_RSTFL_SYNFL_FIN=====0x10;0x8;0x4;0x2;0x1;ST_LISTEN=0;ST_ESTAB=2;ST_FW1=3;ST_FW2=4;staticfinalshortCD=_CDATA;staticfinalshortMTU=248;//Fitsina256byteapdu//////////"TCB"ult,vec[],dst[];shortid,tcb_port;//ipid,tcpportbytetcb_st;//state- 5 -privateip7816(){src=newbyte[4];dst=newbyte[4];register();}publicstaticvoidinstall(APDUapdu){newip7816();}publicbooleanselect(){id=1;tcb_st=ST_LISTEN;returntrue;}publicstaticvoidmain(Stringargs[]){t((short)0x811F);}publicvoidprocess(APDUapdu){shorti,len,port,rcvnxt0,rcvnxt1,sndnxt,offset,datlen,ck,d0,d1;bytepkt[]=fer(),fl;switch(pkt[_INS]){caseCMD_IP://IncomingIPpacketlen=omingAndReceive();if(len<40)t(_WRONG_LENGTH);//Packetmayhavebeentruncatedbyip7816d;findreallenlen=rt(pkt,(short)(CD+2));//Ifit'snothttp,justdropitif(rt(pkt,(short)(CD+22))!=80)break;//opy(pkt,(short)(CD+12),src,(short)0,(short)4);opy(pkt,(short)(CD+16),dst,(short)0,(short)4);port=rt(pkt,(short)(CD+20));//Getthesender'ssequenceandack//XXXNotethisis16-bit;wedon'thandleoverflowrcvnxt0=rt(pkt,(short)(CD+24));rcvnxt1=rt(pkt,(short)(CD+26));sndnxt=rt(pkt,(short)(CD+30));//Findthepayloadoffset=(short)(((pkt[CD+32]>>2)&0x3c)+20);datlen=(short)(len-offset);len=40;fl=FL_ACK;tension();- 6 -//Figureoutwhatkindofpacketthisis,andrespondif((pkt[CD+33]&FL_SYN)!=0){//SYNsndnxt=0;rcvnxt1++;fl|=FL_SYN;tcb_st=ST_ESTAB;}elseif(datlen>0){//incomingdatarcvnxt1+=datlen;//Gettheurl(twocharsafter"GET/")if(pkt[CD+offset+5]==0x20)//Turn"/"into"in"d0=0x696e;elsed0=rt(pkt,(short)(CD+offset+5));//selectthefileandgetitssize//iffilenotfound,try"nf"then"in"if(File(d0)!=S&&File((short)0x6e66)!=S)File((short)0x696e);len+=(short)(eSize()-16);fl|=FL_PSH;tcb_port=port;}elseif((pkt[CD+33]&FL_FIN)!=0){//FINrcvnxt1++;//Don'tbotherwithFIN-WAIT-2,TIME-WAIT,orCLOSEDtcb_st=ST_LISTEN;}elseif((pkt[CD+33]&FL_ACK)!=0){//ackwithnodataif(tcb_port==port&&sndnxt>1){//calculatenoofbyteslefttosendi=(short)(eSize()-16-(sndnxt-1));if(i==0){//EOF;sendFINfl|=FL_FIN;tcb_st=ST_FW1;}elseif(i>0){//notEOF;sendnextsegmentlen+=i;fl|=FL_PSH;}else{//ackofFIN;noreplybreak;}}elsebreak;//Noreplypacket}elsebreak;//tension();- 7 -//Sendreplypacketif(len>MTU)len=MTU;//Readnextsegmentofdataintobufferif(len>40)naryFile(pkt,(short)40,(short)(sndnxt-1),(short)(len-40));tension();for(i=0;i<40;i++)pkt[i]=0;//FillinIPheaderpkt[0]=0x45;//version,rt(pkt,(short)2,len);rt(pkt,(short)4,id);pkt[8]=60;//ttlpkt[9]=6;//opy(dst,(short)0,pkt,opy(src,(short)0,pkt,tension();//CalculateIPheaderchecksumck=d0=d1=0;for(i=0;i<20;i+=2){d0+=(short)(pkt[i]&0xff);d1+=(short)(pkt[i+1]&0xff);}//ThisworksbecauseIPheaderistooshorttooverflowhighbyteck=(short)~(((d0>>8)&0xff)+(d0<<8)+d1);pkt[10]=(byte)(ck>>8);pkt[11]=(byte)ck;tension();//FillinTCPheaderpkt[21]=80;//rt(pkt,(short)22,port);rt(pkt,(short)26,sndnxt);rt(pkt,(short)28,rcvnxt0);rt(pkt,(short)30,rcvnxt1);pkt[32]=0x50;//dataoffset=20(nooptions)pkt[33]=fl;//flagspkt[34]=0x0a;//window=2680pkt[35]=0x78;tension();//CalculateTCPchecksumck=d0=d1=0;pkt[len]=0;for(i=12;i>8)&0xff));ck=(short)~(((d0>>8)&0xff)+(d1&0xff)+((ck>>8)&0xff)+(ck<<8));pkt[36]=(byte)(ck>>8);pkt[37]=(byte)ck;//goingAndSend((short)0,len);break;}}- 9 -}Appendix: Tunnel daemon sources/*Copyright(c)1999TheRegentsofTheUniversityofMichiganAllrightsreservedPermissionisgrantedtouse,copyandredistributethissoftwarefornoncommercialeducationandresearchpurposes,solongasnofeeischarged,andsolongasthecopyrightnoticeabove,thisgrantofpermission,andthedisclaimerbelowappearinallcopiesmade;andsolongasthenameofTheUniversityofMichiganisnotusedinanyadvertisingorpublicitypertainingtotheuseordistributionofthissoftwarewithoutspecific,siontomftwareisprovidedasis,withoutrepresentationastoitsfitnessforanypurpose,andwithoutwarrantyofanykind,eitherexpressorimplied,includingwithoutlimitationtheimentsofTheUniversityofMichiganshallnotbeliableforanydamages,includingspecial,indirect,incidental,orconsequentialdamages,withrespecttoanyclaimarisingoutoforinconnectionwiththeuseofthesoftware,et:info@*//**Readpacketsfromtunneldeviceandsendthemtoasmartcard**Commandlineoptions:*-[12]serialporttouse,1isdefault*-llog(tostdout)incomingconnectionrequests*-vlog(tostdout)allapdus(butnottheircontents)*/#include#include#include#include#include"scrw.h"#defineIP_CLA0x4#defineIP_INS0x12#defineGR_INS0xc0chartunneldevname[]="/dev/tun0";intvflag,lflag;main(ac,av)intac;char*av[];{externintoptind;intscfd,ipfd,port=0,i,d0,n,af,len,r1,r2;char*s,buf[100];staticunsignedcharpkt[1504];- 10 -while((i=getopt(ac,av,"12lv"))!=-1){switch(i){case'1':case'2':port=i-'1';break;case'l':lflag=1;break;case'v':vflag=1;break;}}setlinebuf(stdout);/*openreaderandreset*/scfd=scopen(port,SCODSR,NULL);if(scfd<0){printf("can'topenreadern");exit(1);}screset(scfd,NULL,NULL);/*opentunneldevice*/if(optind1500||len!=n-4){printf("badlen%02xn",len);continue;}- 11 -if(lflag&&pkt[9]==6&&(pkt[33]&0x2))printf("SYNfrom%d.%d.%d.%dn",pkt[12],pkt[13],pkt[14],pkt[15]);if(len>80)len=80;scwrite(scfd,IP_CLA,IP_INS,0,0,len,pkt,&r1,&r2);if(vflag){s=scr1r2s(r1,r2);if(!s)s="";printf("sentpktlen%dstatus%02x.%02x%sn",len,r1,r2,s);}if(r1==0x90)/*Noreturnpacket*/continue;if(r1!=0x61){s=scr1r2s(r1,r2);if(!s)s="";printf("get_response(0)status%02x.%02x%sn",r1,r2,s);continue;}len=r2;if(len==0)continue;/*Readthereturnpacket*/n=scread(scfd,IP_CLA,GR_INS,0,0,len,pkt,&r1,&r2);if(n!=len){printf("badlenwanted%dgot%dn",len,n);len=n;}if(vflag){s=scr1r2s(r1,r2);if(!s)s="";printf("rcvdpktlen%dstatus%02x.%02x%sn",len,r1,r2,s);}/*Insertaddressfamilyandwritetotunnel*/memmove(pkt+4,pkt,len);memmove(pkt,&af,4);write(ipfd,pkt,len+4);}scclose(scfd);close(ipfd);exit(0);}- 12 -

发布者:admin,转转请注明出处:http://www.yc00.com/news/1690100390a305985.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信