Ejemplo n.º 1
0
    def __init__(self):

        # detects the operating system
        if os.uname()[0] == "Darwin":  # MAC
            if os.path.isfile(self.PKCS11_LIB_MAC):
                self.PKCS11_LIB = self.PKCS11_LIB_MAC
            else:
                print("PKCS11 library doesn't exist on OSX!")

        elif platform.uname()[0] == "Windows":
            if os.path.isfile(self.PKCS11_LIB_WINDOWS):
                self.PKCS11_LIB = self.PKCS11_LIB_WINDOWS
            else:
                print("PKCS11 library doesn't exist on Windows!")

        else:
            if os.path.isfile(self.PKCS11_LIB_LINUX):
                self.PKCS11_LIB = self.PKCS11_LIB_LINUX
            else:
                print("PKCS11 library doesn't exist on Linux!")

        self.lib = pkcs11.lib(self.PKCS11_LIB)  # lib to use
        self.token = None

        # select the desired token
        tokens = self.lib.get_tokens()

        for t in tokens:
            self.token = t
            break
Ejemplo n.º 2
0
    def get_slots(self, filter=[]):
        slots = None
        try:
            if self.lib is None:
                self.lib = pkcs11.lib(self.get_module_lib())

            slots = self.lib.get_slots()
            if filter:
                slots = [slot for slot in slots if slot.slot_id in filter]
            self.error_show_message = 0
        except Exception as e:
            if self.error_show_message < self.settings.number_requests_before_fail:
                signals.send(
                    'notify',
                    signals.SignalObject(
                        signals.NOTIFTY_ERROR, {
                            'message':
                            "La biblioteca instalada no funciona para leer "
                            "las tarjetas, porque no ha instalado las "
                            "bibliotecas necesarias o porque el sistema "
                            "operativo no está soportado"
                        }))
                self.error_show_message += 1
            logger.error("Error abriendo dispositivos PKCS11 %r" % (e, ))

        if not slots:
            raise SlotNotFound("PKCS11: Slot not found")

        return slots
Ejemplo n.º 3
0
    def __init__(self, cfg_file=None):
        common_util.assert_in_error(
            cfg_file, "PKCS11 HSM manager requires a configuration file")
        self.session = None
        with open(cfg_file, "r") as read_file:
            self.j_data = json.load(read_file)
        j_data = self.j_data

        lib = pkcs11.lib(j_data["lib_path"])
        common_util.assert_in_error(
            j_data["library_version"] == list(lib.library_version),
            "PKCS11 HSM manager library version mismatch",
        )
        common_util.assert_in_error(
            j_data["cryptoki_version"] == list(lib.cryptoki_version),
            "PKCS11 HSM manager cryptoki version mismatch",
        )
        token = lib.get_token(token_label=j_data["token"]["label"])
        self.session = token.open(user_pin=j_data["token"]["user_password"])
        self.curve = j_data["curve"]

        self.ecparams = self.session.create_domain_parameters(
            pkcs11.KeyType.EC,
            {
                pkcs11.Attribute:
                pkcs11.util.ec.encode_named_curve_parameters(self.curve)
            },
            local=True,
        )
Ejemplo n.º 4
0
    def __init__(self, pin=None):
        lib = pkcs11.lib(
            os.getenv('PKCS11_MODULE', "/usr/local/lib/opensc-pkcs11.dylib"))

        slots = lib.get_slots(token_present=True)
        print("Available slots:")

        for i in range(0, int(len(slots) / 3)):
            # for each slot, get tokens
            slot = slots[i * 3]
            tokens = lib.get_tokens()
            token_label = "Auth PIN (CARTAO DE CIDADAO)"

            for token in tokens:
                if token_label == token.label and slot == token.slot:
                    self.token = token
                    name = self.get_cc_name()
                    print("%d %s" % (i, name))
                    break

        slot_select = input("Select slot: ")

        slot = slots[int(slot_select) * 3]
        tokens = lib.get_tokens()
        token_label = "Auth PIN (CARTAO DE CIDADAO)"

        for token in tokens:
            if token_label == token.label and slot == token.slot:
                self.token = token
                break

        if pin is None:
            self.pin = getpass.getpass("Auth PIN (CARTAO DE CIDADAO): ")
        else:
            self.pin = pin
    def test_get_tokens(self):
        lib = pkcs11.lib(LIB)

        tokens = lib.get_tokens(token_flags=pkcs11.TokenFlag.RNG)
        self.assertEqual(len(list(tokens)), 2)

        tokens = lib.get_tokens(token_label=TOKEN)
        self.assertEqual(len(list(tokens)), 1)
Ejemplo n.º 6
0
    def test():
        lib = pkcs11.lib("C:/Windows/System32/eps2003csp11v2.dll")
        token = lib.get_token(token_label='ePass2003-Palagiris')
        for slot in lib.get_slots():
            token = slot.get_token()
            print(token)

        if token.label == 'ePass2003-Palagiris':
            print(token)
    def test_get_token(self):
        lib = pkcs11.lib(LIB)
        slot, *_ = lib.get_slots()
        token = slot.get_token()

        self.assertIsInstance(token, pkcs11.Token)
        self.assertEqual(token.label, TOKEN)
        self.assertIn(pkcs11.TokenFlag.TOKEN_INITIALIZED, token.flags)
        self.assertIn(pkcs11.TokenFlag.LOGIN_REQUIRED, token.flags)
    def test_get_slots(self):
        lib = pkcs11.lib(LIB)
        slots = lib.get_slots()

        self.assertEqual(len(slots), 2)
        slot1, slot2 = slots

        self.assertIsInstance(slot1, pkcs11.Slot)
        self.assertEqual(slot1.flags, pkcs11.SlotFlag.TOKEN_PRESENT)
Ejemplo n.º 9
0
 def __init__(self, pkcs11library, label, pin):
     self.pkcs11library = pkcs11library
     self.label = label
     self.pin = pin
     lib = pkcs11.lib(pkcs11library)
     self.token = lib.get_token(token_label=self.label)
     self.session = self.token.open(rw=True, user_pin=self.pin)
     self.order = int(
         "115792089210356248762697446949407573529996955224135760342422259061068512044369"
     )
     self.half_order = self.order >> 1
Ejemplo n.º 10
0
    def __post_init__(
        self,
        types: Dict[KeyType, pkcs11.KeyType],
        approved_hashes: Dict[KeyType, Dict[HashType,
                                            Union[hashes.HashAlgorithm,
                                                  pkcs11.Mechanism]]],
    ):
        """Load token for SoftHSM operations."""
        lib = pkcs11.lib(self.so_file)
        self.token = lib.get_token(token_label=self.token_label)

        self.pkcs11_key_type = types[self.key_type]
        self.pkcs11_hash_type = approved_hashes[self.key_type][self.hash_type]
Ejemplo n.º 11
0
    def __init__(self):
        """init members using os.environ

        """
        logging.info(f"KMS_LIB_PATH : {os.environ['KMS_LIB_PATH']}")
        # 환경 변수 설정
        os.environ['PKCS11_MODULE'] = os.environ[
            'KMS_LIB_PATH'] + "/libsgkms_cryptoki.so"
        # Load PKCS11 module
        lib = pkcs11.lib(os.environ['PKCS11_MODULE'])
        # Get token
        self.__token = lib.get_token(token_label='SG-KMS TOKEN')
        self.__agent_pin = None
Ejemplo n.º 12
0
    def __init__(self, store: str, token, user_pin, label: str = ''):
        lib = pkcs11.lib(store)
        try:
            self.token = lib.get_token(token_label=token)
        except pkcs11.MultipleTokensReturned:
            raise RuntimeError(
                f"Multiple tokens returned for token {token}, label {label}"
            ) from None

        self.user_pin = user_pin
        self.label = label or "bridge_key"
        self._address = None
        self.public_key = None

        if self.label:
            self._load_key()
Ejemplo n.º 13
0
    def __init__(self,
                 lib_path=os.environ['PKCS11_LIBRARY_PATH'],
                 token_label='larry',
                 pin='1234'):
        """
        Session constructor.

        @param lib_path: P11 library path.
        @param token_label: Label of p11 token.
        @param pin: Pin corresponding to our p11 token.
        """
        self.__lib_path = lib_path
        self.__token_label = token_label
        self.__pin = pin
        self.lib = pkcs11.lib(self.__lib_path)
        self.token = self.lib.get_token(token_label=self.__token_label)
        self.p11 = self.token.open(user_pin=self.__pin, rw=True)
Ejemplo n.º 14
0
    def __init__(self, lib_location = None):
        """
            Cartao de Cidadao constructor, starts by initialising PKCS#11 library and class variables
        """
        if not lib_location:
            if os.path.isfile('/usr/local/lib/libpteidpkcs11.so'):
                lib_location = '/usr/local/lib/libpteidpkcs11.so'
            elif os.path.isfile('/usr/lib/libpteidpkcs11.so'):
                lib_location = '/usr/lib/libpteidpkcs11.so'
            elif os.path.isfile('/usr/local/lib64/libpteidpkcs11.so'):
                lib_location = '/usr/local/lib64/libpteidpkcs11.so'
            else:
                print("ERROR: libpteidpkcs11 not found!")
                quit()

        self.lib = pkcs11.lib( lib_location )   # Initialise PKCS#11 library
        self.session = None
Ejemplo n.º 15
0
    def __init__(self, key, algorithm, p11: P11Params = P11Key_params):
        super().__init__(key, algorithm)
        #self._key = key
        self._algorithm = algorithm
        self._public_key = None
        self._private_key = None
        self._mechanism = None
        self.p11 = p11

        logger.debug(f'Initialising PKCS#11 module: {self.p11.module}')
        self.lib = pkcs11.lib(self.p11.module)
        for _slot in self.lib.get_slots():
            logger.debug(f'Slot: {_slot}')

        logger.debug(f'Looking for token {repr(self.p11.token_label)}')
        self.token = self.lib.get_token(token_label=self.p11.token_label)

        logger.debug(f'Loaded module {self.lib} (key {key}, alg {algorithm})')
Ejemplo n.º 16
0
    def __init__(self, key_name):
        # load pkcs11 lib
        self.lib = pkcs11.lib(os.environ['PKCS11_LIB'])
        self.user_pin = os.environ['USER_PIN']
        self.token = next(self.lib.get_tokens())  # get any token
        self.key_name = key_name

        # initiate session via pkcs11
        start = time.time()
        self.session = self.token.open(user_pin=self.user_pin)
        print("time (connect) {}s".format(time.time() - start))
        start = time.time()

        # get key returns >1 key for some reason
        # key = session.get_key(object_class=ObjectClass.PRIVATE_KEY,
        #                         key_type=KeyType.EC,
        #                         label=self.key_name)

        # get key by iterating through all session objects instead
        iterator = self.session.get_objects({
            Attribute.KEY_TYPE: KeyType.EC,
            Attribute.CLASS: ObjectClass.PRIVATE_KEY,
            Attribute.LABEL: self.key_name
        })
        self.key = next(iterator)
        print(self.key)
        print("time (get private key) {}s".format(time.time() - start))
        start = time.time()
        _ = next(iterator)  # test get_objects() still returns > 1
        iterator._finalize()

        iterator = self.session.get_objects({
            Attribute.KEY_TYPE: KeyType.EC,
            Attribute.CLASS: ObjectClass.PUBLIC_KEY,
            Attribute.LABEL: self.key_name
        })
        pub = next(iterator)
        print(pub)
        pubder = ec.encode_ec_public_key(pub)
        self.pubcrypto = serialization.load_der_public_key(
            pubder, default_backend())
        print("time (get public key) {}s".format(time.time() - start))
        _ = next(iterator)  # test get_objects() still returns > 1
        iterator._finalize()
Ejemplo n.º 17
0
def sign_p11(sigin, alg, lib_path, slot, key_label, pin):
    lib = pkcs11.lib(lib_path)
    slot = lib.get_slots()[slot]
    token = slot.get_token()
    with token.open(user_pin=pin) as session:
        for priv in session.get_objects({
                Attribute.CLASS: ObjectClass.PRIVATE_KEY,
                Attribute.LABEL: key_label
        }):
            if alg == 'RS256':
                MECHANISM = Mechanism.SHA256_RSA_PKCS
            elif alg == 'RS384':
                MECHANISM = Mechanism.SHA384_RSA_PKCS
            elif alg == 'RS512':
                MECHANISM = Mechanism.SHA512_RSA_PKCS
            else:
                raise Exception('Unsupported algorithm')
            signature = priv.sign(sigin, mechanism=MECHANISM)
    return signature
Ejemplo n.º 18
0
def getCCToken():

    try:
        lib = pkcs11.lib('/usr/local/lib/libpteidpkcs11.so')
        token = None
        slots = lib.get_slots()

        if len(slots) == 0:
            log(logging.ERROR, "Could not find Portuguese Citizen Card")
            return

        for slot in slots:
            token = slot.get_token()
            break

    except Exception as e:
        print(e)
        log(logging.ERROR, "Could not find Portuguese Citizen Card")
        return

    return token
Ejemplo n.º 19
0
    def __init__(self):
        super(CC_Interaction, self).__init__()
        try:
            print("Reading CC...")
            self.lib = pkcs11.lib("/usr/lib/opensc-pkcs11.so")
            self.token = self.lib.get_token(token_label="Auth PIN (CARTAO DE CIDADAO)")
            self.user_pin = getpass.getpass("CC Authentication PIN? ")
            self.cert = Certificate(self.get_my_cert())
            with self.token.open(user_pin = str(self.user_pin)) as session:
                pass


        except (TokenNotPresent, NoSuchToken, IndexError):
            print("Please insert the Citizen Card!\nExiting...")
            sys.exit(-1)
        except (PinIncorrect):
            print("\nExiting...")
            sys.exit(-1)
        except (PKCS11Error):
            print("Invalid PIN!\nExiting...")
            sys.exit(-1)
        except Exception as e:
            raise e
Ejemplo n.º 20
0
def get_LIB():
    global LIB
    if LIB:
        return LIB
    for path in pkcs_module_path:
        try:
            logger.info("Loading library from " + path)
            LIB = pkcs11.lib(path)
            logger.info("Library loading success")
            break
        except:
            logger.info("Library loading failed")
    if not LIB:
        raise DevicePKCS11Error(
            "Cannot load library from {path}. ".format(path=pkcs_module_path) +
            "Check path and its format (bitness, endianness, compiler).")

    logger.info("Library information: {} {} {}".format(LIB.library_description,
                                                       LIB.library_version,
                                                       LIB.manufacturer_id))
    if LIB.library_version[1] < 17 and "OpenSC" in LIB.manufacturer_id:
        logger.warning(
            "Issues may occur with this version of library - OpenSC 0.16.")
    return LIB
def get_LIB():
    global LIB
    if LIB:
        return LIB
    for path in pkcs_module_path:
        try:
            log.info('Loading library from ' + path)
            LIB = pkcs11.lib(path)
            log.info('Library loading success')
            break
        except:
            log.info('Library loading failed')
    if not LIB:
        raise RuntimeError(
            'Cannot load library from {path}. '.format(path=pkcs_module_path) +
            'Check path and its format (bitness, endianness, compiler).')

    log.info('Library information: {} {} {}'.format(LIB.library_description,
                                                    LIB.library_version,
                                                    LIB.manufacturer_id))
    if LIB.library_version[1] < 17 and 'OpenSC' in LIB.manufacturer_id:
        log.warning(
            'Issues may occur with this version of library - OpenSC 0.16.')
    return LIB
Ejemplo n.º 22
0
import sys
from typing import List, cast

from pkcs11 import PublicKey, lib, Token, Session
from pkcs11.util.rsa import encode_rsa_public_key
from Crypto.PublicKey import RSA

lib = lib('/Library/OpenSC/lib/opensc-pkcs11.so')


def get_tokens() -> List[Token]:
    return list(lib.get_tokens())


def get_auth_pubkey(session: Session) -> PublicKey:
    return cast(PublicKey, session.get_key(PublicKey.object_class, id=b'\x01'))


def main():
    token = get_tokens()[0]
    session = token.open()
    print(token.label, file=sys.stderr)

    pubkey = get_auth_pubkey(session)
    der = encode_rsa_public_key(pubkey)
    rsa = RSA.importKey(der)
    print(pubkey.label, file=sys.stderr)
    print(rsa.export_key('OpenSSH').decode())

    session.close()
Ejemplo n.º 23
0
from log import logger
from pkcs11.constants import Attribute
from pkcs11.constants import ObjectClass
from OpenSSL import crypto
from termcolor import colored
import logging
import pkcs11
import getpass
import os
import sys

logger.log(logging.DEBUG, "Initializing CC module...")

lib = pkcs11.lib(os.environ['PKCS11_MODULE'])
token = None
try:
    for t in lib.get_tokens():
        token = t
        break
except:
    print(colored('ERROR: CC device not connected', 'red'))
    sys.exit(0)


def get_correct_pin():
    pin = getpass.getpass(colored("CC Authentication PIN: ", 'blue'))

    # Get correct pin
    text = "\nIncorrect PIN. Please type the correct PIN: "
    while not test_pin(pin):
        pin = getpass.getpass(colored(text, 'red'))
Ejemplo n.º 24
0
#!/usr/bin/env python3
import os
import traceback
import pkcs11
from pkcs11 import KeyType, ObjectClass, Mechanism, MechanismFlag, Attribute, PKCS11Error
from pkcs11.util import ec
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend

# load pkcs11 lib
lib = pkcs11.lib(os.environ['PKCS11_LIB'])

tokens = lib.get_tokens()
token = next(tokens)  # get any token

try:
    # connect to hsm via pkcs11 token and pin
    with token.open(user_pin=os.environ['USER_PIN'], rw=True) as session:

        # ec curve params
        ecparams = session.create_domain_parameters(
            KeyType.EC,
            {
                # hardcoded curve name for secp256k1 taken from https://www.flexiprovider.de/CurveOIDs.html
                # asn1crypto python library currently missing the secp256k1 named curve parameters
                Attribute.EC_PARAMS:
                ec.encode_named_curve_parameters('1.3.132.0.10'),
            },
            local=True)

        try:
Ejemplo n.º 25
0
#!/usr/bin/env python3
import pkcs11
import codecs
import sys
import os

lib = pkcs11.lib(os.getenv('PKCS_MODULE'))
token = lib.get_token(token_label=os.getenv('SECURITY_MODULE_SLOT_LABEL'))
session = token.open(user_pin=os.getenv('SECURITY_MODULE_USER_PIN'))

wanted = int(sys.argv[1])
rand = session.generate_random(wanted * 8)
if len(rand) == wanted:
    print(codecs.encode(rand, 'hex').decode('ascii'))
    sys.exit(0)

print("ERROR_RANDOM_BYTES_LENGTH")
sys.exit(-1)
Ejemplo n.º 26
0
 def setUp(self):
     self.lib = pkcs11.lib('python-pkcs11-provider.so')
Ejemplo n.º 27
0
#!/usr/bin/python3

import os
import binascii
import textwrap
import pkcs11
import pkcs11.util.rsa
import cryptography
import cryptography.hazmat.backends
import cryptography.hazmat.primitives
import cryptography.hazmat.primitives.serialization
import cryptography.hazmat.primitives.asymmetric
import cryptography.hazmat.primitives.asymmetric.padding

lib = pkcs11.lib(os.environ['TEST_PKCS11_LIBRARY_PATH'])
token_label = os.environ[
    'TEST_PKCS11_TOKEN_LABEL']  # pkcs11-tool --module opensc-pkcs11.so --list-slots
key_label = os.environ[
    'TEST_PKCS11_KEY_LABEL']  # pkcs11-tool --module opensc-pkcs11.so --list-slots --list-objects
user_pin = os.environ['TEST_PKCS11_USER_PIN']

# list supported mechanisms.
for slot in lib.get_slots():
    token = slot.get_token()
    if not token.flags & pkcs11.TokenFlag.TOKEN_INITIALIZED:
        continue
    print(f'token-label: {token.label}')
    for m in slot.get_mechanisms():
        info = slot.get_mechanism_info(m)
        print(f'mechanism: {m.name}')
        print(textwrap.indent(str(info), len('mechanism: ') * 2 * ' '))
Ejemplo n.º 28
0
import PyKCS11.LowLevel
import sys
import PyKCS11
import pkcs11

# Initialise our PKCS#11 library
lib = pkcs11.lib("C:/Windows/System32/eps2003csp11v2.dll")
token = lib.get_token(token_label='ePass2003-Palagiris')

pkcs11 = PyKCS11.PyKCS11Lib()
PyKCS11.CK_TOKEN_INFO()
i = PyKCS11.CK_SLOT_INFO()
PyKCS11.CK_SESSION_INFO()
#i = pkcs11.getSlotInfo(0)
#pkcs11.openSession(0)
#print("Library manufacturerID: ") + info.manufacturerID

for slots in lib.get_slots():
    token = slots.get_token()
    if token.label == 'ePass2003-Palagiris':
        break
slots = pkcs11.getSlotList()
print("Available Slots:"), len(slots)
for s in slots:
    try:
        i = pkcs11.getSlotInfo(s)
        print("Slot no:"), s
        print(format_normal % ("slotDescription", i.slotDescription.strip()))
        print(format_normal % ("manufacturerID", i.manufacturerID.strip()))

        t = pkcs11.getTokenInfo(s)
Ejemplo n.º 29
0
    def load_pkcs11_keys(provider,
                         pin=None,
                         *,
                         load_certs=True,
                         token_label=None,
                         token_serial=None,
                         key_label=None,
                         key_id=None):
        """Load PIV keys and X.509 certificates from a PKCS#11 token

           This function loads a list of SSH keypairs with optional X.509
           cerificates from attached PKCS#11 security tokens. The PKCS#11
           provider must be specified, along with a user PIN if the
           tokens are set to require one.

           By default, this function loads both private key handles
           and the X.509 certificates associated with them, allowing for
           X.509 certificate based auth to SSH servers that support it.
           To disable loading of these certificates and perform only
           key-based authentication, load_certs may be set to `False`.

           If token_label and/or token_serial are specified, only tokens
           matching those values will be accessed.

           If key_label and/or key_id are specified, only keys matching
           those values will be loaded. Key IDs can be specified as
           either raw bytes or a string containing hex digits.

               .. note:: If you have an active asyncio event loop at
                         the time you call this function, you may want
                         to consider running it via a call to
                         :meth:`asyncio.AbstractEventLoop.run_in_executor`.
                         While retrieving the keys generally takes only a
                         fraction of a second, calling this function
                         directly could block asyncio event processing
                         until it completes.

           :param provider:
               The path to the PKCS#11 provider's shared library.
           :param pin: (optional)
               The PIN to use when accessing tokens, if needed.
           :param load_certs: (optional)
               Whether or not to load X.509 certificates from the
               security tokens.
           :param token_label: (optional)
               A token label to match against. If set, only security
               tokens with this label will be accessed.
           :param token_serial: (optional)
               A token serial number to match against. If set, only
               security tokens with this serial number  will be accessed.
           :param key_label: (optional)
               A key label to match against. If set, only keys with this
               label will be loaded.
           :param key_id: (optional)
               A key ID to match against. If set, only keys with this ID
               will be loaded.
           :type provider: `str`
           :type pin: `str`
           :type load_certs: `bool`
           :type token_label: `str`
           :type token_serial: `bytes` or `str`
           :type key_label: `str`
           :type key_id: `bytes` or `str`

        """

        lib = pkcs11.lib(provider)

        keys = []

        if isinstance(token_serial, str):
            token_serial = token_serial.encode('utf-8')

        for token in lib.get_tokens(token_label=token_label,
                                    token_serial=token_serial):
            with SSHPKCS11Session.open(token, pin) as session:
                keys.extend(session.get_keys(load_certs, key_label, key_id))

        return keys
Ejemplo n.º 30
0
    def setUpClass(cls):
        super().setUpClass()
        cls.lib = lib = pkcs11.lib(LIB)

        if cls.with_token or cls.with_session:
            cls.token = lib.get_token(token_label=TOKEN)