Giter VIP home page Giter VIP logo

python-pkcs11's People

Contributors

aalba6675 avatar asaero avatar ateska avatar danni avatar dependabot[bot] avatar diabonas avatar h3po avatar joseavegaa avatar kalebmckale avatar keldonin avatar kigawas avatar markwhi avatar maxxiefjv avatar nickray avatar rgl avatar ronf avatar space88man avatar wjmelements avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-pkcs11's Issues

Get Slot by ID

Hi everyone, I'm trying to get a slot by an ID. I tried some ways to do it, unsuccessfully.

Importing public keys

Hi!

Thank you for this great library and the effort you invested. I tested a lot and it really works well.

I've one question regarding the derivation of a shared secret when using EC. How can public keys be imported, which are part of a x509 certificate? I read in the documentation something about a function called import_key(), but I did not found it. Is it already implemented?

Unfortunately the examples and test file always generate new keys, but I need to get the public key from an existing x509.

Thank you!

Python int too large to convert to C ssize_t

ESC[36msigning_web |ESC[0m     for public_obj in session.get_objects(PUBLIC_KEY_OBJECTS_FILTER):
ESC[36msigning_web |ESC[0m   File "pkcs11/_pkcs11.pyx", line 282, in pkcs11._pkcs11.SearchIter.__next__
ESC[36msigning_web |ESC[0m   File "pkcs11/_pkcs11.pyx", line 599, in pkcs11._pkcs11.Object._make
ESC[36msigning_web |ESC[0m   File "pkcs11/_pkcs11.pyx", line 629, in pkcs11._pkcs11.Object.__getitem__
ESC[36msigning_web |ESC[0m   File "pkcs11/_utils.pyx", line 11, in pkcs11._pkcs11.CK_BYTE_buffer
ESC[36msigning_web |ESC[0m   File "stringsource", line 151, in View.MemoryView.array.__cinit__
ESC[36msigning_web |ESC[0m OverflowError: Python int too large to convert to C ssize_t

Version: ref 1bab4197f1098b6933dda2a12c5100f6d92cd706

generate_keypair Not Persisting Objects in SoftHSMv2

Hey there!

Thanks for the great work creating this library. I really like the Pythonic interface to otherwise verbose PKCS11 bindings.

I'm using SoftHSMv2 as a POC to take this library for a spin, and I'm running into some issues when it comes to persisting generated keypairs.

Here's some sample code to show you what I'm doing:

lib = pkcs11.lib(os.environ['PKCS11_MODULE'])
token = lib.get_token(token_label='DEMO')
with token.open(user_pin='1234') as session:
    pub, priv = session.generate_keypair(
        pkcs11.KeyType.RSA, key_length=2048, label="DEMOKEY")

    #print(pkcs11.util.rsa.encode_rsa_public_key(pub))

with token.open(user_pin='1234') as session:
    keys = session.get_objects({pkcs11.Attribute.LABEL: 'DEMOKEY'})
    for key in keys:
        print(key)

In this example, I'm generating a new RSA keypair (which is presumably stored on the HSM), then I'm opening a new session and attempting to search for those keys and print any indication that they're there. Unfortunately, the get_objects iterator is empty.

It's worth noting that:

  • The commented out RSA encoding works fine
  • Even if I move the get_objects call into the same session as the generate_keypair call, it still returns an empty iterator.
  • SoftHSMv2 persistence should be fine, since things seem to work ok when using a different pkcs11 library (specifically Pykcs11).

Any help would be greatly appreciated. If there's any other information you need from me to help track this down, please don't hesitate to let me know!

struct.error: unpack requires a buffer of 1 bytes at printing objects from SmartCard

When I try to print every object available in my Smart Card with:
for i in session.get_objects(): print(i)

I always get this error on the second object

Traceback (most recent call last):
File "cc_test.py", line 59, in
cc.scan()
File "cc_test.py", line 50, in scan
for i in self.session.get_objects():
File "pkcs11/_pkcs11.pyx", line 271, in pkcs11._pkcs11.SearchIter.next
File "pkcs11/_pkcs11.pyx", line 578, in pkcs11._pkcs11.Object._make
File "pkcs11/_pkcs11.pyx", line 605, in pkcs11._pkcs11.Object.getitem
File "pkcs11/_utils.pyx", line 35, in pkcs11._pkcs11._unpack_attributes
File "/lib/python3.7/site-packages/pkcs11/defaults.py", line 113, in
_bool = (Struct('?').pack, lambda v: Struct('?').unpack(v)[0])
struct.error: unpack requires a buffer of 1 bytes

Note that this also happens when I try to use get_key() for some keys.

Reading Token information

Hi!
I want to retrieve information about a certain token like serial number, manufacturer etc.
If I select a token with get_token(token_label='somelabel') I only can read token's label with token.label, but all other token data like token manufacturer, model or serial number is empty.

Hasn't it just been implemented or do I forget something?

missing secp256k1 curve

Hello

I'm attempting the following:

# Generate an EC keypair in this session from a named curve
    ecparams = session.create_domain_parameters(
        pkcs11.KeyType.EC, {
            pkcs11.Attribute: ec.encode_named_curve_parameters('secp256k1'),
        }, local=True)
    pub, priv = ecparams.generate_keypair()

but I get the error:
ValueError: asn1crypto.keys.NamedCurve._map does not contain an entry for "secp256k1"

Isn't secp256k1 supported? I saw it was included here https://python-pkcs11.readthedocs.io/en/latest/opensc.html.

lib = pkcs11.lib(WHAT TO PUT HERE?) Gemalto Safenet USB eToken 5110 JC

I'm trying to use: http://python-pkcs11.readthedocs.io/en/latest/applied.html#getting-a-session but I don't make any idea of what PKCS11_MODULE to use . Is there a list of modules to try? I tried '/lib/libeToken.so.9' (provided by the SAC (Safenet Authentication Module installation), which works fine with pkcs11-tool, but in python I get "AttributeError: module 'pkcs11' has no attribute 'lib'" My token is an USB eToken Aladdin 5110 JC

I can sign data with this token with this command:

pkcs11-tool --module /lib/libeToken.so.9 -l --pin **** -s -i file_to_sign
Which works fine.

The problem is I don't make any idea of what to put inside the lib = pkcs11.lib(WHAT TO PUT HERE?) in the getting session example.

Can't install the library

Do you know how to fix the error below?

pip install python-pkcs11
Collecting python-pkcs11
  Using cached python-pkcs11-0.2.1.tar.gz
    Complete output from command python setup.py egg_info:

    Installed /tmp/pip-build-8T1rhN/python-pkcs11/setuptools_scm-1.15.6-py2.7.egg
    Searching for cython
    Reading http://pypi.python.org/simple/cython/
    Best match: Cython 0.25.2
    Downloading https://pypi.python.org/packages/b7/67/7e2a817f9e9c773ee3995c1e15204f5d01c8da71882016cac10342ef031b/Cython-0.25.2.tar.gz#md5=642c81285e1bb833b14ab3f439964086
    Processing Cython-0.25.2.tar.gz
    Running Cython-0.25.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-1388u4/Cython-0.25.2/egg-dist-tmp-8wQnHf
    Unable to find pgen, not compiling formal grammar.
    warning: no files found matching '*.pyx' under directory 'Cython/Debugger/Tests'
    warning: no files found matching '*.pxd' under directory 'Cython/Debugger/Tests'
    warning: no files found matching '*.h' under directory 'Cython/Debugger/Tests'
    warning: no files found matching '*.pxd' under directory 'Cython/Utility'

    Installed /tmp/pip-build-8T1rhN/python-pkcs11/Cython-0.25.2-py2.7-linux-x86_64.egg
    your setuptools is too old (<12)
    setuptools_scm functionality is degraded
    error in python-pkcs11 setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-8T1rhN/python-pkcs11/

PKCS11 library is incorrectly used

It is assumed that the PKCS#11 library contains symbols like C_WrapKey and C_UnwrapKey. This is wrong, these function should accessed indirectly with the return value of C_GetFunctionList.
SoftHSMV2 supplies all these symbols in the softhsm2.so, but when using a pkcs11-proxy to forward all the requests over the network, the loading of the pkcs11-proxy.so library fails.
$ objdump -T /usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so | grep " C_"
This shows all the available symbols for the
$ objdump -T /usr/lib/libpkcs11-proxy.so | grep " C_"
This show only the C_GetFunctionList.

Correct MAC Mechanism for SoftHSMv2

Hi,

I'm using softhsmv2 (2.3.0) as underlying HSM, where I have a secret AES key (256 bit) stored on a token. Encryption and Decryption works so far with the default mechanism AES_CBC_PAD.

But if I want to use the MAC functionality I got problems with the regarding mechanism. The docu says that AES_MAC is used by default. But softhsmv2 does not offer it. If I print the list of the provided mechanisms I got some like "SHA256_HMAC" etc. but not AES_MAC. When I use SHA256_HMAC with my 256 bit AES key, I get an KeyTypeInconsistent exception. If I use AES_MAC then it says MechanismInvalid.

How can I achieve signing/MAC-creation?

Thank you!

C_Login can fail with CKR_USER_ALREADY_LOGGED_IN

This happens fairly reliably if, within a loop that looks like this:

while True:
  try:
    with pkcs11lib.get_token(/**/).open(/**/) as session:
      key = session.get_key(/**/)
      while True:
        key.sign(/**/)
  except Exception:
    pass

you put the client (Mac in my case) computer to sleep while running an Amphetamine session or equivalent.

I don't think this is a common issue but when it does happen it may be good to workaround the issue gracefully.

pip install fails

Hello,
When installing v0.4.0 on CentOS 7 with python 3.4 (from epel), the procedure fails with the message:

Collecting python-pkcs11
Using cached python-pkcs11-0.4.0.tar.gz
Complete output from command python setup.py egg_info:
Compiling /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Plex/Scanners.py because it changed.
Compiling /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Plex/Actions.py because it changed.
Compiling /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Compiler/Pythran.py because it changed.
Compiling /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Compiler/Lexicon.py because it changed.
Compiling /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Compiler/Scanning.py because it changed.
Compiling /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Compiler/Parsing.py because it changed.
Compiling /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Compiler/Visitor.py because it changed.
Compiling /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Compiler/FlowControl.py because it changed.
Compiling /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Compiler/Code.py because it changed.
Compiling /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Runtime/refnanny.pyx because it changed.
Compiling /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Tempita/_tempita.py because it changed.
[ 1/11] Cythonizing /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Compiler/Code.py
[ 2/11] Cythonizing /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Compiler/FlowControl.py
[ 3/11] Cythonizing /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Compiler/Lexicon.py
[ 4/11] Cythonizing /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Compiler/Parsing.py
[ 5/11] Cythonizing /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Compiler/Pythran.py
[ 6/11] Cythonizing /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Compiler/Scanning.py
[ 7/11] Cythonizing /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Compiler/Visitor.py
[ 8/11] Cythonizing /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Plex/Actions.py
[ 9/11] Cythonizing /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Plex/Scanners.py
[10/11] Cythonizing /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Runtime/refnanny.pyx
[11/11] Cythonizing /tmp/easy_install-a9ozvf88/Cython-0.27.1/Cython/Tempita/_tempita.py
Unable to find pgen, not compiling formal grammar.
warning: no files found matching '2to3-fixers.txt'
warning: no files found matching 'Doc/'
warning: no files found matching '
.pyx' under directory 'Cython/Debugger/Tests'
warning: no files found matching '.pxd' under directory 'Cython/Debugger/Tests'
warning: no files found matching '
.pxd' under directory 'Cython/Utility'

Installed /tmp/pip-build-4xbb9fkr/python-pkcs11/.eggs/Cython-0.27.1-py3.4-linux-x86_64.egg
error in python-pkcs11 setup command: 'install_requires' must be a string or list of strings containing valid project/version requirement specifiers; Expected version spec in aenum; python_version < "3.6" at ; python_version < "3.6"

----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-4xbb9fkr/python-pkcs11/

Segmentation fault (core dumped) public.verify(data, signature)

When trying to verify the signature, it throws segmentation fault error. Any ideas?

try:
for token in lib.get_tokens():
if token.serial.decode() == serial:
with token.open(user_pin=pin) as session:
priv = session.get_key(object_class=pkcs11.constants.ObjectClass.PRIVATE_KEY)
pub = session.get_key(object_class=pkcs11.constants.ObjectClass.PUBLIC_KEY)
data = token.serial.decode()
signature = priv.sign(data, mechanism=pkcs11.Mechanism.SHA256_RSA_PKCS)
print(pub.verify(data, signature))
except TokenNotPresent:
pass

RFE: option to delete False attrs from C_UnwrapKey template

RFE: an option in UnwrapMixin::unwrap_key to del out False attrs from template_

I have encountered a HSM (Gemalto SafeNet) that does not like the template (with AttributeTypeInvalid) for C_UnwrapKey of an RSA/ECDSA private key,
even if the irrelevant attrs are set to False (but are present in the template)

E.g. Attempt to unwrap a private key onto the HSM so
Attribute.ENCRYPT: False, Attribute: WRAP: False, Attribute: VERIFY: False

This doesn't work - returns CKR_ATTRIBUTE_TYPE_INVALID

What works is that the to-be-False attrs are omitted from the template.

N.B. Tracing Gemalto's own tools, that successfully import private keys by C_UnwrapKey-ing them,
the template used does not contain the attrs(ENCRYPT, WRAP, VERIFY).

# RFE: need a strip_false option
class UnwrapMixin(types.UnwrapMixin):
    def unwrap_key(self, object_class, key_type, key_data,
                   id=None, label=None,
                   mechanism=None, mechanism_param=None,
                   store=False, capabilities=None,
                   strip_false=False
                   template=None)

# then later in the method, need something like...
    if strip_false:
        for k in [
            Attribute.ENCRYPT,
            Attribute.DECRYPT,
            Attribute.WRAP,
            Attribute.UNWRAP,
            Attribute.SIGN,
            Attribute.VERIFY,
            Attribute.DERIVE,]:
            if not template_[k]:
                del template_[k]
# default template from _pkcs11.pyx
# too many attributes; even if they are set to False
# SafeNet does not like this template when doing C_UnwrapKey
# of a asymmetric private key(RSA/ECDSA) onto the HSM
template_ = {
            Attribute.CLASS: object_class,
            Attribute.KEY_TYPE: key_type,
            Attribute.ID: id or b'',
            Attribute.LABEL: label or '',
            Attribute.TOKEN: store,
            # Capabilities
            Attribute.ENCRYPT: MechanismFlag.ENCRYPT & capabilities,
            Attribute.DECRYPT: MechanismFlag.DECRYPT & capabilities,
            Attribute.WRAP: MechanismFlag.WRAP & capabilities,
            Attribute.UNWRAP: MechanismFlag.UNWRAP & capabilities,
            Attribute.SIGN: MechanismFlag.SIGN & capabilities,
            Attribute.VERIFY: MechanismFlag.VERIFY & capabilities,
            Attribute.DERIVE: MechanismFlag.DERIVE & capabilities,
        }

CKR_ARGUMENTS_BAD after destroying item inside get_objects

I've noticed a pattern: that if I delete a key inside of a get_objects iteration and I have other keys, it hangs for a long time and then I get CKR_ARGUMENTS_BAD from C_FindObjects. I'm using CloudHSM which doesn't support many pkcs11 features, but I suspect this issue may also happen on other products.

Here is an excerpt from a unit test failure stacktrace:

/lib/hsm.py:165: in delete_key
    for public_obj in session.get_objects(PUBLIC_KEY_OBJECTS_FILTER):
pkcs11/_pkcs11.pyx:275: in pkcs11._pkcs11.SearchIter.__next__
    ???
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

>   ???
E   pkcs11.exceptions.ArgumentsBad

pkcs11/_errors.pyx:88: ArgumentsBad

AES_KEY_WRAP mechanism not usable

AES_KEY_WRAP is defined as an available mechanism, however the following code around line 1007 seems to ignore the mechanism passed in, and use the default wrap (CBC) instead. AWS cloudhsm does not support cbc for key wrapping, so the method fails with 'invalid mechanism' returned.

mech = MechanismWithParam(
self.key_type, DEFAULT_WRAP_MECHANISMS,
mechanism, mechanism_param)

(refer https://docs.aws.amazon.com/cloudhsm/latest/userguide/pkcs11-library.html for supported mechanisms). i think it is not only aws; new hsm's are using the newer mechanism for wrapping.

Question about load the token driver

Hi,
Congratulations for your work. I started studying Python a few weeks ago.
I've used the PyKCS11 package successfully, but I'm interested in studying your package.
Please, I need help about loading the token driver, in snippet below:

import pkcs11
lib = pkcs11.lib("/usr/lib64/libaetpkss.so.3")

It is being reported:

Traceback (most recent call last):
File "/home/falf/eclipse-workspace/MyProject/FindingTokens.py", line 6, in
lib = pkcs11.lib("/usr/lib64/libaetpkss.so.3")
File "/usr/lib64/python2.7/site-packages/pkcs11/init.py", line 36, in lib
_lib = _pkcs11.lib(so)
File "pkcs11/_pkcs11.pyx", line 1179, in pkcs11._pkcs11.lib.init
TypeError: Expected str, got unicode

Sorry if I posted my question in a wrong place. I am using Python 2.7 on centos 7.
Have you have any ideas?

Thank you,
Francisco

Install through pip3 fails

Installation through pip3 does not work (for me).

Platform Linux, Debian Testing
Python 3.6

I use pipenv here but the error occurs without pipenv as well:

jule@tyche:~/Work/crypto/pypkcs11$ pipenv --three install pkcs11
Creating a virtualenv for this project…
Using /usr/bin/python3 (3.6.5) to create virtualenv…
⠋Already using interpreter /usr/bin/python3
Using base prefix '/usr'
New python executable in /home/jule/.local/share/virtualenvs/pypkcs11-DGgHC4vZ/bin/python3
Also creating executable in /home/jule/.local/share/virtualenvs/pypkcs11-DGgHC4vZ/bin/python
Installing setuptools, pip, wheel...done.

Virtualenv location: /home/jule/.local/share/virtualenvs/pypkcs11-DGgHC4vZ
Creating a Pipfile for this project…
Installing pkcs11…
Collecting pkcs11
  Using cached https://files.pythonhosted.org/packages/37/0c/a5244429b0376660fb6267ad02515cbfc3e171bc5d493410d7d5d7f79d42/pkcs11-1.0.4.zip
Building wheels for collected packages: pkcs11
  Running setup.py bdist_wheel for pkcs11: started
  Running setup.py bdist_wheel for pkcs11: finished with status 'error'
  Complete output from command /home/jule/.local/share/virtualenvs/pypkcs11-DGgHC4vZ/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-0s5hihx6/pkcs11/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-io4xab45 --python-tag cp36:
  running bdist_wheel
  running build
  running build_ext
  building 'pkcs11' extension
  error: unknown file type '.rc' (from 'pkcs11.rc')

get_objects() issue

Hello. I have a question about get_objects() returning weird results. I've been searching for a specific public key using label.

first I tried this:

        for obj in session.get_objects({
                                        Attribute.KEY_TYPE: KeyType.RSA,
                                        Attribute.LABEL: 'ae663880619aced7'}):

This will return both the private key and the public key. I get the same result if I exclude the KEY_TYPE attribute from the search.

then I tried:

        for obj in session.get_objects({Attribute.CLASS: ObjectClass.PUBLIC_KEY,
                                        Attribute.LABEL: 'ae663880619aced7'}):

This seems to hang and return the same key multiple times, thus if I tried the same attributes on get_key() it would fail with MultipleObjectsReturned even though there is only one key.

I've looked at the code and it seems this whole handling happens in the C pkcs11 library and has nothing to do with this python-pkcs11 library right?

ECDSA Example code fails with CKR_TEMPLATE_INCOMPLETE

I've taken a modified version of the example code for ECDSA:

#!/usr/bin/python3
import pkcs11
from pkcs11 import util
from pkcs11.util import ec

lib = pkcs11.lib("/usr/lib/softhsm/libsofthsm2.so")
token = lib.get_token(token_label='test')
data = b'INPUT DATA'

# Open a session on our token
with token.open(user_pin='1234') as session:
    # Generate an EC keypair in this session from a named curve
    ecparams = session.create_domain_parameters(pkcs11.KeyType.EC, {pkcs11.Attribute: pkcs11.util.ec.encode_named_curve_parameters('secp256r1'),}, local=True)
    pub, priv = ecparams.generate_keypair()
    # Sign
    signature = priv.sign(data)

And running this fails with:

Traceback (most recent call last):
  File "./ecdsa.py", line 14, in <module>
    pub, priv = ecparams.generate_keypair()
  File "pkcs11/_pkcs11.pyx", line 720, in pkcs11._pkcs11.DomainParameters.generate_keypair
  File "pkcs11/_errors.pyx", line 88, in pkcs11._pkcs11.assertRV
pkcs11.exceptions.TemplateIncomplete

Python 3.6.8 using v0.5 of this library with softhsm v2.5.0.

What am I missing?

pip install fails

Hello all,

I tried to install the python-pkcs11 package into my Anaconda 3 environment, but was not able to finalize this task. I did make some progress with all the errors, I was facing, but got stuck at a certain point.

I am using Anaconda 3 as 64 bit version on a Windows 7 that is installed on a HP laptop with an i5 CPU.

Due to the fact that the compilation failed, I installed first the recommended Visual Studio Builder Tools, but this did not help, so that I at the end installed the full visual studio 2019 environment.

But even with this the installation fails with the error:

pkcs11_loader.c(596): fatal error C1083: Datei (Include) kann nicht ge"ffnet werden: "dlfcn.h": No such file or directory

Attached you will find what the console-output told me during the installation in verbose mode.

pip-installation-output.txt

Could you please tell me, how I can solve the issue, so that the package will be installed?

Kind regards,
Manfred

ECDSA Example

Hi, I'm just starting out with this library, so I apologize if I've missed something blatantly obvious!

My environment is Windows running against SoftHSMv2.

I was trying to use the example for ECDSA , and I was getting an error that prime256v1 is not in the dictionary. It looks as though this key was removed in the asn1crypto library a while ago ( changes ), is the example code out of date? I tried replacing prime256v1 with secp256r1 and got past that line of code but failed out with other errors, so I wasn't sure what the correct solution was. I was able to run the RSA example fine, so my setup seems reasonably correct.

TokenNotRecognized

Hi. I known that in requirements that python version must be < 3.6.
However, thanks to https://github.com/joernheissler/cryptokey, I've changed the CertificateListBuilder.build() to make the signature works with pkcs11 device. In order to do this, I had to use cryptokey and python 3.7.0.
However I have a pkcs11 session working in a Debian Strech 9.8 64 bits and the other token, same model, same python 3.7.0 version, throwing TokenNotRecognized exception in a Ubuntu 16.04 LTS 64 bits.
Here are the requirements installed:
asn1crypto==0.24.0
cached-property==1.5.1
certifi==2018.11.29
cffi==1.12.2
chardet==3.0.4
configobj==5.0.6
cryptography==2.6
idna==2.8
oscrypto==0.19.1
pycparser==2.19
pyOpenSSL==19.0.0
python-dateutil==2.8.0
python-pkcs11==0.5.0
requests==2.21.0
six==1.12.0
Unidecode==1.0.23
urllib3==1.24.1

What could I do to try to make it works in python 3.7.0?

pip install fails on CYGWIN

ld fails :

gcc -shared -Wl,--enable-auto-image-base -L. build/temp.cygwin-2.11.2-x86_64-2.7/pkcs11/_pkcs11.o -L/usr/lib/python2.7/config -L/usr/lib -lpython2.7 -o build/lib.cygwin-2.11.2-x86_64-2.7/pkcs11/_pkcs11.dll
build/temp.cygwin-2.11.2-x86_64-2.7/pkcs11/_pkcs11.o : Dans la fonction « pyx_pf_6pkcs11_7_pkcs11_3lib_15__dealloc » :
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:24855 : référence indéfinie vers « C_Finalize »
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:24855:(.text+0x22cd3): relocalisation tronquée pour concorder avec la taille : R_X86_64_PC32 vers le symbole indéfini C_Finalize
build/temp.cygwin-2.11.2-x86_64-2.7/pkcs11/_pkcs11.o : Dans la fonction « __pyx_pf_6pkcs11_7_pkcs11_11UnwrapMixin_unwrap_key » :
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:21464 : référence indéfinie vers « C_UnwrapKey »
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:21464:(.text+0x2445e): relocalisation tronquée pour concorder avec la taille : R_X86_64_PC32 vers le symbole indéfini C_UnwrapKey
build/temp.cygwin-2.11.2-x86_64-2.7/pkcs11/_pkcs11.o : Dans la fonction « __pyx_pf_6pkcs11_7_pkcs11_6Object_8destroy » :
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:14071 : référence indéfinie vers « C_DestroyObject »
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:14071:(.text+0x267f8): relocalisation tronquée pour concorder avec la taille : R_X86_64_PC32 vers le symbole indéfini C_DestroyObject
build/temp.cygwin-2.11.2-x86_64-2.7/pkcs11/_pkcs11.o : Dans la fonction « pyx_pf_6pkcs11_7_pkcs11_6Object_4__setitem » :
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:13773 : référence indéfinie vers « C_SetAttributeValue »
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:13773:(.text+0x26fc2): relocalisation tronquée pour concorder avec la taille : R_X86_64_PC32 vers le symbole indéfini C_SetAttributeValue
build/temp.cygwin-2.11.2-x86_64-2.7/pkcs11/_pkcs11.o : Dans la fonction « __pyx_pf_6pkcs11_7_pkcs11_7Session_16generate_random » :
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:11547 : référence indéfinie vers « C_GenerateRandom »
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:11547:(.text+0x283ea): relocalisation tronquée pour concorder avec la taille : R_X86_64_PC32 vers le symbole indéfini C_GenerateRandom
build/temp.cygwin-2.11.2-x86_64-2.7/pkcs11/_pkcs11.o : Dans la fonction « __pyx_pf_6pkcs11_7_pkcs11_7Session_14seed_random » :
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:11393 : référence indéfinie vers « C_SeedRandom »
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:11393:(.text+0x29253): relocalisation tronquée pour concorder avec la taille : R_X86_64_PC32 vers le symbole indéfini C_SeedRandom
build/temp.cygwin-2.11.2-x86_64-2.7/pkcs11/_pkcs11.o : Dans la fonction « __pyx_pf_6pkcs11_7_pkcs11_7Session_12_generate_keypair » :
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:11128 : référence indéfinie vers « C_GenerateKeyPair »
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:11128:(.text+0x2b304): relocalisation tronquée pour concorder avec la taille : R_X86_64_PC32 vers le symbole indéfini C_GenerateKeyPair
build/temp.cygwin-2.11.2-x86_64-2.7/pkcs11/_pkcs11.o : Dans la fonction « __pyx_pf_6pkcs11_7_pkcs11_7Session_10generate_key » :
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:9840 : référence indéfinie vers « C_GenerateKey »
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:9840:(.text+0x2fb63): relocalisation tronquée pour concorder avec la taille : R_X86_64_PC32 vers le symbole indéfini C_GenerateKey
build/temp.cygwin-2.11.2-x86_64-2.7/pkcs11/_pkcs11.o : Dans la fonction « __pyx_pf_6pkcs11_7_pkcs11_7Session_4create_object » :
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:7890 : référence indéfinie vers « C_CreateObject »
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:7890:(.text+0x31f8f): relocalisation tronquée pour concorder avec la taille : R_X86_64_PC32 vers le symbole indéfini C_CreateObject
build/temp.cygwin-2.11.2-x86_64-2.7/pkcs11/_pkcs11.o : Dans la fonction « __pyx_pf_6pkcs11_7_pkcs11_7Session_close » :
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:7546 : référence indéfinie vers « C_Logout »
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:7546:(.text+0x32ca2): relocalisation tronquée pour concorder avec la taille : R_X86_64_PC32 vers le symbole indéfini C_Logout
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:7568 : référence indéfinie vers « C_CloseSession »
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:7568:(.text+0x32d23): débordement de relocalisation additionnelle omise à partir de la sortie
build/temp.cygwin-2.11.2-x86_64-2.7/pkcs11/_pkcs11.o : Dans la fonction « __pyx_pf_6pkcs11_7_pkcs11_10SearchIter_8_finalize » :
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:7413 : référence indéfinie vers « C_FindObjectsFinal »
build/temp.cygwin-2.11.2-x86_64-2.7/pkcs11/_pkcs11.o : Dans la fonction « __pyx_pf_6pkcs11_7_pkcs11_4Slot_4get_mechanism_info » :
/tmp/pip-install-GnPBKp/python-pkcs11/pkcs11/_pkcs11.c:6300 : référence indéfinie vers « C_GetMechanismInfo »
build/temp.cygwin-2.11.2-x86_64-2.7/pkcs11/_pkcs11.o : Dans la fonction « __pyx_pf_6pkcs11_7_pkcs11_4Slot_get_token » :

AES operations on Nitrokey Pro 2

Is there anyone who tested AES encryption/decryption on Nitrokey Pro 2 using python-pkcs11?

I'm aware it's written N/A on Python-PKCS#11 compatibility table but here it is written that Nitrokey pro 2 is in fact a OpenPGP Card v3.3 and the specification state AES operations on pages 57-60. I believe it should work. I'm able to do it on softhsm but I would like to know whether it's possible before investing in the product.

Cannot load OpenSC PKCS#11 Library on Ubuntu 16.04

I am using OpenSC's PKCS#11 as the .so file that I pass into pkcs11.lib to setup python-pkcs11. I get the following error:

>>> pkcs11.lib(os.environ['PKCS11_MODULE'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/python_pkcs11-0.5.0-py3.5-linux-x86_64.egg/pkcs11/__init__.py", line 34, in lib
    from . import _pkcs11
ImportError: /usr/local/lib/python3.5/dist-packages/python_pkcs11-0.5.0-py3.5-linux-x86_64.egg/pkcs11/_pkcs11.cpython-35m-x86_64-linux-gnu.so: undefined symbol: C_UnwrapKey

Is this an OpenSC problem, or a problem with the python-pkcs11 module? I also tried loading OpenSC's module using python-pkcs11 on my Mac instead of Ubuntu and it worked fine.

Token not present (after reboot it becomes present?)

Hi everyone, it's happening something a bit weird.

uname -a
Linux waffle 4.4.0-127-generic #153-Ubuntu SMP Sat May 19 10:58:46 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

Distributor ID: Ubuntu
Description: Ubuntu 16.04.4 LTS
Release: 16.04
Codename: xenial

lsusb
Bus 001 Device 002: ID 8087:8000 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 002 Device 007: ID 22b8:2e82 Motorola PCS
Bus 002 Device 004: ID 0a5c:5801 Broadcom Corp. BCM5880 Secure Applications Processor with fingerprint swipe sensor
Bus 002 Device 003: ID 0c45:64d2 Microdia
Bus 002 Device 002: ID 093a:2521 Pixart Imaging, Inc. Optical Mouse
Bus 002 Device 008: ID 0529:0620 Aladdin Knowledge Systems Token JC
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

import pkcs11
from pkcs11.exceptions import TokenNotPresent
lib = pkcs11.lib('/usr/lib/libeToken.so.9')
try:
for token in lib.get_tokens():
print(
'Label: {}\nSerial: {}\nFabricante: {}\nModelo: {}\nVersão do Hardware: {}\nVersão do Firmware: {}\nFlags: {}'.format(
token.label, token.serial.decode(), token.manufacturer_id, token.model,
token.hardware_version,
token.firmware_version, token.flags))
except TokenNotPresent:
pass

The above code works only after a reboot with the USB eToken connected. Something magically happens after the reboot that make it works. I tried to rmmod and modprobe some modules, unsuccessfully.

Any ideas?

Problems with Mechanism during MAC operations

Hi,
I'm using softhsmv2 (2.3.0) as the underlying HSM. I want to use a symmetric key that is stored in the HSM to create a HMAC for a hash value (binary format).
If I do the following:
aes_key_handle.sign(hashed_data, mechanism=pkcs11.Mechanism.SHA256_HMAC)
I get a KeyTypeInconsistent exception.
If I do the following:
aes_key_handle.sign(hashed_data)
I get a MechanismInvalid exception.

The mechanism SHA256_HMAC is supported by the HSM (shown via slot.get_mechanisms()).
I'm using the current version (0.5.0) of python-pkcs11 together with python3.

Can you tell want went wrong or where the error is?

Thank you very much for your help and your great lib!

No sign method created on imported private key object

Playing with signing with imported DER private key, and the object returned from create_object() contains no sign method.

with token.open(rw=True, user_pin=os.environ['PIN']) as session:
        pk = ec.decode_ec_private_key(data)
        pk[Attribute.LABEL] = label
        pk[Attribute.TOKEN] = True
        pk[Attribute.SIGN] = True
        obj = session.create_object(pk)
        der_sig = obj.sign(data) # Fails here

Fails with AttributeError: 'PrivateKey' object has no attribute '_sign'

It looks like for some reason the SignMixin does not get added to the object type on construction and I am not really sure why.

The incoming pk also has attributes ObjectClass, Value, KEY_TYPE

I know I should just generate keypairs on the HSM instead, but I am trying to compare HSM signing R/S values to another signing.

Any ideas here?

Session cannot be closed

Hi,
if I want to close an active Session with session.close(), then I get the following error:

session.close()
File "/var/valkyrie/pkcs11-test/lib/python3.5/site-packages/pkcs11/types.py", line 273, in exit
self.close()
File "pkcs11/_pkcs11.pyx", line 290, in pkcs11._pkcs11.Session.close
File "pkcs11/_errors.pyx", line 88, in pkcs11._pkcs11.assertRV
pkcs11.exceptions.SessionHandleInvalid

I'm using softhsm 2.3.0 as HSM.

Thanks!

ValueError exception on lib.getToken call

Hi !
While giving a try with your library, I encounter a valueError with this code :

import pkcs11
lib = pkcs11.lib('/opt/tw_proteccio/lib/libnethsm.so')
token = lib.get_token(token_label='test_equity')

Witch give me :

Traceback (most recent call last):
  File "aes.py", line 6, in <module>
    token = lib.get_token(token_label='test_equity')
  File "pkcs11/_pkcs11.pyx", line 1248, in pkcs11._pkcs11.lib.get_token (pkcs11/_pkcs11.c:24462)
  File "pkcs11/_pkcs11.pyx", line 1211, in get_tokens (pkcs11/_pkcs11.c:23758)
  File "pkcs11/_pkcs11.pyx", line 188, in pkcs11._pkcs11.Slot.get_mechanisms (pkcs11/_pkcs11.c:6010)
  File "pkcs11/_utils.pyx", line 18, in pkcs11._pkcs11.CK_ULONG_buffer (pkcs11/_pkcs11.c:3371)
  File "stringsource", line 151, in View.MemoryView.array.__cinit__ (pkcs11/_pkcs11.c:25089)
ValueError: Invalid shape in axis 0: 0.

wheel packages

New windows support sounds great so maybe wheel packages help to user to install faster and without compiler this lib.
There is a lot of packages supporting wheels binaries and could be great if no compilation required to have this app (specially on windows).

Nice work.

TypeError: Expected str, got unicode

Platform : MacOS
python 2.7

Code which gives errors:

from pkcs11 import Attribute,KeyType,lib ,Slot,ObjectClass
import os

Initialise our PKCS#11 library

lib = lib(str(os.environ['PKCS11_MODULE']))

error:

/usr/local/bin/python2.7 /client.py
Traceback (most recent call last):
File "/Users/roboguru/learnpython/softhsm/client.py", line 5, in
lib = lib(str(os.environ['PKCS11_MODULE']))
File "/usr/local/lib/python2.7/site-packages/pkcs11/init.py", line 36, in lib
_lib = _pkcs11.lib(so)
File "pkcs11/_pkcs11.pyx", line 1169, in pkcs11._pkcs11.lib.init (pkcs11/_pkcs11.c:22662)
TypeError: Expected str, got unicode

CloudHSM Support

Hi! I'm wondering if there is a project to add CloudHSM on the list of supported devices. I can help with the implementation.

Please tag this as feature request!

VALUE_LEN throws exception when creating ObjectClass.SECRET_KEY and KeyType.AES (softhsm2)

Using softhsm2, below code gives AttributeReadOnly exception. However, it creates an AES object on softhsm2 but it does not correctly label or set defined capabilities. I'm not sure if the key inside VALUE is written correctly.

The cause of this problem, at least I believe, is VALUE_LEN attribute. When commented out it creates object without any exceptions with correct capabilities, label, and etc.

My key was 256 bits. I've also tried hardcoded 32 VALUE_LEN.

attrs = {
    pkcs11.Attribute.CLASS: pkcs11.ObjectClass.SECRET_KEY,
    pkcs11.Attribute.KEY_TYPE: pkcs11.KeyType.AES,
    pkcs11.Attribute.TOKEN: True,
    pkcs11.Attribute.SENSITIVE: True,
    pkcs11.Attribute.ENCRYPT: True,
    pkcs11.Attribute.DECRYPT: False,
    pkcs11.Attribute.WRAP: False,
    pkcs11.Attribute.UNWRAP: False,
    pkcs11.Attribute.SIGN: False,
    pkcs11.Attribute.VERIFY: False,
    pkcs11.Attribute.EXTRACTABLE: False,
    pkcs11.Attribute.VALUE_LEN: len(key),
    pkcs11.Attribute.DERIVE: False,
    pkcs11.Attribute.LABEL: label,
    pkcs11.Attribute.VALUE: key
}

key = session.create_object(attrs)

Verify signature with third-party?

Hi everyone. I'm building a client side application, that gets, for each connected token, it's serial number, and use it as data for signing. Then, it sends a POST request to a Django view, that verifies the signature. Since (I think) there is no way to pass the pkcs11 public key object to Django via POST, I can't use the public key .verify() method.

So, I'm stuck on trying to find out a way to verify the signature. I've concluded that the problem is in the difference between the mechanisms used for signing and verify the data.

Is there a way to instantiate a pkcs11.PublicKey from a PEM encoded data from the database? If so, maybe it's possible to use the .verify() function and use the same mechanism,

I couldn't find a way to use the same mechanisms. Any ideas?

from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256


    def _verifyToken(public_key, signature, token_serial):
        '''
        Verifies with a public key from whom the data came that it was indeed
        signed by their private key
        param: public_key_loc Path to public key
        param: signature String signature to be verified
        return: Boolean. True if the signature is valid; False otherwise.
        '''
        rsakey = RSA.importKey(public_key)
        signer = PKCS1_v1_5.new(rsakey)
        digest = SHA256.new()
        digest.update(token_serial.encode())
        if signer.verify(digest, signature):
            return True
        return False

    def _geraSerialTokenAssinado(serial, pin):
        try:
            for token in lib.get_tokens():
                if token.serial.decode() == serial:
                    with token.open(user_pin=pin) as session:
                        priv = session.get_key(object_class=pkcs11.constants.ObjectClass.PRIVATE_KEY)
                        pub = session.get_key(object_class=pkcs11.constants.ObjectClass.PUBLIC_KEY)
                        pem_pub_bytes = pem.armor('RSA PUBLIC KEY', encode_rsa_public_key(pub))
                        data = token.serial.decode()
                        signature = priv.sign(data, mechanism=pkcs11.Mechanism.SHA256_RSA_PKCS)
                        print('Verify:', _verifyToken(pem_pub_bytes.decode(),signature,'1234'))

                        return {'token_serial':data, 'signature':signature, 'public_key':pem_pub_bytes}
        except TokenNotPresent:
            pass

Change PIN

Its not a real critical feature, but it would be nice if future versions provide the possibility to change the USER-PIN of a token. Thank you!

Derive pubkey from certificate object

Hi everyone,
In the get_objects() I have:

<__main__.Certificate object at 0x7fc905a44b38>
<__main__.Certificate object at 0x7fc905a44b70>
<__main__.Certificate object at 0x7fc905a44b38>
<__main__.Certificate object at 0x7fc905a44b70>
<__main__.Certificate object at 0x7fc905a44b38>
<__main__.Certificate object at 0x7fc905a44b70>
<PrivateKey label='' id='971e4cc5936ddccc' 2048-bit RSA>
<__main__.Certificate object at 0x7fc905a44b70>

So, when I run:


                            try:
                                pub = encode_rsa_public_key(session.get_key(object_class=pkcs11.constants.ObjectClass.PUBLIC_KEY))

                            except pkcs11.MultipleObjectsReturned:
                                for i in session.get_objects({Attribute.CLASS: pkcs11.constants.ObjectClass.PUBLIC_KEY}):
                                    pub = encode_rsa_public_key(i)
                                    break

I fall into NoSuchKey
So I tried

                            except pkcs11.exceptions.NoSuchKey:
                                cert2 = x509.load_pem_x509_certificate(pem.armor('CERTIFICATE', der_bytes),default_backend())
                                pubdata = cert2.public_key().public_bytes(cryptography.hazmat.primitives.serialization.Encoding.DER,cryptography.hazmat.primitives.serialization.PublicFormat.SubjectPublicKeyInfo)
                                pub = pem.armor('RSA PUBLIC KEY', pubdata)

If I use this second one way, I don't know how to adjust the public_key below:

 tbs = TbsCertificate({
                                'version': Version(1),
                                'serial_number': int(SERIAL),
                                'issuer': Name.build({
                                    'common_name': EEA_COMMON_NAME,
                                }),
                                'subject': Name.build({
                                    'common_name': COMMON_NAME,
                                }),
                                'signature': {
                                    'algorithm': signed_digest_algo,
                                    'parameters': None,
                                },
                                'extensions': (extensions_tuple),

                                'validity': {
                                    'not_before': Time({
                                        'general_time': GeneralizedTime(parser.parse(NOT_VALID_BEFORE)),
                                    }),
                                    'not_after': Time({
                                        'general_time': GeneralizedTime(parser.parse(NOT_VALID_AFTER)),
                                    }),
                                },
                                'subject_public_key_info': {
                                    'algorithm': {
                                        'algorithm': 'rsa',
                                        'parameters': None,
                                    },
                                    # 'public_key': RSAPublicKey.load(encode_rsa_public_key(pub)),
                                    'public_key': RSAPublicKey.load(pub),
                                }
                            })

If I let 'public_key': RSAPublicKey.load(pub) I get:

File "/root/sigcerta/.virtualenv/lib/python3.5/site-packages/asn1crypto/core.py", line 5144, in _build
    tag
ValueError: Error parsing asn1crypto.keys.RSAPublicKey - tag should have been 16, but 13 was found

If I let 'public_key': RSAPublicKey.load(encode_rsa_public_key(pub)) I get:

File "/root/sigcerta/.virtualenv/lib/python3.5/site-packages/pkcs11/util/rsa.py", line 77, in encode_rsa_public_key
    'modulus': int.from_bytes(key[Attribute.MODULUS], byteorder='big'),
TypeError: 'int' object is not iterable

Segmentation fault with SafeNet/Gemalto IDPrime MD 830 B

smartcards/test.py

import pkcs11


def main():
  """ Entry point """
  # Initialise the PKCS#11 library
  print 'Attempting to load PKCS#11 module'
  lib = pkcs11.lib('/usr/lib64/libIDPrimePKCS11.so')
  print 'Library loaded'


if __name__ == '__main__':
  main()

Running the script produces a segfault

(venv) [cerealkiller@thegibson Dev]$ python smartcards/test.py
Attempting to load PKCS#11 module
Segmentation fault (core dumped)

PIP information

(venv) [cerealkiller@thegibson Dev]$ pip --version
pip 10.0.1 from /home/cerealkiller/Desktop/Dev/venv/lib/python2.7/site-packages/pip (python 2.7)
(venv) [cerealkiller@thegibson Dev]$ pip show python-pkcs11
Name: python-pkcs11
Version: 0.5.0
Summary: PKCS#11 (Cryptoki) support for Python
Home-page: https://github.com/danni/python-pkcs11
Author: Danielle Madeley
Author-email: [email protected]
License: UNKNOWN
Location: /home/cerealkiller/Desktop/Dev/venv/lib/python2.7/site-packages
Requires: aenum, asn1crypto, cached-property
Required-by: 

Smartcard information
Note, this is using the latest SafeNet Authentication Client (10.0-post-ga for Linux). I use this card daily with many other services / software such as p11tool, OpenSSL, OpenSSH, and web browser for client authentication. This card is not compatible with OpenSC or its kind but I've never seen any other software segfault when using this PKCS#11 module.

(venv) [cerealkiller@thegibson Dev]$ p11tool --list-tokens
...

Token 2:
	URL: pkcs11:model=ID%20Prime%20MD;manufacturer=Gemalto;serial=XXXXXXXXXXXXXX;token=Gemalto%20IDPrime%20830%20B%20%2b%20Mifare%204
	Label: Gemalto IDPrime 830 B + Mifare 4
	Type: Hardware token
	Flags: RNG, Requires login
	Manufacturer: Gemalto
	Model: ID Prime MD
	Serial: XXXXXXXXXXXXXXX
	Module: /usr/lib64/libIDPrimePKCS11.so

I'd be happy to provide traces / OS segfault reports if needed. Thanks in advance!

C_FindObjects not implemented?

Hello,

am I blind or this library doesnt not support finding objects already existing using C_FindObjects pkcs11 native method? :)

It looks like it does not when I checked the code ... Is this an oversight? Could this be changed?

Can I help ?

Thank you

Getting NameError: name 'path' is not defined with python-pkcs11 in windows

I installed latest version of python-pkcs11 in my windows machine. It recently added this feature to install in windows. But I am getting the below error

Traceback (most recent call last):

File "<stdin>", line 1, in <module>
File "C:\Users\Downloads\python-pkcs11-master\pkcs11\__init__.py", line 32, in lib
  _lib = _pkcs11.lib(so)
File "pkcs11\_pkcs11.pyx", line 1235, in pkcs11._pkcs11.lib.__cinit__
  self._load_pkcs11_lib(so)
File "pkcs11\_pkcs11.pyx", line 1200, in 
  pkcs11._pkcs11.lib._load_pkcs11_lib
raise RuntimeError("Cannot open library at {}: {}".format(path, self._winerrormsg()))
NameError: name 'path' is not defined

And my

os.environ['PKCS11_MODULE'] = 'C:\\Windows\\System32\\opensc-pkcs11.dll'

which is correct file path, could you let me know if you can help me with this issue

Windows Support

It would be lovely if I could use this library on Windows, as my driver only comes in dll form.

I'm comfortable with the WinAPI and C, but cython is doing my head in.

Would a potential "easy" fix be using ctypes.dll.LoadLibrary, since that's cross-platform? It seems like there might be some boilerplate behind the scenes to cast function types.

From what I can tell, the current method loads the symbols globally, which makes it "just work". I can't see any reference to the dll itself past the load method.

Problems parsing certificate with x509.decode_x509_certificate

When I parse my DER-encoded certificate with x509.decode_x509_certificate like this.

    from pkcs11.util import x509.decode_x509_certificate
    certs = []
    with token.open() as session:
         for cert in session.get_objects({
                 Attribute.CLASS: ObjectClass.CERTIFICATE}):
              certs.append(decode_x509_certificate(cert[Attribute.VALUE], extended_set=True))

I get this error.
error_parsing_certificate

My certificate is here , and is valid in Costa Rica also is ok if you parsing it with_PyOpenSSL_ or asn1crypto .

RFE: CKA_UNWRAP_TEMPLATE Support

Hi!

Are you able to add support for CKA_UNWRAP_TEMPLATE?

I'd like to generate wrapping keys that cannot be used to bypass CKA_EXTRACTABLE via wrap+unwrap operations.

key = session.generate_key(pkcs11.KeyType.AES, key_length=256, label='ABC1234', store=True, template={
    pkcs11.Attribute.SENSITIVE: True,
    pkcs11.Attribute.EXTRACTABLE: False,
    pkcs11.Attribute.WRAP: True,
    pkcs11.Attribute.UNWRAP: True,
    pkcs11.Attribute.UNWRAP_TEMPLATE: {pkcs11.Attribute.EXTRACTABLE: False},
});

The above code produces:
NotImplementedError: Can't pack this Attribute.UNWRAP_TEMPLATE. Expand ATTRIBUTE_TYPES!

Thanks for the great library!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.