gamringer / php-pkcs11 Goto Github PK
View Code? Open in Web Editor NEWPKCS11 support for PHP
License: Other
PKCS11 support for PHP
License: Other
Hello:
I'm trying to use this module with a propietary pkcs11 provider (bit4id). This driver requires to open a session on a specific slot and create an object like :
$session = $module->openSession(ADMINSLOT , Pkcs11\CKF_RW_SESSION);
$object = $session->createObject([
Pkcs11\CKA_CLASS => Pkcs11\CKO_DATA,
Pkcs11\CKA_TOKEN => true,
Pkcs11\CKA_PRIVATE => true,
Pkcs11\CKA_ID => "login",
Pkcs11\CKA_VALUE => "USER PASS",
]);
When i execute that code i recieve :
Fatal error: Uncaught Pkcs11\Exception: (0x00000082/CKR_OBJECT_HANDLE_INVALID) PKCS#11 module error: Unable to get attribute value in /Users/pemedina/projects/php-pkcs11/index.php:15
Stack trace:
#0 /Users/pemedina/projects/php-pkcs11/index.php(15): Pkcs11\Session->createObject(Array)
The weird thing is: if I enable DEBUG log mode in the driver i can see it connects properly to the HSM, the login is succesfull (it clearly says 200 ok) and the associated certificates are enumerated (due to the DEBUG mode),
but, despite the ok response, the php exception is thrown.
For the records we have a golang wrapper that does the same thing and it works properly (so it is not a driver issue).
I wonder if there's a way to debug this specific exception . Any help will be appreciated.
Both following tests are failing on Ubuntu 20.04.1 with the head of SoftHSM2:
/home/vjardin/bin/bin/softhsm2-util -v
2.6.1
tests/0113-copy-object.sh
object(Pkcs11\P11Object)#3 (0) {
}
Fatal error: Uncaught TypeError: Argument 1 passed to Pkcs11\Session::copyObject() must be an instance of Pkcs11\Object, instance of Pkcs11\P11Object given in php-pkcs11/tests/0113-copy-object.php:18
Stack trace:
#0 php-pkcs11/tests/0113-copy-object.php(18): Pkcs11\Session->copyObject(Object(Pkcs11\P11Object), Array)
#1 {main}
thrown in php-pkcs11/tests/0113-copy-object.php on line 18
tests/0114-destroy-object.sh
object(Pkcs11\P11Object)#3 (0) {
}
array(2) {
[17]=>
string(12) "Hello World!"
[3]=>
string(14) "Original Label"
}
Fatal error: Uncaught TypeError: Argument 1 passed to Pkcs11\Session::destroyObject() must be an instance of Pkcs11\Object, instance of Pkcs11\P11Object given in php-pkcs11/tests/0114-destroy-object.php:24
Stack trace:
#0 php-pkcs11/tests/0114-destroy-object.php(24): Pkcs11\Session->destroyObject(Object(Pkcs11\P11Object))
#1 {main}
thrown in php-pkcs11/tests/0114-destroy-object.php on line 24
Currently, I could not find out why it "passes" with the CI.
Hi there,
I want to sign, but I have the following error Uncaught Pkcs11\Exception: (0x00000101/CKR_USER_NOT_LOGGED_IN).
I successfully login but when I want to sign I have the error.
Likewise, I think it's because I use SafeNet eToken 5110 CC (940) and this key ask me to put pin when I want to sign even if
I login. I try with another key (a gemalto key) and I have not met this bug.
This is related to #31.
When doing something like this (pseudo code):
// function loadModule($path): Module
return new Module($path);
// function openSession($path, $slot, $pin): Session
$module = loadModule($path)
$session = $module->openSession($slot, Pkcs11\CKF_RW_SESSION);
$session->login(Pkcs11\CKU_USER, $pin);
$session->getInfo(); // debug
return $session;
// function getObjects(Session $session)
return $session->findObjects([
Pkcs11\CKA_LABEL => 'My name',
]);
Before the findObjects()
call, the C function pkcs11_shutdown()
is called for the module and upon entering findObjects()
the session functionList
is NULL.
If I put the calls sequentially without functions it does work, so it seems that upon leaving openSession()
somehow the PKCS11 shutdown function is called for the module because it going out of scope. This probably should not happen since the session is still open.
How can we solve this best?
Many tests that uses C_CreateObject() or createObject() fail with a HSM because the HSM does not support the C_CreateObject() OASIS features.
In a few places where parseTemplate() is used, freeTemplate() is only called at the bottom of the function, but if we return early due to a failure, we would leak the memory used by the template.
To be able to control an instance of \Pkcs11\Key
we need to get some attributes from it:
$attributes = $privateKey->getAttributeValue([
\Pkcs11\CKA_PRIVATE,
\Pkcs11\CKA_SIGN,
\Pkcs11\CKA_KEY_TYPE
]);
All of these values are raw bytestrings and it is impossible to compare them with the existing constants. E.g.:
if ($attributes[\Pkcs11\CKA_KEY_TYPE] === \Pkcs11\CKK_RSA) {
...
}
But as the attributes are strings this does not work. Is this an intended behavior or are we missing something?
It is possible to use integer or boolean values when e.g. creating key pairs using the same key constants:
$keypair = $session->generateKeyPair(new Pkcs11\Mechanism(Pkcs11\CKM_RSA_PKCS_KEY_PAIR_GEN), [
Pkcs11\CKA_VERIFY => true,
Pkcs11\CKA_MODULUS_BITS => 2048,
Pkcs11\CKA_PUBLIC_EXPONENT => hex2bin('010001'),
Pkcs11\CKA_LABEL => "Test RSA Public",
],[
Pkcs11\CKA_TOKEN => false,
Pkcs11\CKA_PRIVATE => true,
Pkcs11\CKA_SENSITIVE => true,
Pkcs11\CKA_SIGN => true,
Pkcs11\CKA_LABEL => "Test RSA Private",
]);
Wouldn't it be correct, if these values are also boolean and/or integer values, when they are received back?
If this is an internal issue of how PKCS11 works under the hood, can you share some best practice how to compare these values?
Would this be a correct comparison:
if ($attributes[\Pkcs11\CKA_KEY_TYPE] === pack("P", \Pkcs11\CKK_RSA)) {
...
}
?
Thanks!
Tonight, Guillaume and I had a sync up call (in French :D) in order to target the v1 of this PHP extension:
call_obj_func()
in order to use the models of php_C_xyz() calls so we can get the proper return'd values.object_init_ex()
instead of using a traditional new/constructor approach. However, it leads to some limitations in order to extend these PHP classes. Moreover, some PHP developers may look for the 'traditional' constructors somehow. We'll postpone the support of vanilla constructor (and maybe destructor) after a v1Hi there,
I'm trying to use this extension with the AWS CloudHSM to encrypt/decrypt using the AES-GCM mechanism.
I'm facing an issue during encryption related to the IV.
I'm new to all this but after reading AWS docs many times and trying to understand the code here, it looks to me that it's not compatible because AWS CloudHSM SDK expects the IV of GcmParams to be a "zeroized buffer" and it sets it itself onto the GcmParams object, and this library expects a string for the IV on the \Pkcs11\GcmParams
and set the ulIvLen
based on the given string.
Maybe there is something I'm not doing correctly but right now I end up in those situations:
$iv=random_bytes(12)
on \Pkcs11\GcmParams
and get error from AWS CloudHSM SDK [cloudhsm_pkcs11::encryption::aes_gcm] Iv invalid. Reason: Expect IV to be all 0
$iv
to empty string on \Pkcs11\GcmParams
and get error from AWS CloudHSM SDK [cloudhsm_pkcs11::encryption::aes_gcm] BP000: Expected 'ulIvBits' or 'ulIvLen' to be non-zero
Here are the AWS docs about the mechanism and the way it deals with IV: https://docs.aws.amazon.com/cloudhsm/latest/userguide/pkcs11-mechanisms.html#pkcs11-mech-annotations
Support 4th and 5th arguments of C_OpenSession via a callable argument.
Hello,
Is it possible to compute signatures using this extension? Specifically, I would like to use signed JSON Web Tokens (JWTs) using a key stored on my HSM. I looked through the source but didn't see anything that looked like it would work.
Thanks in advance!
Guillaume,
The test uses SOPIN, but PHP11_PIN is checked from the env:
php-pkcs11/tests/0108-login-so.phpt
Line 18 in 156902b
I could provide a pull request to fix it, but I'd like to check first if you are looking for something specific here ?
Forgive my ignorance. My only experiences with php are using Laravel and Composer to install packages.
How would I use this library in a Laravel project? I don't understand how to pull this code in since it isn't accessible using a package manager.
Again I apologize for the lack of knowledge and appreciate any help provided!
Would love to use this in my Laravel app to communicate with a Thales LunaHSM. As far as I know, they've provided me with all necessary files to interact with one if their hsms. Just not sure how to use this library
I want to export a public key from the token.
I can list and get key as "Pkcs11\Key" and certificates as "Pkcs11\P11Object". Using "getAttributeValue" with the Key doesn't return a "CKA_VALUE".
I could not find any sample code or documentation on how to extract objects on PHP using php-pkcs11.
thank you.
$va = $session->findObjects([ Pkcs11\CKA_LABEL => 'user_keypair', Pkcs11\CKA_CLASS => Pkcs11\CKO_PUBLIC_KEY, Pkcs11\CKA_KEY_TYPE => Pkcs11\CKK_RSA, ]);
var_dump($va);
foreach ($va as $foundObject) {
$attributes = $foundObject->getAttributeValue([
#Pkcs11\CKA_VALUE,
Pkcs11\CKA_LABEL,
]);
var_dump($attributes);
}
As discussed in #17
Doing something like
$foo = new OverloadedKey($session);
instead of
$foo = $session->generateKey(...);
would allow adding extra functionality or overloading methods.
This could be achieved by providing a __construct() method in all objects currently output by factory methods.
Sefault during 3 tests
Encrypt/Decrypt using AES-GCM [tests/0141-sym-encrypt-aes-gcm.phpt]
Encrypt/Decrypt using AES-GCM with update [tests/0145-sym-encrypt-aes-gcm-update.phpt]
Wrapping/Unrapping using RSA OAEP [tests/0165-rsa-encrypt-oaep-wrap.phpt]
Example:
(gdb) bt
#0 0x00007ffff76909d5 in raise () from /lib64/libc.so.6
#1 0x00007ffff76798a4 in abort () from /lib64/libc.so.6
#2 0x00007ffff74a38a8 in std::__replacement_assert(char const*, int, char const*, char const*) () from /usr/lib64/pkcs11/libsofthsm2.so
#3 0x00007ffff74a24e3 in ByteString::operator[](unsigned long) () from /usr/lib64/pkcs11/libsofthsm2.so
#4 0x00007ffff74660e4 in SoftHSM::SymEncryptInit(unsigned long, _CK_MECHANISM*, unsigned long) () from /usr/lib64/pkcs11/libsofthsm2.so
#5 0x00007ffff743ab28 in C_EncryptInit () from /usr/lib64/pkcs11/libsofthsm2.so
#6 0x00007ffff75b6736 in zim_Key_encrypt (execute_data=0x7ffff72143a0, return_value=0x7ffff7214320) at /work/GIT/pecl-and-ext/pkcs11/pkcs11key.c:328
#7 0x00005555559ab408 in ZEND_DO_FCALL_SPEC_RETVAL_USED_HANDLER () at /usr/src/debug/php-7.4.14-1.fc33.remi.x86_64/Zend/zend_vm_execute.h:1730
#8 execute_ex (ex=0x2) at /usr/src/debug/php-7.4.14-1.fc33.remi.x86_64/Zend/zend_vm_execute.h:53865
#9 0x00005555559acc7b in zend_execute (op_array=0x7ffff728a2a0, return_value=0x0) at /usr/src/debug/php-7.4.14-1.fc33.remi.x86_64/Zend/zend_vm_execute.h:57957
#10 0x000055555592349c in zend_execute_scripts (type=type@entry=8, retval=0x7ffff729e7c0, retval@entry=0x0, file_count=-148815840, file_count@entry=3)
at /usr/src/debug/php-7.4.14-1.fc33.remi.x86_64/Zend/zend.c:1679
#11 0x00005555558c0730 in php_execute_script (primary_file=<optimized out>) at /usr/src/debug/php-7.4.14-1.fc33.remi.x86_64/main/main.c:2621
#12 0x00005555559aed7a in do_cli (argc=68, argv=0x555555f75200) at /usr/src/debug/php-7.4.14-1.fc33.remi.x86_64/sapi/cli/php_cli.c:964
#13 0x000055555579042e in main (argc=68, argv=0x555555f75200) at /usr/src/debug/php-7.4.14-1.fc33.remi.x86_64/sapi/cli/php_cli.c:1359
This causes an error:
test.php:
<?php
include 'init.php';
var_dump($session->getInfo());
init.php:
$module = new Pkcs11\Module(getenv('PHP11_MODULE'));
$session = $module->openSession((int)getenv('PHP11_SLOT'), Pkcs11\CKF_RW_SESSION);
But this doesn't:
test.php:
<?php
$module = new Pkcs11\Module(getenv('PHP11_MODULE'));
include 'init.php';
var_dump($session->getInfo());
init.php:
$session = $module->openSession((int)getenv('PHP11_SLOT'), Pkcs11\CKF_RW_SESSION);
Hi team,
Sorry noob in the cryptography area and the whole HSM scenario.
I was just wondering if AWS Cloud HSM is supported.
Thanks
Internal Server Error
(0x00000007/CKR_ARGUMENTS_BAD) PKCS#11 module error: Unable to encrypt [/website/test/app/index/Hsm.php:119]
I use it directly https://github.com/gamringer/php-pkcs11 Address, error reporting.
$iv = random_bytes(16);
$aad = '';
$tagLength = 128;
$gcmParams = new Pkcs11\GcmParams($iv, $aad, $tagLength);
$data = 'Hello World!';
$mechanism = new Pkcs11\Mechanism(Pkcs11\CKM_AES_GCM, $gcmParams);
$ciphertext = $key->encrypt($mechanism, $data);
var_dump(bin2hex($ciphertext));
// string(56) "67940e19213d68c88d163b12d6cd565300f70d693309b5b744085b35"
$plaintext = $key->decrypt($mechanism, $ciphertext);
var_dump($plaintext);
// string(12) "Hello World!"
The encryption and decryption process cannot be used like the instance.
Encryption and decryption can be encrypted and decrypted normally.
However, after the encryption and decryption are separated, the encryption can be, but it cannot be decrypted. All of them fail to decrypt.
We look forward to your reply。
I do not understand this call of getInfo() for the C_GetSessionInfo() method:
Line 741 in 444426c
please, what is the intend ?
TEST 14/14 [tests/0290-oasis_FindObjects.phpt]
========DIFF========
--
int(0)
int(0)
int(%d)
014- dump object 1: %s %d
015- dump DONE
%A
017- dump DONE
int(0)
019- int(0)
OK
========DONE========
FAIL OASIS C_GetAttributeValue(): fetch all [tests/0290-oasis_FindObjects.phpt]
While running the test 0160 with a HSM, we get the following segfault:
Program received signal SIGSEGV, Segmentation fault.
0x000055555582e334 in zend_std_write_property ()
(gdb) bt
#0 0x000055555582e334 in zend_std_write_property ()
#1 0x00005555557fd0be in add_property_zval_ex ()
#2 0x00007ffff56cc13e in zim_Session_generateKeyPair (execute_data=<optimized out>, return_value=0x7ffff5414290)
at php-pkcs11/pkcs11session.c:387
#3 0x0000555555881af5 in execute_ex ()
#4 0x000055555588314b in zend_execute ()
#5 0x00005555557fa1ec in zend_execute_scripts ()
#6 0x0000555555799ed0 in php_execute_script ()
#7 0x0000555555885282 in ?? ()
#8 0x0000555555661938 in ?? ()
#9 0x00007ffff764f0b3 in __libc_start_main (main=0x555555661530, argc=68, argv=0x7fffffffde78, init=<optimized out>, fini=<optimized out>,
rtld_fini=<optimized out>, stack_end=0x7fffffffde68) at ../csu/libc-start.c:308
#10 0x0000555555661ade in _start ()
In pecl tarball, all files have 777 mode, which is not expected
This seems to be a common issue for archive created under windows...
On current master 941f846 using the following logic (pseduo code):
$module = new Pkcs11\Module($path);
// function openSession($path, $slot, $pin): Pkcs11\Session
global $module;
$session = $module->openSession($slot, Pkcs11\CKF_RW_SESSION);
$session->login(Pkcs11\CKU_USER, $pin);
return $session;
// function getKey(Pkcs11\Session $session)
$objects = $session->findObjects([
Pkcs11\CKA_CLASS => Pkcs11\CKO_SECRET_KEY,
Pkcs11\CKA_LABEL => 'My name',
]);
return reset($objects);
// function getMechanism(string $iv): Pkcs11\Mechanism
$gcmParams = new Pkcs11\GcmParams($iv, '', 128);
return new Pkcs11\Mechanism(Pkcs11\CKM_AES_GCM, $gcmParams);
// function encrypt($iv, $data): string
$mechanism = $this->getMechanism($iv);
$session = openSession($path, $slot, $pin);
$key = getKey($session);
return $key->encrypt($mechanism, $data);
// function decrypt($iv, $data): string
$mechanism = $this->getMechanism($iv);
$session = openSession($path, $slot, $pin);
$key = getKey($session);
return $key->decrypt($mechanism, $data);
// main
$iv = openssl_random_pseudo_bytes(16);
$data = 'This is a test';
$encrypted = encrypt($iv, $data);
$decrypted = decrypt($iv, $data);
Results in:
Exception: (0x00000005/CKR_GENERAL_ERROR) PKCS#11 module error: Unable to decrypt
PS: I'm using SoftHSMv2
package.xml states minimal supported version is 7.0.0
But build fails with PHP < 7.4
/builddir/build/BUILD/php-pecl-pkcs11-0.1/NTS/pkcs11object.c:57:54: error: 'ZEND_THIS' undeclared (first use in this function); did you mean 'ZEND_TLS'?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.