use of org.mozilla.jss.pkcs11.PK11Cert in project jss by dogtagpki.
the class JSSEngineReferenceImpl method updateHandshakeState.
private void updateHandshakeState() {
debug("JSSEngine: updateHandshakeState()");
// already failed.
if (seen_exception) {
return;
}
// If we're already done, we should check for SSL ALerts.
if (!step_handshake && handshake_state == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
debug("JSSEngine.updateHandshakeState() - not handshaking");
unknown_state_count = 0;
ssl_exception = checkSSLAlerts();
seen_exception = (ssl_exception != null);
return;
}
// alerts.
if (!step_handshake && handshake_state == SSLEngineResult.HandshakeStatus.FINISHED) {
debug("JSSEngine.updateHandshakeState() - FINISHED to NOT_HANDSHAKING");
// need to call SSL.ForceHandshake().
if (returned_finished) {
handshake_state = SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
}
unknown_state_count = 0;
ssl_exception = checkSSLAlerts();
seen_exception = (ssl_exception != null);
return;
}
// Since we're not obviously done handshaking, and the last time we
// were called, we were still handshaking, step the handshake.
debug("JSSEngine.updateHandshakeState() - forcing handshake");
if (SSL.ForceHandshake(ssl_fd) == SSL.SECFailure) {
int error_value = PR.GetError();
if (error_value != PRErrors.WOULD_BLOCK_ERROR) {
debug("JSSEngine.updateHandshakeState() - FATAL " + getStatus());
ssl_exception = new SSLHandshakeException("Error duing SSL.ForceHandshake() :: " + errorText(error_value));
seen_exception = true;
handshake_state = SSLEngineResult.HandshakeStatus.NEED_WRAP;
return;
}
}
// Check if we've just finished handshaking.
debug("JSSEngine.updateHandshakeState() - read_buf.read=" + Buffer.ReadCapacity(read_buf) + " read_buf.write=" + Buffer.WriteCapacity(read_buf) + " write_buf.read=" + Buffer.ReadCapacity(write_buf) + " write_buf.write=" + Buffer.WriteCapacity(write_buf));
// Set NEED_WRAP when we have data to send to the client.
if (Buffer.ReadCapacity(write_buf) > 0 && handshake_state != SSLEngineResult.HandshakeStatus.NEED_WRAP) {
// Can't write; to read, we need to call wrap to provide more
// data to write.
debug("JSSEngine.updateHandshakeState() - can write " + Buffer.ReadCapacity(write_buf) + " bytes, NEED_WRAP to process");
handshake_state = SSLEngineResult.HandshakeStatus.NEED_WRAP;
unknown_state_count = 0;
return;
}
// call.
if (ssl_fd.handshakeComplete && Buffer.ReadCapacity(write_buf) == 0) {
debug("JSSEngine.updateHandshakeState() - handshakeComplete is " + ssl_fd.handshakeComplete + ", so we've just finished handshaking");
step_handshake = false;
handshake_state = SSLEngineResult.HandshakeStatus.FINISHED;
unknown_state_count = 0;
// handshaking.
try {
PK11Cert[] peer_chain = SSL.PeerCertificateChain(ssl_fd);
session.setPeerCertificates(peer_chain);
} catch (Exception e) {
String msg = "Unable to get peer's certificate chain: ";
msg += e.getMessage();
seen_exception = true;
ssl_exception = new SSLException(msg, e);
}
// Also update our session information here.
session.refreshData();
// Finally, fire any handshake completed event listeners now.
fireHandshakeComplete(new SSLHandshakeCompletedEvent(this));
return;
}
if (Buffer.ReadCapacity(read_buf) == 0 && handshake_state != SSLEngineResult.HandshakeStatus.NEED_UNWRAP) {
// Set NEED_UNWRAP when we have no data to read from the client.
debug("JSSEngine.updateHandshakeState() - can read " + Buffer.ReadCapacity(read_buf) + " bytes, NEED_UNWRAP to give us more");
handshake_state = SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
unknown_state_count = 0;
return;
}
unknown_state_count += 1;
if (unknown_state_count >= 4) {
if (handshake_state == SSLEngineResult.HandshakeStatus.NEED_WRAP) {
handshake_state = SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
} else {
handshake_state = SSLEngineResult.HandshakeStatus.NEED_WRAP;
}
unknown_state_count = 1;
}
}
use of org.mozilla.jss.pkcs11.PK11Cert in project jss by dogtagpki.
the class PKCS12Util method storeCertIntoNSS.
/**
* Store a certificate (and key, if present) in NSSDB.
*/
public void storeCertIntoNSS(PKCS12 pkcs12, Password password, PKCS12CertInfo certInfo, boolean overwrite) throws Exception {
CryptoManager cm = CryptoManager.getInstance();
CryptoToken ct = cm.getInternalKeyStorageToken();
CryptoStore store = ct.getCryptoStore();
String nickname = certInfo.getFriendlyName();
for (X509Certificate cert : cm.findCertsByNickname(nickname)) {
if (!overwrite) {
return;
}
store.deleteCert(cert);
}
X509CertImpl certImpl = certInfo.getCert();
X509Certificate cert;
byte[] keyID = certInfo.getKeyID();
if (keyID != null) {
// cert has key
logger.debug("Importing private key for " + certInfo.getFriendlyName());
PKCS12KeyInfo keyInfo = pkcs12.getKeyInfoByID(keyID);
importKey(pkcs12, password, certInfo.getFriendlyName(), keyInfo);
logger.debug("Importing user certificate " + certInfo.getFriendlyName());
cert = cm.importUserCACertPackage(certImpl.getEncoded(), certInfo.getFriendlyName());
} else {
// cert has no key
logger.debug("Importing CA certificate " + certInfo.getFriendlyName());
// Note: JSS does not preserve CA certificate nickname
cert = cm.importCACertPackage(certImpl.getEncoded());
}
String trustFlags = certInfo.getTrustFlags();
if (trustFlags != null && trustFlagsEnabled) {
PK11Cert pk11Cert = (PK11Cert) cert;
pk11Cert.setTrustFlags(trustFlags);
}
}
use of org.mozilla.jss.pkcs11.PK11Cert in project jss by dogtagpki.
the class PKCS12Util method createCertInfoFromNSS.
public PKCS12CertInfo createCertInfoFromNSS(X509Certificate cert, String friendlyName) throws Exception {
// generate cert ID from SHA-1 hash of cert data
byte[] id = SafeBag.getLocalKeyIDFromCert(cert.getEncoded());
if (friendlyName == null) {
friendlyName = cert.getNickname();
}
X509CertImpl certImpl = new X509CertImpl(cert.getEncoded());
PK11Cert p11Cert = (PK11Cert) cert;
String trustFlags = p11Cert.getTrustFlags();
PKCS12CertInfo certInfo = new PKCS12CertInfo();
certInfo.setID(id);
certInfo.setFriendlyName(friendlyName);
certInfo.setCert(certImpl);
certInfo.setTrustFlags(trustFlags);
return certInfo;
}
use of org.mozilla.jss.pkcs11.PK11Cert in project jss by dogtagpki.
the class JSSTrustManager method getAcceptedIssuers.
@Override
public X509Certificate[] getAcceptedIssuers() {
logger.debug("JSSTrustManager: getAcceptedIssuers():");
Collection<X509Certificate> caCerts = new ArrayList<>();
try {
CryptoManager manager = CryptoManager.getInstance();
for (org.mozilla.jss.crypto.X509Certificate cert : manager.getCACerts()) {
logger.debug("JSSTrustManager: - " + cert.getSubjectDN());
try {
PK11Cert caCert = (PK11Cert) cert;
caCert.checkValidity();
caCerts.add(caCert);
} catch (Exception e) {
logger.debug("JSSTrustManager: invalid CA certificate: " + e);
}
}
} catch (NotInitializedException e) {
logger.error("JSSTrustManager: Unable to get CryptoManager: " + e, e);
throw new RuntimeException(e);
}
return caCerts.toArray(new X509Certificate[caCerts.size()]);
}
use of org.mozilla.jss.pkcs11.PK11Cert in project jss by dogtagpki.
the class TestBufferPRFD method TestSSLHandshake.
public static void TestSSLHandshake(String server_nickname, String client_nickname) throws Exception {
/* Constants */
String host = "localhost";
byte[] peer_info = host.getBytes();
/* Find SSL Server Certificate */
CryptoManager manager = CryptoManager.getInstance();
PK11Cert server_cert = (PK11Cert) manager.findCertByNickname(server_nickname);
PK11PrivKey server_key = (PK11PrivKey) manager.findPrivKeyByCert(server_cert);
assert (server_cert != null);
assert (server_key != null);
/* Find SSL Client Certificate, if nickname given. */
PK11Cert client_cert = null;
if (client_nickname != null) {
client_cert = (PK11Cert) manager.findCertByNickname(client_nickname);
assert (client_cert != null);
}
/* Create Buffers and BufferPRFDs */
BufferProxy read_buf = Buffer.Create(1024);
BufferProxy write_buf = Buffer.Create(1024);
assert (read_buf != null);
assert (write_buf != null);
PRFDProxy c_buffer = PR.NewBufferPRFD(read_buf, write_buf, peer_info);
PRFDProxy s_buffer = PR.NewBufferPRFD(write_buf, read_buf, peer_info);
assert (c_buffer != null);
assert (s_buffer != null);
SSLFDProxy c_nspr = Setup_NSS_Client(c_buffer, host);
SSLFDProxy s_nspr = Setup_NSS_Server(s_buffer, host, server_cert, server_key);
assert (c_nspr != null);
assert (s_nspr != null);
/* Apply Client Certificate, if given. When given, request it as the
* server. */
if (client_cert != null) {
c_nspr.SetClientCert(client_cert);
assert (SSL.AttachClientCertCallback(c_nspr) == SSL.SECSuccess);
assert (SSL.OptionSet(s_nspr, SSL.REQUEST_CERTIFICATE, 1) == SSL.SECSuccess);
}
/* Attach alert logging callback handler. */
assert (SSL.EnableAlertLogging(c_nspr) == SSL.SECSuccess);
assert (SSL.EnableAlertLogging(s_nspr) == SSL.SECSuccess);
assert (!IsHandshakeFinished(c_nspr, s_nspr));
/* Try a handshake */
int count = 0;
while (!IsHandshakeFinished(c_nspr, s_nspr)) {
if (SSL.ForceHandshake(c_nspr) != SSL.SECSuccess) {
int error = PR.GetError();
if (error != PRErrors.WOULD_BLOCK_ERROR) {
System.out.println("Unexpected error: " + new String(PR.ErrorToName(error)) + " (" + error + ")");
System.exit(1);
}
}
if (SSL.ForceHandshake(s_nspr) != SSL.SECSuccess) {
int error = PR.GetError();
if (error != PRErrors.WOULD_BLOCK_ERROR) {
System.out.println("Unexpected error: " + new String(PR.ErrorToName(error)) + " (" + error + ")");
System.exit(1);
}
}
count += 1;
if (count >= 40) {
System.err.println("Error: unable to make progress after " + count + " steps!");
System.exit(1);
}
}
System.out.println("Handshake completed successfully!\n");
assert (IsHandshakeFinished(c_nspr, s_nspr));
/* Test peer data */
assert (SSL.PeerCertificate(c_nspr) != null);
assert (SSL.PeerCertificateChain(c_nspr) != null);
if (client_nickname == null) {
assert (SSL.PeerCertificate(s_nspr) == null);
assert (SSL.PeerCertificateChain(s_nspr) == null);
} else {
assert (SSL.PeerCertificate(s_nspr) != null);
assert (SSL.PeerCertificateChain(s_nspr) != null);
}
/* Send data from client -> server */
byte[] client_message = "Cooking MCs".getBytes();
assert (PR.Write(c_nspr, client_message) == client_message.length);
byte[] server_received = PR.Read(s_nspr, client_message.length);
assert (server_received != null);
if (server_received.length != client_message.length) {
System.out.println("Expected a client message of length " + client_message.length + " but got one of " + server_received.length);
System.exit(1);
}
for (int i = 0; i < client_message.length && i < server_received.length; i++) {
if (client_message[i] != server_received[i]) {
System.out.println("Received byte " + server_received[i] + " on server but expected " + client_message[i]);
System.exit(1);
}
}
/* Send data from server -> client */
byte[] server_message = "like a pound of bacon".getBytes();
assert (PR.Write(s_nspr, server_message) == server_message.length);
byte[] client_received = PR.Read(c_nspr, server_message.length);
assert (client_received != null);
if (client_received.length != server_message.length) {
System.out.println("Expected a server message of length " + server_message.length + " but got one of " + client_received.length);
System.exit(1);
}
for (int i = 0; i < server_message.length && i < client_received.length; i++) {
if (server_message[i] != client_received[i]) {
System.out.println("Received byte " + client_received[i] + " on client but expected " + server_message[i]);
System.exit(1);
}
}
/* Close connections */
assert (PR.Shutdown(c_nspr, PR.SHUTDOWN_BOTH) == PR.SUCCESS);
assert (PR.Shutdown(s_nspr, PR.SHUTDOWN_BOTH) == PR.SUCCESS);
/* Print all alerts. */
for (SSLAlertEvent alert : c_nspr.inboundAlerts) {
System.err.println("client inbound: " + alert);
}
for (SSLAlertEvent alert : c_nspr.outboundAlerts) {
System.err.println("client outbound: " + alert);
}
for (SSLAlertEvent alert : s_nspr.inboundAlerts) {
System.err.println("server inbound: " + alert);
}
for (SSLAlertEvent alert : s_nspr.outboundAlerts) {
System.err.println("server outbound: " + alert);
}
/* Clean up */
assert (PR.Close(c_nspr) == PR.SUCCESS);
assert (PR.Close(s_nspr) == PR.SUCCESS);
Buffer.Free(read_buf);
Buffer.Free(write_buf);
}
Aggregations