use of sun.security.util.DerValue in project jdk8u_jdk by JetBrains.
the class KDC method processAsReq.
/**
* Processes a AS_REQ and generates a AS_REP (or KRB_ERROR)
* @param in the request
* @return the response
* @throws java.lang.Exception for various errors
*/
protected byte[] processAsReq(byte[] in) throws Exception {
ASReq asReq = new ASReq(in);
int[] eTypes = null;
List<PAData> outPAs = new ArrayList<>();
PrincipalName service = asReq.reqBody.sname;
if (options.containsKey(KDC.Option.RESP_NT)) {
service = new PrincipalName((int) options.get(KDC.Option.RESP_NT), service.getNameStrings(), Realm.getDefault());
}
try {
System.out.println(realm + "> " + asReq.reqBody.cname + " sends AS-REQ for " + service + ", " + asReq.reqBody.kdcOptions);
KDCReqBody body = asReq.reqBody;
eTypes = KDCReqBodyDotEType(body);
int eType = eTypes[0];
EncryptionKey ckey = keyForUser(body.cname, eType, false);
EncryptionKey skey = keyForUser(service, eType, true);
if (options.containsKey(KDC.Option.ONLY_RC4_TGT)) {
int tgtEType = EncryptedData.ETYPE_ARCFOUR_HMAC;
boolean found = false;
for (int i = 0; i < eTypes.length; i++) {
if (eTypes[i] == tgtEType) {
found = true;
break;
}
}
if (!found) {
throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);
}
skey = keyForUser(service, tgtEType, true);
}
if (ckey == null) {
throw new KrbException(Krb5.KDC_ERR_ETYPE_NOSUPP);
}
if (skey == null) {
// TODO
throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP);
}
// Session key
EncryptionKey key = generateRandomKey(eType);
// Check time, TODO
KerberosTime till = body.till;
if (till == null) {
// TODO
throw new KrbException(Krb5.KDC_ERR_NEVER_VALID);
} else if (till.isZero()) {
till = new KerberosTime(new Date().getTime() + 1000 * 3600 * 11);
}
//body.from
boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX + 1];
if (body.kdcOptions.get(KDCOptions.FORWARDABLE)) {
List<String> sensitives = (List<String>) options.get(Option.SENSITIVE_ACCOUNTS);
if (sensitives != null && sensitives.contains(body.cname.toString())) {
// Cannot make FORWARDABLE
} else {
bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;
}
}
if (body.kdcOptions.get(KDCOptions.RENEWABLE)) {
bFlags[Krb5.TKT_OPTS_RENEWABLE] = true;
//renew = new KerberosTime(new Date().getTime() + 1000 * 3600 * 24 * 7);
}
if (body.kdcOptions.get(KDCOptions.PROXIABLE)) {
bFlags[Krb5.TKT_OPTS_PROXIABLE] = true;
}
if (body.kdcOptions.get(KDCOptions.POSTDATED)) {
bFlags[Krb5.TKT_OPTS_POSTDATED] = true;
}
if (body.kdcOptions.get(KDCOptions.ALLOW_POSTDATE)) {
bFlags[Krb5.TKT_OPTS_MAY_POSTDATE] = true;
}
bFlags[Krb5.TKT_OPTS_INITIAL] = true;
// Creating PA-DATA
DerValue[] pas2 = null, pas = null;
if (options.containsKey(KDC.Option.DUP_ETYPE)) {
int n = (Integer) options.get(KDC.Option.DUP_ETYPE);
switch(n) {
case // customer's case in 7067974
1:
pas2 = new DerValue[] { new DerValue(new ETypeInfo2(1, null, null).asn1Encode()), new DerValue(new ETypeInfo2(1, "", null).asn1Encode()), new DerValue(new ETypeInfo2(1, realm, new byte[] { 1 }).asn1Encode()) };
pas = new DerValue[] { new DerValue(new ETypeInfo(1, null).asn1Encode()), new DerValue(new ETypeInfo(1, "").asn1Encode()), new DerValue(new ETypeInfo(1, realm).asn1Encode()) };
break;
case // we still reject non-null s2kparams and prefer E2 over E
2:
pas2 = new DerValue[] { new DerValue(new ETypeInfo2(1, realm, new byte[] { 1 }).asn1Encode()), new DerValue(new ETypeInfo2(1, null, null).asn1Encode()), new DerValue(new ETypeInfo2(1, "", null).asn1Encode()) };
pas = new DerValue[] { new DerValue(new ETypeInfo(1, realm).asn1Encode()), new DerValue(new ETypeInfo(1, null).asn1Encode()), new DerValue(new ETypeInfo(1, "").asn1Encode()) };
break;
case // but only E is wrong
3:
pas = new DerValue[] { new DerValue(new ETypeInfo(1, realm).asn1Encode()), new DerValue(new ETypeInfo(1, null).asn1Encode()), new DerValue(new ETypeInfo(1, "").asn1Encode()) };
break;
case // we also ignore rc4-hmac
4:
pas = new DerValue[] { new DerValue(new ETypeInfo(23, "ANYTHING").asn1Encode()), new DerValue(new ETypeInfo(1, null).asn1Encode()), new DerValue(new ETypeInfo(1, "").asn1Encode()) };
break;
case // "" should be wrong, but we accept it now
5:
// See s.s.k.internal.PAData$SaltAndParams
pas = new DerValue[] { new DerValue(new ETypeInfo(1, "").asn1Encode()), new DerValue(new ETypeInfo(1, null).asn1Encode()) };
break;
}
} else {
int[] epas = eTypes;
if (options.containsKey(KDC.Option.RC4_FIRST_PREAUTH)) {
for (int i = 1; i < epas.length; i++) {
if (epas[i] == EncryptedData.ETYPE_ARCFOUR_HMAC) {
epas[i] = epas[0];
epas[0] = EncryptedData.ETYPE_ARCFOUR_HMAC;
break;
}
}
;
} else if (options.containsKey(KDC.Option.ONLY_ONE_PREAUTH)) {
epas = new int[] { eTypes[0] };
}
pas2 = new DerValue[epas.length];
for (int i = 0; i < epas.length; i++) {
pas2[i] = new DerValue(new ETypeInfo2(epas[i], epas[i] == EncryptedData.ETYPE_ARCFOUR_HMAC ? null : getSalt(body.cname), null).asn1Encode());
}
boolean allOld = true;
for (int i : eTypes) {
if (i == EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96 || i == EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96) {
allOld = false;
break;
}
}
if (allOld) {
pas = new DerValue[epas.length];
for (int i = 0; i < epas.length; i++) {
pas[i] = new DerValue(new ETypeInfo(epas[i], epas[i] == EncryptedData.ETYPE_ARCFOUR_HMAC ? null : getSalt(body.cname)).asn1Encode());
}
}
}
DerOutputStream eid;
if (pas2 != null) {
eid = new DerOutputStream();
eid.putSequence(pas2);
outPAs.add(new PAData(Krb5.PA_ETYPE_INFO2, eid.toByteArray()));
}
if (pas != null) {
eid = new DerOutputStream();
eid.putSequence(pas);
outPAs.add(new PAData(Krb5.PA_ETYPE_INFO, eid.toByteArray()));
}
PAData[] inPAs = KDCReqDotPAData(asReq);
if (inPAs == null || inPAs.length == 0) {
Object preauth = options.get(Option.PREAUTH_REQUIRED);
if (preauth == null || preauth.equals(Boolean.TRUE)) {
throw new KrbException(Krb5.KDC_ERR_PREAUTH_REQUIRED);
}
} else {
try {
EncryptedData data = newEncryptedData(new DerValue(inPAs[0].getValue()));
EncryptionKey pakey = keyForUser(body.cname, data.getEType(), false);
data.decrypt(pakey, KeyUsage.KU_PA_ENC_TS);
} catch (Exception e) {
throw new KrbException(Krb5.KDC_ERR_PREAUTH_FAILED);
}
bFlags[Krb5.TKT_OPTS_PRE_AUTHENT] = true;
}
TicketFlags tFlags = new TicketFlags(bFlags);
EncTicketPart enc = new EncTicketPart(tFlags, key, body.cname, new TransitedEncoding(1, new byte[0]), new KerberosTime(new Date()), body.from, till, body.rtime, body.addresses, null);
Ticket t = new Ticket(service, new EncryptedData(skey, enc.asn1Encode(), KeyUsage.KU_TICKET));
EncASRepPart enc_part = new EncASRepPart(key, new LastReq(new LastReqEntry[] { new LastReqEntry(0, new KerberosTime(new Date().getTime() - 10000)) }), // TODO: detect replay?
body.getNonce(), new KerberosTime(new Date().getTime() + 1000 * 3600 * 24), // Next 5 and last MUST be same with ticket
tFlags, new KerberosTime(new Date()), body.from, till, body.rtime, service, body.addresses);
EncryptedData edata = new EncryptedData(ckey, enc_part.asn1Encode(), KeyUsage.KU_ENC_AS_REP_PART);
ASRep asRep = new ASRep(outPAs.toArray(new PAData[outPAs.size()]), body.cname, t, edata);
System.out.println(" Return " + asRep.cname + " ticket for " + asRep.ticket.sname + ", flags " + tFlags);
DerOutputStream out = new DerOutputStream();
out.write(DerValue.createTag(DerValue.TAG_APPLICATION, true, (byte) Krb5.KRB_AS_REP), asRep.asn1Encode());
byte[] result = out.toByteArray();
// Added feature:
// Write the current issuing TGT into a ccache file specified
// by the system property below.
String ccache = System.getProperty("test.kdc.save.ccache");
if (ccache != null) {
asRep.encKDCRepPart = enc_part;
sun.security.krb5.internal.ccache.Credentials credentials = new sun.security.krb5.internal.ccache.Credentials(asRep);
CredentialsCache cache = CredentialsCache.create(asReq.reqBody.cname, ccache);
if (cache == null) {
throw new IOException("Unable to create the cache file " + ccache);
}
cache.update(credentials);
cache.save();
}
return result;
} catch (KrbException ke) {
ke.printStackTrace(System.out);
KRBError kerr = ke.getError();
KDCReqBody body = asReq.reqBody;
System.out.println(" Error " + ke.returnCode() + " " + ke.returnCodeMessage());
byte[] eData = null;
if (kerr == null) {
if (ke.returnCode() == Krb5.KDC_ERR_PREAUTH_REQUIRED || ke.returnCode() == Krb5.KDC_ERR_PREAUTH_FAILED) {
DerOutputStream bytes = new DerOutputStream();
bytes.write(new PAData(Krb5.PA_ENC_TIMESTAMP, new byte[0]).asn1Encode());
for (PAData p : outPAs) {
bytes.write(p.asn1Encode());
}
DerOutputStream temp = new DerOutputStream();
temp.write(DerValue.tag_Sequence, bytes);
eData = temp.toByteArray();
}
kerr = new KRBError(null, null, null, new KerberosTime(new Date()), 0, ke.returnCode(), body.cname, service, KrbException.errorMessage(ke.returnCode()), eData);
}
return kerr.asn1Encode();
}
}
use of sun.security.util.DerValue in project jdk8u_jdk by JetBrains.
the class X509CertSelector method matchSubjectPublicKeyAlgID.
/* match on subject public key algorithm OID */
private boolean matchSubjectPublicKeyAlgID(X509Certificate xcert) {
if (subjectPublicKeyAlgID == null) {
return true;
}
try {
byte[] encodedKey = xcert.getPublicKey().getEncoded();
DerValue val = new DerValue(encodedKey);
if (val.tag != DerValue.tag_Sequence) {
throw new IOException("invalid key format");
}
AlgorithmId algID = AlgorithmId.parse(val.data.getDerValue());
if (debug != null) {
debug.println("X509CertSelector.match: subjectPublicKeyAlgID = " + subjectPublicKeyAlgID + ", xcert subjectPublicKeyAlgID = " + algID.getOID());
}
if (!subjectPublicKeyAlgID.equals((Object) algID.getOID())) {
if (debug != null) {
debug.println("X509CertSelector.match: " + "subject public key alg IDs don't match");
}
return false;
}
} catch (IOException e5) {
if (debug != null) {
debug.println("X509CertSelector.match: IOException in subject " + "public key algorithm OID check");
}
return false;
}
return true;
}
use of sun.security.util.DerValue in project dbeaver by dbeaver.
the class PKCS1Util method loadPrivateKeyFromPKCS1.
public static PrivateKey loadPrivateKeyFromPKCS1(String privateKeyPem) throws GeneralSecurityException, IOException {
DerInputStream derReader = new DerInputStream(Base64.decode(privateKeyPem));
DerValue[] seq = derReader.getSequence(0);
if (seq.length < 9) {
throw new GeneralSecurityException("Could not parse a PKCS1 private key.");
}
// skip version seq[0];
BigInteger modulus = seq[1].getBigInteger();
BigInteger publicExp = seq[2].getBigInteger();
BigInteger privateExp = seq[3].getBigInteger();
BigInteger prime1 = seq[4].getBigInteger();
BigInteger prime2 = seq[5].getBigInteger();
BigInteger exp1 = seq[6].getBigInteger();
BigInteger exp2 = seq[7].getBigInteger();
BigInteger crtCoef = seq[8].getBigInteger();
RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(keySpec);
}
use of sun.security.util.DerValue in project Payara by payara.
the class BaseContainerCallbackHandler method processPrivateKey.
private void processPrivateKey(PrivateKeyCallback privKeyCallback) {
KeyStore[] kstores = secSup.getKeyStores();
if (_logger.isLoggable(Level.FINE)) {
_logger.log(Level.FINE, "JMAC: In PrivateKeyCallback Processor");
}
// make sure we have a keystore
if (kstores == null || kstores.length == 0) {
// cannot get any information
privKeyCallback.setKey(null, null);
return;
}
// get the request type
PrivateKeyCallback.Request req = privKeyCallback.getRequest();
PrivateKey privKey = null;
Certificate[] certs = null;
if (req == null) {
// no request type - set default key
PrivateKeyEntry pke = getDefaultPrivateKeyEntry(kstores);
if (pke != null) {
privKey = pke.getPrivateKey();
certs = pke.getCertificateChain();
}
privKeyCallback.setKey(privKey, certs);
return;
}
// find key based on request type
try {
if (req instanceof PrivateKeyCallback.AliasRequest) {
PrivateKeyCallback.AliasRequest aReq = (PrivateKeyCallback.AliasRequest) req;
String alias = aReq.getAlias();
PrivateKeyEntry privKeyEntry;
if (alias == null) {
// use default key
privKeyEntry = getDefaultPrivateKeyEntry(kstores);
} else {
privKeyEntry = sslUtils.getPrivateKeyEntryFromTokenAlias(alias);
}
if (privKeyEntry != null) {
privKey = privKeyEntry.getPrivateKey();
certs = privKeyEntry.getCertificateChain();
}
} else if (req instanceof PrivateKeyCallback.IssuerSerialNumRequest) {
PrivateKeyCallback.IssuerSerialNumRequest isReq = (PrivateKeyCallback.IssuerSerialNumRequest) req;
X500Principal issuer = isReq.getIssuer();
BigInteger serialNum = isReq.getSerialNum();
if (issuer != null && serialNum != null) {
boolean found = false;
for (int i = 0; i < kstores.length && !found; i++) {
Enumeration aliases = kstores[i].aliases();
while (aliases.hasMoreElements() && !found) {
String nextAlias = (String) aliases.nextElement();
PrivateKey key = secSup.getPrivateKeyForAlias(nextAlias, i);
if (key != null) {
Certificate[] certificates = kstores[i].getCertificateChain(nextAlias);
// check issuer/serial
X509Certificate eeCert = (X509Certificate) certificates[0];
if (eeCert.getIssuerX500Principal().equals(issuer) && eeCert.getSerialNumber().equals(serialNum)) {
privKey = key;
certs = certificates;
found = true;
}
}
}
}
}
} else if (req instanceof PrivateKeyCallback.SubjectKeyIDRequest) {
PrivateKeyCallback.SubjectKeyIDRequest skReq = (PrivateKeyCallback.SubjectKeyIDRequest) req;
byte[] subjectKeyID = skReq.getSubjectKeyID();
if (subjectKeyID != null) {
boolean found = false;
// In DER, subjectKeyID will be an OCTET STRING of OCTET STRING
DerValue derValue1 = new DerValue(DerValue.tag_OctetString, subjectKeyID);
DerValue derValue2 = new DerValue(DerValue.tag_OctetString, derValue1.toByteArray());
byte[] derSubjectKeyID = derValue2.toByteArray();
for (int i = 0; i < kstores.length && !found; i++) {
Enumeration aliases = kstores[i].aliases();
while (aliases.hasMoreElements() && !found) {
String nextAlias = (String) aliases.nextElement();
PrivateKey key = secSup.getPrivateKeyForAlias(nextAlias, i);
if (key != null) {
Certificate[] certificates = kstores[i].getCertificateChain(nextAlias);
X509Certificate eeCert = (X509Certificate) certificates[0];
// Extension: SubjectKeyIdentifier
byte[] derSubKeyID = eeCert.getExtensionValue(SUBJECT_KEY_IDENTIFIER_OID);
if (derSubKeyID != null && Arrays.equals(derSubKeyID, derSubjectKeyID)) {
privKey = key;
certs = certificates;
found = true;
}
}
}
}
}
} else if (req instanceof PrivateKeyCallback.DigestRequest) {
PrivateKeyCallback.DigestRequest dReq = (PrivateKeyCallback.DigestRequest) req;
byte[] digest = dReq.getDigest();
String algorithm = dReq.getAlgorithm();
PrivateKeyEntry privKeyEntry = null;
if (digest == null) {
// get default key
privKeyEntry = getDefaultPrivateKeyEntry(kstores);
} else {
if (algorithm == null) {
algorithm = DEFAULT_DIGEST_ALGORITHM;
}
MessageDigest md = MessageDigest.getInstance(algorithm);
privKeyEntry = getPrivateKeyEntry(kstores, md, digest);
}
if (privKeyEntry != null) {
privKey = privKeyEntry.getPrivateKey();
certs = privKeyEntry.getCertificateChain();
}
} else {
if (_logger.isLoggable(Level.FINE)) {
_logger.log(Level.FINE, "invalid request type: " + req.getClass().getName());
}
}
} catch (Exception e) {
// KeyStoreException
if (_logger.isLoggable(Level.FINE)) {
_logger.log(Level.FINE, "JMAC: In PrivateKeyCallback Processor: " + " Error reading key !", e);
}
} finally {
privKeyCallback.setKey(privKey, certs);
}
}
use of sun.security.util.DerValue in project Bytecoder by mirkosertic.
the class X509CertSelector method matchSubjectPublicKeyAlgID.
/* match on subject public key algorithm OID */
private boolean matchSubjectPublicKeyAlgID(X509Certificate xcert) {
if (subjectPublicKeyAlgID == null) {
return true;
}
try {
byte[] encodedKey = xcert.getPublicKey().getEncoded();
DerValue val = new DerValue(encodedKey);
if (val.tag != DerValue.tag_Sequence) {
throw new IOException("invalid key format");
}
AlgorithmId algID = AlgorithmId.parse(val.data.getDerValue());
if (debug != null) {
debug.println("X509CertSelector.match: subjectPublicKeyAlgID = " + subjectPublicKeyAlgID + ", xcert subjectPublicKeyAlgID = " + algID.getOID());
}
if (!subjectPublicKeyAlgID.equals(algID.getOID())) {
if (debug != null) {
debug.println("X509CertSelector.match: " + "subject public key alg IDs don't match");
}
return false;
}
} catch (IOException e5) {
if (debug != null) {
debug.println("X509CertSelector.match: IOException in subject " + "public key algorithm OID check");
}
return false;
}
return true;
}
Aggregations