not-yet-commons-ssl-0.3.11

    pqgVec.add(g);
        DERSequence pqg = new DERSequence(pqgVec);
        innerVec.add(pqg);
      }
      else
      {
        innerVec.add(DERNull.INSTANCE);
        octetsToAppend = new DEROctetString(privateKey);
      }
      DERSequence inner = new DERSequence(innerVec);
      outterVec.add(derZero);
      outterVec.add(inner);
      outterVec.add(octetsToAppend);
      DERSequence outter = new DERSequence(outterVec);
      return encode(outter);
    }
    catch (IOException ioe)
    {
      throw JavaImpl.newRuntimeException(ioe);
    }
  }
  
  private static boolean allZeroes(byte[] b)
  {
    for (int i = 0; i < b.length; i++) {
      if (b[i] != 0) {
        return false;
      }
    }
    return true;
  }
  
  public static byte[] encode(DEREncodable der)
    throws IOException
  {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    ASN1OutputStream out = new ASN1OutputStream(baos);
    out.writeObject(der);
    out.close();
    return baos.toByteArray();
  }
  
  public static void main(String[] args)
    throws Exception
  {
    String password = "changeit";
    if (args.length == 0)
    {
      System.out.println("Usage1:  [password] [file:private-key]      Prints decrypted PKCS8 key (base64).");
      System.out.println("Usage2:  [password] [file1] [file2] etc...  Checks that all private keys are equal.");
      System.out.println("Usage2 assumes that all files can be decrypted with the same password.");
    }
    else if ((args.length == 1) || (args.length == 2))
    {
      FileInputStream in = new FileInputStream(args[(args.length - 1)]);
      if (args.length == 2) {
        password = args[0];
      }
      byte[] bytes = Util.streamToBytes(in);
      PKCS8Key key = new PKCS8Key(bytes, password.toCharArray());
      PEMItem item = new PEMItem(key.getDecryptedBytes(), "PRIVATE KEY");
      byte[] pem = PEMUtil.encode(Collections.singleton(item));
      System.out.write(pem);
    }
    else
    {
      byte[] original = null;
      File f = new File(args[0]);
      int i = 0;
      if (!f.exists())
      {
        password = args[0];
        i++;
      }
      for (; i < args.length; i++)
      {
        FileInputStream in = new FileInputStream(args[i]);
        byte[] bytes = Util.streamToBytes(in);
        PKCS8Key key = null;
        try
        {
          key = new PKCS8Key(bytes, password.toCharArray());
        }
        catch (Exception e)
        {
          System.out.println(" FAILED! " + args[i] + " " + e);
        }
        if (key != null)
        {
          byte[] decrypted = key.getDecryptedBytes();
          int keySize = key.getKeySize();
          String keySizeStr = "" + keySize;
          if (keySize < 10) {
            keySizeStr = "  " + keySizeStr;
          } else if (keySize < 100) {
            keySizeStr = " " + keySizeStr;
          }
          StringBuffer buf = new StringBuffer(key.getTransformation());
          int maxLen = "Blowfish/CBC/PKCS5Padding".length();
          for (int j = buf.length(); j < maxLen; j++) {
            buf.append(' ');
          }
          String transform = buf.toString();
          String type = key.isDSA() ? "DSA" : "RSA";
          if (original == null)
          {
            original = decrypted;
            System.out.println("   SUCCESS    \t" + type + "\t" + transform + "\t" + keySizeStr + "\t" + args[i]);
          }
          else
          {
            boolean identical = Arrays.equals(original, decrypted);
            if (!identical) {
              System.out.println("***FAILURE*** \t" + type + "\t" + transform + "\t" + keySizeStr + "\t" + args[i]);
            } else {
              System.out.println("   SUCCESS    \t" + type + "\t" + transform + "\t" + keySizeStr + "\t" + args[i]);
            }
          }
        }
      }
    }
  }
  
  static {}
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.PKCS8Key
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import java.util.Map;
import java.util.SortedSet;

public class Ping$Arg
  implements Comparable
{
  public final String shortArg;
  public final String longArg;
  public final String description;
  public final boolean isRequired;
  private final int id;
  
  public Ping$Arg(String s, String l, String d)
  {
    this(s, l, d, false);
  }
  
  public Ping$Arg(String s, String l, String d, boolean isRequired)
  {
    this.isRequired = isRequired;
    shortArg = s;
    longArg = l;
    description = d;
    id = Ping.ARGS.size();
    Ping.ARGS.add(this);
    if ((s != null) && (s.length() >= 2)) {
      Ping.ARGS_MATCH.put(s, this);
    }
    if ((l != null) && (l.length() >= 3)) {
      Ping.ARGS_MATCH.put(l, this);
    }
  }
  
  public int compareTo(Object o)
  {
    return id - id;
  }
  
  public String toString()
  {
    return shortArg + "/" + longArg;
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.Ping.Arg
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import org.apache.commons.ssl.util.ReadLine;

public class Ping
{
  protected static final Arg ARG_TARGET = new Arg("-t", "--target", "[hostname[:port]]              default port=443", true);
  protected static final Arg ARG_BIND = new Arg("-b", "--bind", "[hostname[:port]]              default port=0 \"ANY\"");
  protected static final Arg ARG_PROXY = new Arg("-r", "--proxy", "[hostname[:port]]              default port=80");
  protected static final Arg ARG_TRUST_CERT = new Arg("-tm", "--trust-cert", "[path to trust material]       {pem, der, crt, jks}");
  protected static final Arg ARG_CLIENT_CERT = new Arg("-km", "--client-cert", "[path to client's private key] {jks, pkcs12, pkcs8}");
  protected static final Arg ARG_CERT_CHAIN = new Arg("-cc", "--cert-chain", "[path to client's cert chain for pkcs8/OpenSSL key]");
  protected static final Arg ARG_PASSWORD = new Arg("-p", "--password", "[client cert password]");
  protected static final Arg ARG_HOST_HEADER = new Arg("-h", "--host-header", "[http-host-header]      in case -t is an IP address");
  protected static final Arg ARG_PATH = new Arg("-u", "--path", "[path for GET/HEAD request]    default=/");
  protected static final Arg ARG_METHOD = new Arg("-m", "--method", "[http method to use]           default=HEAD");
  private static String httpMethod = "HEAD";
  private static String path = "/";
  private static int targetPort = 443;
  private static int localPort = 0;
  private static TrustChain trustChain = null;
  protected static SortedSet ARGS = Collections.unmodifiableSortedSet(ARGS);
  protected static Map ARGS_MATCH = Collections.unmodifiableMap(ARGS_MATCH);
  private static HostPort target;
  private static HostPort local;
  private static HostPort proxy;
  private static String hostHeader;
  private static InetAddress targetAddress;
  private static InetAddress localAddress;
  private static File clientCert;
  private static File certChain;
  private static char[] password;
  
  public static void main(String[] args)
    throws Exception
  {
    boolean showUsage = args.length == 0;
    Exception parseException = null;
    if (!showUsage) {
      try
      {
        parseArgs(args);
      }
      catch (Exception e)
      {
        parseException = e;
        showUsage = true;
      }
    }
    if (showUsage)
    {
      if (parseException != null)
      {
        System.out.println();
        System.out.println("* Error: " + parseException.getMessage() + ".");
        parseException.printStackTrace(System.out);
        System.out.println();
      }
      System.out.println("Usage:  java -jar not-yet-commons-ssl-" + Version.VERSION + ".jar [options]");
      System.out.println(Version.versionString());
      System.out.println("Options:   (*=required)");
      Iterator it = ARGS.iterator();
      while (it.hasNext())
      {
        Arg a = (Arg)it.next();
        String s = Util.pad(shortArg, 3, false);
        String l = Util.pad(longArg, 18, false);
        String required = isRequired ? "*" : " ";
        String d = description;
        System.out.println(required + "  " + s + " " + l + " " + d);
      }
      System.out.println();
      String example = "java -jar commons-ssl.jar -t host.com:443 -c ./client.pfx -p `cat ./pass.txt` ";
      System.out.println("Example:");
      System.out.println();
      System.out.println(example);
      System.out.println();
      System.exit(1);
      return;
    }
    SSLClient ssl = new SSLClient();
    Socket s = null;
    InputStream in = null;
    OutputStream out = null;
    Exception socketException = null;
    Exception trustException = null;
    Exception hostnameException = null;
    Exception crlException = null;
    Exception expiryException = null;
    String sslCipher = null;
    try
    {
      try
      {
        ssl.setCheckHostname(false);
        ssl.setCheckExpiry(false);
        ssl.setCheckCRL(false);
        ssl.addTrustMaterial(TrustMaterial.TRUST_ALL);
        if (clientCert != null)
        {
          KeyMaterial km;
          KeyMaterial km;
          if (certChain != null) {
            km = new KeyMaterial(clientCert, certChain, password);
          } else {
            km = new KeyMaterial(clientCert, password);
          }
          if (password != null) {
            for (int i = 0; i < password.length; i++) {
              password[i] = '\000';
            }
          }
          ssl.setKeyMaterial(km);
        }
        if (trustChain != null) {
          ssl.addTrustMaterial(trustChain);
        }
        ssl.setSoTimeout(10000);
        ssl.setConnectTimeout(5000);
        if (proxy != null)
        {
          s = new Socket(proxyhost, proxyport, localaddr, localport);
          
          s.setSoTimeout(10000);
          in = s.getInputStream();
          out = s.getOutputStream();
          String targetHost = targethost;
          String line1 = "CONNECT " + targetHost + ":" + targetPort + " HTTP/1.1\r\n";
          String line2 = "Proxy-Connection: keep-alive\r\n";
          String line3 = "Host: " + targetHost + "\r\n\r\n";
          out.write(line1.getBytes());
          out.write(line2.getBytes());
          out.write(line3.getBytes());
          out.flush();
          
          ReadLine readLine = new ReadLine(in);
          String read1 = readLine.next();
          if (read1.startsWith("HTTP/1.1 200"))
          {
            int avail = in.available();
            in.skip(avail);
            Thread.yield();
            avail = in.available();
            while (avail != 0)
            {
              in.skip(avail);
              Thread.yield();
              avail = in.available();
            }
            s = ssl.createSocket(s, targetHost, targetPort, true);
          }
          else
          {
            System.out.print(line1);
            System.out.print(line2);
            System.out.print(line3);
            System.out.println("Server returned unexpected proxy response!");
            System.out.println("=============================================");
            System.out.println(read1);
            String line = readLine.next();
            while (line != null)
            {
              System.out.println(line);
              line = readLine.next();
            }
            System.exit(1);
          }
        }
        else
        {
          s = ssl.createSocket(targetAddress, targetPort, localAddress, localPort);
        }
        sslCipher = ((SSLSocket)s).getSession().getCipherSuite();
        System.out.println("Cipher: " + sslCipher);
        System.out.println("================================================================================");
        
        String line1 = httpMethod + " " + path + " HTTP/1.1";
        if (hostHeader == null) {
          hostHeader = targetAddress.getHostName();
        }
        String line2 = "Host: " + hostHeader;
        byte[] crlf = { 13, 10 };
        
        System.out.println("Writing: ");
        System.out.println("================================================================================");
        System.out.println(line1);
        System.out.println(line2);
        System.out.println();
        
        out = s.getOutputStream();
        out.write(line1.getBytes());
        out.write(crlf);
        out.write(line2.getBytes());
        out.write(crlf);
        out.write(crlf);
        out.flush();
        
        in = s.getInputStream();
        
        int c = in.read();
        StringBuffer buf = new StringBuffer();
        System.out.println("Reading: ");
        System.out.println("================================================================================");
        while (c >= 0)
        {
          byte b = (byte)c;
          buf.append((char)b);
          System.out.print((char)b);
          if (-1 != buf.toString().indexOf("\r\n\r\n")) {
            break;
          }
          c = in.read();
        }
      }
      catch (Exception e)
      {
        socketException = e;
      }
      trustException = testTrust(ssl, sslCipher, trustChain);
      hostnameException = testHostname(ssl);
      crlException = testCRL(ssl);
      expiryException = testExpiry(ssl);
    }
    finally
    {
      if (out != null) {
        out.close();
      }
      if (in != null) {
        in.close();
      }
      if (s != null) {
        s.close();
      }
      X509Certificate[] peerChain = ssl.getCurrentServerChain();
      if (peerChain != null)
      {
        String title = "Server Certificate Chain for: ";
        title = peerChain.length > 1 ? title : "Server Certificate for: ";
        System.out.println(title + "[" + target + "]");
        System.out.println("================================================================================");
        for (int i = 0; i < peerChain.length; i++)
        {
          X509Certificate cert = peerChain[i];
          String certAsString = Certificates.toString(cert);
          String certAsPEM = Certificates.toPEMString(cert);
          if (i > 0) {
            System.out.println();
          }
          System.out.print(certAsString);
          System.out.print(certAsPEM);
        }
      }
      if (hostnameException != null)
      {
        hostnameException.printStackTrace();
        System.out.println();
      }
      if (crlException != null)
      {
        crlException.printStackTrace();
        System.out.println();
      }
      if (expiryException != null)
      {
        expiryException.printStackTrace();
        System.out.println();
      }
      if (trustException != null)
      {
        trustException.printStackTrace();
        System.out.println();
      }
      if (socketException != null)
      {
        socketException.printStackTrace();
        System.out.println();
      }
    }
  }
  
  private static Exception testTrust(SSLClient ssl, String cipher, TrustChain tc)
  {
    try
    {
      X509Certificate[] chain = ssl.getCurrentServerChain();
      String authType = Util.cipherToAuthType(cipher);
      if (authType == null) {
        authType = "RSA";
      }
      if (chain != null)
      {
        if (tc == null) {
          tc = TrustMaterial.DEFAULT;
        }
        Object[] trustManagers = tc.getTrustManagers();
        for (int i = 0; i < trustManagers.length; i++) {
          JavaImpl.testTrust(trustManagers[i], chain, authType);
        }
      }
    }
    catch (Exception e)
    {
      return e;
    }
    return null;
  }
  
  private static Exception testHostname(SSLClient ssl)
  {
    try
    {
      X509Certificate[] chain = ssl.getCurrentServerChain();
      if (chain != null)
      {
        String hostName = targethost;
        HostnameVerifier.DEFAULT.check(hostName, chain[0]);
      }
    }
    catch (Exception e)
    {
      return e;
    }
    return null;
  }
  
  private static Exception testCRL(SSLClient ssl)
  {
    try
    {
      X509Certificate[] chain = ssl.getCurrentServerChain();
      if (chain != null) {
        for (int i = 0; i < chain.length; i++) {
          Certificates.checkCRL(chain[i]);
        }
      }
    }
    catch (Exception e)
    {
      return e;
    }
    return null;
  }
  
  private static Exception testExpiry(SSLClient ssl)
  {
    try
    {
      X509Certificate[] chain = ssl.getCurrentServerChain();
      if (chain != null) {
        for (int i = 0; i < chain.length; i++) {
          chain[i].checkValidity();
        }
      }
    }
    catch (Exception e)
    {
      return e;
    }
    return null;
  }
  
  public static class Arg
    implements Comparable
  {
    public final String shortArg;
    public final String longArg;
    public final String description;
    public final boolean isRequired;
    private final int id;
    
    public Arg(String s, String l, String d)
    {
      this(s, l, d, false);
    }
    
    public Arg(String s, String l, String d, boolean isRequired)
    {
      this.isRequired = isRequired;
      shortArg = s;
      longArg = l;
      description = d;
      id = Ping.ARGS.size();
      Ping.ARGS.add(this);
      if ((s != null) && (s.length() >= 2)) {
        Ping.ARGS_MATCH.put(s, this);
      }
      if ((l != null) && (l.length() >= 3)) {
        Ping.ARGS_MATCH.put(l, this);
      }
    }
    
    public int compareTo(Object o)
    {
      return id - id;
    }
    
    public String toString()
    {
      return shortArg + "/" + longArg;
    }
  }
  
  private static void parseArgs(String[] cargs)
    throws Exception
  {
    Map args = Util.parseArgs(cargs);
    Iterator it = args.entrySet().iterator();
    while (it.hasNext())
    {
      Map.Entry entry = (Map.Entry)it.next();
      Arg arg = (Arg)entry.getKey();
      String[] values = (String[])entry.getValue();
      if (arg == ARG_TARGET)
      {
        target = Util.toAddress(values[0], 443);
        targetAddress = targetaddr;
        targetPort = targetport;
      }
      else if (arg == ARG_BIND)
      {
        local = Util.toAddress(values[0], 443);
        localAddress = localaddr;
        localPort = localport;
      }
      else if (arg == ARG_PROXY)
      {
        proxy = Util.toAddress(values[0], 80);
      }
      else if (arg == ARG_CLIENT_CERT)
      {
        clientCert = new File(values[0]);
      }
      else if (arg == ARG_CERT_CHAIN)
      {
        certChain = new File(values[0]);
      }
      else if (arg == ARG_PASSWORD)
      {
        password = values[0].toCharArray();
      }
      else if (arg == ARG_METHOD)
      {
        httpMethod = values[0].trim();
      }
      else if (arg == ARG_PATH)
      {
        path = values[0].trim();
      }
      else if (arg == ARG_HOST_HEADER)
      {
        hostHeader = values[0].trim();
      }
      else if (arg == ARG_TRUST_CERT)
      {
        for (int i = 0; i < values.length; i++)
        {
          File f = new File(values[i]);
          if (f.exists())
          {
            if (trustChain == null) {
              trustChain = new TrustChain();
            }
            TrustMaterial tm = new TrustMaterial(f);
            trustChain.addTrustMaterial(tm);
          }
        }
      }
    }
    args.clear();
    for (int i = 0; i < cargs.length; i++) {
      cargs[i] = null;
    }
    if (targetAddress == null) {
      throw new IllegalArgumentException("\"" + ARG_TARGET + "\" is mandatory");
    }
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.Ping
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import java.security.GeneralSecurityException;

public class ProbablyBadPasswordException
  extends GeneralSecurityException
{
  public ProbablyBadPasswordException() {}
  
  public ProbablyBadPasswordException(String s)
  {
    super(s);
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.ProbablyBadPasswordException
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import java.security.GeneralSecurityException;

public class ProbablyNotPKCS8Exception
  extends GeneralSecurityException
{
  public ProbablyNotPKCS8Exception() {}
  
  public ProbablyNotPKCS8Exception(String s)
  {
    super(s);
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.ProbablyNotPKCS8Exception
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import java.io.EOFException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.PrintStream;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.rmi.server.RMISocketFactory;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLProtocolException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

public class RMISocketFactoryImpl
  extends RMISocketFactory
{
  public static final String RMI_HOSTNAME_KEY = "java.rmi.server.hostname";
  private static final LogWrapper log = LogWrapper.getLogger(RMISocketFactoryImpl.class);
  private volatile SocketFactory defaultClient;
  private volatile ServerSocketFactory sslServer;
  private volatile String localBindAddress = null;
  private volatile int anonymousPort = 31099;
  private Map clientMap = new TreeMap();
  private Map serverSockets = new HashMap();
  private final SocketFactory plainClient = SocketFactory.getDefault();
  
  public RMISocketFactoryImpl()
    throws GeneralSecurityException, IOException
  {
    this(true);
  }
  
  public RMISocketFactoryImpl(boolean createDefaultServer)
    throws GeneralSecurityException, IOException
  {
    SSLServer defaultServer = createDefaultServer ? new SSLServer() : null;
    SSLClient defaultClient = new SSLClient();
    
    HostnameVerifier verifier = HostnameVerifier.DEFAULT_AND_LOCALHOST;
    defaultClient.setHostnameVerifier(verifier);
    if (defaultServer != null)
    {
      defaultServer.setHostnameVerifier(verifier);
      
      defaultServer.useTomcatSSLMaterial();
      X509Certificate[] x509 = defaultServer.getAssociatedCertificateChain();
      if ((x509 == null) || (x509.length < 1)) {
        throw new SSLException("Cannot initialize RMI-SSL Server: no KeyMaterial!");
      }
      setServer(defaultServer);
    }
    setDefaultClient(defaultClient);
  }
  
  public void setServer(ServerSocketFactory f)
    throws GeneralSecurityException, IOException
  {
    sslServer = f;
    if ((f instanceof SSLServer))
    {
      HostnameVerifier VERIFIER = HostnameVerifier.DEFAULT_AND_LOCALHOST;
      
      SSLServer ssl = (SSLServer)f;
      X509Certificate[] chain = ssl.getAssociatedCertificateChain();
      String[] cns = Certificates.getCNs(chain[0]);
      String[] subjectAlts = Certificates.getDNSSubjectAlts(chain[0]);
      LinkedList names = new LinkedList();
      if ((cns != null) && (cns.length > 0)) {
        names.add(cns[0]);
      }
      if ((subjectAlts != null) && (subjectAlts.length > 0)) {
        names.addAll(Arrays.asList(subjectAlts));
      }
      String rmiHostName = System.getProperty("java.rmi.server.hostname");
      if (rmiHostName != null)
      {
        try
        {
          VERIFIER.check(rmiHostName, cns, subjectAlts);
        }
        catch (SSLException ssle)
        {
          String s = ssle.toString();
          throw new SSLException("java.rmi.server.hostname of " + rmiHostName + " conflicts with SSL Server Certificate: " + s);
        }
      }
      else
      {
        boolean hopingForBest = false;
        if (names.size() == 1)
        {
          String name = (String)names.get(0);
          if (!name.startsWith("*"))
          {
            System.setProperty("java.rmi.server.hostname", name);
            log.warn("commons-ssl 'java.rmi.server.hostname' set to '" + name + "' as found in my SSL Server Certificate.");
            hopingForBest = true;
          }
        }
        if (!hopingForBest)
        {
          Set s = getMyInternetFacingIPs();
          Iterator it = s.iterator();
          while (it.hasNext())
          {
            String name = (String)it.next();
            try
            {
              VERIFIER.check(name, cns, subjectAlts);
              System.setProperty("java.rmi.server.hostname", name);
              log.warn("commons-ssl 'java.rmi.server.hostname' set to '" + name + "' as found by reverse-dns against my own IP.");
              hopingForBest = true;
            }
            catch (SSLException ssle) {}
          }
        }
        if (!hopingForBest) {
          throw new SSLException("'java.rmi.server.hostname' not present.  Must work with my SSL Server Certificate's CN field: " + names);
        }
      }
    }
    trustOurself();
  }
  
  public void setLocalBindAddress(String localBindAddress)
  {
    this.localBindAddress = localBindAddress;
  }
  
  public void setAnonymousPort(int port)
  {
    anonymousPort = port;
  }
  
  public void setDefaultClient(SocketFactory f)
    throws GeneralSecurityException, IOException
  {
    defaultClient = f;
    trustOurself();
  }
  
  public void setClient(String host, SocketFactory f)
    throws GeneralSecurityException, IOException
  {
    if ((f != null) && (sslServer != null))
    {
      boolean clientIsCommonsSSL = f instanceof SSLClient;
      boolean serverIsCommonsSSL = sslServer instanceof SSLServer;
      if ((clientIsCommonsSSL) && (serverIsCommonsSSL))
      {
        SSLClient c = (SSLClient)f;
        SSLServer s = (SSLServer)sslServer;
        trustEachOther(c, s);
      }
    }
    Set names = hostnamePossibilities(host);
    Iterator it = names.iterator();
    synchronized (this)
    {
      while (it.hasNext()) {
        clientMap.put(it.next(), f);
      }
    }
  }
  
  public void removeClient(String host)
  {
    Set names = hostnamePossibilities(host);
    Iterator it = names.iterator();
    synchronized (this)
    {
      while (it.hasNext()) {
        clientMap.remove(it.next());
      }
    }
  }
  
  public synchronized void removeClient(SocketFactory sf)
  {
    Iterator it = clientMap.entrySet().iterator();
    while (it.hasNext())
    {
      Map.Entry entry = (Map.Entry)it.next();
      Object o = entry.getValue();
      if (sf.equals(o)) {
        it.remove();
      }
    }
  }
  
  private Set hostnamePossibilities(String host)
  {
    host = host != null ? host.toLowerCase().trim() : "";
    if ("".equals(host)) {
      return Collections.EMPTY_SET;
    }
    TreeSet names = new TreeSet();
    names.add(host);
    try
    {
      InetAddress[] addresses = InetAddress.getAllByName(host);
      for (int i = 0; i < addresses.length; i++)
      {
        String name1 = addresses[i].getHostName();
        String name2 = addresses[i].getHostAddress();
        names.add(name1.trim().toLowerCase());
        names.add(name2.trim().toLowerCase());
      }
    }
    catch (UnknownHostException uhe) {}
    try
    {
      host = InetAddress.getByName(host).getHostAddress();
      
      host = InetAddress.getByName(host).getHostName();
      names.add(host.trim().toLowerCase());
      InetAddress[] addresses = InetAddress.getAllByName(host);
      for (int i = 0; i < addresses.length; i++)
      {
        String name1 = addresses[i].getHostName();
        String name2 = addresses[i].getHostAddress();
        names.add(name1.trim().toLowerCase());
        names.add(name2.trim().toLowerCase());
      }
    }
    catch (UnknownHostException uhe) {}
    return names;
  }
  
  private void trustOurself()
    throws GeneralSecurityException, IOException
  {
    if ((defaultClient == null) || (sslServer == null)) {
      return;
    }
    boolean clientIsCommonsSSL = defaultClient instanceof SSLClient;
    boolean serverIsCommonsSSL = sslServer instanceof SSLServer;
    if ((clientIsCommonsSSL) && (serverIsCommonsSSL))
    {
      SSLClient c = (SSLClient)defaultClient;
      SSLServer s = (SSLServer)sslServer;
      trustEachOther(c, s);
    }
  }
  
  private void trustEachOther(SSLClient client, SSLServer server)
    throws GeneralSecurityException, IOException
  {
    if ((client != null) && (server != null))
    {
      X509Certificate[] certs = server.getAssociatedCertificateChain();
      if ((certs != null) && (certs[0] != null))
      {
        TrustMaterial tm = new TrustMaterial(certs[0]);
        client.addTrustMaterial(tm);
      }
      certs = client.getAssociatedCertificateChain();
      if ((certs != null) && (certs[0] != null))
      {
        TrustMaterial tm = new TrustMaterial(certs[0]);
        server.addTrustMaterial(tm);
      }
    }
  }
  
  public ServerSocketFactory getServer()
  {
    return sslServer;
  }
  
  public SocketFactory getDefaultClient()
  {
    return defaultClient;
  }
  
  public synchronized SocketFactory getClient(String host)
  {
    host = host != null ? host.trim().toLowerCase() : "";
    return (SocketFactory)clientMap.get(host);
  }
  
  public synchronized ServerSocket createServerSocket(int port)
    throws IOException
  {
    if (port == 0) {
      port = anonymousPort;
    }
    Integer key = new Integer(port);
    ServerSocket ss = (ServerSocket)serverSockets.get(key);
    if ((ss == null) || (ss.isClosed()))
    {
      if ((ss != null) && (ss.isClosed())) {
        System.out.println("found closed server on port: " + port);
      }
      log.debug("commons-ssl RMI server-socket: listening on port " + port);
      ss = sslServer.createServerSocket(port);
      serverSockets.put(key, ss);
    }
    return ss;
  }
  
  public Socket createSocket(String host, int port)
    throws IOException
  {
    host = host != null ? host.trim().toLowerCase() : "";
    InetAddress local = null;
    String bindAddress = localBindAddress;
    if (bindAddress == null)
    {
      bindAddress = System.getProperty("java.rmi.server.hostname");
      if (bindAddress != null)
      {
        local = InetAddress.getByName(bindAddress);
        if (!local.isLoopbackAddress())
        {
          String ip = local.getHostAddress();
          Set myInternetIps = getMyInternetFacingIPs();
          if (!myInternetIps.contains(ip))
          {
            log.warn("Cannot bind to " + ip + " since it doesn't exist on this machine.");
            
            local = null;
            bindAddress = null;
          }
        }
      }
    }
    if (bindAddress == null) {
      bindAddress = getMyDefaultIP();
    }
    if ((local == null) && (bindAddress != null))
    {
      local = InetAddress.getByName(bindAddress);
      localBindAddress = local.getHostName();
    }
    SocketFactory sf;
    synchronized (this)
    {
      sf = (SocketFactory)clientMap.get(host);
    }
    if (sf == null) {
      sf = defaultClient;
    }
    Socket s = null;
    SSLSocket ssl = null;
    int soTimeout = Integer.MIN_VALUE;
    IOException reasonForPlainSocket = null;
    boolean tryPlain = false;
    try
    {
      s = sf.createSocket(host, port, local, 0);
      soTimeout = s.getSoTimeout();
      Object localObject2;
      if (!(s instanceof SSLSocket)) {
        return s;
      }
      ssl = (SSLSocket)s;
      
      ssl.setSoTimeout(15000);
      ssl.getSession().getPeerCertificates();
      
      ssl.setSoTimeout(soTimeout);
      return ssl;
    }
    catch (IOException ioe)
    {
      Throwable t = ioe;
      while ((!tryPlain) && (t != null))
      {
        tryPlain = (tryPlain) || ((t instanceof EOFException));
        tryPlain = (tryPlain) || ((t instanceof InterruptedIOException));
        tryPlain = (tryPlain) || ((t instanceof SSLProtocolException));
        t = t.getCause();
      }
      if ((!tryPlain) && ((ioe instanceof SSLPeerUnverifiedException)))
      {
        try
        {
          if (ssl != null) {
            ssl.startHandshake();
          }
        }
        catch (IOException ioe2)
        {
          ioe = ioe2;
          t = ioe2;
        }
        while ((!tryPlain) && (t != null))
        {
          tryPlain = (tryPlain) || ((t instanceof EOFException));
          tryPlain = (tryPlain) || ((t instanceof InterruptedIOException));
          tryPlain = (tryPlain) || ((t instanceof SSLProtocolException));
          t = t.getCause();
        }
      }
      if (!tryPlain)
      {
        log.debug("commons-ssl RMI-SSL failed: " + ioe);
        throw ioe;
      }
      reasonForPlainSocket = ioe;
    }
    finally
    {
      boolean isPlain = (tryPlain) || ((s != null) && (ssl == null));
      String socket = isPlain ? "RMI plain-socket " : "RMI ssl-socket ";
      String localIP = local != null ? local.getHostAddress() : "ANY";
      StringBuffer buf = new StringBuffer(64);
      buf.append(socket);
      buf.append(localIP);
      buf.append(" --> ");
      buf.append(host);
      buf.append(":");
      buf.append(port);
      log.debug(buf.toString());
    }
    SocketFactory sf = plainClient;
    s = JavaImpl.connect(null, sf, host, port, local, 0, 15000, null);
    if (soTimeout != Integer.MIN_VALUE) {
      s.setSoTimeout(soTimeout);
    }
    try
    {
      setClient(host, plainClient);
      String msg = "RMI downgrading from SSL to plain-socket for " + host + " because of " + reasonForPlainSocket;
      log.warn(msg, reasonForPlainSocket);
    }
    catch (GeneralSecurityException gse)
    {
      throw new RuntimeException("can't happen because we're using plain socket", gse);
    }
    return s;
  }
  
  public static String getMyDefaultIP()
  {
    String anInternetIP = "64.111.122.211";
    String ip = null;
    try
    {
      DatagramSocket dg = new DatagramSocket();
      dg.setSoTimeout(250);
      
      InetAddress addr = InetAddress.getByName(anInternetIP);
      dg.connect(addr, 12345);
      InetAddress localAddr = dg.getLocalAddress();
      ip = localAddr.getHostAddress();
      
      dg.close();
      if ((localAddr.isLoopbackAddress()) || ("0.0.0.0".equals(ip))) {
        ip = null;
      }
    }
    catch (IOException ioe)
    {
      log.debug("Bogus UDP didn't work: " + ioe);
    }
    return ip;
  }
  
  public static SortedSet getMyInternetFacingIPs()
    throws SocketException
  {
    TreeSet set = new TreeSet();
    Enumeration en = NetworkInterface.getNetworkInterfaces();
    while (en.hasMoreElements())
    {
      NetworkInterface ni = (NetworkInterface)en.nextElement();
      Enumeration en2 = ni.getInetAddresses();
      while (en2.hasMoreElements())
      {
        InetAddress addr = (InetAddress)en2.nextElement();
        if (!addr.isLoopbackAddress())
        {
          String ip = addr.getHostAddress();
          String reverse = addr.getHostName();
          
          set.add(ip);
          
          set.add(reverse);
        }
      }
    }
    return set;
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.RMISocketFactoryImpl
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class SSL
{
  private static final String[] KNOWN_PROTOCOLS = { "TLSv1", "SSLv3", "SSLv2", "SSLv2Hello" };
  private static final String[] SUPPORTED_CIPHERS;
  public static final SortedSet KNOWN_PROTOCOLS_SET;
  public static final SortedSet SUPPORTED_CIPHERS_SET;
  public static final String SSL_RSA_WITH_RC4_128_SHA = "SSL_RSA_WITH_RC4_128_SHA";
  public static final String SSL_RSA_WITH_3DES_EDE_CBC_SHA = "SSL_RSA_WITH_3DES_EDE_CBC_SHA";
  public static final String SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA = "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA";
  public static final String SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA = "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA";
  public static final String TLS_RSA_WITH_AES_128_CBC_SHA = "TLS_RSA_WITH_AES_128_CBC_SHA";
  public static final String TLS_DHE_RSA_WITH_AES_128_CBC_SHA = "TLS_DHE_RSA_WITH_AES_128_CBC_SHA";
  public static final String TLS_DHE_DSS_WITH_AES_128_CBC_SHA = "TLS_DHE_DSS_WITH_AES_128_CBC_SHA";
  public static final String TLS_RSA_WITH_AES_256_CBC_SHA = "TLS_RSA_WITH_AES_256_CBC_SHA";
  public static final String TLS_DHE_RSA_WITH_AES_256_CBC_SHA = "TLS_DHE_RSA_WITH_AES_256_CBC_SHA";
  public static final String TLS_DHE_DSS_WITH_AES_256_CBC_SHA = "TLS_DHE_DSS_WITH_AES_256_CBC_SHA";
  
  static
  {
    TreeSet ts = new TreeSet(Collections.reverseOrder());
    ts.addAll(Arrays.asList(KNOWN_PROTOCOLS));
    KNOWN_PROTOCOLS_SET = Collections.unmodifiableSortedSet(ts);
    
    SSLSocketFactory s = (SSLSocketFactory)SSLSocketFactory.getDefault();
    ts = new TreeSet();
    SUPPORTED_CIPHERS = s.getSupportedCipherSuites();
    Arrays.sort(SUPPORTED_CIPHERS);
    ts.addAll(Arrays.asList(SUPPORTED_CIPHERS));
    SUPPORTED_CIPHERS_SET = Collections.unmodifiableSortedSet(ts);
  }
  
  private Object sslContext = null;
  private int initCount = 0;
  private SSLSocketFactory socketFactory = null;
  private SSLServerSocketFactory serverSocketFactory = null;
  private HostnameVerifier hostnameVerifier = HostnameVerifier.DEFAULT;
  private boolean isSecure = true;
  private boolean checkHostname = true;
  private boolean checkCRL = true;
  private boolean checkExpiry = true;
  private boolean useClientMode = false;
  private boolean useClientModeDefault = true;
  private int soTimeout = 86400000;
  private int connectTimeout = 3600000;
  private TrustChain trustChain = null;
  private KeyMaterial keyMaterial = null;
  private String[] enabledCiphers = null;
  private String[] enabledProtocols = null;
  private String defaultProtocol = "TLS";
  private X509Certificate[] currentServerChain;
  private X509Certificate[] currentClientChain;
  private boolean wantClientAuth = true;
  private boolean needClientAuth = false;
  private SSLWrapperFactory sslWrapperFactory = SSLWrapperFactory.NO_WRAP;
  private Map dnsOverride;
  protected final boolean usingSystemProperties;
  
  public SSL()
    throws GeneralSecurityException, IOException
  {
    boolean usingSysProps = false;
    Properties props = System.getProperties();
    boolean ksSet = props.containsKey("javax.net.ssl.keyStore");
    boolean tsSet = props.containsKey("javax.net.ssl.trustStore");
    if (ksSet)
    {
      String path = System.getPro
1 2 3 4 5 6 7 8 9 10 11 12 13

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2017. Infinite Loop Ltd