Changeset 3232
- Timestamp:
- 09/13/10 15:01:56 (14 years ago)
- Location:
- branches/2.2
- Files:
-
- 22 added
- 17 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/2.2/expressoMail1_2/js/draw_api.js
r3223 r3232 908 908 td_element22.setAttribute("width", "1%"); 909 909 td_element22.id = "td_message_signed_"+headers_msgs.msg_number; 910 910 alert(headers_msgs.ContentType); 911 911 switch(headers_msgs.ContentType) 912 912 { -
branches/2.2/security/ExpressoCert/src/br/gov/serpro/cert/DigitalCertificate.java
r1174 r3232 56 56 import br.gov.serpro.util.Base64Utils; 57 57 import com.sun.mail.util.BASE64DecoderStream; 58 import java.io.InputStreamReader; 59 import java.io.OutputStream; 60 import java.io.OutputStreamWriter; 61 import java.io.PipedInputStream; 62 import java.io.PipedOutputStream; 58 63 import java.security.AlgorithmParameters; 64 import javax.activation.CommandMap; 65 import javax.activation.MailcapCommandMap; 59 66 import javax.mail.BodyPart; 67 import javax.mail.internet.ContentType; 68 import javax.mail.internet.MimeUtility; 69 import javax.mail.internet.PreencodedMimeBodyPart; 60 70 import org.bouncycastle.asn1.ASN1InputStream; 61 71 import org.bouncycastle.asn1.DERObject; … … 71 81 * @author Mário César Kolling - mario.kolling@serpro.gov.br 72 82 */ 73 74 83 //TODO: Criar exceções para serem lançadas, entre elas DigitalCertificateNotLoaded 75 84 //TODO: Adicionar setup 76 77 85 public class DigitalCertificate { 78 86 79 87 private TokenCollection tokens; 80 private Certificate cert; // Certificado extraído da KeyStore. Pode ser nulo. 81 private KeyStore keyStore; // KeyStore que guarda o certificado do usuário. Pode ser nulo. 82 83 private Frame parentFrame; 88 private Certificate cert; // Certificado extraído da KeyStore. Pode ser nulo. 89 private KeyStore keyStore; // KeyStore que guarda o certificado do usuário. Pode ser nulo. 90 private Frame parentFrame; 84 91 private Setup setup; 85 86 // TODO: Transformar pkcs12Input em uma string ou URL com o caminho para a KeyStore pkcs12 87 private FileInputStream pkcs12Input; // stream da KeyStore pkcs12. Pode ser nulo. 88 private String providerName; // Nome do SecurityProvider pkcs11 carregado. Pode ser nulo. 89 private String hostAddress; // Endereço do host, onde a página principal do 90 91 private static final String HOME_SUBDIR; // Subdiretório dentro do diretório home do usuário. Dependente de SO. 92 private static final String EPASS_2000; // Caminho da biblioteca do token ePass2000. Dependente de SO. 93 94 private static final String CRLF = "\r\n"; // Separa campos na resposta do serviço de verificação de certificados 95 private static final String SUBJECT_ALTERNATIVE_NAME = "2.5.29.17"; // Não é mais utilizado. 96 private static final URL[] TRUST_STORES_URLS = new URL[3]; // URLs (file:/) das TrustStores, cacerts (jre), 97 // trusted.certs e trusted.jssecerts (home do usuário) 98 // Utilizadas para validação do certificado do servidor. 99 private static final String[] TRUST_STORES_PASSWORDS = null; // Senhas para cada uma das TrustStores, 100 // caso seja necessário. 101 private int keystoreStatus; 102 public static final int KEYSTORE_DETECTED = 0; 103 public static final int KEYSTORE_NOT_DETECTED = 1; 104 public static final int KEYSTORE_ALREADY_LOADED = 2; 105 106 /* 107 * Bloco estático que define os caminhos padrões da instalação da jre, 108 * do diretório home do usuário, e da biblioteca de sistema do token ePass2000, 109 * de acordo com o sistema operacional. 92 // TODO: Transformar pkcs12Input em uma string ou URL com o caminho para a KeyStore pkcs12 93 private FileInputStream pkcs12Input; // stream da KeyStore pkcs12. Pode ser nulo. 94 private String providerName; // Nome do SecurityProvider pkcs11 carregado. Pode ser nulo. 95 private String hostAddress; // Endereço do host, onde a página principal do 96 private static final String HOME_SUBDIR; // Subdiretório dentro do diretório home do usuário. Dependente de SO. 97 private static final String EPASS_2000; // Caminho da biblioteca do token ePass2000. Dependente de SO. 98 private static final String CRLF = "\r\n"; // Separa campos na resposta do serviço de verificação de certificados 99 private static final String SUBJECT_ALTERNATIVE_NAME = "2.5.29.17"; // Não é mais utilizado. 100 private static final URL[] TRUST_STORES_URLS = new URL[3]; // URLs (file:/) das TrustStores, cacerts (jre), 101 // trusted.certs e trusted.jssecerts (home do usuário) 102 // Utilizadas para validação do certificado do servidor. 103 private static final String[] TRUST_STORES_PASSWORDS = null; // Senhas para cada uma das TrustStores, 104 // caso seja necessário. 105 private int keystoreStatus; 106 public static final int KEYSTORE_DETECTED = 0; 107 public static final int KEYSTORE_NOT_DETECTED = 1; 108 public static final int KEYSTORE_ALREADY_LOADED = 2; 109 110 /* 111 * Bloco estático que define os caminhos padrões da instalação da jre, 112 * do diretório home do usuário, e da biblioteca de sistema do token ePass2000, 113 * de acordo com o sistema operacional. 114 */ 115 static { 116 117 Properties systemProperties = System.getProperties(); 118 Map<String, String> env = System.getenv(); 119 120 /* TODO: Testar a existência de vários drivers de dispositivos. Determinar qual deve ser utilizado 121 * e guardar em uma property no subdiretório home do usuário. 110 122 */ 111 static { 112 113 Properties systemProperties = System.getProperties(); 114 Map<String, String> env = System.getenv(); 115 116 /* TODO: Testar a existência de vários drivers de dispositivos. Determinar qual deve ser utilizado 117 * e guardar em uma property no subdiretório home do usuário. 118 */ 119 120 if (systemProperties.getProperty("os.name").equalsIgnoreCase("linux")){ 121 HOME_SUBDIR = "/.java/deployment/security"; 122 EPASS_2000 = "/usr/lib/libepsng_p11.so"; 123 } 124 else { 125 HOME_SUBDIR = "\\dados de aplicativos\\sun\\java\\deployment\\security"; 126 EPASS_2000 = System.getenv("SystemRoot")+"\\system32\\ngp11v211.dll"; 127 //EPASS_2000 = System.getenv("ProgramFiles")+"\\Gemplus\\GemSafe Libraries\\BIN\\gclib.dll"; 128 } 129 130 try { 131 if (systemProperties.getProperty("os.name").equalsIgnoreCase("linux")){ 132 TRUST_STORES_URLS[0] = new File(systemProperties.getProperty("java.home") 133 + "/lib/security/cacerts").toURI().toURL(); 134 TRUST_STORES_URLS[1] = new File(systemProperties.getProperty("user.home") 135 + HOME_SUBDIR + "/trusted.certs").toURI().toURL(); 136 TRUST_STORES_URLS[2] = new File(systemProperties.getProperty("user.home") 137 + HOME_SUBDIR + "/trusted.jssecerts").toURI().toURL(); 138 } else { 139 140 TRUST_STORES_URLS[0] = new File(systemProperties.getProperty("java.home") + 141 "\\lib\\security\\cacerts").toURI().toURL(); 142 TRUST_STORES_URLS[1] = new File(systemProperties.getProperty("user.home") + 143 HOME_SUBDIR + "\\trusted.certs").toURI().toURL(); 144 TRUST_STORES_URLS[2] = new File(systemProperties.getProperty("user.home") + 145 HOME_SUBDIR + "\\trusted.jssecerts").toURI().toURL(); 146 } 147 148 149 } catch (MalformedURLException e) { 150 e.printStackTrace(); 151 } 152 } 153 154 /** 155 * 156 */ 157 public DigitalCertificate() { 158 this.hostAddress = null; 159 this.parentFrame = null; 160 } 161 162 /** 163 * Construtor da classe. Recebe a {@link URL} da página em que a Applet está incluída. 164 * @param pageAddress URL da página em que a Applet está incluída 165 */ 166 private DigitalCertificate(URL pageAddress){ 167 this.hostAddress = pageAddress.getHost(); 168 this.parentFrame = null; 169 } 170 171 private DigitalCertificate(Frame parent){ 172 this.hostAddress = null; 173 this.parentFrame = parent; 174 } 175 176 177 public DigitalCertificate(Frame parent, Setup setup){ 178 this(parent); 179 this.setup = setup; 180 } 181 182 public DigitalCertificate(URL pageAddress, Setup setup){ 183 this(pageAddress); 184 this.setup = setup; 185 } 186 187 /** 188 * Destrói a Applet, removendo o security provider inicializado se o atributo providerName 189 * for diferente de nulo. 190 */ 191 public void destroy(){ 192 193 AuthProvider ap = null; 194 195 if (this.setup.getParameter("debug").equalsIgnoreCase("true")){ 196 System.out.println("logout no provider"); 197 } 198 if (keyStore != null){ 199 ap = (AuthProvider) this.keyStore.getProvider(); 200 } 201 202 if (ap != null){ 203 try { 204 ap.logout(); 205 } catch (LoginException e) { 206 if (this.setup.getParameter("debug").equalsIgnoreCase("true")){ 207 e.printStackTrace(); 208 } 209 } 210 } 211 212 if (providerName != null){ 213 Security.removeProvider(providerName); 214 } 215 216 this.cert = null; 217 this.keyStore = null; 218 this.hostAddress = null; 219 this.pkcs12Input = null; 220 this.providerName = null; 221 222 } 223 224 /** 225 * Procura pelo token nos locais padrões (Por enquanto só suporta o token ePass200), 226 * senão procura por um certificado A1 em System.getProperties().getProperty("user.home") + 227 * HOME_SUBDIR + "/trusted.clientcerts" e retorna um inteiro de acordo com resultado desta procura. 228 * 229 * @author Mário César Kolling 230 * @return Retorna um destes valores inteiros DigitalCertificate.KEYSTORE_DETECTED, 231 * DigitalCertificate.KEYSTORE_ALREADY_LOADED ou DigitalCertificate.KEYSTORE_NOT_DETECTED 232 * @see DigitalCertificate 233 */ 234 public int init(){ 235 236 // TODO: Usar dentro de um "loop" para testar outros modelos de tokens. 237 this.tokens = new TokenCollection(setup); 238 int interfaceType = DigitalCertificate.KEYSTORE_DETECTED; 239 240 try 241 { 242 // Tenta abrir o Token padrï¿œo (ePass2000). 243 loadKeyStore(); 244 245 } 246 catch (Exception e1){ 247 248 Provider[] providers = Security.getProviders(); 249 if (this.setup.getParameter("debug").equalsIgnoreCase("true")){ 250 for (Provider provider: providers){ 251 System.out.println(provider.getInfo()); 252 } 253 254 // Não conseguiu abrir o token (ePass2000). 255 System.out.println("Erro ao ler o token: " + e1.getMessage()); 256 } 257 258 try 259 { 260 // Tenta abrir a keyStore padrão 261 // USER_HOME/deployment/security/trusted.clientcerts 262 263 Properties props = System.getProperties(); 264 pkcs12Input = new FileInputStream(props.getProperty("user.home") + HOME_SUBDIR + "/trusted.clientcerts"); 265 266 // Se chegar aqui significa que arquivo de KeyStore existe. 267 keyStore = KeyStore.getInstance("JKS"); 268 269 } 270 catch (Exception ioe){ 271 // Não conseguiu abrir a KeyStore pkcs12 272 if (this.setup.getParameter("debug").equalsIgnoreCase("true")){ 273 System.out.println(ioe.getMessage()); 274 } 275 } 276 } 277 278 279 if (keyStore == null){ 280 // Não conseguiu inicializar a KeyStore. Mostra tela de login com usuário e senha. 281 this.keystoreStatus = DigitalCertificate.KEYSTORE_NOT_DETECTED; 282 //} else if (keyStore.getType().equalsIgnoreCase("pkcs11")){ 123 124 if (systemProperties.getProperty("os.name").equalsIgnoreCase("linux")) { 125 HOME_SUBDIR = "/.java/deployment/security"; 126 EPASS_2000 = "/usr/lib/libepsng_p11.so"; 127 } else { 128 HOME_SUBDIR = "\\dados de aplicativos\\sun\\java\\deployment\\security"; 129 EPASS_2000 = System.getenv("SystemRoot") + "\\system32\\ngp11v211.dll"; 130 //EPASS_2000 = System.getenv("ProgramFiles")+"\\Gemplus\\GemSafe Libraries\\BIN\\gclib.dll"; 131 } 132 133 try { 134 if (systemProperties.getProperty("os.name").equalsIgnoreCase("linux")) { 135 TRUST_STORES_URLS[0] = new File(systemProperties.getProperty("java.home") + "/lib/security/cacerts").toURI().toURL(); 136 TRUST_STORES_URLS[1] = new File(systemProperties.getProperty("user.home") + HOME_SUBDIR + "/trusted.certs").toURI().toURL(); 137 TRUST_STORES_URLS[2] = new File(systemProperties.getProperty("user.home") + HOME_SUBDIR + "/trusted.jssecerts").toURI().toURL(); 138 } else { 139 140 TRUST_STORES_URLS[0] = new File(systemProperties.getProperty("java.home") + 141 "\\lib\\security\\cacerts").toURI().toURL(); 142 TRUST_STORES_URLS[1] = new File(systemProperties.getProperty("user.home") + 143 HOME_SUBDIR + "\\trusted.certs").toURI().toURL(); 144 TRUST_STORES_URLS[2] = new File(systemProperties.getProperty("user.home") + 145 HOME_SUBDIR + "\\trusted.jssecerts").toURI().toURL(); 146 } 147 148 // Define os tipos smime no mailcap 149 MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); 150 151 mailcap.addMailcap("application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature"); 152 mailcap.addMailcap("application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime"); 153 mailcap.addMailcap("application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature"); 154 mailcap.addMailcap("application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime"); 155 mailcap.addMailcap("multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed"); 156 157 CommandMap.setDefaultCommandMap(mailcap); 158 159 160 161 } catch (MalformedURLException e) { 162 e.printStackTrace(); 163 } 164 } 165 166 /** 167 * 168 */ 169 public DigitalCertificate() { 170 this.hostAddress = null; 171 this.parentFrame = null; 172 } 173 174 /** 175 * Construtor da classe. Recebe a {@link URL} da página em que a Applet está incluída. 176 * @param pageAddress URL da página em que a Applet está incluída 177 */ 178 private DigitalCertificate(URL pageAddress) { 179 this.hostAddress = pageAddress.getHost(); 180 this.parentFrame = null; 181 } 182 183 private DigitalCertificate(Frame parent) { 184 this.hostAddress = null; 185 this.parentFrame = parent; 186 } 187 188 public DigitalCertificate(Frame parent, Setup setup) { 189 this(parent); 190 this.setup = setup; 191 } 192 193 public DigitalCertificate(URL pageAddress, Setup setup) { 194 this(pageAddress); 195 this.setup = setup; 196 } 197 198 public KeyStore getKeyStore() { 199 return keyStore; 200 } 201 202 public int getKeystoreStatus() { 203 return keystoreStatus; 204 } 205 206 public String getProviderName() { 207 return providerName; 208 } 209 210 /** 211 * Destrói a Applet, removendo o security provider inicializado se o atributo providerName 212 * for diferente de nulo. 213 */ 214 public void destroy() { 215 216 AuthProvider ap = null; 217 218 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 219 System.out.println("logout no provider"); 220 } 221 if (keyStore != null) { 222 ap = (AuthProvider) this.keyStore.getProvider(); 223 } 224 225 if (ap != null) { 226 try { 227 ap.logout(); 228 } catch (LoginException e) { 229 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 230 e.printStackTrace(); 231 } 232 } 233 } 234 235 if (providerName != null) { 236 Security.removeProvider(providerName); 237 } 238 239 this.cert = null; 240 this.keyStore = null; 241 this.hostAddress = null; 242 this.pkcs12Input = null; 243 this.providerName = null; 244 245 } 246 247 /** 248 * Procura pelo token nos locais padrões (Por enquanto só suporta o token ePass200), 249 * senão procura por um certificado A1 em System.getProperties().getProperty("user.home") + 250 * HOME_SUBDIR + "/trusted.clientcerts" e retorna um inteiro de acordo com resultado desta procura. 251 * 252 * @author Mário César Kolling 253 * @return Retorna um destes valores inteiros DigitalCertificate.KEYSTORE_DETECTED, 254 * DigitalCertificate.KEYSTORE_ALREADY_LOADED ou DigitalCertificate.KEYSTORE_NOT_DETECTED 255 * @see DigitalCertificate 256 */ 257 public int init() { 258 259 // TODO: Usar dentro de um "loop" para testar outros modelos de tokens. 260 this.tokens = new TokenCollection(setup); 261 int interfaceType = DigitalCertificate.KEYSTORE_DETECTED; 262 263 try { 264 // Tenta abrir o Token padrï¿œo (ePass2000). 265 loadKeyStore(); 266 267 } catch (Exception e1) { 268 269 Provider[] providers = Security.getProviders(); 270 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 271 for (Provider provider : providers) { 272 System.out.println(provider.getInfo()); 273 } 274 275 // Não conseguiu abrir o token (ePass2000). 276 System.out.println("Erro ao ler o token: " + e1.getMessage()); 277 } 278 279 try { 280 // Tenta abrir a keyStore padrão 281 // USER_HOME/deployment/security/trusted.clientcerts 282 283 Properties props = System.getProperties(); 284 pkcs12Input = new FileInputStream(props.getProperty("user.home") + HOME_SUBDIR + "/trusted.clientcerts"); 285 286 // Se chegar aqui significa que arquivo de KeyStore existe. 287 keyStore = KeyStore.getInstance("JKS"); 288 289 } catch (Exception ioe) { 290 // Não conseguiu abrir a KeyStore pkcs12 291 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 292 System.out.println(ioe.getMessage()); 293 } 294 } 295 } 296 297 298 if (keyStore == null) { 299 // Não conseguiu inicializar a KeyStore. Mostra tela de login com usuário e senha. 300 this.keystoreStatus = DigitalCertificate.KEYSTORE_NOT_DETECTED; 301 //} else if (keyStore.getType().equalsIgnoreCase("pkcs11")){ 302 } else { 303 // Usa certificado digital. 304 try { 305 // Testa se uma keystore já foi carregada previamente 306 if (keyStore.getType().equalsIgnoreCase("pkcs11")) { 307 keyStore.load(null, null); 283 308 } else { 284 // Usa certificado digital. 285 try { 286 // Testa se uma keystore já foi carregada previamente 287 if (keyStore.getType().equalsIgnoreCase("pkcs11")){ 288 keyStore.load(null, null); 289 } else { 290 keyStore.load(pkcs12Input, null); 291 } 292 293 // Se chegou aqui KeyStore está liberada, mostrar tela de login sem pedir o pin. 294 this.keystoreStatus = DigitalCertificate.KEYSTORE_ALREADY_LOADED; 295 296 } catch (ProviderException e) { 297 // Algum erro ocorreu, mostra tela de login com usuário e senha. 298 this.keystoreStatus = DigitalCertificate.KEYSTORE_NOT_DETECTED; 299 if (this.setup.getParameter("debug").equalsIgnoreCase("true")){ 300 e.printStackTrace(); 301 } 302 } catch (IOException e){ 303 // KeyStore não está liberada, mostra tela de login com o pin. 304 if (this.setup.getParameter("debug").equalsIgnoreCase("true")){ 305 System.out.println(e.getMessage()); 306 } 307 this.keystoreStatus = DigitalCertificate.KEYSTORE_DETECTED; 308 } catch (GeneralSecurityException e){ 309 if (this.setup.getParameter("debug").equalsIgnoreCase("true")){ 310 e.printStackTrace(); 311 } 312 } 313 } 314 315 return keystoreStatus; 316 317 } 318 319 /** 320 * Usado para assinar digitalmente um e-mail. 321 * @param mime 322 * @return String vazia 323 */ 324 public String signMail (Map<String, String> data) throws IOException, GeneralSecurityException, SMIMEException, MessagingException{ 325 326 Key privateKey = null; 327 if (this.keystoreStatus == DigitalCertificate.KEYSTORE_DETECTED){ 328 String pin = DialogBuilder.showPinDialog(this.parentFrame, this.setup); 329 if (pin != null){ 330 openKeyStore(pin.toCharArray()); 331 privateKey = this.keyStore.getKey(keyStore.aliases().nextElement(), pin.toCharArray()); 332 } 333 else { 334 return null; 335 } 336 } 337 /* 338 else if (this.keystoreStatus == DigitalCertificate.KEYSTORE_ALREADY_LOADED){ 339 if (DialogBuilder.showPinNotNeededDialog(this.parentFrame)){ 340 openKeyStore(null); 341 privateKey = this.keyStore.getKey(keyStore.aliases().nextElement(), null); 342 } 343 else { 344 return null; 345 } 346 } 347 */ 348 else { 349 350 //DialogBuilder.showMessageDialog(this.parentFrame, "Nenhum token/smartcard foi detectado.\nOperação não pôde ser realizada!"); 351 DialogBuilder.showMessageDialog(this.parentFrame, setup.getLang("ExpressoCertMessages", "DigitalCertificate001"), this.setup); 352 return null; 353 } 354 355 Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); 356 357 Certificate certificate = getCert(); 358 359 KeyPair keypair = new KeyPair(certificate.getPublicKey(), (PrivateKey) privateKey); 360 361 // Cria a cadeia de certificados que a gente vai enviar 362 List certList = new ArrayList(); 363 364 certList.add(certificate); 365 366 // 367 // create the base for our message 368 // 369 String fullMsg = data.get("body"); 370 371 if (this.setup.getParameter("debug").equalsIgnoreCase("true")){ 372 System.out.println("Corpo do e-mail:\n"+fullMsg+"\n"); 373 } 374 375 // 376 // Get a Session object and create the mail message 377 // 378 Properties props = System.getProperties(); 379 Session session = Session.getDefaultInstance(props, null); 380 381 InputStream is = new ByteArrayInputStream(fullMsg.getBytes("iso-8859-1")); 382 MimeMessage unsignedMessage = new MimeMessage(session, is); 383 384 // 385 // create a CertStore containing the certificates we want carried 386 // in the signature 387 // 388 if (this.setup.getParameter("debug").equalsIgnoreCase("true")){ 389 System.out.println("Provider: " + providerName); 390 } 391 CertStore certsAndcrls = CertStore.getInstance( 392 "Collection", 393 new CollectionCertStoreParameters(certList), "BC"); 394 395 // 396 // create some smime capabilities in case someone wants to respond 397 // 398 ASN1EncodableVector signedAttrs = new ASN1EncodableVector(); 399 400 SMIMECapabilityVector caps = new SMIMECapabilityVector(); 401 402 caps.addCapability(SMIMECapability.dES_EDE3_CBC); 403 caps.addCapability(SMIMECapability.rC2_CBC, 128); 404 caps.addCapability(SMIMECapability.dES_CBC); 405 406 SMIMESignedGenerator gen = new SMIMESignedGenerator(unsignedMessage.getEncoding()); 407 408 gen.addSigner(keypair.getPrivate(), (X509Certificate) certificate, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null); 409 410 gen.addCertificatesAndCRLs(certsAndcrls); 411 412 //TODO: Extrair todos os headers de unsignedMessage 413 414 // Gera a assinatura 415 Object content = unsignedMessage.getContent(); 416 417 //TODO: igualar unsignedMessage a null 418 //TODO: Pegar os headers do objeto que guardarï¿œ esses headers quando necessï¿œrio. 419 420 MimeMultipart mimeMultipartContent = null; 421 MimeBodyPart mimeBodyPartContent = new MimeBodyPart(); 422 423 if (content.getClass().getName().contains("MimeMultipart")){ 424 mimeMultipartContent = (MimeMultipart) content; 425 } 426 else { 427 is = new ByteArrayInputStream(content.toString().getBytes("iso-8859-1")); 428 mimeBodyPartContent = new MimeBodyPart(is); 429 mimeBodyPartContent.setHeader("Content-Type", unsignedMessage.getHeader("Content-Type", null)); //TODO: testar se valor existe 430 is = null; 431 } 432 content = null; 433 434 MimeBodyPart msg = null; 435 if (mimeMultipartContent == null){ 436 msg = mimeBodyPartContent; 437 mimeBodyPartContent = null; 438 } 439 else { 440 msg = new MimeBodyPart(); 441 msg.setContent(mimeMultipartContent); 442 mimeMultipartContent = null; 443 } 444 445 // 446 // extract the multipart object from the SMIMESigned object. 447 // 448 MimeMultipart mm = gen.generate(msg, providerName); 449 gen = null; 450 msg = null; 451 452 MimeMessage body = new MimeMessage(session); 453 body.setFrom(unsignedMessage.getFrom()[0]); 454 body.setRecipients(Message.RecipientType.TO, unsignedMessage.getRecipients(Message.RecipientType.TO)); 455 body.setRecipients(Message.RecipientType.CC, unsignedMessage.getRecipients(Message.RecipientType.CC)); 456 body.setRecipients(Message.RecipientType.BCC, unsignedMessage.getRecipients(Message.RecipientType.BCC)); 457 body.setSubject(unsignedMessage.getSubject(), "iso-8859-1"); 458 459 // Atrafuia o resto dos headers 460 body.setHeader("Return-Path", unsignedMessage.getHeader("Return-Path", null)); 461 body.setHeader("Message-ID", unsignedMessage.getHeader("Message-ID", null)); 462 body.setHeader("X-Priority", unsignedMessage.getHeader("X-Priority", null)); 463 body.setHeader("X-Mailer", unsignedMessage.getHeader("X-Mailer", null)); 464 body.setHeader("Disposition-Notification-To", unsignedMessage.getHeader("Disposition-Notification-To", null)); 465 body.setHeader("Date", unsignedMessage.getHeader("Date", null)); 466 body.setContent(mm, mm.getContentType()); 467 mm = null; 468 469 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 470 System.out.println("\nHeaders do e-mail original:\n"); 471 } 472 473 body.saveChanges(); 474 475 ByteArrayOutputStream oStream = new ByteArrayOutputStream(); 476 477 oStream = new ByteArrayOutputStream(); 478 body.writeTo(oStream); 479 480 body = null; 481 return oStream.toString("iso-8859-1"); 482 483 } 484 485 /** 486 * Método utilizado para criptografar um e-mail 487 * @param source 488 * @return 489 */ 490 public String cipherMail(Map<String, String> data) throws IOException, GeneralSecurityException, MessagingException, CMSException, SMIMEException{ 491 492 //Pega certificado do usuário. 493 494 Key privateKey = null; 495 if (this.keystoreStatus == DigitalCertificate.KEYSTORE_DETECTED){ 496 String pin = DialogBuilder.showPinDialog(this.parentFrame, this.setup); 497 if (pin != null){ 498 openKeyStore(pin.toCharArray()); 499 privateKey = this.keyStore.getKey(keyStore.aliases().nextElement(), pin.toCharArray()); 500 } 501 else { 502 return null; 503 } 504 } 505 /* 506 else if (this.keystoreStatus == DigitalCertificate.KEYSTORE_ALREADY_LOADED){ 507 if (DialogBuilder.showPinNotNeededDialog(this.parentFrame)){ 508 openKeyStore(null); 509 privateKey = this.keyStore.getKey(keyStore.aliases().nextElement(), null); 510 } 511 else { 512 return null; 513 } 514 } 515 */ 516 else { 517 518 //DialogBuilder.showMessageDialog(this.parentFrame, "Nenhum token/smartcard foi detectado.\nOperação não pôde ser realizada!"); 519 DialogBuilder.showMessageDialog(this.parentFrame, setup.getLang("ExpressoCertMessages", "DigitalCertificate001"), this.setup); 520 return null; 521 } 522 523 Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); 524 525 X509Certificate cert = (X509Certificate)getCert(); 526 527 RecipientId recId = new RecipientId(); 528 recId.setSerialNumber(cert.getSerialNumber()); 529 recId.setIssuer(cert.getIssuerX500Principal()); 530 531 Properties props = System.getProperties(); 532 Session session = Session.getDefaultInstance(props, null); 533 534 String fullMsg = data.get("body"); 535 InputStream is = new ByteArrayInputStream(fullMsg.getBytes("iso-8859-1")); 536 MimeMessage encriptedMsg = new MimeMessage(session, is); 537 538 Provider prov = Security.getProvider(providerName); 539 if (this.setup.getParameter("debug").equalsIgnoreCase("true")){ 540 System.out.println("Serviços do provider "+providerName+ ":\n"+ prov.getInfo()); 541 for (Provider.Service service: prov.getServices()) 542 System.out.println(service.toString() + ": " + service.getAlgorithm()); 543 } 544 545 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 546 System.out.println("Email criptografado:\n" + fullMsg); 547 } 548 549 SMIMEEnvelopedParser m = new SMIMEEnvelopedParser(encriptedMsg); 550 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 551 System.out.println("Algoritmo de encriptação: " + m.getEncryptionAlgOID()); 552 } 553 554 AlgorithmParameters algParams = m.getEncryptionAlgorithmParameters("BC"); 555 if (this.setup.getParameter("debug").equalsIgnoreCase("true")){ 556 System.out.println("Parâmetros do algoritmo: " + algParams.toString()); 557 } 558 559 RecipientInformationStore recipients = m.getRecipientInfos(); 560 RecipientInformation recipient = recipients.get(recId); 561 562 if (recipient != null){ 563 MimeBodyPart decriptedBodyPart = SMIMEUtil.toMimeBodyPart(recipient.getContentStream(privateKey, this.providerName)); 564 encriptedMsg.setContent(decriptedBodyPart.getContent(), decriptedBodyPart.getContentType()); 565 encriptedMsg.saveChanges(); 566 567 ByteArrayOutputStream oStream = new ByteArrayOutputStream(); 568 encriptedMsg.writeTo(oStream); 569 encriptedMsg = null; 570 571 return oStream.toString("iso-8859-1"); 572 } 573 else { 574 //DialogBuilder.showMessageDialog(this.parentFrame, "Não é possível ler este e-mail com o Certificado Digital apresentado!\n" + 575 // "Motivo: Este e-mail não foi cifrado com a chave pública deste Certificado Digital."); 576 DialogBuilder.showMessageDialog(this.parentFrame, setup.getLang("ExpressoCertMessages", "DigitalCertificate002"), this.setup); 577 return null; 578 } 579 } 580 581 /** 582 * Pega as credenciais de login do dono do certificado do serviço de verificação de certificados 583 * @param pin pin para acessar o token 584 * @return resposta Array de Strings em que: 585 * Indice 0: código de retorno; 586 * Indice 1: username se código de retorno for 0, senão mensagem de erro; 587 * Indice 2: senha decriptada se código de retorno for 0, senão não existe; 588 * @throws SSLHandshakeException 589 * @throws HttpException 590 * @throws IOException 591 * @throws GeneralSecurityException 592 */ 593 public String[] getCredentials(String pin) throws SSLHandshakeException, HttpException, IOException, GeneralSecurityException{ 594 595 String[] resposta = null; 596 597 if (this.setup.getParameter("debug").equalsIgnoreCase("true")){ 598 System.out.println("Proxy Configurado no browser: " + System.getProperty("http.proxyHost") 599 + ":" + System.getProperty("http.proxyPort")); 600 } 601 602 // Registra novo protocolo https, utilizando nova implementação de AuthSSLProtocolSocketFactory 603 Protocol.registerProtocol("https", new Protocol("https", 604 (ProtocolSocketFactory) new AuthSSLProtocolSocketFactory(TRUST_STORES_URLS, TRUST_STORES_PASSWORDS, this.setup), 605 443)); 606 607 HttpClient httpclient = new HttpClient(); 608 // Define um método post para o link do serviço de verificação de certificados 609 if (System.getProperty("http.proxyHost") != null && System.getProperty("http.proxyPort") != null){ 610 httpclient.getHostConfiguration().setProxy(System.getProperty("http.proxyHost"), 611 Integer.parseInt(System.getProperty("http.proxyPort"))); 612 } 613 PostMethod httppost = new PostMethod("https://"+ hostAddress + "/security/vercert.php"); 614 615 try { 616 // Adiciona parâmetro certificado no método post, executa o método, pega a resposta do servidor 617 // como uma string com CRLF de separador entre os campos e gera um array de Strings 618 httppost.addParameter("certificado", Base64Utils.der2pem(cert.getEncoded())); 619 httpclient.executeMethod(httppost); 620 resposta = httppost.getResponseBodyAsString().split(CRLF); 621 622 if (resposta.length > 2){ 623 if (Integer.parseInt(resposta[0].trim()) == 0){ 624 // Se código da resposta for zero, decripta a senha criptografada do usuário 625 resposta[2] = decriptPassword(resposta[2].trim(), pin); 626 } 627 } 628 629 } catch (IOException e){ 630 // Se for instância de SSLHandshakeException faz um cast para este tipo e lança a exceção novamente 631 // Isto é usado para diferenciar o tipo de falha, para que a mensagem para o usuário seja mostrada de 632 // acordo. 633 if (e instanceof SSLHandshakeException){ 634 throw (SSLHandshakeException) e; 635 } 636 // senão lança novamente a exceção do tipo IOException 637 throw e; 638 } finally { 639 // fecha a conexão 640 httppost.releaseConnection(); 641 } 642 643 return resposta; 644 } 645 646 /** 647 * Decripta a senha criptografada 648 * @param encodedPassword senha criptografada e codificada em base64 para ser decriptada 649 * @param pin pin para acessar a KeyStore 650 * @return decodedPassword 651 * @throws GeneralSecurityException se algum problema ocorrer na decriptação da senha. 652 */ 653 public String decriptPassword(String encodedPassword, String pin) throws GeneralSecurityException{ 654 655 String decodedPassword = new String(); 656 657 // Pega a chave privada do primeiro certificado armazenado na KeyStore 658 Enumeration<String> en = this.keyStore.aliases(); 659 String certAlias = en.nextElement(); 660 Key privateKey = this.keyStore.getKey(certAlias, pin.toCharArray()); 661 662 // Inicializa os cipher com os parâmetros corretos para realizar a decriptação 663 Cipher dcipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 664 dcipher.init(Cipher.DECRYPT_MODE, privateKey); 665 666 // Decodifica a senha em base64 e a decripta 667 decodedPassword = new String(dcipher.doFinal(Base64Utils.base64Decode(encodedPassword))); 668 669 return decodedPassword.trim(); 670 671 } 672 673 /** 674 * Carrega um novo SecurityProvider 675 * @param pkcs11Config Linha de configuração do SmartCard ou Token 676 * @throws KeyStoreException Quando não conseguir iniciar a KeyStore, ou a lib do Token 677 * ou Smartcard não foi encontrada, ou o usuário não inseriu o Token. 678 */ 679 private void loadKeyStore() throws KeyStoreException{ 680 681 //Provider pkcs11Provider = new sun.security.pkcs11.SunPKCS11(new ByteArrayInputStream(pkcs11Config.getBytes())); 682 //Security.addProvider(pkcs11Provider); 683 this.keyStore = KeyStore.getInstance("PKCS11"); 684 this.providerName = keyStore.getProvider().getName(); 685 686 } 687 688 /** 689 * Abre a keystore passando o pin 690 * @param pin pin para acessar o Token 691 */ 692 public void openKeyStore(char[] pin) throws IOException{ 693 694 try { 695 696 if (this.keyStore.getType().equals("PKCS11")){ 697 this.keyStore.load(null, pin); 698 } 699 else { 700 this.keyStore.load(this.pkcs12Input, pin); 701 } 702 703 this.cert = this.keyStore.getCertificate(this.keyStore.aliases().nextElement()); 704 705 } catch (GeneralSecurityException e) { 706 if (this.setup.getParameter("debug").equalsIgnoreCase("true")){ 707 e.printStackTrace(); 708 } 709 } 710 711 } 712 713 /** 714 * @return the cert 715 */ 716 Certificate getCert() { 717 return this.cert; 718 } 719 720 /** 721 * @param cert the cert to set 722 */ 723 void setCert(Certificate cert) { 724 this.cert = cert; 725 } 726 309 keyStore.load(pkcs12Input, null); 310 } 311 312 // Se chegou aqui KeyStore está liberada, mostrar tela de login sem pedir o pin. 313 this.keystoreStatus = DigitalCertificate.KEYSTORE_ALREADY_LOADED; 314 315 } catch (ProviderException e) { 316 // Algum erro ocorreu, mostra tela de login com usuário e senha. 317 this.keystoreStatus = DigitalCertificate.KEYSTORE_NOT_DETECTED; 318 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 319 e.printStackTrace(); 320 } 321 } catch (IOException e) { 322 // KeyStore não está liberada, mostra tela de login com o pin. 323 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 324 System.out.println(e.getMessage()); 325 } 326 this.keystoreStatus = DigitalCertificate.KEYSTORE_DETECTED; 327 } catch (GeneralSecurityException e) { 328 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 329 e.printStackTrace(); 330 } 331 } 332 } 333 334 return keystoreStatus; 335 336 } 337 338 /** 339 * Usado para assinar digitalmente um e-mail. 340 * @param mime 341 * @return String vazia 342 */ 343 public String signMail(Map<String, String> data) throws IOException, GeneralSecurityException, SMIMEException, MessagingException { 344 345 Key privateKey = null; 346 if (this.keystoreStatus == DigitalCertificate.KEYSTORE_DETECTED) { 347 String pin = DialogBuilder.showPinDialog(this.parentFrame, this.setup); 348 if (pin != null) { 349 openKeyStore(pin.toCharArray()); 350 privateKey = this.keyStore.getKey(keyStore.aliases().nextElement(), pin.toCharArray()); 351 } else { 352 return null; 353 } 354 } /* 355 else if (this.keystoreStatus == DigitalCertificate.KEYSTORE_ALREADY_LOADED){ 356 if (DialogBuilder.showPinNotNeededDialog(this.parentFrame)){ 357 openKeyStore(null); 358 privateKey = this.keyStore.getKey(keyStore.aliases().nextElement(), null); 359 } 360 else { 361 return null; 362 } 363 } 364 */ else { 365 366 //DialogBuilder.showMessageDialog(this.parentFrame, "Nenhum token/smartcard foi detectado.\nOperação não pôde ser realizada!"); 367 DialogBuilder.showMessageDialog(this.parentFrame, setup.getLang("ExpressoCertMessages", "DigitalCertificate001"), this.setup); 368 return null; 369 } 370 371 Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); 372 373 Certificate certificate = getCert(); 374 375 KeyPair keypair = new KeyPair(certificate.getPublicKey(), (PrivateKey) privateKey); 376 377 // Cria a cadeia de certificados que a gente vai enviar 378 List certList = new ArrayList(); 379 380 certList.add(certificate); 381 382 // 383 // create the base for our message 384 // 385 String fullMsg = data.get("body"); 386 387 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 388 System.out.println("Corpo do e-mail:\n" + fullMsg + "\n"); 389 } 390 391 // 392 // Get a Session object and create the mail message 393 // 394 Properties props = System.getProperties(); 395 Session session = Session.getDefaultInstance(props, null); 396 397 InputStream is = new ByteArrayInputStream(fullMsg.getBytes("iso-8859-1")); 398 MimeMessage unsignedMessage = new MimeMessage(session, is); 399 400 // 401 // create a CertStore containing the certificates we want carried 402 // in the signature 403 // 404 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 405 System.out.println("Provider: " + providerName); 406 } 407 CertStore certsAndcrls = CertStore.getInstance( 408 "Collection", 409 new CollectionCertStoreParameters(certList), "BC"); 410 411 // 412 // create some smime capabilities in case someone wants to respond 413 // 414 ASN1EncodableVector signedAttrs = new ASN1EncodableVector(); 415 416 SMIMECapabilityVector caps = new SMIMECapabilityVector(); 417 418 caps.addCapability(SMIMECapability.dES_EDE3_CBC); 419 caps.addCapability(SMIMECapability.rC2_CBC, 128); 420 caps.addCapability(SMIMECapability.dES_CBC); 421 422 SMIMESignedGenerator gen = new SMIMESignedGenerator(unsignedMessage.getEncoding()); 423 424 //SMIMESignedGenerator gen = new SMIMESignedGenerator(); 425 426 gen.addSigner(keypair.getPrivate(), (X509Certificate) certificate, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null); 427 428 gen.addCertificatesAndCRLs(certsAndcrls); 429 430 //TODO: Extrair todos os headers de unsignedMessage 431 432 // Gera a assinatura 433 Object content = unsignedMessage.getContent(); 434 435 //TODO: igualar unsignedMessage a null 436 //TODO: Pegar os headers do objeto que guardarï¿œ esses headers quando necessï¿œrio. 437 438 MimeMultipart mimeMultipartContent = null; 439 PreencodedMimeBodyPart mimeBodyPartContent = null; 440 441 if (content.getClass().getName().contains("MimeMultipart")) { 442 mimeMultipartContent = (MimeMultipart) content; 443 } else { 444 String encoding = MimeUtility.getEncoding(unsignedMessage.getDataHandler()); 445 mimeBodyPartContent = new PreencodedMimeBodyPart(encoding); 446 if (encoding.equalsIgnoreCase("quoted-printable")) { 447 ByteArrayOutputStream os = new ByteArrayOutputStream(); 448 OutputStream encode = MimeUtility.encode(os, encoding); 449 OutputStreamWriter writer = new OutputStreamWriter(encode, "iso-8859-1"); 450 writer.write(content.toString()); 451 writer.flush(); 452 mimeBodyPartContent.setText(os.toString(), "iso-8859-1"); 453 os = null; 454 encode = null; 455 writer = null; 456 } else { 457 mimeBodyPartContent.setText(content.toString(), "iso-8859-1"); 458 } 459 mimeBodyPartContent.setHeader("Content-Type", unsignedMessage.getHeader("Content-Type", null)); 460 } 461 content = null; 462 463 // 464 // extract the multipart object from the SMIMESigned object. 465 // 466 MimeMultipart mm = null; 467 if (mimeMultipartContent == null) { 468 mm = gen.generate(mimeBodyPartContent, providerName); 469 mimeBodyPartContent = null; 470 } else { 471 MimeBodyPart multipartMsg = new MimeBodyPart(); 472 multipartMsg.setContent(mimeMultipartContent); 473 mm = gen.generate(multipartMsg, providerName); 474 multipartMsg = null; 475 mimeMultipartContent = null; 476 } 477 478 gen = null; 479 480 MimeMessage body = new MimeMessage(session); 481 body.setFrom(unsignedMessage.getFrom()[0]); 482 body.setRecipients(Message.RecipientType.TO, unsignedMessage.getRecipients(Message.RecipientType.TO)); 483 body.setRecipients(Message.RecipientType.CC, unsignedMessage.getRecipients(Message.RecipientType.CC)); 484 body.setRecipients(Message.RecipientType.BCC, unsignedMessage.getRecipients(Message.RecipientType.BCC)); 485 body.setSubject(unsignedMessage.getSubject(), "iso-8859-1"); 486 487 // Atrafuia o resto dos headers 488 body.setHeader("Return-Path", unsignedMessage.getHeader("Return-Path", null)); 489 body.setHeader("Message-ID", unsignedMessage.getHeader("Message-ID", null)); 490 body.setHeader("X-Priority", unsignedMessage.getHeader("X-Priority", null)); 491 body.setHeader("X-Mailer", unsignedMessage.getHeader("X-Mailer", null)); 492 body.setHeader("Disposition-Notification-To", unsignedMessage.getHeader("Disposition-Notification-To", null)); 493 body.setHeader("Date", unsignedMessage.getHeader("Date", null)); 494 body.setContent(mm, mm.getContentType()); 495 mm = null; 496 497 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 498 System.out.println("\nHeaders do e-mail original:\n"); 499 } 500 501 body.saveChanges(); 502 503 ByteArrayOutputStream oStream = new ByteArrayOutputStream(); 504 505 oStream = new ByteArrayOutputStream(); 506 body.writeTo(oStream); 507 508 body = null; 509 return oStream.toString("iso-8859-1"); 510 511 } 512 513 /** 514 * Método utilizado para criptografar um e-mail 515 * @param source 516 * @return 517 */ 518 public String cipherMail(Map<String, String> data) throws IOException, GeneralSecurityException, MessagingException, CMSException, SMIMEException { 519 520 //Pega certificado do usuário. 521 522 Key privateKey = null; 523 if (this.keystoreStatus == DigitalCertificate.KEYSTORE_DETECTED) { 524 String pin = DialogBuilder.showPinDialog(this.parentFrame, this.setup); 525 if (pin != null) { 526 openKeyStore(pin.toCharArray()); 527 privateKey = this.keyStore.getKey(keyStore.aliases().nextElement(), pin.toCharArray()); 528 } else { 529 return null; 530 } 531 } /* 532 else if (this.keystoreStatus == DigitalCertificate.KEYSTORE_ALREADY_LOADED){ 533 if (DialogBuilder.showPinNotNeededDialog(this.parentFrame)){ 534 openKeyStore(null); 535 privateKey = this.keyStore.getKey(keyStore.aliases().nextElement(), null); 536 } 537 else { 538 return null; 539 } 540 } 541 */ else { 542 543 //DialogBuilder.showMessageDialog(this.parentFrame, "Nenhum token/smartcard foi detectado.\nOperação não pôde ser realizada!"); 544 DialogBuilder.showMessageDialog(this.parentFrame, setup.getLang("ExpressoCertMessages", "DigitalCertificate001"), this.setup); 545 return null; 546 } 547 548 Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); 549 550 X509Certificate cert = (X509Certificate) getCert(); 551 552 RecipientId recId = new RecipientId(); 553 recId.setSerialNumber(cert.getSerialNumber()); 554 recId.setIssuer(cert.getIssuerX500Principal()); 555 556 Properties props = System.getProperties(); 557 Session session = Session.getDefaultInstance(props, null); 558 559 String fullMsg = data.get("body"); 560 InputStream is = new ByteArrayInputStream(fullMsg.getBytes("iso-8859-1")); 561 MimeMessage encriptedMsg = new MimeMessage(session, is); 562 563 Provider prov = Security.getProvider(providerName); 564 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 565 System.out.println("Serviços do provider " + providerName + ":\n" + prov.getInfo()); 566 for (Provider.Service service : prov.getServices()) { 567 System.out.println(service.toString() + ": " + service.getAlgorithm()); 568 } 569 } 570 571 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 572 System.out.println("Email criptografado:\n" + fullMsg); 573 } 574 575 SMIMEEnvelopedParser m = new SMIMEEnvelopedParser(encriptedMsg); 576 if (setup.getParameter("debug").equalsIgnoreCase("true")) { 577 System.out.println("Algoritmo de encriptação: " + m.getEncryptionAlgOID()); 578 } 579 580 AlgorithmParameters algParams = m.getEncryptionAlgorithmParameters("BC"); 581 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 582 System.out.println("Parâmetros do algoritmo: " + algParams.toString()); 583 } 584 585 RecipientInformationStore recipients = m.getRecipientInfos(); 586 RecipientInformation recipient = recipients.get(recId); 587 588 if (recipient != null) { 589 String retorno; 590 591 MimeBodyPart decriptedBodyPart = SMIMEUtil.toMimeBodyPart(recipient.getContent(privateKey, getProviderName())); 592 593 if ((new ContentType(decriptedBodyPart.getContentType())).getSubType().equalsIgnoreCase("x-pkcs7-mime")) { 594 StringBuffer sb = new StringBuffer(encriptedMsg.getSize()); 595 596 for (Enumeration e = encriptedMsg.getAllHeaderLines(); e.hasMoreElements();) { 597 String header = (String) e.nextElement(); 598 if (!header.contains("Content-Type") && 599 !header.contains("Content-Transfer-Encoding") && 600 !header.contains("Content-Disposition")) { 601 sb.append(header); 602 sb.append("\r\n"); 603 } 604 } 605 ByteArrayOutputStream oStream = new ByteArrayOutputStream(); 606 decriptedBodyPart.writeTo(oStream); 607 decriptedBodyPart = null; 608 encriptedMsg = null; 609 610 sb.append(oStream.toString("iso-8859-1")); 611 612 retorno = sb.toString(); 613 614 } else { 615 encriptedMsg.setContent(decriptedBodyPart.getContent(), decriptedBodyPart.getContentType()); 616 encriptedMsg.saveChanges(); 617 618 ByteArrayOutputStream oStream = new ByteArrayOutputStream(); 619 encriptedMsg.writeTo(oStream); 620 encriptedMsg = null; 621 622 retorno = oStream.toString("iso-8859-1"); 623 } 624 625 return retorno; 626 } else { 627 //DialogBuilder.showMessageDialog(this.parentFrame, "Não é possível ler este e-mail com o Certificado Digital apresentado!\n" + 628 // "Motivo: Este e-mail não foi cifrado com a chave pública deste Certificado Digital."); 629 DialogBuilder.showMessageDialog(this.parentFrame, setup.getLang("ExpressoCertMessages", "DigitalCertificate002"), this.setup); 630 return null; 631 } 632 } 633 634 /** 635 * Pega as credenciais de login do dono do certificado do serviço de verificação de certificados 636 * @param pin pin para acessar o token 637 * @return resposta Array de Strings em que: 638 * Indice 0: código de retorno; 639 * Indice 1: username se código de retorno for 0, senão mensagem de erro; 640 * Indice 2: senha decriptada se código de retorno for 0, senão não existe; 641 * @throws SSLHandshakeException 642 * @throws HttpException 643 * @throws IOException 644 * @throws GeneralSecurityException 645 */ 646 public String[] getCredentials(String pin) throws SSLHandshakeException, HttpException, IOException, GeneralSecurityException { 647 648 String[] resposta = null; 649 650 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 651 System.out.println("Proxy Configurado no browser: " + System.getProperty("http.proxyHost") + ":" + System.getProperty("http.proxyPort")); 652 } 653 654 // Registra novo protocolo https, utilizando nova implementação de AuthSSLProtocolSocketFactory 655 Protocol.registerProtocol("https", new Protocol("https", 656 (ProtocolSocketFactory) new AuthSSLProtocolSocketFactory(TRUST_STORES_URLS, TRUST_STORES_PASSWORDS, this.setup), 657 443)); 658 659 HttpClient httpclient = new HttpClient(); 660 // Define um método post para o link do serviço de verificação de certificados 661 if (System.getProperty("http.proxyHost") != null && System.getProperty("http.proxyPort") != null) { 662 httpclient.getHostConfiguration().setProxy(System.getProperty("http.proxyHost"), 663 Integer.parseInt(System.getProperty("http.proxyPort"))); 664 } 665 PostMethod httppost = new PostMethod("https://" + hostAddress + "/security/vercert.php"); 666 667 try { 668 // Adiciona parâmetro certificado no método post, executa o método, pega a resposta do servidor 669 // como uma string com CRLF de separador entre os campos e gera um array de Strings 670 httppost.addParameter("certificado", Base64Utils.der2pem(cert.getEncoded())); 671 httpclient.executeMethod(httppost); 672 resposta = httppost.getResponseBodyAsString().split(CRLF); 673 674 if (resposta.length > 2) { 675 if (Integer.parseInt(resposta[0].trim()) == 0) { 676 // Se código da resposta for zero, decripta a senha criptografada do usuário 677 resposta[2] = decriptPassword(resposta[2].trim(), pin); 678 } 679 } 680 681 } catch (IOException e) { 682 // Se for instância de SSLHandshakeException faz um cast para este tipo e lança a exceção novamente 683 // Isto é usado para diferenciar o tipo de falha, para que a mensagem para o usuário seja mostrada de 684 // acordo. 685 if (e instanceof SSLHandshakeException) { 686 throw (SSLHandshakeException) e; 687 } 688 // senão lança novamente a exceção do tipo IOException 689 throw e; 690 } finally { 691 // fecha a conexão 692 httppost.releaseConnection(); 693 } 694 695 return resposta; 696 } 697 698 /** 699 * Decripta a senha criptografada 700 * @param encodedPassword senha criptografada e codificada em base64 para ser decriptada 701 * @param pin pin para acessar a KeyStore 702 * @return decodedPassword 703 * @throws GeneralSecurityException se algum problema ocorrer na decriptação da senha. 704 */ 705 public String decriptPassword(String encodedPassword, String pin) throws GeneralSecurityException { 706 707 String decodedPassword = new String(); 708 709 // Pega a chave privada do primeiro certificado armazenado na KeyStore 710 Enumeration<String> en = this.keyStore.aliases(); 711 String certAlias = en.nextElement(); 712 Key privateKey = this.keyStore.getKey(certAlias, pin.toCharArray()); 713 714 // Inicializa os cipher com os parâmetros corretos para realizar a decriptação 715 Cipher dcipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 716 dcipher.init(Cipher.DECRYPT_MODE, privateKey); 717 718 // Decodifica a senha em base64 e a decripta 719 decodedPassword = new String(dcipher.doFinal(Base64Utils.base64Decode(encodedPassword))); 720 721 return decodedPassword.trim(); 722 723 } 724 725 /** 726 * Carrega um novo SecurityProvider 727 * @param pkcs11Config Linha de configuração do SmartCard ou Token 728 * @throws KeyStoreException Quando não conseguir iniciar a KeyStore, ou a lib do Token 729 * ou Smartcard não foi encontrada, ou o usuário não inseriu o Token. 730 */ 731 private void loadKeyStore() throws KeyStoreException { 732 733 //Provider pkcs11Provider = new sun.security.pkcs11.SunPKCS11(new ByteArrayInputStream(pkcs11Config.getBytes())); 734 //Security.addProvider(pkcs11Provider); 735 this.keyStore = KeyStore.getInstance("PKCS11"); 736 this.providerName = keyStore.getProvider().getName(); 737 738 } 739 740 /** 741 * Abre a keystore passando o pin 742 * @param pin pin para acessar o Token 743 */ 744 public void openKeyStore(char[] pin) throws IOException { 745 746 try { 747 748 if (this.keyStore.getType().equals("PKCS11")) { 749 this.keyStore.load(null, pin); 750 } else { 751 this.keyStore.load(this.pkcs12Input, pin); 752 } 753 754 this.cert = this.keyStore.getCertificate(this.keyStore.aliases().nextElement()); 755 756 System.out.println("Aliases (" + this.keyStore.size() + "): "); 757 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 758 for (Enumeration alias = this.keyStore.aliases(); alias.hasMoreElements();) { 759 System.out.println(alias.nextElement()); 760 } 761 } 762 763 } catch (GeneralSecurityException e) { 764 if (this.setup.getParameter("debug").equalsIgnoreCase("true")) { 765 e.printStackTrace(); 766 } 767 } 768 769 } 770 771 /** 772 * @return the cert 773 */ 774 Certificate getCert() { 775 return this.cert; 776 } 777 778 /** 779 * @param cert the cert to set 780 */ 781 void setCert(Certificate cert) { 782 this.cert = cert; 783 } 727 784 } -
branches/2.2/security/ExpressoCert/src/br/gov/serpro/setup/Setup.java
r1174 r3232 52 52 for (String[] parameter: getParameterInfo()){ 53 53 String parameterName = parameter[0]; 54 String parameterValue = this.currentApplet.getParameter(parameterName); 54 String parameterValue; 55 56 if (this.currentApplet.isActive()){ 57 parameterValue = this.currentApplet.getParameter(parameterName); 58 } 59 else { 60 parameterValue = null; 61 } 55 62 56 63 //System.out.println("Parameter a ser adicionado - " + parameterName + "= " + parameterValue); -
branches/2.2/security/cas/todos.cer
r1174 r3232 1 -----BEGIN CERTIFICATE-----2 MIIEuDCCA6CgAwIBAgIBBDANBgkqhkiG9w0BAQUFADCBtDELMAkGA1UEBhMCQlIx3 EzARBgNVBAoTCklDUC1CcmFzaWwxPTA7BgNVBAsTNEluc3RpdHV0byBOYWNpb25h4 bCBkZSBUZWNub2xvZ2lhIGRhIEluZm9ybWFjYW8gLSBJVEkxETAPBgNVBAcTCEJy5 YXNpbGlhMQswCQYDVQQIEwJERjExMC8GA1UEAxMoQXV0b3JpZGFkZSBDZXJ0aWZp6 Y2Fkb3JhIFJhaXogQnJhc2lsZWlyYTAeFw0wMTExMzAxMjU4MDBaFw0xMTExMzAy7 MzU5MDBaMIG0MQswCQYDVQQGEwJCUjETMBEGA1UEChMKSUNQLUJyYXNpbDE9MDsG8 A1UECxM0SW5zdGl0dXRvIE5hY2lvbmFsIGRlIFRlY25vbG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WrZDLjJ8RS0E32ilT3A30DqdkOIhKgbmjfQuBTZWJ44 8ZA+msEYaOl5AgMA05ejgbcwgbQwPQYDVR0fBDYwNDAyoDCgLoYsaHR0cDovL2Fj45 cmFpei5pY3BicmFzaWwuZ292LmJyL0xDUmFjcmFpei5jcmwwEgYDVR0gBAswCTAH46 BgVgTAEBAjAdBgNVHQ4EFgQU4osVQdt1OSm8HFR7+1E/FAkS8rQwHwYDVR0jBBgw47 FoAUivrxV4QREzWQQvpXSVRpDaTE8DcwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB48 /wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAGJSHMCH3re9mCmtnVH+btonLi8M49 EJgtYDwwOkLvknnwI+0WimHsFDM7ABcaKw4N5OZwAlcSFla4i1vbFjools4HD4z+50 fMwbHIhifTNLQKW49Dm+XqnBIe/UIbNXfDdQmKk770WhsljALMC53k/phxPxHN3y51 qrD06YwDaQKLbuAO800ycCUeIvvxB698oSdrC/m2jf+Wt6NZMybqw7Tp2qBR+c/v52 CZW1g6Qbij5lOm2ADrpXpjiDKnmsUmff9uvByix2mbTHRNa9E+eeev7ZN+PpSLhZ53 5x8xKisZxBXdBL+2aeGaNa81sWculWLam3DI6bARrzAtRrI0cVev2kkSWks=54 -----END CERTIFICATE-----55 1 -----BEGIN CERTIFICATE----- 56 2 MIIFdzCCBF+gAwIBAgISMjAwNTA0MDQxNTUwNTYwMDAxMA0GCSqGSIb3DQEBBQUA … … 165 111 -----END CERTIFICATE----- 166 112 -----BEGIN CERTIFICATE----- 167 MIIEPzCCAyegAwIBAgIBFDANBgkqhkiG9w0BAQUFADCBtDELMAkGA1UEBhMCQlIx168 EzARBgNVBAoTCklDUC1CcmFzaWwxPTA7BgNVBAsTNEluc3RpdHV0byBOYWNpb25h169 bCBkZSBUZWNub2xvZ2lhIGRhIEluZm9ybWFjYW8gLSBJVEkxETAPBgNVBAcTCEJy170 YXNpbGlhMQswCQYDVQQIEwJERjExMC8GA1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znHQspUKgNvAHJeE60oAVgeA8187 cBc+AVVmf5VWbiKOKwx3JiCoGI7g3p41fXxk4urxu/rD8lYh3FcH3v261H6aEAba188 e5eeGwcioeDH9vusedmFYpmcSDGmr8edCoOohZToFffKQJNdNSrpFt1yECQ/Nj/y189 6B+CCY1XWte4TJ2/tbIFasBxzjRDUD7luJ/Ij0X24+3EsyE=190 -----END CERTIFICATE-----191 -----BEGIN CERTIFICATE-----192 113 MIIFCjCCA/KgAwIBAgIEQd8NtTANBgkqhkiG9w0BAQUFADBXMQswCQYDVQQGEwJi 193 114 cjETMBEGA1UEChMKSUNQLUJyYXNpbDEgMB4GA1UECxMXQ2FpeGEgRWNvbm9taWNh … … 309 230 -----END CERTIFICATE----- 310 231 -----BEGIN CERTIFICATE----- 311 MIIEODCCAyCgAwIBAgIBFTANBgkqhkiG9w0BAQUFADCBtDELMAkGA1UEBhMCQlIx312 EzARBgNVBAoTCklDUC1CcmFzaWwxPTA7BgNVBAsTNEluc3RpdHV0byBOYWNpb25h313 bCBkZSBUZWNub2xvZ2lhIGRhIEluZm9ybWFjYW8gLSBJVEkxETAPBgNVBAcTCEJy314 YXNpbGlhMQswCQYDVQQIEwJERjExMC8GA1UEAxMoQXV0b3JpZGFkZSBDZXJ0aWZp315 Y2Fkb3JhIFJhaXogQnJhc2lsZWlyYTAeFw0wNTEyMTkxMzAwMDBaFw0xMTA2MTky316 MzU5MDBaMFAxCzAJBgNVBAYTAkJSMRMwEQYDVQQKEwpJQ1AtQnJhc2lsMSwwKgYD317 VQQDEyNBdXRvcmlkYWRlIENlcnRpZmljYWRvcmEgZGEgSnVzdGljYTCCASIwDQYJ318 KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMZdinSE3Ly323/o9QhmoXxj58rV88m8319 nNzlBPjs84dSB4nvaYTwCwZtbhk+NEbCzs8ydDL5JveYNqIP1sBtqxVz+nfEdDHV320 WdwJuPwrX+q5+zkv91C/nUDfvp6ZcKh2ufGeAdI6YjDiqiPJL8wUxOd4W/KAbejp321 6yynu6X3uUFaK4ziBEsTV5WwSnoh569KSJoDGr1Gyeo/2Di48UdAT3eEemW8l56G322 nwnXX+ZwDKwPMp4rn4nq9n+7VUxlProo+xEe3OUNe8iVXftRLjTp5nrvkXMwJ/g8323 Pu3CpsQUJgDl/GRpuUCB0Tb4c9zVVqu+DTToEytyV47VxJwLOFS76esCAwD3v6OB324 tzCBtDA9BgNVHR8ENjA0MDKgMKAuhixodHRwOi8vYWNyYWl6LmljcGJyYXNpbC5n325 b3YuYnIvTENSYWNyYWl6LmNybDASBgNVHSAECzAJMAcGBWBMAQETMB0GA1UdDgQW326 BBS+OdrawXcl4K69Gs6kW5/AemD8ZTAfBgNVHSMEGDAWgBSK+vFXhBETNZBC+ldJ327 VGkNpMTwNzAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG328 9w0BAQUFAAOCAQEAu22EJMIck6Q5E/piA3I26+JjChyuwU4UOWdk1GxqJ2AiI11N329 ZrjoEHc8W0gFTKZFFaywwBZYVqHvWao7iyRCDCXi4q2iVnPdA3GpMpuM69E2a5sf330 lH5Xd4VUoLpbozdio6hqjRSChX47MiIGu+B2b0DvtejdIIhkElnI2yysa0FhP7af331 qqr/FjH4Z1nDFxfJPIPQ3+u+nVICIGF7Fx/RCefIxo7+1/7e4IPsOdgCaJnsAE3x332 Kr1tz8mC+Wd8WR8ieeWwcEDt7frV1vXHSeqA8n0QwaNWfYneDWqklcr7Z9Z6bu6B333 yQfHRF6V/bSFpw6nZkYHZs7JO3w+3wmyJvc7Tg==334 -----END CERTIFICATE-----335 -----BEGIN CERTIFICATE-----336 232 MIIEczCCA1ugAwIBAgISMjAwNzA3MDYxNDA5MjgwMDAxMA0GCSqGSIb3DQEBBQUA 337 233 MFsxCzAJBgNVBAYTAkJSMRMwEQYDVQQKEwpJQ1AtQnJhc2lsMTcwNQYDVQQDEy5I … … 576 472 -----END CERTIFICATE----- 577 473 -----BEGIN CERTIFICAT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wYDVR0jBBgwFoAUivrxV4QREzWQQvpXSVRpDaTE8DcwDgYDVR0PAQH/BAQD593 AgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADUrc/zWTEEXMYEgO/AI594 lCFD5AWxE0qh80ysKgR0x+W1ULkYwSxM6sZrth3mzb4iIJk/KclqGns94kTLx6e4zFZpi2oK595 mltgkkTKMHjR6hanMMdGwJ1/jZL6APye0SmyL57rof0cM6k5d1reERYbj4HEpUSZlo2WZ5uk596 EfolqJwznssbROIlReQnpThk3Om5GVNJnblgEFFmUhcLoM+IY0Y0spORu938skMEGzECW8+o597 D93t4CCw7Dylho1gPVME85elx3OzQU56JfA5luCcrGXikbrKDTA/0Cy/JrRRn1nPfHXh1C2X598 ocL9SUmEVCNjMLAZL32jf3TTKk68dx6bqB4=599 -----END CERTIFICATE-----600 601 -----BEGIN CERTIFICATE-----602 474 MIID7jCCAtagAwIBAgIBATANBgkqhkiG9w0BAQUFADBPMQswCQYDVQQGEwJCUjEM 603 475 MAoGA1UEChMDSUNQMTIwMAYDVQQDEylBdXRvcmlkYWRlIENlcnRpZmljYWRvcmEg … … 622 494 f8YFOGMjwkNXNOY5t8ZTrrwBCrS8spJQ8DCO9l7wb1FzC2Gg5E3AdJW3mRky85vz 623 495 qWA= 624 -----END CERTIFICATE-----625 -----BEGIN CERTIFICATE-----626 MIIDuzCCAqOgAwIBAgIBAjANBgkqhkiG9w0BAQUFADBPMQswCQYDVQQGEwJCUjEM627 MAoGA1UEChMDSUNQMTIwMAYDVQQDEylBdXRvcmlkYWRlIENlcnRpZmljYWRvcmEg628 UmFpeiBIb21vbG9nYWNhbzAeFw0wOTAxMDMxNjAwMDlaFw0yMDAxMDMxNjAwMDla629 MFgxCzAJBgNVBAYTAkJSMQwwCgYDVQQKEwNJQ1AxOzA5BgNVBAMTMkF1dG9yaWRh630 ZGUgQ2VydGlmaWNhZG9yYSBJbnRlcm1lZGlhcmlhIEhvbW9sb2dhY2FvMIIBIjAN631 BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6VtI2zmzIqaNBls8f7p70Cu2WopJ632 c647RzxkqgIOKhkk67/UEkKYm3ZY1YmK1Y1k3iIpU0+upzH2/ohCo+OOCGAoucsI633 2NWMOb7XRkY7eO9wtD+ErBul/3dGb7feWVnIo4CYoFKmui4VgedV0XlXQoyi1PRA634 2NG+oSMEYyBfwenBppgbHJtAo898eRnx7ZGR/hhdojSw5JXF9AIjUuX2PyjZIXDa635 b6iIsIQ8SB1yMuZOuqGKdHZg0KXTYjJBkAhkoGtSxB+ikIdjNX9vmkUYAYB0kkcr636 X/iIc39yW/dGispzliAGcqXL7XCHxZjkyqvRJhBMxqQ0HCfKMix0trKD+QIDAQAB637 o4GYMIGVMB0GA1UdDgQWBBTWARCTrzdL6Khlw/VGYhjxdqma0zAPBgNVHRMBAf8E638 BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAVBgNVHSAEDjAMMAoGBmBMAQKDRTAAMDwG639 A1UdHwQ1MDMwMaAvoC2GK2h0dHA6Ly9jY2Rob20uc2VycHJvLmdvdi5ici9sY3Iv640 cmFpemhvbS5jcmwwDQYJKoZIhvcNAQEFBQADggEBADrg4jMKCAMgrGB9xqIMDwjg641 Yk0/p4xnqcCI1rGPyLK9e4upvcS5pwoxrlxwCI1RNTFltqOEmaT0thh2yrnD1BIX642 UNvX/OVV+RFnf0jAmEJ+D2iIDz+YVb+rMYxo7C9Xz0kvSzuQfZW/TbMHoV5PWh87643 6uPykYcoAzDtm3+sPbKMSO5FIijdfTxSbPyezQ4D1gs6FHBULeCXLx2lteHr5YTA644 glG8C3S1eJfWjVdF/Z+waEOSJmNshGPOKtIqn4oYr48H36hwNJVs4e+twAJoYJy/645 Z26h2241MRpxXymhfnkdb8Wa7ciAki9+37Pta2rjRXzzcSnSxsNUpIFP62rpfGs=646 496 -----END CERTIFICATE----- 647 497 -----BEGIN CERTIFICATE----- … … 671 521 EOonzgne4Q== 672 522 -----END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5pY3BicmFzaWwuZ292LmJyL0RQQ2FjcmFpei5wZGYwPQYDVR0f 589 BDYwNDAyoDCgLoYsaHR0cDovL2FjcmFpei5pY3BicmFzaWwuZ292LmJyL0xDUmFj 590 cmFpei5jcmwwHQYDVR0OBBYEFIr68VeEERM1kEL6V0lUaQ2kxPA3MA8GA1UdEwEB 591 /wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQAZA5c1 592 U/hgIh6OcgLAfiJgFWpvmDZWqlV30/bHFpj8iBobJSm5uDpt7TirYh1Uxe3fQaGl 593 YjJe+9zd+izPRbBqXPVQA34EXcwk4qpWuf1hHriWfdrx8AcqSqr6CuQFwSr75Fos 594 SzlwDADa70mT7wZjAmQhnZx2xJ6wfWlT9VQfS//JYeIc7Fue2JNLd00UOSMMaiK/ 595 t79enKNHEA2fupH3vEigf5Eh4bVAN5VohrTm6MY53x7XQZZr1ME7a55lFEnSeT0u 596 mlOAjR2mAbvSM5X5oSZNrmetdzyTj2flCM8CC7MLab0kkdngRIlUBGHF1/S5nmPb 597 K+9A46sd33oqK8n8 598 -----END CERTIFICATE----- 599 -----BEGIN CERTIFICATE----- 600 MIIEeDCCA2CgAwIBAgIBEzANBgkqhkiG9w0BAQUFADCBtDELMAkGA1UEBhMCQlIx 601 EzARBgNVBAoTCklDUC1CcmFzaWwxPTA7BgNVBAsTNEluc3RpdHV0byBOYWNpb25h 602 bCBkZSBUZWNub2xvZ2lhIGRhIEluZm9ybWFjYW8gLSBJVEkxETAPBgNVBAcTCEJy 603 YXNpbGlhMQswCQYDVQQIEwJERjExMC8GA1UEAxMoQXV0b3JpZGFkZSBDZXJ0aWZp 604 Y2Fkb3JhIFJhaXogQnJhc2lsZWlyYTAeFw0wNTAzMjQyMDAxMDBaFw0xMTEwMjQy 605 MzU5MDBaMIGPMQswCQYDVQQGEwJCUjETMBEGA1UEChMKSUNQLUJyYXNpbDE7MDkG 606 A1UECxMyU2VydmljbyBGZWR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D+QIDAQAB 689 o4GYMIGVMB0GA1UdDgQWBBTWARCTrzdL6Khlw/VGYhjxdqma0zAPBgNVHRMBAf8E 690 BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAVBgNVHSAEDjAMMAoGBmBMAQKDRTAAMDwG 691 A1UdHwQ1MDMwMaAvoC2GK2h0dHA6Ly9jY2Rob20uc2VycHJvLmdvdi5ici9sY3Iv 692 cmFpemhvbS5jcmwwDQYJKoZIhvcNAQEFBQADggEBADrg4jMKCAMgrGB9xqIMDwjg 693 Yk0/p4xnqcCI1rGPyLK9e4upvcS5pwoxrlxwCI1RNTFltqOEmaT0thh2yrnD1BIX 694 UNvX/OVV+RFnf0jAmEJ+D2iIDz+YVb+rMYxo7C9Xz0kvSzuQfZW/TbMHoV5PWh87 695 6uPykYcoAzDtm3+sPbKMSO5FIijdfTxSbPyezQ4D1gs6FHBULeCXLx2lteHr5YTA 696 glG8C3S1eJfWjVdF/Z+waEOSJmNshGPOKtIqn4oYr48H36hwNJVs4e+twAJoYJy/ 697 Z26h2241MRpxXymhfnkdb8Wa7ciAki9+37Pta2rjRXzzcSnSxsNUpIFP62rpfGs= 698 -----END CERTIFICATE----- -
branches/2.2/security/certificados.js
r1174 r3232 1 var num = 0; 2 var titulo = ''; 3 1 2 var ua = navigator.userAgent.toLowerCase(); 3 if (ua.indexOf(" chrome/") >= 0 || ua.indexOf(" firefox/") >= 0 || ua.indexOf(' gecko/') >= 0) { 4 var StringMaker = function () { 5 this.str = ""; 6 this.length = 0; 7 this.append = function (s) { 8 this.str += s; 9 this.length += s.length; 10 } 11 this.prepend = function (s) { 12 this.str = s + this.str; 13 this.length += s.length; 14 } 15 this.toString = function () { 16 return this.str; 17 } 18 } 19 } else { 20 var StringMaker = function () { 21 this.parts = []; 22 this.length = 0; 23 this.append = function (s) { 24 this.parts.push(s); 25 this.length += s.length; 26 } 27 this.prepend = function (s) { 28 this.parts.unshift(s); 29 this.length += s.length; 30 } 31 this.toString = function () { 32 return this.parts.join(''); 33 } 34 } 35 } 36 37 38 var num = 0; 39 var titulo = ''; 40 41 // This code was written by Tyler Akins and has been placed in the 42 // public domain. It would be nice if you left this header intact. 43 // Base64 code from Tyler Akins -- http://rumkin.com 44 45 var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; 46 47 function encode64(input) { 48 var output = new StringMaker(); 49 var chr1, chr2, chr3; 50 var enc1, enc2, enc3, enc4; 51 var i = 0; 52 53 while (i < input.length) { 54 chr1 = input.charCodeAt(i++); 55 chr2 = input.charCodeAt(i++); 56 chr3 = input.charCodeAt(i++); 57 58 enc1 = chr1 >> 2; 59 enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); 60 enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); 61 enc4 = chr3 & 63; 62 63 if (isNaN(chr2)) { 64 enc3 = enc4 = 64; 65 } else if (isNaN(chr3)) { 66 enc4 = 64; 67 } 68 69 output.append(keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4)); 70 } 71 72 return output.toString(); 73 } 74 75 function decode64(input) { 76 var output = new StringMaker(); 77 var chr1, chr2, chr3; 78 var enc1, enc2, enc3, enc4; 79 var i = 0; 80 81 // remove all characters that are not A-Z, a-z, 0-9, +, /, or = 82 input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); 83 84 while (i < input.length) { 85 enc1 = keyStr.indexOf(input.charAt(i++)); 86 enc2 = keyStr.indexOf(input.charAt(i++)); 87 enc3 = keyStr.indexOf(input.charAt(i++)); 88 enc4 = keyStr.indexOf(input.charAt(i++)); 89 90 chr1 = (enc1 << 2) | (enc2 >> 4); 91 chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); 92 chr3 = ((enc3 & 3) << 6) | enc4; 93 94 output.append(String.fromCharCode(chr1)); 95 96 if (enc3 != 64) { 97 output.append(String.fromCharCode(chr2)); 98 } 99 if (enc4 != 64) { 100 output.append(String.fromCharCode(chr3)); 101 } 102 } 103 104 return output.toString(); 105 } 106 4 107 function msgWin(msg,w,h,params) 5 { 6 var winl = (screen.width - w ) / 2; 7 var wint = (screen.height - h) / 2; 8 var parm = "width=" + w + ",height=" + h + ",top=" + wint + ",left=" + winl + params; 9 win3 = window.open("","12345" + num,parm); 10 num = num + 1; 11 win3.document.writeln(msg); 12 win3.focus(); 13 } 14 15 function Um_Certificado(valor) 16 { 17 if(valor.length < 2) { return; } 18 //verifica se o browser tem suporte a ajax 19 try 20 { 21 ajax = new ActiveXObject("Microsoft.XMLHTTP"); 22 } 23 catch(e) 24 { 25 try 26 { 27 ajax = new ActiveXObject("Msxml2.XMLHTTP"); 28 } 29 catch(ex) 30 { 31 try 32 { 33 ajax = new XMLHttpRequest(); 34 } 35 catch(exc) 36 { 37 alert("Esse browser não tem recursos para uso do Ajax"); 38 ajax = null; 39 } 40 } 41 } 42 43 //se tiver suporte ajax 44 if(ajax) 45 { 46 titulo = valor; 47 ajax.open("POST", "certs_xml.php", true); 48 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 49 ajax.onreadystatechange = function() 50 { 51 //enquanto estiver processando...emite a msg de carregando 52 //if(ajax.readyState == 1) 53 // { 54 // //idOpcao.innerHTML = "Obtendo Certificados ...! "; 55 // } 56 //após ser processado - chama função processa_um_certificado que vai varrer os dados 57 if(ajax.readyState == 4 ) 58 { 59 if(ajax.responseXML) 60 { 61 processa_um_certificado(ajax.responseXML); 62 } 63 else 64 { 65 //caso não seja um arquivo XML emite a mensagem abaixo 66 msg = 'Não foi possível obter dados do certificado.' + '<br/><br/><div align="center"><INPUT type="button" value="Fechar" onClick="window.close()">'; 67 parms = ",scrollbars=1"; 68 msgWin(msg,450,200,parms) 69 } 70 } 71 } 72 //passa o código do certificado desejado... 73 var params = "id="+valor; 74 ajax.send(params); 75 } 76 } 108 { 109 var winl = (screen.width - w ) / 2; 110 var wint = (screen.height - h) / 2; 111 var parm = "width=" + w + ",height=" + h + ",top=" + wint + ",left=" + winl + params; 112 win3 = window.open("","12345" + num,parm); 113 num = num + 1; 114 win3.document.writeln(msg); 115 win3.focus(); 116 } 117 118 function Remover(valor,valor2) 119 { 120 var resp = confirm("Remover certificado n. " + valor + " do arquivo " + valor2 + " ?"); 121 if (resp){ 122 document.getElementById('msgs').innerHTML = ''; 123 Remover_Certificado(valor,valor2); 124 Lista_de_Certificados(); 125 } 126 } 127 128 function Submete_Cas(id,msg) 129 { 130 if(document.getElementById('file').value != ''){ 131 var resp = confirm(msg); 132 if (resp){ 133 document.getElementById(id).submit(); 134 } 135 else{ 136 document.getElementById('file').value = ''; 137 } 138 } 139 else{ 140 alert('Selecione um arquivo valido( .pem, .der, .cer .pfx, .p7b'); 141 } 142 } 143 144 function Salvar_arq(id,msg) 145 { 146 var resp = confirm(msg); 147 if (resp){ 148 document.getElementById(id).submit(); 149 } 150 } 151 152 function Remover_Certificado(valor,valor2) 153 { 154 //verifica se o browser tem suporte a ajax11 155 try 156 { 157 ajax1 = new ActiveXObject("Microsoft.XMLHTTP"); 158 } 159 catch(e) 160 { 161 try 162 { 163 ajax1 = new ActiveXObject("Msxml2.XMLHTTP"); 164 } 165 catch(ex) 166 { 167 try 168 { 169 ajax1 = new XMLHttpRequest(); 170 } 171 catch(exc) 172 { 173 alert("Esse browser não tem recursos para uso do ajax1"); 174 ajax1 = null; 175 } 176 } 177 } 178 179 //se tiver suporte ajax1 180 if(ajax1) 181 { 182 ajax1.open("POST", "manut_certs.php", true); 183 ajax1.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 184 ajax1.onreadystatechange = function() 185 { 186 if(ajax1.readyState == 4 ) 187 { 188 if(ajax1.responseXML) 189 { 190 var arqx = processa_remover_certificado(ajax1.responseXML); 191 } 192 else 193 { 194 //caso não seja um arquivo XML emite a mensagem abaixo 195 //alert('Nao foi possivel remover o certificado(M01).'); 196 } 197 } 198 } 199 //passa o código do certificado desejado... 200 var params = "id=" + valor + '&arquivo=' + valor2; 201 ajax1.send(params); 202 } 203 } 204 205 function processa_remover_certificado(obj) 206 { 207 var dataArray = obj.getElementsByTagName("certificados"); 208 //total de elementos contidos na tag 209 if(dataArray.length > 0) 210 { 211 if (navigator.userAgent.match('MSIE')) 212 { 213 var conteudo = dataArray[0].text; 214 } 215 else 216 { 217 var conteudo = dataArray[0].textContent; 218 } 219 if(conteudo.substr(0,2) == 'OK') 220 { 221 alert('Certificado removido de ' + conteudo.substr(2) + '.'); 222 var path3 = conteudo.substr(2); 223 } 224 else 225 { 226 alert('Certificado nao removido de ' + conteudo.substr(0,4)); 227 var path3 = conteudo.substr(2); 228 } 229 } 230 else 231 { 232 //caso o XML volte vazio, printa a mensagem abaixo 233 alert('Nao foi possivel remover o certificado(M02).'); 234 var path3 = ''; 235 } 236 return path3; 237 } 238 239 240 241 function Um_Certificado(valor,valor2) 242 { 243 if(valor.length < 2) { 244 return; 245 } 246 //verifica se o browser tem suporte a ajax3 247 try 248 { 249 ajax3 = new ActiveXObject("Microsoft.XMLHTTP"); 250 } 251 catch(e) 252 { 253 try 254 { 255 ajax3 = new ActiveXObject("Msxml2.XMLHTTP"); 256 } 257 catch(ex) 258 { 259 try 260 { 261 ajax3 = new XMLHttpRequest(); 262 } 263 catch(exc) 264 { 265 alert("Esse browser não tem recursos para uso do ajax3"); 266 ajax3 = null; 267 } 268 } 269 } 270 271 //se tiver suporte ajax3 272 if(ajax3) 273 { 274 titulo = valor; 275 ajax3.open("POST", "certs_xml.php", true); 276 ajax3.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 277 ajax3.onreadystatechange = function() 278 { 279 //após ser processado - chama função processa_um_certificado que vai varrer os dados 280 if(ajax3.readyState == 4 ) 281 { 282 if(ajax3.responseXML) 283 { 284 processa_um_certificado(ajax3.responseXML); 285 } 286 else 287 { 288 //caso não seja um arquivo XML emite a mensagem abaixo 289 msg = 'Não foi possível obter os dados solicitados(1).' + '<br/><br/><div align="center"><INPUT type="button" value="Fechar" onClick="window.close()">'; 290 parms = ",scrollbars=1"; 291 msgWin(msg,450,200,parms) 292 } 293 } 294 } 295 //passa o código do certificado desejado... 296 var params = "id="+valor + '&arquivo=' + valor2; 297 ajax3.send(params); 298 } 299 } 77 300 78 function processa_um_certificado(obj) 79 { 80 // Tab com tags que deve exibir sho o nome.... 81 var TBtags = new Array( "EMISSOR_CAMINHO_COMPLETO", "SUBJECT" , "CRLDISTRIBUTIONPOINTS" , "KEYUSAGE" ); 82 //pega a tag certificado 83 var dataArray = obj.getElementsByTagName("certificado"); 84 //total de elementos contidos na tag 85 if(dataArray.length > 0) 86 { 87 var novo = "<head><title>" + titulo + "</title></head><body><font size=2><h3 align=center ><font color=#0000EE>Dados do certificado</font></h3>"; 88 //percorre o arquivo XML para extrair os dados 89 for(var i = 0 ; i < dataArray.length ; i++) 90 { 91 var item = dataArray[i]; 92 var cc = item.getElementsByTagName("*"); 93 len = 0; 94 for(var j = 0 ; j < cc.length ; j++) 95 { 96 //contéudo dos campos no arquivo XML 97 var tag = cc[j].nodeName 98 if(tag == "CA") continue; // skipa tag CA .... 99 var xflag = 0; 100 for(var iz = 0;iz< TBtags.length;iz++) 101 { 102 if(TBtags[iz] == tag) xflag = 1; 103 } 104 // Testa se deve exibir o valor da tag.. 105 if(xflag ==1 ) 106 { 107 var nome = "<b>" +tag +":</b> "; 108 } 109 else 110 { 111 // Testa o browser para usar a propriedade correta ... 112 if (navigator.userAgent.match('MSIE')) 113 { 114 var conteudo = cc[j].text; 115 } 116 else 117 { 118 var conteudo = cc[j].textContent; 119 } 301 function processa_um_certificado(obj) 302 { 303 // Tab com tags que deve exibir sho o nome.... 304 var TBtags = new Array( "EMISSOR_CAMINHO_COMPLETO", "SUBJECT" , "CRLDISTRIBUTIONPOINTS" , "KEYUSAGE" , "EXTKEYUSAGE" ); 305 //pega a tag certificado 306 var dataArray = obj.getElementsByTagName("certificado"); 307 //total de elementos contidos na tag 308 if(dataArray.length > 0) 309 { 310 var novo = "<head><title>" + titulo + "</title></head><body><font size=2><h3 align=center ><font color=#0000EE>Dados do certificado</font></h3>"; 311 //percorre o arquivo XML para extrair os dados 312 for(var i = 0 ; i < dataArray.length ; i++) 313 { 314 var item = dataArray[i]; 315 var cc = item.getElementsByTagName("*"); 316 len = 0; 317 for(var j = 0 ; j < cc.length ; j++) 318 { 319 //contéudo dos campos no arquivo XML 320 var tag = cc[j].nodeName 321 if(tag == "CA") continue; // skipa tag CA .... 322 var xflag = 0; 323 if(tag.substr(0,3) == "oid") xflag = 1; 324 for(var iz = 0;iz< TBtags.length;iz++) 325 { 326 if(TBtags[iz] == tag) xflag = 1; 327 } 328 // Testa se deve exibir o valor da tag.. 329 if(xflag ==1 ) 330 { 331 var nome = "<b>" +tag +":</b> "; 332 } 333 else 334 { 335 // Testa o browser para usar a propriedade correta ... 336 if (navigator.userAgent.match('MSIE')) 337 { 338 var conteudo = cc[j].text; 339 } 340 else 341 { 342 var conteudo = cc[j].textContent; 343 } 120 344 121 if(conteudo == "1") 122 123 124 345 if(conteudo == "1") 346 { 347 conteudo = "Sim."; 348 } 125 349 126 if(conteudo == "") 127 128 129 } 350 if(conteudo == "") 351 { 352 conteudo = "Não."; 353 } 130 354 131 132 355 switch(tag) 356 { 133 357 134 case "INICIO_VALIDADE": 135 { 136 var aux = conteudo.substr(0,4) + "/" + conteudo.substr(4,2) + "/" + conteudo.substr(6,2) + " - " + conteudo.substr(8,2) + ":" + conteudo.substr(10,2) + ":" + conteudo.substr(12,2) + " GMT"; 137 conteudo = aux; 138 break; 139 } 140 case "FIM_VALIDADE": 141 { 142 var aux = conteudo.substr(0,4) + "/" + conteudo.substr(4,2) + "/" + conteudo.substr(6,2) + " - " + conteudo.substr(8,2) + ":" + conteudo.substr(10,2) + ":" + conteudo.substr(12,2) + " GMT"; 143 conteudo = aux; 144 break; 145 } 146 default: 147 { 148 break; 149 } 150 } 151 var nome = "<b>" + tag +":</b> " + conteudo; 152 } 153 novo = novo + nome + '<br/>'; 154 len = len + 24; 155 } 156 } 157 msg = novo + '<br/><br/><div align="center"><INPUT type="button" value="Fechar" onClick="window.close()"></font></body>'; 158 } 159 else 160 { 161 //caso o XML volte vazio, printa a mensagem abaixo 162 msg = 'Não foi possível obter dados do certificado.' + '<br/><br/><div align="center"><INPUT type="button" value="Fechar" onClick="window.close()"></font></body>'; 163 len =200; 164 } 165 parms = ",scrollbars=1"; 166 num = num + 1; 167 msgWin(msg,450,len,parms) 168 } 169 358 case "INICIO_VALIDADE": 359 { 360 var aux = conteudo.substr(0,4) + "/" + conteudo.substr(4,2) + "/" + conteudo.substr(6,2) + " - " + conteudo.substr(8,2) + ":" + conteudo.substr(10,2) + ":" + conteudo.substr(12,2) + " GMT"; 361 conteudo = aux; 362 break; 363 } 364 case "FIM_VALIDADE": 365 { 366 var aux = conteudo.substr(0,4) + "/" + conteudo.substr(4,2) + "/" + conteudo.substr(6,2) + " - " + conteudo.substr(8,2) + ":" + conteudo.substr(10,2) + ":" + conteudo.substr(12,2) + " GMT"; 367 conteudo = aux; 368 break; 369 } 370 default: 371 { 372 break; 373 } 374 } 375 var nome = "<b>" + tag +":</b> " + conteudo; 376 } 377 novo = novo + nome + '<br/>'; 378 len = len + 24; 379 } 380 } 381 msg = novo + '<br/><br/><div align="center"><INPUT type="button" value="Fechar" onClick="window.close()"></font></body>'; 382 } 383 else 384 { 385 //caso o XML volte vazio, printa a mensagem abaixo 386 msg = 'Não foi possível obter dados do certificado(2).' + '<br/><br/><div align="center"><INPUT type="button" value="Fechar" onClick="window.close()"></font></body>'; 387 len =200; 388 } 389 parms = ",scrollbars=1"; 390 num = num + 1; 391 msgWin(msg,450,len,parms) 392 } 393 394 function Lista_de_Certificados() 395 { 396 //document.getElementById('titulo1').innerHTML = 'Certificados em ' + path4; 397 try 398 { 399 ajax4 = new ActiveXObject("Microsoft.XMLHTTP"); 400 } 401 catch(e) 402 { 403 try 404 { 405 ajax4 = new ActiveXObject("Msxml2.XMLHTTP"); 406 } 407 catch(ex) 408 { 409 try 410 { 411 ajax4 = new XMLHttpRequest(); 412 } 413 catch(exc) 414 { 415 alert("Esse browser não tem recursos para uso do ajax4"); 416 ajax4 = null; 417 } 418 } 419 } 420 421 if(ajax4) 422 { 423 ajax4.open("POST", "certs_xml.php", true); 424 ajax4.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 425 ajax4.onreadystatechange = function() 426 { 427 if(ajax4.readyState == 4 ) 428 { 429 if(ajax4.responseXML) 430 { 431 Processa_Lista_de_Certificados(ajax4.responseXML); 432 Lista_Arvore(); 433 } 434 else 435 { 436 //caso não seja um arquivo XML emite a mensagem abaixo 437 alert("Ocorreu um erro acessando os dados solicitados.Er-001 - " + ajax4.readyState); 438 } 439 } 440 } 441 document.getElementById('xdiv1').innerHTML = '<br/><font color="#000066"><b> Carregando ...</b></font>'; 442 document.getElementById('xdiv2').innerHTML = '<br/><font color="#000066"><b> Carregando ...</b></font>'; 443 //document.getElementById('path3x').value = path4; 444 //passa o código do certificado desejado... 445 //var params = "id=A&path3=" + path4; 446 var params = "id=A"; 447 ajax4.send(params); 448 } 449 } 450 451 function Processa_Lista_de_Certificados(obj) 452 { 453 //pega a tag certificado 454 var dataArray = obj.getElementsByTagName("cert"); 455 if(dataArray.length > 0) 456 { 457 var novo = '<table border="1" width="100%" ><tr><th>Item</th><th>Remover</th><th>Autoridade Certificadora</th><th>Validade</th></tr>'; 458 //percorre o arquivo XML para extrair os dados 459 var conteudo = ''; 460 for(var i = 0 ; i < dataArray.length ; i++) 461 { 462 var item = dataArray[i]; 463 var cc = item.getElementsByTagName("*"); 464 // Testa o browser para usar a propriedade correta ... 465 //var aux = path5.split('/'); 466 var aux = 'todos.cer'; 467 //aux_novo = '<a href="javascript:Remover(\''+ cc[0].textContent + '\',\'' + aux[aux.length-1] + '\')" style="text-decoration: none;margin:0 0 0 20" ><img src="delete.gif" style="border:none" title="Clique para remover este certificado..."/></a>'; 468 aux_novo = '<a href="javascript:Remover(\''+ cc[0].textContent + '\',\'' + aux + '\')" style="text-decoration: none;margin:0 0 0 20" ><img src="delete.gif" style="border:none" title="Clique para remover este certificado..."/></a>'; 469 //novo = novo + aux_novo + conteudo + '<br/>'; 470 if (navigator.userAgent.match('MSIE')) 471 { 472 var conteudo1 = cc[1].text; 473 if (conteudo1.indexOf('DUPLICADO') != -1) 474 { 475 var conteudo1 = '<font color="#FF0000"><b>' + conteudo + '</b></font>'; 476 } 477 var conteudo = '<tr><td><font size="1">' + cc[0].text + '</font></td><td><font size="1">' + aux_novo + '</font> </td><td><font size="1">' + conteudo1 + ' </font></td><td><font size="1">' + cc[2].text + '</font></td></tr>'; 478 } 479 else 480 { 481 if ( cc[2].textContent.indexOf('DUPLICADO') != -1) 482 { 483 var conteudo2 = '<font size="1" color="#FF0000"><b>' + cc[2].textContent + '</b></font>'; 484 } 485 else 486 { 487 var conteudo2 = '<font size="1">' + cc[2].textContent + '</font>'; 488 } 489 var conteudo = '<tr><td><font size="1">' + cc[0].textContent + '</font></td><td><font size="1">' + aux_novo + ' </font></td><td><font size="1">' + cc[1].textContent + ' </font></td><td>' + conteudo2 + '</td></tr>'; 490 //var conteudo = cc[0].textContent + ' - ' + cc[1].textContent + ' # ' + cc[2].textContent; 491 } 492 493 if (conteudo.indexOf('DUPLICADO') != -1) 494 { 495 var conteudo = '<font color="#FF0000"><b>' + conteudo + '</b></font>'; 496 } 497 498 499 novo = novo + conteudo; 500 501 } 502 msg = novo + '</table>'; 503 } 504 else 505 { 506 //caso o XML volte vazio, printa a mensagem abaixo 507 msg = 'Não foi possível obter dados dos certificados.V02'; 508 } 509 document.getElementById('xdiv1').innerHTML = msg; 510 } 511 512 function Lista_Arvore(path3) 513 { 514 //document.getElementById('titulo1').innerHTML = 'Certificados em ' + path3; 515 //verifica se o browser tem suporte a ajax5 516 try 517 { 518 ajax5 = new ActiveXObject("Microsoft.XMLHTTP"); 519 } 520 catch(e) 521 { 522 try 523 { 524 ajax5 = new ActiveXObject("Msxml2.XMLHTTP"); 525 } 526 catch(ex) 527 { 528 try 529 { 530 ajax5 = new XMLHttpRequest(); 531 } 532 catch(exc) 533 { 534 alert("Esse browser não tem recursos para uso do ajax5"); 535 ajax5 = null; 536 } 537 } 538 } 539 //se tiver suporte ajax5 540 if(ajax5) 541 { 542 ajax5.open("POST", "gera-arvore.php", true); 543 ajax5.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 544 ajax5.onreadystatechange = function() 545 { 546 if(ajax5.readyState == 4 ) 547 { 548 if(ajax5.responseXML) 549 { 550 Processa_Lista_Arvore(ajax5.responseXML); 551 } 552 else 553 { 554 //caso não seja um arquivo XML emite a mensagem abaixo 555 alert("Erro lendo Certificdos das Cas...") 556 } 557 } 558 } 559 //passa o código do certificado desejado... 560 var params = "path3=" + path3; 561 ajax5.send(params); 562 } 563 } 564 565 function Processa_Lista_Arvore(obj) 566 { 567 var dataArray = obj.getElementsByTagName("certificados"); 568 if(dataArray[0].textContent) 569 { 570 document.getElementById('xdiv2').innerHTML = decode64(dataArray[0].textContent); 571 } 572 else 573 { 574 document.getElementById('xdiv2').innerHTML = 'Não foi possível obter dados dos certificados.V01'; 575 } 576 } -
branches/2.2/security/certs_xml.php
r1174 r3232 1 1 <?php 2 $GLOBALS['phpgw_info'] = array(); 3 $GLOBALS['phpgw_info']['flags'] = array('noheader' => True,'nonavbar' => True,'currentapp' => 'admin'); 4 include('../header.inc.php'); 2 5 require_once('classes/CertificadoB.php'); 6 $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; 3 7 // pega caminho completo do arquivo de CAS.. 4 8 $path3 =$GLOBALS['CAs']; 5 9 // se não pude acessar o arquivo com certificados retornar ..... 6 if(!is_file($path3)) exit(); 7 $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; 10 if(!is_file($path3)) 11 { 12 $xml .= '<certificados><cert><item>' . $path3 . '</item><nome>Path para pasta com certificados esta invalida</nome><validade></validade></cert></certificados>'; 13 Header('Content-type: application/xml; charset=utf-8'); 14 echo $xml; 15 exit(); 16 } 8 17 $todos_certificados = ler_certificados_CAS($path3); 9 18 $CB = new CertificadoB(); 10 if($_REQUEST['id']) 11 { 12 if($_REQUEST['id'] != 'A') 13 { 14 // id indica o certificado solicitado .... 15 $aux = explode('-',$_REQUEST['id']); 16 if(count($aux) > 1) 17 { 18 $id =$aux[0]; 19 $id = $id -1; 20 } 21 else 22 { 23 $id = 0; 24 } 25 // Pega o certificado solicitado ... 26 $certificado = $todos_certificados[$id]; 27 // Vai parsear, e gerar o xml ... 28 $CB -> certificado($certificado); 29 // Pega o xml com os dados do certificado .. 30 $xml .= $CB -> dados_xml; 31 } 32 else 33 { 34 // Requisitado todo o conteudo do arquivo de CAs .. 35 $item = 1; 36 $xml .= "<certs>"; 37 foreach($todos_certificados as $certificado) 38 { 39 $CB -> certificado($certificado); 40 $df = $CB -> dados['FIM_VALIDADE']; 41 $xml .= '<certs>'; 42 $xml .= ' <nome>' . 43 $item++ . ' - ' . 44 $CB->dados['SUBJECT']['CN'] . 45 ' ( Expira Em: ;' . substr($df,0,4) . 46 '/' . 47 substr($df,4,2) . 48 '/' . 49 substr($df,6,2) . 50 ' - ' . 51 substr($df,8,2) . 52 ':' . 53 substr($df,10,2) . 54 ':' . 55 substr($df,12,2) . 56 ' GMT )' . 57 '</nome>'; 58 $xml .= '</certs>'; 59 } 60 $xml .= "</certs>"; 61 } 62 } 19 //$_POST['id'] = 'A'; 20 if($_POST['id']) 21 { 22 if($_POST['id'] != 'A') 23 { 24 // id indica o certificado solicitado .... 25 $aux = explode('-',$_POST['id']); 26 if(count($aux) > 1) 27 { 28 $id =$aux[0]; 29 $id = $id -1; 30 } 31 else 32 { 33 $id = 0; 34 } 35 // Pega o certificado solicitado ... 36 $certificado = $todos_certificados[$id]; 37 // Vai parsear, e gerar o xml ... 38 $CB -> certificado($certificado); 39 // Pega o xml com os dados do certificado .. 40 $xml .= $CB -> dados_xml; 41 } 42 else 43 { 44 // Requisitado todo o conteudo do arquivo de CAs .. 45 $item = 1; 46 $processados = array(); 47 $xml .= "<certificados>"; 48 //$xml .= '<cert><item>0</item><nome>Parametro xxxxxxxxxx xxxxxxxxxxxxxxxxxxxx invalido.</nome><validade> asdad </validade></cert>'; 49 50 foreach($todos_certificados as $certificado) 51 { 52 $CB -> certificado($certificado); 53 $df = $CB -> dados['FIM_VALIDADE']; 54 $xml .= '<cert>'; 55 $xml .= '<item>' . $item++ . '</item>'; 56 $xml .= ' <nome>' . $CB->dados['SUBJECT']['CN'] . '</nome>'; 57 if($processados[$CB->dados['SUBJECT']['CN']]) 58 { 59 $alerta = '<font color="#FF0000"><b>DUPLICADO (veja o item ' . $processados[$CB->dados['SUBJECT']['CN']] . ' acima) </b></font>'; 60 } 61 else 62 { 63 $alerta = ''; 64 $processados[$CB->dados['SUBJECT']['CN']] = $item-1; 65 } 66 $xml .= '<validade> ' . $alerta . ' Valido ate ' . substr($df,0,4) . '/' . substr($df,4,2) . 67 '/' . 68 substr($df,6,2) . 69 ' - ' . 70 substr($df,8,2) . 71 ':' . 72 substr($df,10,2) . 73 ':' . 74 substr($df,12,2) . 75 ' GMT' . '</validade>'; 76 $xml .= '</cert>'; 77 } 78 79 80 $xml .= "</certificados>"; 81 82 } 83 } 63 84 else 64 65 exit(); 66 85 { 86 $xml .= '<certificados><cert><item>99</item><nome>Parametro invalido.</nome><validade> </validade></cert></certificados>'; 87 } 67 88 # Fecha o processamento de geracao do xml com um CABEÇALHO 68 Header('Content-type: application/xml; charset=utf-8'); 89 Header('Content-type: application/xml; charset=utf-8'); 69 90 echo $xml; 70 91 ?> -
branches/2.2/security/classes/CertificadoB.php
r1636 r3232 9 9 public $dados = array(); # Area para armazenar os dados recuperados do certificado. 10 10 public $apresentado = false; # Deve ser testado para verificar se no certificado processado foi localizado o CPF 11 public $erros_ssl = array(); 12 public $cert_assinante = ''; 11 public $erros_ssl = array(); 12 public $cert_assinante = ''; 13 13 public $msg_sem_assinatura = ''; #conteï¿œdo da mensagem sem assinatura, que retorna da funᅵᅵo verify do openssl 14 14 public $arquivos_para_deletar = array(); 15 15 16 16 public function __construct() 17 17 { … … 32 32 public function __destruct() 33 33 { 34 #Remover arquivos temporarios..... 34 #Remover arquivos temporarios..... 35 35 deleta_arquivos_temporarios($this->arquivos_para_deletar); 36 36 } 37 37 38 # Recupera dados de um certificado no formato pem 38 # Recupera dados de um certificado no formato pem 39 39 function certificado($certificado_pem) 40 { 41 if (!$certificado_pem) 40 { 41 if (!$certificado_pem) 42 42 { 43 43 $this->apresentado = False; … … 46 46 $this->dados = recupera_dados_do_ceritificado_digital($certificado_pem); 47 47 $this->dados_xml = gera_xml_com_dados_do_certificado($this->dados); 48 # Certificado foi processado, as informacoes obtidas estao em $this->dados. 49 $this->apresentado = true; 48 # Certificado foi processado, as informacoes obtidas estao em $this->dados. 49 $this->apresentado = true; 50 50 } 51 51 … … 71 71 72 72 $w = exec('openssl rsautl -in ' . $senha_arquivo_temporario . ' -out ' . $senha_criptografada_arquivo_temporario . ' -inkey ' . $cert_arquivo_temporario . ' -certin -pkcs -keyform PEM -encrypt',$saida); 73 73 74 74 if(!file_exists($senha_criptografada_arquivo_temporario)) 75 75 { … … 79 79 } 80 80 81 # Recupera a senha criptada, binario..... 81 # Recupera a senha criptada, binario..... 82 82 $retorno = file_get_contents($senha_criptografada_arquivo_temporario); 83 83 … … 97 97 if(!is_array($c)) return false; 98 98 $aux = count($c); 99 if($aux < 1) return false; 99 if($aux < 1) return false; 100 100 if(!is_array($h) ) return false; 101 101 # Tem de verificar todos os certificados que serao utilizados para criptografar a msg.. … … 109 109 $enc_arquivo_temporario = gera_nome_arquivo_temporario(&$this->arquivos_para_deletar); 110 110 //echo $enc_arquivo_temporario.'<br>'; 111 111 112 112 // LIMPA ERROS ... Pode ser um problema para outras aplicacoes que usam openssl(fonte de erros unica). 113 113 while ($erro = openssl_error_string()); // Limpa buffer de erros anteriores...... … … 118 118 { 119 119 // Guarda msgs de erro ... 120 while ($erro = openssl_error_string()) 121 { 120 while ($erro = openssl_error_string()) 121 { 122 122 $this->erros_ssl[] = $erro; 123 123 } … … 126 126 return false; 127 127 } 128 # Recupera a msg criptada...... 128 # Recupera a msg criptada...... 129 129 $retorno = file_get_contents($enc_arquivo_temporario); 130 130 deleta_arquivos_temporarios($this->arquivos_para_deletar); … … 134 134 135 135 136 # Verifica uma msg($m) assinada... 136 # Verifica uma msg($m) assinada... 137 137 public function verificar($m) 138 138 { … … 166 166 while ($erro = openssl_error_string()); // Limpa buffer de erros anteriores...... 167 167 $this->erros_ssl = array(); 168 $resultado = openssl_pkcs7_verify($m_arquivo_temporario,0, $vrf_cert_arquivo_temporario,array($GLOBALS['CAs']),$GLOBALS['CAs'],$vrf_msg_arquivo_temporario); 169 $retorno = true; 168 $resultado = openssl_pkcs7_verify($m_arquivo_temporario,0, $vrf_cert_arquivo_temporario,array($GLOBALS['CAs']),$GLOBALS['CAs'],$vrf_msg_arquivo_temporario); 169 $retorno = true; 170 170 if($resultado === false || $resultado == -1) 171 171 { 172 # Indica ocorrencia de erro ... 172 # Indica ocorrencia de erro ... 173 173 $retorno = false; 174 174 // Guarda msgs de erro ... 175 while ($erro = openssl_error_string()) 176 { 175 while ($erro = openssl_error_string()) 176 { 177 177 $this->erros_ssl[] = $erro; 178 178 } 179 If(file_exists($vrf_msg_arquivo_temporario)) 179 If(file_exists($vrf_msg_arquivo_temporario)) 180 180 { 181 181 $this->msg_sem_assinatura = file_get_contents($vrf_msg_arquivo_temporario); … … 190 190 { 191 191 # Se nao foi possivel obter o certificado retorna com falso ..... 192 If(file_exists($vrf_msg_arquivo_temporario)) 192 If(file_exists($vrf_msg_arquivo_temporario)) 193 193 { 194 194 $this->msg_sem_assinatura = file_get_contents($vrf_msg_arquivo_temporario); … … 218 218 { 219 219 while ($erro = openssl_error_string()); // Limpa buffer de erros anteriores...... 220 # Certificado poderia ter assinado um email?? 220 # Certificado poderia ter assinado um email?? 221 221 if(!($this->dados['KEYUSAGE']['digitalSignature'])) 222 222 { 223 223 $this->erros_ssl[] = 'Certificado nao poderia ter sido utilizado para assinar email.'; 224 while ($erro = openssl_error_string()) 225 { 224 while ($erro = openssl_error_string()) 225 { 226 226 $this->erros_ssl[] = $erro; 227 227 } … … 242 242 } 243 243 deleta_arquivos_temporarios($this->arquivos_para_deletar); 244 $this->arquivos_para_deletar = array(); 244 $this->arquivos_para_deletar = array(); 245 245 return $retorno; 246 } 246 } 247 247 248 248 public function extrai_certificado_da_msg_assinada($m) … … 294 294 $retorno = $item; 295 295 break; 296 } 296 } 297 297 } 298 298 deleta_arquivos_temporarios($this->arquivos_para_deletar); -
branches/2.2/security/classes/Verifica_Certificado.php
r1174 r3232 38 38 return false; 39 39 } 40 if($this->Testa_se_Certificado_Revogado(trim($GLOBALS['CRLs'].$this->CRL),$parametro1['SERIALNUMBER'])) 41 { 42 $this->msgerro = 'MSG011 - Ocorreu erro validando o certificado.'; 43 return false; 44 } 40 if($GLOBALS['CRLs'] != '') 41 { 42 if($this->Testa_se_Certificado_Revogado(trim($GLOBALS['CRLs'].$this->CRL),$parametro1['SERIALNUMBER'])) 43 { 44 $this->msgerro = 'MSG011 - Ocorreu erro validando o certificado.'; 45 return false; 46 } 47 } 45 48 $this->status = true; 46 49 } -
branches/2.2/security/classes/Verifica_Certificado_conf.php
r1174 r3232 1 1 <?php 2 $GLOBALS['dirtemp'] = '/var/www/expresso/security/temp'; 3 $GLOBALS['CAs'] = '/var/www/expresso/security/cas/todos.cer'; 4 $GLOBALS['CRLs'] = '/var/www/expresso/security/crls/'; 2 $GLOBALS['BASE'] = dirname(__FILE__).'/../../'; 3 //$GLOBALS['BASE'] = PHPGW_SERVER_ROOT; // '/var/www/expresso'; 4 $GLOBALS['dirtemp'] = $GLOBALS['BASE'] . '/security/temp'; 5 $GLOBALS['CAs'] = $GLOBALS['BASE'] . '/security/cas/todos.cer'; 6 # Informar $GLOBALS['CRLs'] = '' para o Expresso nao verificar se certificado esta revogado. 7 $GLOBALS['CRLs'] = $GLOBALS['BASE'] . '/security/crls/'; // Tem de ter a barra no final 8 $GLOBALS['arquivos_crls'] = $GLOBALS['BASE'] . '/security/crl_admin/crl_admin.conf'; 9 $GLOBALS['log'] = $GLOBALS['BASE'] . '/logs/arquivo_crls.log'; 10 $GLOBALS['lenMax'] = 1048576; // 1MBytes = tamanho maximo do arquivo(em bytes) de log antes do rotate..... 11 $GLOBALS['bkpNum'] = 10; // Número de arquivos de log mantidos pelo rotate.... 5 12 ?> -
branches/2.2/security/classes/funcoes_auxiliares.php
r1574 r3232 34 34 } 35 35 36 function ler_certificados_CAS($path) 37 { 38 // Ler o arquivo contendo certificados das Cas. 39 // Retorna array com os certificados formato PEM ... 40 $retorno = array(); 41 if(file_exists($path)) 42 { 43 $dados_do_arquivo = file_get_contents($path); 44 $inicio = '-----BEGIN CERTIFICATE-----'; 45 $fim = '-----END CERTIFICATE-----'; 46 $aux1 = explode($inicio,$dados_do_arquivo); 47 foreach($aux1 as $aux2) 48 { 49 if($aux2) 50 { 51 $aux3 = explode($fim,$aux2); 52 $retorno[] =$inicio . $aux3[0] . $fim; 53 } 54 } 55 } 56 return $retorno; 57 } 58 36 function ler_certificados_CAS($path,$flag=false) 37 { 38 // Ler o arquivo contendo certificados das Cas. 39 // Retorna array com os certificados formato PEM ... 40 $retorno = array(); 41 if($flag === false) 42 { 43 if(!file_exists($path)) 44 { 45 return $retorno; 46 } 47 $dados_do_arquivo = file_get_contents($path); 48 } 49 else 50 { 51 $dados_do_arquivo = $path; 52 } 53 $inicio = '-----BEGIN CERTIFICATE-----'; 54 $fim = '-----END CERTIFICATE-----'; 55 $aux1 = explode($inicio,$dados_do_arquivo); 56 foreach($aux1 as $aux2) 57 { 58 if($aux2) 59 { 60 $aux3 = explode($fim,$aux2); 61 $retorno[] =$inicio . $aux3[0] . $fim; 62 } 63 } 64 return $retorno; 65 } 66 59 67 function gera_xml_com_dados_do_certificado($dados) 60 68 { 61 // Recebe array com dados de um certificado e gera o xml com estes dados. 62 // As chaves formam os tags e os dados o conteudo do tag .... 63 $aux_xml = "<certificado>"; 64 if(is_array($dados)) 65 { 66 foreach($dados as $K => $valor) 67 { 68 if(!is_array($valor)) 69 { 70 $aux_xml .= ' <' . $K . '>'.$valor.'</' . $K . '>'; 71 } 72 else 73 { 74 $aux_xml .= ' <' . $K . '>'; 75 foreach($valor as $KX => $valorx) 76 { 77 if(is_int($KX)) $KX = 'D' . $KX; 78 $aux_xml .= ' <' . $KX . '>'.$valorx.'</' . $KX . '>'; 79 } 80 $aux_xml .= ' </' . $K . '>'; 81 } 82 } 83 } 84 $aux_xml .= "</certificado>"; 85 return $aux_xml; 69 // Recebe array com dados de um certificado e gera o xml com estes dados. 70 // As chaves formam os tags e os dados o conteudo do tag .... 71 $aux_xml = "<certificado>"; 72 if(is_array($dados)) 73 { 74 foreach($dados as $K => $valor) 75 { 76 $aux_x = substr($K,0,1); 77 if(is_numeric($aux_x)) $K = 'oid-' . $K; 78 $K = trim($K); 79 if(!is_array($valor)) 80 { 81 $aux_xml .= '<' . $K . '>'.$valor.'</' . $K . '>'; 82 } 83 else 84 { 85 $aux_xml .= '<' . $K . '>'; 86 foreach($valor as $KX => $valorx) 87 { 88 //$KX = trim($KX); 89 if(is_int($KX)) $KX = 'D' . $KX; 90 $KX = trim($KX); 91 $aux_xml .= '<' . $KX . '>'.$valorx.'</' . $KX . '>'; 92 } 93 $aux_xml .= '</' . $K . '>'; 94 } 95 } 96 } 97 $aux_xml .= "</certificado>"; 98 return $aux_xml; 86 99 } 87 100 … … 1164 1177 $integer_data = substr($data, 2 + $bytes, $len); 1165 1178 $data = substr($data, 2 + $bytes + $len); 1179 $result[] = array('integer(' . $len . ')', print_hex($integer_data)); 1180 break; 1181 /* 1166 1182 if($len == 16) 1167 1183 { … … 1198 1214 break; 1199 1215 } 1200 1216 */ 1201 1217 case 0x03: 1202 1218 // Bitstring type … … 1354 1370 1355 1371 case 0xa0: 1372 case 0xa4: 1356 1373 // Extensions 1357 1374 $len = ord($data[1]); … … 1608 1625 { 1609 1626 $AUX = recupera_dados_oid($certificado_digital_formato_der,'2.5.29.31'); 1627 echo '<br/><br/><br/><pre>'; 1628 print_r($AUX); 1629 echo '</pre><br/><br/>'; 1630 exit(); 1631 1632 1610 1633 $i=1; 1611 1634 if(substr($AUX[0][1][0],0,7) == 'boolean') … … 1634 1657 foreach($AUX[0][$i][1][1] as $crl) 1635 1658 { 1636 if(substr($crl[1][0][1][0][1][0][1],0,4) == 'http' )1659 if(substr($crl[1][0][1][0][1][0][1],0,4) == 'http' || substr($crl[1][0][1][0][1][0][1],0,4) == 'ldap') 1637 1660 { 1638 1661 $ret[] = $crl[1][0][1][0][1][0][1]; … … 1640 1663 } 1641 1664 } 1642 } 1665 } 1666 1667 // Se $ret esta vazio tenta obter crls em outra estrutura(outro layout). 1668 if(count($ret) == 0) 1669 { 1670 if(is_array($AUX[0][1][1][1][0][1][0][1][0][1][0])) 1671 { 1672 //Pode existir mais de um local para obter a CRL. 1673 foreach($AUX[0][1][1][1][0][1][0][1][0][1][0]as $crl) 1674 { 1675 if(substr($crl[1],0,4) == 'http' || substr($crl[1],0,4) == 'ldap') 1676 { 1677 $ret[] = $crl[1]; 1678 } 1679 } 1680 } 1681 } 1682 1643 1683 return array('CRLDISTRIBUTIONPOINTS' => $ret); 1644 1684 } 1645 1685 1646 1686 1647 1687 function SERIALNUMBER($cert_data,$KK) 1648 1688 { … … 1671 1711 { 1672 1712 $dados = array(); 1673 $AUX0 = '/';1674 1713 $dados['EMISSOR_CAMINHO_COMPLETO'] = array(); 1675 1714 … … 1682 1721 } 1683 1722 1684 1723 1685 1724 function BEFOREAFTER($cert_data,$KK) 1686 1725 { -
branches/2.2/security/crl_admin/crl_admin.conf
r1174 r3232 1 # Lista das urls apontando CRLs , e onde colocar(path) os arquivos obtidos....1 # Lista das urls apontando CRLs .... 2 2 # Formato: 3 # url ;path ( o path deve terminar com uma /)4 http://ccd.serpro.gov.br/lcr/serproacfv1.crl ;/var/www/expresso/security/crls/5 http://ccd.serpro.gov.br/lcr/serproacfv2.crl ;/var/www/expresso/security/crls/6 http://ccd.serpro.gov.br/lcr/ACPRv1.crl ;/var/www/expresso/security/crls/7 http://ccd.serpro.gov.br/lcr/ACPRv2.crl ;/var/www/expresso/security/crls/8 http://ccd.serpro.gov.br/lcr/ ACSERPRORFB.crl;/var/www/expresso/security/crls/9 http://acraiz.icpbrasil.gov.br/LCRacraizv1.crl ;/var/www/expresso/security/crls/10 http://acraiz.icpbrasil.gov.br/LCRacraiz.crl ;/var/www/expresso/security/crls/11 http://ccd.serpro.gov.br/lcr/acserpro.crl ;/var/www/expresso/security/crls/12 http://ccd.serpro.gov.br/lcr/acserprojus.crl ;/var/www/expresso/security/crls/13 http://ccd.serpro.gov.br/lcr/acserprorfb.crl ;/var/www/expresso/security/crls/14 http://ccd.serpro.gov.br/lcr/acserprosrf.crl ;/var/www/expresso/security/crls/15 http://icp.caixa.gov.br/repositorio/ACCAIXA1.crl ;/var/www/expresso/security/crls/16 http://icp.caixa.gov.br/repositorio/ACCAIXAPF1.crl ;/var/www/expresso/security/crls/17 http://icp.caixa.gov.br/repositorio/ACCAIXAPJ1.crl ;/var/www/expresso/security/crls/18 http://icp.caixa.gov.br/repositorio/ACCAIXAJUS.crl ;/var/www/expresso/security/crls/19 http://ccdhom.serpro.gov.br/lcr/homacraizv2.crl ;/var/www/expresso/security/crls/20 http://ccdhom.serpro.gov.br/lcr/homserprov2.crl ;/var/www/expresso/security/crls/21 http://ccdhom.serpro.gov.br/lcr/acserprorfbv1.crl ;/var/www/expresso/security/crls/3 # url ( url apontando a crl - uma por linha) 4 http://ccd.serpro.gov.br/lcr/serproacfv1.crl 5 http://ccd.serpro.gov.br/lcr/serproacfv2.crl 6 http://ccd.serpro.gov.br/lcr/ACPRv1.crl 7 http://ccd.serpro.gov.br/lcr/ACPRv2.crl 8 http://ccd.serpro.gov.br/lcr/acserprorfb.crl 9 http://acraiz.icpbrasil.gov.br/LCRacraizv1.crl 10 http://acraiz.icpbrasil.gov.br/LCRacraiz.crl 11 http://ccd.serpro.gov.br/lcr/acserpro.crl 12 http://ccd.serpro.gov.br/lcr/acserprojus.crl 13 http://ccd.serpro.gov.br/lcr/acserprorfb.crl 14 http://ccd.serpro.gov.br/lcr/acserprosrf.crl 15 http://icp.caixa.gov.br/repositorio/ACCAIXA1.crl 16 http://icp.caixa.gov.br/repositorio/ACCAIXAPF1.crl 17 http://icp.caixa.gov.br/repositorio/ACCAIXAPJ1.crl 18 http://icp.caixa.gov.br/repositorio/ACCAIXAJUS.crl 19 http://ccdhom.serpro.gov.br/lcr/homacraizv2.crl 20 http://ccdhom.serpro.gov.br/lcr/homserprov2.crl 21 http://ccdhom.serpro.gov.br/lcr/acserprorfbv1.crl -
branches/2.2/security/crl_admin/crl_admin.py
r1174 r3232 2 2 # -*- coding: utf-8 -*- 3 3 4 import os, popen2, fcntl, select, time 4 import os, popen2, fcntl, select, time, sys 5 5 from string import replace 6 7 # Lista com as urls das CRLs, e onde colocar(path) os arquivos obtidos .... 8 CRL_urls = [] 9 Confs = {} 10 11 #Confs['dirtemp'] # path para a pasta temp para conter arquivos auxiliares.... 12 #Confs['CAfile'] # Arquivo com cadeia dos certificados das CAs, para verificacao das CRLs. 13 #Confs['CRLs'] # path para a pasta onde as CRLs sao salvas 14 #Confs['arquivos_crls'] # path para o arquivo de configuracao contendo urls das crls e paths onde serao baixadas... 15 #Confs['log'] # Arquivo onde sera grada log de execucao da qtualizacao/verificacao das crls. 16 # Deixe 'log' igual a vazio para ver as msgs de execucao no terminal....... 17 #Confs['lenMax'] # Tamanho maximo do arquivo de log de atualização das crls antes do rotate..... 18 #Confs['bkpNum'] # Numero de arquivos de log de atualização das crls mantidos pelo rotate.... 19 20 def ler_arquivo_com_configuracao(): 21 # Esta funcao le o arquivo com configuracao geral(linguagen php) para tratar certs. 22 import os,sys 23 BASE = os.path.realpath(__file__).split(os.sep + 'security')[0] # BASE igual a pasta inicial(raiz) do Expresso 24 os.chdir(BASE + '/security/classes') 25 # Esta funcao le o arquivo com configuracao geral(linguagen php) para tratar certs. 26 conf_file = BASE + '/security/classes/Verifica_Certificado_conf.php' 27 e = open(conf_file) 28 r = e.read() 29 aux1 = r.split('\n') 30 # primeiro recupera BASE ... 31 for linha in aux1: 32 linha = linha.strip() 33 if linha[0:16] == "$GLOBALS['BASE']": 34 Confs['BASE'] = BASE 35 break 36 # Agora os demais ... 37 for linha in aux1: 38 linha = linha.strip() 39 if linha[0:10] == "$GLOBALS['": 40 if linha[0:16] != "$GLOBALS['BASE']": 41 aux2 = linha.split(';') 42 if aux2[0] != '': 43 aux2a = aux2[0].split("'") 44 aux3 = aux2[0].split("=") 45 Confs[aux2a[1]] = aux3[1].replace(' ','') 46 # Finalmente trata as ocorrencias de BASE ... 47 for chave in Confs.keys(): 48 if chave != 'BASE': 49 aux = Confs[chave].replace("$GLOBALS['BASE'].",Confs['BASE']) 50 Confs[chave] = aux.replace("'",'') 51 return 52 53 def ler_conf(): 54 # Esta funcao le o arquivo passado como parametro e gera a lista CRL_urls. 55 # O arquivo he esperado no formato: 56 # url ( url = aponta onde buscar a crl, uma por linha. 57 e = open(Confs['arquivos_crls']) 58 r = e.read() 59 aux1 = r.split('\n') 60 for linha in aux1: 61 if linha[0:1] != '#': 62 if linha.strip() != '': 63 # Faz split com ';' para manter compatibilidade com arquivos formato antigo ... 64 CRL_urls.append([linha.split(';')[0].strip(),Confs['CRLs']]) 65 return 66 6 67 7 68 theOutput = [] 8 69 9 def fazlog( dados):10 11 12 13 logging.info(x)70 def fazlog(mL,dados): 71 for i in dados: 72 aux = i.split('\n') 73 for x in aux: 74 mL.info(x) 14 75 15 76 def makeNonBlocking(fd): 16 fl = fcntl.fcntl(fd, fcntl.F_GETFL)17 try:18 fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NDELAY) 19 except AttributeError:20 fcntl.fcntl(fd, fcntl.F_SETFL, fl | fcntl.FNDELAY) 77 fl = fcntl.fcntl(fd, fcntl.F_GETFL) 78 try: 79 fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NDELAY) 80 except AttributeError: 81 fcntl.fcntl(fd, fcntl.F_SETFL, fl | fcntl.FNDELAY) 21 82 22 83 def ExeCmd(command): … … 55 116 # a cadeia de certificados para verificar as crls(CAfile). 56 117 # Apos o import, executar a funcao ler_conf() ..... 57 from crl_admin_confg import * 118 #from crl_admin_confg import * 119 ler_arquivo_com_configuracao() 120 try: 121 ler_arquivo_com_configuracao() 122 except: 123 print 'Erro lendo arquivos de configuracao(ERR-01X)'; 124 sys.exit(1); 58 125 126 try: 127 # A execucao da funcao a seguir carrega a lista das CRLs (CRL_urls) que devem ser processadas... 128 ler_conf() 129 except: 130 print 'Erro lendo arquivos de configuracao(ERR-02X)'; 131 sys.exit(1); 132 133 CAfile = Confs['CAs'] 134 CRLs = Confs['CRLs'] 135 arquivo = Confs['arquivos_crls'] 136 log = Confs['log'] # Deixe log = '' para saida da log na console ..... 137 lenMax = int(Confs['lenMax']) # Tamanho maximo do arquivo de log para iniciar o rotate.... 138 bkpNum = int(Confs['bkpNum']) # Número de arquivos de log mantidos pelo rotate.... 59 139 import logging 140 import logging.handlers 60 141 61 # Configura como sera a log ..... 62 logging.basicConfig(level=logging.INFO, 63 format='%(asctime)s %(levelname)s %(message)s', 64 filename=log, 65 filemode='a') 142 # Prepara para fazer a log das atualizações das crls ... 143 fm = logging.Formatter('%(asctime)s %(levelname)s %(message)s') 144 mL = logging.getLogger('ML') 145 mL.setLevel(logging.DEBUG) 146 hd = logging.handlers.RotatingFileHandler(log, mode='a', maxBytes=lenMax, backupCount=bkpNum) 147 hd.setFormatter(fm) 148 mL.addHandler(hd) 66 149 67 # A execucao da funcao a seguir carrega a lista das CRLs (CRL_urls) que devem ser processadas... 68 ler_conf() 150 if len(sys.argv) > 1: 151 if os.path.isfile(sys.argv[1]): 152 Confs['arquivos_crls'] = sys.argv[1] 153 else: 154 mL.critical('Erro lendo arquivo de configuracao' + sys.argv[1] + ': Nao localizado.\n') 155 sys.exit(2) 156 157 mL.info('Processando arquivo de urls para obter crls: ' +Confs['arquivos_crls'] + ' .') 69 158 70 159 for crl in CRL_urls: 71 arquivo = crl[1] + os.path.split(crl[0])[1] 72 url = crl[0] 73 74 # Obtendo o arquivo com wget ... 75 logging.info('Buscando a CRL: ' + url) 76 saida_wget = ExeCmd("wget " + url + " -O " + arquivo) 77 78 # Abaixo estamos comandando a execucao "openssl crl" passando o arquivo crl . 79 # O resultado esta em saida. Tem de ser 'verify OK' . 80 if os.path.exists(arquivo) and os.path.getsize(arquivo) > 0: 81 logging.info('Verificando ' + arquivo + '(' + str(os.path.getsize(arquivo)) + ' Bytes)') 82 saida = ExeCmd('openssl crl -CAfile ' + CAfile + ' -in ' + arquivo + ' -inform DER -noout') 83 # usa a funcao fazlog porque saida he um array..... 84 fazlog(saida) 85 try: 86 aux1 = replace(saida[1],'\n','') 87 if not aux1 == 'verify OK': 88 logging.critical('Erro verificando a CRL ' + arquivo + '\n') 89 try: 90 os.remove(arquivo) 91 except: 92 pass 93 continue 94 # A crl foi verificada e est OK.... 95 # Atuaiza a data do arquivo... 96 saida = ExeCmd('touch ' + arquivo) 97 except: 98 logging.critical('Erro processando o status da verificacao da CRL ' + arquivo + '\n') 99 try: 100 os.remove(arquivo) 101 except: 102 pass 103 continue 104 else: 105 # usa a funcao fazlog porque saida_wget he um array..... 106 fazlog(saida_wget) 107 logging.critical('Nao foi possivel obter a CRL ' + url + '\n') 108 try: 109 os.remove(arquivo) 110 except: 111 pass 112 160 arquivo = crl[1].strip() + os.path.split(crl[0])[1].strip() 161 url = crl[0].strip() 162 # Obtendo o arquivo com wget ... 163 mL.info('Buscando a CRL: ' + url) 164 saida_wget = ExeCmd("wget --timeout=10 --tries=1 " + url + " -O " + arquivo) 165 # Abaixo estamos comandando a execucao "openssl crl" passando o arquivo crl . 166 # O resultado esta em saida. Tem de ser 'verify OK' . 167 if os.path.exists(arquivo) and os.path.getsize(arquivo) > 0: 168 mL.info('Verificando ' + arquivo + '(' + str(os.path.getsize(arquivo)) + ' Bytes)') 169 saida = ExeCmd('openssl crl -CAfile ' + CAfile + ' -in ' + arquivo + ' -inform DER -noout') 170 # usa a funcao fazlog porque saida he um array..... 171 fazlog(mL,saida) 172 try: 173 aux1 = replace(saida[1],'\n','') 174 if not aux1 == 'verify OK': 175 mL.critical('Erro verificando a CRL ' + arquivo + '\n') 176 try: 177 os.remove(arquivo) 178 except: 179 pass 180 continue 181 # A crl foi verificada e est OK.... 182 # Atuaiza a data do arquivo... 183 saida = ExeCmd('touch ' + arquivo) 184 except: 185 mL.critical('Erro processando o status da verificacao da CRL ' + arquivo + '\n') 186 try: 187 os.remove(arquivo) 188 except: 189 pass 190 continue 191 else: 192 # usa a funcao fazlog porque saida_wget he um array..... 193 fazlog(mL,saida_wget) 194 mL.critical('Nao foi possivel obter a CRL ' + url + '\n') 195 try: 196 os.remove(arquivo) 197 except: 198 pass -
branches/2.2/security/crl_admin/crl_admin_confg.py
r1174 r3232 3 3 # Lista com as urls das CRLs, e onde colocar(path) os arquivos obtidos .... 4 4 CRL_urls = [] 5 Confs = {} 5 6 6 # arquivo : path para o arquivo de configuracao contendo urls das crls e paths onde serao baixadas... 7 arquivo = '/var/www/expresso/security/crl_admin/crl_admin.conf' 8 9 # Arquivo onde sera grada log de execucao da qtualizacao/verificacao das crls. 10 log = '/var/www/expresso/logs/arquivo_crls.log' 11 12 # Deixe 'log' igual a vazio para ver as msgs de execução no terminal....... 13 #log = '' 14 15 # Arquivo com cadeia dos certificados das CAs, para verificacao das CRLs. 16 CAfile = '/var/www/expresso/security/cas/todos.cer' 7 #Confs['dirtemp'] # path para a pasta temp para conter arquivos auxiliares.... 8 #Confs['CAfile'] # Arquivo com cadeia dos certificados das CAs, para verificacao das CRLs. 9 #Confs['CRLs'] # path para a pasta onde as CRLs sao salvas 10 #Confs['arquivos_crls'] # path para o arquivo de configuracao contendo urls das crls e paths onde serao baixadas... 11 #Confs['log'] # Arquivo onde sera grada log de execucao da qtualizacao/verificacao das crls. 12 # Deixe 'log' igual a vazio para ver as msgs de execucao no terminal....... 13 def ler_arquivo_com_configuracao(): 14 # Esta funcao le o arquivo com configuracao geral(linguagen php) para tratar certs. 15 import os,sys 16 BASE = os.path.realpath(__file__).split(os.sep + 'security')[0] # BASE igual a pasta inicial(raiz) do Expresso 17 os.chdir(BASE + '/security/classes') 18 # Esta funcao le o arquivo com configuracao geral(linguagen php) para tratar certs. 19 conf_file = BASE + '/security/classes/Verifica_Certificado_conf.php' 20 e = open(conf_file) 21 r = e.read() 22 aux1 = r.split('\n') 23 # primeiro recupera BASE ... 24 for linha in aux1: 25 linha = linha.strip() 26 if linha[0:16] == "$GLOBALS['BASE']": 27 Confs['BASE'] = BASE 28 break 29 # Agora os demais ... 30 for linha in aux1: 31 linha = linha.strip() 32 if linha[0:10] == "$GLOBALS['": 33 if linha[0:16] != "$GLOBALS['BASE']": 34 aux2 = linha.split(';') 35 if aux2[0] != '': 36 aux2a = aux2[0].split("'") 37 aux3 = aux2[0].split("=") 38 Confs[aux2a[1]] = aux3[1].replace(' ','') 39 # Finalmente trata as ocorrencias de BASE ... 40 for chave in Confs.keys(): 41 if chave != 'BASE': 42 aux = Confs[chave].replace("$GLOBALS['BASE'].",Confs['BASE']) 43 Confs[chave] = aux.replace("'",'') 44 return 17 45 18 46 def ler_conf(): 19 # Esta funcao le o arquivo passado como parametro e gera a lista CRL_urls. 20 # O arquivo he esperado no formato: 21 # url;path ( url = aponta onde buscar a crl, e path aponta onde salvar a crl obtida. 22 e = open(arquivo) 23 r = e.read() 24 aux1 = r.split('\n') 25 for linha in aux1: 26 if linha[0:1] != '#': 27 aux2 = linha.split(';') 28 if aux2[0] != '': 29 CRL_urls.append(aux2) 30 return 47 # Esta funcao le o arquivo passado como parametro e gera a lista CRL_urls. 48 # O arquivo he esperado no formato: 49 # url ( url = aponta onde buscar a crl, uma por linha. 50 ler_arquivo_com_configuracao() 51 e = open(Confs['arquivos_crls']) 52 r = e.read() 53 aux1 = r.split('\n') 54 for linha in aux1: 55 if linha[0:1] != '#': 56 if linha != '': 57 # Faz split com ';' para manter compatibilidade com arquivos formato antigo ... 58 CRL_urls.append([linha.split(';')[0],Confs['CRLs']]) 59 return -
branches/2.2/security/security.php
r1174 r3232 1 1 <?php 2 require_once('classes/CertificadoB.php');3 4 $Linhas = explode(chr(0x0A),file_get_contents($_SERVER["DOCUMENT_ROOT"] . '/security/crl_admin/crl_admin_confg.py'));5 6 foreach($Linhas as $linha)7 {8 $path = pega_path(array( 'arquivo =', 'arquivo='),$linha);9 if($path) $path1 = $path;10 $path = pega_path(array( 'log =', 'log='),$linha);11 if($path) $path2 = $path;12 $path = pega_path(array( 'CAfile =', 'CAfile='),$linha);13 if($path) $path3 = $path;14 }15 16 if($path3)17 {18 $item = 1;19 $todos_certificados = ler_certificados_CAS($path3);20 $aux_emissores= array();21 $tab_certs = array();22 $CB = new CertificadoB();23 foreach($todos_certificados as $certificados)24 {25 $CB -> certificado($certificados);26 $df = $CB->dados['FIM_VALIDADE'];27 $di = $CB->dados['INICIO_VALIDADE'];28 if(gmdate("YmdHis") > $df)29 {30 $cor = '<label style="color: #FF0000" >Expirado em: </label>';31 }32 else33 {34 $cor = '<label>Valido até </label>';35 }36 $info = $cor . substr($df,0,4) . '/' . substr($df,4,2) . '/' . substr($df,6,2) . ' - ' . substr($df,8,2) . ':' . substr($df,10,2) . ':' . substr($df,12,2) . ' GMT';37 $info = '<font size="1"' . $info . '</font>';38 // Armazena alguns dados do certificado. $tabs_certs esta na mesma ordem em que os certificados aparecem no arquivo todos.cer.....39 $tab_certs[$CB->dados['SUBJECT']['CN']]['item'] = $item++;40 $tab_certs[$CB->dados['SUBJECT']['CN']]['emissor'] = $CB->dados['EMISSOR_CAMINHO_COMPLETO']['CN'];41 $tab_certs[$CB->dados['SUBJECT']['CN']]['fim_validade'] = $info;42 $tab_certs[$CB->dados['SUBJECT']['CN']]['inicio_validade'] = $di;43 if($CB->dados['EMISSOR_CAMINHO_COMPLETO']['CN'] != $CB->dados['SUBJECT']['CN'])44 {45 // Se nao he um auto assinado (identifica um raiz), salva emissor , faz a chave a tdata de inicio de validade do certificado...46 $aux_emissores[$di][$CB->dados['EMISSOR_CAMINHO_COMPLETO']['CN']][$CB->dados['SUBJECT']['CN']] = '9' ;47 }48 }49 // ordena certificados pela data de inicio de validade ......50 ksort($aux_emissores);51 $NOVO = array();52 $AUX3 = array();53 $emissores = array();54 55 foreach($aux_emissores as $kchave1 => $emis1)56 {57 foreach($emis1 as $Kchave2 => $emis2)58 {59 foreach($emis2 as $Kchave3 => $emis3)60 {61 $emissores[$Kchave2][$Kchave3] = '9';62 }63 }64 }65 66 // O array $NOVO vai conter a cadeia dos certificados de CAs ....67 foreach($emissores as $K => $V)68 {69 if($AUX3[$K] != '0')70 {71 foreach($V as $K1 => $V1)72 {73 if($emissores[$K1])74 {75 $NOVO[$K][$K1] = $emissores[$K1];76 $AUX3[$K1] = '0';77 }78 else79 {80 $NOVO[$K][$K1] = '0';81 }82 }83 }84 }85 86 // Valores auxiliares para fazer a identacao .....87 $prefixo0 = ' ' . '|';88 $prefixo1 = ' ' . '|' . '____' ;89 $prefixo2 = ' ' . '|' . ' ' . ' ' . ' ' . ' ' . '|' ;90 $prefixo2A = ' ' . ' ' . ' ' . ' ' . ' ' . ' ' . '|' ;91 $prefixo3 = ' ' . '|' . ' ' . ' ' . ' ' . ' ' . '|' . '____' ;92 $prefixo3A = ' ' . ' ' . ' ' . ' ' . ' ' . ' ' . '|' . '____' ;93 94 echo '<script type="text/javascript" src="certificados.js"></script>';95 echo '<h2 style="color: #000066">Cadeias de certificados AC\'s configuradas:</h2>';96 echo '<div style="border: #000000 1px solid; overflow: auto; width: 770px; height: 400px; white-space: pre; padding: 3px; " >';97 echo '<pre>';98 foreach($NOVO as $K => $V)99 {100 if($tab_certs[$K]['fim_validade'])101 {102 $msg = $tab_certs[$K]['fim_validade'];103 }104 else105 {106 $msg = '<font color="FF0000" size="4"><b>Certificado ausente da cadeia.</b></font> ';107 }108 echo '<br/><font color="0000FF" size="4"><b><a href="javascript:Um_Certificado(\''. $tab_certs[$K]['item'] . ' - ' . $K .'\')" style="text-decoration: none" >' . $K . '</a></b></font> ' . $msg . '<br/>';109 if(is_array($V))110 {111 $num = count($V);112 $item = 0;113 foreach($V as $K1 => $V1)114 {115 $item = $item + 1;116 echo $prefixo0 . '<br/>';117 if($tab_certs[$K1]['fim_validade'])118 {119 $msg = $tab_certs[$K1]['fim_validade'];120 }121 else122 {123 $msg = '<font color="FF0000" ><b>Certificado ausente da cadeia.</b></font> ';124 }125 echo $prefixo1 . '<font color="#000000" ><a href="javascript:Um_Certificado(\''. $tab_certs[$K1]['item'] . ' - ' . $K1 .'\')" style="text-decoration: none" >' . $K1 . '</a></font> ' . ' ' . $msg . '<br/>';126 if(is_array($V1))127 {128 foreach($V1 as $K2 => $V2)129 {130 if($tab_certs[$K1]['fim_validade'])131 {132 $msg = $tab_certs[$K1]['fim_validade'];133 }134 else135 {136 $msg = '<font color="FF0000" ><b>Certificado ausente da cadeia.</b></font> ';137 }138 if($num>$item)139 {140 echo $prefixo2 . '<br/>';141 echo$prefixo3 . '<font color="#000000" ><a href="javascript:Um_Certificado(\''. $tab_certs[$K2]['item'] . ' - ' . $K2 .'\')" style="text-decoration: none" >' . $K2 . '</a></font> ' . ' ' . $msg . '<br/>';142 }143 else144 {145 echo $prefixo2A . '<br/>';146 echo $prefixo3A . '<font color="#000000" ><a href="javascript:Um_Certificado(\''. $tab_certs[$K2]['item'] . ' - ' . $K2 .'\')" style="text-decoration: none" >' . $K2 . '</a></font> ' . ' ' . $msg . '<br/>';147 }148 }149 }150 }151 }152 }153 echo '</pre>';154 echo '</div><br/>';155 }156 if($path1)157 {158 $Linhas = explode(chr(0x0A),file_get_contents($path1));159 echo '<h2 style="color: #000066">LCR\'s configuradas:</h2>';160 echo '<table border ="1" style="margin-top: 8px; width: 770px">';161 echo '<th nowrap align="left" style=" padding: 5px">Lista de Certificados revogados obtida em:</th><th nowrap align="left" style=" padding: 5px">Onde é salva a LCR:</th>';162 foreach($Linhas as $linha)163 {164 if($linha[0] != '#' && $linha != '')165 {166 $c = explode(';', $linha);167 $n = explode('/',$c[0]);168 $f = $c[1] . $n[count($n)-1];169 echo '<tr><td nowrap valign="top" style=" padding: 5px">' . $c[0] . '</td><td nowrap style=" padding: 5px">';170 echo $f;171 if(!is_file($f))172 {173 echo '<p style="margin-bottom: 5px"><b style="color: #FF0000">Arquivo não localizado.</b></p>';174 }175 else176 {177 $data = file_get_contents($f);178 $dados = Crl_parseASN($data);179 echo '<br/><br/>Emitido por: ';180 $aux = $dados[1][0][1][2][1]; // pega dados do emissor.181 $aux = $aux[count($aux)-1]; // ultimo item he o do CN.....182 echo $aux[1][1][1][1];183 echo '<br/>Num. certificados: ';184 $num = 0;185 if(count($dados[1][0][1]) > 6) // qtd de itens esperado he 7. o 6 contem os certificados revogados.186 {187 $num = count($dados[1][0][1][5][1]); // pega o numero de certificados revogados na LCR.188 }189 echo $num;190 echo '<br/>LCR num. : ';191 $oid_Num_crl = recupera_dados_oid($data,'2.5.29.20'); // oid que informa o numero de geracao da LCR.192 $num = $oid_Num_crl[0][1][1][1];193 if($num)194 {195 echo $num;196 }197 else198 {199 echo '0';200 }201 echo '<br>';202 $di = data_hora($dados[1][0][1][3][1]); // data, hora em que foi gerada a LCR.203 $df = data_hora($dados[1][0][1][4][1]); // data, hora em que expira a LCR.204 if(gmdate("YmdHis") < $di)205 {206 $cor = 'style="color: #FF0000"';207 }208 else209 {210 $cor = 'style="color: #000066"';211 }212 echo '<p><b ' . $cor . '>Gerada em : </b>' . substr($di,0,4) . '/' . substr($di,4,2) . '/' . substr($di,6,2) . ' - ' . substr($di,8,2) . ':' . substr($di,10,2) . ':' . substr($di,12,2) . ' GMT</p>';213 if(gmdate("YmdHis") > $df)214 {215 $cor = 'style="color: #FF0000" >Expirada em: ';216 }217 else218 {219 $cor = 'style="color: #000066" >Expira em: ';220 }221 echo '<p><b ' . $cor . ' </b>' . substr($df,0,4) . '/' . substr($df,4,2) . '/' . substr($df,6,2) . ' - ' . substr($df,8,2) . ':' . substr($df,10,2) . ':' . substr($df,12,2) . ' GMT</p>';222 }223 echo '</td></tr>';224 }225 }226 echo '</table><br><br><br>';227 }228 229 230 231 232 if($path2)233 {234 echo '<br><h2 style="color: #000066">Log da atualização das LCR\'s:</h2>';235 echo '<div style="border: #000000 1px solid; overflow: auto; width: 770px; height:290px; white-space: pre; padding: 5px" >';236 echo '<pre>';237 if(is_file($path2))238 {239 $saida = array();240 $ret = exec('cat ' . $path2 . ' | grep ' . date('Y-m-d') ,$saida);241 foreach($saida as $linha)242 {243 echo $linha . chr(0x0A);244 }245 }246 else247 {248 echo '<p style="margin-bottom: 5px"><b style="color: #FF0000">Arquivo ' . $path2 . ' não localizado.</b></p>';249 }250 echo '</pre>';251 echo '</div><br><br>';252 }253 2 ?> 3 <div style="padding-left:90px" > 4 <br/><br/> 5 <span> 6 <a href="security-cas.php" style="text-decoration:none"><b><?php echo lang('ACs (Autoridades Certificadoras)') ?></b></a> 7 </span> 8 <br/><br/> 9 <span> 10 <a href="security-clr.php" style="text-decoration:none"><b><?php echo lang('LCRs(Listas de Certificados Revogados)') ?></b></a> 11 </span> 12 <br/><br/> 13 <span> 14 <a href="security-cfg.php" style="text-decoration:none"><b><?php echo lang('Visualizar Configuracao em uso') ?></b></a> 15 </span> 16 <br/><br/><br/><br/> 17 <a href="../admin/index.php" style="text-decoration:none"><input type="button" value="<?php echo lang('Cancelar') ?>"/></a> 18 <br/><br/> 19 </div> -
branches/2.2/security/security_admin.php
r1174 r3232 12 12 else 13 13 { 14 echo '<div><h4> Dados para administração das CA\'s e CRL\'s não foram localizados.</h4></div>';14 echo '<div><h4>' . lang('Dados para administração das CA\'s e CRL\'s não foram localizados') . '.</h4></div>'; 15 15 } 16 16 ?> -
branches/2.2/security/vercert.php
r1636 r3232 19 19 [INICIO_VALIDADE] => 20090318205216 20 20 [FIM_VALIDADE] => 20120317205216 21 [EXPIRADO] => 21 [EXPIRADO] => 22 22 [SUBJECT] => Array 23 23 ( … … 43 43 ) 44 44 45 [CA] => 45 [CA] => 46 46 [CRLDISTRIBUTIONPOINTS] => Array 47 47 ( … … 62 62 [ZONA] => 000 63 63 [SECAO] => 0000 64 [TITULO_CIDADE_UF] => 64 [TITULO_CIDADE_UF] => 65 65 ) 66 66 … … 68 68 [ZONA] => 000 69 69 [SECAO] => 0000 70 [TITULO_CIDADE_UF] => 70 [TITULO_CIDADE_UF] => 71 71 [2.16.76.1.3.1] => Array 72 72 ( … … 85 85 [EMAIL] => cesar.vianna@pr.planalto.gov.br 86 86 ) 87 */ 88 87 */ 88 89 89 // Retorna o CPF para usar como uid. 90 90 return $dados_do_certificado['2.16.76.1.3.1']['CPF']; 91 91 } 92 93 92 93 94 94 $GLOBALS['phpgw_info']['flags'] = array( 95 95 'disable_Template_class' => True, … … 112 112 { 113 113 echo '1'.chr(0x0D).chr(0x0A).'Arquivo header.inc.php não foi localizado.'; 114 exit(); 114 exit(); 115 115 } 116 117 $ldap_context = $GLOBALS['phpgw_info']['server']['ldap_context'];118 $ldap_servidor = $GLOBALS['phpgw_info']['server']['ldap_host'];119 $ldap_dn = $GLOBALS['phpgw_info']['server']['ldap_root_dn'];120 $ldap_passwd = $GLOBALS['phpgw_info']['server']['ldap_root_pw'];121 116 122 117 require_once('classes/CertificadoB.php'); … … 125 120 126 121 # Transforma o certificado do formato PEM para o formato DER ... 127 function troca_espaco_por_mais($pem_data) 122 function troca_espaco_por_mais($pem_data) 128 123 { 129 124 $begin = "CERTIFICATE-----"; 130 125 $end = "-----END"; 131 $aux = substr($pem_data, strpos($pem_data, $begin)+strlen($begin)); 126 $aux = substr($pem_data, strpos($pem_data, $begin)+strlen($begin)); 132 127 $aux = substr($aux, 0, strpos($aux, $end)); 133 128 $aux = strtr($aux,' ','+'); … … 135 130 return $aux; 136 131 } 137 138 132 139 133 $cert =str_replace(chr(0x0A).chr(0x0A),chr(0x0A),$_REQUEST['certificado']); … … 168 162 169 163 echo $msg; 170 exit(); 171 } 172 173 $cc=ldap_connect($ldap_servidor); 174 ldap_set_option($cc, LDAP_OPT_PROTOCOL_VERSION, 3); 175 // bind .. 176 $sr=ldap_bind($cc,$ldap_dn,$ldap_passwd); 177 164 exit(); 165 } 166 167 if ( (!empty($GLOBALS['phpgw_info']['server']['ldap_master_host'])) && 168 (!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_dn'])) && 169 (!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_pw'])) ) 170 { 171 $ds = $GLOBALS['phpgw']->common->ldapConnect($GLOBALS['phpgw_info']['server']['ldap_master_host'], 172 $GLOBALS['phpgw_info']['server']['ldap_master_root_dn'], 173 $GLOBALS['phpgw_info']['server']['ldap_master_root_pw']); 174 } 175 else 176 { 177 $ds = $GLOBALS['phpgw']->common->ldapConnect(); 178 } 179 180 if (!$ds) 181 { 182 echo '8'.chr(0x0D).chr(0x0A).'Não foi possível obter dados do usuario para login.'; 183 exit(); 184 } 185 178 186 $filtro = 'uid='. item_para_uid($c->dados); 179 180 187 $atributos = array(); 181 188 //$atributos[] = 'phpgwaccountexpires'; … … 191 198 $atributos[] = "cryptpassword"; 192 199 $atributos[] = "uid"; 193 194 // Pesquisa uid no RHDS/LDAP 195 $sr=ldap_search($cc, $ldap_context,$filtro,$atributos); 200 201 $sr=ldap_search($ds, $GLOBALS['phpgw_info']['server']['ldap_context'],$filtro,$atributos); 196 202 197 203 // Pega resultado .... 198 $info = ldap_get_entries($ cc, $sr);199 204 $info = ldap_get_entries($ds, $sr); 205 200 206 // Tem de achar só uma entrada.....ao menos uma.... 201 207 if($info["count"]!=1) 202 208 { 203 echo '4'.chr(0x0D).chr(0x0A).'Dados inválidos no diretório de usuários'; 204 ldap_close($ cc);209 echo '4'.chr(0x0D).chr(0x0A).'Dados inválidos no diretório de usuários'; 210 ldap_close($ds); 205 211 exit(); 206 212 } … … 210 216 { 211 217 echo '5'.chr(0x0D).chr(0x0A).'Conta do usuario nao esta ativa no Expresso.'; 212 ldap_close($ cc);218 ldap_close($ds); 213 219 exit(); 214 220 } … … 217 223 { 218 224 echo '0'.chr(0x0D).chr(0x0A).$info[0]["uid"][0].chr(0x0D).chr(0x0A).$info[0]["cryptpassword"][0]; 219 //echo '0' . "\n" . $info[0]["uid"][0] . "\n" . $info[0]["cryptpassword"][0];220 225 } 221 226 else … … 241 246 $user_info['phpgwlastpasswdchange'] = '0'; 242 247 } 243 244 if(!ldap_modify($ cc,$aux1,$user_info))248 249 if(!ldap_modify($ds,$aux1,$user_info)) 245 250 { 246 echo ' 6'.chr(0x0D).chr(0x0A).'Ocorreu um erro no acolhimento do certificado.',$aux1;251 echo '7'.chr(0x0D).chr(0x0A).'Ocorreu um erro no acolhimento do certificado.',$aux1; 247 252 } 248 253 else … … 256 261 } 257 262 } 258 ldap_close($ cc);263 ldap_close($ds); 259 264 ?>
Note: See TracChangeset
for help on using the changeset viewer.