]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.server.jcr/src/org/argeo/jcr/security/JcrKeyring.java
b43c5d6c60e49d12ed5ab44786b2d7cc5255d743
[lgpl/argeo-commons.git] / org.argeo.server.jcr / src / org / argeo / jcr / security / 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.jcr.security;
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.jcr.ArgeoJcrException;
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.util.security.AbstractKeyring;
41 import org.argeo.util.security.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 ArgeoJcrException("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 ArgeoJcrException("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 //keyring.getSession().save();
127
128 // encrypted password hash
129 // IOUtils.closeQuietly(in);
130 // JcrUtils.closeQuietly(binary);
131 // byte[] btPass = hash(password, salt, iterationCount);
132 // in = new ByteArrayInputStream(btPass);
133 // binary = session.getValueFactory().createBinary(in);
134 // keyring.setProperty(ARGEO_PASSWORD, binary);
135
136 notYetSavedKeyring.set(keyring);
137 } catch (Exception e) {
138 throw new ArgeoJcrException("Cannot setup keyring", e);
139 } finally {
140 JcrUtils.closeQuietly(binary);
141 IOUtils.closeQuietly(in);
142 // JcrUtils.discardQuietly(session);
143 }
144 }
145
146 @Override
147 protected void handleKeySpecCallback(PBEKeySpecCallback pbeCallback) {
148 try {
149 Node userHome = UserJcrUtils.getUserHome(session);
150 Node keyring;
151 if (userHome.hasNode(ARGEO_KEYRING))
152 keyring = userHome.getNode(ARGEO_KEYRING);
153 else if (notYetSavedKeyring.get() != null)
154 keyring = notYetSavedKeyring.get();
155 else
156 throw new ArgeoJcrException("Keyring not setup");
157
158 pbeCallback.set(keyring.getProperty(ARGEO_SECRET_KEY_FACTORY)
159 .getString(), JcrUtils.getBinaryAsBytes(keyring
160 .getProperty(ARGEO_SALT)),
161 (int) keyring.getProperty(ARGEO_ITERATION_COUNT).getLong(),
162 (int) keyring.getProperty(ARGEO_KEY_LENGTH).getLong(),
163 keyring.getProperty(ARGEO_SECRET_KEY_ENCRYPTION)
164 .getString());
165
166 if (notYetSavedKeyring.get() != null)
167 notYetSavedKeyring.remove();
168 } catch (RepositoryException e) {
169 throw new ArgeoJcrException("Cannot handle key spec callback", e);
170 }
171 }
172
173 /** The parent node must already exist at this path. */
174 @Override
175 protected synchronized void encrypt(String path, InputStream unencrypted) {
176 // should be called first for lazy initialization
177 SecretKey secretKey = getSecretKey();
178
179 Binary binary = null;
180 InputStream in = null;
181 try {
182 Cipher cipher = createCipher();
183 Node node;
184 if (!session.nodeExists(path)) {
185 String parentPath = JcrUtils.parentPath(path);
186 if (!session.nodeExists(parentPath))
187 throw new ArgeoJcrException("No parent node of " + path);
188 Node parentNode = session.getNode(parentPath);
189 node = parentNode.addNode(JcrUtils.nodeNameFromPath(path));
190 } else {
191 node = session.getNode(path);
192 }
193 node.addMixin(ArgeoTypes.ARGEO_ENCRYPTED);
194 SecureRandom random = new SecureRandom();
195 byte[] iv = new byte[16];
196 random.nextBytes(iv);
197 cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
198 JcrUtils.setBinaryAsBytes(node, ARGEO_IV, iv);
199
200 in = new CipherInputStream(unencrypted, cipher);
201 binary = session.getValueFactory().createBinary(in);
202 node.setProperty(Property.JCR_DATA, binary);
203 session.save();
204 } catch (Exception e) {
205 throw new ArgeoJcrException("Cannot encrypt", e);
206 } finally {
207 IOUtils.closeQuietly(unencrypted);
208 IOUtils.closeQuietly(in);
209 JcrUtils.closeQuietly(binary);
210 }
211 }
212
213 @Override
214 protected synchronized InputStream decrypt(String path) {
215 Binary binary = null;
216 InputStream encrypted = null;
217 Reader reader = null;
218 try {
219 if (!session.nodeExists(path)) {
220 char[] password = ask();
221 reader = new CharArrayReader(password);
222 return new ByteArrayInputStream(IOUtils.toByteArray(reader));
223 } else {
224 // should be called first for lazy initialisation
225 SecretKey secretKey = getSecretKey();
226
227 Cipher cipher = createCipher();
228
229 Node node = session.getNode(path);
230 if (node.hasProperty(ARGEO_IV)) {
231 byte[] iv = JcrUtils.getBinaryAsBytes(node
232 .getProperty(ARGEO_IV));
233 cipher.init(Cipher.DECRYPT_MODE, secretKey,
234 new IvParameterSpec(iv));
235 } else {
236 cipher.init(Cipher.DECRYPT_MODE, secretKey);
237 }
238
239 binary = node.getProperty(Property.JCR_DATA).getBinary();
240 encrypted = binary.getStream();
241 return new CipherInputStream(encrypted, cipher);
242 }
243 } catch (Exception e) {
244 throw new ArgeoJcrException("Cannot decrypt", e);
245 } finally {
246 IOUtils.closeQuietly(encrypted);
247 IOUtils.closeQuietly(reader);
248 JcrUtils.closeQuietly(binary);
249 }
250 }
251
252 protected Cipher createCipher() {
253 try {
254 Node userHome = UserJcrUtils.getUserHome(session);
255 if (!userHome.hasNode(ARGEO_KEYRING))
256 throw new ArgeoJcrException("Keyring not setup");
257 Node keyring = userHome.getNode(ARGEO_KEYRING);
258 Cipher cipher = Cipher.getInstance(keyring
259 .getProperty(ARGEO_CIPHER).getString(),
260 getSecurityProvider());
261 return cipher;
262 } catch (Exception e) {
263 throw new ArgeoJcrException("Cannot get cipher", e);
264 }
265 }
266
267 public synchronized void changePassword(char[] oldPassword,
268 char[] newPassword) {
269 // TODO decrypt with old pw / encrypt with new pw all argeo:encrypted
270 }
271
272 public synchronized void setSession(Session session) {
273 this.session = session;
274 }
275
276 public void setIterationCountFactor(Integer iterationCountFactor) {
277 this.iterationCountFactor = iterationCountFactor;
278 }
279
280 public void setSecreteKeyLength(Long keyLength) {
281 this.secreteKeyLength = keyLength;
282 }
283
284 public void setSecreteKeyFactoryName(String secreteKeyFactoryName) {
285 this.secreteKeyFactoryName = secreteKeyFactoryName;
286 }
287
288 public void setSecreteKeyEncryption(String secreteKeyEncryption) {
289 this.secreteKeyEncryption = secreteKeyEncryption;
290 }
291
292 public void setCipherName(String cipherName) {
293 this.cipherName = cipherName;
294 }
295
296 }