Added Intel AMT TLS/RootCert auto-setup.

Ylian Saint-Hilaire committed Oct 17, 2020 at 23:53 UTC d3ba1349c27f61e993f7bc66b992fb215a6adf3d
1 file changed +316 -21
amtmanager.js
+316 -21
@@ -19,6 +19,8 @@ module.exports.CreateAmtManager = function(parent) {
19 obj.amtDevices = {}; // Nodeid --> [ dev ]
20 obj.activeLocalConnections = {}; // Host --> [ dev ]
21 obj.amtAdminAccounts = {}; // DomainId -> [ { user, pass } ]
22 + obj.rootCertBase64 = obj.parent.certificates.root.cert.split('-----BEGIN CERTIFICATE-----').join('').split('-----END CERTIFICATE-----').join('').split('\r').join('').split('\n').join('')
23 + obj.rootCertCN = obj.parent.certificateOperations.forge.pki.certificateFromPem(obj.parent.certificates.root.cert).subject.getField('CN').value;
24
25 // WSMAN stack
26 const CreateWsmanComm = require('./amt/amt-wsman-comm');
@@ -229,7 +231,7 @@ module.exports.CreateAmtManager = function(parent) {
231 var dotls = -1;
232 if (ciraconn.tag.boundPorts.indexOf('16992')) { dotls = 0; }
233 else if (ciraconn.tag.boundPorts.indexOf('16993')) { dotls = 1; }
232 - if (dotls == -1) { removeDevice(dev.nodeid); return; } // The Intel AMT ports are not open, not a device we can deal with.
234 + if (dotls == -1) { removeAmtDevice(dev); return; } // The Intel AMT ports are not open, not a device we can deal with.
235
236 // Connect now
237 parent.debug('amt', 'CIRA-Connect', (dotls == 1) ? "TLS" : "NoTLS", dev.name, user, pass);
@@ -259,6 +261,7 @@ module.exports.CreateAmtManager = function(parent) {
261
262 // Connect now
263 var comm;
264 + dev.tlsfail = true; // DEBUG!!!!!!!
265 if (dev.tlsfail !== true) {
266 parent.debug('amt', 'Relay-Connect', "TLS", dev.name, user, pass);
267 comm = CreateWsmanComm(dev.nodeid, 16993, user, pass, 1, null, ciraconn); // Perform TLS
@@ -339,19 +342,25 @@ module.exports.CreateAmtManager = function(parent) {
342
343 // Perform Intel AMT clock sync
344 attemptSyncClock(dev, function () {
342 - // See if we need to get hardware inventory
343 - attemptFetchHardwareInventory(dev, function () {
344 - dev.consoleMsg('Done.');
345 - if (dev.connType != 2) {
346 - // Start power polling if not connected to LMS
347 - var ppfunc = function powerPoleFunction() { fetchPowerState(powerPoleFunction.dev); }
348 - ppfunc.dev = dev;
349 - dev.polltimer = new setTimeout(ppfunc, 290000); // Poll for power state every 4 minutes 50 seconds.
350 - fetchPowerState(dev);
351 - } else {
352 - // For LMS connections, close now.
353 - dev.controlMsg({ action: "close" });
354 - }
345 + // Check Intel AMT TLS state
346 + attemptTlsSync(dev, function () {
347 + // Check Intel AMT root certificate state
348 + attemptRootCertSync(dev, function () {
349 + // See if we need to get hardware inventory
350 + attemptFetchHardwareInventory(dev, function () {
351 + dev.consoleMsg('Done.');
352 + if (dev.connType != 2) {
353 + // Start power polling if not connected to LMS
354 + var ppfunc = function powerPoleFunction() { fetchPowerState(powerPoleFunction.dev); }
355 + ppfunc.dev = dev;
356 + dev.polltimer = new setTimeout(ppfunc, 290000); // Poll for power state every 4 minutes 50 seconds.
357 + fetchPowerState(dev);
358 + } else {
359 + // For LMS connections, close now.
360 + dev.controlMsg({ action: "close" });
361 + }
362 + });
363 + });
364 });
365 });
366 } else {
@@ -365,6 +374,7 @@ module.exports.CreateAmtManager = function(parent) {
374 if ((dev.acctry != null) && (obj.amtAdminAccounts[dev.domainid] != null) && (obj.amtAdminAccounts[dev.domainid].length > (dev.acctry + 1))) { dev.acctry++; attemptInitialContact(dev); return; }
375
376 // We are unable to authenticate to this device, clear Intel AMT credentials.
377 + dev.consoleMsg("Unable to connect.");
378 ClearDeviceCredentials(dev);
379 }
380 //console.log(dev.nodeid, dev.name, dev.host, status, 'Bad response');
@@ -378,7 +388,7 @@ module.exports.CreateAmtManager = function(parent) {
388
389 // Check that the mesh exists
390 const mesh = parent.webserver.meshes[dev.meshid];
381 - if (mesh == null) { removeDevice(dev.nodeid); return false; }
391 + if (mesh == null) { removeAmtDevice(dev); return false; }
392
393 // Get the node and change it if needed
394 parent.db.Get(dev.nodeid, function (err, nodes) {
@@ -428,7 +438,7 @@ module.exports.CreateAmtManager = function(parent) {
438
439 // Check that the mesh exists
440 const mesh = parent.webserver.meshes[dev.meshid];
431 - if (mesh == null) { removeDevice(dev.nodeid); return; }
441 + if (mesh == null) { removeAmtDevice(dev); return; }
442
443 // Get the node and change it if needed
444 parent.db.Get(dev.nodeid, function (err, nodes) {
@@ -532,7 +542,7 @@ module.exports.CreateAmtManager = function(parent) {
542 function attemptSyncClockEx(stack, name, response, status) {
543 const dev = stack.dev;
544 if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
535 - if (status != 200) { removeDevice(dev.nodeid); return; }
545 + if (status != 200) { removeAmtDevice(dev); return; }
546
547 // Compute how much drift between Intel AMT and our clock.
548 var t = new Date(), now = new Date();
@@ -552,14 +562,194 @@ module.exports.CreateAmtManager = function(parent) {
562 function attemptSyncClockSet(stack, name, responses, status) {
563 const dev = stack.dev;
564 if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
555 - if (status != 200) { removeDevice(dev.nodeid); }
565 + if (status != 200) { removeAmtDevice(dev); }
566 devTaskCompleted(dev)
567 }
568
569 + // Check if Intel AMT TLS state is correct
570 + function attemptTlsSync(dev, func) {
571 + if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
572 +
573 + // Fetch Intel AMT setup policy
574 + // mesh.amt.type: 0 = No Policy, 1 = Deactivate CCM, 2 = Manage in CCM, 3 = Manage in ACM
575 + // mesh.amt.cirasetup: 0 = No Change, 1 = Remove CIRA, 2 = Setup CIRA
576 + const mesh = parent.webserver.meshes[dev.meshid];
577 + if (mesh == null) { dev.consoleMsg("Unable to find device group."); removeAmtDevice(dev); return; }
578 + var amtPolicy = 0, ciraPolicy = 0;
579 + if (mesh.amt != null) { if (mesh.amt.type) { amtPolicy = mesh.amt.type; } if (mesh.amt.cirasetup) { ciraPolicy = mesh.amt.cirasetup; } }
580 + if (amtPolicy < 2) { ciraPolicy = 0; }
581 + dev.policy = { amtPolicy: amtPolicy, ciraPolicy: ciraPolicy }
582 +
583 + if (amtPolicy < 2) {
584 + // No policy or deactivation, do nothing.
585 + dev.consoleMsg("No server policy for Intel AMT");
586 + func();
587 + } else {
588 + // Manage in CCM or ACM
589 + dev.taskCount = 1;
590 + dev.taskCompleted = func;
591 + // TODO: We only deal with certificates starting with Intel AMT 6 and beyond
592 + dev.amtstack.BatchEnum(null, ['AMT_PublicKeyCertificate', 'AMT_PublicPrivateKeyPair', 'AMT_TLSSettingData', 'AMT_TLSCredentialContext'], attemptTlsSyncEx);
593 + }
594 + }
595 +
596 + function attemptTlsSyncEx(stack, name, responses, status) {
597 + const dev = stack.dev;
598 + if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
599 + if (status != 200) { dev.consoleMsg("Failed to get security information."); removeAmtDevice(dev); return; }
600 +
601 + // Setup the certificates
602 + dev.policy.certPrivateKeys = responses['AMT_PublicPrivateKeyPair'].responses;
603 + dev.policy.tlsSettings = responses['AMT_TLSSettingData'].responses;
604 + dev.policy.tlsCredentialContext = responses['AMT_TLSCredentialContext'].responses;
605 + var xxCertificates = responses['AMT_PublicKeyCertificate'].responses;
606 + for (var i in xxCertificates) {
607 + xxCertificates[i].TrustedRootCertficate = (xxCertificates[i]['TrustedRootCertficate'] == true);
608 + xxCertificates[i].X509Certificate = Buffer.from(xxCertificates[i]['X509Certificate'], 'base64').toString('binary');
609 + xxCertificates[i].XIssuer = parseCertName(xxCertificates[i]['Issuer']);
610 + xxCertificates[i].XSubject = parseCertName(xxCertificates[i]['Subject']);
611 + }
612 + amtcert_linkCertPrivateKey(xxCertificates, dev.policy.certPrivateKeys);
613 + dev.policy.certificates = xxCertificates;
614 +
615 + // Find the current TLS certificate & MeshCentral root certificate
616 + var xxTlsCurrentCert = null;
617 + if (dev.policy.tlsCredentialContext.length > 0) {
618 + var certInstanceId = dev.policy.tlsCredentialContext[0]['ElementInContext']['ReferenceParameters']['SelectorSet']['Selector']['Value'];
619 + for (var i in dev.policy.certificates) { if (dev.policy.certificates[i]['InstanceID'] == certInstanceId) { xxTlsCurrentCert = i; } }
620 + }
621 +
622 + // This is a managed device and TLS is not enabled, turn it on.
623 + if (xxTlsCurrentCert == null) {
624 + // Start by generating a key pair
625 + dev.amtstack.AMT_PublicKeyManagementService_GenerateKeyPair(0, 2048, function (stack, name, responses, status) {
626 + const dev = stack.dev;
627 + if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
628 + if (status != 200) { dev.consoleMsg("Failed to generate a key pair."); removeAmtDevice(dev); return; }
629 +
630 + // Get the new key pair
631 + dev.amtstack.Enum('AMT_PublicPrivateKeyPair', function (stack, name, responses, status, tag) {
632 + const dev = stack.dev;
633 + if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
634 + if (status != 200) { dev.consoleMsg("Failed to get a key pair list."); removeAmtDevice(dev); return; }
635 +
636 + // Get the new DER key
637 + var DERKey = null;
638 + for (var i in responses) { if (responses[i]['InstanceID'] == tag) { DERKey = responses[i]['DERKey']; } }
639 +
640 + // Get certificate values
641 + const commonName = 'IntelAMT-' + Buffer.from(parent.crypto.randomBytes(6), 'binary').toString('hex');
642 + const domain = parent.config.domains[dev.domainid];
643 + var serverName = 'MeshCentral';
644 + if ((domain != null) && (domain.title != null)) { serverName = domain.title; }
645 + const certattributes = { 'CN': commonName, 'O': serverName, 'ST': serverName, 'C': serverName };
646 + const issuerattributes = { 'CN': obj.rootCertCN };
647 + const xxCaPrivateKey = obj.parent.certificates.root.key;
648 +
649 + // Set the extended key usages
650 + var extKeyUsage = { name: 'extKeyUsage', serverAuth: true, clientAuth: true }
651 +
652 + // Sign the key pair using the CA certifiate
653 + const cert = amtcert_createCertificate(certattributes, xxCaPrivateKey, DERKey, issuerattributes, extKeyUsage);
654 + if (cert == null) { dev.consoleMsg("Failed to sign the TLS certificate."); removeAmtDevice(dev); return; }
655 +
656 + // Place the resulting signed certificate back into AMT
657 + var pem = obj.parent.certificateOperations.forge.pki.certificateToPem(cert).replace(/(\r\n|\n|\r)/gm, '');
658 + dev.amtstack.AMT_PublicKeyManagementService_AddCertificate(pem.substring(27, pem.length - 25), function (stack, name, responses, status) {
659 + const dev = stack.dev;
660 + if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
661 + if (status != 200) { dev.consoleMsg("Failed to add TLS certificate."); removeAmtDevice(dev); return; }
662 + var certInstanceId = responses.Body['CreatedCertificate']['ReferenceParameters']['SelectorSet']['Selector']['Value'];
663 +
664 + // Set the TLS certificate
665 + dev.setTlsSecurityPendingCalls = 3;
666 + if (dev.policy.tlsCredentialContext.length > 0) {
667 + // Modify the current context
668 + var newTLSCredentialContext = Clone(dev.policy.tlsCredentialContext[0]);
669 + newTLSCredentialContext['ElementInContext']['ReferenceParameters']['SelectorSet']['Selector']['Value'] = certInstanceId;
670 + dev.amtstack.Put('AMT_TLSCredentialContext', newTLSCredentialContext, amtSwitchToTls, 0, 1);
671 + } else {
672 + // Add a new security context
673 + dev.amtstack.Create('AMT_TLSCredentialContext', {
674 + 'ElementInContext': '<a:Address>/wsman</a:Address><a:ReferenceParameters><w:ResourceURI>' + dev.amtstack.CompleteName('AMT_PublicKeyCertificate') + '</w:ResourceURI><w:SelectorSet><w:Selector Name="InstanceID">' + certInstanceId + '</w:Selector></w:SelectorSet></a:ReferenceParameters>',
675 + 'ElementProvidingContext': '<a:Address>/wsman</a:Address><a:ReferenceParameters><w:ResourceURI>' + dev.amtstack.CompleteName('AMT_TLSProtocolEndpointCollection') + '</w:ResourceURI><w:SelectorSet><w:Selector Name="ElementName">TLSProtocolEndpointInstances Collection</w:Selector></w:SelectorSet></a:ReferenceParameters>'
676 + }, amtSwitchToTls);
677 + }
678 +
679 + // Figure out what index is local & remote
680 + var localNdx = ((dev.policy.tlsSettings[0]['InstanceID'] == 'Intel(r) AMT LMS TLS Settings')) ? 0 : 1, remoteNdx = (1 - localNdx);
681 +
682 + // Remote TLS settings
683 + var xxTlsSettings2 = Clone(dev.policy.tlsSettings);
684 + xxTlsSettings2[remoteNdx]['Enabled'] = true;
685 + xxTlsSettings2[remoteNdx]['MutualAuthentication'] = false;
686 + xxTlsSettings2[remoteNdx]['AcceptNonSecureConnections'] = true;
687 + delete xxTlsSettings2[remoteNdx]['TrustedCN'];
688 +
689 + // Local TLS settings
690 + xxTlsSettings2[localNdx]['Enabled'] = true;
691 + delete xxTlsSettings2[localNdx]['TrustedCN'];
692 +
693 + // Update TLS settings
694 + dev.amtstack.Put('AMT_TLSSettingData', xxTlsSettings2[0], amtSwitchToTls, 0, 1, xxTlsSettings2[0]);
695 + dev.amtstack.Put('AMT_TLSSettingData', xxTlsSettings2[1], amtSwitchToTls, 0, 1, xxTlsSettings2[1]);
696 + });
697 +
698 + }, responses.Body['KeyPair']['ReferenceParameters']['SelectorSet']['Selector']['Value']);
699 + });
700 + } else {
701 + // TLS is setup
702 + devTaskCompleted(dev);
703 + }
704 + }
705 +
706 + function amtSwitchToTls(stack, name, responses, status) {
707 + const dev = stack.dev;
708 + if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
709 + if (status != 200) { dev.consoleMsg("Failed setup TLS."); removeAmtDevice(dev); return; }
710 +
711 + // Check if all the calls are done & perform a commit
712 + if ((--dev.setTlsSecurityPendingCalls) == 0) {
713 + dev.amtstack.AMT_SetupAndConfigurationService_CommitChanges(null, function (stack, name, responses, status) {
714 + const dev = stack.dev;
715 + if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
716 + if (status != 200) { dev.consoleMsg("Failed perform commit."); removeAmtDevice(dev); return; }
717 + dev.consoleMsg("Enabled TLS");
718 + // TODO: Switch our communications to TLS.
719 + devTaskCompleted(dev);
720 + });
721 + }
722 + }
723 +
724 + // Check if Intel AMT has the server root certificate
725 + function attemptRootCertSync(dev, func) {
726 + if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
727 + if (dev.policy.ciraPolicy != 2) { func(); return; } // Server root certificate does not need to be present is CIRA is not needed
728 +
729 + // Find the current TLS certificate & MeshCentral root certificate
730 + var xxMeshCentralRoot = null;
731 + if (dev.policy.tlsCredentialContext.length > 0) {
732 + for (var i in dev.policy.certificates) { if (dev.policy.certificates[i]['X509Certificate'] == obj.rootCertBase64) { xxMeshCentralRoot = i; } }
733 + }
734 +
735 + // If the server root certificate is not present and we need to configure CIRA, add it
736 + if (xxMeshCentralRoot == null) {
737 + dev.taskCount = 1;
738 + dev.taskCompleted = func;
739 + dev.amtstack.AMT_PublicKeyManagementService_AddTrustedRootCertificate(obj.rootCertBase64, function (stack, name, responses, status) {
740 + const dev = stack.dev;
741 + if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
742 + if (status != 200) { dev.consoleMsg("Failed to add server root certificate."); removeAmtDevice(dev); return; }
743 + dev.consoleMsg("Added server root certificate.");
744 + devTaskCompleted(dev);
745 + });
746 + } else { func(); }
747 + }
748 +
749 function attemptFetchHardwareInventory(dev, func) {
750 if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
751 const mesh = parent.webserver.meshes[dev.meshid];
562 - if (mesh == null) { removeDevice(dev.nodeid); return; }
752 + if (mesh == null) { removeAmtDevice(dev); return; }
753 if (mesh.mtype == 1) { // If this is a Intel AMT only device group, pull the hardware inventory and network information for this device
754 dev.consoleMsg("Fetching hardware inventory.");
755 dev.taskCount = 2;
@@ -571,7 +761,7 @@ module.exports.CreateAmtManager = function(parent) {
761 }
762 }
763
574 - //
764 + // Called this when a task is completed, when all tasks are completed the call back function will be called.
765 function devTaskCompleted(dev) {
766 dev.taskCount--;
767 if (dev.taskCount == 0) { var f = dev.taskCompleted; delete dev.taskCount; delete dev.taskCompleted; if (f != null) { f(); } }
@@ -679,7 +869,7 @@ module.exports.CreateAmtManager = function(parent) {
869 if (m.PartNumber) { m2.PartNumber = m.PartNumber.trim(); }
870 if (typeof m.SerialNumber == 'string') { m2.SerialNumber = m.SerialNumber.trim(); }
871 if (typeof m.SerialNumber == 'number') { m2.SerialNumber = m.SerialNumber; }
682 - if (typeof m.SerialNumber == 'string') { m2.Manufacturer = m.Manufacturer.trim(); }
872 + if (typeof m.Manufacturer == 'string') { m2.Manufacturer = m.Manufacturer.trim(); }
873 if (typeof m.Manufacturer == 'number') { m2.Manufacturer = m.Manufacturer; }
874 memory.push(m2);
875 }
@@ -740,5 +930,110 @@ module.exports.CreateAmtManager = function(parent) {
930
931 function guidToStr(g) { return g.substring(6, 8) + g.substring(4, 6) + g.substring(2, 4) + g.substring(0, 2) + '-' + g.substring(10, 12) + g.substring(8, 10) + '-' + g.substring(14, 16) + g.substring(12, 14) + '-' + g.substring(16, 20) + '-' + g.substring(20); }
932
933 + // Check which key pair matches the public key in the certificate
934 + function amtcert_linkCertPrivateKey(certs, keys) {
935 + for (var i in certs) {
936 + var cert = certs[i];
937 + try {
938 + if (keys.length == 0) return;
939 + var b = obj.parent.certificateOperations.forge.asn1.fromDer(cert.X509Certificate);
940 + var a = obj.parent.certificateOperations.forge.pki.certificateFromAsn1(b).publicKey;
941 + var publicKeyPEM = obj.parent.certificateOperations.forge.pki.publicKeyToPem(a).substring(28 + 32).replace(/(\r\n|\n|\r)/gm, "");
942 + for (var j = 0; j < keys.length; j++) {
943 + if (publicKeyPEM === (keys[j]['DERKey'] + '-----END PUBLIC KEY-----')) {
944 + keys[j].XCert = cert; // Link the key pair to the certificate
945 + cert.XPrivateKey = keys[j]; // Link the certificate to the key pair
946 + }
947 + }
948 + } catch (e) { console.log(e); }
949 + }
950 + }
951 +
952 + function Clone(v) { return JSON.parse(JSON.stringify(v)); }
953 +
954 + function parseCertName(x) {
955 + var j, r = {}, xx = x.split(',');
956 + for (var i in xx) { j = xx[i].indexOf('='); r[xx[i].substring(0, j)] = xx[i].substring(j + 1); }
957 + return r;
958 + }
959 +
960 + /*
961 + function amtcert_signWithCaKey(DERKey, caPrivateKey, certAttributes, issuerAttributes, extKeyUsage) {
962 + return amtcert_createCertificate(certAttributes, caPrivateKey, DERKey, issuerAttributes, extKeyUsage);
963 + }
964 + */
965 +
966 + // --- Extended Key Usage OID's ---
967 + // 1.3.6.1.5.5.7.3.1 = TLS Server certificate
968 + // 1.3.6.1.5.5.7.3.2 = TLS Client certificate
969 + // 2.16.840.1.113741.1.2.1 = Intel AMT Remote Console
970 + // 2.16.840.1.113741.1.2.2 = Intel AMT Local Console
971 + // 2.16.840.1.113741.1.2.3 = Intel AMT Client Setup Certificate (Zero-Touch)
972 +
973 + // Generate a certificate with a set of attributes signed by a rootCert. If the rootCert is obmitted, the generated certificate is self-signed.
974 + function amtcert_createCertificate(certAttributes, caPrivateKey, DERKey, issuerAttributes, extKeyUsage) {
975 + // Generate a keypair and create an X.509v3 certificate
976 + var keys, cert = obj.parent.certificateOperations.forge.pki.createCertificate();
977 + cert.publicKey = obj.parent.certificateOperations.forge.pki.publicKeyFromPem('-----BEGIN PUBLIC KEY-----' + DERKey + '-----END PUBLIC KEY-----');
978 + cert.serialNumber = '' + Math.floor((Math.random() * 100000) + 1);
979 + cert.validity.notBefore = new Date(2018, 0, 1);
980 + //cert.validity.notBefore.setFullYear(cert.validity.notBefore.getFullYear() - 1); // Create a certificate that is valid one year before, to make sure out-of-sync clocks don't reject this cert.
981 + cert.validity.notAfter = new Date(2049, 11, 31);
982 + //cert.validity.notAfter.setFullYear(cert.validity.notAfter.getFullYear() + 20);
983 + var attrs = [];
984 + if (certAttributes['CN']) attrs.push({ name: 'commonName', value: certAttributes['CN'] });
985 + if (certAttributes['C']) attrs.push({ name: 'countryName', value: certAttributes['C'] });
986 + if (certAttributes['ST']) attrs.push({ shortName: 'ST', value: certAttributes['ST'] });
987 + if (certAttributes['O']) attrs.push({ name: 'organizationName', value: certAttributes['O'] });
988 + cert.setSubject(attrs);
989 +
990 + // Use root attributes
991 + var rootattrs = [];
992 + if (issuerAttributes['CN']) rootattrs.push({ name: 'commonName', value: issuerAttributes['CN'] });
993 + if (issuerAttributes['C']) rootattrs.push({ name: 'countryName', value: issuerAttributes['C'] });
994 + if (issuerAttributes['ST']) rootattrs.push({ shortName: 'ST', value: issuerAttributes['ST'] });
995 + if (issuerAttributes['O']) rootattrs.push({ name: 'organizationName', value: issuerAttributes['O'] });
996 + cert.setIssuer(rootattrs);
997 +
998 + if (extKeyUsage == null) { extKeyUsage = { name: 'extKeyUsage', serverAuth: true, } } else { extKeyUsage.name = 'extKeyUsage'; }
999 +
1000 + /*
1001 + {
1002 + name: 'extKeyUsage',
1003 + serverAuth: true,
1004 + clientAuth: true,
1005 + codeSigning: true,
1006 + emailProtection: true,
1007 + timeStamping: true,
1008 + '2.16.840.1.113741.1.2.1': true
1009 + }
1010 + */
1011 +
1012 + // Create a leaf certificate
1013 + cert.setExtensions([{
1014 + name: 'basicConstraints'
1015 + }, {
1016 + name: 'keyUsage',
1017 + keyCertSign: true,
1018 + digitalSignature: true,
1019 + nonRepudiation: true,
1020 + keyEncipherment: true,
1021 + dataEncipherment: true
1022 + }, extKeyUsage, {
1023 + name: 'nsCertType',
1024 + client: true,
1025 + server: true,
1026 + email: true,
1027 + objsign: true,
1028 + }, {
1029 + name: 'subjectKeyIdentifier'
1030 + }]);
1031 +
1032 + // Self-sign certificate
1033 + var privatekey = obj.parent.certificateOperations.forge.pki.privateKeyFromPem(caPrivateKey);
1034 + cert.sign(privatekey, obj.parent.certificateOperations.forge.md.sha256.create());
1035 + return cert;
1036 + }
1037 +
1038 return obj;
1039 };