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