]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.security.core/src/org/argeo/security/jcr/JcrKeyring.java
Use standard JAAS login context for RAP login
[lgpl/argeo-commons.git] / org.argeo.security.core / src / org / argeo / security / jcr / JcrKeyring.java
1 /*
2 * Copyright (C) 2007-2012 Argeo GmbH
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.argeo.security.jcr;
17
18 import java.io.ByteArrayInputStream;
19 import java.io.CharArrayReader;
20 import java.io.InputStream;
21 import java.io.Reader;
22 import java.security.SecureRandom;
23
24 import javax.crypto.Cipher;
25 import javax.crypto.CipherInputStream;
26 import javax.crypto.SecretKey;
27 import javax.crypto.spec.IvParameterSpec;
28 import javax.jcr.Binary;
29 import javax.jcr.Node;
30 import javax.jcr.Property;
31 import javax.jcr.RepositoryException;
32 import javax.jcr.Session;
33
34 import org.apache.commons.io.IOUtils;
35 import org.argeo.ArgeoException;
36 import org.argeo.jcr.ArgeoNames;
37 import org.argeo.jcr.ArgeoTypes;
38 import org.argeo.jcr.JcrUtils;
39 import org.argeo.jcr.UserJcrUtils;
40 import org.argeo.security.crypto.AbstractKeyring;
41 import org.argeo.security.crypto.PBEKeySpecCallback;
42
43 /** JCR based implementation of a keyring */
44 public class JcrKeyring extends AbstractKeyring implements ArgeoNames {
45 /**
46 * Stronger with 256, but causes problem with Oracle JVM, force 128 in this
47 * case
48 */
49 public final static Long DEFAULT_SECRETE_KEY_LENGTH = 256l;
50 public final static String DEFAULT_SECRETE_KEY_FACTORY = "PBKDF2WithHmacSHA1";
51 public final static String DEFAULT_SECRETE_KEY_ENCRYPTION = "AES";
52 public final static String DEFAULT_CIPHER_NAME = "AES/CBC/PKCS5Padding";
53
54 private Integer iterationCountFactor = 200;
55 private Long secreteKeyLength = DEFAULT_SECRETE_KEY_LENGTH;
56 private String secreteKeyFactoryName = DEFAULT_SECRETE_KEY_FACTORY;
57 private String secreteKeyEncryption = DEFAULT_SECRETE_KEY_ENCRYPTION;
58 private String cipherName = DEFAULT_CIPHER_NAME;
59
60 private Session session;
61
62 /**
63 * When setup is called the session has not yet been saved and we don't want
64 * to save it since there maybe other data which would be inconsistent. So
65 * we keep a reference to this node which will then be used (an reset to
66 * null) when handling the PBE callback. We keep one per thread in case
67 * multiple users are accessing the same instance of a keyring.
68 */
69 private ThreadLocal<Node> notYetSavedKeyring = new ThreadLocal<Node>() {
70
71 @Override
72 protected Node initialValue() {
73 return null;
74 }
75 };
76
77 @Override
78 protected Boolean isSetup() {
79 try {
80 if (notYetSavedKeyring.get() != null)
81 return true;
82
83 Node userHome = UserJcrUtils.getUserHome(session);
84 return userHome.hasNode(ARGEO_KEYRING);
85 } catch (RepositoryException e) {
86 throw new ArgeoException("Cannot check whether keyring is setup", e);
87 }
88 }
89
90 @Override
91 protected void setup(char[] password) {
92 Binary binary = null;
93 InputStream in = null;
94 try {
95 Node userHome = UserJcrUtils.getUserHome(session);
96 if (userHome.hasNode(ARGEO_KEYRING))
97 throw new ArgeoException("Keyring already setup");
98 Node keyring = userHome.addNode(ARGEO_KEYRING);
99 keyring.addMixin(ArgeoTypes.ARGEO_PBE_SPEC);
100
101 // deterministic salt and iteration count based on username
102 String username = session.getUserID();
103 byte[] salt = new byte[8];
104 byte[] usernameBytes = username.getBytes();
105 for (int i = 0; i < salt.length; i++) {
106 if (i < usernameBytes.length)
107 salt[i] = usernameBytes[i];
108 else
109 salt[i] = 0;
110 }
111 in = new ByteArrayInputStream(salt);
112 binary = session.getValueFactory().createBinary(in);
113 keyring.setProperty(ARGEO_SALT, binary);
114
115 Integer iterationCount = username.length() * iterationCountFactor;
116 keyring.setProperty(ARGEO_ITERATION_COUNT, iterationCount);
117
118 // default algo
119 // TODO check if algo and key length are available, use DES if not
120 keyring.setProperty(ARGEO_SECRET_KEY_FACTORY, secreteKeyFactoryName);
121 keyring.setProperty(ARGEO_KEY_LENGTH, secreteKeyLength);
122 keyring.setProperty(ARGEO_SECRET_KEY_ENCRYPTION,
123 secreteKeyEncryption);
124 keyring.setProperty(ARGEO_CIPHER, cipherName);
125
126 // encrypted password hash
127 // IOUtils.closeQuietly(in);
128 // JcrUtils.closeQuietly(binary);
129 // byte[] btPass = hash(password, salt, iterationCount);
130 // in = new ByteArrayInputStream(btPass);
131 // binary = session.getValueFactory().createBinary(in);
132 // keyring.setProperty(ARGEO_PASSWORD, binary);
133
134 notYetSavedKeyring.set(keyring);
135 } catch (Exception e) {
136 throw new ArgeoException("Cannot setup keyring", e);
137 } finally {
138 JcrUtils.closeQuietly(binary);
139 IOUtils.closeQuietly(in);
140 // JcrUtils.discardQuietly(session);
141 }
142 }
143
144 @Override
145 protected void handleKeySpecCallback(PBEKeySpecCallback pbeCallback) {
146 try {
147 Node userHome = UserJcrUtils.getUserHome(session);
148 Node keyring;
149 if (userHome.hasNode(ARGEO_KEYRING))
150 keyring = userHome.getNode(ARGEO_KEYRING);
151 else if (notYetSavedKeyring.get() != null)
152 keyring = notYetSavedKeyring.get();
153 else
154 throw new ArgeoException("Keyring not setup");
155
156 pbeCallback.set(keyring.getProperty(ARGEO_SECRET_KEY_FACTORY)
157 .getString(), JcrUtils.getBinaryAsBytes(keyring
158 .getProperty(ARGEO_SALT)),
159 (int) keyring.getProperty(ARGEO_ITERATION_COUNT).getLong(),
160 (int) keyring.getProperty(ARGEO_KEY_LENGTH).getLong(),
161 keyring.getProperty(ARGEO_SECRET_KEY_ENCRYPTION)
162 .getString());
163
164 if (notYetSavedKeyring.get() != null)
165 notYetSavedKeyring.remove();
166 } catch (RepositoryException e) {
167 throw new ArgeoException("Cannot handle key spec callback", e);
168 }
169 }
170
171 /** The parent node must already exist at this path. */
172 @Override
173 protected synchronized void encrypt(String path, InputStream unencrypted) {
174 // should be called first for lazy initialization
175 SecretKey secretKey = getSecretKey();
176
177 Binary binary = null;
178 InputStream in = null;
179 try {
180 Cipher cipher = createCipher();
181 Node node;
182 if (!session.nodeExists(path)) {
183 String parentPath = JcrUtils.parentPath(path);
184 if (!session.nodeExists(parentPath))
185 throw new ArgeoException("No parent node of " + path);
186 Node parentNode = session.getNode(parentPath);
187 node = parentNode.addNode(JcrUtils.nodeNameFromPath(path));
188 } else {
189 node = session.getNode(path);
190 }
191 node.addMixin(ArgeoTypes.ARGEO_ENCRYPTED);
192 SecureRandom random = new SecureRandom();
193 byte[] iv = new byte[16];
194 random.nextBytes(iv);
195 cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
196 JcrUtils.setBinaryAsBytes(node, ARGEO_IV, iv);
197
198 in = new CipherInputStream(unencrypted, cipher);
199 binary = session.getValueFactory().createBinary(in);
200 node.setProperty(Property.JCR_DATA, binary);
201 session.save();
202 } catch (Exception e) {
203 throw new ArgeoException("Cannot encrypt", e);
204 } finally {
205 IOUtils.closeQuietly(unencrypted);
206 IOUtils.closeQuietly(in);
207 JcrUtils.closeQuietly(binary);
208 }
209 }
210
211 @Override
212 protected synchronized InputStream decrypt(String path) {
213 Binary binary = null;
214 InputStream encrypted = null;
215 Reader reader = null;
216 try {
217 if (!session.nodeExists(path)) {
218 char[] password = ask();
219 reader = new CharArrayReader(password);
220 return new ByteArrayInputStream(IOUtils.toByteArray(reader));
221 } else {
222 // should be called first for lazy initialisation
223 SecretKey secretKey = getSecretKey();
224
225 Cipher cipher = createCipher();
226
227 Node node = session.getNode(path);
228 if (node.hasProperty(ARGEO_IV)) {
229 byte[] iv = JcrUtils.getBinaryAsBytes(node
230 .getProperty(ARGEO_IV));
231 cipher.init(Cipher.DECRYPT_MODE, secretKey,
232 new IvParameterSpec(iv));
233 } else {
234 cipher.init(Cipher.DECRYPT_MODE, secretKey);
235 }
236
237 binary = node.getProperty(Property.JCR_DATA).getBinary();
238 encrypted = binary.getStream();
239 return new CipherInputStream(encrypted, cipher);
240 }
241 } catch (Exception e) {
242 throw new ArgeoException("Cannot decrypt", e);
243 } finally {
244 IOUtils.closeQuietly(encrypted);
245 IOUtils.closeQuietly(reader);
246 JcrUtils.closeQuietly(binary);
247 }
248 }
249
250 protected Cipher createCipher() {
251 try {
252 Node userHome = UserJcrUtils.getUserHome(session);
253 if (!userHome.hasNode(ARGEO_KEYRING))
254 throw new ArgeoException("Keyring not setup");
255 Node keyring = userHome.getNode(ARGEO_KEYRING);
256 Cipher cipher = Cipher.getInstance(keyring
257 .getProperty(ARGEO_CIPHER).getString(),
258 getSecurityProvider());
259 return cipher;
260 } catch (Exception e) {
261 throw new ArgeoException("Cannot get cipher", e);
262 }
263 }
264
265 public synchronized void changePassword(char[] oldPassword,
266 char[] newPassword) {
267 // TODO decrypt with old pw / encrypt with new pw all argeo:encrypted
268 }
269
270 public synchronized void setSession(Session session) {
271 this.session = session;
272 }
273
274 public void setIterationCountFactor(Integer iterationCountFactor) {
275 this.iterationCountFactor = iterationCountFactor;
276 }
277
278 public void setSecreteKeyLength(Long keyLength) {
279 this.secreteKeyLength = keyLength;
280 }
281
282 public void setSecreteKeyFactoryName(String secreteKeyFactoryName) {
283 this.secreteKeyFactoryName = secreteKeyFactoryName;
284 }
285
286 public void setSecreteKeyEncryption(String secreteKeyEncryption) {
287 this.secreteKeyEncryption = secreteKeyEncryption;
288 }
289
290 public void setCipherName(String cipherName) {
291 this.cipherName = cipherName;
292 }
293
294 }