Validating certificate using NodeJs Crypto - node.js

I'm running a sever in NodeJs whose certificate will be stored in DB as a string (for security purposes). I would like to validate it and it's expiration date, how can I do that?
I looked into 'Crypto' but I could not find a method that can do that.
For example:
-----BEGIN CERTIFICATE-----
MIIDNTCCAh2gAwIBAgIUJqrw/9EDZbp4DExaLjh0vSAHyBgwDQYJKoZIhvcNAQEL
BQAwFjEUMBIGA1UEAxMLbXl2YXVsdC5jb20wHhcNMTcxMjA4MTkyMzIwWhcNMjcx
MjA2MTkyMzQ5WjAWMRQwEgYDVQQDEwtteXZhdWx0LmNvbTCCASIwDQYJKoZIhvcN
AQEBBQADggEPADCCAQoCggEBAKY/vJ6sRFym+yFYUneoVtDmOCaDKAQiGzQw0IXL
BT55jevSPVVu
-----END CERTIFICATE-----

Resolved the issue by using package x509.
https://www.npmjs.com/package/x509
const x509 = require('x509');
var cert = x509.parseCert(__dirname + '/certs/nodejitsu.com.crt');
/*
cert = { subject:
{ countryName: 'US',
postalCode: '10010',
stateOrProvinceName: 'NY',
localityName: 'New York',
streetAddress: '902 Broadway, 4th Floor',
organizationName: 'Nodejitsu',
organizationalUnitName: 'PremiumSSL Wildcard',
commonName: '*.nodejitsu.com' },
issuer:
{ countryName: 'GB',
stateOrProvinceName: 'Greater Manchester',
localityName: 'Salford',
organizationName: 'COMODO CA Limited',
commonName: 'COMODO High-Assurance Secure Server CA' },
notBefore: Sun Oct 28 2012 20:00:00 GMT-0400 (EDT),
notAfter: Wed Nov 26 2014 18:59:59 GMT-0500 (EST),
altNames: [ '*.nodejitsu.com', 'nodejitsu.com' ],
signatureAlgorithm: 'sha1WithRSAEncryption',
fingerPrint: 'E4:7E:24:8E:86:D2:BE:55:C0:4D:41:A1:C2:0E:06:96:56:B9:8E:EC',
publicKey: {
algorithm: 'rsaEncryption',
e: '65537',
n: '.......' } }
*/

Related

Parse td in golang using goquery grep only the require line

I get output from an ajax request as below:
<div style='font-size:12px; font-weight:bold; line-height:17px;'>These results were cached from March 10, 2021, 1:11 pm PST to conserve server resources. <br/>If you are diagnosing a certificate installation problem,
you can get uncached results by clicking here.</div><table class='checker_messages'><tr><td class='passed'> </td><td><h3>www.Google.com resolves to 172.217.11.36</h3><</h3></td><tr><tr><td class='passed'> </td><td><h3>The certificate should be trusted by all major web browsers (all the correct intermediate certificates are installed).</h3></td><tr><tr><td class='passed'> </td><td><h3><table class=""><tr><td>The certificate will expire in <span id="cert_expiration_days">62</span> days. </td>
<td style="padding-left:10px;">Remind me</td></tr></table><input type="hidden" id="cert_valid_to" value="1620822887" /></h3></td><tr><tr><td class='passed'> </td><td><h3>The hostname (www.Google.com) is correctly listed in the certificate.</h3></td><tr></table><table class='checker_certs'><tr><td class='cert'><img src='/assets/templates/sslshopper/images/sslchecker/certificate_good_server.png' height='128' width='128' /></td><td><b>Common name:</b> www.google.com<br/><b>SANs:</b> www.google.com<br/><b>Organization:</b> Google LLC<br/><b>Location:</b> Mountain View, California, US<br/><b>Valid</b> from February 17, 2021 to May 12, 2021<br/><b>Serial Number:</b> 46638b76e6854ad205000000008779ef<br/><b>Signature Algorithm:</b> sha256WithRSAEncryption<br/><b>Issuer:</b> GTS CA 1O1<td></tr><tr><td class='chain'><img src='/assets/templates/sslshopper/images/sslchecker/arrow_down.png' height='48' width='48' /></td><td> </td></tr><tr><td class='cert'><img src='/assets/templates/sslshopper/images/sslchecker/certificate_good_chain.png' height='128' width='128' /></td><td><b>Common name:</b> GTS CA 1O1<br/><b>Organization:</b> Google Trust Services<br/><b>Location:</b> US<br/><b>Valid</b> from June 14, 2017 to December 14, 2021<br/><b>Serial Number:</b> 01e3b49aa18d8aa981256950b8<br/><b>Signature Algorithm:</b> sha256WithRSAEncryption<br/><b>Issuer:</b> GlobalSign<td></tr></table><input type='hidden' id='reminderCertID' value='58366913' /><input type='hidden' id='expirationDate' value='1620822887' /><input type='hidden' id='clean_hostname' value='www.Google.com' />
When I try to parse td using goquery using below snippet:
doc, err := goquery.NewDocumentFromReader(strings.NewReader(pageContent))
if err != nil {
panic(err)
}
doc.Find("td").Each(func(i int, s *goquery.Selection) {
fmt.Printf("%s\n", s.Text())
})
Output:
www.Google.com resolves to 172.217.11.36
Server Type: gws
The certificate should be trusted by all major web browsers (all the correct intermediate certificates are installed).
The certificate will expire in 62 days.
Remind me
The certificate will expire in 62 days.
Remind me
The hostname (www.Google.com) is correctly listed in the certificate.
Common name: www.google.comSANs: www.google.comOrganization: Google LLCLocation: Mountain View, California, USValid from February 17, 2021 to May 12, 2021Serial Number: 46638b76e6854ad205000000008779efSignature Algorithm: sha256WithRSAEncryptionIssuer: GTS CA 1O1
Common name: GTS CA 1O1Organization: Google Trust ServicesLocation: USValid from June 14, 2017 to December 14, 2021Serial Number: 01e3b49aa18d8aa981256950b8Signature Algorithm: sha256WithRSAEncryptionIssuer: GlobalSign
When I try using b tag instead of td i get output as below:
Common name:
SANs:
Organization:
Location:
Valid
Serial Number:
Signature Algorithm:
Issuer:
Common name:
Organization:
Location:
Valid
Serial Number:
Signature Algorithm:
Issuer:
The output I am trying to achieve is to get only Organization: Google LLC.
I recently started using StackOverflow and new to golang so I am not familiar with the environment if I make mistake then let me know.
I was able to achieve the proper output by adding some replacement.
res1 := strings.ReplaceAll(pageContent, "</b>", "")
res2 := strings.ReplaceAll(res1, "<br/>", "</b>")
doc, err := goquery.NewDocumentFromReader(strings.NewReader(res2))
if err != nil {
panic(err)
}
doc.Find("b").Each(func(i int, s *goquery.Selection) {
fmt.Println(s.Nodes[0].FirstChild.Data)
})
Output:
Common name: www.google.com
SANs: www.google.com
Organization: Google LLC
Location: Mountain View, California, US
Valid from February 17, 2021 to May 12, 2021
Serial Number: 46638b76e6854ad205000000008779ef
Signature Algorithm: sha256WithRSAEncryption
Issuer: GTS CA 1O1
Common name: GTS CA 1O1
Organization: Google Trust Services
Location: US
Valid from June 14, 2017 to December 14, 2021
Serial Number: 01e3b49aa18d8aa981256950b8
Signature Algorithm: sha256WithRSAEncryption
Issuer: GlobalSign
But now only want Organization: Google LLC line.

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

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.

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'),

Generate SSL certificates for multiple domains in SubjectAltName with Greenlock

I'm using greenlock to generate certificates, I pass it three domains, and only get 2 in my altnames:
const greenlock = Greenlock.create({
agreeTos: true,
email: myemail,
communityMember: false,
version: 'draft-12',
server: 'https://acme-v02.api.letsencrypt.org/directory',
configDir: '/etc/letsencrypt',
debug: true,
log: (debug) => { console.log(debug) },
})
console.log({ domains })
return greenlock.register({
domains,
email: myemail,
challengeType: 'dns-01',
})
.then((result) => {
console.log(result)
})
here are my logs:
{ domains:
[ 'domain1',
'domain3',
'domain2' ] }
true
true
true
{ result:
{
privkey: '-----BEGIN PRIVATE KEY-----\n\n-----END CERTIFICATE-----\n',
chain: '-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n',
subject: 'domain2',
altnames: [ 'domain1', 'domain2' ],
_issuedAt: 2018-09-19T14:43:31.000Z,
_expiresAt: 2018-12-18T14:43:31.000Z,
issuedAt: 1537368211000,
expiresAt: 1545144211000 } }
As you can see it's not even my first two domains that end up in my altnames but rather those that where already in the old certificate (not sure this is why tho).
I'm not married to greenlock, if someone as a better alternative I'm listening as well.
I tried passing approveDomains to my greenlock constructor and it doesn't seem to change much.
I still don't have my new domain (domain2) listed in my certificate :
openssl x509 -text < /etc/letsencrypt/live/domain1/fullchain.pem | grep 'DNS:' | sed 's/\s*DNS:\([a-z0-9.\-]*\)[,\s]\?/\1 /g'
domain1 domain3
Use Greenlock v2.7+
All of the code related to certificate generation and domain name and altname association has been updated.
Now when you change the domains array to include more domains it handles them individually rather than as a group.
Also, the information about the certificate is read directly from the certificate, so there can't be a mismatch between the "cache" and "the truth".
If you encounter further issues, please let us know directly:
https://git.rootprojects.org/root/greenlock.js/issues

Second if statement in jade layout not working

The first if statement is firing corretly and marking the checkbox as checked when the value is true, but the second isn't.
- var profileVal = false
- var logbookVal = false
div.form-group.col-md-6
-if(user.profilePublic){
- profileVal = true
-}
label Public profile
p Would you like your profile to be public?
input(type='checkbox',name='userPublicProfile',class='floatLeftCheckbox',checked=profileVal)
div.form-group.col-md-6.clearfix
label Public logbook
p Would you like your logbook to be public?
-if(user.logPublic){
- logbookVal = true
-}
input(type='checkbox',name='userPublicLogbook',class='floatLeftCheckbox',checked=logbookVal)
Both are set to Boolean in mongoDB. Both are correctly spelled etc.
Result of console.log:
deserializing user: { _id: 5547e77928d405cc236d4a01,
updated_at: 'Mon May 04 2015 17:41:13 GMT-0400 (EDT)',
created_at: 'Mon May 04 2015 17:41:13 GMT-0400 (EDT)',
admin: false,
lastName: '######',
firstName: '######',
email: '######',
password: '######',
callsign: '######',
uid: '$2a$10$/yF1pqR9N5VkXcnLaNDPBea8xH.tO3Tto82W.9wGD3VdZGPAdXID6',
profilePublic: true,
logPublic: true,
__v: 0 }
Also tried:
-if(user.logPublic)
p It's true
Still nothing

Resources