How to use getAttributeValue() in ClientIdentity for fabric shim? - hyperledger-fabric

I am using nodejs sdk for hyperledger fabric, inside my chaincode i need to get name of the identity (sam) who is execting the transaction.
{"name":"sam","mspid":"Org1MSP","roles":null,"affiliation":"","enrollmentSecret":"","enrollment":{"signingIdentity":"5aad871581d63447218743ee79289c0c6f531a032d3cf1f0be32083e8c0cbaea","identity":{"certificate":"-----BEGIN CERTIFICATE-----\nMIICizCCAjGgAwIBAgIUQq0tPLPFsLujCsRclZc9POmAh6EwCgYIKoZIzj0EAwIw\nczELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMT\nE2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMTkxMTE5MDU0ODAwWhcNMjAxMTE4MDU1\nMzAwWjBAMTAwDQYDVQQLEwZjbGllbnQwCwYDVQQLEwRvcmcxMBIGA1UECxMLZGVw\nYXJ0bWVudDExDDAKBgNVBAMTA3NhbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA\nBGbtyGsC9QNBlO0Z5sumDzEaYR4m8GJpXW2f8Qlvjt79IzCWDjGwFePAIOfnUojz\naDbr0VHgpnWOtUIKUqTVPOujgdUwgdIwDgYDVR0PAQH/BAQDAgeAMAwGA1UdEwEB\n/wQCMAAwHQYDVR0OBBYEFCR78iTBbBSCYjxajhOMyYrWDO8iMCsGA1UdIwQkMCKA\nIHWD+xHmJ7l80nLYW67w4+Bftya5oeDfD9d4KXfnqn3NMGYGCCoDBAUGBwgBBFp7\nImF0dHJzIjp7ImhmLkFmZmlsaWF0aW9uIjoib3JnMS5kZXBhcnRtZW50MSIsImhm\nLkVucm9sbG1lbnRJRCI6InNhbSIsImhmLlR5cGUiOiJjbGllbnQifX0wCgYIKoZI\nzj0EAwIDSAAwRQIhAJcIBDcygI6Z67ueo46b3WnJCZr+D1HzhaWNp6Lj/+7oAiA6\nRRc9JjnWFvaFaqIJTyNaE7/HFXTXKr+HIkig/UEZpQ==\n-----END CERTIFICATE-----\n"}}}
I have used the below code
async approve(ctx) {
try {
const owId = new clientIdentity(ctx.stub).getAttributeValue('name')
return owId.toString();
} catch(error) {
console.log(error);
throw new Error(`Low on amount`);
}
}
but the above code is not returning the name or any other attributes.
Help will be appreciated!!!

The attributes you retrieve with getAttributeValue() in the Smart Contract are created as follows with the command line:
fabric-ca-client register --id.name clare --id.secret hursley1 --id.maxenrollments -1 --id.attrs 'department=Finance:ecert,location=Berkshire:ecert'
So I'm creating 2 attributes for department and location. Note the :ecert on the end which means that I want the attributres written to the certificate, not just stored in the CA database. Note also that the attributes aren't added to existing certificates, but only "appear" when you have enrolled or renrolled.
Using the node SDK this is a snippet of code that would add the department attribute when registering an Identity:
//create user attr array
let registerAttrs = [];
let registerAttribute = {
name: "department",
value: "Finance",
ecert: true
};
registerAttrs.push(registerAttribute);
// at this point we should have the admin user
// first need to register the user with the CA server
return fabric_ca_client.register(
{
enrollmentID: username,
affiliation: "org1",
role: "client",
attrs: registerAttrs
},
admin_user
);
In your smart contract you can then access the attribute:
ctx.clientIdentity.getAttributeValue('department');
Note that with the fabric-contract-api the clientIdentity object is already populated so you don't need a new clientIdentity object.

You have no attribute named "name". If you analyze your X.509 certificate...
openssl x509 -text -noout -in yourcert.pem
...you get...
Certificate:
Data:
Version: 3 (0x2)
Serial Number:
42:ad:2d:3c:b3:c5:b0:bb:a3:0a:c4:5c:95:97:3d:3c:e9:80:87:a1
Signature Algorithm: ecdsa-with-SHA256
Issuer: C = US, ST = California, L = San Francisco, O = org1.example.com, CN = ca.org1.example.com
Validity
Not Before: Nov 19 05:48:00 2019 GMT
Not After : Nov 18 05:53:00 2020 GMT
Subject: OU = client + OU = org1 + OU = department1, CN = sam
Subject Public Key Info:
Public Key Algorithm: id-ecPublicKey
Public-Key: (256 bit)
pub:
04:66:ed:c8:6b:02:f5:03:41:94:ed:19:e6:cb:a6:
0f:31:1a:61:1e:26:f0:62:69:5d:6d:9f:f1:09:6f:
8e:de:fd:23:30:96:0e:31:b0:15:e3:c0:20:e7:e7:
52:88:f3:68:36:eb:d1:51:e0:a6:75:8e:b5:42:0a:
52:a4:d5:3c:eb
ASN1 OID: prime256v1
NIST CURVE: P-256
X509v3 extensions:
X509v3 Key Usage: critical
Digital Signature
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Subject Key Identifier:
24:7B:F2:24:C1:6C:14:82:62:3C:5A:8E:13:8C:C9:8A:D6:0C:EF:22
X509v3 Authority Key Identifier:
keyid:75:83:FB:11:E6:27:B9:7C:D2:72:D8:5B:AE:F0:E3:E0:5F:B7:26:B9:A1:E0:DF:0F:D7:78:29:77:E7:AA:7D:CD
1.2.3.4.5.6.7.8.1:
{"attrs":{"hf.Affiliation":"org1.department1","hf.EnrollmentID":"sam","hf.Type":"client"}}
Signature Algorithm: ecdsa-with-SHA256
30:45:02:21:00:97:08:04:37:32:80:8e:99:eb:bb:9e:a3:8e:
9b:dd:69:c9:09:9a:fe:0f:51:f3:85:a5:8d:a7:a2:e3:ff:ee:
e8:02:20:3a:45:17:3d:26:39:d6:16:f6:85:6a:a2:09:4f:23:
5a:13:bf:c7:15:74:d7:2a:bf:87:22:48:a0:fd:41:19:a5
Your attribute keys are:
hf.Affiliation
hf.EnrollmentID
hf.Type
There is no "name" attribute. You are probably looking for "hf.EnrollmentID".
EDIT: You yourself indicated your certificate in your question, in enrollment.identity.certificate field. I have only saved...
-----BEGIN CERTIFICATE-----
MIICizCCAjGgAwIBAgIUQq0tPLPFsLujCsRclZc9POmAh6EwCgYIKoZIzj0EAwIw
czELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh
biBGcmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMT
E2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMTkxMTE5MDU0ODAwWhcNMjAxMTE4MDU1
MzAwWjBAMTAwDQYDVQQLEwZjbGllbnQwCwYDVQQLEwRvcmcxMBIGA1UECxMLZGVw
YXJ0bWVudDExDDAKBgNVBAMTA3NhbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA
BGbtyGsC9QNBlO0Z5sumDzEaYR4m8GJpXW2f8Qlvjt79IzCWDjGwFePAIOfnUojz
aDbr0VHgpnWOtUIKUqTVPOujgdUwgdIwDgYDVR0PAQH/BAQDAgeAMAwGA1UdEwEB
/wQCMAAwHQYDVR0OBBYEFCR78iTBbBSCYjxajhOMyYrWDO8iMCsGA1UdIwQkMCKA
IHWD+xHmJ7l80nLYW67w4+Bftya5oeDfD9d4KXfnqn3NMGYGCCoDBAUGBwgBBFp7
ImF0dHJzIjp7ImhmLkFmZmlsaWF0aW9uIjoib3JnMS5kZXBhcnRtZW50MSIsImhm
LkVucm9sbG1lbnRJRCI6InNhbSIsImhmLlR5cGUiOiJjbGllbnQifX0wCgYIKoZI
zj0EAwIDSAAwRQIhAJcIBDcygI6Z67ueo46b3WnJCZr+D1HzhaWNp6Lj/+7oAiA6
RRc9JjnWFvaFaqIJTyNaE7/HFXTXKr+HIkig/UEZpQ==
-----END CERTIFICATE-----
...as yourcert.pem to check it via openssl.

Related

MySQL xdevapi Node Error: SELF_SIGNED_CERT_IN_CHAIN

Windows 10 Pro
MySQL8.0
node.js v14.15.5
openssl 1.1.1c
I'm trying to connect to a MySQL database using node, I'm able to connect without TLS just fine. I used openssl to create a private key and self signed certificate. When I try to use TLS in my node app, I keep getting the following error:
$ NODE_TLS_REJECT_UNAUTHORIZED=0 node index.js
(node:15480) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
(Use `node --trace-warnings ...` to show where the warning was created)
Error: self signed certificate in certificate chain
at TLSSocket.onConnectSecure (_tls_wrap.js:1497:34)
at TLSSocket.emit (events.js:315:20)
at TLSSocket._finishInit (_tls_wrap.js:932:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:706:12) {
code: 'SELF_SIGNED_CERT_IN_CHAIN'
}
TypeError: Cannot read property 'sql' of undefined
at C:\Users\gregb\Desktop\PROGRAMMING\VS Code Workspace\xdevapi2\index.js:40:32
at processTicksAndRejections (internal/process/task_queues.js:93:5)
[]
[]
Index.js
let mysqlx = require('#mysql/xdevapi');
let fs = require('fs');
require('dotenv').config();
let rows = [];
let columns = [];
// Works without TLS
// let config = {
// host: 'localhost',
// port: 33060,
// user: 'root',
// database: 'user',
// password: process.env.password
// };
const config = {
host: 'localhost',
port: 33060,
user: 'root',
database: 'user',
password: process.env.password,
ssl: true,
tls: {
rejectUnauthorized: false,
key: fs.readFileSync('./privatekey2.pem'),
cert: fs.readFileSync('./example.crt'),
ca: './cacert.pem'
}
};
(async function () {
let session;
try {
session = await mysqlx.getSession(config);
} catch(err) {
console.log(err);
}
try {
let result = await session.sql('SELECT "firstName" AS c1, "lastName" AS c2')
.execute(row => rows.push(row), column => columns = columns.concat(column));
session.close();
} catch(err) {
console.log(err);
}
console.log(rows); // [['foo', 'bar']]
console.log(columns.map(column => column.getColumnLabel())); // ['c1', 'c2']
})();
I also tried:
NODE_TLS_REJECT_UNAUTHORIZED='0' node index.js
How I used openssl:
Create a public/private key file pair:
openssl genrsa -out privkey2.pem 4096
Split into public/private:
openssl ssh-keygen -t rsa -b 4096 -f privatekey2.pem
Create a cert
openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes -keyout privatekey2.pem -out example.crt
The problem does not seem to be related to the certificate you are using. It should be related to the fact that you provide a path for the certificate authority file (ca). You do this when you want the client to verify that the server certificate was signed using a certificate in the CA chain, which only works if rejectUnauthorized is true, which is automatically set once you provide that valid CA file path, thus, your custom rejectUnauthorized: false is ignored.
Which begs the question, Is the server certificate signed by the CA you are providing? I suspect it is not, in which case, the error is legitimate.
If so, then it is a bug, and you should report it using the public MySQL issue tracker. However, I ran a few tests and I'm convinced there is no issue, but if you are able to produce a server certificate that was, indeed, signed by that particular CA, which allows to reproduce the same exact scenario, maybe we can dig some dirt.
Disclaimer: I'm the lead developer of MySQL X DevAPI Connector for Node.js

How to create a Certificate Authority 'CA' using pem lib NodeJs?

Creating a CA using node
This is how to create a certificate using OpenSSL
OpenSSL Certificate Authority
I tried with pem
This is my closed Issue can't create CSR from private key #244 GitHub
When I trying to generate a CSR
var csrOptions = {
clientKey: '/root/ca/intermediate/private/client.key.pem',
clientKeyPassword: '123456',
hash: 'sha256',
country: 'US',
state: 'California',
locality: 'Mountain View',
organization: 'Alice Ltd',
organizationUnit: 'Alice Ltd Web Services',
commonName: 'pass:client',
}
pem.createCSR( csrOptions , function(err, csr) {
if (err) {
throw err
} else {
console.log(csr.clientKey)
console.log(csr.csr)
}
});
I get this error
/root/sslnode/index2.js:37
throw err
^
% openssl req -new -sha256 -config /root/ca/intermediate/openssl.cnf -key /tmp/54f976cb9cbd0e2dd53b755badb6e6e3fe2256ad -passin file:/tmp/3f4640f1d95ca955f1c44c7f2c4b729347813a5f
unable to load Private Key
140563986715072:error:0906D06C:PEM routines:PEM_read_bio:no start >line:../crypto/pem/pem_lib.c:691:Expecting: ANY PRIVATE KEY
After searching I get the error, clientKey took a key as a string, not a path
clientKey: '/root/ca/intermediate/private/client.key.pem',
clientKey: fs.readFileSync('/root/ca/intermediate/private/client.key.pem'),

Error - "Too many intermediates for path length constraint" when register new identity

In hyperledger fabric-ca, I create chain of CAs like:
Root CA - Intermediate CA 1 - Intermediate CA 2 - Intermediate CA 3
With these CAs, in "signing" part of fabric-ca-config.yaml file I set "maxpathlen:5", and in "csr" part I set "pathlength:5"
It's mean my chain is valid for at least 4 Intermediate CA and I can register new identity in Intermediate CA 3.
In fact, I can enroll admin of Intermediate CA 3, however, when I register new identity, I have this error:
/register 401 26 "Untrusted certificate: Failed to verify certificate: x509: too many intermediates for path length constraint"
What wrong I have done, and how to config this value
My config file
# Version of config file
version: 1.1.0
# Server's listening port (default: 7054)
port: 7054
# Enables debug logging (default: false)
debug: false
# Size limit of an acceptable CRL in bytes (default: 512000)
crlsizelimit: 512000
tls:
# Enable TLS (default: false)
enabled: false
# TLS for the server's listening port
certfile:
keyfile:
clientauth:
type: noclientcert
certfiles:
ca:
# Name of this CA
name:
# Key file (is only used to import a private key into BCCSP)
keyfile:
# Certificate file (default: ca-cert.pem)
certfile:
# Chain file
chainfile:
crl:
# Specifies expiration for the generated CRL. The number of hours
# specified by this property is added to the UTC time, the resulting time
# is used to set the 'Next Update' date of the CRL.
expiry: 24h
registry:
# Maximum number of times a password/secret can be reused for enrollment
# (default: -1, which means there is no limit)
maxenrollments: -1
# Contains identity information which is used when LDAP is disabled
identities:
- name: Admin
pass: adminpw
type: client
affiliation:
attrs:
hf.Registrar.Roles: "*"
hf.Registrar.DelegateRoles: "*"
hf.Revoker: true
hf.IntermediateCA: true
hf.GenCRL: true
hf.Registrar.Attributes: "*"
hf.AffiliationMgr: true
affiliations:
org1:
- department1
- department2
org2:
- department1
signing:
default:
usage:
- digital signature
expiry: 8760h
profiles:
ca:
usage:
- cert sign
- crl sign
expiry: 43800h
caconstraint:
isca: true
maxpathlen: 5
tls:
usage:
- signing
- key encipherment
- server auth
- client auth
- key agreement
expiry: 8760h
csr:
cn: fabric-ca-server
names:
- C: US
ST: "California"
L:
O: Hyperledger
OU: Fabric
hosts:
- ca
- localhost
ca:
expiry: 131400h
pathlength: 5
I found the root cause is simple because when initialize network, I don't create cert/key by myself and config it so that Fabric-CA use itself key/cert which config default set maxpathlen=1.
If I create cert/key by myself and in cert config pathlength > 3 then my network will be ok.

Different certificate chain order when using Node's HTTPS/TLS vs. OpenSSL s_client

I'm trying to parse the certificate chain using Node's HTTPS request. I'm testing it on npmjs.com (not www.npmjs.com). When I test it on OpenSSL, it shows me that the chain is in the incorrect order.
openssl s_client -connect npmjs.com:443 -showcerts
OpenSSL Response First Certificate
subject: /OU=GT40876434/OU=See www.rapidssl.com/resources/cps (c)14/OU=Domain Control Validated - RapidSSL(R)/CN=*.npmjs.com
issuer: /C=US/O=GeoTrust Inc./CN=RapidSSL SHA256 CA - G3
Next Certificate ->
subject: /C=US/O=GeoTrust Inc./CN=GeoTrust Global CA
issuer: /C=US/O=Equifax/OU=Equifax Secure Certificate Authority
Next Certificate ->
subject: /C=US/O=GeoTrust Inc./CN=RapidSSL SHA256 CA - G3
issuer: /C=US/O=GeoTrust Inc./CN=GeoTrust Global CA
However, when I go to step through the certificate chain using my Node's HTTPS request, when the socket is emitted and I do
socket.getPeerCertificate(true)
the chain is in the correct order and I'm getting one different certificate on the Node request than I am on the openssl request.
Node's Response First Certificate:
subject
{ OU:
[ 'GT40876434',
'See www.rapidssl.com/resources/cps (c)14',
'Domain Control Validated - RapidSSL(R)' ],
CN: '*.npmjs.com' }
issuer
{ C: 'US', O: 'GeoTrust Inc.', CN: 'RapidSSL SHA256 CA - G3' }
Next Certificate ->
subject
{ C: 'US', O: 'GeoTrust Inc.', CN: 'RapidSSL SHA256 CA - G3' }
issuer
{ C: 'US', O: 'GeoTrust Inc.', CN: 'GeoTrust Global CA' }
Next Certificate ->
subject
{ C: 'US', O: 'GeoTrust Inc.', CN: 'GeoTrust Global CA' }
issuer
{ C: 'US', O: 'GeoTrust Inc.', CN: 'GeoTrust Global CA' }
Why is this happening?
It looks like node is reordering the certificates for returning in getPeerCertificates so that they reflect the correct order in the trust chain (*). But in reality the certificates are in the wrong order, as can be seen by openssl s_client and also in the analysis of SSLLabs:
Chain issues Incorrect order
(*) the relevant code in node-4.5.0 (LTS) is in src/node_crypto.cc function void SSLWrap<Base>::GetPeerCertificate. There it retrieves the leaf certificate and the original peer certificates from the openssl library using SSL_get_peer_certificate (leaf certificate) and SSL_get_peer_cert_chain (chain). It then does not return the certificates in the original chain order but scans through the chain and adds the certificates in the order how they are depend on each other by checking with X509_check_issued.
This way it returns the certificates in proper dependency order instead of the original order as send by the peer. It also automatically skips any certificates which don't belong in the chain.
It will also add the issuer of the certificate even if it is not contained it the chain (which it usually isn't). This way you not only get a different order of certificates as seen in your example but actually different certificates. The server sends the following certificates in this order:
[A] /OU=GT40876434/OU=See www.rapidssl.com/resources/cps (c)14/OU=Domain Control Validated - RapidSSL(R)/CN=*.npmjs.com
[B] /C=US/O=GeoTrust Inc./CN=GeoTrust Global CA, issued by Equifax
[C] /C=US/O=GeoTrust Inc./CN=RapidSSL SHA256 CA - G3
But getPeerCertificate returns the following:
[A] /OU=GT40876434/OU=See www.rapidssl.com/resources/cps (c)14/OU=Domain Control Validated - RapidSSL(R)/CN=*.npmjs.com
[C] /C=US/O=GeoTrust Inc./CN=RapidSSL SHA256 CA - G3
[R] CA/C=US/O=GeoTrust Inc./CN=GeoTrust Global CA, self-signed
Thus certificate [B] will not be included but instead certificate [R] which is the root certificate contained in the trust store. Both have the same subject and key, but are signed by different entities. [B] is signed by Equifax while [R] is self-signed.

SSL in socket.io with express: Missing PFX or certificate + private key.

I want to socket with socket.io through SSL. I have read the other answers but nothing worked
Here is my code:
var ssl_options = {
key : fs.readFileSync(my_key_path),
cert : fs.readFileSync(my_cert_path)
};
var protocol = "https";
preparedApp = require(protocol).createServer(ssl_options,app);
var io = require('socket.io')(preparedApp);
preparedApp.listen(8080, function(){});
io.on('connection', function(socket){});
And here is the log of my ssl_options...
{ key: <Buffer 41 ...>,
cert: <Buffer 4a ...> }
This errors with the error in the title throw new Error('Missing PFX or certificate + private key.');. Does anyone know what might be happening? None of the other solutions to this answer solved my case.
Use PEM (RSA) format for your private key. Check if the private key is a base64 encoded, enclosed between "-----BEGIN RSA PRIVATE KEY-----" and "-----END RSA PRIVATE KEY-----"
From the docs:
key: A string or Buffer containing the private key of the server in PEM format
cert : A string holding the PEM encoded certificate
passphrase: A string of passphrase for the private key or pfx [optional default: null]
or
pfx : A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates
To convert a private key to RSA PEM: openssl rsa -in <PATH TO KEY> -out key.pem -outform PEM
To create a PKCS #12 bundle use openssl pkcs12 -export -in cert.pem -inkey key.pem -certfile ca.pem -out host.pfx
-- ADDITION --
To ensure the cert is PEM encoded run openssl x509 -in <PATH TO CERT> -out cert.pem -outform PEM

Resources