elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Sigue las noticias más importantes de seguridad informática en el Twitter! de elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  Certificados autofirmados Java
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Certificados autofirmados Java  (Leído 5,152 veces)
alzehimer_cerebral


Desconectado Desconectado

Mensajes: 513



Ver Perfil WWW
Certificados autofirmados Java
« en: 8 Febrero 2011, 20:56 pm »

Hola foro,

llevo bastante tiempo intentando programar una conexion Https con certificados autofirmados..  Haber si alguien me puede aclarar un par de dudas para rematar las clases.

Los clientes que utilizan las clases que posteo a continuacion tiene el certificado autofirmado añadido al cacerts (key store por defecto de la maquina virtual Java donde se encuentran los certificados de confianza).

De momento estoy intentando conectar a dicho un servidor mediante Https para descargar archivos xml. La duda que tengo es si la interfaz X509TrustManager permite realizar conexiones con certificados autofirmados que han sido autofirmados (Lo pregunto porque he leido en algunos sitios que no se puede, pero me surje la duda de que tal vez si se añaden al cacerts si lo permite).

Si se diera el caso de que dicha interfaz no permite las conexiones con certificados autofirmados entonces que interfaz debo utilizar???

Os dejo las clases que estoy implementando por si os sirven de ayuda:

Código
  1. public class Https {
  2.  
  3.  
  4.  
  5.  
  6.     public static void main(String args[]) throws MalformedURLException, NoSuchAlgorithmException, Exception {
  7.  
  8.        //System.setProperty("javax.net.ssl.trustStore","tomcatKeystore");
  9.        //System.setProperty("javax.net.ssl.keyStore", "/usr/jdk1.5.0_11/jre/lib/security/cacerts");
  10.        //System.setProperty("javax.net.ssl.keyStorePassword","changeit");
  11.  
  12.        // java -Djavax.net.ssl.trustStore=truststore -Djavax.net.ssl.trustStorePassword=123456 MyApp
  13.  
  14.        //System.setProperty("javax.net.ssl.trustStore","C:\\Archivos de Programa\\Java\\jre1.6.0_07\\lib\\security\\cacerts");
  15.        //System.setProperty("javax.net.ssl.trustStorePassword","changeit"");
  16.  
  17.        //Para aceptar certificados que no estan en el keystore del cliente
  18.        SSLContext sc = SSLContext.getInstance("TLS");
  19.        sc.init(null, new TrustManager[] { new SimpleTrustManager1() }, null);
  20.        SSLSocketFactory ssf = sc.getSocketFactory();
  21.  
  22.        System.out.println("Antes URL");
  23.        URL url = new URL("https://loquesea.es");
  24.        HttpsURLConnection urlConection = (HttpsURLConnection) url.openConnection();
  25.  
  26.        urlConection.setSSLSocketFactory(ssf);
  27.  
  28.  
  29.        urlConection.setHostnameVerifier(new SimpleHostnameVerifier());
  30.  
  31.        //urlConection.connect();
  32.  
  33.  
  34.        System.out.println("Antes INPUTSTREAM");
  35.        InputStream is = urlConection.getInputStream();
  36.        System.out.println("Despues INPUTSTREAM");
  37.  
  38.  
  39.        System.out.println("Antes leer fichero");
  40.        File fichero = new File("pruebas_ssl.xml");
  41.        FileOutputStream fos = new FileOutputStream(fichero);
  42.        byte[] bytes = new byte[1024];
  43.        int leidos;
  44.        while ((leidos = is.read(bytes)) != -1){
  45.            fos.write(bytes, 0, leidos);
  46.        }
  47.        fos.close();
  48.        is.close();
  49.  
  50.  
  51.     }
  52.  
  53. }
  54.  
  55.  
  56.  
  57.  
  58. public class SimpleTrustManager1 implements X509TrustManager   {
  59.  
  60.    private Set<X509Certificate> certs = new HashSet<X509Certificate>();
  61.  
  62.  
  63.    public SimpleTrustManager1() throws Exception {
  64.        System.out.println("Entra en constructor SimpleTrustManager1()");
  65.        //Falta Cargar los certificados del Keystore en el atributo certs
  66.        KeyStore ks = KeyStore.getInstance("JKS");
  67.        String cacerts = "C:\\Archivos de Programa\\Java\\jre1.6.0_07\\lib\\security\\cacerts";
  68.        FileInputStream stream = new FileInputStream(new File(cacerts));
  69.        ks.load(stream, "changeit".toCharArray());
  70.        stream.close();
  71.  
  72.        //Comprobamos si cacerts se ha cargado correctamente en el KeyStore
  73.  
  74.  
  75.  
  76.        // KeyStore.TrustedCertificateEntry certificateEntry = (KeyStore.TrustedCertificateEntry)ks.getCertificateAlias("alias_certificado");
  77.  
  78.        //certs.addAll();
  79.  
  80.   }
  81.  
  82.   public void checkClientTrusted(X509Certificate[] chain, String authType)
  83.      throws CertificateException {
  84.   }
  85.  
  86.   public X509Certificate[] getAcceptedIssuers() {
  87.        System.out.println("Entra en getAcceptedIssuers");
  88.     return certs.toArray(new X509Certificate[certs.size()]);
  89.   }
  90.  
  91.   public void checkServerTrusted(X509Certificate[] chain, String authType)
  92.      throws CertificateException {
  93.        Boolean trusted =false;
  94.        //try {
  95.  
  96.            System.out.println("chain.length="+chain.length);
  97.            System.out.println("authType:" + authType);
  98.  
  99.            for (int i = 0; i < chain.length; i++) {
  100.                System.out.println("Entra en checkServerTrusted" + i);
  101.                X509Certificate aux = chain[i];
  102.                Principal prueba=aux.getIssuerDN();
  103.                System.out.println(prueba.getName());
  104.  
  105.                if (certs.contains(chain[i])) {
  106.                    System.out.println("certs.contains(chain[i])");
  107.                    trusted=true;
  108.                    return;
  109.                }
  110.            }
  111.  
  112.            if(!trusted){
  113.  
  114.                int x = JOptionPane.showConfirmDialog(null, "El servidor " + chain[0].getIssuerDN() + " no se puede verificar. " + "¿Desde realizar la conexión de todas formas?", "TITULO", JOptionPane.YES_NO_OPTION);
  115.                if (x == JOptionPane.OK_OPTION) {
  116.                //throw new CertificateException("La clave no está en el trustore");
  117.                certs.add(chain[0]);
  118.                trusted=true;
  119.                System.out.println("Despues certs.add(chain[0]); ");
  120.                }
  121.  
  122.                else{
  123.  
  124.                }
  125.                /**System.out.println("El servidor " + chain[0].getIssuerDN() + " no se puede verificar. " + "¿Desde realizar la conexión de todas formas?");
  126.                 //Scanner s = new Scanner(System.in).useDelimiter("\r\n");
  127.                 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  128.                 String linea = br.readLine();
  129.                 System.out.println("Despues Scanner");
  130.                 //String opcion = s.next();
  131.                 System.out.println("opcion:" + linea);
  132.                 if (!linea.equalsIgnoreCase("si")) {
  133.                     throw new CertificateException("La clave no está en el trustore");
  134.                 }
  135.  
  136.                 * */
  137.                /**
  138.             } catch (IOException ex) {
  139.                 Logger.getLogger(SimpleTrustManager1.class.getName()).log(Level.SEVERE, null, ex);
  140.             }**/
  141.  
  142.       }
  143.   }
  144.  
  145.  
  146. }
  147.  
  148.  
  149.  
  150. public class SimpleHostnameVerifier implements HostnameVerifier {
  151.  
  152.    @Override
  153.  public boolean verify(String hostname, SSLSession session) {
  154.     System.out.println("Host: "+hostname);
  155.     try {
  156.        X509Certificate cert = (X509Certificate)session.getPeerCertificates()[0];
  157.        System.out.println("DN:"+cert.getIssuerDN());
  158.     } catch (SSLPeerUnverifiedException e) {
  159.        e.printStackTrace();
  160.     }
  161.     return true;
  162.  }
  163.  
  164.  
  165. }
  166.  

Cada clase se encuentra en un fichero por lo cual no se pueden compartir variables.

Cualquier aclaracion para encaminarme sera mas que agradecida.

Gracias de antemano.

Salu2.

alzehimer_cerebral


« Última modificación: 16 Febrero 2011, 12:17 pm por alzehimer_cerebral » En línea

Servicios Informaticos Valencia - www.ag-solutions.es
Mi blog - www.alvarogarciasolano.com
alzehimer_cerebral


Desconectado Desconectado

Mensajes: 513



Ver Perfil WWW
Re: Certificados autofirmados Java
« Respuesta #1 en: 16 Febrero 2011, 12:12 pm »

He avanzado un poco en la materia de los certificados..  Y apuedo confirmar que si se pueden utilizar certificados autofirmados con X09TrustManager, tambien se como cargar el contenido de cacerts y buscar si se encuentra un cierto certificado.  La cuestion es que me interesa que si un certificado autofirmado no se encuentra en cacerts que se le pregunte al usuario si desea aceptarlo o no..

Lo he implementado dentro de la interfaz X509TrustManager en el metodo checkServerTrusted(X509Certificate[] chain, String authType).

El metodo quedaria asi:

Código
  1.  
  2. public void checkServerTrusted(X509Certificate[] chain, String authType)
  3.      throws CertificateException {
  4.        Boolean trusted =false;
  5.        //try {
  6.  
  7.            System.out.println("chain.length="+chain.length);
  8.            System.out.println("authType:" + authType);
  9.  
  10.            X509Certificate aux= null;
  11.  
  12.            for (int i = 0; i < chain.length; i++) {
  13.                System.out.println("Entra en checkServerTrusted" + i);
  14.                aux = chain[i];
  15.                Principal prueba=aux.getIssuerDN();
  16.                System.out.println("IssuerDN:" + prueba.getName());
  17.  
  18.                if (certs.contains(chain[i])) {
  19.                    System.out.println("certs.contains(chain[i])");
  20.                    trusted=true;
  21.                    return;
  22.                }
  23.            }
  24.  
  25.            if(!trusted){
  26.  
  27.                int x = JOptionPane.showConfirmDialog(null, "El servidor " + chain[0].getIssuerDN() + " no se puede verificar. " + "¿Desde realizar la conexión de todas formas?", "TITULO", JOptionPane.YES_NO_OPTION);
  28.                if (x == JOptionPane.OK_OPTION) {
  29.                //throw new CertificateException("La clave no está en el trustore");
  30.                certs.add(aux);
  31.                trusted=true;
  32.                System.out.println("Despues certs.add(chain[0]); ");
  33.                }
  34.  
  35.                else{
  36.                    System.out.println("No se quiere confiar en el certificado y por lo tanto no se debe proceder con la descarga del fichero");
  37.  
  38.                }
  39.                /**System.out.println("El servidor " + chain[0].getIssuerDN() + " no se puede verificar. " + "¿Desde realizar la conexión de todas formas?");
  40.                 //Scanner s = new Scanner(System.in).useDelimiter("\r\n");
  41.                 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  42.                 String linea = br.readLine();
  43.                 System.out.println("Despues Scanner");
  44.                 //String opcion = s.next();
  45.                 System.out.println("opcion:" + linea);
  46.                 if (!linea.equalsIgnoreCase("si")) {
  47.                     throw new CertificateException("La clave no está en el trustore");
  48.                 }
  49.  
  50.                 * */
  51.                /**
  52.             } catch (IOException ex) {
  53.                 Logger.getLogger(SimpleTrustManager1.class.getName()).log(Level.SEVERE, null, ex);
  54.             }**/
  55.  
  56.       }
  57.   }
  58.  
  59.  
  60. }
  61.  
  62.  

Mi duda es la siguiente: tengo la clase Https (la del post anterior) en la cual dependiendo de la accion del usuario de aceptar o no el certificado se debe proceder con la descarga...

La verdad que no se como hacer para desde el main saber si el usuario acepta o deniega el certificado.  Deberia usar una variable global??

Comentarme cosas please...

Salu2.

alzehimer_cerebral


« Última modificación: 16 Febrero 2011, 12:19 pm por alzehimer_cerebral » En línea

Servicios Informaticos Valencia - www.ag-solutions.es
Mi blog - www.alvarogarciasolano.com
novanoticia

Desconectado Desconectado

Mensajes: 5


Ver Perfil
Re: Certificados autofirmados Java
« Respuesta #2 en: 17 Diciembre 2011, 09:13 am »

hola,
he puesto un ejemplo en c# de como pasar un certificado de un almacen a otro y instalarlo en en servidor IIS:
este es el enlace:
http://foro.elhacker.net/criptografia/certificados_digitales_autofirmados-t316228.0.html;msg1696344#msg1696344
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Certificados SSL
Criptografía
kerberos01 1 3,468 Último mensaje 10 Agosto 2010, 23:52 pm
por el-brujo
Certificados digitales autofirmados « 1 2 »
Criptografía
alzehimer_cerebral 14 22,060 Último mensaje 19 Diciembre 2011, 02:19 am
por APOKLIPTICO
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines