]> git.argeo.org Git - lgpl/argeo-commons.git/blob - InitUtils.java
98b625a98e4effc29da792ee8a09aff591e71236
[lgpl/argeo-commons.git] / InitUtils.java
1 package org.argeo.cms.internal.kernel;
2
3 import static org.argeo.cms.internal.kernel.KernelUtils.getFrameworkProp;
4
5 import java.io.File;
6 import java.io.FileFilter;
7 import java.io.IOException;
8 import java.io.Reader;
9 import java.net.InetAddress;
10 import java.net.URI;
11 import java.nio.charset.StandardCharsets;
12 import java.nio.file.Files;
13 import java.nio.file.Path;
14 import java.security.KeyStore;
15 import java.util.ArrayList;
16 import java.util.Arrays;
17 import java.util.Dictionary;
18 import java.util.Hashtable;
19 import java.util.List;
20
21 import javax.security.auth.x500.X500Principal;
22
23 import org.apache.commons.io.FileUtils;
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26 import org.argeo.api.NodeConstants;
27 import org.argeo.cms.internal.http.InternalHttpConstants;
28 import org.argeo.osgi.useradmin.UserAdminConf;
29
30 /**
31 * Interprets framework properties in order to generate the initial deploy
32 * configuration.
33 */
34 class InitUtils {
35 private final static Log log = LogFactory.getLog(InitUtils.class);
36
37
38 /** Override the provided config with the framework properties */
39 static Dictionary<String, Object> getHttpServerConfig(Dictionary<String, Object> provided) {
40 String httpPort = getFrameworkProp("org.osgi.service.http.port");
41 String httpsPort = getFrameworkProp("org.osgi.service.http.port.secure");
42 /// TODO make it more generic
43 String httpHost = getFrameworkProp(
44 InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.HTTP_HOST);
45 String httpsHost = getFrameworkProp(
46 InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.HTTPS_HOST);
47 String webSocketEnabled = getFrameworkProp(
48 InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.WEBSOCKET_ENABLED);
49
50 final Hashtable<String, Object> props = new Hashtable<String, Object>();
51 // try {
52 if (httpPort != null || httpsPort != null) {
53 boolean httpEnabled = httpPort != null;
54 props.put(InternalHttpConstants.HTTP_ENABLED, httpEnabled);
55 boolean httpsEnabled = httpsPort != null;
56 props.put(InternalHttpConstants.HTTPS_ENABLED, httpsEnabled);
57
58 if (httpEnabled) {
59 props.put(InternalHttpConstants.HTTP_PORT, httpPort);
60 if (httpHost != null)
61 props.put(InternalHttpConstants.HTTP_HOST, httpHost);
62 }
63
64 if (httpsEnabled) {
65 props.put(InternalHttpConstants.HTTPS_PORT, httpsPort);
66 if (httpsHost != null)
67 props.put(InternalHttpConstants.HTTPS_HOST, httpsHost);
68
69 // server certificate
70 Path keyStorePath = KernelUtils.getOsgiInstancePath(KernelConstants.DEFAULT_KEYSTORE_PATH);
71 Path pemKeyPath = KernelUtils.getOsgiInstancePath(KernelConstants.DEFAULT_PEM_KEY_PATH);
72 Path pemCertPath = KernelUtils.getOsgiInstancePath(KernelConstants.DEFAULT_PEM_CERT_PATH);
73 String keyStorePasswordStr = getFrameworkProp(
74 InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.SSL_PASSWORD);
75 char[] keyStorePassword;
76 if (keyStorePasswordStr == null)
77 keyStorePassword = "changeit".toCharArray();
78 else
79 keyStorePassword = keyStorePasswordStr.toCharArray();
80
81 // if PEM files both exists, update the PKCS12 file
82 if (Files.exists(pemCertPath) && Files.exists(pemKeyPath)) {
83 // TODO check certificate update time? monitor changes?
84 KeyStore keyStore = PkiUtils.getKeyStore(keyStorePath, keyStorePassword, PkiUtils.PKCS12);
85 try (Reader key = Files.newBufferedReader(pemKeyPath, StandardCharsets.US_ASCII);
86 Reader cert = Files.newBufferedReader(pemCertPath, StandardCharsets.US_ASCII);) {
87 PkiUtils.loadPem(keyStore, key, keyStorePassword, cert);
88 PkiUtils.saveKeyStore(keyStorePath, keyStorePassword, keyStore);
89 if (log.isDebugEnabled())
90 log.debug("PEM certificate stored in " + keyStorePath);
91 } catch (IOException e) {
92 log.error("Cannot read PEM files " + pemKeyPath + " and " + pemCertPath, e);
93 }
94 }
95
96 if (!Files.exists(keyStorePath))
97 createSelfSignedKeyStore(keyStorePath, keyStorePassword, PkiUtils.PKCS12);
98 props.put(InternalHttpConstants.SSL_KEYSTORETYPE, PkiUtils.PKCS12);
99 props.put(InternalHttpConstants.SSL_KEYSTORE, keyStorePath.toString());
100 props.put(InternalHttpConstants.SSL_PASSWORD, new String(keyStorePassword));
101
102 // props.put(InternalHttpConstants.SSL_KEYSTORETYPE, "PKCS11");
103 // props.put(InternalHttpConstants.SSL_KEYSTORE, "../../nssdb");
104 // props.put(InternalHttpConstants.SSL_PASSWORD, keyStorePassword);
105
106 // client certificate authentication
107 String wantClientAuth = getFrameworkProp(
108 InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.SSL_WANTCLIENTAUTH);
109 if (wantClientAuth != null)
110 props.put(InternalHttpConstants.SSL_WANTCLIENTAUTH, Boolean.parseBoolean(wantClientAuth));
111 String needClientAuth = getFrameworkProp(
112 InternalHttpConstants.JETTY_PROPERTY_PREFIX + InternalHttpConstants.SSL_NEEDCLIENTAUTH);
113 if (needClientAuth != null)
114 props.put(InternalHttpConstants.SSL_NEEDCLIENTAUTH, Boolean.parseBoolean(needClientAuth));
115 }
116
117 // web socket
118 if (webSocketEnabled != null && webSocketEnabled.equals("true"))
119 props.put(InternalHttpConstants.WEBSOCKET_ENABLED, true);
120
121 props.put(NodeConstants.CN, NodeConstants.DEFAULT);
122 }
123 return props;
124 }
125
126 static List<Dictionary<String, Object>> getUserDirectoryConfigs() {
127 List<Dictionary<String, Object>> res = new ArrayList<>();
128 File nodeBaseDir = KernelUtils.getOsgiInstancePath(KernelConstants.DIR_NODE).toFile();
129 List<String> uris = new ArrayList<>();
130
131 // node roles
132 String nodeRolesUri = getFrameworkProp(NodeConstants.ROLES_URI);
133 String baseNodeRoleDn = NodeConstants.ROLES_BASEDN;
134 if (nodeRolesUri == null) {
135 nodeRolesUri = baseNodeRoleDn + ".ldif";
136 File nodeRolesFile = new File(nodeBaseDir, nodeRolesUri);
137 if (!nodeRolesFile.exists())
138 try {
139 FileUtils.copyInputStreamToFile(InitUtils.class.getResourceAsStream(baseNodeRoleDn + ".ldif"),
140 nodeRolesFile);
141 } catch (IOException e) {
142 throw new RuntimeException("Cannot copy demo resource", e);
143 }
144 // nodeRolesUri = nodeRolesFile.toURI().toString();
145 }
146 uris.add(nodeRolesUri);
147
148 // node tokens
149 String nodeTokensUri = getFrameworkProp(NodeConstants.TOKENS_URI);
150 String baseNodeTokensDn = NodeConstants.TOKENS_BASEDN;
151 if (nodeTokensUri == null) {
152 nodeTokensUri = baseNodeTokensDn + ".ldif";
153 File nodeTokensFile = new File(nodeBaseDir, nodeTokensUri);
154 if (!nodeTokensFile.exists())
155 try {
156 FileUtils.copyInputStreamToFile(InitUtils.class.getResourceAsStream(baseNodeTokensDn + ".ldif"),
157 nodeTokensFile);
158 } catch (IOException e) {
159 throw new RuntimeException("Cannot copy demo resource", e);
160 }
161 // nodeRolesUri = nodeRolesFile.toURI().toString();
162 }
163 uris.add(nodeTokensUri);
164
165 // Business roles
166 String userAdminUris = getFrameworkProp(NodeConstants.USERADMIN_URIS);
167 if (userAdminUris == null) {
168 String demoBaseDn = "dc=example,dc=com";
169 userAdminUris = demoBaseDn + ".ldif";
170 File businessRolesFile = new File(nodeBaseDir, userAdminUris);
171 File systemRolesFile = new File(nodeBaseDir, "ou=roles,ou=node.ldif");
172 if (!businessRolesFile.exists())
173 try {
174 FileUtils.copyInputStreamToFile(InitUtils.class.getResourceAsStream(demoBaseDn + ".ldif"),
175 businessRolesFile);
176 if (!systemRolesFile.exists())
177 FileUtils.copyInputStreamToFile(
178 InitUtils.class.getResourceAsStream("example-ou=roles,ou=node.ldif"), systemRolesFile);
179 } catch (IOException e) {
180 throw new RuntimeException("Cannot copy demo resources", e);
181 }
182 // userAdminUris = businessRolesFile.toURI().toString();
183 log.warn("## DEV Using dummy base DN " + demoBaseDn);
184 // TODO downgrade security level
185 }
186 for (String userAdminUri : userAdminUris.split(" "))
187 uris.add(userAdminUri);
188
189 // Interprets URIs
190 for (String uri : uris) {
191 URI u;
192 try {
193 u = new URI(uri);
194 if (u.getPath() == null)
195 throw new IllegalArgumentException(
196 "URI " + uri + " must have a path in order to determine base DN");
197 if (u.getScheme() == null) {
198 if (uri.startsWith("/") || uri.startsWith("./") || uri.startsWith("../"))
199 u = new File(uri).getCanonicalFile().toURI();
200 else if (!uri.contains("/")) {
201 // u = KernelUtils.getOsgiInstanceUri(KernelConstants.DIR_NODE + '/' + uri);
202 u = new URI(uri);
203 } else
204 throw new IllegalArgumentException("Cannot interpret " + uri + " as an uri");
205 } else if (u.getScheme().equals(UserAdminConf.SCHEME_FILE)) {
206 u = new File(u).getCanonicalFile().toURI();
207 }
208 } catch (Exception e) {
209 throw new RuntimeException("Cannot interpret " + uri + " as an uri", e);
210 }
211 Dictionary<String, Object> properties = UserAdminConf.uriAsProperties(u.toString());
212 res.add(properties);
213 }
214
215 return res;
216 }
217
218 /**
219 * Called before node initialisation, in order populate OSGi instance are with
220 * some files (typically LDIF, etc).
221 */
222 static void prepareFirstInitInstanceArea() {
223 String nodeInits = getFrameworkProp(NodeConstants.NODE_INIT);
224 if (nodeInits == null)
225 nodeInits = "../../init";
226
227 for (String nodeInit : nodeInits.split(",")) {
228
229 if (nodeInit.startsWith("http")) {
230 // TODO reconnect it
231 //registerRemoteInit(nodeInit);
232 } else {
233
234 // TODO use java.nio.file
235 File initDir;
236 if (nodeInit.startsWith("."))
237 initDir = KernelUtils.getExecutionDir(nodeInit);
238 else
239 initDir = new File(nodeInit);
240 // TODO also uncompress archives
241 if (initDir.exists())
242 try {
243 FileUtils.copyDirectory(initDir, KernelUtils.getOsgiInstanceDir(), new FileFilter() {
244
245 @Override
246 public boolean accept(File pathname) {
247 if (pathname.getName().equals(".svn") || pathname.getName().equals(".git"))
248 return false;
249 return true;
250 }
251 });
252 log.info("CMS initialized from " + initDir.getCanonicalPath());
253 } catch (IOException e) {
254 throw new RuntimeException("Cannot initialize from " + initDir, e);
255 }
256 }
257 }
258 }
259
260 private static void createSelfSignedKeyStore(Path keyStorePath, char[] keyStorePassword, String keyStoreType) {
261 // for (Provider provider : Security.getProviders())
262 // System.out.println(provider.getName());
263 // File keyStoreFile = keyStorePath.toFile();
264 char[] keyPwd = Arrays.copyOf(keyStorePassword, keyStorePassword.length);
265 if (!Files.exists(keyStorePath)) {
266 try {
267 Files.createDirectories(keyStorePath.getParent());
268 KeyStore keyStore = PkiUtils.getKeyStore(keyStorePath, keyStorePassword, keyStoreType);
269 PkiUtils.generateSelfSignedCertificate(keyStore,
270 new X500Principal("CN=" + InetAddress.getLocalHost().getHostName() + ",OU=UNSECURE,O=UNSECURE"),
271 1024, keyPwd);
272 PkiUtils.saveKeyStore(keyStorePath, keyStorePassword, keyStore);
273 if (log.isDebugEnabled())
274 log.debug("Created self-signed unsecure keystore " + keyStorePath);
275 } catch (Exception e) {
276 try {
277 if (Files.size(keyStorePath) == 0)
278 Files.delete(keyStorePath);
279 } catch (IOException e1) {
280 // silent
281 }
282 log.error("Cannot create keystore " + keyStorePath, e);
283 }
284 } else {
285 throw new IllegalStateException("Keystore " + keyStorePath + " already exists");
286 }
287 }
288
289 }