View Javadoc

1   /**
2    * This file Copyright (c) 2003-2012 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.cms.security;
35  
36  import info.magnolia.cms.core.Path;
37  import info.magnolia.cms.core.SystemProperty;
38  import info.magnolia.cms.exchange.ActivationManager;
39  import info.magnolia.context.MgnlContext;
40  import info.magnolia.objectfactory.Components;
41  
42  import java.io.File;
43  import java.io.FileInputStream;
44  import java.io.FileNotFoundException;
45  import java.io.FileWriter;
46  import java.io.IOException;
47  import java.security.InvalidKeyException;
48  import java.security.KeyFactory;
49  import java.security.KeyPair;
50  import java.security.KeyPairGenerator;
51  import java.security.MessageDigest;
52  import java.security.NoSuchAlgorithmException;
53  import java.security.NoSuchProviderException;
54  import java.security.PrivateKey;
55  import java.security.PublicKey;
56  import java.security.Security;
57  import java.security.spec.InvalidKeySpecException;
58  import java.security.spec.PKCS8EncodedKeySpec;
59  import java.security.spec.X509EncodedKeySpec;
60  import java.text.SimpleDateFormat;
61  import java.util.Date;
62  import java.util.Properties;
63  
64  import javax.crypto.BadPaddingException;
65  import javax.crypto.Cipher;
66  import javax.crypto.IllegalBlockSizeException;
67  import javax.crypto.NoSuchPaddingException;
68  import javax.jcr.RepositoryException;
69  import javax.jcr.Session;
70  
71  import org.apache.commons.lang.StringUtils;
72  import org.bouncycastle.jce.provider.BouncyCastleProvider;
73  import org.mindrot.jbcrypt.BCrypt;
74  
75  /**
76   * Utility functions required in the context of Security.
77   *
78   * @version $Id$
79   */
80  public class SecurityUtil {
81  
82      private static final String PRIVATE_KEY = "key.private";
83      private static final String PUBLIC_KEY = "key.public";
84      private static final String KEY_LOCATION_PROPERTY = "magnolia.author.key.location";
85      
86      
87      public static final String SHA1 = "SHA-1"; //$NON-NLS-1$
88      public static final String MD5 = "MD5"; //$NON-NLS-1$
89      
90      /**
91       * There are five (5) FIPS-approved* algorithms for generating a condensed representation of a message (message
92       * digest): SHA-1, SHA-224, SHA-256,SHA-384, and SHA-512. <strong>Not supported yet</strong>
93       */
94      public static final String SHA256 = "SHA-256"; //$NON-NLS-1$
95      public static final String SHA384 = "SHA-384"; //$NON-NLS-1$
96      public static final String SHA512 = "SHA-512"; //$NON-NLS-1$
97  
98      /**
99       * Encryption algorithm used ... if you are ever changing this, keep in mind underlying impl relies on padding!
100      */
101 
102     private static final String ALGORITHM = "RSA";
103 
104     static {
105         Security.addProvider(new BouncyCastleProvider());
106     }
107 
108     /**
109      * Checks if the currently acting user is anonymous.
110      */
111     public static boolean isAnonymous() {
112         User user = MgnlContext.getUser();
113         return (user != null && UserManager.ANONYMOUS_USER.equals(user.getName()));
114     }
115 
116     public static boolean isAuthenticated() {
117         User user = MgnlContext.getUser();
118         return (user != null && !UserManager.ANONYMOUS_USER.equals(user.getName()));
119     }
120 
121     public static String decrypt(String pass) throws SecurityException {
122         return decrypt(pass, getPublicKey());
123     }
124 
125     public static String decrypt(String message, String encodedKey) throws SecurityException {
126         try {
127             if (StringUtils.isBlank(encodedKey)) {
128                 throw new SecurityException("Activation key was not found. Please make sure your instance is correctly configured.");
129             }
130 
131             // decode key
132             byte[] binaryKey = hexToByteArray(encodedKey);
133 
134             // create RSA public key cipher
135             Cipher pkCipher = Cipher.getInstance(ALGORITHM, "BC");
136             try {
137                 // create private key
138                 X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binaryKey);
139                 KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
140                 PublicKey pk = kf.generatePublic(publicKeySpec);
141                 pkCipher.init(Cipher.DECRYPT_MODE, pk);
142 
143             } catch (InvalidKeySpecException e) {
144                 // decrypting with private key?
145                 PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binaryKey);
146                 KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
147                 PrivateKey pk = kf.generatePrivate(privateKeySpec);
148                 pkCipher.init(Cipher.DECRYPT_MODE, pk);
149             }
150 
151             // decrypt
152             String[] chunks = StringUtils.split(message, ";");
153             if (chunks == null) {
154                 throw new SecurityException("The encrypted information is corrupted or incomplete. Please make sure someone is not trying to intercept or modify encrypted message.");
155             }
156             StringBuilder clearText = new StringBuilder();
157             for (String chunk : chunks) {
158                 byte[] byteChunk = hexToByteArray(chunk);
159                 clearText.append(new String(pkCipher.doFinal(byteChunk), "UTF-8"));
160             }
161             return clearText.toString();
162         } catch (NumberFormatException e) {
163             throw new SecurityException("The encrypted information is corrupted or incomplete. Please make sure someone is not trying to intercept or modify encrypted message.", e);
164         } catch (IOException e) {
165             throw new SecurityException("Failed to read authentication string. Please use Java version with cryptography support.", e);
166         } catch (NoSuchAlgorithmException e) {
167             throw new SecurityException("Failed to read authentication string. Please use Java version with cryptography support.", e);
168         } catch (NoSuchPaddingException e) {
169             throw new SecurityException("Failed to read authentication string. Please use Java version with cryptography support.", e);
170         } catch (InvalidKeySpecException e) {
171             throw new SecurityException("Failed to read authentication string. Please use Java version with cryptography support.", e);
172         } catch (InvalidKeyException e) {
173             throw new SecurityException("Failed to read authentication string. Please use Java version with cryptography support.", e);
174         } catch (NoSuchProviderException e) {
175             throw new SecurityException("Failed to find encryption provider. Please use Java version with cryptography support.", e);
176         } catch (IllegalBlockSizeException e) {
177             throw new SecurityException("Failed to decrypt message. It might have been corrupted during transport.", e);
178         } catch (BadPaddingException e) {
179             throw new SecurityException("Failed to decrypt message. It might have been corrupted during transport.", e);
180         }
181 
182     }
183 
184     public static String encrypt(String pass) throws SecurityException {
185         String encodedKey = getPrivateKey();
186         return encrypt(pass, encodedKey);
187     }
188 
189     public static String encrypt(String message, String encodedKey) {
190         try {
191 
192             // read private key
193             if (StringUtils.isBlank(encodedKey)) {
194                 throw new SecurityException("Activation key was not found. Please make sure your instance is correctly configured.");
195             }
196             byte[] binaryKey = hexToByteArray(encodedKey);
197 
198             // create RSA public key cipher
199             Cipher pkCipher = Cipher.getInstance(ALGORITHM, "BC");
200             try {
201                 // create private key
202                 PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binaryKey);
203                 KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
204                 PrivateKey pk = kf.generatePrivate(privateKeySpec);
205 
206                 pkCipher.init(Cipher.ENCRYPT_MODE, pk);
207             } catch (InvalidKeySpecException e) {
208                 // encrypting with public key?
209                 X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binaryKey);
210                 KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
211                 PublicKey pk = kf.generatePublic(publicKeySpec);
212 
213                 pkCipher.init(Cipher.ENCRYPT_MODE, pk);
214             }
215 
216             // encrypt
217             byte[] bytes = message.getBytes("UTF-8");
218             // split bit message in chunks
219             int start = 0;
220             StringBuilder chaos = new StringBuilder();
221             while (start < bytes.length) {
222                 byte[] tmp = new byte[Math.min(bytes.length - start, binaryKey.length / 8)];
223                 System.arraycopy(bytes, start, tmp, 0, tmp.length);
224                 start += tmp.length;
225                 byte[] encrypted = pkCipher.doFinal(tmp);
226                 chaos.append(byteArrayToHex(encrypted));
227                 chaos.append(";");
228             }
229             chaos.setLength(chaos.length() - 1);
230 
231             return chaos.toString();
232 
233         } catch (IOException e) {
234             throw new SecurityException("Failed to create authentication string. Please use Java version with cryptography support.", e);
235         } catch (NoSuchAlgorithmException e) {
236             throw new SecurityException("Failed to create authentication string. Please use Java version with cryptography support.", e);
237         } catch (NoSuchPaddingException e) {
238             throw new SecurityException("Failed to create authentication string. Please use Java version with cryptography support.", e);
239         } catch (InvalidKeySpecException e) {
240             throw new SecurityException("Failed to create authentication string. Please use Java version with cryptography support.", e);
241         } catch (InvalidKeyException e) {
242             throw new SecurityException("Failed to create authentication string. Please use Java version with cryptography support.", e);
243         } catch (NoSuchProviderException e) {
244             throw new SecurityException("Failed to find encryption provider. Please use Java version with cryptography support.", e);
245         } catch (IllegalBlockSizeException e) {
246             throw new SecurityException("Failed to encrypt string. Please use Java version with cryptography support.", e);
247         } catch (BadPaddingException e) {
248             throw new SecurityException("Failed to encrypt string. Please use Java version with cryptography support.", e);
249         }
250     }
251 
252 
253     public static String getPrivateKey() {
254         String path = SystemProperty.getProperty(KEY_LOCATION_PROPERTY);
255         checkPrivateKeyStoreExistence(path);
256         try {
257             Properties defaultProps = new Properties();
258             FileInputStream in = new FileInputStream(path);
259             defaultProps.load(in);
260             in.close();
261             return defaultProps.getProperty(PRIVATE_KEY);
262         } catch (FileNotFoundException e) {
263             throw new SecurityException("Failed to retrieve private key. Please make sure the key is located in " + path, e);
264         } catch (IOException e) {
265             throw new SecurityException("Failed to retrieve private key. Please make sure the key is located in " + path, e);
266         }
267     }
268 
269     public static void updateKeys(MgnlKeyPair keys) {
270         // update filestore only when private key is present
271         if (keys.getPrivateKey() != null) {
272             String path = SystemProperty.getProperty(KEY_LOCATION_PROPERTY);
273             try {
274                 Properties defaultProps = new Properties();
275                 defaultProps.put(PRIVATE_KEY, keys.getPrivateKey());
276                 defaultProps.put(PUBLIC_KEY, keys.getPublicKey());
277                 File keystore = new File(path);
278                 keystore.getParentFile().mkdirs();
279                 FileWriter writer = new FileWriter(keystore);
280                 String date = new SimpleDateFormat("dd.MMM.yyyy hh:mm").format(new Date());
281                 defaultProps.store(writer, "generated " + date + " by " + MgnlContext.getUser().getName());
282                 writer.close();
283             } catch (FileNotFoundException e) {
284                 throw new SecurityException("Failed to store private key. Please make sure the key is located in " + path, e);
285             } catch (IOException e) {
286                 throw new SecurityException("Failed to store private key. Please make sure the key is located in " + path, e);
287             }
288         }
289         try {
290             Session session = MgnlContext.getSystemContext().getJCRSession("config");
291             session.getNode("/server/activation").setProperty("publicKey", keys.getPublicKey());
292             session.save();
293         } catch (RepositoryException e) {
294             throw new SecurityException("Failed to store public key.", e);
295         }
296     }
297 
298     public static String getPublicKey() {
299         ActivationManager aman = Components.getComponentProvider().getComponent(ActivationManager.class);
300         return aman.getPublicKey();
301     }
302 
303     private static final String HEX = "0123456789ABCDEF";
304 
305     public static String byteArrayToHex(byte[] raw) {
306         if (raw == null) {
307             return null;
308         }
309         final StringBuilder hex = new StringBuilder(2 * raw.length);
310         for (final byte b : raw) {
311             hex.append(HEX.charAt((b & 0xF0) >> 4))
312             .append(HEX.charAt((b & 0x0F)));
313         }
314         return hex.toString();
315     }
316 
317     public static byte[] hexToByteArray(String s) {
318         byte[] b = new byte[s.length() / 2];
319         for (int i = 0; i < b.length; i++) {
320             int index = i * 2;
321             int v = Integer.parseInt(s.substring(index, index + 2), 16);
322             b[i] = (byte) v;
323         }
324         return b;
325     }
326 
327     public static MgnlKeyPair generateKeyPair(int keyLength) throws NoSuchAlgorithmException {
328         KeyPairGenerator kgen = KeyPairGenerator.getInstance(ALGORITHM);
329         kgen.initialize(keyLength);
330         KeyPair key = kgen.genKeyPair();
331         return new MgnlKeyPair(byteArrayToHex(key.getPrivate().getEncoded()), byteArrayToHex(key.getPublic().getEncoded()));
332     }
333 
334     /**
335      * Used for removing password parameter from cache key.
336      * @param cacheKey.toString()
337      * @return
338      */
339     public static String stripPasswordFromCacheLog(String log){
340         String value = stripParameterFromCacheLog(log, "mgnlUserPSWD");
341         value = stripParameterFromCacheLog(value, "passwordConfirmation");
342         value = stripParameterFromCacheLog(value, "password");
343         return value;
344     }
345 
346     public static String stripPasswordFromUrl(String url){
347         if(StringUtils.isBlank(url)){
348             return null;
349         }
350         String value = null;
351         value = StringUtils.substringBefore(url, "mgnlUserPSWD");
352         value = value + StringUtils.substringAfter(StringUtils.substringAfter(url, "mgnlUserPSWD"), "&");
353         return StringUtils.removeEnd(value, "&");
354     }
355 
356     public static String stripParameterFromCacheLog(String log, String parameter){
357         if(StringUtils.isBlank(log)){
358             return null;
359         }else if(!StringUtils.contains(log, parameter)){
360             return log;
361         }
362         String value = null;
363         value = StringUtils.substringBefore(log, parameter);
364         String afterString = StringUtils.substringAfter(log, parameter);
365         if(StringUtils.indexOf(afterString, " ") < StringUtils.indexOf(afterString, "}")){
366             value = value + StringUtils.substringAfter(afterString, " ");
367         }else{
368             value = value + "}" + StringUtils.substringAfter(afterString, "}");
369         }
370         return value;
371     }
372 
373 
374     private static void checkPrivateKeyStoreExistence(final String path) throws SecurityException {
375         if(StringUtils.isBlank(path)) {
376             throw new SecurityException("Private key store path is either null or empty. Please, check [" + KEY_LOCATION_PROPERTY + "] value in magnolia.properties");
377         }
378         String absPath = Path.getAbsoluteFileSystemPath(path);
379         File keypair = new File(absPath);
380         if(!keypair.exists()) {
381             throw new SecurityException("Private key store doesn't exist at [" + keypair.getAbsolutePath() + "]. Please, ensure that [" + KEY_LOCATION_PROPERTY + "] actually points to the correct location");
382         }
383     }
384     
385     public static String getBCrypt(String text) {
386         // gensalt's log_rounds parameter determines the complexity
387         // the work factor is 2^log_rounds, and the default is 10
388         String hashed = BCrypt.hashpw(text, BCrypt.gensalt(12));
389         return hashed;
390     }
391     
392     public static boolean matchBCrypted(String candidate, String hash) {
393         // Check that an unencrypted password matches one that has
394         // previously been hashed
395         return BCrypt.checkpw(candidate, hash);
396     }
397     
398     /**
399      * Message Digesting function.
400      * 
401      */
402     public static String getDigest(String data, String algorithm) throws NoSuchAlgorithmException {
403         MessageDigest md = MessageDigest.getInstance(algorithm);
404         md.reset();
405         return new String(md.digest(data.getBytes()));
406     }
407     
408     /**
409      * Message Digesting function.
410      * 
411      */
412     public static byte[] getDigest(byte[] data, String algorithm) throws NoSuchAlgorithmException {
413         MessageDigest md = MessageDigest.getInstance(algorithm);
414         md.reset();
415         return md.digest(data);
416     }
417     
418     /**
419      * Gets SHA-1 encoded -> hex string.
420      */
421     public static String getSHA1Hex(byte[] data) {
422         try {
423             return byteArrayToHex(getDigest(data, SecurityUtil.SHA1));
424         }
425         catch (NoSuchAlgorithmException e) {
426             throw new SecurityException("Couldn't digest with " + SecurityUtil.SHA1 + " algorithm!");
427         }
428     }
429     
430     public static String getSHA1Hex(String data) {
431         return getSHA1Hex(data.getBytes());
432     }
433      
434     /**
435      * Gets MD5 encoded -> hex string.
436      */
437     public static String getMD5Hex(byte[] data) {
438         try {
439             return byteArrayToHex(getDigest(data, SecurityUtil.MD5));
440         }
441         catch (NoSuchAlgorithmException e) {
442             throw new SecurityException("Couldn't digest with " + SecurityUtil.MD5 + " algorithm!");
443         }
444     }
445     
446     public static String getMD5Hex(String data) {
447         return getMD5Hex(data.getBytes());
448     }
449 }