]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/internal/kernel/InitUtils.java
Make auth more robust
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / internal / kernel / 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.net.InetAddress;
9 import java.net.URI;
10 import java.nio.file.Files;
11 import java.nio.file.Path;
12 import java.security.KeyStore;
13 import java.util.ArrayList;
14 import java.util.Arrays;
15 import java.util.Dictionary;
16 import java.util.Hashtable;
17 import java.util.List;
18
19 import javax.security.auth.x500.X500Principal;
20
21 import org.apache.commons.io.FileUtils;
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24 import org.argeo.cms.CmsException;
25 import org.argeo.cms.internal.http.HttpConstants;
26 import org.argeo.cms.internal.jcr.RepoConf;
27 import org.argeo.node.NodeConstants;
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 /** Override the provided config with the framework properties */
38 static Dictionary<String, Object> getNodeRepositoryConfig(Dictionary<String, Object> provided) {
39 Dictionary<String, Object> props = provided != null ? provided : new Hashtable<String, Object>();
40 for (RepoConf repoConf : RepoConf.values()) {
41 Object value = getFrameworkProp(NodeConstants.NODE_REPO_PROP_PREFIX + repoConf.name());
42 if (value != null)
43 props.put(repoConf.name(), value);
44 }
45 props.put(NodeConstants.CN, NodeConstants.NODE);
46 return props;
47 }
48
49 static Dictionary<String, Object> getRepositoryConfig(String dataModelName, Dictionary<String, Object> provided) {
50 if (dataModelName.equals(NodeConstants.NODE) || dataModelName.equals(NodeConstants.HOME))
51 throw new IllegalArgumentException("Data model '" + dataModelName + "' is reserved.");
52 Dictionary<String, Object> props = provided != null ? provided : new Hashtable<String, Object>();
53 for (RepoConf repoConf : RepoConf.values()) {
54 Object value = getFrameworkProp(
55 NodeConstants.NODE_REPOS_PROP_PREFIX + dataModelName + '.' + repoConf.name());
56 if (value != null)
57 props.put(repoConf.name(), value);
58 }
59 if (props.size() != 0)
60 props.put(NodeConstants.CN, dataModelName);
61 return props;
62 }
63
64 /** Override the provided config with the framework properties */
65 static Dictionary<String, Object> getHttpServerConfig(Dictionary<String, Object> provided) {
66 String httpPort = getFrameworkProp("org.osgi.service.http.port");
67 String httpsPort = getFrameworkProp("org.osgi.service.http.port.secure");
68 /// TODO make it more generic
69 String httpHost = getFrameworkProp(HttpConstants.JETTY_PROPERTY_PREFIX + HttpConstants.HTTP_HOST);
70 String httpsHost = getFrameworkProp(HttpConstants.JETTY_PROPERTY_PREFIX + HttpConstants.HTTPS_HOST);
71
72 final Hashtable<String, Object> props = new Hashtable<String, Object>();
73 // try {
74 if (httpPort != null || httpsPort != null) {
75 if (httpPort != null) {
76 props.put(HttpConstants.HTTP_PORT, httpPort);
77 props.put(HttpConstants.HTTP_ENABLED, true);
78 }
79 if (httpsPort != null) {
80 props.put(HttpConstants.HTTPS_PORT, httpsPort);
81 props.put(HttpConstants.HTTPS_ENABLED, true);
82 Path keyStorePath = KernelUtils.getOsgiInstancePath(KernelConstants.DEFAULT_KEYSTORE_PATH);
83 String keyStorePassword = getFrameworkProp(
84 HttpConstants.JETTY_PROPERTY_PREFIX + HttpConstants.SSL_PASSWORD);
85 if (keyStorePassword == null)
86 keyStorePassword = "changeit";
87 if (!Files.exists(keyStorePath))
88 createSelfSignedKeyStore(keyStorePath, keyStorePassword);
89 props.put(HttpConstants.SSL_KEYSTORETYPE, "PKCS12");
90 props.put(HttpConstants.SSL_KEYSTORE, keyStorePath.toString());
91 props.put(HttpConstants.SSL_PASSWORD, keyStorePassword);
92 props.put(HttpConstants.SSL_WANTCLIENTAUTH, true);
93 }
94 if (httpHost != null)
95 props.put(HttpConstants.HTTP_HOST, httpHost);
96 if (httpsHost != null)
97 props.put(HttpConstants.HTTPS_HOST, httpHost);
98
99 props.put(NodeConstants.CN, NodeConstants.DEFAULT);
100 }
101 return props;
102 }
103
104 static List<Dictionary<String, Object>> getUserDirectoryConfigs() {
105 List<Dictionary<String, Object>> res = new ArrayList<>();
106 File nodeBaseDir = KernelUtils.getOsgiInstancePath(KernelConstants.DIR_NODE).toFile();
107 List<String> uris = new ArrayList<>();
108
109 // node roles
110 String nodeRolesUri = getFrameworkProp(NodeConstants.ROLES_URI);
111 String baseNodeRoleDn = NodeConstants.ROLES_BASEDN;
112 if (nodeRolesUri == null) {
113 nodeRolesUri = baseNodeRoleDn + ".ldif";
114 File nodeRolesFile = new File(nodeBaseDir, nodeRolesUri);
115 if (!nodeRolesFile.exists())
116 try {
117 FileUtils.copyInputStreamToFile(InitUtils.class.getResourceAsStream(baseNodeRoleDn + ".ldif"),
118 nodeRolesFile);
119 } catch (IOException e) {
120 throw new CmsException("Cannot copy demo resource", e);
121 }
122 // nodeRolesUri = nodeRolesFile.toURI().toString();
123 }
124 uris.add(nodeRolesUri);
125
126 // Business roles
127 String userAdminUris = getFrameworkProp(NodeConstants.USERADMIN_URIS);
128 if (userAdminUris == null) {
129 String demoBaseDn = "dc=example,dc=com";
130 userAdminUris = demoBaseDn + ".ldif";
131 File businessRolesFile = new File(nodeBaseDir, userAdminUris);
132 if (!businessRolesFile.exists())
133 try {
134 FileUtils.copyInputStreamToFile(InitUtils.class.getResourceAsStream(demoBaseDn + ".ldif"),
135 businessRolesFile);
136 } catch (IOException e) {
137 throw new CmsException("Cannot copy demo resource", e);
138 }
139 // userAdminUris = businessRolesFile.toURI().toString();
140 log.warn("## DEV Using dummy base DN " + demoBaseDn);
141 // TODO downgrade security level
142 }
143 for (String userAdminUri : userAdminUris.split(" "))
144 uris.add(userAdminUri);
145
146 // Interprets URIs
147 for (String uri : uris) {
148 URI u;
149 try {
150 u = new URI(uri);
151 if (u.getPath() == null)
152 throw new CmsException("URI " + uri + " must have a path in order to determine base DN");
153 if (u.getScheme() == null) {
154 if (uri.startsWith("/") || uri.startsWith("./") || uri.startsWith("../"))
155 u = new File(uri).getCanonicalFile().toURI();
156 else if (!uri.contains("/")) {
157 // u = KernelUtils.getOsgiInstanceUri(KernelConstants.DIR_NODE + '/' + uri);
158 u = new URI(uri);
159 } else
160 throw new CmsException("Cannot interpret " + uri + " as an uri");
161 } else if (u.getScheme().equals(UserAdminConf.SCHEME_FILE)) {
162 u = new File(u).getCanonicalFile().toURI();
163 }
164 } catch (Exception e) {
165 throw new CmsException("Cannot interpret " + uri + " as an uri", e);
166 }
167 Dictionary<String, Object> properties = UserAdminConf.uriAsProperties(u.toString());
168 res.add(properties);
169 }
170
171 return res;
172 }
173
174 /**
175 * Called before node initialisation, in order populate OSGi instance are with
176 * some files (typically LDIF, etc).
177 */
178 static void prepareFirstInitInstanceArea() {
179 String nodeInit = getFrameworkProp(NodeConstants.NODE_INIT);
180 if (nodeInit == null)
181 nodeInit = "../../init";
182 if (nodeInit.startsWith("http")) {
183 // remoteFirstInit(nodeInit);
184 return;
185 }
186
187 // TODO use java.nio.file
188 File initDir;
189 if (nodeInit.startsWith("."))
190 initDir = KernelUtils.getExecutionDir(nodeInit);
191 else
192 initDir = new File(nodeInit);
193 // TODO also uncompress archives
194 if (initDir.exists())
195 try {
196 FileUtils.copyDirectory(initDir, KernelUtils.getOsgiInstanceDir(), new FileFilter() {
197
198 @Override
199 public boolean accept(File pathname) {
200 if (pathname.getName().equals(".svn") || pathname.getName().equals(".git"))
201 return false;
202 return true;
203 }
204 });
205 log.info("CMS initialized from " + initDir.getCanonicalPath());
206 } catch (IOException e) {
207 throw new CmsException("Cannot initialize from " + initDir, e);
208 }
209 }
210
211 private static void createSelfSignedKeyStore(Path keyStorePath, String keyStorePassword) {
212 // for (Provider provider : Security.getProviders())
213 // System.out.println(provider.getName());
214 File keyStoreFile = keyStorePath.toFile();
215 char[] ksPwd = keyStorePassword.toCharArray();
216 char[] keyPwd = Arrays.copyOf(ksPwd, ksPwd.length);
217 if (!keyStoreFile.exists()) {
218 try {
219 keyStoreFile.getParentFile().mkdirs();
220 KeyStore keyStore = PkiUtils.getKeyStore(keyStoreFile, ksPwd);
221 PkiUtils.generateSelfSignedCertificate(keyStore,
222 new X500Principal("CN=" + InetAddress.getLocalHost().getHostName() + ",OU=UNSECURE,O=UNSECURE"),
223 1024, keyPwd);
224 PkiUtils.saveKeyStore(keyStoreFile, ksPwd, keyStore);
225 if (log.isDebugEnabled())
226 log.debug("Created self-signed unsecure keystore " + keyStoreFile);
227 } catch (Exception e) {
228 if (keyStoreFile.length() == 0)
229 keyStoreFile.delete();
230 log.error("Cannot create keystore " + keyStoreFile, e);
231 }
232 } else {
233 throw new CmsException("Keystore " + keyStorePath + " already exists");
234 }
235 }
236
237 }