Balu SKT
Balu SKT

Reputation: 549

Issue while sending command to HSM

I am trying to send commands to HSM (Thales paysheild 9000) using a python code. But the response I am getting from the code is not as per the desired one.

Input: HEADJA12345678912306 #generate random pin of length 6
Ouput: HEADJA12315 

Can any one help me in identifying the issue? The response should ideally have JB instead of JA which I got as output.

The below is the code.

#!/usr/bin/python
import socket, binascii, string
from struct import *
import time;

TCP_IP = 'localhost'
TCP_PORT = 6511

COMMAND = 'HEADJA12345678912306'

def testPrintable(str):
    return all(c in string.printable for c in str)

def buildCommand(command):
    hCommand = ''
    i = 0
    while True:
        if (command[i:i+1] == '<'):
            i = i + 1
            while True:
                hCommand = hCommand + binascii.a2b_hex(command[i:i+2])
                i = i + 2
                if (command[i:i+1] == '>'):
                    i = i + 1
                    break
        else:
            hCommand = hCommand + command[i]
            i = i + 1
        if (i == len(command)):
            break
    return hCommand

def main():
    global TCP_IP
    global TCP_PORT
    global COMMAND

    connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    connection.connect((TCP_IP, TCP_PORT))

    BUFFER_SIZE = 1024

    COMMAND = buildCommand(COMMAND)
    SIZE=pack('>h',len(COMMAND))
    MESSAGE = SIZE + COMMAND
    connection.send(MESSAGE)
    data = connection.recv(BUFFER_SIZE)

    if (testPrintable(MESSAGE[2:])):
        print "sent data (ASCII) :", MESSAGE[2:]
    print "sent data (HEX) :", MESSAGE.encode('hex')
    if (testPrintable(data[2:])):
        print "received data (ASCII):", data[2:]

    print "received data (HEX) :", data.encode('hex')
    connection.close()

if __name__ == "__main__":
    main()

Upvotes: 2

Views: 1871

Answers (2)

AjTeacher
AjTeacher

Reputation: 28

HSMs are designed in such a way that if it receive any command which is not in its list, it will not provide any proper output. This is done for additional security and prevent external hacking. Like in your case you didn't have a clue on what was happening. Luckily for you the problem was with header length. But in some cases it could be any other issue and HSM will not give proper error code.

Upvotes: 1

Balu SKT
Balu SKT

Reputation: 549

The issue was resolved, the header length which I was using was not correct. After correcting the header length the HSM was responding back with correct message.

Upvotes: 2

Related Questions