Changeset 4123


Ignore:
Timestamp:
04/25/11 09:43:20 (13 years ago)
Author:
rafaelraymundo
Message:

Ticket #1739 - Login com certificado em atributo customizável.

Location:
branches/2.2.0.1
Files:
5 edited

Legend:

Unmodified
Added
Removed
  • branches/2.2.0.1/preferences/handlecertificate.php

    r3991 r4123  
    1616if($_POST['certificado']) 
    1717    { 
     18        $GLOBALS['phpgw_info']['flags']['app_header'] = lang('Digital Certificate Registration'); 
     19        $GLOBALS['phpgw']->common->phpgw_header(); 
     20        echo parse_navbar(); 
     21        echo '<form id="answerForm" name="answerForm" method="POST" action="index.php" >'; 
     22        echo '<BR/><BR/><BR/>'; 
     23         
    1824        require_once('../security/classes/CertificadoB.php'); 
    1925        require_once('../security/classes/Verifica_Certificado.php'); 
     
    2531        if (!$c->apresentado) 
    2632            { 
    27                echo '2'.chr(0x0D).chr(0x0A).lang('Fail to get certificate'); 
    28                exit(); 
     33                echo '<div align="center"><h2>'.lang('Fail to get certificate').'</h2>'; 
     34                exit(); 
    2935            } 
    3036        $b = new Verifica_Certificado($c->dados,$cert); 
     
    3743                        $msg .= "\n" . $linha; 
    3844                   } 
    39                echo $msg; 
     45                   echo '<div align="center"><h2>'.$msg.'</h2>'; 
    4046               exit(); 
    4147            } 
     
    5460        if (!$ds) 
    5561             { 
    56                 echo '4'.chr(0x0D).chr(0x0A).lang('Failure when get user data to login'); 
     62                 echo '<div align="center"><h2>'.lang('Failure when get user data to login').'</h2>'; 
    5763                exit(); 
    5864             } 
     
    7783        if($info["count"]!=1) 
    7884            { 
    79                 echo '5'.chr(0x0D).chr(0x0A).lang('Invalid data from users directory').'('.$cert_atrib_cpf.' = ' . $c->dados['2.16.76.1.3.1']['CPF'] . ')'; 
     85                echo '<div align="center"><h2>'.lang('Invalid data from users directory').'('.$cert_atrib_cpf.' = ' . $c->dados['2.16.76.1.3.1']['CPF'] . ')'.'</h2>'; 
    8086                ldap_close($ds); 
    8187                exit(); 
    8288            } 
    83         if($info[0]["userCertificate"][0] && $cert == $info[0]["userCertificate"][0] ) 
     89            if($info[0]["uid"][0] != $GLOBALS['phpgw_info']['user']['userid']) 
     90            { 
     91                echo '<div align="center"><h2>'.lang('Invalid data from users directory').'('.$cert_atrib_cpf.' = ' . $c->dados['2.16.76.1.3.1']['CPF'] . ' - ' . $info[0]["uid"][0] . ' - ' . $GLOBALS['phpgw_info']['user']['userid'] . ')'.'</h2>'; 
     92                ldap_close($ds); 
     93                exit(); 
     94            } 
     95            if($info[0]["userCertificate"][0] && $cert == $info[0]["userCertificate"][0] ) 
    8496            { 
    8597                //echo '0'.chr(0x0D).chr(0x0A).$info[0]["uid"][0].chr(0x0D).chr(0x0A).$info[0]["cryptpassword"][0]; 
    86                 echo '6'.chr(0x0D).chr(0x0A).lang('Certificate already registered'); 
     98                echo '<div align="center"><h2>'.lang('Certificate already registered').'</h2>'; 
    8799                ldap_close($ds); 
    88100                exit(); 
     
    108120        if(!ldap_modify($ds,$aux1,$user_info)) 
    109121            { 
    110                 echo '7'.chr(0x0D).chr(0x0A).lang('Error in Certificate registration'). '  -  ' . $aux1; 
    111             } 
    112         else 
    113             { 
    114                 echo '0'.chr(0x0D).chr(0x0A).lang('To conclude your Certificate registration change your password'); 
    115             } 
     122                echo '<div align="center"><h2>'.lang('Error in Certificate registration'). '  -  ' . $aux1.'</h2>'; 
     123            } 
     124        else 
     125            { 
     126                echo '<div align="center"><h2>'.lang('To conclude your Certificate registration change your password').'</h2>'; 
     127            } 
     128 
     129            echo '<h2><img style="border:0px;margin:31px 0px 58px 0px;" src="../phpgwapi/templates/default/images/acao.gif" /></h2>'; 
     130            echo '<input type="submit" name="ok" value="' . lang('ok') . '" ></div></form>'; 
     131            $GLOBALS['phpgw']->common->phpgw_footer(); 
    116132        ldap_close($ds); 
    117133        exit(); 
     
    193209                                    </script>'; 
    194210                  echo $cod_applet; 
    195                   echo '<form method="POST" action="preferences" >'; 
     211                  echo '<form id="certificateForm" name="certificateForm" method="POST" action="handlecertificate.php" >'; 
    196212                  echo '<BR/><BR/><BR/>'; 
    197213                  echo '<div align="center"><h2>'.lang('Getting your Certificate').'</h2>'; 
    198214                  echo '<h2><img style="border:0px;margin:31px 0px 58px 0px;" src="../phpgwapi/templates/default/images/acao.gif" /></h2>'; 
    199                   echo '<input type="submit" name="cancel" value="' . lang('cancel') . '" ></div>'; 
     215                  echo '<input type="hidden" name="certificado" value="" />'; 
     216                  echo '<input type="submit" name="cancel" value="' . lang('cancel') . '" ></div></form>'; 
    200217                  $GLOBALS['phpgw']->common->phpgw_footer(); 
    201218        } 
  • branches/2.2.0.1/security/ExpressoCert/src/br/gov/serpro/cert/DigitalCertificate.java

    r3633 r4123  
    5858import java.io.OutputStreamWriter; 
    5959import java.security.AlgorithmParameters; 
     60import java.security.cert.CertificateEncodingException; 
    6061import java.util.regex.Matcher; 
    6162import java.util.regex.Pattern; 
     
    8990    private FileInputStream pkcs12Input; // stream da KeyStore pkcs12. Pode ser nulo. 
    9091    private String providerName; // Nome do SecurityProvider pkcs11 carregado. Pode ser nulo. 
    91     private String hostAddress; // Endereço do host, onde a página principal do 
     92    private URL pageAddress; // Endereço do host, onde a página principal do 
    9293    private static final String HOME_SUBDIR; // Subdiretório dentro do diretório home do usuário. Dependente de SO. 
    9394    private static final String EPASS_2000; // Caminho da biblioteca do token ePass2000. Dependente de SO. 
     
    164165     */ 
    165166    public DigitalCertificate() { 
    166         this.hostAddress = null; 
     167        this.pageAddress = null; 
    167168        this.parentFrame = null; 
    168169    } 
     
    173174     */ 
    174175    private DigitalCertificate(URL pageAddress) { 
    175         this.hostAddress = pageAddress.getHost(); 
     176        this.pageAddress = pageAddress; 
    176177        this.parentFrame = null; 
    177178    } 
    178179 
    179180    private DigitalCertificate(Frame parent) { 
    180         this.hostAddress = null; 
     181        this.pageAddress = null; 
    181182        this.parentFrame = parent; 
    182183    } 
     
    236237        this.selectedCertificateAlias = null; 
    237238        this.keyStore = null; 
    238         this.hostAddress = null; 
    239239        this.pkcs12Input = null; 
    240240        this.providerName = null; 
     
    647647     * Pega as credenciais de login do dono do certificado do serviço de verificação de certificados 
    648648     * @param   pin                     pin para acessar o token 
     649     * @param   where                   URL que será acessada para recuperar as credenciais 
    649650     * @return  resposta        Array de Strings em que: 
    650651     *                                          Indice 0: código de retorno; 
     
    656657     * @throws GeneralSecurityException 
    657658     */ 
    658     public String[] getCredentials(String pin) throws SSLHandshakeException, HttpException, IOException, GeneralSecurityException { 
     659 
     660    public String[] getCredentials(String pin, URL where) throws SSLHandshakeException, HttpException, IOException, GeneralSecurityException { 
    659661 
    660662        String[] resposta = null; 
     
    679681                    Integer.parseInt(System.getProperty("http.proxyPort"))); 
    680682        } 
    681         PostMethod httppost = new PostMethod("https://" + hostAddress + "/security/vercert.php"); 
    682  
     683 
     684        PostMethod httppost = new PostMethod(where.toExternalForm()); 
     685         
    683686        try { 
    684687            // Adiciona parâmetro certificado no método post, executa o método, pega a resposta do servidor 
     
    800803 
    801804    /** 
     805     * Get a PEM encoded instance of the user certificate 
     806     * @return PEM encoded Certificate 
     807     * @throws CertificateEncodingException 
     808     */ 
     809    public String getPEMCertificate() throws CertificateEncodingException { 
     810        return Base64Utils.der2pem(this.cert.getEncoded()); 
     811    } 
     812 
     813    /** 
    802814     * @param cert the cert to set 
    803815     */ 
  • branches/2.2.0.1/security/ExpressoCertLogin/src/LoginApplet.java

    r3633 r4123  
    4343        this.setup.addLanguageResource("ExpressoCertLoginMessages"); 
    4444    } 
     45     
     46    private boolean parseVercert(String[] answer){ 
     47        boolean tryAgain = false; 
     48        // Faz o login 
     49        if (setup.getParameter("debug").equalsIgnoreCase("true") && answer != null) { 
     50            System.out.println("Código de retorno: " + answer[0].trim()); 
     51        } 
     52 
     53        if (answer == null){ // Ação cancelada 
     54            tryAgain = false; 
     55            String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() 
     56                    + ":" + this.getCodeBase().getPort() + "/login.php"; 
     57            try { 
     58                this.getAppletContext().showDocument(new URL(redirect)); 
     59            } catch (MalformedURLException e) { 
     60                // TODO Bloco catch gerado automaticamente 
     61                if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
     62                    e.printStackTrace(); 
     63                } 
     64            } 
     65        } 
     66        else if (Integer.parseInt(answer[0].trim()) == 0) { 
     67 
     68            tryAgain = false; 
     69            // Pega usuário e senha de credentials[1] e credentials[2], respectivamente 
     70            // adiciona na página e faz o submit. 
     71            JSObject document = (JSObject) JSObject.getWindow(this).getMember("document"); 
     72            JSObject loginForm = (JSObject) document.getMember("flogin"); 
     73            JSObject loginField = (JSObject) loginForm.getMember("user"); 
     74            loginField.setMember("value", answer[1].trim()); 
     75 
     76            JSObject passwdField = (JSObject) loginForm.getMember("passwd"); 
     77            passwdField.setMember("value", answer[2].trim()); 
     78 
     79            loginForm.call("submit", null); 
     80            Thread.yield(); 
     81 
     82        } else if (Integer.parseInt(answer[0].trim()) == 6) { 
     83 
     84            tryAgain = false; 
     85 
     86            if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
     87                System.out.println("Mensagem de retorno: " + answer[1].trim()); 
     88            } 
     89 
     90            DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), answer[1].trim(), this.setup); 
     91 
     92            String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() 
     93                    + ":" + this.getCodeBase().getPort() + "/login.php?cd=98&ts=202"; 
     94            try { 
     95                this.getAppletContext().showDocument(new URL(redirect)); 
     96            } catch (MalformedURLException e) { 
     97                // TODO Bloco catch gerado automaticamente 
     98                if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 
     99                    e.printStackTrace(); 
     100                } 
     101            } 
     102        } else { 
     103            tryAgain = true; 
     104            dc.destroy(); 
     105            System.gc(); 
     106 
     107            if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
     108                System.out.println("Mensagem de retorno: " + answer[1].trim()); 
     109            } 
     110 
     111            // Mostra mensagem de erro para o usuário 
     112            DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), answer[1].trim(), this.setup); 
     113            Thread.yield(); 
     114        } 
     115 
     116        return tryAgain; 
     117    } 
     118 
     119    private boolean parseHandleCertificateResponse(String certificate){ 
     120         
     121        // Envia certificado 
     122         
     123        JSObject document = (JSObject) JSObject.getWindow(this).getMember("document"); 
     124        JSObject certificateForm = (JSObject) document.getMember("certificateForm"); 
     125        JSObject certificateField = (JSObject) certificateForm.getMember("certificado"); 
     126        certificateField.setMember("value", certificate); 
     127 
     128        // submit e cai fora 
     129        certificateForm.call("submit", null); 
     130        
     131        dc.destroy(); 
     132        System.gc(); 
     133        Thread.yield(); 
     134 
     135        return false; 
     136    } 
    45137 
    46138    /* (non-Javadoc) 
     
    57149 
    58150            // Cria uma instância de DigitalCertificate e a inicializa 
     151            // Aqui pega document base e verifica em que aplicação estamos. 
     152 
    59153            this.dc = new DigitalCertificate(this.getDocumentBase(), setup); 
    60154            useCertificate = dc.init(); 
    61             String[] returnCode = null; 
    62155 
    63156            try { 
     157 
     158                String redirect = ""; 
     159 
     160                // Testa em qual aplicação estamos. 
     161                URL documentURL = this.getDocumentBase(); 
     162 
     163                if (documentURL.getPath().matches(".*login.php$")){ 
     164                    redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() 
     165                        + ":" + this.getCodeBase().getPort() + "/login.php"; 
     166                } 
     167                else { 
     168                    redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() 
     169                        + ":" + this.getCodeBase().getPort() + "/preferences/index.php"; 
     170                } 
     171 
    64172                switch (useCertificate) { 
    65173                    case DigitalCertificate.KEYSTORE_DETECTED: 
    66174                        // Mostra PinNeedeDialog. 
    67175                        String pin = DialogBuilder.showPinDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), this.setup); 
     176                         
    68177                        if (pin != null) { 
    69178                            dc.openKeyStore(pin.toCharArray()); 
    70                             returnCode = dc.getCredentials(pin); 
    71  
    72                             // Faz o login 
    73                             if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    74                                 System.out.println("Código de retorno: " + returnCode[0].trim()); 
     179                            if (documentURL.getPath().matches(".*login.php$")){ 
     180                                tryAgain = parseVercert(dc.getCredentials(pin, new URL(this.getCodeBase().getProtocol()+"://" + 
     181                                    this.getCodeBase().getHost() + ":" + this.getCodeBase().getPort() + 
     182                                    "/security/vercert.php"))); 
    75183                            } 
    76  
    77                             if (returnCode == null){ // Ação cancelada 
    78                                 tryAgain = false; 
    79                                 String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php"; 
    80                                 try { 
    81                                     this.getAppletContext().showDocument(new URL(redirect)); 
    82                                 } catch (MalformedURLException e) { 
    83                                     // TODO Bloco catch gerado automaticamente 
    84                                     if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    85                                         e.printStackTrace(); 
    86                                     } 
    87                                 } 
     184                            else { 
     185                                tryAgain = parseHandleCertificateResponse(dc.getPEMCertificate()); 
    88186                            } 
    89                             else if (Integer.parseInt(returnCode[0].trim()) == 0) { 
    90  
    91                                 tryAgain = false; 
    92                                 // Pega usuário e senha de credentials[1] e credentials[2], respectivamente 
    93                                 // adiciona na página e faz o submit. 
    94                                 JSObject document = (JSObject) JSObject.getWindow(this).getMember("document"); 
    95                                 JSObject loginForm = (JSObject) document.getMember("flogin"); 
    96                                 JSObject loginField = (JSObject) loginForm.getMember("user"); 
    97                                 loginField.setMember("value", returnCode[1].trim()); 
    98  
    99                                 JSObject passwdField = (JSObject) loginForm.getMember("passwd"); 
    100                                 passwdField.setMember("value", returnCode[2].trim()); 
    101  
    102                                 loginForm.call("submit", null); 
    103                                 Thread.yield(); 
    104  
    105                             } else if (Integer.parseInt(returnCode[0].trim()) == 6) { 
    106  
    107                                 tryAgain = false; 
    108  
    109                                 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    110                                     System.out.println("Mensagem de retorno: " + returnCode[1].trim()); 
    111                                 } 
    112  
    113                                 DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), returnCode[1].trim(), this.setup); 
    114  
    115  
    116  
    117                                 String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php?cd=98&ts=202"; 
    118                                 try { 
    119                                     this.getAppletContext().showDocument(new URL(redirect)); 
    120                                 } catch (MalformedURLException e) { 
    121                                     // TODO Bloco catch gerado automaticamente 
    122                                     if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 
    123                                         e.printStackTrace(); 
    124                                     } 
    125                                 } 
    126                             } else { 
    127                                 tryAgain = true; 
    128                                 dc.destroy(); 
    129                                 System.gc(); 
    130  
    131                                 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 
    132                                     System.out.println("Mensagem de retorno: " + returnCode[1].trim()); 
    133                                 } 
    134  
    135                                 // Mostra mensagem de erro para o usuário 
    136                                 DialogBuilder.showMessageDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, this), returnCode[1].trim(), this.setup); 
    137                                 Thread.yield(); 
    138                             } 
    139187 
    140188                        } else { 
    141189 
     190                            // TODO: Notifica usuário 
    142191                            tryAgain = false; 
    143                             String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php"; 
    144192                            try { 
    145193                                this.getAppletContext().showDocument(new URL(redirect)); 
     
    155203                    default: 
    156204 
    157                         // Mostra Diálogo dizendo que token não foi encontrado 
     205                        // TODO: notifica usuário que token não foi encontrado 
    158206                        // ou repositório de chaves públicas não foi configurado. 
    159207                        // Tentar carregar token/keystore novamente? / Logon sem certificado digital? 
     
    167215                        System.gc(); 
    168216 
    169                         String redirect = this.getCodeBase().getProtocol() + "://" + this.getCodeBase().getHost() + "/login.php"; 
    170217                        try { 
    171218                            this.getAppletContext().showDocument(new URL(redirect)); 
Note: See TracChangeset for help on using the changeset viewer.