View Javadoc

1   /*
2    * $Id: PGPSecurityFilter.java 22865 2011-09-05 17:23:45Z dfeist $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.module.pgp.filters;
12  
13  import org.mule.api.EncryptionStrategy;
14  import org.mule.api.MuleEvent;
15  import org.mule.api.MuleMessage;
16  import org.mule.api.lifecycle.InitialisationException;
17  import org.mule.api.security.Authentication;
18  import org.mule.api.security.SecurityContext;
19  import org.mule.api.security.SecurityException;
20  import org.mule.api.security.UnauthorisedException;
21  import org.mule.api.security.UnknownAuthenticationTypeException;
22  import org.mule.config.i18n.CoreMessages;
23  import org.mule.module.pgp.LiteralMessage;
24  import org.mule.module.pgp.Message;
25  import org.mule.module.pgp.MessageFactory;
26  import org.mule.module.pgp.PGPAuthentication;
27  import org.mule.module.pgp.PGPCryptInfo;
28  import org.mule.module.pgp.PGPKeyRing;
29  import org.mule.module.pgp.SignedMessage;
30  import org.mule.module.pgp.i18n.PGPMessages;
31  import org.mule.security.AbstractEndpointSecurityFilter;
32  
33  import org.bouncycastle.openpgp.PGPPublicKey;
34  
35  public class PGPSecurityFilter extends AbstractEndpointSecurityFilter
36  {
37      private EncryptionStrategy strategy;
38  
39      private String strategyName;
40  
41      private boolean signRequired;
42  
43      private PGPKeyRing keyManager;
44  
45      @Override
46      protected void authenticateInbound(MuleEvent event)
47          throws SecurityException, UnauthorisedException, UnknownAuthenticationTypeException
48      {
49          MuleMessage message = event.getMessage();
50  
51          String userId = (String)getCredentialsAccessor().getCredentials(event);
52  
53          byte[] creds = null;
54          try
55          {
56              creds = message.getPayloadAsBytes();
57              creds = strategy.decrypt(creds, null);
58          }
59          catch (Exception e1)
60          {
61              throw new UnauthorisedException(CoreMessages.failedToReadPayload(), event, e1);
62          }
63  
64          Authentication authentication;
65          try
66          {
67              authentication = new PGPAuthentication(userId, decodeMsgRaw(creds), event);
68          }
69          catch (Exception e1)
70          {
71              throw new UnauthorisedException(CoreMessages.failedToReadPayload(), event, e1);
72          }
73  
74          final Authentication authResult;
75          try
76          {
77              authResult = getSecurityManager().authenticate(authentication);
78          }
79          catch (Exception e)
80          {
81              // Authentication failed
82              if (logger.isDebugEnabled())
83              {
84                  logger.debug("Authentication request for user: " + userId + " failed: " + e.toString());
85              }
86  
87              throw new UnauthorisedException(CoreMessages.authFailedForUser(userId), event, e);
88          }
89  
90          // Authentication success
91          if (logger.isDebugEnabled())
92          {
93              logger.debug("Authentication success: " + authResult.toString());
94          }
95  
96          SecurityContext context = getSecurityManager().createSecurityContext(authResult);
97          event.getSession().setSecurityContext(context);
98  
99          try
100         {
101             updatePayload(message, getUnencryptedMessageWithoutSignature((PGPAuthentication)authResult), event);
102 //            TODO RequestContext.rewriteEvent(new DefaultMuleMessage(
103 //                getUnencryptedMessageWithoutSignature((PGPAuthentication)authResult)));
104         }
105         catch (Exception e2)
106         {
107             throw new UnauthorisedException(event, context, this);
108         }
109     }
110 
111     private Message decodeMsgRaw(byte[] raw) throws Exception
112     {
113         return MessageFactory.getMessage(raw);
114     }
115 
116     private String getUnencryptedMessageWithoutSignature(PGPAuthentication auth) throws Exception
117     {
118         Message msg = (Message)auth.getCredentials();
119 
120         if (msg instanceof SignedMessage)
121         {
122             msg = ((SignedMessage)msg).getContents();
123         }
124 
125         if (msg instanceof LiteralMessage)
126         {
127             return ((LiteralMessage)msg).getTextData();
128         }
129         else
130         {
131             throw new Exception("Wrong data");
132         }
133     }
134 
135     @Override
136     protected void authenticateOutbound(MuleEvent event) throws SecurityException, UnauthorisedException
137     {
138         logger.debug("authenticateOutbound:" + event.getId());
139 
140         if (!isAuthenticate())
141         {
142             return;
143         }
144 
145         MuleMessage message = event.getMessage();
146 
147         PGPPublicKey userKeyBundle = keyManager.getPublicKey((String)getCredentialsAccessor().getCredentials(
148             event));
149 
150         final PGPCryptInfo cryptInfo = new PGPCryptInfo(userKeyBundle, signRequired);
151 
152         try
153         {
154             updatePayload(event.getMessage(), strategy.encrypt(message.getPayloadAsBytes(), cryptInfo), event);
155         }
156         catch (Exception e1)
157         {
158             throw new UnauthorisedException(CoreMessages.failedToReadPayload(), event, e1);
159         }
160     }
161 
162     @Override
163     protected void doInitialise() throws InitialisationException
164     {
165         if (strategyName != null)
166         {
167             strategy = muleContext.getSecurityManager().getEncryptionStrategy(strategyName);
168         }
169 
170         if (strategy == null)
171         {
172             throw new InitialisationException(PGPMessages.encryptionStrategyNotSet(), this);
173         }
174     }
175 
176     public EncryptionStrategy getStrategy()
177     {
178         return strategy;
179     }
180 
181     public void setStrategy(EncryptionStrategy strategy)
182     {
183         this.strategy = strategy;
184     }
185 
186     public void setStrategyName(String name)
187     {
188         strategyName = name;
189     }
190 
191     public boolean isSignRequired()
192     {
193         return signRequired;
194     }
195 
196     public void setSignRequired(boolean signRequired)
197     {
198         this.signRequired = signRequired;
199     }
200 
201     public PGPKeyRing getKeyManager()
202     {
203         return keyManager;
204     }
205 
206     public void setKeyManager(PGPKeyRing keyManager)
207     {
208         this.keyManager = keyManager;
209     }
210 }