Example #1
0
def semtec_function():
    log = getSyslog()
    log.log(' Hello semtec')
    enc = semtec.encryptor()
    enc.set_TID('325010967')
    log.log('SemtecResult=', enc.decrypt(pan='5413335519260012',
                                         expiry='5812'))
def do_testharness():
    parse_args()
    slog = getSyslog()
    fd = None
    old_term = None
    if os.name == 'posix':
        import termios
        fd = sys.stdin.fileno()
        try:
            new_term = termios.tcgetattr(fd)
            old_term = termios.tcgetattr(fd)
            new_term[3] = (new_term[3] & ~termios.ICANON & ~termios.ECHO)
            termios.tcsetattr(fd, termios.TCSAFLUSH, new_term)
        except termios.error:
            pass
    try:
        for t in __testharness_tests:
            t()
    except Exception:
        slog.save_xml_output()
        slog.logerr(traceback.format_exc())
    finally:
        slog.save_xml_output()
        if os.name == 'posix' and old_term != None:
            termios.tcsetattr(fd, termios.TCSAFLUSH, old_term)
Example #3
0
def putfile(filename, remotefilename, forceput):
    conn = Connection()
    log = getSyslog()
    req_unsolicited = conn.connect()
    if req_unsolicited:
        #Receive unsolicited
        status, buf, uns = conn.receive()
        if status != 0x9000:
            log.logerr('Unsolicited fail')
            exit(-1)
        log.log('Unsolicited', TLVParser(buf))
    progress = partial(util.display_console_progress_bar,
                       util.get_terminal_width())
    if forceput:
        fops.putfile(conn, log, filename, remotefilename, progress=progress)
    else:
        try:
            fops.updatefile(conn,
                            log,
                            filename,
                            remotefilename,
                            False,
                            progress=progress)
        except exc.invResponseException as e:
            log.logerr("Unable to use updatefile fallback to putfile")
            fops.putfile(conn,
                         log,
                         filename,
                         remotefilename,
                         progress=progress)
def OnlinePIN():
    ''' First create connection '''
    req_unsolicited = conn.connect()
    ''' If unsolicited read it'''
    #status, buf, uns = conn.receive()
    #check_status_error( status )
    ''' Send data '''
    pan = b'\x54\x13\x33\x00\x89\x00\x00\x39'
    c_tag = tagStorage()
    #BUG: Unable to push the direct string not bytearray
    c_tag.store( (0xDF, 0xEC, 0x05), 0x00 )
    c_tag.store( (0xDF, 0xED, 0x05), 0x08 )
    c_tag.store( (0xDF, 0x17), '\x00\x00\x00\x00\x01\x51' )
    c_tag.store( (0xDF, 0x24), '\x08\x26' )
    c_tag.store( (0xDF, 0x1C,), 0x02 )
    c_tag.store( (0x5A), pan )
    conn.send([0xDE, 0xD6, 0x03, 0x00] , c_tag.getTemplate(0xE0))
    
    sleep(3)

    conn.send([0xD0, 0x00, 0x00, 0x32])
    status, buf, uns = conn.receive()
    check_status_error( status )

    # Wait for last package
    status, buf, uns = conn.receive()
    slog = getSyslog()
    if status == 0x9F41:
        slog.loginfo('Status is "Cancelled amount" as expected:', hex(status))
    else:
        slog.logerr('Status is not "Cancelled amount"', hex(status), buf)
        sys.exit(-1)
Example #5
0
 def _send(self, value , tags = None, le_byte = None, log_packet = True, se=False ):
         se = True if (se and not (str(value[0])+ str(value[1])).upper() in self.ClearCommands) else False
         slog = getSyslog()
         slog.loginfo("-- SE --" + str(se))
         from testharness.exceptions import logicalException
         tlvp = TLVPrepare()
         tosend=None
         if len( value ) != 4:
                 logicalException(' Invalid header len must be equal 4')
         log_out_frame_buf = []
         tags_array = None
         le_array = bytearray()
         if le_byte != None:
             le_array = bytearray([ le_byte & 0xFF ])
         if tags == None:
                 c_pcb = 0
                 tosend=bytearray( value ) + le_array 
                 
                 if se:
                     self.__SEQ_NUM+=1
                     tosend+=self.__SEQ_NUM.to_bytes(4,'big')
                     tosend = self.tdes.encrypt( tosend )
                     c_pcb |= 2
                 w_len = len( tosend )
                 lrc = tutil.lrccalc( self.__nad, c_pcb, w_len, tosend )
                 log_out_frame_buf += self.send_raw( self.__nad, c_pcb, w_len, tosend ,lrc )
         else:
                 tags_array = tlvp.prepare_packet_from_tags(tags)
                 #Prepare length
                 tags_array[0] = 255 if (len(tags_array)-1) > 255 else len(tags_array)-1
                 tags_array = bytearray( value ) + tags_array
                 tags_array += le_array
                 if se:
                     self.__SEQ_NUM+=1
                     tags_array+=self.__SEQ_NUM.to_bytes(4,'big')
                     tags_array=self.tdes.encrypt( tags_array )
                 w_len = len( tags_array )
                 #Send long or short packets depends on the chained msgs enabled
                 if w_len > self.__MAX_PACKET_PROTO_LEN and not self.__chained_tx_messages:
                         raise logicalException('Packet too long > 254 and chained msgs not enabled')
                 if w_len <= self.__MAX_PACKET_PROTO_LEN:
                         c_pcb = 2 if se else 0
                         lrc = tutil.lrccalc( self.__nad, c_pcb, w_len, tags_array )
                         log_out_frame_buf += self.send_raw( self.__nad, c_pcb, w_len ,tags_array ,lrc )            
                 else:
                         total_len = w_len
                         for p in range(0,total_len, self.__MAX_PACKET_PROTO_LEN):
                                 raw_data = tags_array[p:(p+self.__MAX_PACKET_PROTO_LEN) ]
                                 c_pcb = 2 if se else 0
                                 c_pcb |= 1 if len(raw_data)==self.__MAX_PACKET_PROTO_LEN else 0
                                 raw_len = len(raw_data)
                                 lrc = tutil.lrccalc( self.__nad, c_pcb, raw_len, raw_data )
                                 log_out_frame_buf += self.send_raw( self.__nad, c_pcb, raw_len, raw_data ,lrc )
         if not se and log_packet:
             self.log_message('send', tags_array , log_out_frame_buf, tags, value)
         elif log_packet:
             if tags == None:
                 self.log_message('send', tags_array, [ self.tdes.decrypt( tosend) ], tags, value )
             else:
                 self.log_message('send', tags_array, [ self.tdes.decrypt( tags_array ) ], tags, value )
def transtest_function():
	log = getSyslog()
	conn = connection.Connection();
	prev_nad = conn.setnad(2)
	#Create ssl server
	#conn.connect_serial('COM1', 57600, timeout=2 );
	req_unsolicited = conn.connect()
	if req_unsolicited:
		#Receive unsolicited
		status, buf, uns = conn.receive()
		if status != 0x9000:
			log.logerr('Unsolicited fail')
			exit(-1)
		log.log('Unsolicited', TLVParser(buf) )
		
	#Send INIT contactless
	conn.send([0xc0, 0x01, 0x00, 0x00])
	status, buf, uns = conn.receive()
	if status != 0x9000:
		log.logerr('ctls init fail')
		exit(-1)


	# Now wait for the user to send CLOSE
	input("[ENTER] to send 'close'")

	#Send CLOSE contactless
	conn.send([0xc0, 0x02, 0x00, 0x00])
	status, buf, uns = conn.receive()
	if status != 0x9000:
		log.logerr('ctls close fail')
		exit(-1)
Example #7
0
def execute_script(filename):
    global __SCRIPT_ROOT
    __SCRIPT_ROOT = os.path.dirname(os.path.abspath(filename))
    th_ast_parser = __create_ast_th_language_syntax()
    ast = th_ast_parser.parseFile(filename, True)
    log = getSyslog()
    conn = connection.Connection()
    req_unsolicited = conn.connect()
    abort_sw1sw2 = True
    pool = tagStorage()
    localtempl = {}
    if req_unsolicited:
        #Receive unsolicited
        status, buf, uns = conn.receive()
        if status != 0x9000:
            raise exc.invResponseException('Unsolicited message fail', status)
        log.log('Unsolicited', TLVParser(buf))
    for toks in ast:
        if toks[0] == 'setnad':
            conn.setnad(toks[1])
            log.loginfo('Set NAD to', toks[1])
        elif toks[0] == '#':
            log.loginfo("Comment:", str(toks[1]).strip())
        elif toks[0] == 'setdevice':
            log.loginfo('Set device to', toks[1])
        elif toks[0] == 'flush':
            log.loginfo('Flush comms')
        elif toks[0] == 'clearlocalpool':
            pool.clear()
            localtempl.clear()
            log.loginfo('Clear local pool')
        elif toks[0] == 'pause':
            log.loginfo('Pause for', toks[1], 'sec')
            time.sleep(toks[1])
        elif toks[0] == 'send':
            __send_command(toks, conn, pool, localtempl, log)
        elif toks[0] == 'abortsw1sw2':
            abort_sw1sw2 = toks[1]
            log.loginfo('Abort SW1SW2 =', abort_sw1sw2)
        elif toks[0] == 'wait':
            __wait_command(toks, conn, log, abort_sw1sw2)
        elif toks[0] == 'prompt':
            log.loginfo('Prompt message:', str(" ").join(toks[1].asList()))
            __wait_command(toks, conn, log, abort_sw1sw2)
        elif toks[0] == 'storelocaltag':
            pool = __storetag_command(toks, pool)
        elif toks[0] == 'appendlocal':
            tpl, data = __appendlocal_command(toks, pool)
            localtempl[tpl] = data
        elif toks[0] == 'senddirect':
            __senddirect_command(toks, conn, log)
        elif toks[0] == 'putfile':
            __putfile_command(toks, conn, log)
        elif toks[0] == 'updatefile':
            __updatefile_command(toks, conn, log)
        elif toks[0] == 'getfile':
            __getfile_command(toks, conn, log)
        else:
            log.logerr('Unknown tokens', str(toks))
            raise exc.logicalException('Unknown tokens in script')
def check_status_error(receive_tpl):
    slog = getSyslog()
    if type(receive_tpl) == int:
        status = receive_tpl
        buf = None
    else:
        status, buf, uns = receive_tpl
    if status != 0x9000:
        slog.logerr('Check status failed', hex(status), buf)
        sys.exit(-1)
def checkfile( filename ):
    conn = Connection()
    log = getSyslog()
    req_unsolicited = conn.connect()
    if req_unsolicited:
        #Receive unsolicited
        status, buf, uns = conn.receive()
        if status != 0x9000:
            log.logerr('Unsolicited fail')
            exit(-1)
        log.log('Unsolicited', TLVParser(buf) )
    progress = partial( util.display_console_progress_bar, util.get_terminal_width() )
    openfile( conn, log, filename, progress )
Example #10
0
 def connect(self): 
     slog = getSyslog()
     #Create argument list
     result = tutil.parse_args()
     if 'sslkey' in vars(result): ssl_protocol = True
     else: ssl_protocol = None
     SSLVERIFY = { 'none': ssl.CERT_NONE, 'optional' : ssl.CERT_OPTIONAL, 'required' : ssl.CERT_REQUIRED }
     ctimeout = result.timeout
     if type(ctimeout)==int and ctimeout < 1: ctimeout=1
     sslverify = isslverify=SSLVERIFY[result.sslverify] if 'sslverify' in vars(result) else None
     sslca = result.sslca if 'sslca' in vars(result) else None
     sslcert = result.sslcert if 'sslcert' in vars(result) else None
     sslkey = result.sslkey if 'sslkey' in vars(result) else None
     sslpasswd = result.sslpasswd if 'sslpasswd' in vars(result) else None
     # Information about certificate
     if result.se_whitelist:
         self.ClearCommands=result.se_whitelist.split(',')
     if result.seq_num:
         self.__SEQ_NUM = int(result.seq_num)
     if result.se_cert == None:
         self.send = self.send_standard
         self.receive = self.receive_standard
     else:
         self.send = self.send_se
         self.receive = self.receive_se
         self.tdes=pyDes.triple_des(open(result.se_cert, 'rb').read(), pyDes.CBC, b"\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5)
     if result.serial_port!=None and ssl_protocol:
         slog.log('SSL mode CA:', sslca, 'KEYFILE:', sslkey,
                 'CERT:', sslcert, 'VERIFY:', result.sslverify,
                 'CERTPASS:'******'Yes' if result.sslpasswd else 'No' )
     #Parse results and apply class member
     if result.tcp_server!=None:
         slog.log("Argument parse TCP server mode listen on port", int(result.tcp_server))
         self.connect_tcp_server( port = int(result.tcp_server), timeout = ctimeout,
                 ssl_protocol=ssl_protocol, verify_mode=sslverify, ca_cert=sslca,
                 certfile=sslcert, keyfile=sslkey, cert_pass = sslpasswd )
     elif result.tcp_client!=None:
         hostport= result.tcp_client.split(':')
         slog.log("Argument parse TCP client mode trying to connect to", result.tcp_client)
         self.connect_tcp_client(hostport[0], int(hostport[1]) ,ssl_protocol, ctimeout,
                 sslverify, sslca, sslcert, sslkey, sslpasswd )
     else:
         portspeed = result.serial_port.split(':')
         if len( portspeed )==1:  portspeed.append('57600')
         slog.log("Argument parse SERIAL mode connecting to", result.serial_port,
             ", flow control:", result.flow_ctrl)
         self.connect_serial(portspeed[0], int(portspeed[1]), timeout=ctimeout,
             use_rtscts = (result.flow_ctrl == 'rts-cts'),
             use_xonxoff = (result.flow_ctrl == 'xon-xoff'))
     return self.in_waiting(10) > self.__HEADER_PROTO_LEN
def delfile(file):
    conn = Connection()
    log = getSyslog()
    req_unsolicited = conn.connect()
    if req_unsolicited:
        #Receive unsolicited
        status, buf, uns = conn.receive()
        if status != 0x9000:
            log.logerr('Unsolicited fail')
            exit(-1)
        log.log('Unsolicited', TLVParser(buf) )
    
    conn.send([0x00, 0xAB, 0x00, 0x00], file)
    sw12 = conn.receive()[0]
    if sw12 != 0x9000: exit(sw12)
Example #12
0
def transtest_function():
    log = getSyslog()
    conn = connection.Connection()
    #Create ssl server
    #conn.connect_serial('COM1', 57600, timeout=2 );
    req_unsolicited = conn.connect()
    if req_unsolicited:
        #Receive unsolicited
        status, buf, uns = conn.receive()
        if status != 0x9000:
            log.logerr('Unsolicited fail')
            exit(-1)
        log.log('Unsolicited', TLVParser(buf))
    #Send INIT contactless
    conn.send([0xc0, 0x01, 0x00, 0x00])
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('ctls init fail')
        exit(-1)

    #Create localtag for transaction
    start_trans_tag = [[(0x9F, 0x02), b'\x00\x00\x00\x00\x04\x56'],
                       [(0x9C), b'\x00'], [(0x5F, 0x2A), b'\x08\x26'],
                       [(0x9F, 0x1A), b'\x08\x26']]
    start_templ = (0xe0, start_trans_tag)
    print(start_templ)
    #Start transaction
    conn.send([0xc0, 0xa0, 0x01, 0x20], start_templ)
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Start transaction fail', hex(status), buf)
        exit(-1)

    # Now wait for the user to CANCEL
    input("ENTER to CANCEL")

    conn.send([0xc0, 0xc0, 0x00, 0x00])
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('cancel fail!')
        exit(-1)

    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('start txn fail!')
        exit(-1)
Example #13
0
 def connect_tcp_client(self, host, port=16107,ssl_protocol = None, timeout = None, verify_mode = ssl.CERT_OPTIONAL,
                        ca_cert = None, certfile = None, keyfile =None, cert_pass = None ):
     slog = getSyslog()
     s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
     if ssl_protocol == True:
         raw_sock = ssl.wrap_socket(s, keyfile=keyfile, certfile=certfile, cert_reqs=verify_mode, ca_certs = ca_cert)
         raw_sock.settimeout(10)
         self.ssl = True
     else: raw_sock = s
     raw_sock.connect((host,port))
     if ssl_protocol != None: slog.logsys('Server cert is',raw_sock.getpeercert()) 
     slog.logsys('Connected to', host, port  )
     if timeout != None: raw_sock.settimeout(timeout)
     else: raw_sock.settimeout(None)
     self.__connection = socket.SocketIO( raw_sock, "rwb")
     self.__raw_socket = raw_sock
     self.__timeout = timeout
Example #14
0
 def connect_tcp_server(self, interface='0.0.0.0', port=16107, timeout = None, ssl_protocol = None,
                          verify_mode = ssl.CERT_OPTIONAL, ca_cert = None, certfile = None, 
                          keyfile =None, cert_pass = None):
     slog = getSyslog()
     listen_s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
     listen_s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     listen_s.bind((interface,port))
     listen_s.listen(1)
     slog.logsys('Waiting for connections');
     s, addr = listen_s.accept()
     if ssl_protocol == True:
         raw_sock = ssl.wrap_socket(s, keyfile=keyfile, certfile=certfile, cert_reqs=verify_mode, ca_certs = ca_cert, server_side=True)
         raw_sock.settimeout(10)
         self.ssl = True
     else: raw_sock = s
     if timeout != None: raw_sock.settimeout( timeout )
     else: raw_sock.settimeout( None )
     slog.logsys("Connected from", addr )
     if ssl_protocol == True:
         cert = raw_sock.getpeercert()
         slog.logsys('Peer cert', cert)
     self.__connection = socket.SocketIO( raw_sock, "rwb")
     self.__raw_socket = raw_sock
     self.__timeout = timeout
from testharness.utility import check_status_error
from binascii import hexlify, unhexlify
''' How to create example scripts '''


def demo_function():
    ''' First create connection '''
    req_unsolicited = conn.connect()
    ''' If unsolicited read it'''
    if req_unsolicited:
        status, buf, uns = conn.receive()
        check_status_error(status)
    ''' Reset display '''
    conn.send([0xD2, 0x01, 0x01, 0x00])
    status, buf, uns = conn.receive()
    check_status_error(status)
    ''' Send data '''
    conn.send_rawhex(
        '010036DD210100B2E0B0DF831308D202964900000000DF831A203030203030203030203030203030203030203030203030203030203030203036'
    )
    ''' Check for status '''
    status, buf, uns = conn.receive()
    check_status_error(status)


if __name__ == '__main__':
    log = getSyslog()
    conn = connection.Connection()
    utility.register_testharness_script(demo_function)
    utility.do_testharness()
def transtest_function():
    log = getSyslog()
    conn = connection.Connection()

    #
    # !!! NOTE: Now you can set connection parameters from command line!
    #
    #Create ssl server
    #conn.connect_serial('COM1', 57600, timeout=2 );

    req_unsolicited = conn.connect()
    if req_unsolicited:
        #Receive unsolicited
        status, buf, uns = conn.receive()
        if status != 0x9000:
            log.logerr('Unsolicited fail')
            exit(-1)
        log.log('Unsolicited', TLVParser(buf))

    #Send INIT contactless
    conn.send([0xc0, 0x01, 0x00, 0x00])
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('ctls init fail')
        exit(-1)

    #####################################################
    # Get handle
    conn.send([0xc0, 0xf8, 0x01, 0x00])
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Get handle fail', hex(status), buf)
        exit(-1)

    tlv = TLVParser(buf)
    cicappHandle = tlv.getTag((0xdf, 0xc0, 0x01), TLVParser.CONVERT_INT)[0]
    log.log('Handle=', hex(cicappHandle))

    #####################################################
    # Force proxy mode
    conn.send([0xc0, 0xf8, 0x02, 0x01])
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Control proxy mode fail', hex(status), buf)
        exit(-1)

    #####################################################
    # Send 'PassThruEnable'
    passThruCtlTags = [
        [(0xdf, 0xc0, 0x01), [cicappHandle]],
        [(0xdf, 0x1f), [0x30]],  # POS timeout
        [(0xdf, 0xc0, 0x40), [0x01]]
    ]
    SendPassThruPacket(conn, 220, passThruCtlTags)
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Send pass-thru fail', hex(status), buf)
        exit(-1)

    #####################################################
    # Send 'ControlUI'
    log.log('Enable LEDs')

    controlUI = [
        [(0xdf, 0xc0, 0x01), [cicappHandle]],
        [(0xdf, 0x1f), [0x30]],  # POS timeout
        [(0xdf, 0xc0, 0x18), [0xff]],  # All LED's on
        [(0xdf, 0x0c), [0x01]]  # Buzzer - success/single beep
    ]

    # 222=ControlUI
    SendPassThruPacket(conn, 222, controlUI)
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Send pass-thru fail', hex(status), buf)
        exit(-1)

    time.sleep(1)

    #####################################################
    # Send 'ControlUI'
    log.log('Change LEDs')

    controlUI = [
        [(0xdf, 0xc0, 0x01), [cicappHandle]],
        [(0xdf, 0x1f), [0x30]],  # POS timeout
        [(0xdf, 0xc0, 0x18), [0x04]]  # 3rd LED on
    ]

    # 222=ControlUI
    SendPassThruPacket(conn, 222, controlUI)
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Send pass-thru fail', hex(status), buf)
        exit(-1)

    time.sleep(1)

    #####################################################
    # Send 'ControlUI'
    log.log('Change LEDs')

    controlUI = [
        [(0xdf, 0xc0, 0x01), [cicappHandle]],
        [(0xdf, 0x1f), [0x30]],  # POS timeout
        [(0xdf, 0xc0, 0x18), [0x0a]],  # 2nd & 4th LED on
        [(0xdf, 0x0c), [0x02]]  # Buzzer - error/double beep
    ]

    # 222=ControlUI
    SendPassThruPacket(conn, 222, controlUI)
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Send pass-thru fail', hex(status), buf)
        exit(-1)

    time.sleep(1)

    #####################################################
    # Send 'ControlUI'
    log.log('Disable LEDs')

    controlUI = [
        [(0xdf, 0xc0, 0x01), [cicappHandle]],
        [(0xdf, 0x1f), [0x30]],  # POS timeout
        [(0xdf, 0xc0, 0x18), [0x00]]  # All LED's off
    ]

    # 222=ControlUI
    SendPassThruPacket(conn, 222, controlUI)
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Send pass-thru fail', hex(status), buf)
        exit(-1)
from testharness import syslog
tags = [[(0xDF, 0xA2, 0x22), 'CHI'], [(0xDF, 0xA2, 0x23), [0x10, 0x20, 0x30]],
        [(0xDF, 0xA2, 0x24), b'\x05\x10\x15']]

data1 = [0xD1, 0xD2, 0xD3, 0xD4, 0xD5]
data2 = "dupajas1"

template1 = ((0xE0), tags)
template2 = ((0xE1), tags)

long_tag = [[(
    0xDF, 0xC0, 0x01
), b'0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789'
             ]]

slog = syslog.getSyslog()
slog.logerr('Error log', 1, 2, 3)
slog.log('Normal log')
exit(0)

conn = connection.Connection()
#conn.connect_serial('COM5', 57600, timeout=2 );
#conn.connect_tcp_server(timeout=15)
#conn.connect_tcp_client('192.168.16.120', ssl_protocol=True,
#                       ca_cert='c:/pc/testharness/certs/ca.pem',
#                        timeout = 10)
#conn.send_raw( unhexlify(b'010004D2D0000007') );
#conn.send_rawhex('010004D2D0000007');
#conn.send_raw( [0x01, 0x00, 0x04, 0xD2, 0xD0, 0x00, 0x00, 0x07] );
#status0, buf0 = conn.receive()
#print( buf0 )
Example #18
0
def transtest_function():
	log = getSyslog()
	conn = connection.Connection();
	
	#
	# !!! NOTE: Now you can set connection parameters from command line!
	#
	#Create ssl server
	#conn.connect_serial('COM1', 57600, timeout=2 );
	
	req_unsolicited = conn.connect()
	if req_unsolicited:
		#Receive unsolicited
		status, buf, uns = conn.receive()
		if status != 0x9000:
			log.logerr('Unsolicited fail')
			exit(-1)
		log.log('Unsolicited', TLVParser(buf) )

	#Send INIT contactless
	conn.send([0xc0, 0x01, 0x00, 0x00])
	status, buf, uns = conn.receive()
	if status != 0x9000:
		log.logerr('ctls init fail')
		exit(-1)


	#####################################################
	# Get handle
	conn.send([0xc0, 0xf8, 0x01, 0x00])
	status, buf, uns = conn.receive()
	if status != 0x9000:
		log.logerr('Get handle fail', hex(status), buf)
		exit(-1)

	tlv = TLVParser(buf)
	cicappHandle = tlv.getTag((0xdf,0xc0,0x01), TLVParser.CONVERT_INT)[0]
	log.log('Handle=', hex(cicappHandle))

	#####################################################
	# Force proxy mode
	conn.send([0xc0, 0xf8, 0x02, 0x01])
	status, buf, uns = conn.receive()
	if status != 0x9000:
		log.logerr('Control proxy mode fail', hex(status), buf)
		exit(-1)


	#####################################################
	# Send 'PassThruEnable'
	passThruCtlTags = [
		[ (0xdf, 0xc0, 0x01), [cicappHandle] ],
		[ (0xdf, 0x1f), [0x30] ],		# POS timeout
		[ (0xdf, 0xc0, 0x40), [0x01] ]
	]
	SendPassThruPacket(conn, 220, passThruCtlTags)
	status, buf, uns = conn.receive()
	if status != 0x9000:
		log.logerr('Send pass-thru fail', hex(status), buf)
		exit(-1)


	#####################################################
	# Send 'WaitForCard'
	waitForCardTags = [
		[ (0xdf, 0xc0, 0x01), [cicappHandle] ],
		[ (0xdf, 0x1f), [0x30] ]		# POS timeout
	]

	SendPassThruPacket(conn, 221, waitForCardTags)
	status, buf, uns = conn.receive()
	if status != 0x9000:
		log.logerr('Send pass-thru fail', hex(status), buf)
		exit(-1)
	
	
	# Wait for unsolicited message
	status, buf, uns = conn.receive()
	if status != 0x9000:
		log.logerr('Wait for card fail!')
		exit(-1)
	

	#####################################################
	# Send 'HighLevelPassThru' ('MIFARE Authenticate')
	innerTags = [
		[ (0xdf, 0xc0, 0x5a), [0x00] ],	# Sector number
		[ (0xdf, 0xc0, 0x5b), [0x01] ],	# Key A (01)
		[ (0xdf, 0xc0, 0x5c), [0xff, 0xff, 0xff, 0xff, 0xff, 0xff ] ]	# Key value
	]
	
	hlPassThruTags = [
		[ (0xdf, 0xc0, 0x01), [cicappHandle] ],
		[ (0xdf, 0x1f), [0x30] ],		# POS timeout
		[ (0xdf, 0xc0, 0x58), [0x00, 0x01] ],		# Subcommand: MIFARE Authenticate
		[ (0xdf, 0xc0, 0x59), Tags2Array(innerTags) ]		# Subcommand data
	]

	SendPassThruPacket(conn, 224, hlPassThruTags)
	status, buf, uns = conn.receive()
	if status != 0x9000:
		log.logerr('Send pass-thru fail', hex(status), buf)
		exit(-1)



	#####################################################
	# Send 'HighLevelPassThru' ('MIFARE Read')
	innerTags = [
		[ (0xdf, 0xc0, 0x5e), [0x01] ],	# Block count
		[ (0xdf, 0xc0, 0x5d), [0x02] ]	# Start block
	]
	
	hlPassThruTags = [
		[ (0xdf, 0xc0, 0x01), [cicappHandle] ],
		[ (0xdf, 0x1f), [0x30] ],		# POS timeout
		[ (0xdf, 0xc0, 0x58), [0x00, 0x02] ],		# Subcommand: MIFARE Read
		[ (0xdf, 0xc0, 0x59), Tags2Array(innerTags) ]		# Subcommand data
	]

	SendPassThruPacket(conn, 224, hlPassThruTags)
	status, buf, uns = conn.receive()
	if status != 0x9000:
		log.logerr('Send pass-thru fail', hex(status), buf)
		exit(-1)


	#####################################################
	# Send 'HighLevelPassThru' ('MIFARE Write')
	innerTags = [
		[ (0xdf, 0xc0, 0x5e), [0x01] ],	# Block count
		[ (0xdf, 0xc0, 0x5d), [0x02] ],	# Start block
		[ (0xdf, 0xc0, 0x5f), binascii.unhexlify(b'0123456789abcdef0f1e2d3c4b5a6978') ]	# Data 16 bytes!
	]
	
	hlPassThruTags = [
		[ (0xdf, 0xc0, 0x01), [cicappHandle] ],
		[ (0xdf, 0x1f), [0x30] ],		# POS timeout
		[ (0xdf, 0xc0, 0x58), [0x00, 0x03] ],		# Subcommand: MIFARE Write
		[ (0xdf, 0xc0, 0x59), Tags2Array(innerTags) ]		# Subcommand data
	]

	SendPassThruPacket(conn, 224, hlPassThruTags)
	status, buf, uns = conn.receive()
	if status != 0x9000:
		log.logerr('Send pass-thru fail', hex(status), buf)
		exit(-1)


	#####################################################
	# Send 'HighLevelPassThru' ('MIFARE Read')
	innerTags = [
		[ (0xdf, 0xc0, 0x5e), [0x01] ],	# Block count
		[ (0xdf, 0xc0, 0x5d), [0x02] ]	# Start block
	]
	
	hlPassThruTags = [
		[ (0xdf, 0xc0, 0x01), [cicappHandle] ],
		[ (0xdf, 0x1f), [0x30] ],		# POS timeout
		[ (0xdf, 0xc0, 0x58), [0x00, 0x02] ],		# Subcommand: MIFARE Read
		[ (0xdf, 0xc0, 0x59), Tags2Array(innerTags) ]		# Subcommand data
	]

	SendPassThruPacket(conn, 224, hlPassThruTags)
	status, buf, uns = conn.receive()
	if status != 0x9000:
		log.logerr('Send pass-thru fail', hex(status), buf)
		exit(-1)
Example #19
0
 def __receive( self, parse, timeout, log_packet, se=False ):
         if timeout == None:
             timeout = self.__timeout
             req_set = False
         else:
             req_set = True
         if timeout !=None and timeout > 0 and req_set == True:
             if self.__raw_socket != None:
                 self.__raw_socket.settimeout( timeout )
             else:
                 self.__connection.setTimeout( timeout )
         from testharness.exceptions import logicalException
         data_frame = bytearray()
         is_unsolicited = None
         log_out_frame_buf = []
         while True:
                 rxbuf = bytearray()
                 while True:
                         read_value = self.__connection.read( 3 )
                         if timeout!=None and timeout > 0 and len( read_value )==0:
                             raise timeoutException()
                         rxbuf += read_value
                         if len(rxbuf) < 3: continue
                         nad =  rxbuf[0]
                         pcb =  rxbuf[1]
                         blen = rxbuf[2]
                         if is_unsolicited==None: is_unsolicited = True if pcb&0x40 else False
                         break
                 rxbuf = bytearray()
                 while True:
                         read_value = self.__connection.read( blen )
                         if timeout!=None and timeout > 0 and len( read_value )==0:
                             raise timeoutException()
                         rxbuf += read_value
                         if len(rxbuf) >= blen: break
                 while True:
                         lrc = self.__connection.read( 1 )
                         if timeout!=None and timeout > 0 and len( lrc )==0:
                             raise timeoutException()
                         if len( lrc ) >= 1: break
                 calc_lrc = tutil.lrccalc( nad, pcb, blen, rxbuf, lrc )
                 if calc_lrc != 0 and nad == self.__nad:
                         raise logicalException('Invalid LRC')
                 if nad != self.__nad:
                         rxbuf = bytearray()
                         continue
                 data_frame += rxbuf
                 log_out_frame_buf += [ bytearray( [nad] ) +  bytearray( [pcb] ) +  bytearray( [blen] ) + data_frame + lrc ]
                 if pcb&1 == 0: break 
         from struct import unpack
         from binascii import hexlify
         tags=None
         slog = getSyslog()
         if se and ( pcb & 2):
             data_frame = bytearray(self.tdes.decrypt( data_frame ) )
             slog.log("Received seq num: ",str(hexlify(  data_frame[ len(data_frame) - 4: ] )))
             # if se take response except last 4 bytes
             data_frame = data_frame[:-4]
         slog.loginfo("IN: " + str(hexlify(data_frame)))
         if parse:
             tlvp = TLVPrepare()
             tags = tlvp.parse_received_data( data_frame )
         else:
             tags = data_frame[:-2]
         b_status = unpack("!H",data_frame[-2:])[0] 
         if log_packet:
             self.log_message('recv', data_frame[:-2] , log_out_frame_buf, tags, b_status)
         return b_status, tags , is_unsolicited
def transtest_function():
    log = getSyslog()
    conn = connection.Connection()

    #
    # !!! NOTE: Now you can set connection parameters from command line!
    #
    #Create ssl server
    #conn.connect_serial('COM1', 57600, timeout=2 );

    req_unsolicited = conn.connect()
    if req_unsolicited:
        #Receive unsolicited
        status, buf, uns = conn.receive()
        if status != 0x9000:
            log.logerr('Unsolicited fail')
            exit(-1)
        log.log('Unsolicited', TLVParser(buf))

    #Send INIT contactless
    conn.send([0xc0, 0x01, 0x00, 0x00])
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('ctls init fail')
        exit(-1)

    #####################################################
    # Get handle
    conn.send([0xc0, 0xf8, 0x01, 0x00])
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Get handle fail', hex(status), buf)
        exit(-1)

    tlv = TLVParser(buf)
    cicappHandle = tlv.getTag((0xdf, 0xc0, 0x01), TLVParser.CONVERT_INT)[0]
    log.log('Handle=', hex(cicappHandle))

    #####################################################
    # Force proxy mode
    log.log('Force MAPP ctls proxy mode')
    conn.send([0xc0, 0xf8, 0x02, 0x01])
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Control proxy mode fail', hex(status), buf)
        exit(-1)

    #####################################################
    # Send 'StartTxn' with MIFARE poll
    log.log('Sending StartTxn with MIFARE polling on')
    innerTags = [[(0x9F, 0x02), b'\x00\x00\x00\x00\x04\x56'], [(0x9C),
                                                               b'\x00'],
                 [(0x5F, 0x2A), b'\x08\x26'], [(0x9F, 0x1A), b'\x08\x26']]

    passThruCtlTags = [
        [(0xdf, 0xc0, 0x01), [cicappHandle]],
        [(0xdf, 0x1f), [0x05]],  # POS timeout
        [(0xdf, 0xc0, 0x30), Tags2Array(innerTags)],  # Transaction data
        [(0xdf, 0xc0, 0x31), [0x01]],  # Transaction result request
        [(0xdf, 0xc0, 0x3d), [0x01]]  # TransactionSelectionMask: PollForMIFARE
    ]

    # 203 = StartTransaction
    SendPassThruPacket(conn, 203, passThruCtlTags)
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Send pass-thru fail', hex(status), buf)
        exit(-1)

    log.log("Waiting for card tap")

    # Wait for unsolicited message
    transactionOutcome = -1
    while True:
        status, buf, uns = conn.receive()
        if status != 0x9000:
            log.logerr('Wait for card fail!')
            exit(-1)

        # Check the buffer for transaction outcome
        log.log('type(buf)=', type(buf))
        log.log('buf=', buf)
        tlv = TLVParser(buf)
        print('tlv=', tlv)

        rawCICAPPFrame = tlv.getTag((0xdf, 0xc0, 0x59))
        if len(rawCICAPPFrame) == 0:
            log.logerr('Unexpected frame received')
        else:
            # FULL CICAPP frame received
            frameData = rawCICAPPFrame[0]
            cmdCode = frameData.pop(0)
            log.log('Received response for command', hex(cmdCode), "=",
                    cmdCode)

            tlv = TLVParser(Array2Tags(frameData))
            print('tlv=', tlv)
            transactionOutcome = tlv.getTag((0xdf, 0xc0, 0x36),
                                            TLVParser.CONVERT_INT)
            if (len(transactionOutcome) > 0):
                transactionOutcome = transactionOutcome[0]
                log.log('TransactionOutcome=', transactionOutcome)
                break

            resultCode = tlv.getTag((0xdf, 0x30), TLVParser.CONVERT_INT)
            print('resultCodeLen=', len(resultCode))
            if (len(resultCode) > 0):
                resultCode = resultCode[0]
                log.log('resultCode=', resultCode)
                if resultCode != 250:
                    break

    # TransactionOutcome::SwitchedToPassThru=50
    if transactionOutcome == 50:
        # Pass thru card - display serial number and type
        cardType = tlv.getTag((0xdf, 0xc0, 0x41), TLVParser.CONVERT_INT)
        if (len(cardType)): cardType = cardType[0]
        cardSerial = tlv.getTag((0xdf, 0xc0, 0x42), TLVParser.CONVERT_HEX_STR)
        if (len(cardSerial)): cardSerial = cardSerial[0]
        log.log('cardType=', cardType, ' cardSerial=', cardSerial)

        #####################################################
        # Send 'PassThruDisable'
        log.log('Disabling pass-thru')
        passThruCtlTags = [
            [(0xdf, 0xc0, 0x01), [cicappHandle]],
            [(0xdf, 0x1f), [0x30]],  # POS timeout
            [(0xdf, 0xc0, 0x40), [0x00]]
        ]
        SendPassThruPacket(conn, 220, passThruCtlTags)
        status, buf, uns = conn.receive()
        if status != 0x9000:
            log.logerr('Send pass-thru fail', hex(status), buf)
            exit(-1)
Example #21
0
 def log_message(self, title, buf_total, buf_frames, tags,val_extra):
     #To ascii internal convert
     def toascii( inp ):
         if inp==None: return ''
         inp = bytearray(inp if type(inp)!=int else [inp])
         for i, ch in enumerate(inp):
             if ch<ord(' ') or ch>127: inp[i] = ord('.')
         return str(inp, 'iso8859-1')
     #To hex internal convert
     def tohex( inp ):
         if inp==None: return ''
         inp = bytearray(inp if type(inp)!=int else [inp])
         from binascii import hexlify
         return str(hexlify(inp) if inp!=None else '', 'iso8859-1')
     slog = getSyslog()
     log_array = [
                     [ 'data',
                        [ 'hex',  tohex(buf_total)],
                        [ 'ascii',  toascii(buf_total)]  
                     ]
                 ]
     frames = [ 'frames ']
     for f in  buf_frames: frames.append(['frame', tohex(f)  ])
     log_array.append(frames)
     if type(val_extra)==int:
         asc =  ['ascii', self.__desc_cfg['SW1SW2'].get("%04X"%val_extra,"NA")]
         value_v = [ 'value',  ['hex', val_extra], asc ]
     else:
         sval = tohex(bytearray(val_extra))
         asc =  ['ascii', self.__desc_cfg['CLAINS'].get(sval[:4].upper(),"NA")]
         value_v = ['value', ['hex', sval], asc ]
     tlv_v = ['tlv']
     if tags!=None:
         #Single elem
         if type(tags)==tuple: tags = [tags]
         for idx0 in tags:
             if type(idx0)!=int and len(idx0)==2:
                 if type(idx0[1])==bytes: idx0[1] = bytearray(idx0[1])
                 if type(idx0[0])==tuple and (type(idx0[1])==bytearray or (type(idx0[1])==list and len(idx0[1])>0 and type(idx0[1][0])==int) ) :
                     tag_v = ['tag', ['value', tohex(idx0[0])], ['desc', 'NA'],
                                 [   'data', 
                                     ['hex', tohex(idx0[1])], 
                                     ['ascii', toascii(idx0[1])] 
                                 ]
                             ]
                     tlv_v.append(tag_v)
                 elif (type(idx0[0])==tuple or type(idx0[0])==int) and type(idx0[1])==list:
                     tpl_desc = self.__desc_cfg['Templates'].get(tohex(idx0[0]),"NA")
                     tpl_v = [ 'template', ['value', idx0[0]], ['desc', tpl_desc] 
                             ]
                     for idx1 in idx0[1]:
                         tag_desc = self.__desc_cfg['Tags'].get(tohex(idx1[0]).upper(),'NA')
                         tag_v = [ 'tag', ['value', tohex(idx1[0])], ['desc', tag_desc],
                                      [  'data', 
                                          ['hex', tohex(idx1[1])], 
                                          ['ascii', toascii(idx1[1])] 
                                      ]
                                ] 
                         tpl_v.append(tag_v)
                     tlv_v.append(tpl_v)
                 elif type(idx0[0])==str:
                     unp_v = ['unparsed',
                                ['hex', tohex(idx0[1])], 
                                ['ascii', toascii(idx0[1])] 
                             ]
                     tlv_v.append(unp_v)
                 else:
                     err_v = ['error', str(idx0)]
                     tlv_v.append(err_v)
     #Parsed v
     parsed_v = [ 'parsed ',  value_v, tlv_v]
     log_array.append(parsed_v)
     slog.log_send_receive(title, log_array)
def transtest_function():
    log = getSyslog()
    conn = connection.Connection();
    #Create ssl server
    #conn.connect_tcp_server(timeout=30)
    #conn.connect_tcp_client('localhost',16107)
    #conn.connect_serial('COM1', 57600, timeout=2 );
    req_unsolicited = conn.connect()
    if req_unsolicited:
        #Receive unsolicited
        status, buf, uns = conn.receive()
        if status != 0x9000:
            log.logerr('Unsolicited fail')
            exit(-1)
        log.log('Unsolicited', TLVParser(buf) )
    #Send reset device
    conn.send([0xD2, 0x01, 0x01, 0x00])
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('reset fail')
        exit(-1)
    #Monitor card status
    conn.send([0xD0, 0x60, 0x01, 0x00])
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Cardstatus fail')
        exit(-1)
    #print('CardStatus',TLVParser(buf))
    #Prompt for card
    conn.send([0xD2, 0x01, 0x0D, 0x00])
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('prompt card fail')
        exit(-1)
    #Short insert card notification
    log.log('**** WAIT FOR CARD INSERTION ****')
    status, buf, uns = conn.receive()
    if status != 0x9000 and not uns:
        log.logerr('Pinpad fail!!', hex(status),uns)
        exit(-1)
    tlv = TLVParser(buf)
    ins_tag_val = tlv.getTag(0x48, tlv.CONVERT_INT)
    if ins_tag_val[0]!=0x300:
        log.logerr('PINPAD FAILED tag 0x48 is', ins_tag_val)
        exit(-1)
    #Create localtag for transaction
    start_trans_tag = [
         [(0x9F, 0x02), b'\x00\x00\x00\x10\x04\x00' ],
         [(0x9A), b'\x04\x01\x01'],
         [(0x9C), b'\x00'],
         [(0x9F,0x21), b'\x01\x01\x01'],
         [(0x9F,0x41), b'\x00\x01' ],
         [(0x5F,0x2A), b'\x08\x26' ],
         [(0xDF,0xA2,0x18), b'\x00'],
         [(0xDF,0xA2,0x14), b'\x01'],
         [(0xDF,0xA2,0x04), b'\x01']
    ]
    start_templ = ( 0xE0, start_trans_tag )
    print(start_templ)
    #Start transaction
    conn.send([0xDE, 0xD1, 0x00, 0x00], start_templ)
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Start transaction fail', hex(status), buf)
        exit(-1)
    #print(TLVParser(buf))
    #Continue transaction
    c_tag = tagStorage()
    c_tag.store( (0x9F,0x02), [0x00, 0x00, 0x00,0x00, 0x54, 0x00 ] )
    c_tag.store( (0x5F,0x2A), [0x09, 0x78] )
    c_tag.store(  0xC2, [0x30, 0x30] )
    c_tag.store( (0xDF,0xA2,0x18), 0x00 )
    c_tag.store( (0xDF,0xA3,0x07), [0x03,0xE8] )
    c_tag.store( 0xC0, 0x01 )
    c_tag.store( 0x8A, [0x59, 0x32 ] )
    c_tag.store( 0x91, [0x37,0xDD,0x29,0x75,0xC2,0xB6,0x68,0x2D,0x00,0x12] ) 

    #continue_tran_tag = [
    #    [ (0x9F,0x02), [0x00, 0x00, 0x00,0x00, 0x54, 0x00 ] ],
    #    [ (0x5F,0x2A), [0x09, 0x78] ],
    #    [ (0xC2), [0x30, 0x30] ],
    #    [ (0xDF,0xA2,0x18), [0x00] ],
    #    [ (0xDF,0xA3,0x07), [0x03,0xE8] ],
    #    [ (0xC0), [0x01] ],
    #    [ (0x8A), [0x59, 0x32 ] ],
    #    [ (0x91), [0x37,0xDD,0x29,0x75,0xC2,0xB6,0x68,0x2D,0x00,0x12] ]
    #]
    #continue_tpl = (0xE0, continue_tran_tag )
    #conn.send([0xDE, 0xD2, 0x00, 0x00], continue_tpl)
    conn.send( [0xDE, 0xD2, 0x00, 0x00], c_tag.getTemplate(0xE0) )

    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Continue transaction fail', hex(status), buf)
        exit(-1)
    #print(TLVParser(buf))
    log.log('*** PIN ENTRY WAIT ***')
    status, buf, uns = conn.receive()
    utility.check_status_error((status, buf, uns))
    tlv = TLVParser(buf)
    #print(tlv)
    if tlv.tagCount(0xE6) != 0:
        log.logerr('Not complete response wait again')
        status, buf, uns = conn.receive()
        if status != 0x9000:
            log.logerr('Pin entry wait #2', hex(status), buf)
            exit(-1)
    # Continue with positive response
    conn.send([0xDE, 0xD2, 0x00, 0x00])
    log.log('*** ONLINE REQUEST WAIT ***')
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Online Request wait', hex(status), buf)
        exit(-1)
    #print(TLVParser(buf))
    #Remove card
    conn.send([0xD2, 0x01, 0x0E, 0x00])
    log.log('*** REMOVE CARD PROMPT***')
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Remove card', hex(status), buf)
        exit(-1)
    log.log('*** REMOVE CARD WAIT ***')
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Remove card wait', hex(status), buf)
        exit(-1)
    #Reset display
    conn.send([0xD2, 0x01, 0x01, 0x00])
    log.log('*** RESET DISPLAY ***')
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Reset display wait', hex(status), buf)
        exit(-1)
    #Disconnect
    conn.send([0xD2, 0x01, 0x01, 0x00])
    log.log('*** DISCONNECT ***')
    status, buf, uns = conn.receive()
    if status != 0x9000:
        log.logerr('Disconnect wait', hex(status), buf)
        exit(-1)