phpseclib user cert for tls authetication - x509

Update: I have rewritten the sample code and the CSR is very close to the actual openssl created CSR (only missing the CA:False extended attribute)
I have a CA already and would like to dynamically generate user certs for enrolling authorized devices with phpseclib.
I know the logic is a little cloudy, this code was pieced together from a variety of different examples:
<?php
$USERNAME = "tester";
$DEVICENAME = "command";
$PASSWORD = "test";
$ID = 123;
require_once("config.inc.php"); // Sets defined paths to CA cert and key
require_once("File/X509.php");
require_once("Crypt/RSA.php");
// Setup our CA
$CA = array(); // Store our certificate authority information
$CA["key" ] = new Crypt_RSA();
$CA["key" ]->loadKey( file_get_contents(CAKEY) ); // Load our CA key to sign with
$CA["asciicert" ] = file_get_contents(CACERT);
$CA["cert" ] = new File_X509();
$CA["cert" ]->loadX509( $CA["asciicert"] ); // Load our CA cert and public key
$CA["cert" ]->setPrivateKey($CA["key"]);
// Create a new keypair
$DEVICE = array();
$DEVICE["keys" ] = new Crypt_RSA();
$DEVICE["keypair" ] = $DEVICE["keys"]->createKey(2048);
// Save our private key
$DEVICE["privkey" ] = new Crypt_RSA();
$DEVICE["privkey" ]->loadKey($DEVICE["keypair"]["privatekey"]);
// Save our public key
$DEVICE["pubkey" ] = new Crypt_RSA();
$DEVICE["pubkey" ]->loadKey($DEVICE["keypair"]["publickey"]);
// Create a new CSR
$DEVICE["csr" ] = new File_X509();
$DEVICE["csr" ]->setPrivateKey($DEVICE["privkey"]);
$DEVICE["csr" ]->setPublicKey ($DEVICE["pubkey" ]);
$DEVICE["csr" ]->setDN("C=SS, ST=obscure, L=obscure, O=secure, OU=networksecurity, CN={$USERNAME}#{$DEVICENAME}/emailAddress={$USERNAME}#{$DEVICENAME}");
// Sign the CSR
$DEVICE["signedcsr" ] = $DEVICE["csr"]->signCSR("sha256WithRSAEncryption");
$DEVICE["asciicsr" ] = $DEVICE["csr"]->saveCSR($DEVICE["signedcsr"]);
// Update the CSR with attributes
$DEVICE["cert" ] = new File_X509();
$DEVICE["cert" ]->loadX509( $DEVICE["asciicsr"] ); // Now load it back up so we can set extended attributes
$DEVICE["cert" ]->setPublicKey ($DEVICE["pubkey" ]);
$DEVICE["cert" ]->setStartDate("-1 day"); // Make it valid from yesterday...
$DEVICE["cert" ]->setEndDate("+ 5 years"); // Set a 5 year expiration on all device certs
$DEVICE["cert" ]->setSerialNumber($ID, 10); // Use our ID number in the DB, base 10 (decimal) notation
// These wont work, ill fix this later...
$DEVICE["cert" ]->setExtension("id-ce-basicConstraints", array("cA" => false ), 1 );
$DEVICE["cert" ]->setExtension("id-ce-keyUsage" , array("keyEncipherment" ,"nonRepudiation" ,"digitalSignature" ), 1 );
$DEVICE["cert" ]->setExtension("id-ce-extKeyUsage" , array("id-kp-emailProtection" ,"id-kp-clientAuth" ), 1 );
$DEVICE["cert" ]->setExtension("netscape-cert-type" , array("Email" ,"SSLClient" ), 1 );
// Finally have the CA sign the updated CSR
$DEVICE["signedcert"] = $DEVICE["cert"]->sign($CA["cert"], $DEVICE["cert"], "sha256WithRSAEncryption"); // Sign the new certificate with our CA
$DEVICE["asciicert" ] = $DEVICE["cert"]->saveX509($DEVICE["signedcert"]); // Ascii our certificate for presentation
print <<<END
User Public key:\n{$DEVICE["keypair"]["publickey"]}\n
User Private key:\n{$DEVICE["keypair"]["privatekey"]}\n
User CSR:\n{$DEVICE["asciicsr"]}\n
CA Cert:\n{$CA["asciicert"]}\n
User Certificate:\n{$DEVICE["asciicert"]}\n
END;
?>
Below is some sample output from this program:
...
User CSR:
-----BEGIN CERTIFICATE REQUEST-----
MIIC1DCCAb4CAQAwgZQxCzAJBgNVBAYMAlNTMRAwDgYDVQQIDAdvYnNjdXJlMRAw
DgYDVQQHDAdvYnNjdXJlMQ8wDQYDVQQKDAZzZWN1cmUxGDAWBgNVBAsMD25ldHdv
cmtzZWN1cml0eTEXMBUGA1UEAwwOdGVzdGVyQGNvbW1hbmQxHTAbBgkqhkiG9w0B
CQEMDnRlc3RlckBjb21tYW5kMIIBIDALBgkqhkiG9w0BAQEDggEPADCCAQoCggEB
ANzsEUPULfmkbDK2DLTWUbHxpqbxiQ0WF5vuUOXutcdJADG9uExyllRtnPmUq3yV
GhfF/jbKKwXrDMTc9JLRoPRjbCesHQq9p+WU2pgzHWOGne3b2SNB6ISSVUbmZwRd
3Uu78u2EIPw2yB/YAdMaSipuLnA4jbGwWHtMXWSr9g0en+CkJ0cHN3P0GAnDR7BF
2pq88si5Who9Dvn/Mo3npMZiAmD5D7qwD88mVFMC1j4q1xnqHi2X19Xz9+xgWZ1h
IdedpWh+v0i2kHE73Csu0Jiczxb28zdm+MjBEYGZ6X6LzCYHI5kx2wDKsxuxraMf
sY0QS/kATiTzSJMcWzxR82UCAwEAATALBgkqhkiG9w0BAQsDggEBABuThxlknbCS
Fzd8B+eM98uFW6YQmfp5js/S2+Cor3+btGi2d/siXDGusW7ceOEv4WLRikrv+0tt
rHNzndhl77ukSikA0H0VMUqNFYIL1N//W2nDhphYKWwKWHGoQ+/ZH30aLgw43iNz
IzWAj2d39bGEqAvGPzU6BDpm8o1ucMoJaqUAHNov69Ro/n+rb0k3ouuTqjewF781
lQFHMPhUY4j2JbGKpah3qPGvAgc44JR6VmG6Rh9nVhcZz5szit8K1UTgvIlSl7EH
7ggBHQl67kON19JKlKneJVsD36tczkEhuDGU5Dv4TH7SLiKwIRYHulD3bmqg2/Nq
sGAxVviaKBA=
-----END CERTIFICATE REQUEST-----
CA Cert:
-----BEGIN CERTIFICATE-----
MIIDVTCCAj2gAwIBAgICEA8wDQYJKoZIhvcNAQELBQAwSTELMAkGA1UEBhMCU1Mx
EjAQBgNVBAgMCVNlY3VyZSBDQTESMBAGA1UEBwwJU2VjdXJlIENBMRIwEAYDVQQK
DAlTZWN1cmUgQ0EwHhcNMTUwMjAxMTkzNjA2WhcNMTYwMjAxMTkzNjA2WjBPMQsw
CQYDVQQGEwJTUzEPMA0GA1UECAwGU2VjdXJlMQ8wDQYDVQQKDAZTZWN1cmUxHjAc
BgNVBAMMFW5ldHdvcmtzZWN1cml0eS5uaW5qYTCCASIwDQYJKoZIhvcNAQEBBQAD
ggEPADCCAQoCggEBAN7PJWsyd3Hn7q5/Y4N9Dcpvtip/hiSEFwrkl4UWd+bD7CGz
wQjyZziVAj7mXjgTrPCmMzwV/aRtT2WM7l1vI8WV0swsTEidvZF+EDEAujnadMxr
8JWVC+ljYvhy7nIDRYpPwkKSBWpIF1UFaG8MduHxBtqlRlOJoIDQmJkLQO5fV/kv
cujct4myMhar6TPx52xWX0FLt0B3Rn04Rb0InstyDY0NtrTMsgSq32rj3sijTCAG
WDsnxNO+jsC7uFAjjldcWnqBs7of+sVb7TPiEsq/5adE6G50ctqW8H7JpY+SFZzG
Y+wPRUxJZsYq4qt/rkEv7ldtsbhHD6wO4I61eksCAwEAAaNBMD8wDAYDVR0TBAUw
AwEB/zALBgNVHQ8EBAMCBeAwIgYDVR0RBBswGYIXKi5uZXR3b3Jrc2VjdXJpdHku
bmluamEwDQYJKoZIhvcNAQELBQADggEBAMsXyUX95AkQKadbaZ1XEWoayElWtKUc
dRB15XDJ7xoWGQo/fDYebXOJMPffIQoOGtRZcYtPaVjr3PMUCaxIAUvdmO3UMfLh
M8kQhYBzyEKw+SRwcUHmKbU8Tz5AolL1qjoNm5SWBV9RbFj2TRcR27v/apmhIR+K
6KKbcIXklKhhBPacJL7NwAgibb8Ip4OtxSuzarydddPryAwTwUSJNlmozRAx7dFk
xLkLMQMqEtW7BmJqU+YUczddYvbsxmYqfaChM/TBo7VZd84RlWoXOqqfon6JGLWN
5lN86iVnfXeGLbhLt5GKWB6e4rUbiMAqmGYO6Cd2BMFRtlp9IYZIBSY=
-----END CERTIFICATE-----
User Certificate:
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
I find it really confusing that the signed certificate is blank. The error checking in place seems to make me think it would simply return FALSE if there was a problem, but getting blank output between the ----- lines makes me wonder what is going on.

From your code:
$DEVICE["cert" ]->loadX509( $DEVICE["asciicsr"] );
Try this:
$DEVICE["cert" ]->loadCSR( $DEVICE["asciicsr"] );

Related

Private key from Certificate generated with certreq is not exportable

I have created a Certificate with an inf-file and certreq with the following settings:
$InfFile = #"
[NewRequest]`r
FriendlyName = $FQDN
Subject = "CN=$FQDN,OU=$OrganizationalUnit,O=$Organisation,L=$Locality,S=$State,C=$CountryName,E=$Email"`r
KeySpec = 1
KeyLength = 2048
Exportable = TRUE`r
RequestType = PKCS10`r
[Extensions]
2.5.29.17 = "{text}"
_continue_ = "DNS=$FQDN&"
_continue_ = "DNS=$SERVERNAME"
"#
If I run this in a Script, the certificate will be created. But I'm unable to export the private key even though I set the value of "Exportable" to true. It seems no key is associated with the certificate as shown in this picture:
Certificate without key
Here a Certificate with associated Key for reference:
Certificate with Key
I'm not quite sure what I am doing wrong, any ideas?
Cheers
Buffalosoldier
Just found the answer to my own question. I had to add the following to the inf file: MachineKeySet = TRUE

alg value for Ed25519?

The RFC7518 has a list of algorithms values used in JWT. However there is no value for EdDSA, such as Ed25519. Also Ed25519 is not accepted as a valid value when verifying in Jose. What is the correct alg value for Ed25519?
ED25519 is a EdDSA (Edwards-curve DSA) signature scheme. See also RFC8037 and RFC8032.
According to the jose documentation alg needs to be set to EdDSA:
JWS Algorithm: Edwards-curve DSA
alg: EdDSA
EdDSAis also listed in the section JSON Web Signature and Encryption Algorithms of the IANA Registry (thanks #Florent Morselli for the hint)
Here I show an example how to generate a ed25519 keypair and a signed token in Node.js with jose and crypto and then verify the token with the public key in Python:
Generate key pair and token:
const { SignJWT } = require('jose/jwt/sign')
const { generateKeyPairSync } = require('crypto')
const { publicKey, privateKey } = generateKeyPairSync('ed25519');
console.log(publicKey.export({format:'pem',type:'spki'}))
console.log(privateKey.export({format:'pem',type:'pkcs8'}))
const jwt = await new SignJWT({ 'id': 1 })
.setProtectedHeader({ alg: 'EdDSA' })
.setExpirationTime('2h')
.sign(privateKey)
console.log(jwt)
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEA7fySb/9h7hVH8j1paD5IoLfXj4prjfNLwOPUYKvsTOc=
-----END PUBLIC KEY-----
-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VwBCIEIIJtJBnTuKbIy5YjoNiH95ky3DcA3kRB0I2i7DkVM6Cf
-----END PRIVATE KEY-----
eyJhbGciOiJFZERTQSJ9.eyJpZCI6MX0.RAxBAQPFOxrCfgqb56eaAz9u2lByj-WEO-
JWgJH3Cyx1o1Hwjn1pA2M4NgJeob9vb2Oaw4FOeYFr6_33XMTnAQ
the decoded token header:
{
"alg": "EdDSA"
}
Verify the token in Python with PyJWT:
import jwt
public_key = """-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEA7fySb/9h7hVH8j1paD5IoLfXj4prjfNLwOPUYKvsTOc=
-----END PUBLIC KEY-----"""
token = 'eyJhbGciOiJFZERTQSJ9.eyJpZCI6MX0.RAxBAQPFOxrCfgqb56eaAz9u2lByj-WEO-JWgJH3Cyx1o1Hwjn1pA2M4NgJeob9vb2Oaw4FOeYFr6_33XMTnAQ'
decoded = jwt.decode(token, public_key, algorithms='EdDSA', verify=True)
print(decoded)
Note: jwt.io currently doesn't support the EdDSA/ED25519 algorithm, so you can't verify the token on that site. I also don't know about any other JWT website that can verify EdDSA signed tokens.

phpseclib $X509->setDomain on CSR?

Is it possible to set x509 v3 extended attribute for subjectAltName on a CSR?
I am able to successfully generate a CSR, and then pass that to a CA to sign.
The CA is able to call functions like X509->setDomain("bob.com","*.bob.com","asdf.org"); and they appear in the final cert without issue (note: i am doing the sign, reload, set extensions, resign workaround for phpseclib).
The CSR process calling the same functions $X509->setExtension("id-ce-subjectAltName",array("names","here") ) or $X509->setDomain("domain1","domain2"); does not appear to set some X509 extended attributes in the CSR itself (openssl can), I have only been able to add SAN by the CA after re-import before the second signing.
Thanks!
Edit: I created an example CSR (sign, reload, x509v3 extensions, resign workaround) and it seems possible to set SOME extended attributes (CA: false, key usage, etc.) but NOT the subjectAltName info:
-----BEGIN CERTIFICATE REQUEST-----
MIIC1TCCAb8CAQAwVDELMAkGA1UEBgwCU1MxEDAOBgNVBAgMB09ic2N1cmUxDzAN
BgNVBAcMBlNlY3VyZTEQMA4GA1UECgwHYm9iY29ycDEQMA4GA1UEAwwHYm9iLmNv
bTCCASAwCwYJKoZIhvcNAQEBA4IBDwAwggEKAoIBAQCunNrjxEOILsESZ1osUkT3
zSeAHlzNiCBQnc/Xf+oW7Ir7wKfbHkV10cM583mw3Zy8rlCT/lUq0H+f3Uoc5/FA
dsYWhatlJRlTjv+yjSsxyB9i/hZ/KliP3Ix2O+Pq1wZIWfvk40hmCHHSB6YDtqt0
vXqUTIhH3SfyLtK9nd/6WG8bgIq9jgL6xvF3h44ynEwkuOnHt4a9WrflGX4KKcwo
OM98M/TAntDgSXBEYoLxenIbl3ypa7gtghVHHls3QOSay5QM87K3PJ3kSWVlZ3tN
tZGfbFdLiS+3MH8G3ujSX8XYeBnUj5jXi4SzpzQ9o5pyArL8DD8kC/Q9P/el1aZb
AgMBAAGgQDA+BgkqhkiG9w0BCQ4xMTAvMAwGA1UdEwEB/wQCMAAwFgYDVR0lAQH/
BAwwCgYIKwYBBQUHAwEwBwYDVR0RBAAwCwYJKoZIhvcNAQELA4IBAQAUIhgLf6LH
WwhncU+yrNy6yHPHjFbipehUaS/Wa6FBbANpLyEdslqNwFD2FyXofSQVCB0L6VnH
NNXHcfZqWOT8+Xd0yNmfr/w+vg+s1yY4S0VAG6mxGsqwdIJqgXm2jaw0rMpzRs/k
wfOpJ+gyRTrQz9VJrn4xC4Uv6zTGNj56qZehDievW74SGISbGzj7AGmCxpp5/qZD
LN4Ls3wZ7I4TfuYZDh7qWuFwEAEEv40JPF2qO3VitvyAYrKg3bnUlFzQrOsfs4Ot
xzihLwkFEobih1bOEhzTnSv+lMckfw0DQ5Eb8mtFTC+/KOqEMMU5Hq1fm3B9Bkgs
FmqQZk4QlerY
-----END CERTIFICATE REQUEST-----
I figured it out, the SignCSR function in phpseclib doesnt respsect the setDomain function, or any content in the $this->domains array however it IS possible to manually encode and force set the subject alt names yourself:
$OPTIONS["altnames"] = array(
"bob.com",
"10.123.123.123",
"*.bob.com",
"asdf.fdsa",
);
$ALTNAMES = $this->altnames($OPTIONS["altnames"]);
if ( count($ALTNAMES) )
{
$CSR->setExtension("id-ce-subjectAltName" , $ALTNAMES );
}
protected function altnames($ALTNAMES)
{
//Sort names and IPs into two different arrays
$DOMAINS = array(); $IPS = array();
foreach ($ALTNAMES as $ALTNAME)
{
if ( filter_var($ALTNAME, FILTER_VALIDATE_IP) )
{
array_push($IPS,$ALTNAME);
}else{
array_push($DOMAINS,$ALTNAME);
}
}
// Create our altname array for the subjectAltName parser
$RETURN = array();
foreach ($DOMAINS as $DOMAIN) { array_push($RETURN, array("dNSName" => $DOMAIN ) ); }
foreach ($IPS as $IP) { array_push($RETURN, array("iPAddress" => $IP ) ); }
return $RETURN;
}
Now, the one caveat I found (that is a feature issue for phpseclib to consider) is the lack of IPv6 support. If you provide a valid IPv6 address in the altnames array (2620:153::1234) it will translate to IP Address: 0.0.0.0 because of the use of IP2LONG and LONG2IP embedded in the X509 code.
While not a showstopper for my use case, it is a minor annoyance and I have experimented with using a custom IP2BIN and BIN2IP function replacing the encode and decode logic for an IP in the library and not met with much success.
Example CSR generated with my code above:
-----BEGIN CERTIFICATE REQUEST-----
MIIC/DCCAeYCAQAwVDELMAkGA1UEBgwCU1MxEDAOBgNVBAgMB09ic2N1cmUxDzAN
BgNVBAcMBlNlY3VyZTEQMA4GA1UECgwHYm9iY29ycDEQMA4GA1UEAwwHYm9iLmNv
bTCCASAwCwYJKoZIhvcNAQEBA4IBDwAwggEKAoIBAQDOGLdjEr2IyW27e08hmRN+
Bcu4uOWAWEvxvY3+5pHdBQQEXhww5YQuEvpmgbKtav0j7aqFPDYNSXTv+aQNe9fq
cP3nZmKAWU+qbQMjWxwV9mEJOlWI214v7C8lLbMvBlny141J7KTvv1TGGLCBH/V2
EnQSdJzGDwXmJ2k0iChlQ7zl1TlonamYX9gefzp3N/DDp6kNhuPSX9zRorYIp5CC
WEIRmDdegwxHACrNu0K4xwuPjTRJf0oUkRsfBuDxqvBalQ0bzd/23fiQ51MEVla3
fUWL/+b2SKOlvgfu0XbfZ+Qx21DeyRQpqIWnv0gR4AM8qltxUgRjZloUfK5IQ8rp
AgMBAAGgZzBlBgkqhkiG9w0BCQ4xWDBWMAwGA1UdEwEB/wQCMAAwFgYDVR0lAQH/
BAwwCgYIKwYBBQUHAwEwLgYDVR0RBCcwJYIHYm9iLmNvbYIJKi5ib2IuY29tgglh
c2RmLmZkc2GHBAp7e3swCwYJKoZIhvcNAQELA4IBAQAf1Vlt09ZBhVpxlmi+n93u
Gm8fNrd5afeIzWj0h4dFGJSOg5T8SkfL5txk2C9tQEdayQWB1kllx5rIqXAPe6gz
kbcjJn8l2IB3khIoKYmylmtV8Yo0Fl/Xba1oLCAsixbK+UxiSLgXqMryz9DBy40s
5oYXpy5JOnqL7BRC7b+Lk/chw7CcncPZI4rei6HM8WATymTySdrPoQegvBj0VIar
qHBZrMV9lsjTREJ9hvA/FycA/PNlP9y8N+eTF9SBrnTi8ix+v+Iirc43xeD2EVLG
6uqXecClji6OEOKcdDsH0D0HD1PMFmKB0FWvq71dt7eVIHkTPwTLFG2XAjfn6Fb8
-----END CERTIFICATE REQUEST-----
Decodes to:
Certificate Request:
Data:
Version: 0 (0x0)
Subject: C=SS, ST=Obscure, L=Secure, O=bobcorp, CN=bob.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
Modulus:
00:ce:18:b7:63:12:bd:88:c9:6d:bb:7b:4f:21:99:
13:7e:05:cb:b8:b8:e5:80:58:4b:f1:bd:8d:fe:e6:
91:dd:05:04:04:5e:1c:30:e5:84:2e:12:fa:66:81:
b2:ad:6a:fd:23:ed:aa:85:3c:36:0d:49:74:ef:f9:
a4:0d:7b:d7:ea:70:fd:e7:66:62:80:59:4f:aa:6d:
03:23:5b:1c:15:f6:61:09:3a:55:88:db:5e:2f:ec:
2f:25:2d:b3:2f:06:59:f2:d7:8d:49:ec:a4:ef:bf:
54:c6:18:b0:81:1f:f5:76:12:74:12:74:9c:c6:0f:
05:e6:27:69:34:88:28:65:43:bc:e5:d5:39:68:9d:
a9:98:5f:d8:1e:7f:3a:77:37:f0:c3:a7:a9:0d:86:
e3:d2:5f:dc:d1:a2:b6:08:a7:90:82:58:42:11:98:
37:5e:83:0c:47:00:2a:cd:bb:42:b8:c7:0b:8f:8d:
34:49:7f:4a:14:91:1b:1f:06:e0:f1:aa:f0:5a:95:
0d:1b:cd:df:f6:dd:f8:90:e7:53:04:56:56:b7:7d:
45:8b:ff:e6:f6:48:a3:a5:be:07:ee:d1:76:df:67:
e4:31:db:50:de:c9:14:29:a8:85:a7:bf:48:11:e0:
03:3c:aa:5b:71:52:04:63:66:5a:14:7c:ae:48:43:
ca:e9
Exponent: 65537 (0x10001)
Attributes:
Requested Extensions:
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Extended Key Usage: critical
TLS Web Server Authentication
X509v3 Subject Alternative Name:
DNS:bob.com, DNS:*.bob.com, DNS:asdf.fdsa, IP Address:10.123.123.123
Signature Algorithm: sha256WithRSAEncryption
1f:d5:59:6d:d3:d6:41:85:5a:71:96:68:be:9f:dd:ee:1a:6f:
1f:36:b7:79:69:f7:88:cd:68:f4:87:87:45:18:94:8e:83:94:
fc:4a:47:cb:e6:dc:64:d8:2f:6d:40:47:5a:c9:05:81:d6:49:
65:c7:9a:c8:a9:70:0f:7b:a8:33:91:b7:23:26:7f:25:d8:80:
77:92:12:28:29:89:b2:96:6b:55:f1:8a:34:16:5f:d7:6d:ad:
68:2c:20:2c:8b:16:ca:f9:4c:62:48:b8:17:a8:ca:f2:cf:d0:
c1:cb:8d:2c:e6:86:17:a7:2e:49:3a:7a:8b:ec:14:42:ed:bf:
8b:93:f7:21:c3:b0:9c:9d:c3:d9:23:8a:de:8b:a1:cc:f1:60:
13:ca:64:f2:49:da:cf:a1:07:a0:bc:18:f4:54:86:ab:a8:70:
59:ac:c5:7d:96:c8:d3:44:42:7d:86:f0:3f:17:27:00:fc:f3:
65:3f:dc:bc:37:e7:93:17:d4:81:ae:74:e2:f2:2c:7e:bf:e2:
22:ad:ce:37:c5:e0:f6:11:52:c6:ea:ea:97:79:c0:a5:8e:2e:
8e:10:e2:9c:74:3b:07:d0:3d:07:0f:53:cc:16:62:81:d0:55:
af:ab:bd:5d:b7:b7:95:20:79:13:3f:04:cb:14:6d:97:02:37:
e7:e8:56:fc
OK, I think i found a "feature" in phpseclib's X509 signing function:
function sign($issuer, $subject, $signatureAlgorithm = 'sha1WithRSAEncryption')
If you sign the CSR, the code in the sign function claims to copy the X509 v3 extended attributes, however by the time it executes this line:
$csrexts = $subject->getAttribute('pkcs-9-at-extensionRequest', 0);
The result is always blank (an empty array), the attributes in $THIS (new) cert were overwritten somewhere in the previous ~30 lines of code.
I moved the csrexts line to the top of the Sign function, and attributes are now being copied correctly into generated certificates with X509 extended attributes in the CSR (that had to be manually calculated and set by my previous answer)
I will use sourceforge to try and post a bug request to save others the struggle hopefully.
OK, so I've got this to work using an example from the PHPSecLib documentation and playing around with it for a good few hours. Perhaps this is something added post February, but in any case, here is how to generate a CSR with an Subject Alternative Name:
$privKey = new Crypt_RSA();
extract($privKey->createKey());
$privKey->loadKey($privatekey);
$x509 = new File_X509();
$x509->setPrivateKey($privKey);
$x509->setDNProp('id-at-organizationName', 'Company');
$x509->setDNProp('id-at-organizationalUnitName', 'CompanyDepartment');
$x509->setDNProp('id-at-commonName', 'myurl.com');
$x509->setDNProp('id-at-localityName', $this->application);
$x509->loadCSR($x509->saveCSR($x509->signCSR()));
// Set extension request.
$x509->setExtension("id-ce-subjectAltName", [
['dNSName' => 'myalternativename.com', 'iPAddress' => 127.0.0.1]
]);
echo $x509->saveCSR($x509->signCSR());
That should print out the CSR with myalternativename.com as the SAN.
The bug still actual in 2020.
Cause of this bug is need for a valid $x509->currentCert array. The setExtension() function has no effect with empty currentCert array.
The currentCert array structure is equal to result of signCSR() function. Therefore you can just initialize it as following: $x509->currentCert = $x509->signCSR();
Now you can call setExtension() function.
Here is full example how to generate CSR with SAN attribute:
use \phpseclib\Crypt\RSA;
use \phpseclib\File\X509;
$privateKey = new RSA();
$privateKey->loadKey(file_get_contents(__DIR__ . '/private.key'));
$x509 = new X509();
$x509->setPrivateKey($privateKey);
$x509->setDNProp('commonname', 'example.com');
$x509->setDNProp('emailaddress', 'admin#mail.com');
$x509->currentCert = $x509->signCSR(); // Important!
$x509->setExtension('id-ce-subjectAltName', [
['iPAddress' => '127.0.0.1'],
['dNSName' => 'www.example.com'],
]);
$csr = $x509->signCSR();
file_put_contents(__DIR__ . '/domain.csr', $x509->saveCSR($csr));
echo "OK\n";

grails - RestClientBuilder

I am using the current version of rest client builder plugin. I tested out the uri via curl:
curl --user username:password https://localhost:8085/rest/api/latest/plan.json?os_authType=basic
I get the expected json in return. When I try to translate this to grails using the plugin like this:
RestBuilder rb = new RestBuilder()
def response = rb.get("https://localhost:8085/rest/api/latest/plan.json?os_authType=basic"){
auth 'username', 'password'
}
response.json instanceof JSONObject
I get this error:
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Why does it work in curl and not with the plugin? How do I get this to work?
Thanks!
You need to add the root certificate to the store of the trusted ones.
http://docs.oracle.com/javase/tutorial/security/toolsign/rstep2.html
Import the Certificate as a Trusted Certificate
Before you can grant the signed code permission to read a specified file, you need to import Susan's certificate as a trusted certificate in your keystore.
Suppose that you have received from Susan
the signed JAR file sCount.jar, which contains the Count.class file, and
the file Example.cer, which contains the public key certificate for the public key corresponding to the private key used to sign the JAR file.
Even though you created these files and they haven't actually been transported anywhere, you can simulate being someone other than the creater and sender, Susan. Pretend that you are now Ray. Acting as Ray, you will create a keystore named exampleraystore and will use it to import the certificate into an entry with an alias of susan.
A keystore is created whenever you use a keytool command specifying a keystore that doesn't yet exist. Thus we can create the exampleraystore and import the certificate via a single keytool command. Do the following in your command window.
Go to the directory containing the public key certificate file Example.cer. (You should actually already be there, since this lesson assumes that you stay in a single directory throughout.)
Type the following command on one line:
keytool -import -alias susan
-file Example.cer -keystore exampleraystore
Since the keystore doesn't yet exist, it will be created, and you will be prompted for a keystore password; type whatever password you want.
The keytool command will print out the certificate information and ask you to verify it, for example, by comparing the displayed certificate fingerprints with those obtained from another (trusted) source of information. (Each fingerprint is a relatively short number that uniquely and reliably identifies the certificate.) For example, in the real world you might call up Susan and ask her what the fingerprints should be. She can get the fingerprints of the Example.cer file she created by executing the command
keytool -printcert -file Example.cer
If the fingerprints she sees are the same as the ones reported to you by keytool, the certificate has not been modified in transit. In that case you let keytool proceed with placing a trusted certificate entry in the keystore. The entry contains the public key certificate data from the file Example.cer and is assigned the alias susan.
You can just disable SSL check for RestBuilder.
See an example of code:
static Scheme disableSSLCheck() {
def sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, [new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
#Override
X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0]
}
}] as TrustManager[], new SecureRandom())
def sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
def httpsScheme = new Scheme("https", sf, 443)
httpsScheme
}
And register this Scheme to the RestClient:
Scheme httpsScheme = disableSSLCheck()
restClient.client.connectionManager.schemeRegistry.register(httpsScheme)
Mb too late but have a look here.
https://gist.github.com/thomastaylor312/80fcb016020e4115aa64320b98fb0017
I do have it as separate method in my Integration test
def static disableSSLCheck() {
def nullTrustManager = [
checkClientTrusted: { chain, authType -> },
checkServerTrusted: { chain, authType -> },
getAcceptedIssuers: { null }
]
def nullHostnameVerifier = [
verify: { hostname, session -> true }
]
SSLContext sc = SSLContext.getInstance("SSL")
sc.init(null, [nullTrustManager as X509TrustManager] as TrustManager[], null)
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())
HttpsURLConnection.setDefaultHostnameVerifier(nullHostnameVerifier as HostnameVerifier)
}
And then just
void "test authentication"(){
given:
String url = "j_spring_security_check"
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
form.add("grant_type", "password")
form.add("j_username", "vadim#ondeviceresearch.com")
form.add("j_password", "notSecure")
form.add("_spring_security_remember_me", "true")
//TODO SET username and pass
//todo get token back
disableSSLCheck()
when:
RestResponse response = rest.post(host + url){
accept("application/json")
contentType("application/x-www-form-urlencoded")
body(form)
}
response
then:
response.status == 200
}

Problems with openSSL command line

I am working with O'Reilly's book on SSL, which uses openSSL for its examples.
After creating a configuration file:
[ ca ]
default_ca = mobileCA
[ mobileCA ]
dir = /users/crodgers/src/sds2mobile/Server/CA
certificate = $dir/cacert.pem
database = $dir/index.txt
new_certs_dir = $dir/certs
private_key = $dir/private/key.pem
serial = $dir/serial
default_crl_days = 7
default_days = 365
default_md = md5
policy = mobile_CA_policy
x509_extensions = certificate_extensions
[ mobileCA_policy ]
commonName = SDS/2 Mobile Certificate
stateOrProvinceName = Nebraska
countryName = US
emailAddress = designdatamobiledevelopment#gmail.com
organizationName = Design Data
[ certificate_extensions ]
basicConstraints = CA:false
[ req ]
default_bits = 2048
default_keyfile = /users/crodgers/src/sds2mobile/Server/CA/private/key.pem
default_md = md5
prompt = no
distinguished_name = root_ca_distinguished_name
x509_extensions = root_ca_extensions
[ root_ca_distinguished_name ]
commonName = Root Certificate
stateOrProvinceName = Nebraska
countryName = US
emailAddress = designdatamobiledevelopment#gmail.com
organizationName = Design Data
[ root_ca_extensions ]
basicConstraints = CA:true
The user is instructed to enter the following command:
openssl req -x509 -newkey rsa -out cacert.pem -outform PEM
This is supposed to create a self-signed root certificate.
This command gives me the -help output. I'm assuming something in the command is incorrect, but have been unable to narrow down what.
Currently working in Ubuntu 10.04 and openSSL 0.9.8k
You're missing the RSA key size, e.g. -newkey rsa:1024 for a 1024-bit key.