diff options
author | PKI Team <PKI Team@c9f7a03b-bd48-0410-a16d-cbbf54688b0b> | 2008-03-18 22:36:57 +0000 |
---|---|---|
committer | PKI Team <PKI Team@c9f7a03b-bd48-0410-a16d-cbbf54688b0b> | 2008-03-18 22:36:57 +0000 |
commit | d0f2e4efbd3eb0f1d7f5a28e7f97c1fb4ec027bb (patch) | |
tree | 7e7473fae8af5ad7e6cda7eabbef787093fc59a7 /pki/base/util/src/com/netscape | |
parent | 273f8d85df5c31293a908185622b378c8f3cf7e8 (diff) | |
download | pki-d0f2e4efbd3eb0f1d7f5a28e7f97c1fb4ec027bb.tar.gz pki-d0f2e4efbd3eb0f1d7f5a28e7f97c1fb4ec027bb.tar.xz pki-d0f2e4efbd3eb0f1d7f5a28e7f97c1fb4ec027bb.zip |
Initial open source version based upon proprietary Red Hat Certificate System (RHCS) 7.3.
git-svn-id: svn+ssh://svn.fedorahosted.org/svn/pki/trunk@2 c9f7a03b-bd48-0410-a16d-cbbf54688b0b
Diffstat (limited to 'pki/base/util/src/com/netscape')
104 files changed, 10342 insertions, 0 deletions
diff --git a/pki/base/util/src/com/netscape/cmsutil/crypto/CryptoUtil.java b/pki/base/util/src/com/netscape/cmsutil/crypto/CryptoUtil.java new file mode 100644 index 000000000..73cb74db8 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/crypto/CryptoUtil.java @@ -0,0 +1,958 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.crypto; + + +import java.net.*; +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; + +import java.security.*; +import java.security.cert.CertificateException; +import java.security.cert.CertificateEncodingException; +import java.security.NoSuchAlgorithmException; +import java.security.interfaces.RSAPublicKey; +import java.security.interfaces.DSAPublicKey; +import java.security.interfaces.DSAParams; +import java.security.cert.*; + +import sun.misc.BASE64Encoder; +import sun.misc.BASE64Decoder; +import org.mozilla.jss.*; +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.util.*; +import org.mozilla.jss.pkix.primitive.*; +import org.mozilla.jss.pkix.crmf.*; +import org.mozilla.jss.pkcs7.ContentInfo; +import org.mozilla.jss.pkcs7.*; +import org.mozilla.jss.pkcs11.*; +import org.mozilla.jss.crypto.*; +import org.mozilla.jss.crypto.KeyPairGenerator; +import org.mozilla.jss.crypto.PrivateKey; +import org.mozilla.jss.crypto.Signature; +import org.mozilla.jss.crypto.X509Certificate; +import org.mozilla.jss.util.Base64OutputStream; + +import netscape.security.util.*; +import netscape.security.pkcs.*; +import netscape.security.x509.*; + + +public class CryptoUtil { + + public static final String CERTREQ_BEGIN_HEADING = "-----BEGIN CERTIFICATE REQUEST-----"; + public static final String CERTREQ_END_HEADING = "-----END CERTIFICATE REQUEST-----"; + public static final int LINE_COUNT = 76; + public static final String CERT_BEGIN_HEADING = "-----BEGIN CERTIFICATE-----"; + public static final String CERT_END_HEADING = "-----END CERTIFICATE-----"; + + /* + * encodes cert + */ + private static BASE64Encoder mEncoder = new BASE64Encoder(); + public static String toMIME64(X509CertImpl cert) { + try { + return + "-----BEGIN CERTIFICATE-----\n" + + mEncoder.encodeBuffer(cert.getEncoded()) + + "-----END CERTIFICATE-----\n"; + } catch (Exception e) {} + return null; + } + + public static boolean arraysEqual(byte[] bytes, byte[] ints) { + if (bytes == null || ints == null) { + return false; + } + + if (bytes.length != ints.length) { + return false; + } + + for (int i = 0; i < bytes.length; i++) { + if (bytes[i] != ints[i]) { + return false; + } + } + return true; + } + + /** + * Retrieves handle to a JSS token. + */ + public static CryptoToken getTokenByName(String token) + throws CryptoManager.NotInitializedException, + NoSuchTokenException { + CryptoManager cm = CryptoManager.getInstance(); + CryptoToken t = null; + + if (token.equals("internal")) { + t = cm.getInternalKeyStorageToken(); + } else { + t = cm.getTokenByName(token); + } + return t; + } + + /** + * Generates a RSA key pair. + */ + public static KeyPair generateRSAKeyPair(String token, int keysize) + throws CryptoManager.NotInitializedException, + NoSuchTokenException, + NoSuchAlgorithmException, + TokenException { + CryptoToken t = getTokenByName(token); + KeyPairGenerator g = t.getKeyPairGenerator(KeyPairAlgorithm.RSA); + + g.initialize(keysize); + KeyPair pair = g.genKeyPair(); + + return pair; + } + + public static boolean isECCKey(X509Key key) + { + String keyAlgo = key.getAlgorithm(); + if (keyAlgo.equals("EC") || + keyAlgo.equals("OID.1.2.840.10045.44")) { // ECC + return true; + } + return false; + } + + /** + * Generates an ecc key pair. + */ + public static KeyPair generateECCKeyPair(String token, int keysize) + throws CryptoManager.NotInitializedException, + NoSuchTokenException, + NoSuchAlgorithmException, + TokenException { + CryptoToken t = getTokenByName(token); + KeyPairAlgorithm alg = KeyPairAlgorithm.EC; + KeyPairGenerator g = t.getKeyPairGenerator(alg); + + g.initialize(keysize); + KeyPair pair = g.genKeyPair(); + + return pair; + } + + public static byte[] getModulus(PublicKey pubk) { + RSAPublicKey rsaKey = (RSAPublicKey) pubk; + + return rsaKey.getModulus().toByteArray(); + } + + public static byte[] getPublicExponent(PublicKey pubk) { + RSAPublicKey rsaKey = (RSAPublicKey) pubk; + + return rsaKey.getPublicExponent().toByteArray(); + } + + public static String base64Encode(byte[] bytes) throws IOException { + // All this streaming is lame, but Base64OutputStream needs a + // PrintStream + ByteArrayOutputStream output = new ByteArrayOutputStream(); + Base64OutputStream b64 = new Base64OutputStream(new + PrintStream(new + FilterOutputStream(output))); + + b64.write(bytes); + b64.flush(); + + // This is internationally safe because Base64 chars are + // contained within 8859_1 + return output.toString("8859_1"); + } + + public static byte[] base64Decode(String s) throws IOException { + BASE64Decoder base64 = new BASE64Decoder(); + byte[] d = base64.decodeBuffer(s); + + return d; + } + + /* + * formats a cert request + */ + public static String reqFormat(String content) { + int beginIndex = CERTREQ_BEGIN_HEADING.length(); + int endIndex = CERTREQ_END_HEADING.length(); + + String result = CERTREQ_BEGIN_HEADING + "\n"; + int index = 0; + + while (content.length() >= LINE_COUNT) { + result = result + content.substring(0, LINE_COUNT) + "\n"; + content = content.substring(LINE_COUNT); + } + if (content.length() > 0) { + result = result + content + "\n" + CERTREQ_END_HEADING; + } else { + result = result + CERTREQ_END_HEADING; + } + + return result; + } + + public static String getPKCS10FromKey(String dn, + byte modulus[], byte exponent[], byte prikdata[]) + throws IOException, + InvalidKeyException, + TokenException, + NoSuchProviderException, + CertificateException, + SignatureException, + CryptoManager.NotInitializedException, + NoSuchAlgorithmException + { + X509Key x509key = getPublicX509Key(modulus, exponent); + PrivateKey prik = findPrivateKeyFromID(prikdata); + PKCS10 pkcs10 = createCertificationRequest(dn, x509key, prik); + ByteArrayOutputStream bs = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(bs); + pkcs10.print(ps); + return bs.toString(); + } + + /* + * formats a cert + */ + public static String certFormat(String content) { + if (content == null || content.length() == 0) { + return ""; + } + int beginIndex = CERT_BEGIN_HEADING.length(); + int endIndex = CERT_END_HEADING.length(); + + String result = CERT_BEGIN_HEADING + "\n"; + int index = 0; + + while (content.length() >= LINE_COUNT) { + result = result + content.substring(0, LINE_COUNT) + "\n"; + content = content.substring(LINE_COUNT); + } + if (content.length() > 0) { + result = result + content + "\n" + CERT_END_HEADING; + } else { + result = result + CERT_END_HEADING; + } + + return result; + } + + /** + * strips out the begin and end certificate brackets + * @param s the string potentially bracketed with + * "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" + * @return string without the brackets + */ + public static String stripCertBrackets(String s) { + if (s == null) { + return s; + } + + if (s.startsWith(CERT_BEGIN_HEADING) && s.endsWith(CERT_END_HEADING)) { + return (s.substring(27, (s.length() - 25))); + } + + // To support Thawte's header and footer + if ((s.startsWith("-----BEGIN PKCS #7 SIGNED DATA-----")) + && (s.endsWith("-----END PKCS #7 SIGNED DATA-----"))) { + return (s.substring(35, (s.length() - 33))); + } + + return s; + } + + public static String normalizeCertAndReq(String s) { + if (s == null) { + return s; + } + s = s.replaceAll("-----BEGIN CERTIFICATE REQUEST-----", ""); + s = s.replaceAll("-----BEGIN NEW CERTIFICATE REQUEST-----", ""); + s = s.replaceAll("-----END CERTIFICATE REQUEST-----", ""); + s = s.replaceAll("-----END NEW CERTIFICATE REQUEST-----", ""); + s = s.replaceAll("-----BEGIN CERTIFICATE-----", ""); + s = s.replaceAll("-----END CERTIFICATE-----", ""); + + StringBuffer sb = new StringBuffer(); + StringTokenizer st = new StringTokenizer(s, "\r\n "); + + while (st.hasMoreTokens()) { + String nextLine = st.nextToken(); + + nextLine = nextLine.trim(); + if (nextLine.equals("-----BEGIN CERTIFICATE REQUEST-----")) { + continue; + } + if (nextLine.equals("-----BEGIN NEW CERTIFICATE REQUEST-----")) { + continue; + } + if (nextLine.equals("-----END CERTIFICATE REQUEST-----")) { + continue; + } + if (nextLine.equals("-----END NEW CERTIFICATE REQUEST-----")) { + continue; + } + if (nextLine.equals("-----BEGIN CERTIFICATE-----")) { + continue; + } + if (nextLine.equals("-----END CERTIFICATE-----")) { + continue; + } + sb.append(nextLine); + } + return sb.toString(); + } + + public static String normalizeCertStr(String s) { + String val = ""; + + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == '\n') { + continue; + } else if (s.charAt(i) == '\r') { + continue; + } else if (s.charAt(i) == '"') { + continue; + } else if (s.charAt(i) == ' ') { + continue; + } + val += s.charAt(i); + } + return val; + } + + public static void importCertificateChain(String certchain) + throws IOException, + CryptoManager.NotInitializedException, + TokenException, + CertificateEncodingException, + CertificateException + { + byte[] blah = base64Decode(certchain); + CryptoManager manager = CryptoManager.getInstance(); + PKCS7 pkcs7 = null; + try { + // try PKCS7 first + pkcs7 = new PKCS7(blah); + } catch (Exception e) { + } + X509Certificate cert = null; + if (pkcs7 == null) { + cert = manager.importCACertPackage(blah); + } else { + java.security.cert.X509Certificate certsInP7[] = + pkcs7.getCertificates(); + if (certsInP7 == null) { + cert = manager.importCACertPackage(blah); + } else { + for (int i = 0; i < certsInP7.length; i++) { + // import P7 one by one + cert = manager.importCACertPackage(certsInP7[i].getEncoded()); + } + } + } + X509Certificate[] certchains = + CryptoManager.getInstance().buildCertificateChain(cert); + + if (certchains != null) { + cert = certchains[certchains.length - 1]; + } + InternalCertificate icert = (InternalCertificate) cert; + icert.setSSLTrust( InternalCertificate.TRUSTED_CA + | InternalCertificate.TRUSTED_CLIENT_CA + | InternalCertificate.VALID_CA); + } + + public static SEQUENCE parseCRMFMsgs(byte cert_request[]) + throws IOException, InvalidBERException + { + ByteArrayInputStream crmfBlobIn = + new ByteArrayInputStream(cert_request); + SEQUENCE crmfMsgs = (SEQUENCE) + new SEQUENCE.OF_Template(new CertReqMsg.Template()).decode( + crmfBlobIn); + return crmfMsgs; + } + + public static X509Key getX509KeyFromCRMFMsgs(SEQUENCE crmfMsgs) + throws IOException, NoSuchAlgorithmException, + InvalidKeyException, InvalidKeyFormatException + { + int nummsgs = crmfMsgs.size(); + if (nummsgs <= 0) { + throw new IOException("invalid certificate requests"); + } + CertReqMsg msg = (CertReqMsg) crmfMsgs.elementAt(0); + CertRequest certreq = msg.getCertReq(); + CertTemplate certTemplate = certreq.getCertTemplate(); + SubjectPublicKeyInfo spkinfo = certTemplate.getPublicKey(); + PublicKey pkey = spkinfo.toPublicKey(); + X509Key x509key = convertPublicKeyToX509Key(pkey); + return x509key; + } + + public static X509Key getPublicX509Key(byte modulus[], byte exponent[]) + throws InvalidKeyException { + return new netscape.security.provider.RSAPublicKey(new BigInt(modulus), + new BigInt(exponent)); + } + + public static X509Key getPublicX509ECCKey(byte encoded[]) + throws InvalidKeyException { + try { + return X509Key.parse(new DerValue(encoded)); + } catch (IOException e) { + throw new InvalidKeyException(); + } + } + + public static X509Key convertPublicKeyToX509Key(PublicKey pubk) + throws InvalidKeyException { + X509Key xKey; + + if (pubk instanceof RSAPublicKey) { + RSAPublicKey rsaKey = (RSAPublicKey) pubk; + + xKey = new netscape.security.provider.RSAPublicKey( + new BigInt(rsaKey.getModulus()), + new BigInt(rsaKey.getPublicExponent())); + } else { + // Assert.assert(pubk instanceof DSAPublicKey); + DSAPublicKey dsaKey = (DSAPublicKey) pubk; + DSAParams params = dsaKey.getParams(); + + xKey = new netscape.security.provider.DSAPublicKey(dsaKey.getY(), + params.getP(), params.getQ(), params.getG()); + } + return xKey; + } + + public static String getSubjectName(SEQUENCE crmfMsgs) + throws IOException { + int nummsgs = crmfMsgs.size(); + if (nummsgs <= 0) { + throw new IOException("invalid certificate requests"); + } + CertReqMsg msg = (CertReqMsg) crmfMsgs.elementAt(0); + CertRequest certreq = msg.getCertReq(); + CertTemplate certTemplate = certreq.getCertTemplate(); + Name n = certTemplate.getSubject(); + ByteArrayOutputStream subjectEncStream = new ByteArrayOutputStream(); + n.encode(subjectEncStream); + + byte[] b = subjectEncStream.toByteArray(); + X500Name subject = new X500Name(b); + return subject.toString(); + } + + /** + * Creates a Certificate template. + */ + public static X509CertInfo createX509CertInfo(KeyPair pair, + int serialno, String issuername, String subjname, + Date notBefore, Date notAfter) + throws IOException, + CertificateException, + InvalidKeyException { + return createX509CertInfo(convertPublicKeyToX509Key(pair.getPublic()), + serialno, issuername, subjname, notBefore, notAfter); + } + + public static X509CertInfo createX509CertInfo(PublicKey publickey, + int serialno, String issuername, String subjname, + Date notBefore, Date notAfter) + throws IOException, + CertificateException, + InvalidKeyException { + return createX509CertInfo(convertPublicKeyToX509Key(publickey), serialno, + issuername, subjname, notBefore, notAfter); + } + + public static X509CertInfo createX509CertInfo(X509Key x509key, + int serialno, String issuername, String subjname, + Date notBefore, Date notAfter) + throws IOException, + CertificateException, + InvalidKeyException { + X509CertInfo info = new X509CertInfo(); + + info.set(X509CertInfo.VERSION, new + CertificateVersion(CertificateVersion.V3)); + info.set(X509CertInfo.SERIAL_NUMBER, new + CertificateSerialNumber(serialno)); + info.set(X509CertInfo.ISSUER, new + CertificateIssuerName(new X500Name(issuername))); + info.set(X509CertInfo.SUBJECT, new + CertificateSubjectName(new X500Name(subjname))); + info.set(X509CertInfo.VALIDITY, new + CertificateValidity(notBefore, notAfter)); + AlgorithmId sigAlgId = new AlgorithmId( + AlgorithmId.md5WithRSAEncryption_oid); + + info.set(X509CertInfo.ALGORITHM_ID, new + CertificateAlgorithmId(sigAlgId)); + info.set(X509CertInfo.KEY, new CertificateX509Key(x509key)); + info.set(X509CertInfo.EXTENSIONS, new CertificateExtensions()); + return info; + } + + + public static X509CertImpl signECCCert(PrivateKey privateKey, + X509CertInfo certInfo) + throws NoSuchTokenException, + CryptoManager.NotInitializedException, + NoSuchAlgorithmException, + NoSuchTokenException, + TokenException, + InvalidKeyException, + SignatureException, + IOException, + CertificateException + { + return signCert(privateKey, certInfo, + SignatureAlgorithm.ECSignatureWithSHA1Digest); + } + + /** + * Signs certificate. + */ + public static X509CertImpl signCert(PrivateKey privateKey, + X509CertInfo certInfo, SignatureAlgorithm sigAlg) + throws NoSuchTokenException, + CryptoManager.NotInitializedException, + NoSuchAlgorithmException, + NoSuchTokenException, + TokenException, + InvalidKeyException, + SignatureException, + IOException, + CertificateException { + + DerInputStream ds = new DerInputStream(ASN1Util.encode(sigAlg.toOID())); + ObjectIdentifier sigAlgOID = new ObjectIdentifier(ds); + AlgorithmId aid = new AlgorithmId(sigAlgOID); + certInfo.set(X509CertInfo.ALGORITHM_ID, + new CertificateAlgorithmId(aid)); + + org.mozilla.jss.crypto.PrivateKey priKey = + (org.mozilla.jss.crypto.PrivateKey) privateKey; + CryptoToken token = priKey.getOwningToken(); + + DerOutputStream tmp = new DerOutputStream(); + DerOutputStream out = new DerOutputStream(); + + certInfo.encode(tmp); + Signature signer = token.getSignatureContext(sigAlg); + + signer.initSign(priKey); + signer.update(tmp.toByteArray()); + byte signed[] = signer.sign(); + + aid.encode(tmp); + tmp.putBitString(signed); + out.write(DerValue.tag_Sequence, tmp); + X509CertImpl signedCert = new X509CertImpl(out.toByteArray()); + + return signedCert; + } + + /** + * Creates a PKCS#10 request. + */ + public static PKCS10 createCertificationRequest(String subjectName, + X509Key pubk, PrivateKey prik) + throws NoSuchAlgorithmException, NoSuchProviderException, + InvalidKeyException, IOException, CertificateException, + SignatureException { + X509Key key = pubk; + String alg = "MD5/RSA"; + if (isECCKey(key)) { + alg = "SHA1withEC"; + } + java.security.Signature sig = java.security.Signature.getInstance(alg, + "Mozilla-JSS"); + + sig.initSign(prik); + PKCS10 pkcs10 = new PKCS10(key); + X500Name name = new X500Name(subjectName); + X500Signer signer = new X500Signer(sig, name); + + pkcs10.encodeAndSign(signer); + return pkcs10; + } + + /** + * Creates a PKCS#10 request. + */ + public static PKCS10 createCertificationRequest(String subjectName, + KeyPair keyPair) + throws NoSuchAlgorithmException, NoSuchProviderException, + InvalidKeyException, IOException, CertificateException, + SignatureException { + PublicKey pubk = keyPair.getPublic(); + X509Key key = convertPublicKeyToX509Key(pubk); + String alg; + + if (pubk instanceof RSAPublicKey) { + alg = "MD5/RSA"; + } else { + // Assert.assert(pubk instanceof DSAPublicKey); + alg = "DSA"; + } + java.security.Signature sig = java.security.Signature.getInstance(alg, + "Mozilla-JSS"); + + sig.initSign(keyPair.getPrivate()); + + PKCS10 pkcs10 = new PKCS10(key); + + X500Name name = new X500Name(subjectName); + X500Signer signer = new X500Signer(sig, name); + + pkcs10.encodeAndSign(signer); + + return pkcs10; + } + + public static void unTrustCert(InternalCertificate cert) { + // remove TRUSTED_CA + int flag = cert.getSSLTrust(); + + flag ^= InternalCertificate.VALID_CA; + cert.setSSLTrust(flag); + } + + /** + * Trusts a certificate by nickname. + */ + public static void trustCertByNickname(String nickname) + throws CryptoManager.NotInitializedException, + TokenException { + CryptoManager cm = CryptoManager.getInstance(); + X509Certificate certs[] = cm.findCertsByNickname(nickname); + + if (certs == null) { + return; + } + for (int i = 0; i < certs.length; i++) { + trustCert((InternalCertificate) certs[i]); + } + } + + /** + * Trusts a certificate. + */ + public static void trustCert(InternalCertificate cert) { + int flag = InternalCertificate.VALID_CA | InternalCertificate.TRUSTED_CA + | InternalCertificate.USER + | InternalCertificate.TRUSTED_CLIENT_CA; + + cert.setSSLTrust(flag); + cert.setObjectSigningTrust(flag); + cert.setEmailTrust(flag); + } + + /** + * To certificate server point of view, SSL trust is + * what we referring. + */ + public static boolean isCertTrusted(InternalCertificate cert) { + if (isTrust(cert.getSSLTrust()) && isTrust(cert.getObjectSigningTrust()) + && isTrust(cert.getEmailTrust())) { + return true; + } else { + return false; + } + } + + public static boolean isTrust(int flag) { + if (((flag & InternalCertificate.VALID_CA) > 0) + && ((flag & InternalCertificate.TRUSTED_CA) > 0) + && ((flag & InternalCertificate.USER) > 0) + && ((flag & InternalCertificate.TRUSTED_CLIENT_CA) > 0)) { + return true; + } else { + return false; + } + } + + /** + * Generates a symmetric key. + */ + public static SymmetricKey generateKey(CryptoToken token, + KeyGenAlgorithm alg) + throws TokenException, NoSuchAlgorithmException, + IllegalStateException { + try { + KeyGenerator kg = token.getKeyGenerator(alg); + + return kg.generate(); + } catch (CharConversionException e) { + throw new RuntimeException( + "CharConversionException while generating symmetric key"); + } + } + + /** + * Compares 2 byte arrays to see if they are the same. + */ + public static boolean compare(byte src[], byte dest[]) { + if (src != null && dest != null) { + if (src.length == dest.length) { + boolean matched = true; + + for (int i = 0; i < src.length; i++) { + if (src[i] != dest[i]) { + matched = false; + } + } + if (matched) { + return true; + } + } + } + return false; + } + + public static String byte2string(byte id[]) { + return new BigInteger(id).toString(16); + } + + public static byte[] string2byte(String id) { + return (new BigInteger(id, 16)).toByteArray(); + } + + /** + * Retrieves a private key from a unique key ID. + */ + public static PrivateKey findPrivateKeyFromID(byte id[]) + throws CryptoManager.NotInitializedException, + TokenException { + CryptoManager cm = CryptoManager.getInstance(); + Enumeration enums = cm.getAllTokens(); + + while (enums.hasMoreElements()) { + CryptoToken token = (CryptoToken) enums.nextElement(); + String tokenName = token.getName(); + CryptoStore store = token.getCryptoStore(); + PrivateKey keys[] = store.getPrivateKeys(); + + if (keys != null) { + for (int i = 0; i < keys.length; i++) { + if (compare(keys[i].getUniqueID(), id)) { + return keys[i]; + } + } + } + } + return null; + } + + /** + * Retrieves all user certificates from all tokens. + */ + public static X509CertImpl[] getAllUserCerts() + throws CryptoManager.NotInitializedException, + TokenException { + Vector certs = new Vector(); + CryptoManager cm = CryptoManager.getInstance(); + Enumeration enums = cm.getAllTokens(); + + while (enums.hasMoreElements()) { + CryptoToken token = (CryptoToken) enums.nextElement(); + String tokenName = token.getName(); + + CryptoStore store = token.getCryptoStore(); + org.mozilla.jss.crypto.X509Certificate list[] = store.getCertificates(); + + for (int i = 0; i < list.length; i++) { + try { + PrivateKey key = cm.findPrivKeyByCert(list[i]); + X509CertImpl impl = null; + + try { + impl = new X509CertImpl(list[i].getEncoded()); + } catch (CertificateException e) { + continue; + } + certs.addElement(impl); + } catch (TokenException e) { + continue; + } catch (ObjectNotFoundException e) { + continue; + } + } + } + if (certs.size() == 0) { + return null; + } else { + X509CertImpl c[] = new X509CertImpl[certs.size()]; + + certs.copyInto(c); + return c; + } + } + + /** + * Deletes a private key. + */ + public static void deletePrivateKey(PrivateKey prikey) + throws CryptoManager.NotInitializedException, TokenException { + CryptoManager cm = CryptoManager.getInstance(); + + try { + CryptoToken token = prikey.getOwningToken(); + CryptoStore store = token.getCryptoStore(); + + store.deletePrivateKey(prikey); + } catch (NoSuchItemOnTokenException e) {} + } + + /** + * Retrieves a private key by nickname. + */ + public static PrivateKey getPrivateKey(String nickname) + throws CryptoManager.NotInitializedException, TokenException { + try { + CryptoManager cm = CryptoManager.getInstance(); + X509Certificate cert = cm.findCertByNickname(nickname); + org.mozilla.jss.crypto.PrivateKey prikey = cm.findPrivKeyByCert(cert); + + return prikey; + } catch (ObjectNotFoundException e) {} + return null; + } + + /** + * Deletes all certificates by a nickname. + */ + public static void deleteAllCertificates(String nickname) + throws CryptoManager.NotInitializedException, TokenException { + CryptoManager cm = CryptoManager.getInstance(); + X509Certificate certs[] = cm.findCertsByNickname(nickname); + + if (certs == null) { + return; + } + for (int i = 0; i < certs.length; i++) { + try { + X509Certificate cert = certs[i]; + org.mozilla.jss.crypto.PrivateKey prikey = cm.findPrivKeyByCert( + cert); + CryptoToken token = prikey.getOwningToken(); + CryptoStore store = token.getCryptoStore(); + + store.deleteCert(cert); + } catch (NoSuchItemOnTokenException e) {} catch (ObjectNotFoundException e) {} + } + } + + /** + * Imports a PKCS#7 certificate chain that includes the user + * certificate, and trusts the certificate. + */ + public static X509Certificate importUserCertificateChain(String c, + String nickname) + throws CryptoManager.NotInitializedException, + CryptoManager.NicknameConflictException, + CryptoManager.UserCertConflictException, + NoSuchItemOnTokenException, + TokenException, + CertificateEncodingException { + CryptoManager cm = CryptoManager.getInstance(); + X509Certificate cert = cm.importCertPackage(c.getBytes(), nickname); + + trustCertByNickname(nickname); + return cert; + } + + /** + * Imports a user certificate, and trusts the certificate. + */ + public static void importUserCertificate(X509CertImpl cert, String nickname) + throws CryptoManager.NotInitializedException, + CertificateEncodingException, + NoSuchItemOnTokenException, + TokenException, + CryptoManager.NicknameConflictException, + CryptoManager.UserCertConflictException { + CryptoManager cm = CryptoManager.getInstance(); + + cm.importUserCACertPackage(cert.getEncoded(), nickname); + trustCertByNickname(nickname); + } + + public static void importUserCertificate(X509CertImpl cert, String nickname, + boolean trust) + throws CryptoManager.NotInitializedException, + CertificateEncodingException, + NoSuchItemOnTokenException, + TokenException, + CryptoManager.NicknameConflictException, + CryptoManager.UserCertConflictException { + CryptoManager cm = CryptoManager.getInstance(); + + cm.importUserCACertPackage(cert.getEncoded(), nickname); + if (trust) + trustCertByNickname(nickname); + } + + public static java.security.cert.X509Certificate[] getX509CertificateFromPKCS7(byte[] b) throws IOException { + ByteArrayInputStream bis = new ByteArrayInputStream(b); + CertificateChain certchain = new CertificateChain(); + + certchain.decode(bis); + java.security.cert.X509Certificate[] certs = certchain.getChain(); + + return certs; + } +} + +// START ENABLE_ECC +// This following can be removed when JSS with ECC capability +// is integrated. +class CryptoAlgorithm extends Algorithm +{ + protected CryptoAlgorithm(int oidIndex, String name) { + super(oidIndex, name); + } +} + +class CryptoKeyPairAlgorithm extends KeyPairAlgorithm +{ + protected CryptoKeyPairAlgorithm(int oidIndex, String name, Algorithm algFamily) { super(oidIndex, name, algFamily); + } +} + +class CryptoSignatureAlgorithm extends SignatureAlgorithm +{ + protected CryptoSignatureAlgorithm(int oidIndex, String name, + SignatureAlgorithm signingAlg, DigestAlgorithm digestAlg, + OBJECT_IDENTIFIER oid) + { + super(oidIndex, name, signingAlg, digestAlg, oid); + } +} +// END ENABLE_ECC diff --git a/pki/base/util/src/com/netscape/cmsutil/crypto/Module.java b/pki/base/util/src/com/netscape/cmsutil/crypto/Module.java new file mode 100644 index 000000000..9a4fa800d --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/crypto/Module.java @@ -0,0 +1,75 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.crypto; + +import org.mozilla.jss.crypto.*; + +import java.util.*; + +public class Module { + // Common Name is the name given when module is added + private String mCommonName = ""; + // User friendly name is the name to be displayed on panel + private String mUserFriendlyName = ""; + private String mImagePath = ""; + // a Vector of Tokens + private Vector mTokens = null; + private boolean mFound = false; + + public Module (String name, String printName) { + mCommonName = name; + mUserFriendlyName = printName; + mTokens = new Vector(); + } + + public Module (String name, String printName, String image) { + mCommonName = name; + mUserFriendlyName = printName; + mImagePath = image; + mTokens = new Vector(); + } + + public void addToken(CryptoToken t) { + Token token = new Token(t); + mTokens.addElement(token); + } + + public String getCommonName() { + return mCommonName; + } + + public String getUserFriendlyName() { + return mUserFriendlyName; + } + + public String getImagePath() { + return mImagePath; + } + + public boolean isFound() { + return mFound; + } + + public void setFound(boolean isFound) { + mFound = isFound; + } + + public Vector getTokens() { + return mTokens; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/crypto/Token.java b/pki/base/util/src/com/netscape/cmsutil/crypto/Token.java new file mode 100644 index 000000000..801472676 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/crypto/Token.java @@ -0,0 +1,59 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.crypto; + +import java.util.*; +import org.mozilla.jss.*; +import org.mozilla.jss.crypto.*; + +public class Token { + CryptoToken mToken; + + public Token (CryptoToken token) { + mToken = token; + } + + public String getNickName() { + String nickName=""; + try { + nickName = mToken.getName(); + } catch (Exception e) { + } + return nickName; + } + + public boolean isLoggedIn() { + boolean isLoggedIn = false; + try { + isLoggedIn = mToken.isLoggedIn(); + } catch (Exception e) { + } + + return isLoggedIn; + } + + public boolean isPresent() { + boolean isPresent = false; + try { + isPresent = mToken.isPresent(); + } catch (Exception e) { + } + + return isPresent; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/http/ConnectAsync.java b/pki/base/util/src/com/netscape/cmsutil/http/ConnectAsync.java new file mode 100644 index 000000000..61d6d785f --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/http/ConnectAsync.java @@ -0,0 +1,55 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.http; + + +import java.net.*; +import java.io.*; +import netscape.ldap.*; +import org.mozilla.jss.ssl.*; + +import com.netscape.cmsutil.net.*; +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.crypto.X509Certificate; +import org.mozilla.jss.crypto.X509Certificate; + + +public class ConnectAsync extends Thread { + String host = null; + int port = 0; + ISocketFactory obj = null; + + public ConnectAsync(ISocketFactory sock, String host, int port) { + super(); + this.host = host; + this.port = port; + this.obj = sock; + setName("ConnectAsync"); + } + + public void run() { + try { + obj.makeSocket(host, port); + } catch (SocketException e) { + // Stop throwing exception + } catch (Exception e) { + // Stop throwing exception + } + } +} + diff --git a/pki/base/util/src/com/netscape/cmsutil/http/Http.java b/pki/base/util/src/com/netscape/cmsutil/http/Http.java new file mode 100644 index 000000000..acece15d1 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/http/Http.java @@ -0,0 +1,32 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.http; + + +public class Http { + public static final String HttpVers = "HTTP/1.0"; + + public static final String Vers1_0 = "HTTP/1.0"; + public static final String Vers1_1 = "HTTP/1.1"; + public static final String CRLF = "\r\n"; + + public static final char CR = '\r'; + public static final char LF = '\n'; + public static final char SP = ' '; + +} diff --git a/pki/base/util/src/com/netscape/cmsutil/http/HttpClient.java b/pki/base/util/src/com/netscape/cmsutil/http/HttpClient.java new file mode 100644 index 000000000..2efc72674 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/http/HttpClient.java @@ -0,0 +1,213 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.http; + +import java.net.Socket; +import java.io.*; +import com.netscape.cmsutil.net.*; +import org.mozilla.jss.ssl.*; + +/** + * basic http client. + * not optimized for performance. + * handles only string content. + */ +public class HttpClient { + protected ISocketFactory mFactory = null; + + protected Socket mSocket = null; + protected InputStream mInputStream = null; + protected OutputStream mOutputStream = null; + + protected InputStreamReader mInputStreamReader = null; + protected OutputStreamWriter mOutputStreamWriter = null; + protected BufferedReader mBufferedReader = null; + protected SSLCertificateApprovalCallback mCertApprovalCallback = null; + protected boolean mConnected = false; + + public HttpClient() { + } + + public HttpClient(ISocketFactory factory) { + mFactory = factory; + } + + public HttpClient(ISocketFactory factory, SSLCertificateApprovalCallback certApprovalCallback) { + mFactory = factory; + mCertApprovalCallback = certApprovalCallback; + } + + public void connect(String host, int port) + throws IOException { + if (mFactory != null) { + if (mCertApprovalCallback == null) { + mSocket = mFactory.makeSocket(host, port); + } else { + mSocket = mFactory.makeSocket(host, port, mCertApprovalCallback, null); + } + } else { + mSocket = new Socket(host, port); + } + + if (mSocket == null) { + IOException e = new IOException("Couldn't make connection"); + + throw e; + } + + mInputStream = mSocket.getInputStream(); + mOutputStream = mSocket.getOutputStream(); + mInputStreamReader = new InputStreamReader(mInputStream, "UTF8"); + mBufferedReader = new BufferedReader(mInputStreamReader); + mOutputStreamWriter = new OutputStreamWriter(mOutputStream, "UTF8"); + mConnected = true; + } + + // Inserted by beomsuk + public void connect(String host, int port, int timeout) + throws IOException { + if (mFactory != null) { + mSocket = mFactory.makeSocket(host, port, timeout); + } else { + mSocket = new Socket(host, port); + } + + if (mSocket == null) { + IOException e = new IOException("Couldn't make connection"); + + throw e; + } + + mInputStream = mSocket.getInputStream(); + mOutputStream = mSocket.getOutputStream(); + mInputStreamReader = new InputStreamReader(mInputStream, "UTF8"); + mBufferedReader = new BufferedReader(mInputStreamReader); + mOutputStreamWriter = new OutputStreamWriter(mOutputStream, "UTF8"); + mConnected = true; + } + + // Insert end + public boolean connected() { + return mConnected; + } + + /** + * Sends a request to http server. + * Returns a http response. + */ + public HttpResponse send(HttpRequest request) + throws IOException { + HttpResponse resp = new HttpResponse(); + + + if (mOutputStream == null) + throw new IOException("Output stream not initialized"); + request.write(mOutputStreamWriter); + try { + resp.parse(mBufferedReader); + } catch (IOException e) { + // XXX should we disconnect in all cases ? + disconnect(); + throw e; + } + disconnect(); + return resp; + } + + public void disconnect() + throws IOException { + mSocket.close(); + mInputStream = null; + mOutputStream = null; + mConnected = false; + } + + public InputStream getInputStream() { + return mInputStream; + } + + public OutputStream getOutputStream() { + return mOutputStream; + } + + public BufferedReader getBufferedReader() { + return mBufferedReader; + } + + public InputStreamReader getInputStreamReader() { + return mInputStreamReader; + } + + public OutputStreamWriter getOutputStreamWriter() { + return mOutputStreamWriter; + } + + public Socket getSocket() { + return mSocket; + } + + /** + * unit test + */ + public static void main(String args[]) + throws Exception { + HttpClient c = new HttpClient(); + HttpRequest req = new HttpRequest(); + HttpResponse resp = null; + + System.out.println("connecting to " + args[0] + " " + args[1]); + c.connect(args[0], Integer.parseInt(args[1])); + + req.setMethod("GET"); + req.setURI(args[2]); + if (args.length >= 4) + req.setHeader("Connection", args[3]); + resp = c.send(req); + + System.out.println("version " + resp.getHttpVers()); + System.out.println("status code " + resp.getStatusCode()); + System.out.println("reason " + resp.getReasonPhrase()); + System.out.println("content " + resp.getContent()); + + //String lenstr = resp.getHeader("Content-Length"); + //System.out.println("content len is "+lenstr); + //int length = Integer.parseInt(lenstr); + //char[] content = new char[length]; + //c.mBufferedReader.read(content, 0, content.length); + //System.out.println(content); + + if (args.length >= 4 && args[3].equalsIgnoreCase("keep-alive")) { + int len; + char[] msgbody; + + for (int i = 0; i < 2; i++) { + if (i == 1) req.setHeader("Connection", "Close"); + resp = c.send(req); + System.out.println("version " + resp.getHttpVers()); + System.out.println("status code " + resp.getStatusCode()); + System.out.println("reason " + resp.getReasonPhrase()); + System.out.println("content " + resp.getContent()); + //len = Integer.parseInt(resp.getHeader("Content-Length")); + //System.out.println("content len is "+len); + //msgbody = new char[len]; + //c.mBufferedReader.read(msgbody, 0, len); + //System.out.println(content); + } + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/http/HttpEofException.java b/pki/base/util/src/com/netscape/cmsutil/http/HttpEofException.java new file mode 100644 index 000000000..6944b386a --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/http/HttpEofException.java @@ -0,0 +1,32 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.http; + + +import java.io.IOException; + + +public class HttpEofException extends IOException { + public HttpEofException() { + super(); + } + + public HttpEofException(String msg) { + super(msg); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/http/HttpMessage.java b/pki/base/util/src/com/netscape/cmsutil/http/HttpMessage.java new file mode 100644 index 000000000..56c4a27f9 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/http/HttpMessage.java @@ -0,0 +1,163 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.http; + + +import java.io.*; +import java.util.Hashtable; +import java.util.Enumeration; + + +/** + * Basic HTTP Message, excluding message body. + * Not optimized for performance. + * Set fields or parse from input. + */ +public class HttpMessage { + protected String mLine = null; // request or response line. + protected Hashtable mHeaders = null; + protected String mContent = null; // arbitrary content chars assumed. + + /** + * Instantiate a HttpResponse for write to http client. + */ + public HttpMessage() { + mHeaders = new Hashtable(); + } + + /** + * Set a header field. <br> + * Content-length is automatically set on write.<br> + * If value spans multiple lines must be in proper http format for + * multiple lines. + */ + public void setHeader(String name, String value) { + if (mHeaders == null) + mHeaders = new Hashtable(); + mHeaders.put(name.toLowerCase(), value); + } + + /** + * get a header + */ + public String getHeader(String name) { + return (String) mHeaders.get(name.toLowerCase()); + } + + /** + * write http headers + * does not support values of more than one line + */ + public void writeHeaders(OutputStreamWriter writer) + throws IOException { + if (mHeaders != null) { + Enumeration keys = mHeaders.keys(); + String header, value; + + while (keys.hasMoreElements()) { + header = (String) keys.nextElement(); + value = (String) mHeaders.get(header); + writer.write(header + ":" + value + Http.CRLF); + } + } + writer.write(Http.CRLF); // end with CRLF line. + } + + /** + * read http headers. + * does not support values of more than one line or multivalue headers. + */ + public void readHeaders(BufferedReader reader) + throws IOException { + mHeaders = new Hashtable(); + + int colon; + String line, key, value; + + while (true) { + line = reader.readLine(); + if (line == null || line.equals("")) + break; + colon = line.indexOf(':'); + if (colon == -1) { + mHeaders = null; + throw new HttpProtocolException("Bad Http header format"); + } + key = line.substring(0, colon); + value = line.substring(colon + 1); + mHeaders.put(key.toLowerCase(), value.trim()); + } + } + + public void write(OutputStreamWriter writer) + throws IOException { + writer.write(mLine + Http.CRLF); + writeHeaders(writer); + writer.flush(); + if (mContent != null) { + writer.write(mContent); + } + writer.flush(); + } + + public void parse(BufferedReader reader) + throws IOException { + String line = reader.readLine(); + +// if (line == null) { + // throw new HttpEofException("End of stream reached"); + // } + if (line.equals("")) { + throw new HttpProtocolException("Bad Http req/resp line " + line); + } + mLine = line; + readHeaders(reader); + + // won't work if content length is not set. + String lenstr = (String) mHeaders.get("content-length"); + + if (lenstr != null) { + int len = Integer.parseInt(lenstr); + char[] cbuf = new char[len]; + int done = reader.read(cbuf, 0, cbuf.length); + int total = done; + + while (done >= 0 && total < len) { + done = reader.read(cbuf, total, len - total); + total += done; + } + + mContent = new String(cbuf); + } + } + + public void reset() { + mLine = null; + mHeaders = null; + mContent = null; + } + + public void setContent(String content) { + mContent = content; + } + + public String getContent() { + return mContent; + } + +} diff --git a/pki/base/util/src/com/netscape/cmsutil/http/HttpProtocolException.java b/pki/base/util/src/com/netscape/cmsutil/http/HttpProtocolException.java new file mode 100644 index 000000000..8a52f4f78 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/http/HttpProtocolException.java @@ -0,0 +1,32 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.http; + + +import java.io.IOException; + + +public class HttpProtocolException extends IOException { + public HttpProtocolException() { + super(); + } + + public HttpProtocolException(String msg) { + super(msg); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/http/HttpRequest.java b/pki/base/util/src/com/netscape/cmsutil/http/HttpRequest.java new file mode 100644 index 000000000..f22c50452 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/http/HttpRequest.java @@ -0,0 +1,139 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.http; + + +import java.io.*; +import java.util.Hashtable; +import java.util.Enumeration; + + +/** + * Basic HTTP Request. not optimized for performance. + * Set fields or parse from input. + * Handles text content. + */ +public class HttpRequest extends HttpMessage { + public static final String GET = "GET"; + public static final String POST = "POST"; + public static final String HEAD = "HEAD"; + + protected String mMethod = null; + protected String mURI = null; + protected String mHttpVers = null; + + /** + * Instantiate a HttpResponse for write to http client. + */ + public HttpRequest() { + super(); + } + + /** + * set set request method. + */ + public void setMethod(String method) + throws HttpProtocolException { + if (!method.equals(GET) && !method.equals(HEAD) && + !method.equals(POST)) + throw new HttpProtocolException("No such method " + method); + mMethod = method; + } + + /** + * set reason phrase. + */ + public void setURI(String uri) { + mURI = uri; + } + + /** + * write request to the http client + */ + public void write(OutputStreamWriter writer) + throws IOException { + if (mMethod == null || mURI == null) { + HttpProtocolException e = new HttpProtocolException( + "Http request method or uri not initialized"); + + //e.printStackTrace(); + throw e; + } + + mLine = mMethod + " " + mURI + " " + Http.HttpVers; + super.write(writer); + } + + /** + * parse a http request from a http client + */ + public void parse(BufferedReader reader) + throws IOException { + super.parse(reader); + + int method = mLine.indexOf(Http.SP); + + mMethod = mLine.substring(0, method); + if (!mMethod.equals(GET) && !mMethod.equals(POST) && + !mMethod.equals(HEAD)) { + reset(); + throw new HttpProtocolException("Bad Http request method"); + } + + int uri = mLine.lastIndexOf(Http.SP); + + mURI = mLine.substring(method + 1, uri); + + mHttpVers = mLine.substring(uri + 1); + if (!mHttpVers.equals("")) { + if (!mHttpVers.equals(Http.Vers1_0) && + !mHttpVers.equals(Http.Vers1_1)) { + reset(); + throw new HttpProtocolException("Bad Http version in request"); + } + } + } + + public void reset() { + mMethod = null; + mURI = null; + mHttpVers = null; + super.reset(); + } + + /** + * get method + */ + public String getMethod() { + return mMethod; + } + + /** + * get reason phrase + */ + public String getURI() { + return mURI; + } + + /** + * get http version + */ + public String getHttpVers() { + return mHttpVers; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/http/HttpResponse.java b/pki/base/util/src/com/netscape/cmsutil/http/HttpResponse.java new file mode 100644 index 000000000..9309f2bb1 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/http/HttpResponse.java @@ -0,0 +1,141 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.http; + + +import java.io.*; +import java.util.Hashtable; +import java.util.Enumeration; + + +/** + * Basic HTTP Response. + * Set fields or parse from input. + * Handles only text content. + */ +public class HttpResponse extends HttpMessage { + protected String mStatusCode = null; + protected String mReasonPhrase = null; + protected String mHttpVers = null; + + /** + * Instantiate a HttpResponse for write to http client. + */ + public HttpResponse() { + super(); + } + + /** + * set status code of response + */ + public void setStatusCode(int code) { + mStatusCode = String.valueOf(code); + } + + /** + * set reason phrase. + */ + public void setReasonPhrase(String phrase) { + mReasonPhrase = phrase; + } + + /** + * get status code + */ + public String getStatusCode() { + return mStatusCode; + } + + /** + * get reason phrase + */ + public String getReasonPhrase() { + return mReasonPhrase; + } + + /** + * write the response out to the http client + */ + public void write(OutputStreamWriter writer) + throws IOException { + if (mStatusCode == null) { + throw new HttpProtocolException("status code not set in response"); + } + // write status-line + mLine = Http.HttpVers + " " + mStatusCode + " "; + if (mReasonPhrase != null) + mLine += mReasonPhrase; + mLine += Http.CRLF; + super.write(writer); + } + + /** + * parse a http response from a http server + */ + public void parse(BufferedReader reader) + throws IOException { + mHttpVers = null; + mStatusCode = null; + mReasonPhrase = null; + + super.parse(reader); + + int httpvers = mLine.indexOf(' '); + + if (httpvers == -1) { + reset(); + throw new HttpProtocolException("no Http version in response"); + } + mHttpVers = mLine.substring(0, httpvers); + if (!mHttpVers.equals(Http.Vers1_0) && + !mHttpVers.equals(Http.Vers1_1)) { + reset(); + throw new HttpProtocolException("Bad Http version in response"); + } + + int code = mLine.indexOf(' ', httpvers + 1); + + if (code == -1) { + reset(); + throw new HttpProtocolException("no status code in response"); + } + mStatusCode = mLine.substring(httpvers + 1, code); + try { + Integer.parseInt(mStatusCode); + } catch (NumberFormatException e) { + reset(); + throw new HttpProtocolException("Bad status code in response"); + } + + mReasonPhrase = mLine.substring(code + 1); + } + + public void reset() { + mStatusCode = null; + mHttpVers = null; + mReasonPhrase = null; + super.reset(); + } + + /** + * get http version + */ + public String getHttpVers() { + return mHttpVers; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/http/JssSSLSocketFactory.java b/pki/base/util/src/com/netscape/cmsutil/http/JssSSLSocketFactory.java new file mode 100644 index 000000000..f0a6625b6 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/http/JssSSLSocketFactory.java @@ -0,0 +1,155 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.http; + + +import java.net.*; +import java.io.*; +import netscape.ldap.*; +import org.mozilla.jss.ssl.*; +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.crypto.X509Certificate; + +import com.netscape.cmsutil.net.*; + +/** + * Uses HCL ssl socket. + */ +public class JssSSLSocketFactory implements ISocketFactory { + private String mClientAuthCertNickname = null; + private SSLSocket s = null; + + public JssSSLSocketFactory() { + } + + public JssSSLSocketFactory(String certNickname) { + mClientAuthCertNickname = certNickname; + } + + // XXX remove these static SSL cipher suite initializations later on. + static final int cipherSuites[] = { + SSLSocket.SSL3_RSA_WITH_RC4_128_MD5, + SSLSocket.SSL3_RSA_WITH_3DES_EDE_CBC_SHA, + SSLSocket.SSL3_RSA_WITH_DES_CBC_SHA, + SSLSocket.SSL3_RSA_EXPORT_WITH_RC4_40_MD5, + SSLSocket.SSL3_RSA_EXPORT_WITH_RC2_CBC_40_MD5, + SSLSocket.SSL3_RSA_WITH_NULL_MD5, + 0 + }; + + static { + int i; + + for (i = SSLSocket.SSL2_RC4_128_WITH_MD5; + i <= SSLSocket.SSL2_RC2_128_CBC_EXPORT40_WITH_MD5; ++i) { + try { + SSLSocket.setCipherPreferenceDefault(i, true); + } catch( SocketException e) { + } + } + //skip SSL_EN_IDEA_128_EDE3_CBC_WITH_MD5 + for (i = SSLSocket.SSL2_DES_64_CBC_WITH_MD5; + i <= SSLSocket.SSL2_DES_192_EDE3_CBC_WITH_MD5; ++i) { + try { + SSLSocket.setCipherPreferenceDefault(i, true); + } catch( SocketException e) { + } + } + for (i = 0; cipherSuites[i] != 0; ++i) { + try { + SSLSocket.setCipherPreferenceDefault(cipherSuites[i], true); + } catch( SocketException e) { + } + } + } + + public Socket makeSocket(String host, int port) + throws IOException, UnknownHostException { + return makeSocket(host, port, null, null); + } + + public Socket makeSocket(String host, int port, + SSLCertificateApprovalCallback certApprovalCallback, + SSLClientCertificateSelectionCallback clientCertCallback) + throws IOException, UnknownHostException { + + try { + s = new SSLSocket(host, port, null, 0, certApprovalCallback, + clientCertCallback); + s.setUseClientMode(true); + + SSLHandshakeCompletedListener listener = null; + + listener = new ClientHandshakeCB(this); + s.addHandshakeCompletedListener(listener); + + if (mClientAuthCertNickname != null) { + // 052799 setClientCertNickname does not + // report error if the nickName is invalid. + // So we check this ourself using + // findCertByNickname + X509Certificate cert = CryptoManager.getInstance().findCertByNickname(mClientAuthCertNickname); + + s.setClientCertNickname(mClientAuthCertNickname); + } + s.forceHandshake(); + } catch (org.mozilla.jss.crypto.ObjectNotFoundException e) { + throw new IOException(e.toString()); + } catch (org.mozilla.jss.crypto.TokenException e) { + throw new IOException(e.toString()); + } catch (UnknownHostException e) { + throw e; + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new IOException(e.toString()); + } + return s; + } + + public Socket makeSocket(String host, int port, int timeout) + throws IOException, UnknownHostException { + Thread t = new ConnectAsync(this, host, port); + + t.start(); + try { + t.join(1000 * timeout); + } catch (InterruptedException e) { + } + + if (t.isAlive()) { + } + + return s; + } + + public void log(int level, String msg) { + } + + class ClientHandshakeCB implements SSLHandshakeCompletedListener { + Object sc; + + public ClientHandshakeCB(Object sc) { + this.sc = sc; + } + + public void handshakeCompleted(SSLHandshakeCompletedEvent event) { + } + } +} + diff --git a/pki/base/util/src/com/netscape/cmsutil/ldap/LDAPUtil.java b/pki/base/util/src/com/netscape/cmsutil/ldap/LDAPUtil.java new file mode 100644 index 000000000..9f0884833 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ldap/LDAPUtil.java @@ -0,0 +1,60 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ldap; + +import netscape.ldap.*; +import netscape.ldap.util.*; +import java.io.*; + +public class LDAPUtil { + public static void importLDIF(LDAPConnection conn, String filename) throws IOException { + LDIF ldif = new LDIF(filename); + while (true) { + try { + LDIFRecord record = ldif.nextRecord(); + if (record == null) + break; + + String dn = record.getDN(); + LDIFContent content = record.getContent(); + int type = content.getType(); + if (type == LDIFContent.ATTRIBUTE_CONTENT) { + LDIFAttributeContent c = (LDIFAttributeContent)content; + LDAPAttribute[] attrs = c.getAttributes(); + LDAPAttributeSet myAttrs = new LDAPAttributeSet(); + for (int i=0; i<attrs.length; i++) + myAttrs.add(attrs[i]); + LDAPEntry entry = new LDAPEntry(dn, myAttrs); + try { + conn.add(entry); + } catch (LDAPException ee) { + } + } else if (type == LDIFContent.MODIFICATION_CONTENT) { + LDIFModifyContent c = (LDIFModifyContent)content; + LDAPModification[] mods = c.getModifications(); + try { + conn.modify(dn, mods); + } catch (LDAPException ee) { + } + } + } catch (Exception e) { + throw new IOException(e.toString()); + } + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/net/ISocketFactory.java b/pki/base/util/src/com/netscape/cmsutil/net/ISocketFactory.java new file mode 100644 index 000000000..3bbe2303a --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/net/ISocketFactory.java @@ -0,0 +1,36 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.net; + +import java.net.Socket; +import java.io.IOException; +import java.net.UnknownHostException; +import org.mozilla.jss.ssl.*; + +public interface ISocketFactory +{ + Socket makeSocket(String host, int port) + throws IOException, UnknownHostException; + Socket makeSocket(String host, int port, int timeout) + throws IOException, UnknownHostException; + Socket makeSocket(String host, int port, + SSLCertificateApprovalCallback certApprovalCallback, + SSLClientCertificateSelectionCallback clientCertCallback) + throws IOException, UnknownHostException; +} + diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/BasicOCSPResponse.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/BasicOCSPResponse.java new file mode 100644 index 000000000..3da34d203 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/BasicOCSPResponse.java @@ -0,0 +1,162 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import java.io.*; +import org.mozilla.jss.asn1.*; +import java.security.Signer; +import org.mozilla.jss.asn1.OCTET_STRING; +import org.mozilla.jss.asn1.BIT_STRING; +import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier; +import org.mozilla.jss.pkix.cert.Certificate; + +/** + * RFC 2560: + * + * BasicOCSPResponse ::= SEQUENCE { + * tbsResponseData ResponseData, + * signatureAlgorithm AlgorithmIdentifier, + * signature BIT STRING, + * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ +public class BasicOCSPResponse implements Response +{ + private byte mData[] = null; + private ResponseData _rd = null; + private AlgorithmIdentifier _signAlg = null; + private BIT_STRING _signature = null; + private Certificate _certs[] = null; + + public BasicOCSPResponse(ResponseData rd, AlgorithmIdentifier signAlg, + BIT_STRING signature, Certificate certs[]) + { + _rd = rd; + _signAlg = signAlg; + _signature = signature; + _certs = certs; + } + + public BasicOCSPResponse(OCTET_STRING os) + { + mData = os.toByteArray(); + } + + public BasicOCSPResponse(byte data[]) + { + mData = data; + } + + private static final Tag TAG = SEQUENCE.TAG; + + public Tag getTag() + { + return TAG; + } + + public void encode(Tag t, OutputStream os) throws IOException + { + os.write(mData); + } + + public void encode(OutputStream os) throws IOException + { + os.write(mData); + } + + public OCTET_STRING getBytes() + { + return null; + } + + public ResponseData getResponseData() + { + return _rd; + } + + public AlgorithmIdentifier getSignatureAlgorithm() + { + return _signAlg; + } + + public BIT_STRING getSignature() + { + return _signature; + } + + public int getCertsCount() + { + return _certs.length; + } + + public Certificate getCertificateAt(int pos) + { + return _certs[pos]; + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() { + return templateInstance; + } + + /** + * A Template for decoding <code>ResponseBytes</code>. + */ + public static class Template implements ASN1Template + { + + private SEQUENCE.Template seqt; + + public Template() + { + seqt = new SEQUENCE.Template(); + seqt.addElement( ResponseData.getTemplate() ); + seqt.addElement( AlgorithmIdentifier.getTemplate() ); + seqt.addElement( BIT_STRING.getTemplate() ); + seqt.addOptionalElement( new EXPLICIT.Template( + new Tag(0), new SEQUENCE.OF_Template( + Certificate.getTemplate())) ); + } + + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream); + + ResponseData rd = (ResponseData)seq.elementAt(0); + AlgorithmIdentifier alg = + (AlgorithmIdentifier)seq.elementAt(1); + BIT_STRING bs = + (BIT_STRING)seq.elementAt(2); + return new BasicOCSPResponse(rd, alg, bs, null); + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/CertID.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/CertID.java new file mode 100644 index 000000000..469102adc --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/CertID.java @@ -0,0 +1,159 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier; +import org.mozilla.jss.asn1.*; +import java.io.*; + +/** + * RFC 2560: + * + * CertID ::= SEQUENCE { + * hashAlgorithm AlgorithmIdentifier, + * issuerNameHash OCTET STRING, -- Hash of Issuer's DN + * issuerKeyHash OCTET STRING, -- Hash of Issuers public key + * serialNumber CertificateSerialNumber } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ + +public class CertID implements ASN1Value +{ + /////////////////////////////////////////////////////////////////////// + // Members and member access + /////////////////////////////////////////////////////////////////////// + private AlgorithmIdentifier hashAlgorithm; + private OCTET_STRING issuerNameHash; + private OCTET_STRING issuerKeyHash; + private INTEGER serialNumber; + private SEQUENCE sequence; + + public AlgorithmIdentifier getHashAlgorithm() + { + return hashAlgorithm; + } + + public OCTET_STRING getIssuerNameHash() + { + return issuerNameHash; + } + + public OCTET_STRING getIssuerKeyHash() + { + return issuerKeyHash; + } + + public INTEGER getSerialNumber() + { + return serialNumber; + } + + /////////////////////////////////////////////////////////////////////// + // Constructors + /////////////////////////////////////////////////////////////////////// + private CertID() { } + + public CertID(AlgorithmIdentifier hashAlgorithm, + OCTET_STRING issuerNameHash, OCTET_STRING issuerKeyHash, + INTEGER serialNumber) + { + sequence = new SEQUENCE(); + + this.hashAlgorithm = hashAlgorithm; + sequence.addElement(hashAlgorithm); + + this.issuerNameHash = issuerNameHash; + sequence.addElement(issuerNameHash); + + this.issuerKeyHash = issuerKeyHash; + sequence.addElement(issuerKeyHash); + + this.serialNumber = serialNumber; + sequence.addElement(serialNumber); + } + + /////////////////////////////////////////////////////////////////////// + // encoding/decoding + /////////////////////////////////////////////////////////////////////// + + private static final Tag TAG = SEQUENCE.TAG; + + public Tag getTag() + { + return TAG; + } + + public void encode(OutputStream ostream) throws IOException + { + encode(TAG, ostream); + } + + public void encode(Tag implicitTag, OutputStream ostream) + throws IOException + { + sequence.encode(implicitTag, ostream); + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() { + return templateInstance; + } + + /** + * A Template for decoding a <code>CertID</code>. + */ + public static class Template implements ASN1Template + { + + private SEQUENCE.Template seqt; + + public Template() + { + seqt = new SEQUENCE.Template(); + seqt.addElement( AlgorithmIdentifier.getTemplate() ); + seqt.addElement( OCTET_STRING.getTemplate() ); + seqt.addElement( OCTET_STRING.getTemplate() ); + seqt.addElement( INTEGER.getTemplate() ); + } + + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream); + + return new CertID( + (AlgorithmIdentifier) seq.elementAt(0), + (OCTET_STRING) seq.elementAt(1), + (OCTET_STRING) seq.elementAt(2), + (INTEGER) seq.elementAt(3)); + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/CertStatus.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/CertStatus.java new file mode 100644 index 000000000..46ba17522 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/CertStatus.java @@ -0,0 +1,37 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import java.io.*; +import org.mozilla.jss.pkix.primitive.Name; +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.pkix.cert.Extension; + +/** + * RFC 2560: + * + * CertStatus ::= CHOICE { + * good [0] IMPLICIT NULL, + * revoked [1] IMPLICIT RevokedInfo, + * unknown [2] IMPLICIT UnknownInfo } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ +public interface CertStatus extends ASN1Value +{ +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/GoodInfo.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/GoodInfo.java new file mode 100644 index 000000000..c0d99065a --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/GoodInfo.java @@ -0,0 +1,100 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import java.io.*; +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.pkix.primitive.Name; +import org.mozilla.jss.pkix.cert.Extension; + +/** + * RFC 2560: + * + * CertStatus ::= CHOICE { + * good [0] IMPLICIT NULL, + * revoked [1] IMPLICIT RevokedInfo, + * unknown [2] IMPLICIT UnknownInfo } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ +public class GoodInfo implements CertStatus +{ + private static final Tag TAG = SEQUENCE.TAG; + + public GoodInfo() + { + } + + public Tag getTag() + { + return Tag.get(0); + } + + public void encode(Tag t, OutputStream os) throws IOException + { + NULL.getInstance().encode(getTag(), os); + } + + public void encode(OutputStream os) throws IOException + { + encode(getTag(), os); + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() { + return templateInstance; + } + + /** + * A Template for decoding <code>ResponseBytes</code>. + */ + public static class Template implements ASN1Template + { + + private SEQUENCE.Template seqt; + + public Template() + { + seqt = new SEQUENCE.Template(); + seqt.addElement(new NULL.Template() ); + + } + + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + // SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, + // istream); + + return new GoodInfo(); + + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/KeyHashID.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/KeyHashID.java new file mode 100644 index 000000000..77bf18c61 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/KeyHashID.java @@ -0,0 +1,107 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import java.io.*; +import org.mozilla.jss.pkix.primitive.Name; +import org.mozilla.jss.asn1.*; + +/** + * RFC 2560: + * + * ResponderID ::= CHOICE { + * byName [1] EXPLICIT Name, + * byKey [2] EXPLICIT KeyHash } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ +public class KeyHashID implements ResponderID +{ + private OCTET_STRING _hash = null; + private static final Tag TAG = SEQUENCE.TAG; + + public KeyHashID(OCTET_STRING hash) + { + _hash = hash; + } + + public Tag getTag() + { + return Tag.get(2); + } + + public void encode(Tag tag, OutputStream os) throws IOException + { + _hash.encode(os); + } + + public void encode(OutputStream os) throws IOException + { + _hash.encode(os); + } + + public OCTET_STRING getHash() + { + return _hash; + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() { + return templateInstance; + } + + /** + * A Template for decoding <code>ResponseBytes</code>. + */ + public static class Template implements ASN1Template + { + + private SEQUENCE.Template seqt; + + public Template() + { + seqt = new SEQUENCE.Template(); +// seqt.addElement(new EXPLICIT.Template( + // new Tag (2), new OCTET_STRING.Template()) ); + seqt.addElement(new OCTET_STRING.Template() ); + + } + + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, + istream); + + OCTET_STRING o = (OCTET_STRING)seq.elementAt(0); + return new KeyHashID(o); + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/NameID.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/NameID.java new file mode 100644 index 000000000..2645c64f2 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/NameID.java @@ -0,0 +1,108 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import java.io.*; +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.pkix.primitive.Name; + +/** + * RFC 2560: + * + * ResponderID ::= CHOICE { + * byName [1] EXPLICIT Name, + * byKey [2] EXPLICIT KeyHash } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ +public class NameID implements ResponderID +{ + private Name _name = null; + private static final Tag TAG = SEQUENCE.TAG; + + public NameID(Name n) + { + _name = n; + } + + public Tag getTag() + { + return Tag.get(1); + } + + public void encode(Tag tag, OutputStream os) throws IOException + { + _name.encode(os); + } + + public void encode(OutputStream os) throws IOException + { + _name.encode(os); + } + + public Name getName() + { + return _name; + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() { + return templateInstance; + } + + /** + * A Template for decoding <code>ResponseBytes</code>. + */ + public static class Template implements ASN1Template + { + + private SEQUENCE.Template seqt; + + public Template() + { + seqt = new SEQUENCE.Template(); + // seqt.addElement(new EXPLICIT.Template( + // new Tag (1), new Name.Template()) ); + seqt.addElement(new Name.Template()); + + } + + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, + istream); + + // EXPLICIT e_name = (EXPLICIT) seq.elementAt(0); + Name name = (Name)seq.elementAt(0); + return new NameID(name); + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPRequest.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPRequest.java new file mode 100644 index 000000000..5181f488b --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPRequest.java @@ -0,0 +1,148 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import org.mozilla.jss.asn1.*; +import java.io.*; + +/** + * RFC 2560: + * + * OCSPRequest ::= SEQUENCE { + * tbsRequest TBSRequest, + * optionalSignature [0] EXPLICIT Signature OPTIONAL } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ + +public class OCSPRequest implements ASN1Value +{ + + /////////////////////////////////////////////////////////////////////// + // Members and member access + /////////////////////////////////////////////////////////////////////// + private TBSRequest tbsRequest; + private Signature optionalSignature; + private SEQUENCE sequence; + + /** + * Returns the <code>TBSRequest</code> field. + */ + public TBSRequest getTBSRequest() + { + return tbsRequest; + } + + /** + * Returns the <code>Signature</code> field. + */ + public Signature getSignature() + { + return optionalSignature; + } + + /////////////////////////////////////////////////////////////////////// + // Constructors + /////////////////////////////////////////////////////////////////////// + private OCSPRequest() { } + + /* THIS code is probably broken. It does not properly encode the explicit element */ + + public OCSPRequest(TBSRequest tbsRequest, Signature optionalSignature) + { + sequence = new SEQUENCE(); + + this.tbsRequest = tbsRequest; + sequence.addElement(tbsRequest); + + this.optionalSignature = optionalSignature; + if (optionalSignature != null) { + sequence.addElement(optionalSignature); + } + } + + /////////////////////////////////////////////////////////////////////// + // encoding/decoding + /////////////////////////////////////////////////////////////////////// + private static final Tag TAG = SEQUENCE.TAG; + + public Tag getTag() + { + return TAG; + } + + public void encode(OutputStream ostream) throws IOException + { + encode(TAG, ostream); + } + + public void encode(Tag implicitTag, OutputStream ostream) + throws IOException + { + sequence.encode(implicitTag, ostream); + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() + { + return templateInstance; + } + + /** + * A Template for decoding OCSPRequest. + */ + public static class Template implements ASN1Template + { + + private SEQUENCE.Template seqt; + + public Template() + { + seqt = new SEQUENCE.Template(); + seqt.addElement(TBSRequest.getTemplate()); + seqt.addOptionalElement( new EXPLICIT.Template( new Tag(0), + new Signature.Template()) ); + } + + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + SEQUENCE seq = (SEQUENCE) seqt.decode(istream); + Signature signature = null; + if (seq.elementAt(1) != null) { + signature = (Signature)((EXPLICIT)seq.elementAt(1)).getContent(); + } + + return new OCSPRequest( + (TBSRequest) seq.elementAt(0), + signature); + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponse.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponse.java new file mode 100644 index 000000000..48d5a632f --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponse.java @@ -0,0 +1,142 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import org.mozilla.jss.asn1.*; +import java.io.*; + +/** + * RFC 2560: + * + * OCSPResponse ::= SEQUENCE { + * responseStatus OCSPResponseStatus, + * responseBytes [0] EXPLICIT ResponseBytes OPTIONAL } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ +public class OCSPResponse implements ASN1Value +{ + /////////////////////////////////////////////////////////////////////// + // Members and member access + /////////////////////////////////////////////////////////////////////// + private OCSPResponseStatus responseStatus = null; + private ResponseBytes responseBytes = null; + private SEQUENCE sequence; + + public OCSPResponseStatus getResponseStatus() + { + return responseStatus; + } + + public ResponseBytes getResponseBytes() + { + return responseBytes; + } + + /////////////////////////////////////////////////////////////////////// + // Constructors + /////////////////////////////////////////////////////////////////////// + private OCSPResponse() { } + + public OCSPResponse(OCSPResponseStatus responseStatus, + ResponseBytes responseBytes) + { + sequence = new SEQUENCE(); + + this.responseStatus = responseStatus; + sequence.addElement(responseStatus); + + this.responseBytes = responseBytes; + sequence.addElement(new EXPLICIT(Tag.get(0), responseBytes)); + } + + /////////////////////////////////////////////////////////////////////// + // encoding/decoding + /////////////////////////////////////////////////////////////////////// + + private static final Tag TAG = SEQUENCE.TAG; + + public Tag getTag() + { + return TAG; + } + + public void encode(OutputStream ostream) throws IOException + { + encode(TAG, ostream); + } + + public void encode(Tag implicitTag, OutputStream ostream) + throws IOException + { + sequence.encode(implicitTag, ostream); + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() { + return templateInstance; + } + + /** + * A Template for decoding an <code>OCSPResponse</code>. + */ + public static class Template implements ASN1Template + { + + private SEQUENCE.Template seqt; + + public Template() + { + seqt = new SEQUENCE.Template(); + seqt.addElement( OCSPResponseStatus.getTemplate() ); + seqt.addOptionalElement( + new EXPLICIT.Template( + new Tag (0), new ResponseBytes.Template()) ); + + } + + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream); + + OCSPResponseStatus rs = (OCSPResponseStatus) seq.elementAt(0); + ResponseBytes rb = null; + ASN1Value val = seq.elementAt(1); + if (val instanceof EXPLICIT) { + EXPLICIT exp = (EXPLICIT)val; + rb = (ResponseBytes)exp.getContent(); + } else { + rb = (ResponseBytes)val; + } + return new OCSPResponse(rs, rb); + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponseStatus.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponseStatus.java new file mode 100644 index 000000000..34f179f7d --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponseStatus.java @@ -0,0 +1,126 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import org.mozilla.jss.asn1.*; +import java.io.*; + +/** + * RFC 2560: + * + * OCSPResponseStatus ::= ENUMERATED { + * successful (0), --Response has valid confirmations + * malformedRequest (1), --Illegal confirmation request + * internalError (2), --Internal error in issuer + * tryLater (3), --Try again later + * --(4) is not used + * sigRequired (5), --Must sign the request + * unauthorized (6) --Request unauthorized + * } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ +public class OCSPResponseStatus implements ASN1Value +{ + /////////////////////////////////////////////////////////////////////// + // Members and member access + /////////////////////////////////////////////////////////////////////// + public final static OCSPResponseStatus SUCCESSFUL = + new OCSPResponseStatus(0); + public final static OCSPResponseStatus MALFORMED_REQUEST = + new OCSPResponseStatus(1); + public final static OCSPResponseStatus INTERNAL_ERROR = + new OCSPResponseStatus(2); + public final static OCSPResponseStatus TRY_LATER = + new OCSPResponseStatus(3); + public final static OCSPResponseStatus SIG_REQUIRED = + new OCSPResponseStatus(5); + public final static OCSPResponseStatus UNAUTHORIZED = + new OCSPResponseStatus(6); + + private ENUMERATED responseStatus; + + public long getValue() + { + return responseStatus.getValue(); + } + + /////////////////////////////////////////////////////////////////////// + // Constructors + /////////////////////////////////////////////////////////////////////// + private OCSPResponseStatus() { } + + public OCSPResponseStatus(long val) + { + responseStatus = new ENUMERATED(val); + } + + /////////////////////////////////////////////////////////////////////// + // encoding/decoding + /////////////////////////////////////////////////////////////////////// + + private static final Tag TAG = ENUMERATED.TAG; + + public Tag getTag() + { + return TAG; + } + + public void encode(OutputStream ostream) throws IOException + { + encode(TAG, ostream); + } + + public void encode(Tag implicitTag, OutputStream ostream) + throws IOException + { + responseStatus.encode(implicitTag, ostream); + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() { + return templateInstance; + } + + /** + * A Template for decoding an <code>OCSPResponseStatus</code>. + */ + public static class Template implements ASN1Template + { + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + ENUMERATED.Template enumt = new ENUMERATED.Template(); + ENUMERATED enum1 = (ENUMERATED) enumt.decode(implicitTag, istream); + + return new OCSPResponseStatus(enum1.getValue()); + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/Request.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/Request.java new file mode 100644 index 000000000..55a5cbfde --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/Request.java @@ -0,0 +1,157 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import org.mozilla.jss.pkix.cert.Extension; +import org.mozilla.jss.asn1.*; +import java.io.*; + +/** + * RFC 2560: + * + * Request ::= SEQUENCE { + * reqCert CertID, + * singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ + +public class Request implements ASN1Value +{ + /////////////////////////////////////////////////////////////////////// + // members and member access + /////////////////////////////////////////////////////////////////////// + private CertID reqCert = null; + private SEQUENCE singleRequestExtensions = null; + private SEQUENCE sequence = null; + + public CertID getCertID() + { + return reqCert; + } + + public int getExtensionsCount() + { + if(singleRequestExtensions == null) { + return 0; + } else { + return singleRequestExtensions.size(); + } + } + + public Extension getRequestExtensionAt(int index) + { + if(singleRequestExtensions == null) { + throw new ArrayIndexOutOfBoundsException(); + } + return (Extension) singleRequestExtensions.elementAt(index); + } + + /////////////////////////////////////////////////////////////////////// + // constructors + /////////////////////////////////////////////////////////////////////// + private Request() { } + + public Request(CertID reqCert, SEQUENCE singleRequestExtensions) + { + sequence = new SEQUENCE(); + + this.reqCert = reqCert; + sequence.addElement(reqCert); + + if (singleRequestExtensions != null) { + this.singleRequestExtensions = singleRequestExtensions; + sequence.addElement(singleRequestExtensions); + } + } + + /////////////////////////////////////////////////////////////////////// + // encode / decode + /////////////////////////////////////////////////////////////////////// + private static final Tag TAG = SEQUENCE.TAG; + + public Tag getTag() + { + return TAG; + } + + public void encode(OutputStream ostream) throws IOException + { + encode(TAG, ostream); + } + + public void encode(Tag implicitTag, OutputStream ostream) + throws IOException + { + sequence.encode(implicitTag, ostream); + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() + { + return templateInstance; + } + + /** + * A Template for decoding Request. + */ + public static class Template implements ASN1Template + { + + private SEQUENCE.Template seqt; + + public Template() + { + seqt = new SEQUENCE.Template(); + seqt.addElement( CertID.getTemplate() ); + seqt.addOptionalElement(new EXPLICIT.Template(new Tag(0), + new SEQUENCE.OF_Template(new Extension.Template()) )); + } + + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream); + + EXPLICIT tag = (EXPLICIT) seq.elementAt(1); + + if (tag == null) { + return new Request( + (CertID) seq.elementAt(0), + (SEQUENCE) null); + } + else { + return new Request( + (CertID) seq.elementAt(0), + (SEQUENCE) tag.getContent()); + } + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponderID.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponderID.java new file mode 100644 index 000000000..f770b6200 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponderID.java @@ -0,0 +1,36 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import java.io.OutputStream; +import org.mozilla.jss.pkix.primitive.*; +import org.mozilla.jss.asn1.*; + + +/** + * RFC 2560: + * + * ResponderID ::= CHOICE { + * byName [1] EXPLICIT Name, + * byKey [2] EXPLICIT KeyHash } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ +public interface ResponderID extends ASN1Value +{ +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/Response.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/Response.java new file mode 100644 index 000000000..2a3f15bb4 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/Response.java @@ -0,0 +1,33 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import java.io.*; +import org.mozilla.jss.asn1.*; + +/** + * RFC 2560: + * + * response OCTET STRING + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ +public interface Response extends ASN1Value +{ + public OCTET_STRING getBytes(); +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseBytes.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseBytes.java new file mode 100644 index 000000000..51077b00f --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseBytes.java @@ -0,0 +1,136 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import org.mozilla.jss.asn1.*; +import java.io.*; + +/** + * RFC 2560: + * + * ResponseBytes ::= SEQUENCE { + * responseType OBJECT IDENTIFIER, + * response OCTET STRING } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ +public class ResponseBytes implements ASN1Value +{ + /////////////////////////////////////////////////////////////////////// + // Members and member access + /////////////////////////////////////////////////////////////////////// + public final static OBJECT_IDENTIFIER OCSP = + new OBJECT_IDENTIFIER("1.3.6.1.5.5.7.48.1"); + public final static OBJECT_IDENTIFIER OCSP_BASIC = + new OBJECT_IDENTIFIER("1.3.6.1.5.5.7.48.1.1"); + + private OBJECT_IDENTIFIER responseType = null; + private OCTET_STRING response = null; + private SEQUENCE sequence; + + public OBJECT_IDENTIFIER getObjectIdentifier() + { + return responseType; + } + + public OCTET_STRING getResponse() + { + return response; + } + + /////////////////////////////////////////////////////////////////////// + // Constructors + /////////////////////////////////////////////////////////////////////// + private ResponseBytes() { } + + public ResponseBytes(OBJECT_IDENTIFIER responseType, OCTET_STRING response) + { + sequence = new SEQUENCE(); + + this.responseType = responseType; + sequence.addElement(responseType); + + this.response = response; + sequence.addElement(response); + } + + /////////////////////////////////////////////////////////////////////// + // encoding/decoding + /////////////////////////////////////////////////////////////////////// + + private static final Tag TAG = SEQUENCE.TAG; + + public Tag getTag() + { + return TAG; + } + + public void encode(OutputStream ostream) throws IOException + { + encode(TAG, ostream); + } + + public void encode(Tag implicitTag, OutputStream ostream) + throws IOException + { + sequence.encode(implicitTag, ostream); + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() { + return templateInstance; + } + + /** + * A Template for decoding <code>ResponseBytes</code>. + */ + public static class Template implements ASN1Template + { + + private SEQUENCE.Template seqt; + + public Template() + { + seqt = new SEQUENCE.Template(); + seqt.addElement( OBJECT_IDENTIFIER.getTemplate() ); + seqt.addElement( OCTET_STRING.getTemplate() ); + } + + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream); + + return new ResponseBytes( + (OBJECT_IDENTIFIER) seq.elementAt(0), + (OCTET_STRING) seq.elementAt(1)); + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseData.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseData.java new file mode 100644 index 000000000..3625ace85 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/ResponseData.java @@ -0,0 +1,213 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import java.io.*; +import java.io.OutputStream; +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.asn1.BIT_STRING; +import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier; +import org.mozilla.jss.pkix.cert.Certificate; +import org.mozilla.jss.asn1.GeneralizedTime; +import org.mozilla.jss.pkix.cert.Extension; + +/** + * RFC 2560: + * + * ResponseData ::= SEQUENCE { + * version [0] EXPLICIT Version DEFAULT v1, + * responderID ResponderID, + * producedAt GeneralizedTime, + * responses SEQUENCE OF SingleResponse, + * responseExtensions [1] EXPLICIT Extensions OPTIONAL } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ +public class ResponseData implements ASN1Value +{ + private ResponderID mRID = null; + private GeneralizedTime mProduced = null; + private SingleResponse mSR[] = null; + private Extension mExts[] = null; + + private static final Tag TAG = SEQUENCE.TAG; + + public ResponseData(ResponderID rid, GeneralizedTime produced, + SingleResponse sr[]) + { + this(rid, produced, sr, null); + } + + public ResponseData(ResponderID rid, GeneralizedTime produced, + SingleResponse sr[], Extension exts[]) + { + mRID = rid; + mProduced = produced; + mSR = sr; + mExts = exts; + } + + public Tag getTag() + { + return TAG; + } + + public void encode(OutputStream os) throws IOException + { + encode(null, os); + } + + public void encode(Tag t, OutputStream os) throws IOException + { + SEQUENCE seq = new SEQUENCE(); + seq.addElement(new EXPLICIT(Tag.get(0), new INTEGER(0))); + seq.addElement(new EXPLICIT(mRID.getTag(), mRID)); + seq.addElement(mProduced); + SEQUENCE responses = new SEQUENCE(); + for (int i = 0; i < mSR.length; i++) { + responses.addElement(mSR[i]); + } + seq.addElement(responses); + if (mExts != null) { + SEQUENCE exts = new SEQUENCE(); + for (int i = 0; i < mExts.length; i++) { + exts.addElement(mExts[i]); + } + seq.addElement(new EXPLICIT(Tag.get(1), exts)); + } + if (t == null) { + seq.encode(os); + } else { + seq.encode(t, os); + } + } + + public ResponderID getResponderID() + { + return mRID; + } + + public GeneralizedTime getProducedAt() + { + return mProduced; + } + + public int getResponseCount() + { + if (mSR == null) + return 0; + else + return mSR.length; + } + + public SingleResponse getResponseAt(int pos) + { + if (mSR == null) + return null; + else + return mSR[pos]; + } + + public int getResponseExtensionCount() + { + return 0; + } + + public Extension getResponseExtensionAt(int pos) + { + return null; + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() { + return templateInstance; + } + + /** + * A Template for decoding <code>ResponseBytes</code>. + */ + public static class Template implements ASN1Template + { + + private SEQUENCE.Template seqt; + + public Template() + { + seqt = new SEQUENCE.Template(); + seqt.addOptionalElement(new EXPLICIT.Template( + new Tag (0), new INTEGER.Template()) ); + seqt.addElement(new ANY.Template() ); + seqt.addElement(new GeneralizedTime.Template() ); + seqt.addElement(new SEQUENCE.OF_Template( + SingleResponse.getTemplate())); + seqt.addOptionalElement(new EXPLICIT.Template( + new Tag(1), new SEQUENCE.OF_Template( + Extension.getTemplate()))); + + } + + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, + istream); + + INTEGER ver = null; + EXPLICIT e_ver = (EXPLICIT)seq.elementAt(0); + if (e_ver != null && e_ver.getTag().getNum() == 0) { + ver = (INTEGER)e_ver.getContent(); + } + ResponderID rid = null; + ANY e_rid = (ANY)seq.elementAt(1); + if (e_rid.getTag().getNum() == 1) { + // name id + rid = (NameID) + NameID.getTemplate().decode(e_rid.getTag(), + new ByteArrayInputStream(e_rid.getEncoded())); + } else if (e_rid.getTag().getNum() == 2) { + // key hash id + rid = (KeyHashID) + KeyHashID.getTemplate().decode(e_rid.getTag(), + new ByteArrayInputStream(e_rid.getEncoded())); + } + GeneralizedTime producedAt = (GeneralizedTime) + seq.elementAt(2); + SEQUENCE responses = (SEQUENCE)seq.elementAt(3); + SingleResponse sr[] = null; + if (responses.size() > 0) { + sr = new SingleResponse[responses.size()]; + for (int i = 0; i < responses.size(); i++) { + sr[i] = (SingleResponse)responses.elementAt(i); + } + } + return new ResponseData(rid, producedAt, sr); + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/RevokedInfo.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/RevokedInfo.java new file mode 100644 index 000000000..2576d1de0 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/RevokedInfo.java @@ -0,0 +1,113 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import java.io.*; +import org.mozilla.jss.asn1.*; + +/** + * RFC 2560: + * + * RevokedInfo ::= SEQUENCE { + * revocationTime GeneralizedTime, + * revocationReason [0] EXPLICIT CRLReason OPTIONAL } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ +public class RevokedInfo implements CertStatus +{ + private static final Tag TAG = SEQUENCE.TAG; + + private GeneralizedTime mRevokedAt; + + public RevokedInfo(GeneralizedTime revokedAt) + { + mRevokedAt = revokedAt; + } + + public Tag getTag() + { + return Tag.get(1); + } + + public void encode(Tag t, OutputStream os) throws IOException + { + SEQUENCE seq = new SEQUENCE(); + seq.addElement(mRevokedAt); + seq.encode(t, os); + } + + public void encode(OutputStream os) throws IOException + { + encode(getTag(), os); + } + + public GeneralizedTime getRevocationTime() + { + return mRevokedAt; + } + + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() { + return templateInstance; + } + + /** + * A Template for decoding <code>ResponseBytes</code>. + */ + public static class Template implements ASN1Template + { + + private SEQUENCE.Template seqt; + + public Template() + { + seqt = new SEQUENCE.Template(); + seqt.addElement(new GeneralizedTime.Template() ); + seqt.addOptionalElement( + new EXPLICIT.Template( new Tag(0), + new INTEGER.Template()) ); + + } + + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, + istream); + + GeneralizedTime revokedAt = (GeneralizedTime) + seq.elementAt(0); + return new RevokedInfo(revokedAt); + + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/Signature.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/Signature.java new file mode 100644 index 000000000..bfd60d079 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/Signature.java @@ -0,0 +1,168 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier; +import org.mozilla.jss.pkix.cert.Certificate; +import org.mozilla.jss.asn1.*; +import java.io.*; + +/** + * RFC 2560: + * + * Signature ::= SEQUENCE { + * signatureAlgorithm AlgorithmIdentifier, + * signature BIT STRING, + * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ + +public class Signature implements ASN1Value +{ + /////////////////////////////////////////////////////////////////////// + // Members and member access + /////////////////////////////////////////////////////////////////////// + private AlgorithmIdentifier signatureAlgorithm; + private BIT_STRING signature; + private SEQUENCE certs; + private SEQUENCE sequence; + + public AlgorithmIdentifier getSignatureAlgorithm() + { + return signatureAlgorithm; + } + + public BIT_STRING getSignature() + { + return signature; + } + + public int getCertificateCount() + { + if(certs == null) { + return 0; + } else { + return certs.size(); + } + } + + public Certificate getCertificateAt(int index) + { + if(certs == null) { + throw new ArrayIndexOutOfBoundsException(); + } + return (Certificate) certs.elementAt(index); + } + + /////////////////////////////////////////////////////////////////////// + // constructors + /////////////////////////////////////////////////////////////////////// + private Signature() { } + + public Signature(AlgorithmIdentifier signatureAlgorithm, + BIT_STRING signature, SEQUENCE certs) + { + sequence = new SEQUENCE(); + + this.signatureAlgorithm = signatureAlgorithm; + sequence.addElement(signatureAlgorithm); + + this.signature = signature; + sequence.addElement(signature); + + this.certs = certs; + sequence.addElement(certs); + } + + /////////////////////////////////////////////////////////////////////// + // encode / decode + /////////////////////////////////////////////////////////////////////// + private static final Tag TAG = SEQUENCE.TAG; + + public Tag getTag() + { + return TAG; + } + + public void encode(OutputStream ostream) throws IOException + { + encode(TAG, ostream); + } + + public void encode(Tag implicitTag, OutputStream ostream) + throws IOException + { + sequence.encode(implicitTag, ostream); + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() + { + return templateInstance; + } + + /** + * A Template for decoding Request. + */ + public static class Template implements ASN1Template + { + + private SEQUENCE.Template seqt; + + public Template() + { + seqt = new SEQUENCE.Template(); + seqt.addElement( AlgorithmIdentifier.getTemplate() ); + seqt.addElement( BIT_STRING.getTemplate() ); + seqt.addOptionalElement( + new EXPLICIT.Template( + new Tag(0), + new SEQUENCE.OF_Template( new Certificate.Template()) + ) + ); + } + + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream); + SEQUENCE certs=null; + if( seq.elementAt(2) != null ) { + certs = (SEQUENCE) ((EXPLICIT)seq.elementAt(2)).getContent(); + } + + return new Signature( + (AlgorithmIdentifier) seq.elementAt(0), + (BIT_STRING) seq.elementAt(1), + certs); + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/SingleResponse.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/SingleResponse.java new file mode 100644 index 000000000..6129836e3 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/SingleResponse.java @@ -0,0 +1,187 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import java.io.*; +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.pkix.primitive.Name; +import org.mozilla.jss.pkix.cert.Extension; + +/** + * RFC 2560: + * + * SingleResponse ::= SEQUENCE { + * certID CertID, + * certStatus CertStatus, + * thisUpdate GeneralizedTime, + * nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL, + * singleExtensions [1] EXPLICIT Extensions OPTIONAL } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ +public class SingleResponse implements ASN1Value +{ + private CertID mCID = null; + private CertStatus mStatus = null; + private GeneralizedTime mThisUpdate = null; + private GeneralizedTime mNextUpdate = null; + + private static final Tag TAG = SEQUENCE.TAG; + + public SingleResponse(CertID cid, CertStatus s, + GeneralizedTime thisUpdate, GeneralizedTime nextUpdate) + { + mCID = cid; + mStatus = s; + mThisUpdate = thisUpdate; + mNextUpdate = nextUpdate; + } + + public CertID getCertID() + { + return mCID; + } + + public Tag getTag() + { + return null; + } + + public void encode(Tag t, OutputStream os) throws IOException + { + SEQUENCE seq = new SEQUENCE(); + seq.addElement(mCID); + seq.addElement(mStatus); + seq.addElement(mThisUpdate); + if (mNextUpdate != null) + { + seq.addElement(new EXPLICIT(Tag.get(0), mNextUpdate)); + } + if (t == null) { + seq.encode(os); + } else { + seq.encode(t, os); + } + } + + public void encode(OutputStream os) throws IOException + { + encode(null, os); + } + + public CertStatus getCertStatus() + { + return mStatus; + } + + public GeneralizedTime getThisUpdate() + { + return mThisUpdate; + } + + public GeneralizedTime getNextUpdate() + { + return mNextUpdate; + } + + public int getExtensionCount() + { + return 0; + } + + public Extension getExtensionAt(int pos) + { + return null; + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() { + return templateInstance; + } + + /** + * A Template for decoding <code>ResponseBytes</code>. + */ + public static class Template implements ASN1Template + { + + private SEQUENCE.Template seqt; + + public Template() + { + seqt = new SEQUENCE.Template(); + seqt.addElement(new CertID.Template() ); + seqt.addElement(new ANY.Template() ); + seqt.addElement(new GeneralizedTime.Template() ); + seqt.addOptionalElement(new EXPLICIT.Template( + new Tag(0), new GeneralizedTime.Template())); + seqt.addOptionalElement(new EXPLICIT.Template(new Tag(1), + new SEQUENCE.OF_Template(new Extension.Template()))); + + } + + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, + istream); + + CertID cid = (CertID)seq.elementAt(0); + CertStatus status = null; + ANY e_status = (ANY)seq.elementAt(1); + if (e_status.getTag().getNum() == 0) { + status = (GoodInfo) + GoodInfo.getTemplate().decode( + e_status.getTag(), + new ByteArrayInputStream(e_status.getEncoded())); + // good + } else if (e_status.getTag().getNum() == 1) { + // revoked + status = (RevokedInfo) + RevokedInfo.getTemplate().decode( + e_status.getTag(), + new ByteArrayInputStream(e_status.getEncoded())); + } else if (e_status.getTag().getNum() == 2) { + // unknown + status = (UnknownInfo) + UnknownInfo.getTemplate().decode( + e_status.getTag(), + new ByteArrayInputStream(e_status.getEncoded())); + } + GeneralizedTime thisUpdate = (GeneralizedTime) + seq.elementAt(2); + GeneralizedTime nextUpdate = null; + + return new SingleResponse(cid, status, thisUpdate, + nextUpdate); + + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/TBSRequest.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/TBSRequest.java new file mode 100644 index 000000000..5387adbbe --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/TBSRequest.java @@ -0,0 +1,204 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import org.mozilla.jss.pkix.cert.Extension; +import org.mozilla.jss.asn1.*; +import java.io.*; + +/** + * RFC 2560: + * + * TBSRequest ::= SEQUENCE { + * version [0] EXPLICIT Version DEFAULT v1, + * requestorName [1] EXPLICIT GeneralName OPTIONAL, + * requestList SEQUENCE OF Request, + * requestExtensions [2] EXPLICIT Extensions OPTIONAL } + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ + +public class TBSRequest implements ASN1Value +{ + /////////////////////////////////////////////////////////////////////// + // members and member access + /////////////////////////////////////////////////////////////////////// + private static final INTEGER version = new INTEGER (1); + private ANY requestorName; + private SEQUENCE requestList; + private SEQUENCE requestExtensions; + private SEQUENCE sequence; + + public INTEGER getVersion() + { + return version; + } + + public ANY getRequestorName() + { + return requestorName; + } + + public int getRequestCount() + { + if( requestList == null ) { + return 0; + } else { + return requestList.size(); + } + } + + public Request getRequestAt(int index) + { + return (Request) requestList.elementAt(index); + } + + public int getExtensionsCount() + { + if( requestExtensions == null ) { + return 0; + } else { + return requestExtensions.size(); + } + } + + public Extension getRequestExtensionAt(int index) + { + return (Extension) requestExtensions.elementAt(index); + } + + /////////////////////////////////////////////////////////////////////// + // constructors + /////////////////////////////////////////////////////////////////////// + /* this code is probably broken - it doesn't do appropriate tagging */ + private TBSRequest() {} + + public TBSRequest(INTEGER version, ANY requestorName, + SEQUENCE requestList, SEQUENCE requestExtensions) + { + sequence = new SEQUENCE(); + + if (version != null) { + sequence.addElement (version); + } + + this.requestorName = requestorName; + if (requestorName != null) { + sequence.addElement (requestorName); + } + + this.requestList = requestList; + sequence.addElement (requestList); + + this.requestExtensions = requestExtensions; + if (requestExtensions != null) { + sequence.addElement (requestExtensions); + } + } + + /////////////////////////////////////////////////////////////////////// + // encode / decode + /////////////////////////////////////////////////////////////////////// + public static final Tag TAG = SEQUENCE.TAG; + + public Tag getTag() + { + return TAG; + } + + public void encode(OutputStream ostream) + throws IOException + { + encode(TAG, ostream); + } + + public void encode(Tag implicitTag, OutputStream ostream) + throws IOException + { + sequence.encode(implicitTag, ostream); + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() + { + return templateInstance; + } + + /** + * A Template for decoding POPOSigningKey. + */ + public static class Template implements ASN1Template + { + + private SEQUENCE.Template seqt; + + public Template() + { + seqt = new SEQUENCE.Template(); + seqt.addElement( + new EXPLICIT.Template( + new Tag(0), new INTEGER.Template()), + new EXPLICIT( new Tag(0), new INTEGER(0)) + ); + seqt.addOptionalElement( + new EXPLICIT.Template( + new Tag (1), new ANY.Template()) ); + seqt.addElement( new SEQUENCE.OF_Template(new Request.Template()) ); + seqt.addOptionalElement(new EXPLICIT.Template(new Tag(2), + new SEQUENCE.OF_Template(new Extension.Template())) ); + } + + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, istream); + + EXPLICIT exts = (EXPLICIT) seq.elementAt(3); + SEQUENCE exts_seq; + if (exts != null) { + exts_seq = (SEQUENCE)exts.getContent(); + } else { + exts_seq = null; + } + + INTEGER v = (INTEGER) ((EXPLICIT)seq.elementAt(0)).getContent(); + ANY requestorname = null; + if (seq.elementAt(1) != null) { + requestorname = (ANY) ((EXPLICIT)seq.elementAt(1)).getContent(); + } + + return new TBSRequest( + v, + requestorname, + (SEQUENCE) seq.elementAt(2), + exts_seq); + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/ocsp/UnknownInfo.java b/pki/base/util/src/com/netscape/cmsutil/ocsp/UnknownInfo.java new file mode 100644 index 000000000..8e98e93ab --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/ocsp/UnknownInfo.java @@ -0,0 +1,95 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.ocsp; + +import java.io.*; +import org.mozilla.jss.asn1.*; + +/** + * RFC 2560: + * + * UnknownInfo ::= NULL -- this can be replaced with an enumeration + * + * $Revision: 14564 $ $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + */ +public class UnknownInfo implements CertStatus +{ + private static final Tag TAG = SEQUENCE.TAG; + + public UnknownInfo() + { + } + + public Tag getTag() + { + return Tag.get(2); + } + + public void encode(Tag t, OutputStream os) throws IOException + { + NULL.getInstance().encode(getTag(), os); + } + + public void encode(OutputStream os) throws IOException + { + encode(getTag(), os); + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() { + return templateInstance; + } + + /** + * A Template for decoding <code>ResponseBytes</code>. + */ + public static class Template implements ASN1Template + { + + private SEQUENCE.Template seqt; + + public Template() + { +// seqt = new SEQUENCE.Template(); + // seqt.addElement(new NULL.Template() ); + + } + + public boolean tagMatch(Tag tag) + { + return TAG.equals(tag); + } + + public ASN1Value decode(InputStream istream) + throws InvalidBERException, IOException + { + return decode(TAG, istream); + } + + public ASN1Value decode(Tag implicitTag, InputStream istream) + throws InvalidBERException, IOException + { + // SEQUENCE seq = (SEQUENCE) seqt.decode(implicitTag, + // istream); + + return new UnknownInfo(); + + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/password/IPasswordReader.java b/pki/base/util/src/com/netscape/cmsutil/password/IPasswordReader.java new file mode 100644 index 000000000..7cdb7ec92 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/password/IPasswordReader.java @@ -0,0 +1,26 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.password; +import java.util.*; +import java.io.*; + +public interface IPasswordReader { + public void init(String pwdPath) throws IOException; + public String getPassword(String tag); + public Enumeration getTags(); +} diff --git a/pki/base/util/src/com/netscape/cmsutil/password/IPasswordStore.java b/pki/base/util/src/com/netscape/cmsutil/password/IPasswordStore.java new file mode 100644 index 000000000..0f12f5242 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/password/IPasswordStore.java @@ -0,0 +1,30 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.password; + +import java.util.*; +import java.io.*; + +public interface IPasswordStore { + public void init(String pwdPath) throws IOException; + public String getPassword(String tag); + public Enumeration getTags(); + public Object putPassword(String tag, String password); + public void commit() + throws IOException, ClassCastException, NullPointerException; +} diff --git a/pki/base/util/src/com/netscape/cmsutil/password/IPasswordWriter.java b/pki/base/util/src/com/netscape/cmsutil/password/IPasswordWriter.java new file mode 100644 index 000000000..4aa505601 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/password/IPasswordWriter.java @@ -0,0 +1,28 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.password; +import java.io.*; +import java.util.*; + +public interface IPasswordWriter { + public void init(String pwdPath) + throws IOException;; + public Object putPassword(String tag, String password); + public void commit() + throws IOException, ClassCastException, NullPointerException; +} diff --git a/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordFile.java b/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordFile.java new file mode 100644 index 000000000..fd3fc8b0d --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordFile.java @@ -0,0 +1,64 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.password; + +import java.util.Properties; +import java.io.*; +import java.util.*; + +public class PlainPasswordFile implements IPasswordStore{ + private String mPwdPath = ""; + private Properties mPwdStore; + private static final String PASSWORD_WRITER_HEADER = ""; + + public PlainPasswordFile() { + } + + public void init(String pwdPath) + throws IOException + { + mPwdStore = new Properties(); + // initialize mPwdStore + mPwdPath = pwdPath; + + FileInputStream file = new FileInputStream(mPwdPath); + mPwdStore.load(file); + file.close(); + } + + public String getPassword(String tag) { + return (String) mPwdStore.getProperty(tag); + } + + // return an array of String-based tag + public Enumeration getTags() { + return mPwdStore.propertyNames(); + } + + public Object putPassword(String tag, String password) { + return mPwdStore.setProperty(tag, password); + } + + public void commit() + throws IOException, ClassCastException, NullPointerException + { + FileOutputStream file = new FileOutputStream(mPwdPath); + mPwdStore.store(file, PASSWORD_WRITER_HEADER); + file.close(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordReader.java b/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordReader.java new file mode 100644 index 000000000..c6a138236 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordReader.java @@ -0,0 +1,52 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.password; + +import java.util.Properties; +import java.io.*; +import java.util.*; + +public class PlainPasswordReader implements IPasswordReader{ + private String mPwdPath = ""; + private Properties mPwdStore; + + public PlainPasswordReader() { + } + + public void init(String pwdPath) + throws IOException + { + mPwdStore = new Properties(); + // initialize mPwdStore + mPwdPath = pwdPath; + mPwdStore = new Properties(); + + FileInputStream file = new FileInputStream(mPwdPath); + mPwdStore.load(file); + file.close(); + } + + public String getPassword(String tag) { + return (String) mPwdStore.getProperty(tag); + } + + // return an array of String-based tag + public Enumeration getTags() { + return mPwdStore.propertyNames(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordWriter.java b/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordWriter.java new file mode 100644 index 000000000..382c117b7 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/password/PlainPasswordWriter.java @@ -0,0 +1,57 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.password; + +import java.util.Properties; +import java.io.*; +import java.util.*; + +public class PlainPasswordWriter implements IPasswordWriter{ + private static final String PASSWORD_WRITER_HEADER = ""; + private String mPwdPath = ""; + private Properties mPwdStore; + + public PlainPasswordWriter() { + } + + public void init(String pwdPath) + throws IOException + { + mPwdStore = new Properties(); + // initialize mPwdStore + mPwdPath = pwdPath; + mPwdStore = new Properties(); + + FileInputStream file = new FileInputStream(mPwdPath); + mPwdStore.load(file); + file.close(); + } + + public Object putPassword(String tag, String password) { + return mPwdStore.setProperty(tag, password); + } + + public void commit() + throws IOException, ClassCastException, NullPointerException + { + FileOutputStream file = new FileOutputStream(mPwdPath); + mPwdStore.store(file, PASSWORD_WRITER_HEADER); + file.close(); + } + +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/AccessAccept.java b/pki/base/util/src/com/netscape/cmsutil/radius/AccessAccept.java new file mode 100644 index 000000000..adff75a96 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/AccessAccept.java @@ -0,0 +1,33 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class AccessAccept extends ServerPacket { + public AccessAccept(byte data[]) throws IOException { + super(data); + } + +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/AccessChallenge.java b/pki/base/util/src/com/netscape/cmsutil/radius/AccessChallenge.java new file mode 100644 index 000000000..4db3ea935 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/AccessChallenge.java @@ -0,0 +1,33 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class AccessChallenge extends ServerPacket { + public AccessChallenge(byte data[]) throws IOException { + super(data); + } + +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/AccessReject.java b/pki/base/util/src/com/netscape/cmsutil/radius/AccessReject.java new file mode 100644 index 000000000..96e4b1fae --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/AccessReject.java @@ -0,0 +1,33 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class AccessReject extends ServerPacket { + public AccessReject(byte data[]) throws IOException { + super(data); + } + +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/AccessRequest.java b/pki/base/util/src/com/netscape/cmsutil/radius/AccessRequest.java new file mode 100644 index 000000000..4098bbf15 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/AccessRequest.java @@ -0,0 +1,33 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class AccessRequest extends NASPacket { + public AccessRequest(short id, Authenticator auth) { + super(ACCESS_REQUEST, id, auth); + } + +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/Attribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/Attribute.java new file mode 100644 index 000000000..16e60bb55 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/Attribute.java @@ -0,0 +1,102 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public abstract class Attribute { + public static final int USER_NAME = 1; + public static final int USER_PASSWORD = 2; + public static final int CHAP_PASSWORD = 3; + public static final int NAS_IP_ADDRESS = 4; + public static final int NAS_PORT = 5; + public static final int SERVICE_TYPE = 6; + public static final int FRAMED_PROTOCOL = 7; + public static final int FRAMED_IP_ADDRESS = 8; + public static final int FRAMED_IP_NETMASK = 9; + public static final int FRAMED_ROUTING = 10; + public static final int FILTER_ID = 11; + public static final int FRAMED_MTU = 12; + public static final int FRAMED_COMPRESSION = 13; + public static final int LOGIN_IP_HOST = 14; + public static final int LOGIN_SERVICE = 15; + public static final int LOGIN_TCP_PORT = 16; + // 17 HAS NOT BEEN ASSIGNED + public static final int REPLY_MESSAGE = 18; + public static final int CALLBACK_NUMBER = 19; + public static final int CALLBACK_ID = 20; + // 21 HAS NOT BEEN ASSIGNED + public static final int FRAMED_ROUTE = 22; + public static final int FRAMED_IPX_NETWORK = 23; + public static final int STATE = 24; + public static final int NAS_CLASS = 25; + public static final int VENDOR_SPECIFIC = 26; + public static final int SESSION_TIMEOUT = 27; + public static final int IDLE_TIMEOUT = 28; + public static final int TERMINATION_ACTION = 29; + public static final int CALLER_STATION_ID = 30; + public static final int CALLING_STATION_ID = 31; + public static final int NAS_IDENTIFIER = 32; + public static final int PROXY_STATE = 33; + public static final int LOGIN_LAT_SERVICE = 34; + public static final int LOGIN_LAT_NODE = 35; + public static final int LOGIN_LAT_GROUP = 36; + public static final int FRAMED_APPLETALK_LINK = 37; + public static final int FRAMED_APPLETALK_NETWORK = 38; + public static final int FRAMED_APPLETALK_ZONE = 39; + // 40-59 HAS NOT BEEN ASSIGNED + public static final int CHAP_CHALLENGE = 60; + public static final int NAS_PORT_TYPE = 61; + public static final int PORT_LIMIT = 62; + public static final int LOGIN_LAT_PORT = 63; + + protected int _t = 0; + + public Attribute() { + } + + public Attribute(int t) { + _t = t; + } + + public int getType() { + return _t; + } + + public abstract byte[] getValue() + throws IOException; + + public byte[] getData() + throws IOException { + ByteArrayOutputStream attrOS = new ByteArrayOutputStream(); + + attrOS.write(_t); // type + byte value[] = getValue(); + + attrOS.write(value.length + 2); // length + attrOS.write(value); + + return attrOS.toByteArray(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/AttributeFactory.java b/pki/base/util/src/com/netscape/cmsutil/radius/AttributeFactory.java new file mode 100644 index 000000000..1290011fe --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/AttributeFactory.java @@ -0,0 +1,160 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class AttributeFactory { + public static Attribute createAttribute(byte data[]) + throws IOException { + switch (data[0] & 0xFF) { + case Attribute.USER_NAME: // 1 + return new UserNameAttribute(data); + + case Attribute.USER_PASSWORD: // 2 + return new UserPasswordAttribute(data); + + case Attribute.NAS_IP_ADDRESS: // 4 + return new NASIPAddressAttribute(data); + + case Attribute.NAS_PORT: // 5 + return new NASPortAttribute(data); + + case Attribute.CHAP_PASSWORD: // 3 + return new CHAPPasswordAttribute(data); + + case Attribute.SERVICE_TYPE: // 6 + return new ServiceTypeAttribute(data); + + case Attribute.FRAMED_PROTOCOL: // 7 + return new FramedProtocolAttribute(data); + + case Attribute.FRAMED_IP_ADDRESS: // 8 + return new FramedIPAddressAttribute(data); + + case Attribute.FRAMED_IP_NETMASK: // 9 + return new FramedIPNetmaskAttribute(data); + + case Attribute.FRAMED_ROUTING: // 10 + return new FramedRoutingAttribute(data); + + case Attribute.FILTER_ID: // 11 + return new FilterIdAttribute(data); + + case Attribute.FRAMED_MTU: // 12 + return new FramedMTUAttribute(data); + + case Attribute.FRAMED_COMPRESSION: // 13 + return new FramedCompressionAttribute(data); + + case Attribute.LOGIN_IP_HOST: // 14 + return new LoginIPHostAttribute(data); + + case Attribute.LOGIN_SERVICE: // 15 + return new LoginServiceAttribute(data); + + case Attribute.LOGIN_TCP_PORT: // 16 + return new LoginTCPPortAttribute(data); + + case Attribute.REPLY_MESSAGE: // 18 + return new ReplyMessageAttribute(data); + + case Attribute.CALLBACK_NUMBER: // 19 + return new CallbackNumberAttribute(data); + + case Attribute.CALLBACK_ID: // 20 + return new CallbackIdAttribute(data); + + case Attribute.FRAMED_ROUTE: // 22 + return new FramedRouteAttribute(data); + + case Attribute.FRAMED_IPX_NETWORK: // 23 + return new FramedIPXNetworkAttribute(data); + + case Attribute.STATE: // 24 + return new StateAttribute(data); + + case Attribute.NAS_CLASS: // 25 + return new NASClassAttribute(data); + + case Attribute.VENDOR_SPECIFIC: // 26 + return new VendorSpecificAttribute(data); + + case Attribute.SESSION_TIMEOUT: // 27 + return new SessionTimeoutAttribute(data); + + case Attribute.IDLE_TIMEOUT: // 28 + return new IdleTimeoutAttribute(data); + + case Attribute.TERMINATION_ACTION: // 29 + return new TerminationActionAttribute(data); + + case Attribute.CALLER_STATION_ID: // 30 + return new CallerStationIdAttribute(data); + + case Attribute.CALLING_STATION_ID: // 31 + return new CallingStationIdAttribute(data); + + case Attribute.NAS_IDENTIFIER: // 32 + return new NASIdentifierAttribute(data); + + case Attribute.PROXY_STATE: // 33 + return new ProxyStateAttribute(data); + + case Attribute.LOGIN_LAT_SERVICE: // 34 + return new LoginLATServiceAttribute(data); + + case Attribute.LOGIN_LAT_NODE: // 35 + return new LoginLATNodeAttribute(data); + + case Attribute.LOGIN_LAT_GROUP: // 36 + return new LoginLATGroupAttribute(data); + + case Attribute.FRAMED_APPLETALK_LINK: // 37 + return new FramedAppleTalkLinkAttribute(data); + + case Attribute.FRAMED_APPLETALK_NETWORK: // 38 + return new FramedAppleTalkNetworkAttribute(data); + + case Attribute.FRAMED_APPLETALK_ZONE: // 39 + return new FramedAppleTalkZoneAttribute(data); + + case Attribute.CHAP_CHALLENGE: // 60 + return new CHAPChallengeAttribute(data); + + case Attribute.NAS_PORT_TYPE: // 61 + return new NASPortTypeAttribute(data); + + case Attribute.PORT_LIMIT: // 62 + return new PortLimitAttribute(data); + + case Attribute.LOGIN_LAT_PORT: // 63 + return new LoginLATPortAttribute(data); + + default: + return new GenericAttribute(data); + // throw new IOException("Unknown attribute " + (data[0] & 0xFF)); + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/AttributeSet.java b/pki/base/util/src/com/netscape/cmsutil/radius/AttributeSet.java new file mode 100644 index 000000000..4c17f441d --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/AttributeSet.java @@ -0,0 +1,61 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class AttributeSet { + private Vector _attrs = new Vector(); + + public AttributeSet() { + } + + public void addAttribute(Attribute attr) { + _attrs.addElement(attr); + } + + public int size() { + return _attrs.size(); + } + + public Enumeration getAttributes() { + return _attrs.elements(); + } + + public Attribute getAttributeByType(int type) { + int l = _attrs.size(); + + for (int i = 0; i < l; i++) { + Attribute attr = getAttributeAt(i); + + if (attr.getType() == type) + return attr; + } + return null; + } + + public Attribute getAttributeAt(int pos) { + return (Attribute) _attrs.elementAt(pos); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/Authenticator.java b/pki/base/util/src/com/netscape/cmsutil/radius/Authenticator.java new file mode 100644 index 000000000..7fe060975 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/Authenticator.java @@ -0,0 +1,30 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public abstract class Authenticator { + public abstract byte[] getData() throws IOException; +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/CHAPChallengeAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/CHAPChallengeAttribute.java new file mode 100644 index 000000000..5ddc186bc --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/CHAPChallengeAttribute.java @@ -0,0 +1,44 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class CHAPChallengeAttribute extends Attribute { + private String _str = null; + + public CHAPChallengeAttribute(byte value[]) { + super(); + _t = CHAP_CHALLENGE; + _str = new String(value, 2, value.length - 2); + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/CHAPPasswordAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/CHAPPasswordAttribute.java new file mode 100644 index 000000000..063ce891c --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/CHAPPasswordAttribute.java @@ -0,0 +1,61 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class CHAPPasswordAttribute extends Attribute { + private byte _value[] = null; + private int _ident = 0; + private String _str = null; + + public CHAPPasswordAttribute(String s) { + _str = s; + } + + public CHAPPasswordAttribute(byte value[]) { + super(); + _t = CHAP_PASSWORD; + _ident = value[2]; + _str = new String(value, 2, 16); + _value = value; + } + + public int getIdent() { + return _ident; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + byte val[] = new byte[1 + _str.length()]; + byte s[] = _str.getBytes(); + + val[0] = (byte) _ident; + System.arraycopy(s, 0, val, 1, s.length); + return val; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/CallbackIdAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/CallbackIdAttribute.java new file mode 100644 index 000000000..c4c175be2 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/CallbackIdAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class CallbackIdAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public CallbackIdAttribute(byte value[]) { + super(); + _t = CALLBACK_ID; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/CallbackNumberAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/CallbackNumberAttribute.java new file mode 100644 index 000000000..818930170 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/CallbackNumberAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class CallbackNumberAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public CallbackNumberAttribute(byte value[]) { + super(); + _t = CALLBACK_NUMBER; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/CallerStationIdAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/CallerStationIdAttribute.java new file mode 100644 index 000000000..a0afb3fcd --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/CallerStationIdAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class CallerStationIdAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public CallerStationIdAttribute(byte value[]) { + super(); + _t = CALLER_STATION_ID; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/CallingStationIdAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/CallingStationIdAttribute.java new file mode 100644 index 000000000..162d7098e --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/CallingStationIdAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class CallingStationIdAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public CallingStationIdAttribute(byte value[]) { + super(); + _t = CALLING_STATION_ID; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/ChallengeException.java b/pki/base/util/src/com/netscape/cmsutil/radius/ChallengeException.java new file mode 100644 index 000000000..bdcd77abc --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/ChallengeException.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class ChallengeException extends Exception { + private AccessChallenge _res = null; + + public ChallengeException(AccessChallenge res) { + _res = res; + } + + public AttributeSet getAttributeSet() { + return _res.getAttributeSet(); + } + + public String getState() { + return ((StateAttribute) (_res.getAttributeSet().getAttributeByType(Attribute.STATE))).getString(); + } + + public String getReplyMessage() { + return ((ReplyMessageAttribute) (_res.getAttributeSet().getAttributeByType(Attribute.REPLY_MESSAGE))).getString(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FilterIdAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FilterIdAttribute.java new file mode 100644 index 000000000..15b8940d4 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/FilterIdAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class FilterIdAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public FilterIdAttribute(byte value[]) { + super(); + _t = CHAP_PASSWORD; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkLinkAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkLinkAttribute.java new file mode 100644 index 000000000..649442fa2 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkLinkAttribute.java @@ -0,0 +1,57 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class FramedAppleTalkLinkAttribute extends Attribute { + public static int UN_NUMBERED = 0; + + private byte _value[] = null; + private int _type = 0; + + public FramedAppleTalkLinkAttribute(byte value[]) { + super(); + _t = FRAMED_APPLETALK_LINK; + _value = value; + _type = value[5] & 0xFF; + _type |= ((value[4] << 8) & 0xFF00); + _type |= ((value[3] << 16) & 0xFF0000); + _type |= ((value[2] << 24) & 0xFF000000); + } + + public int getType() { + return _type; + } + + public byte[] getValue() throws IOException { + byte[] p = new byte[4]; + + p[0] = (byte) ((_type >>> 24) & 0xFF); + p[1] = (byte) ((_type >>> 16) & 0xFF); + p[2] = (byte) ((_type >>> 8) & 0xFF); + p[3] = (byte) (_type & 0xFF); + return p; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkNetworkAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkNetworkAttribute.java new file mode 100644 index 000000000..e59449862 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkNetworkAttribute.java @@ -0,0 +1,55 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class FramedAppleTalkNetworkAttribute extends Attribute { + private byte _value[] = null; + private int _type = 0; + + public FramedAppleTalkNetworkAttribute(byte value[]) { + super(); + _t = FRAMED_APPLETALK_NETWORK; + _value = value; + _type = value[5] & 0xFF; + _type |= ((value[4] << 8) & 0xFF00); + _type |= ((value[3] << 16) & 0xFF0000); + _type |= ((value[2] << 24) & 0xFF000000); + } + + public int getType() { + return _type; + } + + public byte[] getValue() throws IOException { + byte[] p = new byte[4]; + + p[0] = (byte) ((_type >>> 24) & 0xFF); + p[1] = (byte) ((_type >>> 16) & 0xFF); + p[2] = (byte) ((_type >>> 8) & 0xFF); + p[3] = (byte) (_type & 0xFF); + return p; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkZoneAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkZoneAttribute.java new file mode 100644 index 000000000..18f064448 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkZoneAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class FramedAppleTalkZoneAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public FramedAppleTalkZoneAttribute(byte value[]) { + super(); + _t = FRAMED_APPLETALK_ZONE; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedCompressionAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedCompressionAttribute.java new file mode 100644 index 000000000..9b2f398cc --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedCompressionAttribute.java @@ -0,0 +1,60 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class FramedCompressionAttribute extends Attribute { + public static final int NONE = 1; + public static final int VJ_TCP_IP_HEADER = 2; + public static final int IPX_HEADER = 2; + public static final int STAC_LZS = 3; + + private byte _value[] = null; + private int _type = 0; + + public FramedCompressionAttribute(byte value[]) { + super(); + _t = FRAMED_COMPRESSION; + _type = value[5] & 0xFF; + _type |= ((value[4] << 8) & 0xFF00); + _type |= ((value[3] << 16) & 0xFF0000); + _type |= ((value[2] << 24) & 0xFF000000); + _value = value; + } + + public int getType() { + return _type; + } + + public byte[] getValue() throws IOException { + byte[] p = new byte[4]; + + p[0] = (byte) ((_type >>> 24) & 0xFF); + p[1] = (byte) ((_type >>> 16) & 0xFF); + p[2] = (byte) ((_type >>> 8) & 0xFF); + p[3] = (byte) (_type & 0xFF); + return p; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPAddressAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPAddressAttribute.java new file mode 100644 index 000000000..55b313a1b --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPAddressAttribute.java @@ -0,0 +1,45 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class FramedIPAddressAttribute extends Attribute { + private byte _value[] = null; + private byte _addr[] = new byte[4]; + + public FramedIPAddressAttribute(byte value[]) { + super(); + _t = FRAMED_IP_ADDRESS; + _addr[0] = value[2]; + _addr[1] = value[3]; + _addr[2] = value[4]; + _addr[3] = value[5]; + _value = value; + } + + public byte[] getValue() throws IOException { + return _addr; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPNetmaskAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPNetmaskAttribute.java new file mode 100644 index 000000000..c8f7324f2 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPNetmaskAttribute.java @@ -0,0 +1,45 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class FramedIPNetmaskAttribute extends Attribute { + private byte _value[] = null; + private byte _mask[] = new byte[4]; + + public FramedIPNetmaskAttribute(byte value[]) { + super(); + _t = FRAMED_IP_NETMASK; + _mask[0] = value[2]; + _mask[1] = value[3]; + _mask[2] = value[4]; + _mask[3] = value[5]; + _value = value; + } + + public byte[] getValue() throws IOException { + return _mask; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPXNetworkAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPXNetworkAttribute.java new file mode 100644 index 000000000..448dbb5de --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedIPXNetworkAttribute.java @@ -0,0 +1,45 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class FramedIPXNetworkAttribute extends Attribute { + private byte _value[] = null; + private byte _net[] = new byte[4]; + + public FramedIPXNetworkAttribute(byte value[]) { + super(); + _t = FRAMED_IPX_NETWORK; + _net[0] = value[2]; + _net[1] = value[3]; + _net[2] = value[4]; + _net[3] = value[5]; + _value = value; + } + + public byte[] getValue() throws IOException { + return _net; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedMTUAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedMTUAttribute.java new file mode 100644 index 000000000..0c9de7268 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedMTUAttribute.java @@ -0,0 +1,55 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class FramedMTUAttribute extends Attribute { + private byte _value[] = null; + private int _type = 0; + + public FramedMTUAttribute(byte value[]) { + super(); + _t = FRAMED_IP_ADDRESS; + _value = value; + _type = value[5] & 0xFF; + _type |= ((value[4] << 8) & 0xFF00); + _type |= ((value[3] << 16) & 0xFF0000); + _type |= ((value[2] << 24) & 0xFF000000); + } + + public int getType() { + return _type; + } + + public byte[] getValue() throws IOException { + byte[] p = new byte[4]; + + p[0] = (byte) ((_type >>> 24) & 0xFF); + p[1] = (byte) ((_type >>> 16) & 0xFF); + p[2] = (byte) ((_type >>> 8) & 0xFF); + p[3] = (byte) (_type & 0xFF); + return p; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedProtocolAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedProtocolAttribute.java new file mode 100644 index 000000000..a13321c8d --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedProtocolAttribute.java @@ -0,0 +1,62 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class FramedProtocolAttribute extends Attribute { + public static final int PPP = 1; + public static final int SLIP = 2; + public static final int ARAP = 3; + public static final int GANDALF = 4; + public static final int XYLOGICS = 5; + public static final int X_75 = 6; + + private byte _value[] = null; + private int _type = 0; + + public FramedProtocolAttribute(byte value[]) { + super(); + _t = SERVICE_TYPE; + _type = value[5] & 0xFF; + _type |= ((value[4] << 8) & 0xFF00); + _type |= ((value[3] << 16) & 0xFF0000); + _type |= ((value[2] << 24) & 0xFF000000); + _value = value; + } + + public int getType() { + return _type; + } + + public byte[] getValue() throws IOException { + byte[] p = new byte[4]; + + p[0] = (byte) ((_type >>> 24) & 0xFF); + p[1] = (byte) ((_type >>> 16) & 0xFF); + p[2] = (byte) ((_type >>> 8) & 0xFF); + p[3] = (byte) (_type & 0xFF); + return p; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedRouteAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedRouteAttribute.java new file mode 100644 index 000000000..07777bd12 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedRouteAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class FramedRouteAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public FramedRouteAttribute(byte value[]) { + super(); + _t = FRAMED_ROUTE; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/FramedRoutingAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/FramedRoutingAttribute.java new file mode 100644 index 000000000..ade7e34f2 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/FramedRoutingAttribute.java @@ -0,0 +1,60 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class FramedRoutingAttribute extends Attribute { + public static final int NONE = 0; + public static final int SEND_ROUTING_PACKETS = 1; + public static final int LISTEN_FOR_ROUTING_PACKETS = 2; + public static final int SEND_AND_LISTEN = 3; + + private byte _value[] = null; + private int _type = 0; + + public FramedRoutingAttribute(byte value[]) { + super(); + _t = FRAMED_ROUTING; + _type = value[5] & 0xFF; + _type |= ((value[4] << 8) & 0xFF00); + _type |= ((value[3] << 16) & 0xFF0000); + _type |= ((value[2] << 24) & 0xFF000000); + _value = value; + } + + public int getType() { + return _type; + } + + public byte[] getValue() throws IOException { + byte[] p = new byte[4]; + + p[0] = (byte) ((_type >>> 24) & 0xFF); + p[1] = (byte) ((_type >>> 16) & 0xFF); + p[2] = (byte) ((_type >>> 8) & 0xFF); + p[3] = (byte) (_type & 0xFF); + return p; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/GenericAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/GenericAttribute.java new file mode 100644 index 000000000..df42fb6f9 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/GenericAttribute.java @@ -0,0 +1,41 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class GenericAttribute extends Attribute { + private byte _value[] = null; + + public GenericAttribute(byte value[]) { + super(); + _t = value[0]; + _value = new byte[value.length - 2]; + System.arraycopy(value, 2, _value, 0, _value.length); + } + + public byte[] getValue() throws IOException { + return _value; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/IdleTimeoutAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/IdleTimeoutAttribute.java new file mode 100644 index 000000000..513c1077f --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/IdleTimeoutAttribute.java @@ -0,0 +1,58 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class IdleTimeoutAttribute extends Attribute { + private int _timeout = 0; + + public IdleTimeoutAttribute(byte value[]) { + super(); + _t = IDLE_TIMEOUT; + _timeout = value[5] & 0xFF; + _timeout |= ((value[4] << 8) & 0xFF00); + _timeout |= ((value[3] << 16) & 0xFF0000); + _timeout |= ((value[2] << 24) & 0xFF000000); + } + + public IdleTimeoutAttribute(int timeout) { + super(IDLE_TIMEOUT); + _timeout = timeout; + } + + public int getTimeout() { + return _timeout; + } + + public byte[] getValue() throws IOException { + byte[] p = new byte[4]; + + p[0] = (byte) ((_timeout >>> 24) & 0xFF); + p[1] = (byte) ((_timeout >>> 16) & 0xFF); + p[2] = (byte) ((_timeout >>> 8) & 0xFF); + p[3] = (byte) (_timeout & 0xFF); + return p; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/LoginIPHostAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/LoginIPHostAttribute.java new file mode 100644 index 000000000..2f8dae725 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/LoginIPHostAttribute.java @@ -0,0 +1,58 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class LoginIPHostAttribute extends Attribute { + public static final int NAS_ALLOW_SELECT = 0xFFFFFFFF; + public static final int NAS_SELECT = 0; + + private byte _value[] = null; + private int _type = 0; + + public LoginIPHostAttribute(byte value[]) { + super(); + _t = LOGIN_IP_HOST; + _type = value[5] & 0xFF; + _type |= ((value[4] << 8) & 0xFF00); + _type |= ((value[3] << 16) & 0xFF0000); + _type |= ((value[2] << 24) & 0xFF000000); + _value = value; + } + + public int getType() { + return _type; + } + + public byte[] getValue() throws IOException { + byte[] p = new byte[4]; + + p[0] = (byte) ((_type >>> 24) & 0xFF); + p[1] = (byte) ((_type >>> 16) & 0xFF); + p[2] = (byte) ((_type >>> 8) & 0xFF); + p[3] = (byte) (_type & 0xFF); + return p; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATGroupAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATGroupAttribute.java new file mode 100644 index 000000000..5c1891f78 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATGroupAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class LoginLATGroupAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public LoginLATGroupAttribute(byte value[]) { + super(); + _t = LOGIN_LAT_GROUP; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATNodeAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATNodeAttribute.java new file mode 100644 index 000000000..55948d443 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATNodeAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class LoginLATNodeAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public LoginLATNodeAttribute(byte value[]) { + super(); + _t = LOGIN_LAT_NODE; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATPortAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATPortAttribute.java new file mode 100644 index 000000000..a0e61ab98 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATPortAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class LoginLATPortAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public LoginLATPortAttribute(byte value[]) { + super(); + _t = PROXY_STATE; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATServiceAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATServiceAttribute.java new file mode 100644 index 000000000..7116630ac --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/LoginLATServiceAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class LoginLATServiceAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public LoginLATServiceAttribute(byte value[]) { + super(); + _t = LOGIN_LAT_SERVICE; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/LoginServiceAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/LoginServiceAttribute.java new file mode 100644 index 000000000..1dcd12b2f --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/LoginServiceAttribute.java @@ -0,0 +1,64 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class LoginServiceAttribute extends Attribute { + public static final int TELNET = 0; + public static final int RLOGIN = 1; + public static final int TCP_CLEAR = 2; + public static final int PORTMASTER = 3; + public static final int LAT = 4; + public static final int X25_PAD = 5; + public static final int X25_T3POS = 6; + public static final int TCP_CLEAR_QUIET = 8; + + private byte _value[] = null; + private int _type = 0; + + public LoginServiceAttribute(byte value[]) { + super(); + _t = LOGIN_SERVICE; + _type = value[5] & 0xFF; + _type |= ((value[4] << 8) & 0xFF00); + _type |= ((value[3] << 16) & 0xFF0000); + _type |= ((value[2] << 24) & 0xFF000000); + _value = value; + } + + public int getType() { + return _type; + } + + public byte[] getValue() throws IOException { + byte[] p = new byte[4]; + + p[0] = (byte) ((_type >>> 24) & 0xFF); + p[1] = (byte) ((_type >>> 16) & 0xFF); + p[2] = (byte) ((_type >>> 8) & 0xFF); + p[3] = (byte) (_type & 0xFF); + return p; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/LoginTCPPortAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/LoginTCPPortAttribute.java new file mode 100644 index 000000000..b7921c3a8 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/LoginTCPPortAttribute.java @@ -0,0 +1,58 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class LoginTCPPortAttribute extends Attribute { + private int _port = 0; + + public LoginTCPPortAttribute(byte value[]) { + super(); + _t = LOGIN_TCP_PORT; + _port = value[5] & 0xFF; + _port |= ((value[4] << 8) & 0xFF00); + _port |= ((value[3] << 16) & 0xFF0000); + _port |= ((value[2] << 24) & 0xFF000000); + } + + public LoginTCPPortAttribute(int port) { + super(LOGIN_TCP_PORT); + _port = port; + } + + public int getPort() { + return _port; + } + + public byte[] getValue() throws IOException { + byte[] p = new byte[4]; + + p[0] = (byte) ((_port >>> 24) & 0xFF); + p[1] = (byte) ((_port >>> 16) & 0xFF); + p[2] = (byte) ((_port >>> 8) & 0xFF); + p[3] = (byte) (_port & 0xFF); + return p; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/NASClassAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/NASClassAttribute.java new file mode 100644 index 000000000..539c259f9 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/NASClassAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class NASClassAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public NASClassAttribute(byte value[]) { + super(); + _t = NAS_CLASS; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/NASIPAddressAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/NASIPAddressAttribute.java new file mode 100644 index 000000000..3b9e438ff --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/NASIPAddressAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class NASIPAddressAttribute extends Attribute { + private InetAddress _ip = null; + private byte _value[] = null; + + public NASIPAddressAttribute(byte value[]) { + super(); + _t = NAS_IP_ADDRESS; + _value = value; + } + + public NASIPAddressAttribute(InetAddress ip) { + super(NAS_IP_ADDRESS); + _ip = ip; + } + + public byte[] getValue() throws IOException { + return _ip.getAddress(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/NASIdentifierAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/NASIdentifierAttribute.java new file mode 100644 index 000000000..3cc67d8ec --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/NASIdentifierAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class NASIdentifierAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public NASIdentifierAttribute(byte value[]) { + super(); + _t = NAS_IDENTIFIER; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/NASPacket.java b/pki/base/util/src/com/netscape/cmsutil/radius/NASPacket.java new file mode 100644 index 000000000..86eec6dbf --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/NASPacket.java @@ -0,0 +1,57 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public abstract class NASPacket extends Packet { + public NASPacket(int c, short id, Authenticator auth) { + super(c, id, auth); + } + + public byte[] getData() throws IOException { + // prepare the attributes first + ByteArrayOutputStream attrsOS = new ByteArrayOutputStream(); + + for (int i = 0; i < _attrs.size(); i++) { + Attribute attr = (Attribute) getAttributeAt(i); + + attrsOS.write(attr.getData()); + } + byte attrsData[] = attrsOS.toByteArray(); + + ByteArrayOutputStream dataOS = new ByteArrayOutputStream(); + + dataOS.write(_c); // code + dataOS.write(_id); // identifier + int len = attrsData.length + 20; + + dataOS.write((len >>> 8) & 0xFF); + dataOS.write(len & 0xFF); + dataOS.write(_auth.getData()); + dataOS.write(attrsData); + + return dataOS.toByteArray(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/NASPortAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/NASPortAttribute.java new file mode 100644 index 000000000..ebf1aa218 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/NASPortAttribute.java @@ -0,0 +1,54 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class NASPortAttribute extends Attribute { + private int _port = 0; + + public NASPortAttribute(byte value[]) { + super(); + _t = NAS_PORT; + _port = value[5] & 0xFF; + _port |= ((value[4] << 8) & 0xFF00); + _port |= ((value[3] << 16) & 0xFF0000); + _port |= ((value[2] << 24) & 0xFF000000); + } + + public NASPortAttribute(int port) { + super(NAS_PORT); + _port = port; + } + + public byte[] getValue() throws IOException { + byte[] p = new byte[4]; + + p[0] = (byte) ((_port >>> 24) & 0xFF); + p[1] = (byte) ((_port >>> 16) & 0xFF); + p[2] = (byte) ((_port >>> 8) & 0xFF); + p[3] = (byte) (_port & 0xFF); + return p; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/NASPortTypeAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/NASPortTypeAttribute.java new file mode 100644 index 000000000..a6e40ae4b --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/NASPortTypeAttribute.java @@ -0,0 +1,59 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class NASPortTypeAttribute extends Attribute { + public static final int ASYNC = 0; + public static final int SYNC = 1; + public static final int ISDN_SYNC = 2; + public static final int ISDN_ASYNC_V120 = 3; + public static final int ISDN_ASYNC_V110 = 4; + public static final int VIRTUAL = 5; + public static final int PIAFS = 6; + public static final int HDLC = 7; + public static final int X_25 = 8; + public static final int X_75 = 9; + public static final int G3_FAX = 10; + public static final int SDSL = 11; + public static final int ADSL_CAP = 12; + public static final int ADSL_DMT = 13; + public static final int IDSL = 14; + public static final int ETHERNET = 15; + public static final int XDSL = 16; + public static final int CABLE = 17; + + private byte _value[] = null; + + public NASPortTypeAttribute(byte value[]) { + super(); + _t = NAS_PORT_TYPE; + _value = value; + } + + public byte[] getValue() throws IOException { + return _value; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/Packet.java b/pki/base/util/src/com/netscape/cmsutil/radius/Packet.java new file mode 100644 index 000000000..cd0e5a881 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/Packet.java @@ -0,0 +1,78 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public abstract class Packet { + public static final int ACCESS_REQUEST = 1; + public static final int ACCESS_ACCEPT = 2; + public static final int ACCESS_REJECT = 3; + // public static final int ACCOUNTING_REQUEST = 4; + // public static final int ACCOUNTING_RESPONSE = 5; + public static final int ACCESS_CHALLENGE = 11; + public static final int RESERVED = 255; + + protected int _c = 0; + protected short _id = 0; + protected Authenticator _auth = null; + protected AttributeSet _attrs = new AttributeSet(); + + public Packet() { + } + + public Packet(int c, short id, Authenticator auth) { + _c = c; + _id = id; + _auth = auth; + } + + public int getCode() { + return _c; + } + + public short getIdentifier() { + return _id; + } + + public Authenticator getAuthenticator() { + return _auth; + } + + public void addAttribute(Attribute attr) { + _attrs.addAttribute(attr); + } + + public AttributeSet getAttributeSet() { + return _attrs; + } + + public Attribute getAttributeAt(int pos) { + return _attrs.getAttributeAt(pos); + } + + public String toString() { + return "Packet [code=" + _c + ",id=" + (_id & 0xFF) + "]"; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/PacketFactory.java b/pki/base/util/src/com/netscape/cmsutil/radius/PacketFactory.java new file mode 100644 index 000000000..9bd5d1921 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/PacketFactory.java @@ -0,0 +1,45 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class PacketFactory { + public static ServerPacket createServerPacket(byte data[]) + throws IOException { + switch (data[0] & 0xFF) { + case Packet.ACCESS_ACCEPT: + return new AccessAccept(data); + + case Packet.ACCESS_REJECT: + return new AccessReject(data); + + case Packet.ACCESS_CHALLENGE: + return new AccessChallenge(data); + + default: + throw new IOException("Unknown server packet " + (data[0] & 0xFF)); + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/PortLimitAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/PortLimitAttribute.java new file mode 100644 index 000000000..41d185e88 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/PortLimitAttribute.java @@ -0,0 +1,57 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class PortLimitAttribute extends Attribute { + private int _port = 0; + + private byte _value[] = null; + + public PortLimitAttribute(byte value[]) { + super(); + _t = FRAMED_IP_ADDRESS; + _value = value; + _port = value[5] & 0xFF; + _port |= ((value[4] << 8) & 0xFF00); + _port |= ((value[3] << 16) & 0xFF0000); + _port |= ((value[2] << 24) & 0xFF000000); + + } + + public int getPort() { + return _port; + } + + public byte[] getValue() throws IOException { + byte[] p = new byte[4]; + + p[0] = (byte) ((_port >>> 24) & 0xFF); + p[1] = (byte) ((_port >>> 16) & 0xFF); + p[2] = (byte) ((_port >>> 8) & 0xFF); + p[3] = (byte) (_port & 0xFF); + return p; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/ProxyStateAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/ProxyStateAttribute.java new file mode 100644 index 000000000..91210b354 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/ProxyStateAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class ProxyStateAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public ProxyStateAttribute(byte value[]) { + super(); + _t = PROXY_STATE; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/RadiusConn.java b/pki/base/util/src/com/netscape/cmsutil/radius/RadiusConn.java new file mode 100644 index 000000000..5d16cd8a2 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/RadiusConn.java @@ -0,0 +1,229 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +/** + * This class implements RFC2865 - Remote Authentication Dial In + * User Service (RADIUS), June 2000. + */ +public class RadiusConn { + public static int MAX_RETRIES = 10; + public static int OFFICAL_PORT = 1812; + public static int DEFAULT_PORT = 1645; + public static int DEFAULT_TIMEOUT = 5; + + public static String OPTION_DEBUG = "OPTION_DEBUG"; + + private Properties _options = null; + private boolean _traceOn = true; + private String _host[] = new String[2]; + private int _port[] = new int[2]; + private int _selected = 0; + private String _secret = null; + private DatagramSocket _socket = null; + private short _id = (short) System.currentTimeMillis(); + private int _maxRetries = MAX_RETRIES; + private SecureRandom _rand = null; + + public RadiusConn(String host1, String host2, int port, String secret, + int timeout) throws SocketException { + this(host1, port, host2, port, secret, timeout, null, null); + } + + public RadiusConn(String host, int port, String secret, byte seed[], + Properties options) + throws SocketException { + this(host, port, host, port, secret, DEFAULT_TIMEOUT, seed, options); + } + + public RadiusConn(String host1, int port1, String host2, int port2, + String secret, int timeout, byte seed[], Properties options) + throws SocketException { + _host[0] = host1; + _port[0] = port1; + _host[1] = host2; + _port[1] = port2; + _selected = 0; + _secret = secret; + _options = options; + _socket = new DatagramSocket(); + _socket.setSoTimeout(timeout * 1000); + if (seed == null) { + _rand = new SecureRandom(); + } else { + _rand = new SecureRandom(seed); + } + } + + public void disconnect() throws IOException { + _socket.disconnect(); + } + + public void authenticate(String name, String password) + throws IOException, NoSuchAlgorithmException, + RejectException, ChallengeException { + int retries = 0; + Packet res = null; + + do { + AccessRequest req = createAccessRequest(); + + req.addAttribute(new UserNameAttribute(name)); + req.addAttribute(new UserPasswordAttribute(req.getAuthenticator(), + _secret, password)); + req.addAttribute(new NASIPAddressAttribute(InetAddress.getLocalHost())); + req.addAttribute(new NASPortAttribute(_socket.getLocalPort())); + + send(req, _host[_selected], _port[_selected]); + try { + retries++; + res = receive(); + if (res instanceof AccessReject) { + throw new RejectException((AccessReject) res); + } else if (res instanceof AccessChallenge) { + throw new ChallengeException((AccessChallenge) res); + } + } catch (InterruptedIOException e) { + if (retries >= _maxRetries) { + // switch server if maxRetries reaches limit + retries = 0; + if (_selected == 0) { + _selected = 1; + } else { + _selected = 0; + } + // throw e; + } + + } + } + while (res == null); + } + + public void replyChallenge(String password, ChallengeException ce) + throws IOException, NoSuchAlgorithmException, + RejectException, ChallengeException { + replyChallenge(null, password, ce); + } + + public void replyChallenge(String name, String password, + ChallengeException ce) + throws IOException, NoSuchAlgorithmException, + RejectException, ChallengeException { + StateAttribute state = (StateAttribute) + ce.getAttributeSet().getAttributeByType(Attribute.STATE); + + if (state == null) + throw new IOException("State not found in challenge"); + AccessRequest req = createAccessRequest(); + + req.addAttribute(state); // needed in challenge + if (name != null) { + req.addAttribute(new UserNameAttribute(name)); + } + req.addAttribute(new UserPasswordAttribute(req.getAuthenticator(), + _secret, password)); + req.addAttribute(new NASIPAddressAttribute(InetAddress.getLocalHost())); + req.addAttribute(new NASPortAttribute(_socket.getLocalPort())); + + send(req, _host[_selected], _port[_selected]); + Packet res = receive(); + + if (res instanceof AccessReject) { + throw new RejectException((AccessReject) res); + } else if (res instanceof AccessChallenge) { + throw new ChallengeException((AccessChallenge) res); + } + } + + public void replyChallenge(String name, String password, String state) + throws IOException, NoSuchAlgorithmException, + RejectException, ChallengeException { + if (state == null) + throw new IOException("State not found in challenge"); + AccessRequest req = createAccessRequest(); + + req.addAttribute(new StateAttribute(state)); // needed in challenge + req.addAttribute(new UserNameAttribute(name)); + req.addAttribute(new UserPasswordAttribute(req.getAuthenticator(), + _secret, password)); + req.addAttribute(new NASIPAddressAttribute(InetAddress.getLocalHost())); + req.addAttribute(new NASPortAttribute(_socket.getLocalPort())); + + send(req, _host[_selected], _port[_selected]); + Packet res = receive(); + + if (res instanceof AccessReject) { + throw new RejectException((AccessReject) res); + } else if (res instanceof AccessChallenge) { + throw new ChallengeException((AccessChallenge) res); + } + } + + private short getIdentifier() { + return _id++; + } + + private void send(NASPacket packet, String host, int port) + throws IOException { + DatagramPacket dp = new DatagramPacket(new byte[4096], 4096); + + dp.setPort(port); + dp.setAddress(InetAddress.getByName(host)); + byte data[] = packet.getData(); + + dp.setLength(data.length); + dp.setData(data); + _socket.send(dp); + if (_traceOn) + trace("Sent " + packet); + } + + private ServerPacket receive() + throws IOException { + DatagramPacket dp = new DatagramPacket(new byte[4096], 4096); + + _socket.receive(dp); + byte data[] = dp.getData(); + ServerPacket p = PacketFactory.createServerPacket(data); + + if (_traceOn) + trace("Received " + p + " size=" + p.getAttributeSet().size()); + return p; + } + + private AccessRequest createAccessRequest() throws NoSuchAlgorithmException { + RequestAuthenticator ra = new RequestAuthenticator(_rand, _secret); + AccessRequest req = new AccessRequest(getIdentifier(), ra); + + return req; + } + + private void trace(String msg) { + System.out.println("TRACE: " + msg); + System.out.flush(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/RejectException.java b/pki/base/util/src/com/netscape/cmsutil/radius/RejectException.java new file mode 100644 index 000000000..1a76e7603 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/RejectException.java @@ -0,0 +1,42 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class RejectException extends Exception { + private AccessReject _res = null; + + public RejectException(AccessReject res) { + _res = res; + } + + public AttributeSet getAttributeSet() { + return _res.getAttributeSet(); + } + + public String getReplyMessage() { + return ((ReplyMessageAttribute) (_res.getAttributeSet().getAttributeByType(Attribute.REPLY_MESSAGE))).getString(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/ReplyMessageAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/ReplyMessageAttribute.java new file mode 100644 index 000000000..dd1fc29d1 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/ReplyMessageAttribute.java @@ -0,0 +1,46 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class ReplyMessageAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public ReplyMessageAttribute(byte value[]) { + super(); + _t = REPLY_MESSAGE; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/RequestAuthenticator.java b/pki/base/util/src/com/netscape/cmsutil/radius/RequestAuthenticator.java new file mode 100644 index 000000000..eaba2077a --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/RequestAuthenticator.java @@ -0,0 +1,47 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class RequestAuthenticator extends Authenticator { + private byte _ra[] = null; + + public RequestAuthenticator(SecureRandom rand, String secret) + throws NoSuchAlgorithmException { + byte[] authenticator = new byte[16]; + + rand.nextBytes(authenticator); + + MessageDigest md5 = MessageDigest.getInstance("MD5"); + + md5.update(authenticator); + md5.update(secret.getBytes()); + _ra = md5.digest(); + } + + public byte[] getData() throws IOException { + return _ra; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/ResponseAuthenticator.java b/pki/base/util/src/com/netscape/cmsutil/radius/ResponseAuthenticator.java new file mode 100644 index 000000000..509ddc35d --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/ResponseAuthenticator.java @@ -0,0 +1,38 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class ResponseAuthenticator extends Authenticator { + private byte _data[] = null; + + public ResponseAuthenticator(byte data[]) { + _data = data; + } + + public byte[] getData() throws IOException { + return _data; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/ServerPacket.java b/pki/base/util/src/com/netscape/cmsutil/radius/ServerPacket.java new file mode 100644 index 000000000..c349fed9a --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/ServerPacket.java @@ -0,0 +1,53 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public abstract class ServerPacket extends Packet { + public ServerPacket(byte data[]) throws IOException { + super(); + _c = data[0]; + _id = data[1]; + int datalen = data[3] & 0xFF; + + datalen |= ((data[2] << 8) & 0xFF00); + byte authData[] = new byte[16]; + + System.arraycopy(data, 4, authData, 0, 16); + _auth = new ResponseAuthenticator(authData); + + // building attributes + int startp = 20; + + while (startp != datalen) { + int attrLen = (data[startp + 1] & 0xFF); + byte attrData[] = new byte[attrLen]; + + System.arraycopy(data, startp, attrData, 0, attrData.length); + addAttribute(AttributeFactory.createAttribute(attrData)); + startp += attrData.length; + } + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/ServiceTypeAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/ServiceTypeAttribute.java new file mode 100644 index 000000000..7de8cfb01 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/ServiceTypeAttribute.java @@ -0,0 +1,67 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class ServiceTypeAttribute extends Attribute { + public static final int LOGIN = 1; + public static final int FRAMED = 2; + public static final int CALLBACK_LOGIN = 3; + public static final int CALLBACK_FRAMED = 4; + public static final int OUTBOUND = 5; + public static final int ADMINSITRATIVE = 6; + public static final int NAS_PROMPT = 7; + public static final int AUTHENTICATE_ONLY = 8; + public static final int CALLBACK_NAS_PROMPT = 9; + public static final int CALL_CHECK = 10; + public static final int CALLBACK_ADMINISTRATIVE = 11; + + private byte _value[] = null; + private int _type = 0; + + public ServiceTypeAttribute(byte value[]) { + super(); + _t = SERVICE_TYPE; + _type = value[5] & 0xFF; + _type |= ((value[4] << 8) & 0xFF00); + _type |= ((value[3] << 16) & 0xFF0000); + _type |= ((value[2] << 24) & 0xFF000000); + _value = value; + } + + public int getType() { + return _type; + } + + public byte[] getValue() throws IOException { + byte[] p = new byte[4]; + + p[0] = (byte) ((_type >>> 24) & 0xFF); + p[1] = (byte) ((_type >>> 16) & 0xFF); + p[2] = (byte) ((_type >>> 8) & 0xFF); + p[3] = (byte) (_type & 0xFF); + return p; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/SessionTimeoutAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/SessionTimeoutAttribute.java new file mode 100644 index 000000000..f83690d6f --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/SessionTimeoutAttribute.java @@ -0,0 +1,54 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class SessionTimeoutAttribute extends Attribute { + private int _timeout = 0; + + public SessionTimeoutAttribute(byte value[]) { + super(); + _t = SESSION_TIMEOUT; + _timeout = value[5] & 0xFF; + _timeout |= ((value[4] << 8) & 0xFF00); + _timeout |= ((value[3] << 16) & 0xFF0000); + _timeout |= ((value[2] << 24) & 0xFF000000); + } + + public SessionTimeoutAttribute(int timeout) { + super(SESSION_TIMEOUT); + _timeout = timeout; + } + + public byte[] getValue() throws IOException { + byte[] p = new byte[4]; + + p[0] = (byte) ((_timeout >>> 24) & 0xFF); + p[1] = (byte) ((_timeout >>> 16) & 0xFF); + p[2] = (byte) ((_timeout >>> 8) & 0xFF); + p[3] = (byte) (_timeout & 0xFF); + return p; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/StateAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/StateAttribute.java new file mode 100644 index 000000000..c18e59880 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/StateAttribute.java @@ -0,0 +1,51 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class StateAttribute extends Attribute { + private byte _value[] = null; + private String _str = null; + + public StateAttribute(String str) { + _t = STATE; + _str = str; + } + + public StateAttribute(byte value[]) { + super(); + _t = STATE; + _str = new String(value, 2, value.length - 2); + _value = value; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + return _str.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/TerminationActionAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/TerminationActionAttribute.java new file mode 100644 index 000000000..1a554ea2d --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/TerminationActionAttribute.java @@ -0,0 +1,61 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class TerminationActionAttribute extends Attribute { + public static final int DEFAULT = 0; + public static final int RADIUS_REQUEST = 1; + + private int _action = 0; + + public TerminationActionAttribute(byte value[]) { + super(); + _t = TERMINATION_ACTION; + _action = value[5] & 0xFF; + _action |= ((value[4] << 8) & 0xFF00); + _action |= ((value[3] << 16) & 0xFF0000); + _action |= ((value[2] << 24) & 0xFF000000); + } + + public TerminationActionAttribute(int action) { + super(TERMINATION_ACTION); + _action = action; + } + + public int getAction() { + return _action; + } + + public byte[] getValue() throws IOException { + byte[] p = new byte[4]; + + p[0] = (byte) ((_action >>> 24) & 0xFF); + p[1] = (byte) ((_action >>> 16) & 0xFF); + p[2] = (byte) ((_action >>> 8) & 0xFF); + p[3] = (byte) (_action & 0xFF); + return p; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/UserNameAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/UserNameAttribute.java new file mode 100644 index 000000000..4e725ac3f --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/UserNameAttribute.java @@ -0,0 +1,45 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class UserNameAttribute extends Attribute { + private String _name = null; + + public UserNameAttribute(byte value[]) { + super(); + _t = USER_NAME; + _name = new String(value, 2, value.length - 2); + } + + public UserNameAttribute(String name) { + super(USER_NAME); + _name = name; + } + + public byte[] getValue() throws IOException { + return _name.getBytes(); + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/UserPasswordAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/UserPasswordAttribute.java new file mode 100644 index 000000000..4550081ae --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/UserPasswordAttribute.java @@ -0,0 +1,77 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class UserPasswordAttribute extends Attribute { + private Authenticator _ra = null; + private String _secret = null; + private String _password = null; + + public UserPasswordAttribute(byte value[]) { + // + } + + public UserPasswordAttribute(Authenticator ra, String secret, String password) { + super(USER_PASSWORD); + _ra = ra; + _secret = secret; + _password = password; + } + + public byte[] getValue() throws IOException { + MessageDigest md5 = null; + + try { + md5 = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new IOException(e.getMessage()); + } + md5.update(_secret.getBytes()); + md5.update(_ra.getData()); + byte sum[] = md5.digest(); + + byte up[] = _password.getBytes(); + int oglen = (up.length / 16) + 1; + byte ret[] = new byte[oglen * 16]; + + for (int i = 0; i < ret.length; i++) { + if ((i % 16) == 0) { + md5.reset(); + md5.update(_secret.getBytes()); + } + if (i < up.length) { + ret[i] = (byte) (sum[i % 16] ^ up[i]); + } else { + ret[i] = (byte) (sum[i % 16] ^ 0); + } + md5.update(ret[i]); + if ((i % 16) == 15) { + sum = md5.digest(); + } + } + return ret; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/radius/VendorSpecificAttribute.java b/pki/base/util/src/com/netscape/cmsutil/radius/VendorSpecificAttribute.java new file mode 100644 index 000000000..1d19a5055 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/radius/VendorSpecificAttribute.java @@ -0,0 +1,58 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.radius; + + +import java.util.*; +import java.math.*; +import java.security.*; +import java.net.*; +import java.io.*; + + +public class VendorSpecificAttribute extends Attribute { + private byte _value[] = null; + private String _id = null; + private String _str = null; + + public VendorSpecificAttribute(byte value[]) { + super(); + _t = VENDOR_SPECIFIC; + _id = new String(value, 2, 4); + _str = new String(value, 6, value.length - 6); + _value = value; + } + + public String getId() { + return _id; + } + + public String getString() { + return _str; + } + + public byte[] getValue() throws IOException { + byte v[] = new byte[_id.length() + _str.length()]; + byte idData[] = _id.getBytes(); + byte strData[] = _str.getBytes(); + + System.arraycopy(idData, 0, v, 0, _id.length()); + System.arraycopy(strData, 0, v, _id.length(), _str.length()); + return v; + } +} diff --git a/pki/base/util/src/com/netscape/cmsutil/scep/CRSPKIMessage.java b/pki/base/util/src/com/netscape/cmsutil/scep/CRSPKIMessage.java new file mode 100644 index 000000000..5ea7eaa8d --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/scep/CRSPKIMessage.java @@ -0,0 +1,800 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.scep; + + +import org.mozilla.jss.asn1.*; +import org.mozilla.jss.pkcs7.*; +import java.io.*; +import java.util.Arrays; +import java.util.Hashtable; +import org.mozilla.jss.pkcs7.ContentInfo; +//import org.mozilla.jss.util.Assert; +import org.mozilla.jss.pkix.primitive.*; +//import org.mozilla.jss.pkix.primitive.Attribute; +import org.mozilla.jss.pkcs7.Attribute; +import org.mozilla.jss.crypto.*; +import java.security.PublicKey; +import org.mozilla.jss.pkix.cert.*; + + +public class CRSPKIMessage { + + // OIDs for authenticated attributes + public static OBJECT_IDENTIFIER CRS_MESSAGETYPE = + new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 113733, 1, 9, 2} + ); + public static OBJECT_IDENTIFIER CRS_PKISTATUS = + new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 113733, 1, 9, 3} + ); + public static OBJECT_IDENTIFIER CRS_FAILINFO = + new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 113733, 1, 9, 4} + ); + public static OBJECT_IDENTIFIER CRS_SENDERNONCE = + new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 113733, 1, 9, 5} + ); + public static OBJECT_IDENTIFIER CRS_RECIPIENTNONCE = + new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 113733, 1, 9, 6} + ); + public static OBJECT_IDENTIFIER CRS_TRANSID = + new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 113733, 1, 9, 7} + ); + public static OBJECT_IDENTIFIER CRS_EXTENSIONREQ = + new OBJECT_IDENTIFIER(new long[] {2, 16, 840, 1, 113733, 1, 9, 8} + ); + + // PKCS9 defined OIDs + + public static OBJECT_IDENTIFIER PKCS9_CONTENT_TYPE = + new OBJECT_IDENTIFIER(new long[] {1, 2, 840, 113549, 1, 9, 3} + ); + + public static OBJECT_IDENTIFIER PKCS9_MESSAGE_DIGEST = + new OBJECT_IDENTIFIER(new long[] {1, 2, 840, 113549, 1, 9, 4} + ); + + /* PKCS 1 - rsaEncryption */ + public static OBJECT_IDENTIFIER RSA_ENCRYPTION = + new OBJECT_IDENTIFIER(new long[] {1, 2, 840, 113549, 1, 1, 1} + ); + + public static OBJECT_IDENTIFIER DES_CBC_ENCRYPTION = + new OBJECT_IDENTIFIER(new long[] {1, 3, 14, 3, 2, 7} + ); + + public static OBJECT_IDENTIFIER MD5_DIGEST = + new OBJECT_IDENTIFIER(new long[] {1, 2, 840, 113549, 2, 5} + ); + + // Strings given in 'messageType' authenticated attribute + public final static String mType_PKCSReq = "19"; + public final static String mType_CertRep = "3"; + public final static String mType_GetCertInitial = "20"; + public final static String mType_GetCert = "21"; + public final static String mType_GetCRL = "22"; + + // Strings given in 'PKIStatus' authenticated attribute + public final static String mStatus_SUCCESS = "0"; + public final static String mStatus_FAILURE = "2"; + public final static String mStatus_PENDING = "3"; + + // Strings given in 'failInfo' authenticated attribute + public final static String mFailInfo_badAlg = "0"; + public final static String mFailInfo_badMessageCheck = "1"; + public final static String mFailInfo_badRequest = "2"; + public final static String mFailInfo_badTime = "3"; + public final static String mFailInfo_badCertId = "4"; + public final static String mFailInfo_unsupportedExt = "5"; + public final static String mFailInfo_mustArchiveKeys = "6"; + public final static String mFailInfo_badIdentity = "7"; + public final static String mFailInfo_popRequired = "8"; + public final static String mFailInfo_popFailed = "9"; + public final static String mFailInfo_noKeyReuse = "10"; + public final static String mFailInfo_internalCAError = "11"; + public final static String mFailInfo_tryLater = "12"; + + // ************************************************************************ + // These private members represent the flattened structure of the PKIMessage + // ************************************************************************ + + // top level is just a ContentInfo + private ContentInfo crsci; + // it's content is a signedData + private SignedData sd; + + // In the signed data, we have: + private int sdv; // Version + private ContentInfo data; // The data to be digested + private EnvelopedData sded; // Enveloped data inside of signed data + private byte[] signerCertBytes; + org.mozilla.jss.pkix.cert.Certificate signerCert; + + private SET sis; // set of SignerInfos + private SignerInfo si; // First SignerInfo + private int siv; // Version + private SET aa; // Authenticated Attributes + private SET aa_old; // Authenticated Attributes + private IssuerAndSerialNumber sgnIASN; // Signer's Issuer Name and Serialnum + private OCTET_STRING aa_digest; // digest of the authenticated attrs + + private String messageType; // these are all authenticated attributes + private String failInfo; + private String pkiStatus; + private String transactionID; + private byte[] senderNonce; + private byte[] recipientNonce; + private OCTET_STRING msg_digest; // digest of the message + + // Inside the sded Enveloped data + private RecipientInfo ri; // First RecipientInfo + private int riv; // Version + private AlgorithmIdentifier riAlgid; // alg that the bulk key is wrapped with + private byte[] riKey; // bulk key, wrapped with above algorithm + private byte[] cKey; // * 'clear', unwrapped key (not in ASN.1) * + private IssuerAndSerialNumber rcpIASN; // Recipient's Issuer Name and Serial Number + + private EncryptedContentInfo eci; + private byte[] iv; // initialization vector for above key + private byte[] ec; // encrypted content (P10, in case of request) + private byte[] cc; // * 'clear' content (not in ASN.1) * + + // For the CertRep, the enveloped content is another signed Data: + private SignedData crsd; + private int rsdVersion; + private byte[] rsdCert; // certificate to send in response + + private Object myP10; + + private Hashtable attrs; // miscellanous + + // *** END *** // + + + public void debug() { + } + + public void put(Object a, Object b) { + attrs.put(a, b); + } + + public Object get(Object a) { + return attrs.get(a); + } + + // These functions are used to initialize the various blobs + + public void makeSignedData(int version, + byte[] certificate) { + + try { + SET digest_algs = new SET(); + + digest_algs.addElement(new AlgorithmIdentifier(MD5_DIGEST, new NULL())); + + // SET certs = new SET(); + // certs.addElement(new ANY(certificate)); + + SET sis = new SET(); + + sis.addElement(si); + + ContentInfo data = this.data; + + this.sd = new SignedData( + digest_algs, + data, + null, // don't send the certs, he already has them + null, // crl's + sis); + + } catch (Exception e) { + } + } + + public byte[] getResponse() throws IOException, InvalidBERException { + + crsci = new ContentInfo(ContentInfo.SIGNED_DATA, + sd); + + return ASN1Util.encode(crsci); + + // ANY a = crsci.getContent(); + // return a.getEncoded(); + } + + /* + public void makeSignerInfo_old(int version, + // issuer and serialnumber + byte[] digest) { + + si = new SignerInfo(new INTEGER(version), + sgnIASN, // issuer and serialnum + new AlgorithmIdentifier(MD5_DIGEST, new NULL()), // digest algorithm + this.aa, // Authenticated Attributes + new AlgorithmIdentifier(RSA_ENCRYPTION,new NULL()), // digest encryption algorithm + new OCTET_STRING(digest), // digest + null); // unauthenticated attributes + + } + */ + + public void makeSignerInfo(int version, + // issuer and serialnumber + org.mozilla.jss.crypto.PrivateKey pk) + throws java.security.NoSuchAlgorithmException, + TokenException, + java.security.InvalidKeyException, + java.security.SignatureException, + org.mozilla.jss.CryptoManager.NotInitializedException { + + si = new SignerInfo(sgnIASN, // issuer and serialnum + this.aa, // Authenticated Attributes + null, // Unauthenticated Attrs + ContentInfo.ENVELOPED_DATA, // content type + msg_digest.toByteArray(), // digest + SignatureAlgorithm.RSASignatureWithMD5Digest, + pk); + + } + + public void makeAuthenticatedAttributes() { + + aa = new SET(); + + try { + if (transactionID != null) { + SET tidset = new SET(); + + tidset.addElement((new PrintableString(transactionID))); + aa.addElement(new Attribute(CRS_TRANSID, tidset)); + } + + if (pkiStatus != null) { + SET pkistatusset = new SET(); + + pkistatusset.addElement(new PrintableString(pkiStatus)); + aa.addElement(new Attribute(CRS_PKISTATUS, pkistatusset)); + } + + if (messageType != null) { + SET aaset = new SET(); + + aaset.addElement(new PrintableString(messageType)); + aa.addElement(new Attribute(CRS_MESSAGETYPE, aaset)); + } + + if (failInfo != null) { + SET fiset = new SET(); + + fiset.addElement(new PrintableString(failInfo)); + aa.addElement(new Attribute(CRS_FAILINFO, fiset)); + } + + if (recipientNonce != null) { + SET rnset = new SET(); + + rnset.addElement(new OCTET_STRING(recipientNonce)); + aa.addElement(new Attribute(CRS_RECIPIENTNONCE, rnset)); + } + + // XXX sender nonce + + } catch (CharConversionException e) { + } + } + + public byte[] makeEnvelopedData(int version) { + + byte[] r; + + try { + + if (this.ri != null) { + ContentInfo ci; + + SET ris = new SET(); + + ris.addElement(this.ri); + + this.sded = new EnvelopedData( + new INTEGER(version), + ris, + eci); + + ci = new ContentInfo(ContentInfo.ENVELOPED_DATA, + sded); + ByteArrayOutputStream ba = new ByteArrayOutputStream(); + + ci.encode(ba); + r = ba.toByteArray(); + } else { + r = new byte[0]; + } + + this.data = new ContentInfo(ContentInfo.DATA, + new OCTET_STRING(r)); + + return r; + + // return this.sded.getEncodedContents(); + } catch (Exception e) { + return null; + } + + } + + public void makeRecipientInfo(int version, byte[] riKey) { + this.riv = version; + + this.riAlgid = new AlgorithmIdentifier(RSA_ENCRYPTION, new NULL()); + this.riKey = riKey; + + this.ri = new RecipientInfo( + new INTEGER(this.riv), + rcpIASN, + this.riAlgid, + new OCTET_STRING(this.riKey) + ); + } + + public void makeEncryptedContentInfo(byte[] iv, byte[] ec) { + this.iv = iv; + this.ec = ec; + + try { + + AlgorithmIdentifier aid = new AlgorithmIdentifier(DES_CBC_ENCRYPTION, new OCTET_STRING(iv)); + + //eci = EncryptedContentInfo.createCRSCompatibleEncryptedContentInfo( + eci = new EncryptedContentInfo(ContentInfo.DATA, + aid, + new OCTET_STRING(ec) + ); + + } catch (Exception e) { + } + } + + public byte[] makeSignedRep(int v, byte[] certificate) { + rsdVersion = v; + rsdCert = certificate; + try { + SET certs = new SET(); + ANY cert = new ANY(certificate); + + certs.addElement(cert); + + crsd = new SignedData( + new SET(), // empty set of digestAlgorithmID's + new ContentInfo( + new OBJECT_IDENTIFIER(new long[] {1, 2, 840, 113549, 1, 7, 1} + ), + null), //empty content + certs, + null, // no CRL's + new SET() // empty SignerInfos + ); + ContentInfo wrap = new ContentInfo(ContentInfo.SIGNED_DATA, + crsd); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + wrap.encode(baos); + + return baos.toByteArray(); + // return crsd.getEncodedContents(); + } catch (Exception e) { + return null; + } + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("{ messageType="); + sb.append(getMessageType()); + sb.append(", failInfo="); + sb.append(getFailInfo()); + sb.append(", pkiStatus="); + sb.append(getPKIStatus()); + sb.append(", transactionID="); + sb.append(getTransactionID()); + sb.append(", senderNonce="); + sb.append( Arrays.toString( getSenderNonce() ) ); + sb.append(", recipientNonce="); + sb.append( Arrays.toString( getRecipientNonce() ) ); + sb.append(" }"); + + String s = sb.toString(); + return s; + } + + public String getMessageType() { + return messageType; + } + + public String getFailInfo() { + return failInfo; + } + + public String getPKIStatus() { + return pkiStatus; + } + + public String getTransactionID() { + return transactionID; + } + + public byte[] getSenderNonce() { + return senderNonce; + } + + public byte[] getRecipientNonce() { + return recipientNonce; + } + + public byte[] getWrappedKey() { + return riKey; + } + + public byte[] getEncryptedPkcs10() { + return ec; + } + + public byte[] getIV() { + return iv; + } + + public PublicKey getSignerPublicKey() { + try { + + org.mozilla.jss.pkix.cert.Certificate.Template ct = new + org.mozilla.jss.pkix.cert.Certificate.Template(); + + ByteArrayInputStream bais = new ByteArrayInputStream(this.signerCertBytes); + + signerCert = (org.mozilla.jss.pkix.cert.Certificate) ct.decode(bais); + return signerCert.getInfo().getSubjectPublicKeyInfo().toPublicKey(); + } catch (Exception e) { + return null; + } + } + + public byte[] getAA() { + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + aa.encode(baos); + return baos.toByteArray(); + } catch (Exception e) { + return null; + } + + } + + public void setAA_old( SET auth_attrs ) { + aa_old = auth_attrs; + } + + // SWP + public byte[] getAA_old() { + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + aa_old.encode(baos); + return baos.toByteArray(); + } catch (Exception e) { + return null; + } + + } + + public byte[] getAADigest() { + return aa_digest.toByteArray(); + } + + public Object getP10() { + return myP10; + } + + public void setP10(Object p10) { + myP10 = p10; + } + + public void setSgnIssuerAndSerialNumber(IssuerAndSerialNumber iasn) { + this.sgnIASN = iasn; + } + + public void setRcpIssuerAndSerialNumber(IssuerAndSerialNumber iasn) { + this.rcpIASN = iasn; + } + + public IssuerAndSerialNumber getSgnIssuerAndSerialNumber() { + return this.sgnIASN; + } + + public IssuerAndSerialNumber getRcpIssuerAndSerialNumber() { + return this.rcpIASN; + } + + public void setMessageType(String messageType) { + this.messageType = messageType; + } + + public void setPKIStatus(String pkiStatus) { + this.pkiStatus = pkiStatus; + } + + public void setFailInfo(String failInfo) { + this.failInfo = failInfo; + } + + public void setTransactionID(String tid) { + this.transactionID = tid; + } + + public void setRecipientNonce(byte[] rn) { + this.recipientNonce = rn; + } + + public void setSenderNonce(byte[] sn) { + this.senderNonce = sn; + } + + // public void setCertificate(byte [] cert) { this.certificate = cert; } + + + public void setMsgDigest(byte[] digest) { + this.msg_digest = new OCTET_STRING(digest); + } + + public void setAADigest(byte[] digest) { + this.aa_digest = new OCTET_STRING(digest); + } + + public void setPending() { + // setIssuerAndSerialNumber(); + + setMessageType(mType_CertRep); + setPKIStatus(mStatus_PENDING); + }; + + public void setFailure(String failInfo) { + setMessageType(mType_CertRep); + setPKIStatus(mStatus_FAILURE); + setFailInfo(failInfo); + } + + // Should add a Certificate to this call + public void setSuccess() { + setMessageType(mType_CertRep); + setPKIStatus(mStatus_SUCCESS); + } + + /** + * Gets a byte array which is the der-encoded blob + * which gets sent back to the router. + */ + + public byte[] getEncoded() { + //Assert.assert(messageType != null); + //Assert.assert(pkiStatus != null); + + return new byte[1]; // blagh + } + + public CRSPKIMessage() { + attrs = new Hashtable(); + + } + + public CRSPKIMessage (ByteArrayInputStream bais) throws InvalidBERException, Exception { + attrs = new Hashtable(); + + org.mozilla.jss.pkcs7.ContentInfo.Template crscit; + + crscit = new ContentInfo.Template(); + crsci = (ContentInfo) crscit.decode(bais); + + if (!ContentInfo.SIGNED_DATA.equals(crsci.getContentType())) { + throw new Exception("ContentType wasn't signed data, it was" + crsci.getContentType()); + } + + // Now that we know that the contentInfo is a SignedData, we can decode it + SignedData.Template sdt = new SignedData.Template(); + + sd = (SignedData) sdt.decode( + new ByteArrayInputStream( + ((ANY) crsci.getContent()).getEncoded() + )); + + this.decodeSD(); + + } + + private void decodeSD() throws Exception { + ContentInfo sdci; + + sis = sd.getSignerInfos(); + + decodeSI(); + + sdci = sd.getContentInfo(); + + // HACK to work with CRS + ANY a = (ANY) sdci.getContent(); + ByteArrayInputStream s = new ByteArrayInputStream(a.getEncoded()); + OCTET_STRING os = (OCTET_STRING) (new OCTET_STRING.Template()).decode(s); + + ByteArrayInputStream s2 = new ByteArrayInputStream(os.toByteArray()); + ContentInfo ci = (ContentInfo) (new ContentInfo.Template()).decode(s2); + ByteArrayInputStream s3 = new ByteArrayInputStream(((ANY) ci.getContent()).getEncoded()); + + EnvelopedData.Template edt = new EnvelopedData.Template(); + + sded = (EnvelopedData) edt.decode(s3); + + SET signerCerts = (SET) sd.getCertificates(); + Certificate firstCert = (Certificate) signerCerts.elementAt(0); + + signerCertBytes = ASN1Util.encode(firstCert); + + CertificateInfo firstCertInfo = firstCert.getInfo(); + + sgnIASN = new IssuerAndSerialNumber(firstCertInfo.getIssuer(), + firstCertInfo.getSerialNumber()); + + decodeED(); + + } + + private void decodeSI() throws Exception { + if (sis.size() == 0) { + throw new Exception("SignerInfos is empty"); + } + si = (SignerInfo) sis.elementAt(0); + decodeAA(); + + aa_digest = new OCTET_STRING(si.getEncryptedDigest()); + } + + private void decodeED() throws Exception { + SET ris; + + ris = (SET) sded.getRecipientInfos(); + + if (ris.size() == 0) { + throw new Exception("RecipientInfos is empty"); + } + ri = (RecipientInfo) ris.elementAt(0); + eci = sded.getEncryptedContentInfo(); + + if (!eci.getContentEncryptionAlgorithm().getOID().equals(DES_CBC_ENCRYPTION)) { + throw new Exception("P10 encrypted alg is not supported (not DES)"); + } + + ec = eci.getEncryptedContent().toByteArray(); + + OCTET_STRING.Template ost = new OCTET_STRING.Template(); + + OCTET_STRING os = (OCTET_STRING) + ost.decode(new ByteArrayInputStream( + ((ANY) eci.getContentEncryptionAlgorithm().getParameters()).getEncoded() + ) + ); + + iv = os.toByteArray(); + + decodeRI(); + + } + + /** + * The PKCS10 request is encrypt with a symmetric key. + * This key in turn is encrypted with the RSA key in the + * CA certificate. + * + * riAlgid is the algorithm the symm key is encrypted with. It had + * better be RSA + * riKey is the encrypted symmetric key + */ + + private void decodeRI() throws Exception { + + // really should get issuer and serial number of our RI, as this + // indicates the key we should use to decrypt with. However, we're just + // going to assume that the key is the Signing cert for the server. + + riAlgid = ri.getKeyEncryptionAlgorithmID(); + + if (!riAlgid.getOID().equals(RSA_ENCRYPTION)) { + throw new Exception("Request is protected by a key which we can't decrypt"); + } + + riKey = ri.getEncryptedKey().toByteArray(); + + } + + private void decodeAA() throws InvalidBERException, IOException { + aa = si.getAuthenticatedAttributes(); + + int count; + + for (count = 0; count < aa.size(); count++) { + Attribute a = (Attribute) aa.elementAt(count); + SET s = (SET) a.getValues(); + ANY f = (ANY) s.elementAt(0); + PrintableString ps; + PrintableString.Template pst = new PrintableString.Template(); + OCTET_STRING.Template ost = new OCTET_STRING.Template(); + + OBJECT_IDENTIFIER oid = a.getType(); + + if (oid.equals(CRS_MESSAGETYPE)) { + ps = (PrintableString) pst.decode(new ByteArrayInputStream(f.getEncoded())); + // We make a new string here + messageType = ps.toString(); + + } else if (oid.equals(CRS_PKISTATUS)) { + ps = (PrintableString) pst.decode(new ByteArrayInputStream(f.getEncoded())); + pkiStatus = new String (ps.toString()); + } else if (oid.equals(CRS_FAILINFO)) { + ps = (PrintableString) pst.decode(new ByteArrayInputStream(f.getEncoded())); + failInfo = new String (ps.toString()); + } else if (oid.equals(CRS_SENDERNONCE)) { + OCTET_STRING oss = (OCTET_STRING) ost.decode(new ByteArrayInputStream(f.getEncoded())); + + senderNonce = oss.toByteArray(); + } else if (oid.equals(CRS_RECIPIENTNONCE)) { + OCTET_STRING osr = (OCTET_STRING) ost.decode(new ByteArrayInputStream(f.getEncoded())); + + recipientNonce = osr.toByteArray(); + } else if (oid.equals(CRS_TRANSID)) { + ps = (PrintableString) pst.decode(new ByteArrayInputStream(f.getEncoded())); + transactionID = new String (ps.toString()); + } + + } + + } // end of decodeAA(); + + public String getMessageTypeString() { + if (messageType == null) { + return null; + } + + if (messageType.equals(mType_PKCSReq)) { + return "PKCSReq"; + } + if (messageType.equals(mType_CertRep)) { + return "CertRep"; + } + if (messageType.equals(mType_GetCertInitial)) { + return "GetCertInitial"; + } + if (messageType.equals(mType_GetCert)) { + return "GetCert"; + } + if (messageType.equals(mType_GetCRL)) { + return "GetCRL"; + } + // messageType should match one of the above + //Assert.assert(false); + return null; + } +} + diff --git a/pki/base/util/src/com/netscape/cmsutil/util/Cert.java b/pki/base/util/src/com/netscape/cmsutil/util/Cert.java new file mode 100644 index 000000000..8190321c2 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/util/Cert.java @@ -0,0 +1,179 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.util; + + +import netscape.security.pkcs.PKCS7; +import netscape.security.x509.X509CRLImpl; +import netscape.security.x509.X509CertImpl; +import org.mozilla.jss.crypto.SignatureAlgorithm; +import sun.misc.BASE64Decoder; + +import java.io.IOException; +import java.security.cert.CertificateException; +import java.security.cert.X509CRL; +import java.security.cert.X509Certificate; + +public class Cert { + + public static SignatureAlgorithm mapAlgorithmToJss(String algname) { + if (algname.equals("MD5withRSA")) + return SignatureAlgorithm.RSASignatureWithMD5Digest; + else if (algname.equals("MD2withRSA")) + return SignatureAlgorithm.RSASignatureWithMD2Digest; + else if (algname.equals("SHA1withRSA")) + return SignatureAlgorithm.RSASignatureWithSHA1Digest; + else if (algname.equals("SHA1withDSA")) + return SignatureAlgorithm.DSASignatureWithSHA1Digest; + else if (algname.equals("SHA256withRSA")) + return SignatureAlgorithm.RSASignatureWithSHA256Digest; + else if (algname.equals("SHA512withRSA")) + return SignatureAlgorithm.RSASignatureWithSHA512Digest; + else if (algname.equals("SHA1withEC")) + return SignatureAlgorithm.ECSignatureWithSHA1Digest; + return null; + } + + public static String stripBrackets(String s) { + if (s == null) { + return s; + } + + if ((s.startsWith("-----BEGIN CERTIFICATE-----")) && + (s.endsWith("-----END CERTIFICATE-----"))) { + return (s.substring(27, (s.length() - 25))); + } + + // To support Thawte's header and footer + if ((s.startsWith("-----BEGIN PKCS #7 SIGNED DATA-----")) && + (s.endsWith("-----END PKCS #7 SIGNED DATA-----"))) { + return (s.substring(35, (s.length() - 33))); + } + + return s; + } + + public static String stripCRLBrackets(String s) { + if (s == null) { + return s; + } + if ((s.startsWith("-----BEGIN CERTIFICATE REVOCATION LIST-----")) && + (s.endsWith("-----END CERTIFICATE REVOCATION LIST-----"))) { + return (s.substring(43, (s.length() - 41))); + } + return s; + } + + public static String stripCertBrackets(String s) { + return stripBrackets(s); + } + + private static BASE64Decoder mDecoder = new BASE64Decoder(); + public static X509CertImpl mapCert(String mime64) + throws IOException { + mime64 = stripCertBrackets(mime64.trim()); + String newval = normalizeCertStr(mime64); + byte rawPub[] = mDecoder.decodeBuffer(newval); + X509CertImpl cert = null; + + try { + cert = new X509CertImpl(rawPub); + } catch (CertificateException e) { + } + return cert; + } + + public static X509Certificate[] mapCertFromPKCS7(String mime64) + throws IOException { + mime64 = stripCertBrackets(mime64.trim()); + String newval = normalizeCertStr(mime64); + byte rawPub[] = mDecoder.decodeBuffer(newval); + PKCS7 p7 = null; + + try { + p7 = new PKCS7(rawPub); + } catch (Exception e) { + throw new IOException( "p7 is null" ); + } + return p7.getCertificates(); + } + + public static X509CRL mapCRL(String mime64) + throws IOException { + mime64 = stripCRLBrackets(mime64.trim()); + String newval = normalizeCertStr(mime64); + byte rawPub[] = mDecoder.decodeBuffer(newval); + X509CRL crl = null; + + try { + crl = new X509CRLImpl(rawPub); + } catch (Exception e) { + } + return crl; + } + + public static X509CRL mapCRL1(String mime64) + throws IOException { + mime64 = stripCRLBrackets(mime64.trim()); + + byte rawPub[] = com.netscape.osutil.OSUtil.AtoB(mime64); + X509CRL crl = null; + + try { + crl = new X509CRLImpl(rawPub); + } catch (Exception e) { + throw new IOException(e.toString()); + } + return crl; + } + + public static String normalizeCertStr(String s) { + String val = ""; + + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == '\n') { + continue; + } else if (s.charAt(i) == '\r') { + continue; + } else if (s.charAt(i) == '"') { + continue; + } else if (s.charAt(i) == ' ') { + continue; + } + val += s.charAt(i); + } + return val; + } + + public static String normalizeCertStrAndReq(String s) { + String val = ""; + + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) == '\n') { + continue; + } else if (s.charAt(i) == '\r') { + continue; + } else if (s.charAt(i) == '"') { + continue; + } + val += s.charAt(i); + } + return val; + } +} + diff --git a/pki/base/util/src/com/netscape/cmsutil/util/Fmt.java b/pki/base/util/src/com/netscape/cmsutil/util/Fmt.java new file mode 100644 index 000000000..49b878c4c --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/util/Fmt.java @@ -0,0 +1,604 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.util; + +// Fmt - some simple single-arg sprintf-like routines +// +// Copyright (C) 1996 by Jef Poskanzer <jef@acme.com>. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +// SUCH DAMAGE. +// +// Visit the ACME Labs Java page for up-to-date versions of this and other +// fine Java utilities: http://www.acme.com/java/ + + +/// Some simple single-arg sprintf-like routines. +// <P> +// It is apparently impossible to declare a Java method that accepts +// variable numbers of any type of argument. You can declare it to take +// Objects, but numeric variables and constants are not in fact Objects. +// <P> +// However, using the built-in string concatenation, it's almost as +// convenient to make a series of single-argument formatting routines. +// <P> +// Fmt can format the following types: +// <BLOCKQUOTE><CODE> +// byte short int long float double char String Object +// </CODE></BLOCKQUOTE> +// For each type there is a set of overloaded methods, each returning +// a formatted String. There's the plain formatting version: +// <BLOCKQUOTE><PRE> +// Fmt.fmt( x ) +// </PRE></BLOCKQUOTE> +// There's a version specifying a minimum field width: +// <BLOCKQUOTE><PRE> +// Fmt.fmt( x, minWidth ) +// </PRE></BLOCKQUOTE> +// And there's a version that takes flags: +// <BLOCKQUOTE><PRE> +// Fmt.fmt( x, minWidth, flags ) +// </PRE></BLOCKQUOTE> +// Currently available flags are: +// <BLOCKQUOTE><PRE> +// Fmt.ZF - zero-fill +// Fmt.LJ - left justify +// Fmt.HX - hexadecimal +// Fmt.OC - octal +// </PRE></BLOCKQUOTE> +// The HX and OC flags imply unsigned output. +// <P> +// For doubles and floats, there's a significant-figures parameter before +// the flags: +// <BLOCKQUOTE><PRE> +// Fmt.fmt( d ) +// Fmt.fmt( d, minWidth ) +// Fmt.fmt( d, minWidth, sigFigs ) +// Fmt.fmt( d, minWidth, sigFigs, flags ) +// </PRE></BLOCKQUOTE> +// <P> +// <A HREF="/resources/classes/Acme/Fmt.java">Fetch the software.</A><BR> +// <A HREF="/resources/classes/Acme.tar.Z">Fetch the entire Acme package.</A> +// <HR> +// Similar classes: +// <UL> +// <LI> Andrew Scherpbier's <A HREF="http://www.sdsu.edu/doc/java-SDSU/sdsu.FormatString.html">FormatString</A> +// Tries to allow variable numbers of arguments by +// supplying overloaded routines with different combinations of parameters, +// but doesn't actually supply that many. The floating point conversion +// is described as "very incomplete". +// <LI> Core Java's <A HREF="http://www.apl.jhu.edu/~hall/java/CoreJava-Format.html">Format</A>. +// The design seems a little weird. They want you to create an instance, +// passing the format string to the constructor, and then call an instance +// method with your data to do the actual formatting. The extra steps are +// pointless; better to just use static methods. +// </UL> + +public class Fmt { + + // Flags. + /// Zero-fill. + public static final int ZF = 1; + /// Left justify. + public static final int LJ = 2; + /// Hexadecimal. + public static final int HX = 4; + /// Octal. + public static final int OC = 8; + // Was a number - internal use. + private static final int WN = 16; + + // byte + public static String fmt(byte b) { + return fmt(b, 0, 0); + } + + public static String fmt(byte b, int minWidth) { + return fmt(b, minWidth, 0); + } + + public static String fmt(byte b, int minWidth, int flags) { + boolean hexadecimal = ((flags & HX) != 0); + boolean octal = ((flags & OC) != 0); + + if (hexadecimal) + return fmt(Integer.toString(b & 0xff, 16), minWidth, flags | WN); + else if (octal) + return fmt(Integer.toString(b & 0xff, 8), minWidth, flags | WN); + else + return fmt(Integer.toString(b & 0xff), minWidth, flags | WN); + } + + // short + public static String fmt(short s) { + return fmt(s, 0, 0); + } + + public static String fmt(short s, int minWidth) { + return fmt(s, minWidth, 0); + } + + public static String fmt(short s, int minWidth, int flags) { + boolean hexadecimal = ((flags & HX) != 0); + boolean octal = ((flags & OC) != 0); + + if (hexadecimal) + return fmt( + Integer.toString(s & 0xffff, 16), minWidth, flags | WN); + else if (octal) + return fmt( + Integer.toString(s & 0xffff, 8), minWidth, flags | WN); + else + return fmt(Integer.toString(s), minWidth, flags | WN); + } + + // int + public static String fmt(int i) { + return fmt(i, 0, 0); + } + + public static String fmt(int i, int minWidth) { + return fmt(i, minWidth, 0); + } + + public static String fmt(int i, int minWidth, int flags) { + boolean hexadecimal = ((flags & HX) != 0); + boolean octal = ((flags & OC) != 0); + + if (hexadecimal) + return fmt( + Long.toString(i & 0xffffffffL, 16), minWidth, flags | WN); + else if (octal) + return fmt( + Long.toString(i & 0xffffffffL, 8), minWidth, flags | WN); + else + return fmt(Integer.toString(i), minWidth, flags | WN); + } + + // long + public static String fmt(long l) { + return fmt(l, 0, 0); + } + + public static String fmt(long l, int minWidth) { + return fmt(l, minWidth, 0); + } + + public static String fmt(long l, int minWidth, int flags) { + boolean hexadecimal = ((flags & HX) != 0); + boolean octal = ((flags & OC) != 0); + + if (hexadecimal) { + if ((l & 0xf000000000000000L) != 0) + return fmt( + Long.toString(l >>> 60, 16) + + fmt(l & 0x0fffffffffffffffL, 15, HX | ZF), + minWidth, flags | WN); + else + return fmt(Long.toString(l, 16), minWidth, flags | WN); + } else if (octal) { + if ((l & 0x8000000000000000L) != 0) + return fmt( + Long.toString(l >>> 63, 8) + + fmt(l & 0x7fffffffffffffffL, 21, OC | ZF), + minWidth, flags | WN); + else + return fmt(Long.toString(l, 8), minWidth, flags | WN); + } else + return fmt(Long.toString(l), minWidth, flags | WN); + } + + // float + public static String fmt(float f) { + return fmt(f, 0, 0, 0); + } + + public static String fmt(float f, int minWidth) { + return fmt(f, minWidth, 0, 0); + } + + public static String fmt(float f, int minWidth, int sigFigs) { + return fmt(f, minWidth, sigFigs, 0); + } + + public static String fmt(float f, int minWidth, int sigFigs, int flags) { + if (sigFigs != 0) + return fmt( + sigFigFix(Float.toString(f), sigFigs), minWidth, + flags | WN); + else + return fmt(Float.toString(f), minWidth, flags | WN); + } + + // double + public static String fmt(double d) { + return fmt(d, 0, 0, 0); + } + + public static String fmt(double d, int minWidth) { + return fmt(d, minWidth, 0, 0); + } + + public static String fmt(double d, int minWidth, int sigFigs) { + return fmt(d, minWidth, sigFigs, 0); + } + + public static String fmt(double d, int minWidth, int sigFigs, int flags) { + if (sigFigs != 0) + return fmt( + sigFigFix(doubleToString(d), sigFigs), minWidth, + flags | WN); + else + return fmt(doubleToString(d), minWidth, flags | WN); + } + + // char + public static String fmt(char c) { + return fmt(c, 0, 0); + } + + public static String fmt(char c, int minWidth) { + return fmt(c, minWidth, 0); + } + + public static String fmt(char c, int minWidth, int flags) { + // return fmt( Character.toString( c ), minWidth, flags ); + // Character currently lacks a static toString method. Workaround + // is to make a temporary instance and use the instance toString. + return fmt(Character.valueOf(c).toString(), minWidth, flags); + } + + // Object + public static String fmt(Object o) { + return fmt(o, 0, 0); + } + + public static String fmt(Object o, int minWidth) { + return fmt(o, minWidth, 0); + } + + public static String fmt(Object o, int minWidth, int flags) { + return fmt(o.toString(), minWidth, flags); + } + + // String + public static String fmt(String s) { + return fmt(s, 0, 0); + } + + public static String fmt(String s, int minWidth) { + return fmt(s, minWidth, 0); + } + + public static String fmt(String s, int minWidth, int flags) { + int len = s.length(); + boolean zeroFill = ((flags & ZF) != 0); + boolean leftJustify = ((flags & LJ) != 0); + boolean hexadecimal = ((flags & HX) != 0); + boolean octal = ((flags & OC) != 0); + boolean wasNumber = ((flags & WN) != 0); + + if ((hexadecimal || octal || zeroFill) && !wasNumber) + throw new InternalError("Acme.Fmt: number flag on a non-number"); + if (zeroFill && leftJustify) + throw new InternalError("Acme.Fmt: zero-fill left-justify is silly"); + if (hexadecimal && octal) + throw new InternalError("Acme.Fmt: can't do both hex and octal"); + if (len >= minWidth) + return s; + int fillWidth = minWidth - len; + StringBuffer fill = new StringBuffer(fillWidth); + + for (int i = 0; i < fillWidth; ++i) + if (zeroFill) + fill.append('0'); + else + fill.append(' '); + if (leftJustify) + return s + fill; + else if (zeroFill && s.startsWith("-")) + return "-" + fill + s.substring(1); + else + return fill + s; + } + + // Internal routines. + + private static String sigFigFix(String s, int sigFigs) { + // First dissect the floating-point number string into sign, + // integer part, fraction part, and exponent. + String sign; + String unsigned; + + if (s.startsWith("-") || s.startsWith("+")) { + sign = s.substring(0, 1); + unsigned = s.substring(1); + } else { + sign = ""; + unsigned = s; + } + String mantissa; + String exponent; + int eInd = unsigned.indexOf('e'); + + if (eInd == -1) { + mantissa = unsigned; + exponent = ""; + } else { + mantissa = unsigned.substring(0, eInd); + exponent = unsigned.substring(eInd); + } + StringBuffer number, fraction; + int dotInd = mantissa.indexOf('.'); + + if (dotInd == -1) { + number = new StringBuffer(mantissa); + fraction = new StringBuffer(""); + } else { + number = new StringBuffer(mantissa.substring(0, dotInd)); + fraction = new StringBuffer(mantissa.substring(dotInd + 1)); + } + + int numFigs = number.length(); + int fracFigs = fraction.length(); + + if( ( numFigs == 0 || number.toString().equals( "0" ) ) && + fracFigs > 0 ) { + // Don't count leading zeros in the fraction. + numFigs = 0; + for (int i = 0; i < fraction.length(); ++i) { + if (fraction.charAt(i) != '0') + break; + --fracFigs; + } + } + int mantFigs = numFigs + fracFigs; + + if (sigFigs > mantFigs) { + // We want more figures; just append zeros to the fraction. + for (int i = mantFigs; i < sigFigs; ++i) + fraction.append('0'); + } else if (sigFigs < mantFigs && sigFigs >= numFigs) { + // Want fewer figures in the fraction; chop. + fraction.setLength( + fraction.length() - (fracFigs - (sigFigs - numFigs))); + // Round? + } else if (sigFigs < numFigs) { + // Want fewer figures in the number; turn them to zeros. + fraction.setLength(0); // should already be zero, but make sure + for (int i = sigFigs; i < numFigs; ++i) + number.setCharAt(i, '0'); + // Round? + } + // Else sigFigs == mantFigs, which is fine. + + if (fraction.length() == 0) + return sign + number + exponent; + else + return sign + number + "." + fraction + exponent; + } + + /// Improved version of Double.toString(), returns more decimal places. + // <P> + // The JDK 1.0.2 version of Double.toString() returns only six decimal + // places on some systems. In JDK 1.1 full precision is returned on + // all platforms. + // @deprecated + // @see java.lang.Double.toString + public static String doubleToString(double d) { + // Handle special numbers first, to avoid complications. + if (Double.isNaN(d)) + return "NaN"; + if (d == Double.NEGATIVE_INFINITY) + return "-Inf"; + if (d == Double.POSITIVE_INFINITY) + return "Inf"; + + // Grab the sign, and then make the number positive for simplicity. + boolean negative = false; + + if (d < 0.0D) { + negative = true; + d = -d; + } + + // Get the native version of the unsigned value, as a template. + String unsStr = Double.toString(d); + + // Dissect out the exponent. + String mantStr, expStr; + int exp; + int eInd = unsStr.indexOf('e'); + + if (eInd == -1) { + mantStr = unsStr; + expStr = ""; + exp = 0; + } else { + mantStr = unsStr.substring(0, eInd); + expStr = unsStr.substring(eInd + 1); + if (expStr.startsWith("+")) + exp = Integer.parseInt(expStr.substring(1)); + else + exp = Integer.parseInt(expStr); + } + + // Dissect out the number part. + String numStr; + int dotInd = mantStr.indexOf('.'); + + if (dotInd == -1) + numStr = mantStr; + else + numStr = mantStr.substring(0, dotInd); + long num; + + if (numStr.length() == 0) + num = 0; + else + num = Integer.parseInt(numStr); + + // Build the new mantissa. + StringBuffer newMantBuf = new StringBuffer(numStr + "."); + double p = Math.pow(10, exp); + double frac = d - num * p; + String digits = "0123456789"; + int nDigits = 16 - numStr.length(); // about 16 digits in a double + + for (int i = 0; i < nDigits; ++i) { + p /= 10.0D; + int dig = (int) (frac / p); + + if (dig < 0) dig = 0; + if (dig > 9) dig = 9; + newMantBuf.append(digits.charAt(dig)); + frac -= dig * p; + } + + if ((int) (frac / p + 0.5D) == 1) { + // Round up. + boolean roundMore = true; + + for (int i = newMantBuf.length() - 1; i >= 0; --i) { + int dig = digits.indexOf(newMantBuf.charAt(i)); + + if (dig == -1) + continue; + ++dig; + if (dig == 10) { + newMantBuf.setCharAt(i, '0'); + continue; + } + newMantBuf.setCharAt(i, digits.charAt(dig)); + roundMore = false; + break; + } + if (roundMore) { + // If this happens, we need to prepend a 1. But I haven't + // found a test case yet, so I'm leaving it out for now. + // But if you get this message, please let me know! + newMantBuf.append("ROUNDMORE"); + } + } + + // Chop any trailing zeros. + int len = newMantBuf.length(); + + while (newMantBuf.charAt(len - 1) == '0') + newMantBuf.setLength(--len); + // And chop a trailing dot, if any. + if (newMantBuf.charAt(len - 1) == '.') + newMantBuf.setLength(--len); + + // Done. + return (negative ? "-" : "") + + newMantBuf + + (expStr.length() != 0 ? ("e" + expStr) : ""); + } + + /****************************************************************************** + /// Test program. + public static void main( String[] args ) + { + System.out.println( "Starting tests." ); + show( Fmt.fmt( "Hello there." ) ); + show( Fmt.fmt( 123 ) ); + show( Fmt.fmt( 123, 10 ) ); + show( Fmt.fmt( 123, 10, Fmt.ZF ) ); + show( Fmt.fmt( 123, 10, Fmt.LJ ) ); + show( Fmt.fmt( -123 ) ); + show( Fmt.fmt( -123, 10 ) ); + show( Fmt.fmt( -123, 10, Fmt.ZF ) ); + show( Fmt.fmt( -123, 10, Fmt.LJ ) ); + show( Fmt.fmt( (byte) 0xbe, 22, Fmt.OC ) ); + show( Fmt.fmt( (short) 0xbabe, 22, Fmt.OC ) ); + show( Fmt.fmt( 0xcafebabe, 22, Fmt.OC ) ); + show( Fmt.fmt( 0xdeadbeefcafebabeL, 22, Fmt.OC ) ); + show( Fmt.fmt( 0x8000000000000000L, 22, Fmt.OC ) ); + show( Fmt.fmt( (byte) 0xbe, 16, Fmt.HX ) ); + show( Fmt.fmt( (short) 0xbabe, 16, Fmt.HX ) ); + show( Fmt.fmt( 0xcafebabe, 16, Fmt.HX ) ); + show( Fmt.fmt( 0xdeadbeefcafebabeL, 16, Fmt.HX ) ); + show( Fmt.fmt( 0x8000000000000000L, 16, Fmt.HX ) ); + show( Fmt.fmt( 'c' ) ); + show( Fmt.fmt( new java.util.Date() ) ); + show( Fmt.fmt( 123.456F ) ); + show( Fmt.fmt( 123456000000000000.0F ) ); + show( Fmt.fmt( 123.456F, 0, 8 ) ); + show( Fmt.fmt( 123.456F, 0, 7 ) ); + show( Fmt.fmt( 123.456F, 0, 6 ) ); + show( Fmt.fmt( 123.456F, 0, 5 ) ); + show( Fmt.fmt( 123.456F, 0, 4 ) ); + show( Fmt.fmt( 123.456F, 0, 3 ) ); + show( Fmt.fmt( 123.456F, 0, 2 ) ); + show( Fmt.fmt( 123.456F, 0, 1 ) ); + show( Fmt.fmt( 123456000000000000.0F, 0, 4 ) ); + show( Fmt.fmt( -123.456F, 0, 4 ) ); + show( Fmt.fmt( -123456000000000000.0F, 0, 4 ) ); + show( Fmt.fmt( 123.0F ) ); + show( Fmt.fmt( 123.0D ) ); + show( Fmt.fmt( 1.234567890123456789F ) ); + show( Fmt.fmt( 1.234567890123456789D ) ); + show( Fmt.fmt( 1234567890123456789F ) ); + show( Fmt.fmt( 1234567890123456789D ) ); + show( Fmt.fmt( 0.000000000000000000001234567890123456789F ) ); + show( Fmt.fmt( 0.000000000000000000001234567890123456789D ) ); + show( Fmt.fmt( 12300.0F ) ); + show( Fmt.fmt( 12300.0D ) ); + show( Fmt.fmt( 123000.0F ) ); + show( Fmt.fmt( 123000.0D ) ); + show( Fmt.fmt( 1230000.0F ) ); + show( Fmt.fmt( 1230000.0D ) ); + show( Fmt.fmt( 12300000.0F ) ); + show( Fmt.fmt( 12300000.0D ) ); + show( Fmt.fmt( Float.NaN ) ); + show( Fmt.fmt( Float.POSITIVE_INFINITY ) ); + show( Fmt.fmt( Float.NEGATIVE_INFINITY ) ); + show( Fmt.fmt( Double.NaN ) ); + show( Fmt.fmt( Double.POSITIVE_INFINITY ) ); + show( Fmt.fmt( Double.NEGATIVE_INFINITY ) ); + show( Fmt.fmt( 1.0F / 8.0F ) ); + show( Fmt.fmt( 1.0D / 8.0D ) ); + System.out.println( "Done with tests." ); + } + + private static void show( String str ) + { + System.out.println( "#" + str + "#" ); + } + ******************************************************************************/ + +} diff --git a/pki/base/util/src/com/netscape/cmsutil/util/HMACDigest.java b/pki/base/util/src/com/netscape/cmsutil/util/HMACDigest.java new file mode 100644 index 000000000..adf7d00c7 --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/util/HMACDigest.java @@ -0,0 +1,202 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.util; + + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + + +/** + * This class implements the HMAC algorithm specified in RFC 2104 using + * any MessageDigest. + * + * @author mikep + * @version $Revision: 14564 $, $Date: 2007-05-01 10:40:13 -0700 (Tue, 01 May 2007) $ + * @see java.security.MessageDigest + */ +public class HMACDigest implements Cloneable { + public static final int PAD_BYTES = 64; + public static final int IPAD = 0x36; + public static final int OPAD = 0x5C; + + /** + * inner padding - key XORd with ipad + */ + private byte[] mKeyIpad = new byte[PAD_BYTES]; + + /** + * outer padding - key XORd with opad + */ + private byte[] mKeyOpad = new byte[PAD_BYTES]; + + /** + * The real MessageDigest + */ + private MessageDigest mMD = null; + + /** + * Creates an HMACDigest + * + * @param md The MessageDigest to be used for the HMAC calculation. It + * must be clonable. + */ + public HMACDigest(MessageDigest md) { + mMD = md; + } + + /** + * Creates an HMACDigest and initializes the HMAC function + * with the given key. + * + * @param md The MessageDigest to be used for the HMAC calculation. It + * must be clonable. + * @param key The key value to be used in the HMAC calculation + */ + public HMACDigest(MessageDigest md, byte[] key) { + this(md); + init(key); + } + + /** + * Return the MessageDigest used for this HMAC + */ + public MessageDigest getMessageDigest() { + return mMD; + } + + /** + * Initialize the HMAC function + * + * The HMAC transform looks like: + * + * hash(key XOR opad, hash(key XOR ipad, text)) + * + * where key is an n byte key + * ipad is the byte 0x36 repeated 64 times + * opad is the byte 0x5c repeated 64 times + * and text is the data being protected + * + * This routine must be called after every reset. + * + * @param key The password used to protect the hash value + */ + public void init(byte[] key) { + int i; + + reset(); + + // If the key is longer than 64 bytes, just hash it down + if (key.length > 64) { + key = mMD.digest(key); + mMD.reset(); // Redundant? + } + + // Copy the key. Truncate if key is too long + for (i = 0; i < key.length && i < PAD_BYTES; i++) { + mKeyIpad[i] = key[i]; + mKeyOpad[i] = key[i]; + } + + // XOR in the pads + for (i = 0; i < PAD_BYTES; i++) { + mKeyIpad[i] ^= IPAD; + mKeyOpad[i] ^= OPAD; + } + + mMD.update(mKeyIpad); + + // Hmmm, we really shouldn't key Opad around in memory for so + // long, but it would just force the user to key their key around + // until digest() time. Oh well, at least clear the key and Ipad + for (i = 0; i < PAD_BYTES; i++) { + mKeyIpad[i] = 0; + } + for (i = 0; i < key.length; i++) { + key[0] = 0; + } + } + + /** + * Updates the digest using the specified array of bytes. + * + * @param input the array of bytes. + */ + public void update(byte[] input) { + mMD.update(input); + } + + /** + * Completes the HMAC computation with the outer pad + * The digest is reset after this call is made. + * + * @return the array of bytes for the resulting hash value. + */ + public byte[] digest() { + byte[] finalDigest; + byte[] innerDigest = mMD.digest(); + + mMD.reset(); // Redundant? + mMD.update(mKeyOpad); + mMD.update(innerDigest); + finalDigest = mMD.digest(); + reset(); // Clear pad arrays + return finalDigest; + } + + /** + * Resets the digest for further use. + */ + public void reset() { + int i; + + mMD.reset(); + + // Clear out the pads + for (i = 0; i < PAD_BYTES; i++) { + mKeyIpad[i] = 0; + mKeyOpad[i] = 0; + } + } + + /** + * Clone the HMACDigest + * + * @return a clone if the implementation is cloneable. + * @exception CloneNotSupportedException if this is called on a + * MessageDigest implementation that does not support + * <code>Cloneable</code>. + */ + public Object clone() throws CloneNotSupportedException { + int i; + + HMACDigest hd = (HMACDigest) super.clone(); + + hd.mKeyOpad = new byte[PAD_BYTES]; + hd.mKeyIpad = new byte[PAD_BYTES]; + + for (i = 0; i < PAD_BYTES; i++) { + hd.mKeyOpad[i] = mKeyOpad[i]; + hd.mKeyIpad[i] = mKeyIpad[i]; + } + + hd.mMD = (MessageDigest) mMD.clone(); + return hd; + } + +} diff --git a/pki/base/util/src/com/netscape/cmsutil/util/Utils.java b/pki/base/util/src/com/netscape/cmsutil/util/Utils.java new file mode 100644 index 000000000..9d0fb05ac --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/util/Utils.java @@ -0,0 +1,251 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.util; + + +import java.net.*; +import java.io.*; +import java.util.*; +import java.text.*; + +public class Utils { + /** + * Checks if this is NT. + */ + public static boolean isNT() { + return ((File.separator).equals("\\")); + } + + public static boolean exec(String cmd) { + try { + String cmds[] = null; + if (isNT()) { + // NT + cmds = new String[3]; + cmds[0] = "cmd"; + cmds[1] = "/c"; + cmds[2] = cmd; + } else { + // UNIX + cmds = new String[3]; + cmds[0] = "/bin/sh"; + cmds[1] = "-c"; + cmds[2] = cmd; + } + Process process = Runtime.getRuntime().exec(cmds); + process.waitFor(); + BufferedReader pOut = null; + String l = null; + + if (process.exitValue() == 0) { + /** + pOut = new BufferedReader( + new InputStreamReader(process.getInputStream())); + while ((l = pOut.readLine()) != null) { + System.out.println(l); + } + **/ + return true; + } else { + /** + pOut = new BufferedReader( + new InputStreamReader(process.getErrorStream())); + l = null; + while ((l = pOut.readLine()) != null) { + System.out.println(l); + } + **/ + return false; + } + } catch (Exception e) { + return false; + } + } + + public static String SpecialURLDecode(String s) { + if (s == null) + return null; + ByteArrayOutputStream out = new ByteArrayOutputStream(s.length()); + + for (int i = 0; i < s.length(); i++) { + int c = (int) s.charAt(i); + + if (c == '+') { + out.write(' '); + } else if (c == '#') { + int c1 = Character.digit(s.charAt(++i), 16); + int c2 = Character.digit(s.charAt(++i), 16); + + out.write((char) (c1 * 16 + c2)); + } else { + out.write(c); + } + } // end for + return out.toString(); + } + + public static byte[] SpecialDecode(String s) { + if (s == null) + return null; + ByteArrayOutputStream out = new ByteArrayOutputStream(s.length()); + + for (int i = 0; i < s.length(); i++) { + int c = (int) s.charAt(i); + + if (c == '+') { + out.write(' '); + } else if (c == '#') { + int c1 = Character.digit(s.charAt(++i), 16); + int c2 = Character.digit(s.charAt(++i), 16); + + out.write((char) (c1 * 16 + c2)); + } else { + out.write(c); + } + } // end for + return out.toByteArray(); + } + + public static String SpecialEncode(byte data[]) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < data.length; i++) { + sb.append("%"); + if ((data[i] & 0xff) < 16) { + sb.append("0"); + } + sb.append(Integer.toHexString((data[i] & 0xff))); + } + return sb.toString().toUpperCase(); + } + + public static void checkHost(String hostname) throws UnknownHostException { + InetAddress addr = InetAddress.getByName(hostname); + } + + public static void copy(String orig, String dest) { + try { + BufferedReader in = new BufferedReader(new FileReader(orig)); + PrintWriter out = new PrintWriter( + new BufferedWriter(new FileWriter(dest))); + String line = ""; + while (in.ready()) { + line = in.readLine(); + if (line != null) + out.println(line); + } + in.close(); + out.close(); + } catch (Exception ee) { + } + } + + public static void copyStream(InputStream in, OutputStream out) throws IOException { + byte[] buf = new byte[4096]; + int len; + + while ((len = in.read(buf)) != -1) { + out.write(buf, 0, len); + } + } + + public static void copyStream(BufferedReader in, OutputStreamWriter out) throws IOException { + char[] buf = new char[4096]; + int len; + + while ((len = in.read(buf)) != -1) { + out.write(buf, 0, len); + } + } + + /// Sorts an array of Strings. + // Java currently has no general sort function. Sorting Strings is + // common enough that it's worth making a special case. + public static void sortStrings(String[] strings) { + // Just does a bubblesort. + for (int i = 0; i < strings.length - 1; ++i) { + for (int j = i + 1; j < strings.length; ++j) { + if (strings[i].compareTo(strings[j]) > 0) { + String t = strings[i]; + + strings[i] = strings[j]; + strings[j] = t; + } + } + } + } + + /// Returns a date string formatted in Unix ls style - if it's within + // six months of now, Mmm dd hh:ss, else Mmm dd yyyy. + public static String lsDateStr(Date date) { + long dateTime = date.getTime(); + + if (dateTime == -1L) + return "------------"; + long nowTime = System.currentTimeMillis(); + SimpleDateFormat formatter = new SimpleDateFormat(); + + if (Math.abs(nowTime - dateTime) < 183L * 24L * 60L * 60L * 1000L) + formatter.applyPattern("MMM dd hh:ss"); + else + formatter.applyPattern("MMM dd yyyy"); + return formatter.format(date); + } + + /** + * compares contents two byte arrays returning true if exactly same. + */ + static public boolean byteArraysAreEqual(byte[] a, byte[] b) { + if (a.length != b.length) + return false; + for (int i = 0; i < a.length; i++) { + if (a[i] != b[i]) + return false; + } + return true; + } + + /** + * strips out double quotes around String parameter + * @param s the string potentially bracketed with double quotes + * @return string stripped of surrounding double quotes + */ + public static String stripQuotes(String s) { + if (s == null) { + return s; + } + + if ((s.startsWith("\"")) && (s.endsWith("\""))) { + return (s.substring(1, (s.length() - 1))); + } + + return s; + } + + /** + * returns an array of strings from a vector of Strings + * there'll be trouble if the Vector contains something other + * than just Strings + */ + public static String[] getStringArrayFromVector(Vector v) { + String s[] = new String[v.size()]; + + v.copyInto(s); + return s; + } + +} diff --git a/pki/base/util/src/com/netscape/cmsutil/xml/XMLObject.java b/pki/base/util/src/com/netscape/cmsutil/xml/XMLObject.java new file mode 100644 index 000000000..95cf8541c --- /dev/null +++ b/pki/base/util/src/com/netscape/cmsutil/xml/XMLObject.java @@ -0,0 +1,161 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cmsutil.xml; +import org.w3c.dom.*; +import org.xml.sax.*; +import org.apache.xerces.parsers.DOMParser; +import org.apache.xerces.dom.*; +import javax.xml.parsers.*; +import javax.xml.transform.*; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.*; +import java.util.*; + +public class XMLObject +{ + private Document mDoc = null; + + public XMLObject() throws ParserConfigurationException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + mDoc = docBuilder.newDocument(); + } + + public XMLObject(InputStream s) + throws SAXException, IOException, ParserConfigurationException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + mDoc = docBuilder.parse(s); + } + + public XMLObject(File f) + throws SAXException, IOException, ParserConfigurationException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + mDoc = docBuilder.parse(f); + } + + public Document getDocument() { + return mDoc; + } + + /** + * Each document should have 1 root only. This method should be called once. + */ + public Node createRoot(String name) { + Element root = mDoc.createElement(name); + mDoc.appendChild(root); + return (Node)root; + } + + public Node getRoot() { + return mDoc.getFirstChild(); + } + + /** + * If you have duplicate containers, then this method will return the + * first container in the list. + */ + public Node getContainer(String tagname) { + NodeList list = mDoc.getElementsByTagName(tagname); + if (list.getLength() > 0) + return list.item(0); + return null; + } + + public Node createContainer(Node containerParent, String containerName) { + Element node = mDoc.createElement(containerName); + containerParent.appendChild(node); + return (Node)node; + } + + public void addItemToContainer(Node container, String tagname, String value) { + Element node = mDoc.createElement(tagname); + Text text = mDoc.createTextNode(value); + node.appendChild(text); + container.appendChild(node); + } + + public String getValue(String tagname) { + Node n = getContainer(tagname); + + if (n != null) { + NodeList c = n.getChildNodes(); + if (c.getLength() == 0) + return null; + Node item = c.item(0); + return item.getNodeValue(); + } + + return null; + } + + public Vector getAllValues(String tagname) { + Vector v = new Vector(); + NodeList nodes = mDoc.getElementsByTagName(tagname); + for (int i=0; i<nodes.getLength(); i++) { + Node n = nodes.item(i); + NodeList c = n.getChildNodes(); + if (c.getLength() > 0) { + Node nn = c.item(0); + if (nn.getNodeType() == Node.TEXT_NODE) + v.addElement(nn.getNodeValue()); + } + } + return v; + } + + public Vector getValuesFromContainer(Node container, String tagname) { + Vector v = new Vector(); + NodeList c = container.getChildNodes(); + int len = c.getLength(); + for (int i=0; i<len; i++) { + Node subchild = c.item(i); + if (subchild.getNodeName().equals(tagname)) { + NodeList grandchildren = subchild.getChildNodes(); + if (grandchildren.getLength() > 0) { + Node grandchild = grandchildren.item(0); + if (grandchild.getNodeType() == Node.TEXT_NODE) + v.addElement(grandchild.getNodeValue()); + } + } + } + + return v; + } + + public byte[] toByteArray() throws TransformerConfigurationException, TransformerException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + TransformerFactory tranFactory = TransformerFactory.newInstance(); + Transformer aTransformer = tranFactory.newTransformer(); + Source src = new DOMSource(mDoc); + Result dest = new StreamResult(bos); + aTransformer.transform(src, dest); + return bos.toByteArray(); + } + + public void output(OutputStream os) + throws TransformerConfigurationException, TransformerException { + TransformerFactory tranFactory = TransformerFactory.newInstance(); + Transformer aTransformer = tranFactory.newTransformer(); + Source src = new DOMSource(mDoc); + Result dest = new StreamResult(os); + aTransformer.transform(src, dest); + } +} |