KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > proactive > ext > security > ProActiveSecurityManager


1 /*
2 * ################################################################
3 *
4 * ProActive: The Java(TM) library for Parallel, Distributed,
5 * Concurrent computing with Security and Mobility
6 *
7 * Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis
8 * Contact: proactive-support@inria.fr
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
23 * USA
24 *
25 * Initial developer(s): The ProActive Team
26 * http://www.inria.fr/oasis/ProActive/contacts.html
27 * Contributor(s):
28 *
29 * ################################################################
30 */

31 package org.objectweb.proactive.ext.security;
32
33 import java.io.ByteArrayInputStream JavaDoc;
34 import java.io.ByteArrayOutputStream JavaDoc;
35 import java.io.File JavaDoc;
36 import java.io.FileInputStream JavaDoc;
37 import java.io.IOException JavaDoc;
38 import java.io.InputStream JavaDoc;
39 import java.io.Serializable JavaDoc;
40 import java.security.Key JavaDoc;
41 import java.security.KeyFactory JavaDoc;
42 import java.security.PrivateKey JavaDoc;
43 import java.security.Provider JavaDoc;
44 import java.security.PublicKey JavaDoc;
45 import java.security.SecureRandom JavaDoc;
46 import java.security.Security JavaDoc;
47 import java.security.Signature JavaDoc;
48 import java.security.SignedObject JavaDoc;
49 import java.security.cert.CertificateEncodingException JavaDoc;
50 import java.security.cert.CertificateExpiredException JavaDoc;
51 import java.security.cert.CertificateFactory JavaDoc;
52 import java.security.cert.CertificateNotYetValidException JavaDoc;
53 import java.security.cert.X509Certificate JavaDoc;
54 import java.security.interfaces.RSAPrivateKey JavaDoc;
55 import java.security.spec.PKCS8EncodedKeySpec JavaDoc;
56 import java.security.spec.X509EncodedKeySpec JavaDoc;
57 import java.util.ArrayList JavaDoc;
58 import java.util.Enumeration JavaDoc;
59 import java.util.Hashtable JavaDoc;
60 import java.util.Random JavaDoc;
61
62 import javax.crypto.Cipher;
63 import javax.crypto.KeyGenerator;
64 import javax.crypto.SecretKey;
65 import javax.crypto.spec.IvParameterSpec;
66 import javax.crypto.spec.SecretKeySpec;
67
68 import org.apache.log4j.Logger;
69 import org.objectweb.proactive.core.ProActiveException;
70 import org.objectweb.proactive.core.body.BodyImpl;
71 import org.objectweb.proactive.core.body.UniversalBody;
72 import org.objectweb.proactive.core.node.Node;
73 import org.objectweb.proactive.core.node.NodeException;
74 import org.objectweb.proactive.core.node.NodeFactory;
75 import org.objectweb.proactive.core.runtime.ProActiveRuntimeImpl;
76 import org.objectweb.proactive.core.runtime.RuntimeFactory;
77 import org.objectweb.proactive.core.xml.XMLPropertiesStore;
78 import org.objectweb.proactive.examples.garden.Flower;
79 import org.objectweb.proactive.ext.security.crypto.AuthenticationException;
80 import org.objectweb.proactive.ext.security.crypto.AuthenticationTicket;
81 import org.objectweb.proactive.ext.security.crypto.AuthenticationTicketProperty;
82 import org.objectweb.proactive.ext.security.crypto.ConfidentialityTicket;
83 import org.objectweb.proactive.ext.security.crypto.KeyExchangeException;
84 import org.objectweb.proactive.ext.security.crypto.RandomLongGenerator;
85 import org.objectweb.proactive.ext.security.crypto.Session;
86 import org.xml.sax.SAXException JavaDoc;
87
88 import sun.rmi.server.MarshalOutputStream;
89
90
91 /**
92  * @author acontes
93  *
94  * To change this generated comment edit the template variable "typecomment":
95  * Window>Preferences>Java>Templates.
96  * To enable and disable the creation of type comments go to
97  * Window>Preferences>Java>Code Generation.
98  */

99 public class ProActiveSecurityManager implements Serializable JavaDoc {
100     protected static Logger logger = Logger.getLogger(ProActiveSecurityManager.class.getName());
101
102     /* contains all active sessions for the current active object */
103     protected Hashtable JavaDoc sessions;
104
105     /* random generator used for generating sesssion key */
106     protected transient RandomLongGenerator randomLongGenerator;
107
108     /* Policy server */
109     protected PolicyServer policyServer;
110
111     /* Active object certificate */
112     protected X509Certificate JavaDoc certificate;
113
114     /* Active Object private Key */
115     protected PrivateKey JavaDoc privateKey;
116
117     /* owner certificate */
118     protected transient X509Certificate JavaDoc parentCertificate;
119     protected PublicKey JavaDoc publicKey;
120     protected byte[] privateKeyEncoded;
121     protected X509Certificate JavaDoc[] trustedCertificationAuthority;
122     protected XMLPropertiesStore policiesRules;
123     protected transient UniversalBody myBody;
124     protected String JavaDoc VNName;
125
126     // protected UniversalBody body;
127

128     /**
129      * This a the default constructor to use with the ProActiveSecurityManager
130      */

131     public ProActiveSecurityManager() {
132         sessions = new Hashtable JavaDoc();
133     }
134
135     /**
136      * Method ProActiveSecurityManager.
137      * @param file the file containing the policy
138      * @throws IOException if the file doesn't exist
139      */

140     public ProActiveSecurityManager(X509Certificate JavaDoc certificate, PrivateKey JavaDoc pk,
141         PolicyServer ps) {
142         Provider JavaDoc myProvider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
143         Security.addProvider(myProvider);
144         this.policyServer = ps;
145         this.certificate = certificate;
146         this.privateKey = pk;
147         publicKey = certificate.getPublicKey();
148         sessions = new Hashtable JavaDoc();
149         logger.debug(
150             "psm +-+--+-+-++-+-+-++-++-+--+-+-+-+-+-+-+-+-+-+-+-++--+-+-+-+-+-+-+-+ ");
151     }
152
153     public ProActiveSecurityManager(String JavaDoc file) throws java.io.IOException JavaDoc {
154         Provider JavaDoc myProvider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
155         Security.addProvider(myProvider);
156         sessions = new Hashtable JavaDoc();
157
158         if ((new File JavaDoc(file)).exists()) {
159             this.policiesRules = new XMLPropertiesStore(file);
160             try {
161                 this.policyServer = ProActiveSecurityDescriptorHandler.createPolicyServer(file);
162             } catch (IOException JavaDoc e) {
163                 e.printStackTrace();
164             } catch (SAXException JavaDoc e) {
165                 e.printStackTrace();
166             }
167             setCertificate();
168             setPrivateKey();
169             setTrustedCertificationAuthority();
170             publicKey = certificate.getPublicKey();
171         }
172         logger.debug("psm" + file +
173             " +-+--+-+-++-+-+-++-++-+--+-+-+-+-+-+-+-+-+-+-+-++--+-+-+-+-+-+-+-+ ");
174     }
175
176     public void setBody(UniversalBody body) {
177         myBody = body;
178     }
179
180     /**
181      * Method setCertificate.
182      * set the certificate of the active object
183      */

184     private void setCertificate() {
185         String JavaDoc certificateFile = policiesRules.getValueAsString(SecurityConstants.XML_CERTIFICATE)
186                                               .trim();
187         X509Certificate JavaDoc certificate = null;
188
189         try {
190             InputStream JavaDoc inStream = new FileInputStream JavaDoc(certificateFile);
191             CertificateFactory JavaDoc cfe = CertificateFactory.getInstance("X.509");
192             certificate = (X509Certificate JavaDoc) cfe.generateCertificate(inStream);
193             inStream.close();
194         } catch (IOException JavaDoc e) {
195             logger.warn(" Certificate file " + certificateFile + " not found");
196             e.printStackTrace();
197         } catch (java.security.cert.CertificateException JavaDoc e) {
198             logger.warn(
199                 "An error occurs while loading active object certificate");
200             e.printStackTrace();
201         }
202
203         this.certificate = certificate;
204     }
205
206     /**
207             * Method getPolicyTo.
208             * @param certificate the object certificate we want to get the policy from
209             * @return Policy policy attributes
210             */

211     public SecurityContext getPolicy(SecurityContext securityContext)
212         throws SecurityNotAvailableException {
213         if (policyServer == null) {
214             // if Active Obect policy server is null, maybe a runtime poilicy server exists
215
try {
216                 policyServer = RuntimeFactory.getDefaultRuntime()
217                                              .getPolicyServer();
218                 if (policyServer == null) {
219                     throw new SecurityNotAvailableException(
220                         "No Runtime nor Active Object Policy server found");
221                 }
222             } catch (ProActiveException e) {
223                 throw new SecurityNotAvailableException(
224                     "No Runtime nor Active Object Policy server found");
225             }
226         }
227         return policyServer.getPolicy(securityContext);
228     }
229
230     /**
231      * Method getPolicyTo.
232      * @param certificate the object certificate we want to get the policy from
233      * @return Policy policy attributes
234      */

235     public Policy getPolicyTo(X509Certificate JavaDoc certificate) {
236         return policyServer.getPolicyTo(certificate);
237     }
238
239     /**
240      * Method getPolicyTo.
241      * @param certificate the object certificate we want to get the policy from
242      * @return Policy policy attributes
243      */

244     public Communication getPolicyTo(String JavaDoc type, String JavaDoc from, String JavaDoc to)
245         throws SecurityNotAvailableException {
246         if (policyServer == null) {
247             throw new SecurityNotAvailableException();
248         }
249         return policyServer.getPolicyTo(type, from, to);
250     }
251
252     /**
253      * Method setTrustedCertificationAuthority.
254      * Loads external trusted certification authority if exist
255      * Done once when the ProActiveSecurityManager is created
256      */

257     private void setTrustedCertificationAuthority() {
258         X509Certificate JavaDoc[] trustedCertificationAuthority = null;
259         X509Certificate JavaDoc certificate;
260         String JavaDoc file = "";
261
262         try {
263             org.w3c.dom.Node JavaDoc[] nodes = policiesRules.getAllNodes(SecurityConstants.XML_TRUSTED_CERTIFICATION_AUTHORITY);
264
265             if (nodes == null) {
266         // logger.info(" No Trusted Certification Authority");
267

268                 return;
269             }
270
271             int i = 0;
272
273             // initialize the array of trusted CA
274
trustedCertificationAuthority = new X509Certificate JavaDoc[nodes.length];
275
276             // prepare to read CA certificate
277
InputStream JavaDoc inStream = null;
278
279             // read all certificate from disk and save it in memory
280
for (; i < nodes.length; i++) {
281                 // get the file path
282
file = policiesRules.getValueAsString(SecurityConstants.XML_CERTIFICATION_AUTHORITY_CERTIFICATE,
283                         nodes[i]);
284                 file = file.trim();
285
286                 //initialize the reader
287
inStream = new FileInputStream JavaDoc(file);
288
289                 CertificateFactory JavaDoc cfe = CertificateFactory.getInstance("X.509");
290                 certificate = (X509Certificate JavaDoc) cfe.generateCertificate(inStream);
291
292                 // Add the certificate
293
trustedCertificationAuthority[i] = certificate;
294             }
295
296             // close the stream
297
if (inStream != null) {
298                 inStream.close();
299             }
300         } catch (java.security.cert.CertificateException JavaDoc e) {
301             System.out.println(
302                 "An error occurs while loading authority certification certificate");
303             e.printStackTrace();
304         } catch (IOException JavaDoc e) {
305             e.printStackTrace();
306         }
307
308         this.trustedCertificationAuthority = trustedCertificationAuthority;
309     }
310
311     private void decodePrivateKey() {
312         RSAPrivateKey JavaDoc privateKey = null;
313
314         try {
315             KeyFactory JavaDoc key_factory = KeyFactory.getInstance("RSA", "BC");
316             PKCS8EncodedKeySpec JavaDoc key_spec = new PKCS8EncodedKeySpec JavaDoc(privateKeyEncoded);
317             privateKey = (RSAPrivateKey JavaDoc) key_factory.generatePrivate(key_spec);
318         } catch (java.security.spec.InvalidKeySpecException JavaDoc e) {
319             System.out.println("private key invalide");
320             e.printStackTrace();
321         } catch (java.security.NoSuchAlgorithmException JavaDoc e) {
322             e.printStackTrace();
323         } catch (java.security.NoSuchProviderException JavaDoc e) {
324             e.printStackTrace();
325         }
326
327         this.privateKey = privateKey;
328     }
329
330     /**
331      * Method setPrivateKey.
332      * sets the private key of the active object
333      */

334     private void setPrivateKey() {
335       // logger.info("Loading private key ...");
336

337         String JavaDoc privateKeyFile = policiesRules.getValueAsString(SecurityConstants.XML_PRIVATE_KEY)
338                                              .trim();
339         RSAPrivateKey JavaDoc privateKey = null;
340         PKCS8EncodedKeySpec JavaDoc key_spec = null;
341
342         byte[] key_bytes = null;
343
344         try {
345             FileInputStream JavaDoc fis = new FileInputStream JavaDoc(privateKeyFile);
346             ByteArrayOutputStream JavaDoc key_baos = new ByteArrayOutputStream JavaDoc();
347             int aByte = 0;
348
349             while ((aByte = fis.read()) != -1) {
350                 key_baos.write(aByte);
351             }
352
353             fis.close();
354             key_bytes = key_baos.toByteArray();
355             key_baos.close();
356
357             KeyFactory JavaDoc key_factory = KeyFactory.getInstance("RSA", "BC");
358             key_spec = new PKCS8EncodedKeySpec JavaDoc(key_bytes);
359             privateKey = (RSAPrivateKey JavaDoc) key_factory.generatePrivate(key_spec);
360         } catch (IOException JavaDoc e) {
361             System.out.println("Private Key not found : file " +
362                 privateKeyFile + " not found");
363             e.printStackTrace();
364         } catch (java.security.spec.InvalidKeySpecException JavaDoc e) {
365             System.out.println("private key invalide :" + privateKeyFile);
366             e.printStackTrace();
367         } catch (java.security.NoSuchAlgorithmException JavaDoc e) {
368             e.printStackTrace();
369         } catch (java.security.NoSuchProviderException JavaDoc e) {
370             e.printStackTrace();
371         }
372
373         this.privateKeyEncoded = key_bytes;
374         this.privateKey = privateKey;
375      // logger.info("Loading private key done ...");
376
}
377
378     /**
379      * Method initiateSession. This method is the entry point for an secured communication. We get local and distant policies,
380      * compute it, and generate the result policy, then if needed, we start an symmetric key exchange to encrypt the communication.
381      * @param distantBody
382      * @throws CommunicationForbiddenException
383      * @throws AuthenticationException
384      */

385     public void initiateSession(int type, UniversalBody distantBody)
386         throws CommunicationForbiddenException,
387             org.objectweb.proactive.ext.security.crypto.AuthenticationException,
388             RenegotiateSessionException, SecurityNotAvailableException {
389         X509Certificate JavaDoc distantBodyCertificate = null;
390         Communication localPolicy = null;
391         Communication distantBodyPolicy = null;
392
393         PolicyServer runtimePolicyServer = null;
394
395         distantBody = distantBody.getRemoteAdapter();
396
397         // get runtime Policy Server if exists
398
try {
399             runtimePolicyServer = RuntimeFactory.getDefaultRuntime()
400                                                 .getPolicyServer();
401         } catch (ProActiveException e1) {
402             e1.printStackTrace();
403         }
404
405         // identify local Virtual Node
406
Node n = null;
407
408         //System.out.println ("myBody is intanceof HalfBody " + (myBody instanceof HalfBody) + myBody + " " + myBody.getClass());
409
logger.debug(" myBody.getNodeURL() : " + myBody.getNodeURL() +
410             "VNNAME " + VNName);
411         if (VNName == null) {
412             // && (! myBody.getNodeURL().equals("LOCAL"))) {
413
// can be null if security was not enable at lauching time
414
// retrieving node's virtual node name
415
try {
416                 //logger.debug (" myBody.getNodeURL() : "+ myBody.getNodeURL());
417
System.out.println("NODE LOCAL");
418                 if (myBody.getNodeURL().equals ("LOCAL")) {
419                 VNName = NodeFactory.getDefaultNode().getVnName();
420                     
421                 } else {
422                     System.out.println("NODE PAS LOCAL");
423                 n = NodeFactory.getNode(myBody.getNodeURL());
424                 VNName = ProActiveSecurity.retrieveVNName(n.getNodeInformation()
425                                                            .getName());
426                 }
427             } catch (NodeException e2) {
428                 e2.printStackTrace();
429             }
430
431             //} else {
432
// VNName = "*";
433
}
434         if (n != null) {
435             logger.debug("sender : node ' " + n.getNodeInformation().getURL() +
436                 " " + n.getNodeInformation().getName() +
437                 "' - virtual node : '" + VNName);
438         }
439
440         String JavaDoc distantOAVirtualNode = null;
441
442         try {
443             distantOAVirtualNode = distantBody.getVNName();
444         } catch (IOException JavaDoc e3) {
445             e3.printStackTrace();
446         }
447
448         Communication runtimePolicy;
449         Communication VNPolicy;
450         Communication distantPolicy;
451         runtimePolicy = VNPolicy = distantBodyPolicy = null;
452         ArrayList JavaDoc arrayFrom = new ArrayList JavaDoc();
453         ArrayList JavaDoc arrayTo = new ArrayList JavaDoc();
454
455         if (VNName == null) {
456             arrayFrom.add(new DefaultEntity());
457         } else {
458             try {
459                 arrayFrom = myBody.getEntities();
460             } catch (SecurityNotAvailableException e2) {
461             } catch (IOException JavaDoc e2) {
462             }
463
464             //arrayFrom.add(new EntityVirtualNode(VNName));
465
}
466         if (distantOAVirtualNode == null) {
467             arrayTo.add(new DefaultEntity());
468         } else {
469             try {
470                 arrayTo = distantBody.getEntities();
471             } catch (IOException JavaDoc e2) {
472                 e2.printStackTrace();
473             }
474
475             ///arrayTo.add(new EntityVirtualNode(distantOAVirtualNode));
476
}
477         if (runtimePolicyServer != null) {
478             if (distantOAVirtualNode == null) {
479                 // distant Active Object is not security aware
480
distantOAVirtualNode = "*";
481             }
482             SecurityContext sc = new SecurityContext(SecurityContext.COMMUNICATION_SEND_REQUEST_TO,
483                     arrayFrom, arrayTo);
484             localPolicy = runtimePolicyServer.getPolicy(sc).getSendRequest();
485         } else {
486             logger.debug("No Runtime policy server installed : VN[ " + VNName +
487                 "], node " + myBody.getNodeURL());
488             localPolicy = new Communication();
489         }
490         if (!localPolicy.isCommunicationAllowed()) {
491             throw new CommunicationForbiddenException(
492                 "Sending request is denied to " + distantOAVirtualNode);
493         }
494
495         try {
496             SecurityContext sc = new SecurityContext(SecurityContext.COMMUNICATION_RECEIVE_REQUEST_FROM,
497                     arrayFrom, arrayTo);
498             distantPolicy = distantBody.getPolicy(sc).getReceiveRequest();
499
500             if (!distantPolicy.isCommunicationAllowed()) {
501                 throw new CommunicationForbiddenException(
502                     "Receiving request id denied for " + distantOAVirtualNode);
503             }
504
505             if (distantBodyPolicy == null) {
506                 distantBodyPolicy = new Communication();
507             }
508
509             Communication resultPolicy = Communication.computeCommunication(localPolicy,
510                     distantBodyPolicy);
511
512             long sessionID = 0;
513
514             try {
515                 sessionID = distantBody.startNewSession(resultPolicy);
516             } catch (IOException JavaDoc e) {
517                 logger.warn("can't start a new session");
518                 e.printStackTrace();
519                 throw new org.objectweb.proactive.ext.security.crypto.AuthenticationException();
520             }
521
522             Session session = null;
523
524             try {
525                 session = new Session(sessionID, resultPolicy);
526             } catch (Exception JavaDoc e) {
527                 e.printStackTrace();
528             }
529
530             session.distantBody = distantBody;
531             session.setDistantOACertificate(distantBodyCertificate);
532             sessions.put(new Long JavaDoc(sessionID), session);
533
534             if (distantBodyCertificate != null) {
535                 session.setDistantOAPublicKey(distantBodyCertificate.getPublicKey());
536             } else {
537                 session.setDistantOAPublicKey(distantBody.getPublicKey());
538             }
539
540             try {
541                 logger.debug("VN[" + VNName + "]:" + myBody + " -> VN " +
542                     distantOAVirtualNode + "Key echange session id :" +
543                     sessionID);
544                 keyNegociationSenderSide(distantBody, sessionID);
545             } catch (KeyExchangeException e) {
546                 logger.warn("Key exchange exception ");
547                 // System.exit(0);
548
throw new CommunicationForbiddenException();
549             }
550         } catch (java.io.IOException JavaDoc e) {
551             logger.warn("exception thrown while initiating the session");
552             e.printStackTrace();
553         }
554     }
555
556     public X509Certificate JavaDoc getCertificate() {
557         return certificate;
558     }
559
560     public void terminateSession(UniversalBody body, long sessionID) {
561         terminateSession(sessionID);
562     }
563
564     public void terminateSession(long sessionID) {
565         synchronized (sessions) {
566             sessions.remove(new Long JavaDoc(sessionID));
567
568             Session s = (Session) sessions.get(new Long JavaDoc(sessionID));
569             if (s == null) {
570                 System.out.println("Session " + sessionID +
571                     " deleted, new size " + sessions.size());
572             } else {
573                 System.out.println("ARRRRGGGGGGG Session " + sessionID +
574                     " not deleted");
575             }
576         }
577     }
578
579     public long startNewSession(Communication po) {
580         long id = 0;
581         Policy defaultPolicy = new Policy();
582         if (!defaultPolicy.equals(po)) {
583             try {
584                 Session ses = null;
585                 id = new Random JavaDoc().nextLong() + System.currentTimeMillis();
586
587                 Session newSession = ses = new Session(id, po);
588                 sessions.put(new Long JavaDoc(id), newSession);
589             } catch (Exception JavaDoc e) {
590                 e.printStackTrace();
591             }
592         }
593
594         return id;
595     }
596
597     /**
598      * Method encrypt.
599      * @param sessionID the session we use to encrypt the Object
600      * @param object the object to encrypt
601      * @return byte[][] encrypted result
602      */

603     public byte[][] encrypt(long sessionID, Object JavaDoc object) {
604         Session session = (Session) sessions.get(new Long JavaDoc(sessionID));
605         if (session != null) {
606             try {
607                 ByteArrayOutputStream JavaDoc bout = new ByteArrayOutputStream JavaDoc();
608
609                 MarshalOutputStream out = new MarshalOutputStream(bout);
610                 out.writeObject(object);
611                 out.flush();
612                 out.close();
613
614                 byte[] byteArray = bout.toByteArray();
615
616                 bout.close();
617
618                 return session.writePDU(byteArray);
619             } catch (Exception JavaDoc e) {
620                 e.printStackTrace();
621             }
622
623             // return encryptionEngine.encrypt(message, ((Session) sessions.get(s)).getSessionKey(id));
624
}
625
626         return null;
627     }
628
629     /**
630      * Method decrypt.
631      * @param sessionID the session we use to decrypt the message
632      * @param message the message to decrypt
633      * @return byte[] the decrypted message returns as byte array
634      */

635     public byte[] decrypt(long sessionID, byte[][] message)
636         throws RenegotiateSessionException {
637         Session session = (Session) sessions.get(new Long JavaDoc(sessionID));
638         if (session != null) {
639             try {
640                 return session.readPDU(message[0], message[1]);
641             } catch (Exception JavaDoc e) {
642                 e.printStackTrace();
643             }
644         } else {
645             Object JavaDoc o;
646             if (myBody instanceof BodyImpl) {
647                 o = ((Flower) ((BodyImpl) myBody).getReifiedObject()).getName();
648             } else {
649                 o = "HalfBody ";
650             }
651             logger.warn(o + "I have not find " + sessionID +
652                 " session to decrypt the message ");
653             throw new RenegotiateSessionException(myBody.getRemoteAdapter());
654         }
655
656         return null;
657     }
658
659     public boolean mutualAuthenticationSenderSide(UniversalBody distantBody,
660         X509Certificate JavaDoc distantBodyCertificate) throws AuthenticationException {
661         checkCertificate(distantBodyCertificate);
662         unilateralAuthenticationSenderSide(distantBody);
663
664         return true;
665     }
666
667     /**
668      * Method checkCertificate. Checks the validity of an certificate
669      * @param distantBodyCertificate the certificate to check
670      * @return boolean. returns true if the certificate is valid, false otherwise
671      */

672     private boolean checkCertificate(X509Certificate JavaDoc distantBodyCertificate) {
673         // logger.info("Checking distant OA certificate validity");
674
try {
675             distantBodyCertificate.checkValidity();
676         } catch (CertificateExpiredException JavaDoc e) {
677             logger.warn(distantBodyCertificate.getSubjectDN() +
678                 " has expired, negociation stopped");
679
680             return false;
681         } catch (CertificateNotYetValidException JavaDoc e) {
682             logger.warn(distantBodyCertificate.getSubjectDN() +
683                 " is not yet valid, negociation stopped");
684
685             return false;
686         }
687
688         // logger.info("Retrieving DistantOA Domain Server");
689
String JavaDoc domainLocation = distantBodyCertificate.getIssuerDN().getName();
690
691         return true;
692     }
693
694     public boolean unilateralAuthenticationSenderSide(UniversalBody distantBody)
695         throws AuthenticationException {
696         long rb = randomLongGenerator.generateLong(32);
697         AuthenticationTicket authenticationTicket = new AuthenticationTicket();
698         String JavaDoc B = certificate.getIssuerDN().getName();
699         long ra = authenticationTicket.random;
700         String JavaDoc addresse = authenticationTicket.identity;
701
702         if (addresse.equals(B) == false) {
703             throw new AuthenticationException(
704                 "SessionInitializer : WRONG IDENTITY");
705         }
706
707         // Emitter Certificate Checking
708
X509Certificate JavaDoc emitterCertificate = authenticationTicket.certificate;
709         String JavaDoc A = emitterCertificate.getIssuerDN().getName();
710
711         // A is the sessionInitializer
712
checkCertificate(emitterCertificate);
713
714         AuthenticationTicketProperty properties = new AuthenticationTicketProperty();
715
716         try {
717             properties = (AuthenticationTicketProperty) ((SignedObject JavaDoc) authenticationTicket.signedAuthenticationTicketProperty).getObject();
718         } catch (Exception JavaDoc e) {
719             System.out.println(
720                 "SessionInitializer : Exception in AuthenticationTicketProperty extraction : " +
721                 e);
722         }
723
724         if (properties.random1 != ra) {
725             throw new AuthenticationException("SessionInitializer : wrong ra");
726         }
727
728         if (properties.random2 != rb) {
729             throw new AuthenticationException("SessionInitializer : wrong rb");
730         }
731
732         if (properties.identity.equals(B) == false) {
733             throw new AuthenticationException("SessionInitializer : wrong B");
734         }
735
736         // this.authentication = true;
737
return true;
738     }
739
740     /**
741      * Method keyNegociationSenderSide. starts the challenge to negociate a session key.
742      * @param distantOA distant active object we want to communicate to.
743      * @param sessionID the id of the session we will use
744      * @return boolean returns true if the negociation has succeed.
745      * @throws KeyExchangeException
746      */

747     public boolean keyNegociationSenderSide(UniversalBody distantOA,
748         long sessionID) throws KeyExchangeException {
749         Session session = (Session) sessions.get(new Long JavaDoc(sessionID));
750         distantOA = distantOA.getRemoteAdapter();
751         if (session == null) {
752             throw new KeyExchangeException("the session is null");
753         }
754
755         try {
756             // Step 1. public key exchange for authentication
757
//
758
// Send a HELLO to server + my random value.
759
// The server will now respond with its Hello + random.
760
// se_rand is the server response
761
// Read the HELLO back from the server and collect
762
// the Server Random value.
763
//
764
session.sec_rand.nextBytes(session.cl_rand);
765             session.se_rand = distantOA.randomValue(sessionID, session.cl_rand);
766
767             // Next send my public key from the key pair that is only
768
// used for encryption/decryption purposes. Then sign the whole
769
// exchange with my signing only key pair.
770
//
771
//
772
// Set up Signature Class.
773
//
774
byte[] my_pub;
775             byte[] my_cert;
776             byte[] sig_code;
777             Signature JavaDoc sig = Signature.getInstance("MD5withRSA", "BC");
778
779             //
780
// Init signature with the private key used for signing.
781
//
782
sig.initSign(privateKey, session.sec_rand);
783
784             //
785
// All signatures incorporate the client random and the server
786
// random values.
787
//
788
sig.update(session.cl_rand); // Incorporated into every sig.
789
sig.update(session.se_rand);
790
791             //
792
// Get my public key (for encryption) as a byte array.
793
//
794
my_pub = publicKey.getEncoded();
795
796             //
797
// Get my certificate (for sig validation and auth) as a byte array.
798
//
799
my_cert = certificate.getEncoded();
800             sig.update(my_pub); // Incorporate public key into signature.
801
sig.update(my_cert); // Incorporate certificate into signature.
802

803             sig_code = sig.sign();
804
805             // System.out.println(session);
806
//
807
// complete the PDU and send it to the server
808
//
809
byte[][] tab = distantOA.publicKeyExchange(sessionID,
810                     myBody.getRemoteAdapter(), my_pub, my_cert, sig_code);
811
812             //
813
// Now server should respond with its public key exchange message.
814
// If it does not I must break as the protocol has been broken.
815
//
816
//
817
// Read in Server Public key.
818
//
819
byte[] pub_key = tab[0];
820
821             //
822
// Before we can use the public key we must convert it back
823
// to a Key object by using the KeyFactory and the appropriate
824
// KeySpec.. In this case the X509EncodedKeySpec is the correct one.
825
//
826
X509EncodedKeySpec JavaDoc key_spec = new X509EncodedKeySpec JavaDoc(pub_key);
827             KeyFactory JavaDoc key_fact = KeyFactory.getInstance("RSA", "BC");
828
829             //
830
// Recover Servers Public key.
831
//
832
session.distantOAPublicKey = key_fact.generatePublic(key_spec);
833
834             //
835
// Read in the encoded form of the X509Certificate that the
836
// server uses. For authentication of its identity.
837
//
838
byte[] cert = tab[1];
839
840             //
841
// Set up a Certificate Factory to process the raw certificate
842
// back into an X509 Certificate
843
//
844
CertificateFactory JavaDoc cf = CertificateFactory.getInstance("X.509");
845
846             //
847
// Recover Servers Certificate
848
//
849
session.distantOACertificate = (X509Certificate JavaDoc) cf.generateCertificate(new ByteArrayInputStream JavaDoc(
850                         cert));
851
852             // NOTE:
853
// At this point it should be noted that the client must employ
854
// some mechanism to validate and authenticate the servers
855
// certificate.
856
// PublicKey se_public = distantOA.getPublicKey();
857
// X509Certificate server_cert = distantOA.getCertificate();
858
//
859
// Read in Signature code.
860
//
861
sig_code = tab[2];
862
863             //
864
// Now we must verify the data that we received against
865
// the signature code at the end of the pdu.
866
//
867
//
868
// Using the authentication certificate sent by the server.
869
//
870
synchronized (sig) {
871                 sig.initVerify(session.distantOACertificate);
872                 sig.update(session.cl_rand); // Incorporate in Client Random.
873
sig.update(session.se_rand); // Incorporate in Server Random.
874
sig.update(pub_key); // Incorporate in Public key (as sent in encoded form).
875
sig.update(cert); // Incorporate in Certificate. (as sent in encoded form).
876

877                 if (!sig.verify(sig_code)) {
878                     throw new Exception JavaDoc(
879                         "(CLIENT)Signature failed on Public key exchange data unit");
880                 }
881             }
882
883             // ==== confidentiality part : secret key exchange
884
//
885
// Now that we have successfully exchanged public keys
886
// The client now needs to being a SecretKey Exchange process.
887
// First we need to generate some secrets using the appropriate
888
// KeyGenerator. When using the JCE you should always use a
889
// KeyGenerator instance specifically set up for your target cipher.
890
// The KeyGenerator code will generate a secret that is "safe" for use
891
// and filter out any keys that may be weak or broken for that cipher.
892
//
893
KeyGenerator key_gen = KeyGenerator.getInstance("AES", "BC"); // Get instance for AES
894
synchronized (key_gen) {
895                 key_gen.init(192, session.sec_rand); // Use a 192 bit key size.
896
session.cl_aes_key = key_gen.generateKey(); // Generate the SecretKey
897

898                 key_gen.init(160, session.sec_rand); // Set up for a 160 bit key.
899
session.cl_hmac_key = key_gen.generateKey(); // Generate key for HMAC.
900
}
901             session.cl_iv = new IvParameterSpec(new byte[16]);
902
903             Object JavaDoc i = new Object JavaDoc();
904             byte[] aes_key;
905             byte[] iv;
906             byte[] mac;
907             byte[] lock;
908             byte[] sigtab;
909
910             //
911
// I have added this extra piece of data so that an attacker
912
// cannot resign or modify the secret exchange without being one of the recipients.
913
//
914
byte[] tmp_lock = new byte[24];
915             Cipher aes_lock = null;
916             synchronized (i) {
917                 //
918
// Next we need it instantiate the Cipher class that will be used by
919
// the client. As this is the client side the cipher needs to be set
920
// up for Encryption.
921
//
922
session.cl_cipher.init(Cipher.ENCRYPT_MODE, session.cl_aes_key,
923                     session.cl_iv, session.sec_rand);
924
925                 //
926
// Set up Client side MAC with key.
927
//
928
session.cl_mac.init(session.cl_hmac_key);
929
930                 //
931
// Load byte array with random data.
932
//
933
session.sec_rand.nextBytes(tmp_lock);
934
935                 //
936
// Set up RSA for encryption.
937
//
938
session.rsa_eng.init(Cipher.ENCRYPT_MODE,
939                     session.distantOAPublicKey);
940
941                 //
942
// Set up and instace of AES for the Signature locking data.
943
//
944
aes_lock = Cipher.getInstance("AES/CBC/PKCS7Padding");
945                 aes_lock.init(Cipher.ENCRYPT_MODE, session.cl_aes_key,
946                     session.cl_iv, session.sec_rand);
947
948                 //
949
// Secret Keys Exchange. = confidentiality
950
//
951
//
952
// Set up Signature so that the server can validate our data.
953
//
954
sig.initSign(privateKey);
955                 sig.update(session.cl_rand); // Incorporate Client Random
956
sig.update(session.se_rand); // Incorporate Server Random.
957

958                 aes_key = session.rsa_eng.doFinal(session.cl_aes_key.getEncoded()); // Encrypt the encoded AES key.
959
sig.update(aes_key); // Incorporate into signature.
960

961                 iv = session.rsa_eng.doFinal(session.cl_iv.getIV()); // Encrypt the IV.
962
sig.update(iv); // Incorporate into signature.
963

964                 mac = session.rsa_eng.doFinal(session.cl_hmac_key.getEncoded()); // Encrypt and encode MAC key.
965
sig.update(mac); // Incorporate into signature.
966

967                 lock = aes_lock.doFinal(tmp_lock); // Encrypt lock data.
968
sig.update(tmp_lock); // Incorporate plain text of lock data into signature.
969

970                 // send to server and get the results
971
sigtab = sig.sign();
972             }
973
974             byte[][] tabresult = distantOA.secretKeyExchange(sessionID,
975                     aes_key, iv, mac, lock, sigtab);
976
977             //
978
// Read back the server secret.
979
//
980
// The server should respond with its secret if it does not then
981
// the protocol is broken..
982
//
983
//
984
// Set up RSA in decrypt mode so that we can decrypt their
985
// server's secrets.
986
//
987
byte[] aes_key_enc;
988
989             //
990
// Read back the server secret.
991
//
992
// The server should respond with its secret if it does not then
993
// the protocol is broken..
994
//
995
//
996
// Set up RSA in decrypt mode so that we can decrypt their
997
// server's secrets.
998
//
999
byte[] iv_enc;
1000
1001            //
1002
// Read back the server secret.
1003
//
1004
// The server should respond with its secret if it does not then
1005
// the protocol is broken..
1006
//
1007
//
1008
// Set up RSA in decrypt mode so that we can decrypt their
1009
// server's secrets.
1010
//
1011
byte[] hmac_key_enc;
1012
1013            //
1014
// Read back the server secret.
1015
//
1016
// The server should respond with its secret if it does not then
1017
// the protocol is broken..
1018
//
1019
//
1020
// Set up RSA in decrypt mode so that we can decrypt their
1021
// server's secrets.
1022
//
1023
byte[] tmp_loc;
1024
1025            synchronized (session.rsa_eng) {
1026                session.rsa_eng.init(Cipher.DECRYPT_MODE, privateKey,
1027                    session.sec_rand);
1028
1029                //
1030
// Read in secret key.
1031
//
1032
aes_key_enc = tabresult[0];
1033
1034                //
1035
// Read in IV
1036
//
1037
iv_enc = tabresult[1];
1038
1039                //
1040
// Read in HMAC key.
1041
//
1042
hmac_key_enc = tabresult[2];
1043
1044                //
1045
// Read in lock
1046
//
1047
tmp_lock = tabresult[3];
1048
1049                //
1050
// Now we must validate the received data.
1051
// NOTE: the need to decrypt the tmp_lock data.
1052
//
1053
//
1054
// Set up AES lock so we can decrypt lock data.
1055
//
1056
SecretKey sk = (SecretKey) new SecretKeySpec(session.rsa_eng.doFinal(
1057                            aes_key_enc), "AES");
1058                IvParameterSpec ivspec = new IvParameterSpec(session.rsa_eng.doFinal(
1059                            iv_enc));
1060                aes_lock.init(Cipher.DECRYPT_MODE, sk, ivspec);
1061                sig.initVerify(session.distantOACertificate); // Set up using server's certificate.
1062
sig.update(session.cl_rand);
1063                sig.update(session.se_rand);
1064                sig.update(aes_key_enc);
1065                sig.update(iv_enc);
1066                sig.update(hmac_key_enc);
1067                sig.update(aes_lock.doFinal(tmp_lock));
1068
1069                if (!sig.verify(tabresult[4])) {
1070                    throw new Exception JavaDoc(
1071                        "Signature failed on Public key exchange data unit");
1072                } else {
1073                    // System.out.println("Client: Server PDU for secret key exchange signature passed");
1074
}
1075
1076                //
1077
// At this point we have successfully exchanged secrets..
1078
// So now we need to set up a Cipher class to allow us to
1079
// Decrypt data sent from the server to the client.
1080
//
1081
//
1082
session.se_aes_key = (SecretKey) new SecretKeySpec(session.rsa_eng.doFinal(
1083                            aes_key_enc), "AES");
1084                session.se_iv = new IvParameterSpec(session.rsa_eng.doFinal(
1085                            iv_enc));
1086                session.se_cipher.init(Cipher.DECRYPT_MODE, session.se_aes_key,
1087                    session.se_iv);
1088
1089                //
1090
// We also need to set up the MAC so that we can validate
1091
// data sent from the server.
1092
//
1093
session.se_hmac_key = (SecretKey) new SecretKeySpec(session.rsa_eng.doFinal(
1094                            hmac_key_enc), "AES");
1095                session.se_mac.init(session.se_hmac_key);
1096            }
1097
1098            // System.out.println("session key end");
1099
//
1100
// Set up session to generate appropriate PDUs.
1101
// To see this shape of the PDUs that are used to exchange
1102
// encrypted data.
1103
//
1104
// setup for sending and receiving are automaticly done if we succeed
1105
// the key echange
1106
} catch (Exception JavaDoc e) {
1107            e.printStackTrace();
1108            throw new KeyExchangeException();
1109
1110            //e.printStackTrace();
1111
}
1112
1113        return true;
1114    }
1115
1116    public AuthenticationTicket mutualAuthenticationReceiverSide(
1117        AuthenticationTicket authenticationTicket, long randomID)
1118        throws org.objectweb.proactive.ext.security.crypto.AuthenticationException {
1119        return null;
1120    }
1121
1122    /**
1123     * Method generateSessionKey. generates a session key using Rijndael algorithms.
1124     * @return Key a symetric key used to encrypt/decrypt communications between active objects
1125     */

1126    private Key JavaDoc generateSessionKey() {
1127        try {
1128            KeyGenerator keyGen = KeyGenerator.getInstance("Rijndael", "BC");
1129            keyGen.init(128, new SecureRandom JavaDoc());
1130
1131            return keyGen.generateKey();
1132        } catch (java.security.NoSuchProviderException JavaDoc e) {
1133            e.printStackTrace();
1134        } catch (java.security.NoSuchAlgorithmException JavaDoc e) {
1135            e.printStackTrace();
1136        }
1137
1138        return null;
1139    }
1140
1141    public AuthenticationTicket unilateralAuthenticationReceiverSide(
1142        long randomID, long rb, String JavaDoc emittor) throws AuthenticationException {
1143        return null;
1144    }
1145
1146    public ConfidentialityTicket keyNegociationReceiverSide(
1147        ConfidentialityTicket confidentialityTicket, long randomID)
1148        throws KeyExchangeException {
1149        return null;
1150    }
1151
1152    public byte[] randomValue(long sessionID, byte[] cl_rand)
1153        throws Exception JavaDoc {
1154        // server side
1155
// Step one..
1156
// Upon receipt of client Hello the server process reads
1157
// in a byte array of 32 random bytes. The server process
1158
// then responds with a byte array of random data.
1159
//
1160
// System.out.println("RAndomValue sessionID : " + new Long(sessionID));
1161
// System.out.println("++++++++++++++++++ List opened sessions : ++++++++++++++++++++++++");
1162
// System.out.println("Certificat : " + certificate.getSubjectDN());
1163
// for (Enumeration e = sessions.elements() ; e.hasMoreElements() ;) {
1164
// System.out.println(e.nextElement());
1165
// }
1166
// System.out.println("++++++++++++++++++ End List opened sessions : ++++++++++++++++++++++++");
1167
Session session = (Session) sessions.get(new Long JavaDoc(sessionID));
1168
1169        // System.out.println("fsdfsda session : " + session);
1170
if (session == null) {
1171            throw new KeyExchangeException(
1172                "Session not started,session is null");
1173        }
1174
1175        try {
1176            // System.out.println("Server: got HELLO from client");
1177
session.cl_rand = cl_rand;
1178
1179            //
1180
// Generate Server's Random;
1181
//
1182
session.sec_rand.nextBytes(session.se_rand); // Fill with random data.
1183

1184            // System.out.println("Server: Sending my HELLO to client");
1185
} catch (Exception JavaDoc e) {
1186            System.out.println("Server: Hello failed");
1187            e.printStackTrace();
1188        }
1189
1190        return session.se_rand;
1191    }
1192
1193    public byte[][] publicKeyExchange(long sessionID,
1194        UniversalBody distantBody, byte[] pub_key, byte[] cert, byte[] sig_code)
1195        throws Exception JavaDoc {
1196        // server side
1197
// Step two..
1198
// 1. The server reads in the clients public key.
1199
// 2. The clients signing certificate.
1200
// 3. A signature.
1201
//
1202
// Note that the signature is composed of:
1203
// Client public key;
1204
// Concatenation of Clients random and Server random;
1205
// Clients signing certificate.
1206
//
1207
// By including the shared randoms we effectively make
1208
// this exchange unique each time a session is started.
1209
// This would stop an attacker from replaying a previously
1210
// recorded exchange.
1211
//
1212
Session session = (Session) sessions.get(new Long JavaDoc(sessionID));
1213
1214        if (session == null) {
1215            throw new KeyExchangeException("Session not started");
1216        }
1217
1218        // System.out.println("Server: Reading public key + cert + sig from client" + sessionID);
1219
// setting distant OA proxy
1220
session.distantBody = distantBody;
1221
1222        // Read public key
1223
//
1224
// Now we must take in the encoded public key and
1225
// use a KeyFactory to turn it back into a Key Object.
1226
//
1227
X509EncodedKeySpec JavaDoc key_spec = new X509EncodedKeySpec JavaDoc(pub_key);
1228        KeyFactory JavaDoc key_fact = KeyFactory.getInstance("RSA", "BC");
1229        session.distantOAPublicKey = key_fact.generatePublic(key_spec); // Generate the public key.
1230

1231        CertificateFactory JavaDoc cf = CertificateFactory.getInstance("X.509");
1232
1233        // System.out.println("certif :" + cert);
1234
session.distantOACertificate = (X509Certificate JavaDoc) cf.generateCertificate(new ByteArrayInputStream JavaDoc(
1235                    cert)); // Convert.
1236

1237        Signature JavaDoc sig = null;
1238
1239        sig = Signature.getInstance("MD5withRSA", "BC"); // Set up Signer.
1240
sig.initVerify(session.distantOAPublicKey); // Initialize with clients signing certificate.
1241
sig.update(session.cl_rand); // Incorporate client random.
1242
sig.update(session.se_rand); // Incorporate server random.
1243
sig.update(pub_key); // Incorporate encoded public key.
1244
sig.update(cert); // Incorporate encoded certificate.
1245

1246        if (!sig.verify(sig_code)) {
1247            System.out.println(session);
1248            logger.warn("Signature failed on Public key exchange data unit");
1249            throw new Exception JavaDoc(
1250                "Signature failed on Public key exchange data unit");
1251        } else {
1252            // System.out.println("Server: Client PDU signature passed");
1253
}
1254
1255        // System.out.println("Server: Sending my public key + cert + sig to client.");
1256
//
1257
// Send server public key to client.
1258
//
1259
//
1260
// Set up signer.
1261
//
1262
sig.initSign(privateKey);
1263        sig.update(session.cl_rand);
1264        sig.update(session.se_rand);
1265
1266        //
1267
// Get my public key (for encryption) as a byte array.
1268
//
1269
byte[] my_pub = certificate.getPublicKey().getEncoded();
1270
1271        //
1272
// Get my certificate (for sig validation and auth) as
1273
// a byte array.
1274
//
1275
byte[] my_cert = certificate.getEncoded();
1276        sig.update(my_pub);
1277        sig.update(my_cert);
1278
1279        byte[][] result = new byte[4][];
1280        result[0] = certificate.getPublicKey().getEncoded();
1281        result[1] = certificate.getEncoded();
1282        sig_code = sig.sign();
1283        result[2] = sig_code;
1284
1285        // return the results to the client
1286
return result;
1287    }
1288
1289    public static String JavaDoc displayByte(byte[] tab) {
1290        String JavaDoc s = "";
1291
1292        for (int i = 0; i < tab.length; i++) {
1293            s += tab[i];
1294        }
1295
1296        return s;
1297    }
1298
1299    /**
1300     * Method secretKeyExchange. exchamge secret between objects
1301     * @param sessionID the session
1302     * @param aesKey the private key
1303     * @param iv
1304     * @param macKey the MAC key
1305     * @param lockData
1306     * @param signature signature of aesKey,iv, macKey and lockData
1307     * @return byte[][]
1308     */

1309    public byte[][] secretKeyExchange(long sessionID, byte[] aesKey, byte[] iv,
1310        byte[] macKey, byte[] lockData, byte[] signature) {
1311        byte[][] result = new byte[5][];
1312
1313        try {
1314            Session session = (Session) sessions.get(new Long JavaDoc(sessionID));
1315
1316            if (session == null) {
1317                throw new KeyExchangeException("Session not started");
1318            }
1319
1320            // Part 3: The Secret Exchange..
1321
//
1322
// 1. Read SecretKey encrypted with RSA.
1323
// 2. Read IV encrypted with RSA.
1324
// 3. Read HMAC key encrypted with RSA.
1325
// 4. Read in signature.
1326
//
1327
// NOTE: No need to send cert again. Certificate
1328
// sent in previous stage.
1329
//
1330
Cipher aes_lock = Cipher.getInstance("AES/CBC/PKCS7Padding");
1331
1332            //
1333
// Read in secret key .
1334
//
1335
byte[] aes_key_enc = aesKey;
1336
1337            //
1338
// Read in IV
1339
//
1340
byte[] iv_enc = iv;
1341
1342            //
1343
// Read in HMAC key.
1344
//
1345
byte[] hmac_key_enc = macKey;
1346
1347            //
1348
// Read in lock
1349
//
1350
byte[] tmp_lock = lockData;
1351
1352            //
1353
// Validate message against client's signing certificate
1354
// exchanged in the previous stage.
1355
//
1356
// But first we need to decrypt the lock data to incorperate into the exchange.
1357
//
1358
// System.out.println("MyBody is " + myBody);
1359
// System.out.println("session.rsa_eng is " + session.rsa_eng);
1360
// System.out.println(" aes_key_enc " + aes_key_enc);
1361
// System.out.println(" certi " + certificate);
1362
Provider JavaDoc myProvider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
1363            Security.addProvider(myProvider);
1364            session.rsa_eng = Cipher.getInstance("RSA/None/OAEPPadding", "BC"); // RSA Cipher.
1365

1366            session.rsa_eng.init(Cipher.DECRYPT_MODE, privateKey);
1367
1368            SecretKey sk = (SecretKey) new SecretKeySpec(session.rsa_eng.doFinal(
1369                        aes_key_enc), "AES");
1370            IvParameterSpec ivspec = new IvParameterSpec(session.rsa_eng.doFinal(
1371                        iv_enc));
1372            aes_lock.init(Cipher.DECRYPT_MODE, sk, ivspec);
1373
1374            Signature JavaDoc sig = Signature.getInstance("MD5withRSA", "BC");
1375            sig.initVerify(session.distantOACertificate);
1376            sig.update(session.cl_rand);
1377            sig.update(session.se_rand);
1378            sig.update(aes_key_enc);
1379            sig.update(iv_enc);
1380            sig.update(hmac_key_enc);
1381            sig.update(aes_lock.doFinal(tmp_lock));
1382
1383            if (!sig.verify(signature)) {
1384                throw new Exception JavaDoc(
1385                    "(Server) :Signature failed on Public key exchange data unit");
1386            } else {
1387                // System.out.println("Server: Client PDU for secret key exchange signature passed");
1388
}
1389
1390            //
1391
// Now we can set up a Cipher instance that will decrypt
1392
// data sent from the client.
1393
//
1394
session.se_aes_key = (SecretKey) new SecretKeySpec(session.rsa_eng.doFinal(
1395                        aes_key_enc), "AES");
1396            session.se_iv = new IvParameterSpec(session.rsa_eng.doFinal(iv_enc));
1397            session.se_cipher.init(Cipher.DECRYPT_MODE, session.se_aes_key,
1398                session.se_iv);
1399
1400            //
1401
// Set up the MAC to validate data sent from the client
1402
// side.
1403
//
1404
session.se_mac_enc = session.rsa_eng.doFinal(hmac_key_enc);
1405            session.se_hmac_key = (SecretKey) new SecretKeySpec(session.se_mac_enc,
1406                    "AES");
1407            session.se_mac.init(session.se_hmac_key);
1408
1409            //
1410
// Now send my secrets back to client encrypted with
1411
// public key exchanged by client.
1412
//
1413
//
1414
// Generate my secrets.
1415
//
1416
KeyGenerator key_gen = KeyGenerator.getInstance("AES", "BC");
1417            key_gen.init(192, session.sec_rand);
1418            session.cl_aes_key = key_gen.generateKey();
1419            key_gen.init(160, session.sec_rand);
1420            session.cl_hmac_key = key_gen.generateKey();
1421            session.cl_cipher.init(Cipher.ENCRYPT_MODE, session.cl_aes_key,
1422                session.cl_iv, session.sec_rand);
1423
1424            byte[] my_iv = session.cl_cipher.getIV();
1425            session.cl_iv = new IvParameterSpec(my_iv);
1426            session.cl_mac.init(session.cl_hmac_key);
1427            tmp_lock = new byte[24];
1428            session.sec_rand.nextBytes(tmp_lock);
1429
1430            //
1431
// Set up RSA for encryption.
1432
//
1433
sig.initSign(privateKey);
1434            sig.update(session.cl_rand);
1435            sig.update(session.se_rand);
1436            session.rsa_eng.init(Cipher.ENCRYPT_MODE,
1437                session.distantOAPublicKey, session.sec_rand);
1438
1439            //
1440
// Encrypt and send AES key.
1441
//
1442
result[0] = session.rsa_eng.doFinal(session.cl_aes_key.getEncoded());
1443            sig.update(result[0]);
1444
1445            //
1446
// Encrypt and send IV for cipher.
1447
//
1448
result[1] = session.rsa_eng.doFinal(my_iv);
1449            sig.update(result[1]);
1450
1451            //
1452
// Encrypt and send MAC key..
1453
//
1454
result[2] = session.rsa_eng.doFinal(session.cl_hmac_key.getEncoded());
1455            sig.update(result[2]);
1456
1457            //
1458
// Encrypt and send LOCK data..
1459
//
1460
aes_lock.init(Cipher.ENCRYPT_MODE, session.cl_aes_key,
1461                new IvParameterSpec(my_iv), session.sec_rand);
1462            result[3] = aes_lock.doFinal(tmp_lock);
1463            sig.update(tmp_lock); // Incorporate plain text into signature.
1464

1465            result[4] = sig.sign();
1466
1467            //
1468
// Now we have finished exchanging symmetric keys we
1469
// can set up our PDU generators to send encrypted
1470
// messages.
1471
//
1472
// System.out.println("Key exchanged and session is up");
1473
} catch (Exception JavaDoc e) {
1474            System.out.println("Invalid Key Exchange !");
1475            e.printStackTrace();
1476        }
1477
1478        return result;
1479    }
1480
1481    // implements Serializable
1482
private void writeObject(java.io.ObjectOutputStream JavaDoc out)
1483        throws IOException JavaDoc {
1484        // privateKeyEncoded = privateKey.getEncoded();
1485
out.defaultWriteObject();
1486
1487        try {
1488            byte[] certE = certificate.getEncoded();
1489            out.writeInt(certE.length);
1490            out.write(certE);
1491        } catch (CertificateEncodingException JavaDoc e) {
1492            e.printStackTrace();
1493        } catch (IOException JavaDoc e) {
1494            e.printStackTrace();
1495        }
1496    }
1497
1498    private void readObject(java.io.ObjectInputStream JavaDoc in)
1499        throws IOException JavaDoc, ClassNotFoundException JavaDoc {
1500        in.defaultReadObject();
1501        logger = Logger.getLogger(
1502                "org.objectweb.proactive.ext.security.ProActiveSecurityManager");
1503
1504        //privateKeyEncoded = in.read();
1505
// Add bouncycastle security provider
1506
// Provider myProvider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
1507
// Security.addProvider(myProvider);
1508
// Security.insertProviderAt(myProvider, 0);
1509
// decompressing the private Key
1510
// logger.info("decompressing private key " + privateKey);
1511
//decodePrivateKey();
1512
randomLongGenerator = new RandomLongGenerator();
1513
1514        int i = in.readInt();
1515        byte[] certEncoded = new byte[i];
1516        in.read(certEncoded);
1517
1518        certificate = ProActiveSecurity.decodeCertificate(certEncoded);
1519
1520        // logger.info("creating randomgenerator " + randomLongGenerator);
1521
// logger.info("Security Manager restarted");
1522
}
1523
1524    // public long getSessionIDTo(UniversalBody distantBody) {
1525
//
1526
// Session session = null;
1527
//
1528
// for (Enumeration e = sessions.elements(); e.hasMoreElements();) {
1529
// session = (Session)e.nextElement();
1530
//
1531
// // System.out.println("session " + session);
1532
// // System.out.println("session distantBody " + session.distantBody);
1533
// // System.out.println("distantBody " + distantBody);
1534
// if (session != null) {
1535
//
1536
// if ((session.distantBody != null) &&
1537
// (session.distantBody.equals(distantBody))) {
1538
// logger.info(
1539
// "find an already initialized session" + session);
1540
//
1541
// return session.sessionID;
1542
// }
1543
// }
1544
// }
1545
//
1546
// return (long)0;
1547
// }
1548
public long getSessionIDTo(X509Certificate JavaDoc cert) {
1549        Object JavaDoc o;
1550        Object JavaDoc o1;
1551        o = o1 = null;
1552        if (myBody instanceof BodyImpl) {
1553            o1 = ((BodyImpl) myBody).getReifiedObject();
1554            if (o1 instanceof Flower) {
1555                o = ((Flower) o1).getName();
1556            } else {
1557                o = o1;
1558            }
1559        }
1560
1561        // System.out.println(o + "----------------------");
1562
// System.out.println(o + "Source :" + certificate.getSubjectDN());
1563
// System.out.println(o + "Target :" + cert.getSubjectDN());
1564
Session session = null;
1565        if (sessions == null) {
1566            return (long) 0;
1567        }
1568
1569        for (Enumeration JavaDoc e = sessions.elements(); e.hasMoreElements();) {
1570            session = (Session) e.nextElement();
1571
1572            /*
1573                            System.out.println("-----------------\nsession " + session);
1574                            System.out.println("session distantBody " + session.distantOACertificate.getSubjectDN());
1575                            System.out.println("distantBodyCertificate " + certificate.getSubjectDN());
1576                            System.out.println("-----------------\n");
1577              */

1578            if (session != null) {
1579                // System.out.println(o + "tested :" + session.distantOACertificate.getSubjectDN());
1580
if ((cert != null) && (session.distantOACertificate != null) &&
1581                        cert.getSubjectDN().equals(session.distantOACertificate.getSubjectDN())) {
1582                    // logger.info("find an already initialized session" + session);
1583
//certificate.equals(session.distantOACertificate);
1584
// System.out.println(o+"=====yes========");
1585
return session.sessionID;
1586                }
1587            }
1588        }
1589
1590        // System.out.println("=======no======");
1591

1592        /* We didn't find a session */
1593        return (long) 0;
1594    }
1595
1596    /**
1597     * Method getPublicKey.
1598     * @return PublicKey the public key of the active object
1599     */

1600    public PublicKey JavaDoc getPublicKey() {
1601        return certificate.getPublicKey();
1602    }
1603
1604    /**
1605     *
1606     */

1607    public void setParentCertificate(X509Certificate JavaDoc certificate) {
1608        parentCertificate = certificate;
1609    }
1610
1611    public Hashtable JavaDoc getOpenedConnexion() {
1612        Hashtable JavaDoc table = null;
1613        if (sessions == null) {
1614            return table;
1615        }
1616
1617        table = new Hashtable JavaDoc();
1618
1619        for (Enumeration JavaDoc e = sessions.keys(); e.hasMoreElements();) {
1620            Long JavaDoc l = (Long JavaDoc) e.nextElement();
1621            table.put(l, l.toString());
1622        }
1623
1624        return table;
1625    }
1626
1627    /**
1628     * @param string
1629     */

1630    public void setVNName(String JavaDoc string) {
1631        // System.out.println("setting vn node name " + string);
1632
this.VNName = string;
1633
1634        //policyServer.setVNName(string);
1635
}
1636
1637    /**
1638     * @return virtual node name where object has been created
1639     */

1640    public String JavaDoc getVNName() {
1641        return VNName;
1642    }
1643
1644    /**
1645    * @return policy server
1646    */

1647    public PolicyServer getPolicyServer() {
1648        return policyServer;
1649    }
1650
1651    /**
1652     * @return certificate as byte array
1653     */

1654    public byte[] getCertificateEncoded() {
1655        try {
1656            return certificate.getEncoded();
1657        } catch (CertificateEncodingException JavaDoc e) {
1658            e.printStackTrace();
1659        }
1660
1661        return null;
1662    }
1663
1664    /**
1665     * @param set object policy server
1666     */

1667    public void setPolicyServer(PolicyServer policyServer) {
1668        this.policyServer = policyServer;
1669    }
1670
1671    /**
1672     * @param type
1673     * @param from
1674     * @param to
1675     * @return communication attributes
1676     */

1677    public Communication getPolicyFrom(String JavaDoc type, String JavaDoc from, String JavaDoc to) {
1678        return null;
1679    }
1680
1681    /**
1682     * @return entities that inforces security policy on the object
1683     */

1684    public ArrayList JavaDoc getEntities() {
1685        ProActiveRuntimeImpl proActiveRuntime = (ProActiveRuntimeImpl) ProActiveRuntimeImpl.getProActiveRuntime();
1686
1687        Node n = null;
1688        ArrayList JavaDoc a = new ArrayList JavaDoc();
1689        try {
1690            n = NodeFactory.getNode(myBody.getNodeURL());
1691        } catch (NodeException e) {
1692            e.printStackTrace();
1693        }
1694
1695   // PolicyServer p = proActiveRuntime.getNodePolicyServer(n.getNodeInformation()
1696
// .getName());
1697

1698   try {
1699   
1700    
1701        if (policyServer != null) {
1702            EntityVirtualNode entityVirtualNode = new EntityVirtualNode(VNName,
1703                    policyServer.getApplicationCertificate(), policyServer.getCertificate());
1704            a.add(entityVirtualNode);
1705            return a;
1706        } else {
1707        
1708        a.add(new DefaultEntity());
1709        }
1710   } catch (Exception JavaDoc e) {
1711    System.out.println(" exception in node " + n.getNodeInformation().getName() + " " + n.getNodeInformation().getName());
1712  
1713   }
1714        return a;
1715    }
1716}
1717
Popular Tags