diff options
Diffstat (limited to 'base/util/src/com')
104 files changed, 10568 insertions, 0 deletions
diff --git a/base/util/src/com/netscape/cmsutil/crypto/CryptoUtil.java b/base/util/src/com/netscape/cmsutil/crypto/CryptoUtil.java new file mode 100644 index 000000000..bf8a9cfc1 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/crypto/CryptoUtil.java @@ -0,0 +1,1292 @@ +// --- 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.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.CharConversionException; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.math.BigInteger; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.KeyPair; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.PublicKey; +import java.security.SignatureException; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateException; +import java.security.interfaces.DSAParams; +import java.security.interfaces.DSAPublicKey; +import java.security.interfaces.RSAPublicKey; +import java.util.Date; +import java.util.Enumeration; +import java.util.StringTokenizer; +import java.util.Vector; + +import netscape.security.pkcs.PKCS10; +import netscape.security.pkcs.PKCS7; +import netscape.security.util.BigInt; +import netscape.security.util.DerInputStream; +import netscape.security.util.DerOutputStream; +import netscape.security.util.DerValue; +import netscape.security.util.ObjectIdentifier; +import netscape.security.x509.AlgorithmId; +import netscape.security.x509.CertificateAlgorithmId; +import netscape.security.x509.CertificateChain; +import netscape.security.x509.CertificateExtensions; +import netscape.security.x509.CertificateIssuerName; +import netscape.security.x509.CertificateSerialNumber; +import netscape.security.x509.CertificateSubjectName; +import netscape.security.x509.CertificateValidity; +import netscape.security.x509.CertificateVersion; +import netscape.security.x509.CertificateX509Key; +import netscape.security.x509.X500Name; +import netscape.security.x509.X500Signer; +import netscape.security.x509.X509CertImpl; +import netscape.security.x509.X509CertInfo; +import netscape.security.x509.X509Key; + +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.CryptoManager.NotInitializedException; +import org.mozilla.jss.NoSuchTokenException; +import org.mozilla.jss.asn1.ASN1Util; +import org.mozilla.jss.asn1.BIT_STRING; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.OBJECT_IDENTIFIER; +import org.mozilla.jss.asn1.OCTET_STRING; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.crypto.Algorithm; +import org.mozilla.jss.crypto.BadPaddingException; +import org.mozilla.jss.crypto.Cipher; +import org.mozilla.jss.crypto.CryptoStore; +import org.mozilla.jss.crypto.CryptoToken; +import org.mozilla.jss.crypto.DigestAlgorithm; +import org.mozilla.jss.crypto.EncryptionAlgorithm; +import org.mozilla.jss.crypto.IVParameterSpec; +import org.mozilla.jss.crypto.IllegalBlockSizeException; +import org.mozilla.jss.crypto.InternalCertificate; +import org.mozilla.jss.crypto.InvalidKeyFormatException; +import org.mozilla.jss.crypto.KeyGenAlgorithm; +import org.mozilla.jss.crypto.KeyGenerator; +import org.mozilla.jss.crypto.KeyPairAlgorithm; +import org.mozilla.jss.crypto.KeyPairGenerator; +import org.mozilla.jss.crypto.KeyWrapAlgorithm; +import org.mozilla.jss.crypto.KeyWrapper; +import org.mozilla.jss.crypto.NoSuchItemOnTokenException; +import org.mozilla.jss.crypto.ObjectNotFoundException; +import org.mozilla.jss.crypto.PBEAlgorithm; +import org.mozilla.jss.crypto.PrivateKey; +import org.mozilla.jss.crypto.Signature; +import org.mozilla.jss.crypto.SignatureAlgorithm; +import org.mozilla.jss.crypto.SymmetricKey; +import org.mozilla.jss.crypto.TokenException; +import org.mozilla.jss.crypto.X509Certificate; +import org.mozilla.jss.pkcs11.PK11ECPublicKey; +import org.mozilla.jss.pkcs12.PasswordConverter; +import org.mozilla.jss.pkcs7.EncryptedContentInfo; +import org.mozilla.jss.pkix.crmf.CertReqMsg; +import org.mozilla.jss.pkix.crmf.CertRequest; +import org.mozilla.jss.pkix.crmf.CertTemplate; +import org.mozilla.jss.pkix.crmf.EncryptedKey; +import org.mozilla.jss.pkix.crmf.EncryptedValue; +import org.mozilla.jss.pkix.crmf.PKIArchiveOptions; +import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier; +import org.mozilla.jss.pkix.primitive.Name; +import org.mozilla.jss.pkix.primitive.SubjectPublicKeyInfo; +import org.mozilla.jss.util.Base64OutputStream; +import org.mozilla.jss.util.Password; + +import com.netscape.cmsutil.util.Cert; +import com.netscape.cmsutil.util.Utils; + +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()) + + Utils.base64encode(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 { + return generateECCKeyPair(token, keysize, null, null); + } + + public static KeyPair generateECCKeyPair(String token, int keysize, + org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_ops, + org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_mask) + throws CryptoManager.NotInitializedException, + NoSuchTokenException, + NoSuchAlgorithmException, + TokenException { + CryptoToken t = getTokenByName(token); + + KeyPairAlgorithm alg = KeyPairAlgorithm.EC; + KeyPairGenerator g = t.getKeyPairGenerator(alg); + + g.setKeyPairUsages(usage_ops, usage_mask); + g.initialize(keysize); + + KeyPair pair = g.genKeyPair(); + + return pair; + } + + /** + * Generates an ecc key pair by curve name + */ + public static KeyPair generateECCKeyPair(String token, String curveName) + throws CryptoManager.NotInitializedException, + NoSuchTokenException, + NoSuchAlgorithmException, + TokenException { + return generateECCKeyPair(token, curveName, null, null); + } + + public static KeyPair generateECCKeyPair(CryptoToken token, String curveName) + throws CryptoManager.NotInitializedException, + NoSuchTokenException, + NoSuchAlgorithmException, + TokenException { + return generateECCKeyPair(token, curveName, null, null); + } + + public static KeyPair generateECCKeyPair(String token, String curveName, + org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_ops, + org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_mask) + throws CryptoManager.NotInitializedException, + NoSuchTokenException, + NoSuchAlgorithmException, + TokenException { + CryptoToken t = getTokenByName(token); + return generateECCKeyPair(t, curveName, usage_ops, usage_mask); + } + + public static KeyPair generateECCKeyPair(CryptoToken token, String curveName, + org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_ops, + org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage[] usage_mask) + throws CryptoManager.NotInitializedException, + NoSuchTokenException, + NoSuchAlgorithmException, + TokenException { + KeyPairAlgorithm alg = KeyPairAlgorithm.EC; + KeyPairGenerator g = token.getKeyPairGenerator(alg); + + g.setKeyPairUsages(usage_ops, usage_mask); + + System.out.println("CryptoUtil: generateECCKeyPair: curve = " + curveName); + int curveCode = 0; + try { + curveCode = g.getCurveCodeByName(curveName); + } catch (Exception e) { + System.out.println("CryptoUtil: generateECCKeyPair: " + e.toString()); + throw new NoSuchAlgorithmException(); + } + g.initialize(curveCode); + + System.out.println("CryptoUtil: generateECCKeyPair: after KeyPairGenerator initialize with:" + curveName); + 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); + byte[] d = Utils.base64decode(s); + + return d; + } + + /* + * formats a cert request + */ + public static String reqFormat(String content) { + String result = CERTREQ_BEGIN_HEADING + "\n"; + + 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(); + } + + public static String getPKCS10FromKey(String dn, + byte modulus[], byte exponent[], byte prikdata[], String alg) + 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, alg); + 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 ""; + } + String result = CERT_BEGIN_HEADING + "\n"; + + 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 if (pubk instanceof PK11ECPublicKey) { + byte encoded[] = pubk.getEncoded(); + xKey = CryptoUtil.getPublicX509ECCKey(encoded); + } 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 { + // set default; use the other call with "alg" to set algorithm + String alg = "SHA256withRSA"; + try { + return createX509CertInfo(x509key, serialno, issuername, subjname, notBefore, notAfter, alg); + } catch (NoSuchAlgorithmException ex) { + // for those that calls the old call without alg + throw new CertificateException("createX509CertInfo old call should not be here"); + } + } + + public static X509CertInfo createX509CertInfo(X509Key x509key, + int serialno, String issuername, String subjname, + Date notBefore, Date notAfter, String alg) + throws IOException, + CertificateException, + InvalidKeyException, + NoSuchAlgorithmException { + 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)); + info.set(X509CertInfo.ALGORITHM_ID, new + CertificateAlgorithmId(AlgorithmId.get(alg))); + 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 { + // set default; use the other call with "alg" to specify algorithm + String alg = "SHA256withEC"; + return signECCCert(privateKey, certInfo, alg); + } + + public static X509CertImpl signECCCert(PrivateKey privateKey, + X509CertInfo certInfo, String alg) + throws NoSuchTokenException, + CryptoManager.NotInitializedException, + NoSuchAlgorithmException, + NoSuchTokenException, + TokenException, + InvalidKeyException, + SignatureException, + IOException, + CertificateException { + return signCert(privateKey, certInfo, + Cert.mapAlgorithmToJss(alg)); + } + + /** + * Signs certificate. + */ + public static X509CertImpl signCert(PrivateKey privateKey, + X509CertInfo certInfo, String alg) + throws NoSuchTokenException, + CryptoManager.NotInitializedException, + NoSuchAlgorithmException, + NoSuchTokenException, + TokenException, + InvalidKeyException, + SignatureException, + IOException, + CertificateException { + return signCert(privateKey, certInfo, + Cert.mapAlgorithmToJss(alg)); + } + + 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 { + // give default + String alg = "SHA256withRSA"; + if (isECCKey(pubk)) { + alg = "SHA256withEC"; + } + return createCertificationRequest(subjectName, pubk, prik, alg); + } + + public static PKCS10 createCertificationRequest(String subjectName, + X509Key pubk, PrivateKey prik, String alg) + throws NoSuchAlgorithmException, NoSuchProviderException, + InvalidKeyException, IOException, CertificateException, + SignatureException { + X509Key key = pubk; + 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 { + String alg; + PublicKey pubk = keyPair.getPublic(); + X509Key key = convertPublicKeyToX509Key(pubk); + if (pubk instanceof RSAPublicKey) { + alg = "SHA256withRSA"; + } else if (isECCKey(key)) { + alg = "SHA256withEC"; + } else { + // Assert.assert(pubk instanceof DSAPublicKey); + alg = "DSA"; + } + return createCertificationRequest(subjectName, keyPair, alg); + } + + public static PKCS10 createCertificationRequest(String subjectName, + KeyPair keyPair, String alg) + throws NoSuchAlgorithmException, NoSuchProviderException, + InvalidKeyException, IOException, CertificateException, + SignatureException { + PublicKey pubk = keyPair.getPublic(); + X509Key key = convertPublicKeyToX509Key(pubk); + + 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(); + @SuppressWarnings("unchecked") + Enumeration<CryptoToken> enums = cm.getAllTokens(); + + while (enums.hasMoreElements()) { + CryptoToken token = enums.nextElement(); + 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<X509CertImpl> certs = new Vector<X509CertImpl>(); + CryptoManager cm = CryptoManager.getInstance(); + @SuppressWarnings("unchecked") + Enumeration<CryptoToken> enums = cm.getAllTokens(); + + while (enums.hasMoreElements()) { + CryptoToken token = (CryptoToken) enums.nextElement(); + + CryptoStore store = token.getCryptoStore(); + org.mozilla.jss.crypto.X509Certificate list[] = store.getCertificates(); + + for (int i = 0; i < list.length; i++) { + try { + @SuppressWarnings("unused") + PrivateKey key = cm.findPrivKeyByCert(list[i]); // check for errors + 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 { + + 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; + } + + @SuppressWarnings("deprecation") + public static String unwrapUsingPassphrase(String wrappedRecoveredKey, String recoveryPassphrase) + throws IOException, InvalidBERException, InvalidKeyException, IllegalStateException, + NoSuchAlgorithmException, InvalidAlgorithmParameterException, NotInitializedException, TokenException, + IllegalBlockSizeException, BadPaddingException { + EncryptedContentInfo cInfo = null; + String unwrappedData = null; + + //We have to do this to get the decoding to work. + @SuppressWarnings("unused") + PBEAlgorithm pbeAlg = PBEAlgorithm.PBE_SHA1_DES3_CBC; + + Password pass = new Password(recoveryPassphrase.toCharArray()); + PasswordConverter passConverter = new + PasswordConverter(); + + byte[] encoded = Utils.base64decode(wrappedRecoveredKey); + + ByteArrayInputStream inStream = new ByteArrayInputStream(encoded); + cInfo = (EncryptedContentInfo) + new EncryptedContentInfo.Template().decode(inStream); + + byte[] decodedData = cInfo.decrypt(pass, passConverter); + + unwrappedData = Utils.base64encode(decodedData); + + return unwrappedData; + } + + @SuppressWarnings("deprecation") + public static String unwrapUsingSymmetricKey(CryptoToken token, IVParameterSpec IV, byte[] wrappedRecoveredKey, + SymmetricKey recoveryKey, EncryptionAlgorithm alg) throws NoSuchAlgorithmException, TokenException, + BadPaddingException, + IllegalBlockSizeException, InvalidKeyException, InvalidAlgorithmParameterException { + + Cipher decryptor = token.getCipherContext(alg); + decryptor.initDecrypt(recoveryKey, IV); + byte[] unwrappedData = decryptor.doFinal(wrappedRecoveredKey); + String unwrappedS = Utils.base64encode(unwrappedData); + + return unwrappedS; + } + + @SuppressWarnings("deprecation") + public static byte[] wrapPassphrase(CryptoToken token, String passphrase, IVParameterSpec IV, SymmetricKey sk, + EncryptionAlgorithm alg) + throws NoSuchAlgorithmException, TokenException, InvalidKeyException, + InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException { + byte[] wrappedPassphrase = null; + Cipher encryptor = null; + + encryptor = token.getCipherContext(alg); + + if (encryptor != null) { + encryptor.initEncrypt(sk, IV); + wrappedPassphrase = encryptor.doFinal(passphrase.getBytes("UTF-8")); + } else { + throw new IOException("Failed to create cipher"); + } + + return wrappedPassphrase; + } + + @SuppressWarnings("deprecation") + public static byte[] wrapSymmetricKey(CryptoManager manager, CryptoToken token, String transportCert, + SymmetricKey sk) throws CertificateEncodingException, TokenException, NoSuchAlgorithmException, + InvalidKeyException, InvalidAlgorithmParameterException { + byte transport[] = Utils.base64decode(transportCert); + X509Certificate tcert = manager.importCACertPackage(transport); + KeyWrapper rsaWrap = token.getKeyWrapper(KeyWrapAlgorithm.RSA); + rsaWrap.initWrap(tcert.getPublicKey(), null); + byte session_data[] = rsaWrap.wrap(sk); + return session_data; + } + + @SuppressWarnings("deprecation") + public static byte[] createPKIArchiveOptions(CryptoManager manager, CryptoToken token, String transportCert, + SymmetricKey vek, String passphrase, KeyGenAlgorithm keyGenAlg, IVParameterSpec IV) throws TokenException, + CharConversionException, + NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException, + CertificateEncodingException, IOException, IllegalStateException, IllegalBlockSizeException, + BadPaddingException, InvalidBERException { + byte[] key_data = null; + + //generate session key + SymmetricKey sk = CryptoUtil.generateKey(token, keyGenAlg); + + if (passphrase != null) { + key_data = wrapPassphrase(token, passphrase, IV, sk, EncryptionAlgorithm.DES3_CBC_PAD); + } else { + // wrap payload using session key + KeyWrapper wrapper1 = token.getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD); + wrapper1.initWrap(sk, IV); + key_data = wrapper1.wrap(vek); + } + + // wrap session key using transport key + byte[] session_data = wrapSymmetricKey(manager, token, transportCert, sk); + + // create PKIArchiveOptions structure + AlgorithmIdentifier algS = new AlgorithmIdentifier(new OBJECT_IDENTIFIER("1.2.840.113549.3.7"), + new OCTET_STRING(IV.getIV())); + EncryptedValue encValue = new EncryptedValue(null, algS, new BIT_STRING(session_data, 0), null, null, + new BIT_STRING(key_data, 0)); + EncryptedKey key = new EncryptedKey(encValue); + PKIArchiveOptions opt = new PKIArchiveOptions(key); + + byte[] encoded = null; + + //Let's make sure we can decode the encoded PKIArchiveOptions.. + ByteArrayOutputStream oStream = new ByteArrayOutputStream(); + + opt.encode(oStream); + + encoded = oStream.toByteArray(); + ByteArrayInputStream inStream = new ByteArrayInputStream(encoded); + + @SuppressWarnings("unused") + PKIArchiveOptions options = (PKIArchiveOptions) + (new PKIArchiveOptions.Template()).decode(inStream); + + return encoded; + } +} + +// 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/base/util/src/com/netscape/cmsutil/crypto/Module.java b/base/util/src/com/netscape/cmsutil/crypto/Module.java new file mode 100644 index 000000000..bf4a7fe73 --- /dev/null +++ b/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 java.util.Vector; + +import org.mozilla.jss.crypto.CryptoToken; + +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<Token> mTokens = null; + private boolean mFound = false; + + public Module(String name, String printName) { + mCommonName = name; + mUserFriendlyName = printName; + mTokens = new Vector<Token>(); + } + + public Module(String name, String printName, String image) { + mCommonName = name; + mUserFriendlyName = printName; + mImagePath = image; + mTokens = new Vector<Token>(); + } + + 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<Token> getTokens() { + return mTokens; + } +} diff --git a/base/util/src/com/netscape/cmsutil/crypto/Token.java b/base/util/src/com/netscape/cmsutil/crypto/Token.java new file mode 100644 index 000000000..c6f5a5e3c --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/crypto/Token.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.crypto; + +import org.mozilla.jss.crypto.CryptoToken; + +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/base/util/src/com/netscape/cmsutil/http/ConnectAsync.java b/base/util/src/com/netscape/cmsutil/http/ConnectAsync.java new file mode 100644 index 000000000..ca230ca21 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/http/ConnectAsync.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.http; + +import java.net.SocketException; + +import com.netscape.cmsutil.net.ISocketFactory; + +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/base/util/src/com/netscape/cmsutil/http/Http.java b/base/util/src/com/netscape/cmsutil/http/Http.java new file mode 100644 index 000000000..2cda7fd12 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/http/Http.java @@ -0,0 +1,31 @@ +// --- 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/base/util/src/com/netscape/cmsutil/http/HttpClient.java b/base/util/src/com/netscape/cmsutil/http/HttpClient.java new file mode 100644 index 000000000..438c70c23 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/http/HttpClient.java @@ -0,0 +1,217 @@ +// --- 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.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.net.Socket; + +import org.mozilla.jss.ssl.SSLCertificateApprovalCallback; + +import com.netscape.cmsutil.net.ISocketFactory; + +/** + * 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")) { + 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/base/util/src/com/netscape/cmsutil/http/HttpEofException.java b/base/util/src/com/netscape/cmsutil/http/HttpEofException.java new file mode 100644 index 000000000..824b9ea2a --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/http/HttpEofException.java @@ -0,0 +1,35 @@ +// --- 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 { + /** + * + */ + private static final long serialVersionUID = 433303354049669059L; + + public HttpEofException() { + super(); + } + + public HttpEofException(String msg) { + super(msg); + } +} diff --git a/base/util/src/com/netscape/cmsutil/http/HttpMessage.java b/base/util/src/com/netscape/cmsutil/http/HttpMessage.java new file mode 100644 index 000000000..badec5930 --- /dev/null +++ b/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.BufferedReader; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.util.Enumeration; +import java.util.Hashtable; + +/** + * 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<String, String> mHeaders = null; + protected String mContent = null; // arbitrary content chars assumed. + + /** + * Instantiate a HttpResponse for write to http client. + */ + public HttpMessage() { + mHeaders = new Hashtable<String, String>(); + } + + /** + * 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<String, String>(); + 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<String> keys = mHeaders.keys(); + String header, value; + + while (keys.hasMoreElements()) { + header = keys.nextElement(); + value = 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<String, String>(); + + 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 = 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/base/util/src/com/netscape/cmsutil/http/HttpProtocolException.java b/base/util/src/com/netscape/cmsutil/http/HttpProtocolException.java new file mode 100644 index 000000000..b5ceb1d7f --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/http/HttpProtocolException.java @@ -0,0 +1,35 @@ +// --- 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 { + /** + * + */ + private static final long serialVersionUID = -953002842302351684L; + + public HttpProtocolException() { + super(); + } + + public HttpProtocolException(String msg) { + super(msg); + } +} diff --git a/base/util/src/com/netscape/cmsutil/http/HttpRequest.java b/base/util/src/com/netscape/cmsutil/http/HttpRequest.java new file mode 100644 index 000000000..9024dabf0 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/http/HttpRequest.java @@ -0,0 +1,137 @@ +// --- 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.BufferedReader; +import java.io.IOException; +import java.io.OutputStreamWriter; + +/** + * 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/base/util/src/com/netscape/cmsutil/http/HttpResponse.java b/base/util/src/com/netscape/cmsutil/http/HttpResponse.java new file mode 100644 index 000000000..7ac7e2f69 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/http/HttpResponse.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.BufferedReader; +import java.io.IOException; +import java.io.OutputStreamWriter; + +/** + * 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/base/util/src/com/netscape/cmsutil/http/JssSSLSocketFactory.java b/base/util/src/com/netscape/cmsutil/http/JssSSLSocketFactory.java new file mode 100644 index 000000000..c2013a5d2 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/http/JssSSLSocketFactory.java @@ -0,0 +1,182 @@ +// --- 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; +import java.net.Socket; +import java.net.SocketException; +import java.net.UnknownHostException; + +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.ssl.SSLCertificateApprovalCallback; +import org.mozilla.jss.ssl.SSLClientCertificateSelectionCallback; +import org.mozilla.jss.ssl.SSLHandshakeCompletedEvent; +import org.mozilla.jss.ssl.SSLHandshakeCompletedListener; +import org.mozilla.jss.ssl.SSLSocket; + +import com.netscape.cmsutil.net.ISocketFactory; + +/** + * Uses NSS ssl socket. + * + * @version $Revision$ $Date$ + */ +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, + SSLSocket.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, + SSLSocket.TLS_RSA_WITH_AES_128_CBC_SHA, + SSLSocket.TLS_RSA_WITH_AES_256_CBC_SHA, + SSLSocket.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, + SSLSocket.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, + //SSLSocket.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, + //SSLSocket.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, + //SSLSocket.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, + SSLSocket.TLS_DHE_DSS_WITH_AES_128_CBC_SHA, + SSLSocket.TLS_DHE_DSS_WITH_AES_256_CBC_SHA, + SSLSocket.TLS_DHE_RSA_WITH_AES_128_CBC_SHA, + SSLSocket.TLS_DHE_RSA_WITH_AES_256_CBC_SHA, + 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, false); + } 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, false); + } 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); + for (int i = 0; cipherSuites[i] != 0; ++i) { + try { + SSLSocket.setCipherPreferenceDefault(cipherSuites[i], true); + } catch (SocketException e) { + } + } + + s.setUseClientMode(true); + s.enableSSL2(false); + //TODO Do we rally want to set the default each time? + SSLSocket.enableSSL2Default(false); + s.enableV2CompatibleHello(false); + + 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 + 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/base/util/src/com/netscape/cmsutil/ldap/LDAPUtil.java b/base/util/src/com/netscape/cmsutil/ldap/LDAPUtil.java new file mode 100644 index 000000000..e821db67a --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ldap/LDAPUtil.java @@ -0,0 +1,101 @@ +// --- 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 java.io.IOException; +import java.util.ArrayList; + +import netscape.ldap.LDAPAttribute; +import netscape.ldap.LDAPAttributeSet; +import netscape.ldap.LDAPConnection; +import netscape.ldap.LDAPEntry; +import netscape.ldap.LDAPException; +import netscape.ldap.LDAPModification; +import netscape.ldap.util.LDIF; +import netscape.ldap.util.LDIFAttributeContent; +import netscape.ldap.util.LDIFContent; +import netscape.ldap.util.LDIFModifyContent; +import netscape.ldap.util.LDIFRecord; + +public class LDAPUtil { + + // special chars are *, (, ), \, null + public static String SPECIAL_CHARS = "*()\\\000"; + + /** + * This method escapes special characters for LDAP filter (RFC 4515). + * Each special character will be replaced by a backslash followed by + * 2-digit hex of the ASCII code. + * + * @param string string to escape + * @return escaped string + */ + public static String escape(String string) { + StringBuilder sb = new StringBuilder(); + for (char c : string.toCharArray()) { + if (SPECIAL_CHARS.indexOf(c) >= 0) { + sb.append('\\'); + if (c < 0x10) sb.append('0'); // make sure it's 2-digit + sb.append(Integer.toHexString(c)); + } else { + sb.append(c); + } + } + return sb.toString(); + } + + public static void importLDIF(LDAPConnection conn, String filename, ArrayList<String> errors) 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) { + errors.add("LDAPUtil:importLDIF: exception in adding entry " + dn + + ":" + ee.toString() + "\n"); + } + } else if (type == LDIFContent.MODIFICATION_CONTENT) { + LDIFModifyContent c = (LDIFModifyContent) content; + LDAPModification[] mods = c.getModifications(); + try { + conn.modify(dn, mods); + } catch (LDAPException ee) { + errors.add("LDAPUtil:importLDIF: exception in modifying entry " + dn + + ":" + ee.toString()); + } + } + } catch (Exception e) { + throw new IOException(e.toString()); + } + } + } +} diff --git a/base/util/src/com/netscape/cmsutil/net/ISocketFactory.java b/base/util/src/com/netscape/cmsutil/net/ISocketFactory.java new file mode 100644 index 000000000..18f6cac88 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/net/ISocketFactory.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.net; + +import java.io.IOException; +import java.net.Socket; +import java.net.UnknownHostException; + +import org.mozilla.jss.ssl.SSLCertificateApprovalCallback; +import org.mozilla.jss.ssl.SSLClientCertificateSelectionCallback; + +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/base/util/src/com/netscape/cmsutil/ocsp/BasicOCSPResponse.java b/base/util/src/com/netscape/cmsutil/ocsp/BasicOCSPResponse.java new file mode 100644 index 000000000..11ae7f152 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/BasicOCSPResponse.java @@ -0,0 +1,195 @@ +// --- 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.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.BIT_STRING; +import org.mozilla.jss.asn1.EXPLICIT; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.OCTET_STRING; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.asn1.Tag; +import org.mozilla.jss.pkix.cert.Certificate; +import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier; + +/** + * RFC 2560: + * + * <pre> + * BasicOCSPResponse ::= SEQUENCE { + * tbsResponseData ResponseData, + * signatureAlgorithm AlgorithmIdentifier, + * signature BIT STRING, + * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } + * </pre> + * + * @version $Revision$ $Date$ + */ +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) { + this(os.toByteArray()); + } + + public BasicOCSPResponse(byte data[]) { + mData = data; + + // extract _rd, _signAlg, _signature and _certs + try { + BasicOCSPResponse resp = (BasicOCSPResponse) getTemplate().decode(new ByteArrayInputStream(data)); + _rd = resp.getResponseData(); + _signAlg = resp.getSignatureAlgorithm(); + _signature = resp.getSignature(); + _certs = resp.getCerts(); + } catch (Exception e) { + // exception in decoding byte data + } + } + + private static final Tag TAG = SEQUENCE.TAG; + + public Tag getTag() { + return TAG; + } + + public void encode(Tag t, OutputStream os) throws IOException { + if (mData != null) { + os.write(mData); + } else { + SEQUENCE seq = new SEQUENCE(); + seq.addElement(_rd); + seq.addElement(_signAlg); + seq.addElement(_signature); + if (_certs != null) { + SEQUENCE certsSeq = new SEQUENCE(); + for (Certificate c : _certs) { + certsSeq.addElement(c); + } + EXPLICIT certsExplicit = new EXPLICIT(new Tag(0), certsSeq); + seq.addElement(certsExplicit); + } + seq.encode(t, os); + } + } + + public void encode(OutputStream os) throws IOException { + encode(TAG, os); + } + + 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 != null) ? _certs.length : 0; + } + + public Certificate[] getCerts() { + return _certs; + } + + public Certificate getCertificateAt(int pos) { + return (_certs != null) ? _certs[pos] : 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(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); + Certificate[] certs = null; + if (seq.size() == 4) { + // optional certificates are present + EXPLICIT certSeqExplicit = (EXPLICIT) seq.elementAt(3); + SEQUENCE certSeq = (SEQUENCE) certSeqExplicit.getContent(); + if (certSeq != null) { + certs = new Certificate[certSeq.size()]; + for (int x = 0; x < certSeq.size(); x++) { + certs[x] = (Certificate) certSeq.elementAt(x); + } + } + } + + return new BasicOCSPResponse(rd, alg, bs, certs); + } + } +} diff --git a/base/util/src/com/netscape/cmsutil/ocsp/CertID.java b/base/util/src/com/netscape/cmsutil/ocsp/CertID.java new file mode 100644 index 000000000..b6979c784 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/CertID.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.ocsp; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.INTEGER; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.OCTET_STRING; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.asn1.Tag; +import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier; + +/** + * RFC 2560: + * + * <pre> + * CertID ::= SEQUENCE { + * hashAlgorithm AlgorithmIdentifier, + * issuerNameHash OCTET STRING, -- Hash of Issuer's DN + * issuerKeyHash OCTET STRING, -- Hash of Issuers public key + * serialNumber CertificateSerialNumber } + * </pre> + * + * @version $Revision$ $Date$ + */ + +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 + /////////////////////////////////////////////////////////////////////// + + 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/base/util/src/com/netscape/cmsutil/ocsp/CertStatus.java b/base/util/src/com/netscape/cmsutil/ocsp/CertStatus.java new file mode 100644 index 000000000..a90eb215f --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/CertStatus.java @@ -0,0 +1,35 @@ +// --- 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.ASN1Value; + +/** + * RFC 2560: + * + * <pre> + * CertStatus ::= CHOICE { + * good [0] IMPLICIT NULL, + * revoked [1] IMPLICIT RevokedInfo, + * unknown [2] IMPLICIT UnknownInfo } + * </pre> + * + * @version $Revision$ $Date$ + */ +public interface CertStatus extends ASN1Value { +} diff --git a/base/util/src/com/netscape/cmsutil/ocsp/GoodInfo.java b/base/util/src/com/netscape/cmsutil/ocsp/GoodInfo.java new file mode 100644 index 000000000..fa7387260 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/GoodInfo.java @@ -0,0 +1,98 @@ +// --- 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.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.NULL; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.asn1.Tag; + +/** + * RFC 2560: + * + * <pre> + * CertStatus ::= CHOICE { + * good [0] IMPLICIT NULL, + * revoked [1] IMPLICIT RevokedInfo, + * unknown [2] IMPLICIT UnknownInfo } + * </pre> + * + * @version $Revision$ $Date$ + */ +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/base/util/src/com/netscape/cmsutil/ocsp/KeyHashID.java b/base/util/src/com/netscape/cmsutil/ocsp/KeyHashID.java new file mode 100644 index 000000000..358fb0ebd --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/KeyHashID.java @@ -0,0 +1,105 @@ +// --- 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.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.OCTET_STRING; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.asn1.Tag; + +/** + * RFC 2560: + * + * <pre> + * ResponderID ::= CHOICE { + * byName [1] EXPLICIT Name, + * byKey [2] EXPLICIT KeyHash } + * </pre> + * + * @version $Revision$ $Date$ + */ +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/base/util/src/com/netscape/cmsutil/ocsp/NameID.java b/base/util/src/com/netscape/cmsutil/ocsp/NameID.java new file mode 100644 index 000000000..529ededbb --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/NameID.java @@ -0,0 +1,106 @@ +// --- 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.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.asn1.Tag; +import org.mozilla.jss.pkix.primitive.Name; + +/** + * RFC 2560: + * + * <pre> + * ResponderID ::= CHOICE { + * byName [1] EXPLICIT Name, + * byKey [2] EXPLICIT KeyHash } + * </pre> + * + * @version $Revision$ $Date$ + */ +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/base/util/src/com/netscape/cmsutil/ocsp/OCSPRequest.java b/base/util/src/com/netscape/cmsutil/ocsp/OCSPRequest.java new file mode 100644 index 000000000..963bdc832 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/OCSPRequest.java @@ -0,0 +1,140 @@ +// --- 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.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.EXPLICIT; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.asn1.Tag; + +/** + * RFC 2560: + * + * <pre> + * OCSPRequest ::= SEQUENCE { + * tbsRequest TBSRequest, + * optionalSignature [0] EXPLICIT Signature OPTIONAL } + * </pre> + * + * @version $Revision$ $Date$ + */ + +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; + } + + /* 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/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponse.java b/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponse.java new file mode 100644 index 000000000..6696cd9dc --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponse.java @@ -0,0 +1,135 @@ +// --- 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.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.EXPLICIT; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.asn1.Tag; + +/** + * RFC 2560: + * + * <pre> + * OCSPResponse ::= SEQUENCE { + * responseStatus OCSPResponseStatus, + * responseBytes [0] EXPLICIT ResponseBytes OPTIONAL } + * </pre> + * + * @version $Revision$ $Date$ + */ +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; + } + + 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/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponseStatus.java b/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponseStatus.java new file mode 100644 index 000000000..38ca881c2 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/OCSPResponseStatus.java @@ -0,0 +1,120 @@ +// --- 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.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.ENUMERATED; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.Tag; + +/** + * RFC 2560: + * + * <pre> + * 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 + * } + * </pre> + * + * @version $Revision$ $Date$ + */ +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(); + } + + 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/base/util/src/com/netscape/cmsutil/ocsp/Request.java b/base/util/src/com/netscape/cmsutil/ocsp/Request.java new file mode 100644 index 000000000..85c97de22 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/Request.java @@ -0,0 +1,147 @@ +// --- 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.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.EXPLICIT; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.asn1.Tag; +import org.mozilla.jss.pkix.cert.Extension; + +/** + * RFC 2560: + * + * <pre> + * Request ::= SEQUENCE { + * reqCert CertID, + * singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL } + * </pre> + * + * @version $Revision$ $Date$ + */ + +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); + } + + 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/base/util/src/com/netscape/cmsutil/ocsp/ResponderID.java b/base/util/src/com/netscape/cmsutil/ocsp/ResponderID.java new file mode 100644 index 000000000..02e30de05 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/ResponderID.java @@ -0,0 +1,34 @@ +// --- 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.ASN1Value; + +/** + * RFC 2560: + * + * <pre> + * ResponderID ::= CHOICE { + * byName [1] EXPLICIT Name, + * byKey [2] EXPLICIT KeyHash } + * </pre> + * + * @version $Revision$ $Date$ + */ +public interface ResponderID extends ASN1Value { +} diff --git a/base/util/src/com/netscape/cmsutil/ocsp/Response.java b/base/util/src/com/netscape/cmsutil/ocsp/Response.java new file mode 100644 index 000000000..0d363e811 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/Response.java @@ -0,0 +1,34 @@ +// --- 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.ASN1Value; +import org.mozilla.jss.asn1.OCTET_STRING; + +/** + * RFC 2560: + * + * <pre> + * response OCTET STRING + * </pre> + * + * @version $Revision$ $Date$ + */ +public interface Response extends ASN1Value { + public OCTET_STRING getBytes(); +} diff --git a/base/util/src/com/netscape/cmsutil/ocsp/ResponseBytes.java b/base/util/src/com/netscape/cmsutil/ocsp/ResponseBytes.java new file mode 100644 index 000000000..c5d461148 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/ResponseBytes.java @@ -0,0 +1,130 @@ +// --- 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.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.OBJECT_IDENTIFIER; +import org.mozilla.jss.asn1.OCTET_STRING; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.asn1.Tag; + +/** + * RFC 2560: + * + * <pre> + * ResponseBytes ::= SEQUENCE { + * responseType OBJECT IDENTIFIER, + * response OCTET STRING } + * </pre> + * + * @version $Revision$ $Date$ + */ +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; + } + + 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/base/util/src/com/netscape/cmsutil/ocsp/ResponseData.java b/base/util/src/com/netscape/cmsutil/ocsp/ResponseData.java new file mode 100644 index 000000000..1b28cf134 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/ResponseData.java @@ -0,0 +1,222 @@ +// --- 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.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ANY; +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.EXPLICIT; +import org.mozilla.jss.asn1.GeneralizedTime; +import org.mozilla.jss.asn1.INTEGER; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.asn1.Tag; +import org.mozilla.jss.pkix.cert.Extension; + +/** + * RFC 2560: + * + * <pre> + * ResponseData ::= SEQUENCE { + * version [0] EXPLICIT Version DEFAULT v1, + * responderID ResponderID, + * producedAt GeneralizedTime, + * responses SEQUENCE OF SingleResponse, + * responseExtensions [1] EXPLICIT Extensions OPTIONAL } + * </pre> + * + * @version $Revision$ $Date$ + */ +public class ResponseData implements ASN1Value { + private static final INTEGER v1 = new INTEGER(0); + private INTEGER mVer; + 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(INTEGER ver, ResponderID rid, GeneralizedTime produced, + SingleResponse sr[], Extension exts[]) { + mVer = (ver != null) ? ver : v1; + mRID = rid; + mProduced = produced; + mSR = sr; + mExts = exts; + } + + public ResponseData(ResponderID rid, GeneralizedTime produced, + SingleResponse sr[]) { + this(v1, rid, produced, sr, null); + } + + public ResponseData(ResponderID rid, GeneralizedTime produced, + SingleResponse sr[], Extension exts[]) { + this(v1, rid, produced, sr, 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(); + + if (mVer != v1) { + seq.addElement(new EXPLICIT(Tag.get(0), new INTEGER(mVer))); + } + + 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() { + return (mSR != null) ? mSR.length : 0; + } + + public SingleResponse getResponseAt(int pos) { + return (mSR != null) ? mSR[pos] : null; + } + + public int getResponseExtensionCount() { + return (mExts != null) ? mExts.length : 0; + } + + public Extension getResponseExtensionAt(int pos) { + return (mExts != null) ? mExts[pos] : 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 = v1; + 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 != null) && (responses.size() > 0)) { + sr = new SingleResponse[responses.size()]; + for (int i = 0; i < responses.size(); i++) { + sr[i] = (SingleResponse) responses.elementAt(i); + } + } + + //decode response extension sequence + EXPLICIT extns_exp = (EXPLICIT) seq.elementAt(4); + SEQUENCE extns_seq; + Extension[] extns_array = null; + if (extns_exp != null) { + extns_seq = (SEQUENCE) extns_exp.getContent(); + extns_array = new Extension[extns_seq.size()]; + for (int x = 0; x < extns_array.length; x++) { + extns_array[x] = (Extension) extns_seq.elementAt(x); + } + } + + return new ResponseData(ver, rid, producedAt, sr, extns_array); + } + } +} diff --git a/base/util/src/com/netscape/cmsutil/ocsp/RevokedInfo.java b/base/util/src/com/netscape/cmsutil/ocsp/RevokedInfo.java new file mode 100644 index 000000000..9b0b2d186 --- /dev/null +++ b/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.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.EXPLICIT; +import org.mozilla.jss.asn1.GeneralizedTime; +import org.mozilla.jss.asn1.INTEGER; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.asn1.Tag; + +/** + * RFC 2560: + * + * <pre> + * RevokedInfo ::= SEQUENCE { + * revocationTime GeneralizedTime, + * revocationReason [0] EXPLICIT CRLReason OPTIONAL } + * </pre> + * + * @version $Revision$ $Date$ + */ +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/base/util/src/com/netscape/cmsutil/ocsp/Signature.java b/base/util/src/com/netscape/cmsutil/ocsp/Signature.java new file mode 100644 index 000000000..b9b192aee --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/Signature.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 java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.BIT_STRING; +import org.mozilla.jss.asn1.EXPLICIT; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.asn1.Tag; +import org.mozilla.jss.pkix.cert.Certificate; +import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier; + +/** + * RFC 2560: + * + * <pre> + * Signature ::= SEQUENCE { + * signatureAlgorithm AlgorithmIdentifier, + * signature BIT STRING, + * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } + * </pre> + * + * @version $Revision$ $Date$ + */ + +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); + } + + 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/base/util/src/com/netscape/cmsutil/ocsp/SingleResponse.java b/base/util/src/com/netscape/cmsutil/ocsp/SingleResponse.java new file mode 100644 index 000000000..ab54e5019 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/SingleResponse.java @@ -0,0 +1,182 @@ +// --- 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.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ANY; +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.EXPLICIT; +import org.mozilla.jss.asn1.GeneralizedTime; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.asn1.Tag; +import org.mozilla.jss.pkix.cert.Extension; + +/** + * RFC 2560: + * + * <pre> + * SingleResponse ::= SEQUENCE { + * certID CertID, + * certStatus CertStatus, + * thisUpdate GeneralizedTime, + * nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL, + * singleExtensions [1] EXPLICIT Extensions OPTIONAL } + * </pre> + * + * @version $Revision$ $Date$ + */ +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/base/util/src/com/netscape/cmsutil/ocsp/TBSRequest.java b/base/util/src/com/netscape/cmsutil/ocsp/TBSRequest.java new file mode 100644 index 000000000..b7f706edb --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/ocsp/TBSRequest.java @@ -0,0 +1,210 @@ +// --- 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.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ANY; +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.EXPLICIT; +import org.mozilla.jss.asn1.INTEGER; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.asn1.Tag; +import org.mozilla.jss.pkix.cert.Extension; + +/** + * RFC 2560: + * + * <pre> + * TBSRequest ::= SEQUENCE { + * version [0] EXPLICIT Version DEFAULT v1, + * requestorName [1] EXPLICIT GeneralName OPTIONAL, + * requestList SEQUENCE OF Request, + * requestExtensions [2] EXPLICIT Extensions OPTIONAL } + * </pre> + * + * @version $Revision$ $Date$ + */ + +public class TBSRequest implements ASN1Value { + /////////////////////////////////////////////////////////////////////// + // members and member access + /////////////////////////////////////////////////////////////////////// + private static final INTEGER v1 = new INTEGER(0); + private INTEGER version; + private ANY requestorName; + private SEQUENCE requestList; + private SEQUENCE requestExtensions; + + 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 + /////////////////////////////////////////////////////////////////////// + + public TBSRequest(INTEGER version, ANY requestorName, + SEQUENCE requestList, SEQUENCE requestExtensions) { + this.version = (version != null) ? version : v1; + this.requestorName = requestorName; + this.requestList = requestList; + this.requestExtensions = 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 seq = new SEQUENCE(); + + if (version != v1) { + seq.addElement(new EXPLICIT(Tag.get(0), version)); + } + + if (requestorName != null) { + seq.addElement(new EXPLICIT(Tag.get(1), requestorName)); + } + + seq.addElement(requestList); + + if (requestExtensions != null) { + seq.addElement(new EXPLICIT(Tag.get(2), requestExtensions)); + } + if (implicitTag == null) { + seq.encode(ostream); + } else { + seq.encode(implicitTag, ostream); + } + } + + private static final Template templateInstance = new Template(); + + public static Template getTemplate() { + return templateInstance; + } + + /** + * A Template for decoding TBSRequest. + */ + 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); + + INTEGER v = v1; //assume default version + EXPLICIT e_ver = (EXPLICIT) seq.elementAt(0); + if (e_ver != null) { + v = (INTEGER) e_ver.getContent(); + } + + ANY requestorname = null; + EXPLICIT e_requestorName = (EXPLICIT) seq.elementAt(1); + if (e_requestorName != null) { + requestorname = (ANY) e_requestorName.getContent(); + } + + //request sequence (element 2) done below + + EXPLICIT exts = (EXPLICIT) seq.elementAt(3); + SEQUENCE exts_seq; + if (exts != null) { + exts_seq = (SEQUENCE) exts.getContent(); + } else { + exts_seq = null; + } + + return new TBSRequest( + v, + requestorname, + (SEQUENCE) seq.elementAt(2), + exts_seq); + } + } +} diff --git a/base/util/src/com/netscape/cmsutil/ocsp/UnknownInfo.java b/base/util/src/com/netscape/cmsutil/ocsp/UnknownInfo.java new file mode 100644 index 000000000..1fe4ea743 --- /dev/null +++ b/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.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.mozilla.jss.asn1.ASN1Template; +import org.mozilla.jss.asn1.ASN1Value; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.NULL; +import org.mozilla.jss.asn1.SEQUENCE; +import org.mozilla.jss.asn1.Tag; + +/** + * RFC 2560: + * + * <pre> + * UnknownInfo ::= NULL -- this can be replaced with an enumeration + * </pre> + * + * @version $Revision$ $Date$ + */ +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/base/util/src/com/netscape/cmsutil/password/IPasswordReader.java b/base/util/src/com/netscape/cmsutil/password/IPasswordReader.java new file mode 100644 index 000000000..759e9e777 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/password/IPasswordReader.java @@ -0,0 +1,29 @@ +// --- 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.IOException; +import java.util.Enumeration; + +public interface IPasswordReader { + public void init(String pwdPath) throws IOException; + + public String getPassword(String tag); + + public Enumeration<String> getTags(); +} diff --git a/base/util/src/com/netscape/cmsutil/password/IPasswordStore.java b/base/util/src/com/netscape/cmsutil/password/IPasswordStore.java new file mode 100644 index 000000000..49b2610fa --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/password/IPasswordStore.java @@ -0,0 +1,34 @@ +// --- 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.IOException; +import java.util.Enumeration; + +public interface IPasswordStore { + public void init(String pwdPath) throws IOException; + + public String getPassword(String tag); + + public Enumeration<String> getTags(); + + public Object putPassword(String tag, String password); + + public void commit() + throws IOException, ClassCastException, NullPointerException; +} diff --git a/base/util/src/com/netscape/cmsutil/password/IPasswordWriter.java b/base/util/src/com/netscape/cmsutil/password/IPasswordWriter.java new file mode 100644 index 000000000..c9f9691e7 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/password/IPasswordWriter.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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/password/PlainPasswordFile.java b/base/util/src/com/netscape/cmsutil/password/PlainPasswordFile.java new file mode 100644 index 000000000..eb43607f0 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/password/PlainPasswordFile.java @@ -0,0 +1,70 @@ +// --- 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.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Enumeration; +import java.util.Properties; +import java.util.Vector; + +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<String> getTags() { + Enumeration<?> e = mPwdStore.propertyNames(); + Vector<String> v = new Vector<String>(); + while (e.hasMoreElements()) { + v.add((String) e.nextElement()); + } + return v.elements(); + } + + 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/base/util/src/com/netscape/cmsutil/password/PlainPasswordReader.java b/base/util/src/com/netscape/cmsutil/password/PlainPasswordReader.java new file mode 100644 index 000000000..68724a9f6 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/password/PlainPasswordReader.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.password; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Enumeration; +import java.util.Properties; +import java.util.Vector; + +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<String> getTags() { + Enumeration<?> e = mPwdStore.propertyNames(); + Vector<String> v = new Vector<String>(); + while (e.hasMoreElements()) { + v.add((String) e.nextElement()); + } + return v.elements(); + } +} diff --git a/base/util/src/com/netscape/cmsutil/password/PlainPasswordWriter.java b/base/util/src/com/netscape/cmsutil/password/PlainPasswordWriter.java new file mode 100644 index 000000000..3ceac4bd6 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/password/PlainPasswordWriter.java @@ -0,0 +1,56 @@ +// --- 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.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Properties; + +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/base/util/src/com/netscape/cmsutil/radius/AccessAccept.java b/base/util/src/com/netscape/cmsutil/radius/AccessAccept.java new file mode 100644 index 000000000..4824c885f --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/AccessAccept.java @@ -0,0 +1,27 @@ +// --- 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.io.IOException; + +public class AccessAccept extends ServerPacket { + public AccessAccept(byte data[]) throws IOException { + super(data); + } + +} diff --git a/base/util/src/com/netscape/cmsutil/radius/AccessChallenge.java b/base/util/src/com/netscape/cmsutil/radius/AccessChallenge.java new file mode 100644 index 000000000..c06f809b1 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/AccessChallenge.java @@ -0,0 +1,27 @@ +// --- 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.io.IOException; + +public class AccessChallenge extends ServerPacket { + public AccessChallenge(byte data[]) throws IOException { + super(data); + } + +} diff --git a/base/util/src/com/netscape/cmsutil/radius/AccessReject.java b/base/util/src/com/netscape/cmsutil/radius/AccessReject.java new file mode 100644 index 000000000..5f32ef349 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/AccessReject.java @@ -0,0 +1,27 @@ +// --- 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.io.IOException; + +public class AccessReject extends ServerPacket { + public AccessReject(byte data[]) throws IOException { + super(data); + } + +} diff --git a/base/util/src/com/netscape/cmsutil/radius/AccessRequest.java b/base/util/src/com/netscape/cmsutil/radius/AccessRequest.java new file mode 100644 index 000000000..7856b0cc8 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/AccessRequest.java @@ -0,0 +1,25 @@ +// --- 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; + +public class AccessRequest extends NASPacket { + public AccessRequest(short id, Authenticator auth) { + super(ACCESS_REQUEST, id, auth); + } + +} diff --git a/base/util/src/com/netscape/cmsutil/radius/Attribute.java b/base/util/src/com/netscape/cmsutil/radius/Attribute.java new file mode 100644 index 000000000..5e79816e4 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/Attribute.java @@ -0,0 +1,97 @@ +// --- 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.io.ByteArrayOutputStream; +import java.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/AttributeFactory.java b/base/util/src/com/netscape/cmsutil/radius/AttributeFactory.java new file mode 100644 index 000000000..021c06720 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/AttributeFactory.java @@ -0,0 +1,154 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/AttributeSet.java b/base/util/src/com/netscape/cmsutil/radius/AttributeSet.java new file mode 100644 index 000000000..d6974d371 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/AttributeSet.java @@ -0,0 +1,56 @@ +// --- 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.Enumeration; +import java.util.Vector; + +public class AttributeSet { + private Vector<Attribute> _attrs = new Vector<Attribute>(); + + public AttributeSet() { + } + + public void addAttribute(Attribute attr) { + _attrs.addElement(attr); + } + + public int size() { + return _attrs.size(); + } + + public Enumeration<Attribute> 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 _attrs.elementAt(pos); + } +} diff --git a/base/util/src/com/netscape/cmsutil/radius/Authenticator.java b/base/util/src/com/netscape/cmsutil/radius/Authenticator.java new file mode 100644 index 000000000..008af489a --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/Authenticator.java @@ -0,0 +1,24 @@ +// --- 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.io.IOException; + +public abstract class Authenticator { + public abstract byte[] getData() throws IOException; +} diff --git a/base/util/src/com/netscape/cmsutil/radius/CHAPChallengeAttribute.java b/base/util/src/com/netscape/cmsutil/radius/CHAPChallengeAttribute.java new file mode 100644 index 000000000..cd715a031 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/CHAPChallengeAttribute.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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/CHAPPasswordAttribute.java b/base/util/src/com/netscape/cmsutil/radius/CHAPPasswordAttribute.java new file mode 100644 index 000000000..3f0ef1793 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/CHAPPasswordAttribute.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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/CallbackIdAttribute.java b/base/util/src/com/netscape/cmsutil/radius/CallbackIdAttribute.java new file mode 100644 index 000000000..5fd806003 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/CallbackIdAttribute.java @@ -0,0 +1,40 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/CallbackNumberAttribute.java b/base/util/src/com/netscape/cmsutil/radius/CallbackNumberAttribute.java new file mode 100644 index 000000000..d6e45cecd --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/CallbackNumberAttribute.java @@ -0,0 +1,40 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/CallerStationIdAttribute.java b/base/util/src/com/netscape/cmsutil/radius/CallerStationIdAttribute.java new file mode 100644 index 000000000..3b5eec804 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/CallerStationIdAttribute.java @@ -0,0 +1,40 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/CallingStationIdAttribute.java b/base/util/src/com/netscape/cmsutil/radius/CallingStationIdAttribute.java new file mode 100644 index 000000000..9a57f8089 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/CallingStationIdAttribute.java @@ -0,0 +1,40 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/ChallengeException.java b/base/util/src/com/netscape/cmsutil/radius/ChallengeException.java new file mode 100644 index 000000000..972f7f084 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/ChallengeException.java @@ -0,0 +1,43 @@ +// --- 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; + +public class ChallengeException extends Exception { + /** + * + */ + private static final long serialVersionUID = -3496050461777520369L; + 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/base/util/src/com/netscape/cmsutil/radius/FilterIdAttribute.java b/base/util/src/com/netscape/cmsutil/radius/FilterIdAttribute.java new file mode 100644 index 000000000..879d7d5c7 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/FilterIdAttribute.java @@ -0,0 +1,40 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkLinkAttribute.java b/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkLinkAttribute.java new file mode 100644 index 000000000..05273780f --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkLinkAttribute.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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkNetworkAttribute.java b/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkNetworkAttribute.java new file mode 100644 index 000000000..cea0d936a --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkNetworkAttribute.java @@ -0,0 +1,49 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkZoneAttribute.java b/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkZoneAttribute.java new file mode 100644 index 000000000..54ee47c45 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/FramedAppleTalkZoneAttribute.java @@ -0,0 +1,40 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/FramedCompressionAttribute.java b/base/util/src/com/netscape/cmsutil/radius/FramedCompressionAttribute.java new file mode 100644 index 000000000..b57c030b5 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/FramedCompressionAttribute.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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/FramedIPAddressAttribute.java b/base/util/src/com/netscape/cmsutil/radius/FramedIPAddressAttribute.java new file mode 100644 index 000000000..2f66ee8c2 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/FramedIPAddressAttribute.java @@ -0,0 +1,39 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/FramedIPNetmaskAttribute.java b/base/util/src/com/netscape/cmsutil/radius/FramedIPNetmaskAttribute.java new file mode 100644 index 000000000..f8e1980c7 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/FramedIPNetmaskAttribute.java @@ -0,0 +1,39 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/FramedIPXNetworkAttribute.java b/base/util/src/com/netscape/cmsutil/radius/FramedIPXNetworkAttribute.java new file mode 100644 index 000000000..92f47eec1 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/FramedIPXNetworkAttribute.java @@ -0,0 +1,39 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/FramedMTUAttribute.java b/base/util/src/com/netscape/cmsutil/radius/FramedMTUAttribute.java new file mode 100644 index 000000000..5cd9551a2 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/FramedMTUAttribute.java @@ -0,0 +1,49 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/FramedProtocolAttribute.java b/base/util/src/com/netscape/cmsutil/radius/FramedProtocolAttribute.java new file mode 100644 index 000000000..5af219b9a --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/FramedProtocolAttribute.java @@ -0,0 +1,56 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/FramedRouteAttribute.java b/base/util/src/com/netscape/cmsutil/radius/FramedRouteAttribute.java new file mode 100644 index 000000000..9b123fe2a --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/FramedRouteAttribute.java @@ -0,0 +1,40 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/FramedRoutingAttribute.java b/base/util/src/com/netscape/cmsutil/radius/FramedRoutingAttribute.java new file mode 100644 index 000000000..14d2b0cc8 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/FramedRoutingAttribute.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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/GenericAttribute.java b/base/util/src/com/netscape/cmsutil/radius/GenericAttribute.java new file mode 100644 index 000000000..ac1798ae3 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/GenericAttribute.java @@ -0,0 +1,35 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/IdleTimeoutAttribute.java b/base/util/src/com/netscape/cmsutil/radius/IdleTimeoutAttribute.java new file mode 100644 index 000000000..44b0c5087 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/IdleTimeoutAttribute.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.radius; + +import java.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/LoginIPHostAttribute.java b/base/util/src/com/netscape/cmsutil/radius/LoginIPHostAttribute.java new file mode 100644 index 000000000..0d1c0565a --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/LoginIPHostAttribute.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.radius; + +import java.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/LoginLATGroupAttribute.java b/base/util/src/com/netscape/cmsutil/radius/LoginLATGroupAttribute.java new file mode 100644 index 000000000..4cee6bc3a --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/LoginLATGroupAttribute.java @@ -0,0 +1,40 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/LoginLATNodeAttribute.java b/base/util/src/com/netscape/cmsutil/radius/LoginLATNodeAttribute.java new file mode 100644 index 000000000..2c2d3411e --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/LoginLATNodeAttribute.java @@ -0,0 +1,40 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/LoginLATPortAttribute.java b/base/util/src/com/netscape/cmsutil/radius/LoginLATPortAttribute.java new file mode 100644 index 000000000..330161ec8 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/LoginLATPortAttribute.java @@ -0,0 +1,40 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/LoginLATServiceAttribute.java b/base/util/src/com/netscape/cmsutil/radius/LoginLATServiceAttribute.java new file mode 100644 index 000000000..158630d27 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/LoginLATServiceAttribute.java @@ -0,0 +1,40 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/LoginServiceAttribute.java b/base/util/src/com/netscape/cmsutil/radius/LoginServiceAttribute.java new file mode 100644 index 000000000..73f49d39f --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/LoginServiceAttribute.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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/LoginTCPPortAttribute.java b/base/util/src/com/netscape/cmsutil/radius/LoginTCPPortAttribute.java new file mode 100644 index 000000000..6b44f50c6 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/LoginTCPPortAttribute.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.radius; + +import java.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/NASClassAttribute.java b/base/util/src/com/netscape/cmsutil/radius/NASClassAttribute.java new file mode 100644 index 000000000..57b983028 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/NASClassAttribute.java @@ -0,0 +1,40 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/NASIPAddressAttribute.java b/base/util/src/com/netscape/cmsutil/radius/NASIPAddressAttribute.java new file mode 100644 index 000000000..d4022b3dd --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/NASIPAddressAttribute.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.io.IOException; +import java.net.InetAddress; + +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/base/util/src/com/netscape/cmsutil/radius/NASIdentifierAttribute.java b/base/util/src/com/netscape/cmsutil/radius/NASIdentifierAttribute.java new file mode 100644 index 000000000..0a3a62cd8 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/NASIdentifierAttribute.java @@ -0,0 +1,40 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/NASPacket.java b/base/util/src/com/netscape/cmsutil/radius/NASPacket.java new file mode 100644 index 000000000..70d143989 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/NASPacket.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.radius; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/NASPortAttribute.java b/base/util/src/com/netscape/cmsutil/radius/NASPortAttribute.java new file mode 100644 index 000000000..0f7b31e75 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/NASPortAttribute.java @@ -0,0 +1,48 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/NASPortTypeAttribute.java b/base/util/src/com/netscape/cmsutil/radius/NASPortTypeAttribute.java new file mode 100644 index 000000000..84ccc3ae1 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/NASPortTypeAttribute.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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/Packet.java b/base/util/src/com/netscape/cmsutil/radius/Packet.java new file mode 100644 index 000000000..4fad0ba79 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/Packet.java @@ -0,0 +1,70 @@ +// --- 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; + +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/base/util/src/com/netscape/cmsutil/radius/PacketFactory.java b/base/util/src/com/netscape/cmsutil/radius/PacketFactory.java new file mode 100644 index 000000000..8d2e20e74 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/PacketFactory.java @@ -0,0 +1,39 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/PortLimitAttribute.java b/base/util/src/com/netscape/cmsutil/radius/PortLimitAttribute.java new file mode 100644 index 000000000..7903bb1fd --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/PortLimitAttribute.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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/ProxyStateAttribute.java b/base/util/src/com/netscape/cmsutil/radius/ProxyStateAttribute.java new file mode 100644 index 000000000..83831b652 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/ProxyStateAttribute.java @@ -0,0 +1,40 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/RadiusConn.java b/base/util/src/com/netscape/cmsutil/radius/RadiusConn.java new file mode 100644 index 000000000..b22807a5d --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/RadiusConn.java @@ -0,0 +1,230 @@ +// --- 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.io.IOException; +import java.io.InterruptedIOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.SocketException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Properties; + +/** + * 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/base/util/src/com/netscape/cmsutil/radius/RejectException.java b/base/util/src/com/netscape/cmsutil/radius/RejectException.java new file mode 100644 index 000000000..f312ef2a4 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/RejectException.java @@ -0,0 +1,39 @@ +// --- 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; + +public class RejectException extends Exception { + /** + * + */ + private static final long serialVersionUID = -6410697638175895003L; + 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/base/util/src/com/netscape/cmsutil/radius/ReplyMessageAttribute.java b/base/util/src/com/netscape/cmsutil/radius/ReplyMessageAttribute.java new file mode 100644 index 000000000..5ec4ea052 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/ReplyMessageAttribute.java @@ -0,0 +1,40 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/RequestAuthenticator.java b/base/util/src/com/netscape/cmsutil/radius/RequestAuthenticator.java new file mode 100644 index 000000000..5d82752dd --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/RequestAuthenticator.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.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +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/base/util/src/com/netscape/cmsutil/radius/ResponseAuthenticator.java b/base/util/src/com/netscape/cmsutil/radius/ResponseAuthenticator.java new file mode 100644 index 000000000..3c3de33c4 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/ResponseAuthenticator.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.radius; + +import java.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/ServerPacket.java b/base/util/src/com/netscape/cmsutil/radius/ServerPacket.java new file mode 100644 index 000000000..f7d7fa302 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/ServerPacket.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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/ServiceTypeAttribute.java b/base/util/src/com/netscape/cmsutil/radius/ServiceTypeAttribute.java new file mode 100644 index 000000000..f31c74f9a --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/ServiceTypeAttribute.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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/SessionTimeoutAttribute.java b/base/util/src/com/netscape/cmsutil/radius/SessionTimeoutAttribute.java new file mode 100644 index 000000000..2809aee4b --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/SessionTimeoutAttribute.java @@ -0,0 +1,48 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/StateAttribute.java b/base/util/src/com/netscape/cmsutil/radius/StateAttribute.java new file mode 100644 index 000000000..027f95620 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/StateAttribute.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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/TerminationActionAttribute.java b/base/util/src/com/netscape/cmsutil/radius/TerminationActionAttribute.java new file mode 100644 index 000000000..b47a70d8c --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/TerminationActionAttribute.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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/UserNameAttribute.java b/base/util/src/com/netscape/cmsutil/radius/UserNameAttribute.java new file mode 100644 index 000000000..af7ce6bbe --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/UserNameAttribute.java @@ -0,0 +1,39 @@ +// --- 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.io.IOException; + +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/base/util/src/com/netscape/cmsutil/radius/UserPasswordAttribute.java b/base/util/src/com/netscape/cmsutil/radius/UserPasswordAttribute.java new file mode 100644 index 000000000..31c27cdfd --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/UserPasswordAttribute.java @@ -0,0 +1,73 @@ +// --- 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.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +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/base/util/src/com/netscape/cmsutil/radius/VendorSpecificAttribute.java b/base/util/src/com/netscape/cmsutil/radius/VendorSpecificAttribute.java new file mode 100644 index 000000000..5f3d9f170 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/radius/VendorSpecificAttribute.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.radius; + +import java.io.IOException; + +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/base/util/src/com/netscape/cmsutil/scep/CRSPKIMessage.java b/base/util/src/com/netscape/cmsutil/scep/CRSPKIMessage.java new file mode 100644 index 000000000..03bc68723 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/scep/CRSPKIMessage.java @@ -0,0 +1,905 @@ +// --- 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 java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.CharConversionException; +import java.io.IOException; +import java.security.PublicKey; +import java.util.Arrays; +import java.util.Hashtable; + +import netscape.security.pkcs.PKCS10; + +import org.mozilla.jss.asn1.ANY; +import org.mozilla.jss.asn1.ASN1Util; +import org.mozilla.jss.asn1.INTEGER; +import org.mozilla.jss.asn1.InvalidBERException; +import org.mozilla.jss.asn1.NULL; +import org.mozilla.jss.asn1.OBJECT_IDENTIFIER; +import org.mozilla.jss.asn1.OCTET_STRING; +import org.mozilla.jss.asn1.PrintableString; +import org.mozilla.jss.asn1.SET; +import org.mozilla.jss.crypto.SignatureAlgorithm; +import org.mozilla.jss.crypto.TokenException; +import org.mozilla.jss.pkcs7.Attribute; +import org.mozilla.jss.pkcs7.ContentInfo; +import org.mozilla.jss.pkcs7.EncryptedContentInfo; +import org.mozilla.jss.pkcs7.EnvelopedData; +import org.mozilla.jss.pkcs7.IssuerAndSerialNumber; +import org.mozilla.jss.pkcs7.RecipientInfo; +import org.mozilla.jss.pkcs7.SignedData; +import org.mozilla.jss.pkcs7.SignerInfo; +import org.mozilla.jss.pkix.cert.Certificate; +import org.mozilla.jss.pkix.cert.CertificateInfo; +import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier; + +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 DES_EDE3_CBC_ENCRYPTION = + new OBJECT_IDENTIFIER(new long[] { 1, 2, 840, 113549, 3, 7 } + ); + + public static OBJECT_IDENTIFIER MD5_DIGEST = + new OBJECT_IDENTIFIER(new long[] { 1, 2, 840, 113549, 2, 5 } + ); + + public static OBJECT_IDENTIFIER SHA1_DIGEST = + new OBJECT_IDENTIFIER(new long[] { 1, 3, 14, 3, 2, 26 } + ); + + public static OBJECT_IDENTIFIER SHA256_DIGEST = + new OBJECT_IDENTIFIER(new long[] { 2, 16, 840, 1, 101, 3, 4, 2, 1 } + ); + + public static OBJECT_IDENTIFIER SHA512_DIGEST = + new OBJECT_IDENTIFIER(new long[] { 2, 16, 840, 1, 101, 3, 4, 2, 3 } + ); + + // 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 AlgorithmIdentifier digestAlgorithmId = null; + 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) * + private String encryptionAlgorithm = null; + + // 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 PKCS10 myP10; + + private Hashtable<String, Object> attrs; // miscellanous + + // *** END *** // + + public void debug() { + } + + public void put(String a, Object b) { + attrs.put(a, b); + } + + public Object get(Object a) { + return attrs.get(a); + } + + private SignatureAlgorithm getSignatureAlgorithm(String hashAlgorithm) { + SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RSASignatureWithMD5Digest; + if (hashAlgorithm != null) { + if (hashAlgorithm.equals("SHA1")) { + signatureAlgorithm = SignatureAlgorithm.RSASignatureWithSHA1Digest; + } else if (hashAlgorithm.equals("SHA256")) { + signatureAlgorithm = SignatureAlgorithm.RSASignatureWithSHA256Digest; + } else if (hashAlgorithm.equals("SHA512")) { + signatureAlgorithm = SignatureAlgorithm.RSASignatureWithSHA512Digest; + } + } + return signatureAlgorithm; + } + + private OBJECT_IDENTIFIER getAlgorithmOID(String hashAlgorithm) { + OBJECT_IDENTIFIER oid = MD5_DIGEST; + if (hashAlgorithm != null) { + if (hashAlgorithm.equals("SHA1")) { + oid = SHA1_DIGEST; + } else if (hashAlgorithm.equals("SHA256")) { + oid = SHA256_DIGEST; + } else if (hashAlgorithm.equals("SHA512")) { + oid = SHA512_DIGEST; + } + } + return oid; + } + + // getHashAlgorithm is added to work around issue 636217 + private String getHashAlgorithm(OBJECT_IDENTIFIER algorithmOID) { + String hashAlgorithm = null; + if (algorithmOID != null) { + if (algorithmOID.equals(MD5_DIGEST)) { + hashAlgorithm = "MD5"; + } else if (algorithmOID.equals(SHA1_DIGEST)) { + hashAlgorithm = "SHA1"; + } else if (algorithmOID.equals(SHA256_DIGEST)) { + hashAlgorithm = "SHA256"; + } else if (algorithmOID.equals(SHA512_DIGEST)) { + hashAlgorithm = "SHA512"; + } + } + return hashAlgorithm; + } + + // These functions are used to initialize the various blobs + + public void makeSignedData(int version, + byte[] certificate, String hashAlgorithm) { + + try { + SET digest_algs = new SET(); + + digest_algs.addElement(new AlgorithmIdentifier(getAlgorithmOID(hashAlgorithm), 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, String hashAlgorithm) + 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 + getSignatureAlgorithm(hashAlgorithm), + 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 (senderNonce != null) { + SET snset = new SET(); + + snset.addElement(new OCTET_STRING(senderNonce)); + aa.addElement(new Attribute(CRS_SENDERNONCE, snset)); + } + + 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, String algorithm) { + this.iv = iv; + this.ec = ec; + + try { + OBJECT_IDENTIFIER oid = DES_CBC_ENCRYPTION; + if (algorithm != null && algorithm.equals("DES3")) + oid = DES_EDE3_CBC_ENCRYPTION; + + AlgorithmIdentifier aid = new AlgorithmIdentifier(oid, 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 String getEncryptionAlgorithm() { + return encryptionAlgorithm; + } + + public String getDigestAlgorithmName() { + String name = null; + if (digestAlgorithmId != null) { + name = getHashAlgorithm(digestAlgorithmId.getOID()); + } + return name; + } + + 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 PKCS10 getP10() { + return myP10; + } + + public void setP10(PKCS10 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 + } + + private void decodeCRSPKIMessage(ByteArrayInputStream bais) throws InvalidBERException, Exception { + + 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(); + } + + public CRSPKIMessage() { + attrs = new Hashtable<String, Object>(); + } + + public CRSPKIMessage(ByteArrayInputStream bais) throws InvalidBERException, Exception { + attrs = new Hashtable<String, Object>(); + decodeCRSPKIMessage(bais); + } + + 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); + + digestAlgorithmId = si.getDigestAlgorithmIdentifer(); + + 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_EDE3_CBC_ENCRYPTION)) { + encryptionAlgorithm = "DES3"; + } else if (eci.getContentEncryptionAlgorithm().getOID().equals(DES_CBC_ENCRYPTION)) { + encryptionAlgorithm = "DES"; + } else { + throw new Exception("P10 encrypted alg is not supported (not DES): " + + eci.getContentEncryptionAlgorithm().getOID()); + } + + 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/base/util/src/com/netscape/cmsutil/util/Cert.java b/base/util/src/com/netscape/cmsutil/util/Cert.java new file mode 100644 index 000000000..3563f70c7 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/util/Cert.java @@ -0,0 +1,186 @@ +// --- 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.io.IOException; +import java.security.cert.CertificateException; +import java.security.cert.X509CRL; +import java.security.cert.X509Certificate; + +import netscape.security.pkcs.PKCS7; +import netscape.security.x509.X509CRLImpl; +import netscape.security.x509.X509CertImpl; + +import org.mozilla.jss.crypto.SignatureAlgorithm; + +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; + else if (algname.equals("SHA256withEC")) + return SignatureAlgorithm.ECSignatureWithSHA256Digest; + else if (algname.equals("SHA384withEC")) + return SignatureAlgorithm.ECSignatureWithSHA384Digest; + else if (algname.equals("SHA512withEC")) + return SignatureAlgorithm.ECSignatureWithSHA512Digest; + 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); + byte rawPub[] = Utils.base64decode(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); + byte rawPub[] = Utils.base64decode(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); + byte rawPub[] = Utils.base64decode(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[] = Utils.base64decode(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/base/util/src/com/netscape/cmsutil/util/Fmt.java b/base/util/src/com/netscape/cmsutil/util/Fmt.java new file mode 100644 index 000000000..a24b8d090 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/util/Fmt.java @@ -0,0 +1,605 @@ +// --- 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/base/util/src/com/netscape/cmsutil/util/HMACDigest.java b/base/util/src/com/netscape/cmsutil/util/HMACDigest.java new file mode 100644 index 000000000..09bf53bbf --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/util/HMACDigest.java @@ -0,0 +1,198 @@ +// --- 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; + +/** + * This class implements the HMAC algorithm specified in RFC 2104 using + * any MessageDigest. + * + * @author mikep + * @version $Revision$, $Date$ + * @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/base/util/src/com/netscape/cmsutil/util/Utils.java b/base/util/src/com/netscape/cmsutil/util/Utils.java new file mode 100644 index 000000000..303566416 --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/util/Utils.java @@ -0,0 +1,276 @@ +// --- 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 org.apache.commons.codec.binary.Base64; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Vector; + +public class Utils { + /** + * Checks if this is NT. + */ + public static boolean isNT() { + return File.separator.equals("\\"); + } + + public static boolean isUnix() { + 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(); + + 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.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<String> v) { + String s[] = new String[v.size()]; + + v.copyInto(s); + return s; + } + + public static String base64encode(byte[] bytes) { + String string = new Base64(64).encodeToString(bytes); + return string; + } + + public static byte[] base64decode(String string) { + byte[] bytes = Base64.decodeBase64(string); + return bytes; + } +} diff --git a/base/util/src/com/netscape/cmsutil/xml/XMLObject.java b/base/util/src/com/netscape/cmsutil/xml/XMLObject.java new file mode 100644 index 000000000..ed2fb67ee --- /dev/null +++ b/base/util/src/com/netscape/cmsutil/xml/XMLObject.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.xml; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.StringWriter; +import java.util.Vector; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.Text; +import org.xml.sax.SAXException; + +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<String> getAllValues(String tagname) { + Vector<String> v = new Vector<String>(); + 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<String> getValuesFromContainer(Node container, String tagname) { + Vector<String> v = new Vector<String>(); + 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); + } + + public String toXMLString() throws TransformerConfigurationException, TransformerException { + TransformerFactory tranFactory = TransformerFactory.newInstance(); + Transformer transformer = tranFactory.newTransformer(); + Source src = new DOMSource(mDoc); + StreamResult dest = new StreamResult(new StringWriter()); + transformer.transform(src, dest); + String xmlString = dest.getWriter().toString(); + return xmlString; + } +} |