Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
INS_SIGN = 0x04
INS_HASH = 0x08
P1_FIRST = 0x00
P1_MORE = 0x80
P2_DISPLAY_HASH = 0x00
P2_SIGN_HASH = 0x01
// exception codes
#define SW_DEVELOPER_ERR 0x6B00
#define SW_INVALID_PARAM 0x6B01
#define SW_IMPROPER_INIT 0x6B02
#define SW_USER_REJECTED 0x6985
#define SW_OK 0x9000
"""
dongle = getDongle(True)
publicKey = dongle.exchange(bytes("8004000000".decode('hex')))
print "publicKey " + str(publicKey).encode('hex')
try:
offset = 0
signature = b''
while offset <> len(textToSign):
if (len(textToSign) - offset) > 255:
chunk = textToSign[offset : offset + 255]
else:
chunk = textToSign[offset:]
if (offset + len(chunk)) == len(textToSign):
p1 = 0x80
else:
p1 = 0x00
apdu = bytes("8002".decode('hex')) + chr(p1) + chr(0x00) + chr(len(chunk)) + bytes(chunk)
signature += dongle.exchange(apdu)
def pack_sign_input(transaction_idx):
struct = Struct("
def _hardware_wallet_init(self, auth_type):
"""Initialize hardware wallets"""
self._ledger = None
if auth_type in ["ledger", "trezor"]:
assert auth_type == 'ledger', "Unsupported hardware wallet, only Ledger is supported at this time"
try:
self._ledger = LedgerWallet()
return True
except CommException:
self.logger.error('No Ledger USB dongle found!')
raise
printer.addArea(param_start, paramsSectionContent)
# account for added regions (install parameters, icon ...)
appLength = printer.maxAddr() - printer.minAddr()
loader.createAppNoInstallParams(args.appFlags, appLength, args.appName, None, path, 0, len(paramsSectionContent), string_to_bytes(args.appVersion))
else:
# account for added regions (install parameters, icon ...)
appLength = printer.maxAddr() - printer.minAddr()
loader.createAppNoInstallParams(args.appFlags, appLength, args.appName, args.icon, path, None, None, string_to_bytes(args.appVersion))
hash = loader.load(0x0, 0xF0, printer, targetId=args.targetId, targetVersion=args.targetVersion, doCRC=not (args.nocrc or NOCRC))
print("Application full hash : " + hash)
if (signature == None and args.signApp):
masterPrivate = PrivateKey(bytes(bytearray.fromhex(args.signPrivateKey)))
signature = masterPrivate.ecdsa_serialize(masterPrivate.ecdsa_sign(bytes(binascii.unhexlify(hash)), raw=True))
print("Application signature: " + str(binascii.hexlify(signature)))
if (args.tlv):
loader.commit(signature)
else:
loader.run(args.bootAddr-printer.minAddr(), signature)
elif MCUPROXY is not None:
return getDongleHTTP(remote_host=MCUPROXY, debug=debug)
elif TCP_PROXY is not None:
return getDongleTCP(server=TCP_PROXY[0], port=TCP_PROXY[1], debug=debug)
dev = None
hidDevicePath = None
ledger = True
for hidDevice in hid.enumerate(0, 0):
if hidDevice['vendor_id'] == 0x2c97:
if ('interface_number' in hidDevice and hidDevice['interface_number'] == 0) or ('usage_page' in hidDevice and hidDevice['usage_page'] == 0xffa0):
hidDevicePath = hidDevice['path']
if hidDevicePath is not None:
dev = hid.device()
dev.open_path(hidDevicePath)
dev.set_nonblocking(True)
return HIDDongleHIDAPI(dev, ledger, debug)
if PCSC:
connection = None
for reader in readers():
try:
connection = reader.createConnection()
connection.connect()
if selectCommand != None:
response, sw1, sw2 = connection.transmit(toBytes("00A4040010FF4C4547522E57414C5430312E493031"))
sw = (sw1 << 8) | sw2
if sw == 0x9000:
break
else:
connection.disconnect()
connection = None
else:
break
def handleSignRequest(message, key, eddsa, path):
logging.debug("Sign request")
blobSize = struct.unpack(">I", message[0:4])[0]
blob = message[4 : 4 + blobSize]
if blob <> key:
logging.debug("Client sent a different blob " + blob.encode('hex'))
return chr(SSH_AGENT_FAILURE)
challengeSize = struct.unpack(">I", message[4 + blobSize : 4 + blobSize + 4])[0]
challenge = message[4 + blobSize + 4: 4 + blobSize + 4 + challengeSize]
# Send the challenge in chunks
dongle = getDongle(logging.getLogger().isEnabledFor(logging.DEBUG))
donglePath = parse_bip32_path(args.path)
offset = 0
while offset <> len(challenge):
data = ""
if offset == 0:
donglePath = parse_bip32_path(path)
data = chr(len(donglePath) / 4) + donglePath
if (len(challenge) - offset) > (255 - len(data)):
chunkSize = (255 - len(data))
else:
chunkSize = len(challenge) - offset
data += challenge[offset : offset + chunkSize]
if offset == 0:
p1 = 0x00
else:
p1 = 0x01
def connect(self, device):
self.token = None
if device.startswith("ledger:"):
self.token = getDongle(True)
self.exchange = self._exchange_ledger
self.disconnect = self._disconnect_ledger
elif device.startswith("pcsc:"):
allreaders = readers()
for r in allreaders:
rname = str(r)
#print('try: %s : %s'%(rname,device[5:]))
if rname.startswith(device[5:]):
r.createConnection()
self.token = r
self.connection = r.createConnection()
self.connection.connect()
self.exchange = self._exchange_pcsc
self.disconnect = self._disconnect_pcsc
else:
#print("No")
from .comm import getDongle
args = get_argparser().parse_args()
if args.url == None:
raise Exception("No URL specified")
if args.perso == None:
raise Exception("No personalization specified")
if args.endorsement == None:
raise Exception("No endorsement specified")
if args.key != 1 and args.key != 2:
raise Exception("Invalid endorsement scheme number")
if args.targetId == None:
args.targetId = 0x31000002 # Ledger Blue by default
dongle = getDongle(args.apdu)
# Identify
targetid = bytearray(struct.pack('>I', args.targetId))
apdu = bytearray([0xe0, 0x04, 0x00, 0x00]) + bytearray([len(targetid)]) + targetid
dongle.exchange(apdu)
# Get nonce and ephemeral key
request = Request()
request.reference = "signEndorsement"
parameter = request.remote_parameters.add()
parameter.local = False
parameter.alias = "persoKey"
parameter.name = args.perso
args = parser.parse_args()
if args.path == None:
if args.split_to_eth: # sign from ETC
#args.path = "44'/60'/160720'/0'/0"
args.path = "44'/60'/0'/0"
else: # sign from ETH
args.path = "44'/60'/0'/0"
if args.to == None:
if args.split_to_eth: # target ETH
args.to = "44'/60'/0'/0"
else: # target ETC transitional
args.to = "44'/60'/160720'/0'/0"
dongle = getDongle(True)
donglePath = parse_bip32_path(args.to)
apdu = "e0060000".decode('hex') + chr(len(donglePath) + 1) + \
chr(len(donglePath) / 4) + donglePath
dongle.exchange(bytes(apdu))
apdu = "e0020000".decode('hex') + chr(len(donglePath) + 1) + \
chr(len(donglePath) / 4) + donglePath
result = dongle.exchange(bytes(apdu))
publicKey = str(result[1: 1 + result[0]])
encodedPublicKey = sha3(publicKey[1:])[12:]
if (args.nonce == None) or (args.amount == None):
donglePathFrom = parse_bip32_path(args.path)
apdu = "e0020000".decode('hex') + chr(len(donglePathFrom) + 1) + \
chr(len(donglePathFrom) / 4) + donglePathFrom
parser.add_argument("--persistent", help="""Persist passphrase as secondary PIN (otherwise, it's set as a temporary
passphrase)""", action='store_true')
return parser
def auto_int(x):
return int(x, 0)
if __name__ == '__main__':
from .comm import getDongle
import getpass
import unicodedata
import sys
args = get_argparser().parse_args()
dongle = getDongle(False)
passphrase = getpass.getpass("Enter BIP39 passphrase : ")
if isinstance(passphrase, bytes):
passphrase = passphrase.decode(sys.stdin.encoding)
if len(passphrase) != 0:
if args.persistent:
p1 = 0x02
else:
p1 = 0x01
passphrase = unicodedata.normalize('NFKD', passphrase)
apdu = bytearray([0xE0, 0xD0, p1, 0x00, len(passphrase)]) + bytearray(passphrase, 'utf8')
dongle.exchange(apdu, timeout=300)