diff --git a/hsarback/src/de/hsadmin/mods/dom/DomainProcessorFactory.java b/hsarback/src/de/hsadmin/mods/dom/DomainProcessorFactory.java index feab37b..0bd881e 100644 --- a/hsarback/src/de/hsadmin/mods/dom/DomainProcessorFactory.java +++ b/hsarback/src/de/hsadmin/mods/dom/DomainProcessorFactory.java @@ -269,11 +269,20 @@ public class DomainProcessorFactory implements EntityProcessorFactory { ifOption(templateVars, query, "multiviews", "+MultiViews", "-MultiViews"); ifOption(templateVars, query, "htdocsfallback", Boolean.TRUE, Boolean.FALSE); final Processor domSetupProcessor = new CompoundProcessor( - new ShellProcessor("export PEMS_DIR=/etc/apache2/pems-enabled/" + dom.getUser().getName() + " && " - + "mkdir -p $PEMS_DIR/ && " + new CreateFileProcessor("/de/hsadmin/mods/dom/openssl-sna.cnf", templateVars, dom, "/tmp/openssl-sna.cnf", "root", "root", "644", true), + new ShellProcessor("export PEMS_DIR=/etc/apache2/pems-generated && " + + "mkdir -p $PEMS_DIR && " + "cd $PEMS_DIR && " - + "( ls " + domName + ".crt || ( echo \"\" > " + domName + ".chain && " - + "openssl req -x509 -newkey rsa:2048 -keyout " + domName + ".key -out " + domName + ".crt -days 1100 -nodes -sha256 -subj '/CN=" + domName + "' ) ) &&" + + "( ls " + domName + ".crt || ( echo \"\" > _." + domName + ".chain && " + + "openssl req -x509 -newkey rsa:2048 -keyout _." + domName + ".key -out _." + domName + ".crt -days 1100 -nodes -sha256 -config /tmp/openssl-sna.cnf ) ) &&" + + "chmod 400 _." + domName + "*"), + new ShellProcessor("export PEMS_DIR=/etc/apache2/pems-enabled && " + + "mkdir -p $PEMS_DIR && " + + "cd $PEMS_DIR && " + + "( ls " + domName + ".crt ||" + + " ( ln -s ../pems-generated/_." + domName + ".key " + domName + ".key" + + " && ln -s ../pems-generated/_." + domName + ".crt " + domName + ".crt" + + " && ln -s ../pems-generated/_." + domName + ".chain " + domName + ".chain ) ) && " + "chmod 400 " + domName + "*"), new CreateFileProcessor("/de/hsadmin/mods/dom/apache-vhost.vm", templateVars, dom, "/etc/apache2/sites-available/" + domName + ".tmp", "root", "root", "644", true), new ShellProcessor( diff --git a/hsarback/src/de/hsadmin/mods/dom/apache-vhost.vm b/hsarback/src/de/hsadmin/mods/dom/apache-vhost.vm index e4fdd2d..320e786 100644 --- a/hsarback/src/de/hsadmin/mods/dom/apache-vhost.vm +++ b/hsarback/src/de/hsadmin/mods/dom/apache-vhost.vm @@ -90,9 +90,9 @@ #end SSLEngine On - SSLCertificateFile /etc/apache2/pems-enabled/${dom.user.name}/${dom.name}.crt - SSLCertificateKeyFile /etc/apache2/pems-enabled/${dom.user.name}/${dom.name}.key - SSLCertificateChainFile /etc/apache2/pems-enabled/${dom.user.name}/${dom.name}.chain + SSLCertificateFile /etc/apache2/pems-enabled/${dom.name}.crt + SSLCertificateKeyFile /etc/apache2/pems-enabled/${dom.name}.key + SSLCertificateChainFile /etc/apache2/pems-enabled/${dom.name}.chain DocumentRoot /home/doms/${dom.name}/htdocs-ssl diff --git a/hsarback/src/de/hsadmin/mods/dom/openssl-sna.cnf b/hsarback/src/de/hsadmin/mods/dom/openssl-sna.cnf new file mode 100644 index 0000000..b5cd207 --- /dev/null +++ b/hsarback/src/de/hsadmin/mods/dom/openssl-sna.cnf @@ -0,0 +1,12 @@ +[req] +prompt = no +distinguished_name = req_dn +x509_extensions = v3_ca + +[req_dn] +commonName = *.${dom.name} + +[v3_ca] +basicConstraints = CA:FALSE +extendedKeyUsage=serverAuth +subjectAltName=DNS:*.${dom.name},DNS:${dom.name} diff --git a/hsarjcli/.classpath b/hsarjcli/.classpath deleted file mode 100644 index 883126c..0000000 --- a/hsarjcli/.classpath +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/hsarjcli/.gitignore b/hsarjcli/.gitignore deleted file mode 100644 index 2f230b7..0000000 --- a/hsarjcli/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/build -/bin \ No newline at end of file diff --git a/hsarjcli/.project b/hsarjcli/.project deleted file mode 100644 index 528bfcc..0000000 --- a/hsarjcli/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - hsarjcli - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - diff --git a/hsarjcli/.settings/org.eclipse.jdt.core.prefs b/hsarjcli/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index bca7901..0000000 --- a/hsarjcli/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,12 +0,0 @@ -#Mon May 16 15:05:41 CEST 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/hsarjcli/build.xml b/hsarjcli/build.xml deleted file mode 100644 index 66e5e4f..0000000 --- a/hsarjcli/build.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/hsarjcli/scripting/package_dump.js b/hsarjcli/scripting/package_dump.js deleted file mode 100644 index 6d5556c..0000000 --- a/hsarjcli/scripting/package_dump.js +++ /dev/null @@ -1,213 +0,0 @@ -var pacs = pac.search(); -var hive = 'h99'; -var password = 'p!' + (new String(Math.random())).substring(2,16) + '!'; -function runbash(cmd) { - var runtime = java.lang.Runtime.getRuntime(); - runtime.exec(["bash", "-c", cmd]); -} -function mysqldump(pac, db) { - var dump = "/home/pacs/" + pac + "/.bak/mysql-" + db + ".dmp.gz"; - var cmd = "mysqldump --create-options --flush-logs --force --quote-names --quick --single-transaction " - + db + "|gzip --best|secat --user=" + pac + " --group=" + pac + " --umask=007 --output=" + dump; - runbash(cmd); -} -function pgsqldump(pac, db) { - var dump = "/home/pacs/" + pac + "/.bak/pgsql-" + db + ".dmp.gz"; - var cmd = "export PGUSER=postgres; pg_dump --disable-triggers --oids --compress=0 --format=c " - + db + "|gzip --best|secat --user=" + pac + " --group=" + pac + " --umask=007 --output=" + dump; - runbash(cmd); -} -function crontabdump(pac, user) { - var dump = "/home/pacs/" + pac + "/.bak/crontab-" + user + ".gz"; - var cmd = "crontab -u " + user + " -l" - + "|gzip --best|secat --user=" + pac + " --group=" + pac + " --umask=007 --output=" + dump; - runbash(cmd); -} -function shadowdump(pac) { - var dump = "/home/pacs/" + pac + "/.bak/shadow.gz"; - var cmd = "grep -e '^" + pac + "' /etc/shadow|cut -f1-2 -d':' " - + "|gzip --best|secat --user=" + pac + " --group=" + pac + " --umask=007 --output=" + dump; - runbash(cmd); -} -function mysqlaclsdump(pac) { - var dump = "/home/pacs/" + pac + "/.bak/mysql_passwd"; - var cmd = "mysqldump --no-create-db --skip-opt --no-create-info --replace --where=\"user like '" + pac + "%'\" mysql --tables user > " + dump - + " && mysqldump --no-create-db --skip-opt --no-create-info --replace --where=\"db like '" + pac + "%'\" mysql --tables db tables_priv proc >>" + dump - + " && chown " + pac + ":" + pac + " " + dump; - runbash(cmd); -} -function pgsqlpasswddump(pac) { - var dump = "/home/pacs/" + pac + "/.bak/pgsql_passwd.gz"; - var cmd = "export PGUSER=postgres; pg_dumpall -r | grep ^ALTER | grep " + pac - + "|gzip --best|secat --user=" + pac + " --group=" + pac + " --umask=007 --output=" + dump; - runbash(cmd); -} -if (pacs.length == 1 && hive != 'undef') { - var pacname = pacs[0]['name']; - var file = new java.io.FileWriter(pacname + '_dump.js'); - // Pac - file.write('pac.add({set:{\n'); - file.write('name: "' + pacs[0]['name'] + '",\n'); - file.write('curinetaddr: "' + pacs[0]['curinetaddr'] + '",\n'); - file.write('customer: "' + pacs[0]['customer'] + '",\n'); - file.write('basepac: "' + pacs[0]['basepac'] + '",\n'); - file.write('hive: "' + hive + '",\n'); - file.write('password: "' + password + '"\n'); - file.write('}});\n'); - file.write('pac.update({where:{\n'); - file.write('name: "' + pacs[0]['name'] + '"\n'); - file.write('},set:{\n'); - file.write('components: {\n'); - for (var opt in pacs[0]['components']) { - file.write(' ' + opt + ': "' + pacs[0]['components'][opt] + '",\n'); - } - file.write('}}});\n'); - // User - var unixusers = user.search(); - for (idx=0; idx 5) { - file.write('user.add({set:{\n'); - file.write('name: "' + unixusers[idx]['name'] + '",\n'); - file.write('shell: "' + unixusers[idx]['shell'] + '",\n'); - file.write('userid: "' + unixusers[idx]['userid'] + '",\n'); - file.write('comment: "' + unixusers[idx]['comment'] + '",\n'); - file.write('homedir: "' + unixusers[idx]['homedir'] + '",\n'); - file.write('quota_hardlimit: "' + unixusers[idx]['quota_hardlimit'] + '",\n'); - file.write('quota_softlimit: "' + unixusers[idx]['quota_softlimit'] + '",\n'); - file.write('password: "' + password + '"\n'); - file.write('}});\n'); - } - crontabdump(pacname, unixusers[idx]['name']); - } - // Domain - var domains = domain.search(); - for (idx=0; idx "); - final String user = cmdParser.getUser(); - final ScriptClient scriptClient = new ScriptClient(console, user, runAs, cmdParser.getArgs()); - final String file = cmdParser.getFile(); - if (file != null && file.length() > 0) { - if ("-".equals(file)) { - scriptClient.execute(new InputStreamReader(System.in)); - console.println(formatter.format(scriptClient.getLastRpcResult())); - } else { - BufferedReader bufferedReader = null; - try { - bufferedReader = new BufferedReader(new FileReader(file)); - String inputLine = bufferedReader.readLine(); - boolean isFirstLine = true; - final StringBuffer scriptFromFile = new StringBuffer(); - while (inputLine != null) { - if (isFirstLine && inputLine.startsWith("#!")) { - scriptFromFile.append("//"); - scriptFromFile.append(inputLine.substring(2)); - } else { - scriptFromFile.append(inputLine); - } - scriptFromFile.append("\n"); - isFirstLine = false; - inputLine = bufferedReader.readLine(); - } - scriptClient.execute(scriptFromFile.toString()); - } catch (FileNotFoundException e) { - System.err.println("File not found: " + file); - } finally { - if (bufferedReader != null) { - bufferedReader.close(); - } - } - } - } - final String expr = cmdParser.getExpression(); - if (expr != null && expr.length() > 0) { - scriptClient.execute(expr); - console.println(formatter.format(scriptClient.getLastRpcResult())); - } - if (cmdParser.isInteractive()) { - String command = console.readInput(); - while (!("bye".equals(command.trim()) || "exit".equals(command.trim()) || "quit".equals(command.trim()))) { - try { - scriptClient.execute(command); - console.println(formatter.format(scriptClient.getLastRpcResult())); - } catch (Exception e) { - console.println("Error: " + e.getLocalizedMessage() + "\n"); - } - command = console.readInput(); - } - } - } catch (Exception e) { - System.err.println(e.getMessage()); - System.exit(-1); - } - } - -} diff --git a/hsarjcli/src/de/hsadmin/jscli/RpcClient.java b/hsarjcli/src/de/hsadmin/jscli/RpcClient.java deleted file mode 100644 index b193b54..0000000 --- a/hsarjcli/src/de/hsadmin/jscli/RpcClient.java +++ /dev/null @@ -1,92 +0,0 @@ -package de.hsadmin.jscli; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.xmlrpc.XmlRpcException; -import org.apache.xmlrpc.client.XmlRpcClient; -import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; - -import de.hsadmin.jscli.cas.CASTicketProvider; -import de.hsadmin.jscli.conf.Config; -import de.hsadmin.jscli.exception.JSCliException; - -public class RpcClient { - - private static final String XMLRPC_URL = "https://config.hostsharing.net:443/hsar/xmlrpc/hsadmin"; - - private final List clientList; - private final Map clientMap; - - public RpcClient(final CASTicketProvider tgt) throws JSCliException { - clientList = new ArrayList(); - clientMap = new HashMap(); - try { - final String xmlrpcURLsString = Config.getInstance().getProperty("xmlrpcURL", XMLRPC_URL); - final String[] xmlrpcURLsArray = xmlrpcURLsString.split(","); - for (final String xmlrpcURL : xmlrpcURLsArray) { - final XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); - config.setServerURL(new URL(xmlrpcURL)); - config.setEnabledForExtensions(true); - final XmlRpcClient client = new XmlRpcClient(); - client.setConfig(config); - clientList.add(client); - } - } catch (MalformedURLException e) { - throw new JSCliException(e); - } - } - - public List listMethods() throws JSCliException { - final List methodList = new ArrayList(); - for (final XmlRpcClient client : clientList) { - final List execute = execute(client, "system.listMethods"); - for (final Object obj : execute) { - final String methodString = obj.toString(); - final String[] path = methodString.split("\\."); - if (path.length == 2) { - clientMap.put(path[0], client); - } - methodList.add(methodString); - } - } - return methodList; - } - - private List execute(final XmlRpcClient client, final String method) throws JSCliException { - return execute(client, method, new ArrayList()); - } - - private List execute(final XmlRpcClient client, final String method, final List params) throws JSCliException { - try { - final Object execute = client.execute(method, params); - final ArrayList list = new ArrayList(); - if (execute instanceof Object[]) { - final Object[] resArray = (Object[]) execute; - for (int idx=0; idx < resArray.length; idx++) { - list.add(resArray[idx]); - } - } - if (execute instanceof Map) { - list.add(execute); - } - return list; - } catch (XmlRpcException e) { - throw new JSCliException(e); - } - } - - public List execute(final String method, final List params) throws JSCliException { - final String[] path = method.split("\\."); - if (path.length == 2) { - return execute(clientMap.get(path[0]), method, params); - } else { - throw new JSCliException("method not found: " + method); - } - } - -} diff --git a/hsarjcli/src/de/hsadmin/jscli/ScriptClient.java b/hsarjcli/src/de/hsadmin/jscli/ScriptClient.java deleted file mode 100644 index b4c7870..0000000 --- a/hsarjcli/src/de/hsadmin/jscli/ScriptClient.java +++ /dev/null @@ -1,127 +0,0 @@ -package de.hsadmin.jscli; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; - -import de.hsadmin.jscli.cas.CASTicketProvider; -import de.hsadmin.jscli.console.ConsoleWrapper; -import de.hsadmin.jscli.exception.JSCliException; - -public class ScriptClient { - - final private ScriptEngine engine; - final private Set completionStrings; - - public ScriptClient(final ConsoleWrapper console, final String user, final String runAs, final String... arguments) throws JSCliException { - final CASTicketProvider ticketProvider = new CASTicketProvider(console, user, runAs); - final RpcClient rpcClient = new RpcClient(ticketProvider); - final ScriptEngineManager engineManager = new ScriptEngineManager(); - engine = engineManager.getEngineByName("js"); - engine.put("casgrantingticket", ticketProvider); - engine.put("xmlrpcclient", rpcClient); - engine.put("xmlrpcLastResult", null); - completionStrings = new HashSet(); - completionStrings.add("set"); - completionStrings.add("where"); - considerArguments(arguments); - try { - final InputStream inputResource = getClass().getClassLoader().getResourceAsStream("js/functions.js"); - engine.eval(new InputStreamReader(inputResource)); - } catch (ScriptException e) { - throw new JSCliException(e); - } - final List methods = rpcClient.listMethods(); - for (final String method : methods) { - final String[] parts = method.split("\\."); - if (parts.length == 2) { - final String module = parts[0]; - final String function = parts[1]; - if ("system".equals(module) || "getModuleLookup".equals(function) || "createValueObject".equals(function)) { - continue; - } - completionStrings.add(module); - final String jsFunctionIdent; - if ("delete".equals(function)) { - jsFunctionIdent = module + "['remove']"; - completionStrings.add(module + ".remove"); - } else { - jsFunctionIdent = module + "['" + function + "']"; - completionStrings.add(module + "." + function); - } - try { - engine.eval( - "if (typeof " + module + " === 'undefined')" + - " { var " + module + " = { }; };\n" + - jsFunctionIdent + - " = function(json) { return hsaModuleCall('" + module + "', '" + function + "', json); }" - ); - } catch (ScriptException e) { - e.printStackTrace(); - } - } - } - console.codeCompletion(getCodeCompletionStrings()); - } - - public String[] getCodeCompletionStrings() { - final String[] codeCompletionStrings = new String[completionStrings.size()]; - int idx = 0; - for (final String s : completionStrings) { - codeCompletionStrings[idx] = s; - idx++; - } - return codeCompletionStrings; - } - - public Object execute(final String snippet) throws JSCliException { - try { - engine.put("xmlrpcLastResult", null); - return engine.eval(snippet); - } catch (ScriptException e) { - throw new JSCliException(e); - } - } - - public Object execute(final Reader rd) throws JSCliException { - try { - engine.put("xmlrpcLastResult", null); - return engine.eval(rd); - } catch (ScriptException e) { - throw new JSCliException(e); - } - } - - public Object getLastRpcResult() { - return engine.get("xmlrpcLastResult"); - } - - private void considerArguments(final String... arguments) - throws JSCliException { - final StringBuilder argsBuilder = new StringBuilder("var arguments = [ "); - boolean isFirstArg = true; - for (final String arg : arguments) { - if (!isFirstArg) { - argsBuilder.append(", "); - } - argsBuilder.append('\''); - argsBuilder.append(arg); - argsBuilder.append('\''); - isFirstArg = false; - } - argsBuilder.append(" ];"); - try { - engine.eval(argsBuilder.toString()); - } catch (ScriptException e) { - throw new JSCliException(e); - } - } - -} diff --git a/hsarjcli/src/de/hsadmin/jscli/cas/CASTicketProvider.java b/hsarjcli/src/de/hsadmin/jscli/cas/CASTicketProvider.java deleted file mode 100644 index c17cf17..0000000 --- a/hsarjcli/src/de/hsadmin/jscli/cas/CASTicketProvider.java +++ /dev/null @@ -1,200 +0,0 @@ -package de.hsadmin.jscli.cas; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.ProtocolException; -import java.net.URL; -import java.net.URLEncoder; -import java.util.Properties; - -import javax.net.ssl.HttpsURLConnection; - -import de.hsadmin.jscli.conf.Config; -import de.hsadmin.jscli.console.PasswordReader; -import de.hsadmin.jscli.exception.JSCliException; - -public class CASTicketProvider { - - private static final String LOGIN_URL = "https://login.hostsharing.net:443/cas/v1/tickets"; - private static final String BACKEND_URL = "https://config.hostsharing.net:443/hsar/backend"; - - final private String loginURL; - final private String backendURL; - final private String runAs; - final private String user; - final private PasswordReader passwordReader; - - private String grantingTicket; - - public CASTicketProvider(final PasswordReader console, final String user, final String runAs) throws JSCliException { - this.passwordReader = console; - this.user = user; - this.runAs = runAs; - final Config config = Config.getInstance(); - backendURL = config.getProperty("backendURL", BACKEND_URL); - loginURL = config.getProperty("loginURL", LOGIN_URL); - if ("TestUmgebung".equals(loginURL)) { - grantingTicket = "ticket:" + user; - } else { - grantingTicket = readFiledGrantingTicket(); - } - } - - public String getTicket() throws JSCliException, FileNotFoundException { - if (grantingTicket != null && grantingTicket.startsWith("ticket:")) { - return grantingTicket.replaceFirst("ticket", "user"); - } - try { - String encodedParams = URLEncoder.encode("service", "UTF-8") - + "=" + URLEncoder.encode(backendURL, "UTF-8"); - return doHttpPost(grantingTicket, encodedParams); - } catch (UnsupportedEncodingException e) { - throw new JSCliException(e); - } - } - - public String getRunAs() { - return runAs; - } - - private String getGrantingTicket() throws JSCliException { - grantingTicket = null; - String password = Config.getInstance().getProperty(user + ".passWord"); - if (password == null || password.length() <= 0) { - password = readPasswordFromConsole(); - } - try { - String encodedParams = URLEncoder.encode("username", "UTF-8") - + "=" + URLEncoder.encode(user, "UTF-8") - + "&" + URLEncoder.encode("password", "UTF-8") - + "=" + URLEncoder.encode(password, "UTF-8"); - grantingTicket = doHttpPost(loginURL, encodedParams); - } catch (UnsupportedEncodingException e) { - throw new JSCliException(e); - } catch (FileNotFoundException e) { - throw new JSCliException("cas server not available: " + loginURL); - } - return grantingTicket; - } - - private String readPasswordFromConsole() throws JSCliException { - return passwordReader.readPassword(); - } - - private String doHttpPost(final String urlString, final String encodedParams) throws JSCliException, FileNotFoundException { - String result = null; - try { - result = extractTicket(urlString, encodedParams); - } catch (FileNotFoundException e) { - grantingTicket = getGrantingTicket(); - saveProperties(grantingTicket, getTicketFile()); - try { - result = extractTicket(grantingTicket, encodedParams); - } catch (IOException e1) { - throw new JSCliException(e1); - } - } catch (IOException e) { - throw new JSCliException(e); - } - return result; - } - - private String extractTicket(final String urlString, - final String encodedParams) throws MalformedURLException, - IOException, ProtocolException { - String result; - final HttpsURLConnection connection = doConnect(urlString, encodedParams); - final String ticket = readTicket(connection); - if (ticket != null && ticket.startsWith("ST-")) { - result = ticket; - } else { - result = connection.getHeaderField("Location"); - } - return result; - } - - private String readTicket(final HttpsURLConnection connection) - throws IOException { - final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - final String ticket = reader.readLine(); - String readLine = null; - do { - readLine = reader.readLine(); - } while (readLine != null); - return ticket; - } - - private HttpsURLConnection doConnect(final String urlString, - final String encodedParams) throws MalformedURLException, - IOException, ProtocolException { - final URL url = new URL(urlString); - final HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); - connection.setDoInput(true); - connection.setDoOutput(true); - connection.setUseCaches(false); - connection.setAllowUserInteraction(false); - final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); - writer.write(encodedParams); - writer.close(); - return connection; - } - - private String readFiledGrantingTicket() throws JSCliException { - String filedTicket = null; - final File file = getTicketFile(); - final Properties properties = loadProperties(file); - filedTicket = properties.getProperty(user); - if (filedTicket == null) { - filedTicket = getGrantingTicket(); - saveProperties(filedTicket, file); - } - return filedTicket; - } - - private File getTicketFile() { - final String userHome = System.getProperty("user.home"); - final String ticketFileName = userHome + "/.hsadmin.tgt"; - return new File(ticketFileName); - } - - private void saveProperties(final String filedTicket, final File file) throws JSCliException { - final Properties properties = loadProperties(file); - if (filedTicket != null) { - properties.setProperty(user, filedTicket); - try { - properties.store(new FileOutputStream(file), ""); - } catch (IOException e) { - throw new JSCliException(e); - } - } - } - - private Properties loadProperties(final File file) throws JSCliException { - final Properties properties = new Properties(); - if (file.isFile() && file.canRead()) { - try { - properties.load(new FileReader(file)); - } catch (IOException e) { - throw new JSCliException(e); - } - } - return properties; - } - - @Override - public String toString() { - return grantingTicket; - } - -} diff --git a/hsarjcli/src/de/hsadmin/jscli/conf/CommandlineParser.java b/hsarjcli/src/de/hsadmin/jscli/conf/CommandlineParser.java deleted file mode 100644 index b900683..0000000 --- a/hsarjcli/src/de/hsadmin/jscli/conf/CommandlineParser.java +++ /dev/null @@ -1,72 +0,0 @@ -package de.hsadmin.jscli.conf; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.apache.commons.cli.PosixParser; - -import de.hsadmin.jscli.exception.JSCliException; - -public class CommandlineParser { - - - private CommandLine cmd; - private Options opts; - - public CommandlineParser(String[] args) throws JSCliException { - opts = new Options(); - opts.addOption("h", "help", false, "print this message"); - opts.addOption("u", "user", true, "specify login user"); - opts.addOption("r", "runas", true, "specify run-as user"); - opts.addOption("e", "expr", true, "expression to execute"); - opts.addOption("f", "file", true, "script file to execute"); - opts.addOption("i", "interactive", false, "interactive shell"); - PosixParser parser = new PosixParser(); - try { - if (args.length < 1) { - printHelp(); - System.exit(0); - } - cmd = parser.parse(opts, args); - if (cmd.hasOption("help")) { - printHelp(); - System.exit(0); - } - } catch (ParseException e) { - throw new JSCliException(e); - } - } - - public String getUser() { - final String systemUser = System.getProperty("user.name"); - final String configUser = Config.getInstance().getProperty("userName", systemUser); - return cmd.getOptionValue("user", configUser); - } - - public String getRunAs() { - return cmd.getOptionValue("runas", getUser()); - } - - public String getExpression() { - return cmd.getOptionValue("expr", null); - } - - public String getFile() { - return cmd.getOptionValue("file", null); - } - - public boolean isInteractive() { - return cmd.hasOption("interactive"); - } - - public void printHelp() { - HelpFormatter formatter = new HelpFormatter(); - formatter.printHelp("hsscript", opts); - } - - public String[] getArgs() { - return cmd.getArgs(); - } - -} diff --git a/hsarjcli/src/de/hsadmin/jscli/conf/Config.java b/hsarjcli/src/de/hsadmin/jscli/conf/Config.java deleted file mode 100644 index 5b24a65..0000000 --- a/hsarjcli/src/de/hsadmin/jscli/conf/Config.java +++ /dev/null @@ -1,57 +0,0 @@ -package de.hsadmin.jscli.conf; - -import java.io.File; -import java.io.FileReader; -import java.util.Properties; - -public class Config { - - private static Config instance; - - private Properties props; - - private Config() { - props = new Properties(); - File file = new File(System.getProperty("user.dir") + "/hsadmin.properties"); - if (!file.canRead()) { - file = new File(System.getProperty("user.dir") + "/conf/hsadmin.properties"); - } - if (!file.canRead()) { - file = new File(System.getProperty("user.home") + "/.hsadmin.properties"); - } - if (!file.canRead()) { - file = new File("/etc/hsadmin.properties"); - } - if (!file.canRead()) { - file = new File("/etc/hsadmin/hsadmin.properties"); - } - if (file.canRead()) { - try { - props.load(new FileReader(file)); - } catch (Exception e) { - // should not happen - e.printStackTrace(); - } - } - } - - public static Config getInstance() { - if (instance == null) { - instance = new Config(); - } - return instance; - } - - public String getProperty(String propertyName) { - String property = props.getProperty(propertyName); - if (property == null) { - return null; - } - return property.trim(); - } - - public String getProperty(String propertyName, String defaultValue) { - return props.getProperty(propertyName, defaultValue).trim(); - } - -} diff --git a/hsarjcli/src/de/hsadmin/jscli/console/ConsoleWrapper.java b/hsarjcli/src/de/hsadmin/jscli/console/ConsoleWrapper.java deleted file mode 100644 index 1715ec2..0000000 --- a/hsarjcli/src/de/hsadmin/jscli/console/ConsoleWrapper.java +++ /dev/null @@ -1,67 +0,0 @@ -package de.hsadmin.jscli.console; - -import java.io.File; -import java.io.IOException; - -import jline.ConsoleReader; -import jline.History; -import jline.SimpleCompletor; -import de.hsadmin.jscli.exception.JSCliException; - -public class ConsoleWrapper implements PasswordReader { - - private ConsoleReader cons; - private String prompt; - - public void open(final String prompt) throws JSCliException { - this.prompt = prompt; - try { - cons = new ConsoleReader(); - cons.setDefaultPrompt(prompt); - final String userHome = System.getProperty("user.home"); - cons.setHistory(new History(new File(userHome + "/.hsscript_history"))); - } catch (IOException e) { - throw new JSCliException(e); - } - } - - public String readInput() throws JSCliException { - try { - String line = cons.readLine(); - while (line.trim().endsWith("\\")) { - line = line.substring(0, line.length() - 1) + "\n" + cons.readLine(">"); - } - return line; - } catch (IOException e) { - throw new JSCliException(e); - } - } - - public void println(final String text) throws JSCliException { - try { - if (cons != null) { - cons.printString(text); - cons.printNewline(); - } else { - throw new JSCliException("cannot write console"); - } - } catch (IOException e) { - throw new JSCliException(e); - } - } - - public String readPassword() throws JSCliException { - try { - final String pw = cons.readLine("Password: ", new Character('*')); - cons.setDefaultPrompt(prompt); - return pw; - } catch (IOException e) { - throw new JSCliException(e); - } - } - - public void codeCompletion(final String[] candidateStrings) { - cons.addCompletor(new SimpleCompletor(candidateStrings)); - } - -} diff --git a/hsarjcli/src/de/hsadmin/jscli/console/PasswordReader.java b/hsarjcli/src/de/hsadmin/jscli/console/PasswordReader.java deleted file mode 100644 index 4a42f3c..0000000 --- a/hsarjcli/src/de/hsadmin/jscli/console/PasswordReader.java +++ /dev/null @@ -1,9 +0,0 @@ -package de.hsadmin.jscli.console; - -import de.hsadmin.jscli.exception.JSCliException; - -public interface PasswordReader { - - String readPassword() throws JSCliException; - -} diff --git a/hsarjcli/src/de/hsadmin/jscli/exception/JSCliException.java b/hsarjcli/src/de/hsadmin/jscli/exception/JSCliException.java deleted file mode 100644 index ab3cb10..0000000 --- a/hsarjcli/src/de/hsadmin/jscli/exception/JSCliException.java +++ /dev/null @@ -1,16 +0,0 @@ -package de.hsadmin.jscli.exception; - - -public class JSCliException extends Exception { - - private static final long serialVersionUID = 1L; - - public JSCliException(Exception e) { - super(e); - } - - public JSCliException(String message) { - super(message); - } - -} diff --git a/hsarjcli/src/de/hsadmin/jscli/json/JSONFormatter.java b/hsarjcli/src/de/hsadmin/jscli/json/JSONFormatter.java deleted file mode 100644 index 3fa2711..0000000 --- a/hsarjcli/src/de/hsadmin/jscli/json/JSONFormatter.java +++ /dev/null @@ -1,101 +0,0 @@ -package de.hsadmin.jscli.json; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -public class JSONFormatter { - - private int indent = 1; - - public String format(final Object object) { - if (object == null) return ""; - if (object instanceof List) { - return formatList((List) object); - } - if (object instanceof Map) { - return formatMap((Map) object); - } - if (object instanceof String) { - return formatString((String) object); - } - if (object instanceof Object[]) { - return formatArr((Object[]) object); - } - return "an instance of " + object.getClass().getCanonicalName(); - } - - public String formatMap(final Map map) { - final StringBuffer result = new StringBuffer(); - result.append('{'); - incr(); - result.append(newline()); - final StringBuffer formattedMap = new StringBuffer(); - final List listOfKeys = Arrays.asList(map.keySet().toArray(new String[] {})); - Collections.sort(listOfKeys); - for (final Object key : listOfKeys) { - if (formattedMap.length() > 0) { - formattedMap.append(','); - formattedMap.append(newline()); - } - formattedMap.append(key.toString()); - formattedMap.append(':'); - formattedMap.append(format(map.get(key))); - } - result.append(formattedMap.toString()); - decr(); - result.append(newline()); - result.append('}'); - return result.toString(); - } - - public String formatString(final String str) { - return "'" + str + "'"; - } - - public String formatList(final List list) { - return formatArr(list.toArray()); - } - - public String formatArr(final Object[] arr) { - StringBuffer result = new StringBuffer(); - result.append('['); - incr(); - result.append(newline()); - StringBuffer formattedList = new StringBuffer(); - for (int idx = 0; idx < arr.length; idx ++) { - if (formattedList.length() > 0) { - formattedList.append(','); - formattedList.append(newline()); - } - formattedList.append(format(arr[idx])); - } - result.append(formattedList.toString()); - decr(); - if (formattedList.length() > 0) { - result.append(newline()); - } - result.append(']'); - return result.toString(); - } - - private void incr() { - indent += 3; - } - - private void decr() { - if (indent > 3) { - indent -= 3; - } - } - - private String newline() { - int ind = indent; - if (ind > 52) { - ind = 52; - } - return "\n ".substring(0, indent); - } - -} diff --git a/hsarjcli/src/tools/InstallCert.java b/hsarjcli/src/tools/InstallCert.java deleted file mode 100644 index 4d36b6b..0000000 --- a/hsarjcli/src/tools/InstallCert.java +++ /dev/null @@ -1,159 +0,0 @@ -package tools; - -import javax.net.ssl.*; -import java.io.*; -import java.security.KeyStore; -import java.security.MessageDigest; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -/** - * Class used to add the server's certificate to the KeyStore - * with your trusted certificates. - */ -public class InstallCert { - - public static void main(String[] args) throws Exception { - String host; - int port; - char[] passphrase; - if ((args.length == 1) || (args.length == 2)) { - String[] c = args[0].split(":"); - host = c[0]; - port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); - String p = (args.length == 1) ? "changeit" : args[1]; - passphrase = p.toCharArray(); - } else { - System.out.println("Usage: java InstallCert [:port] [passphrase]"); - return; - } - - File file = new File("jssecacerts"); - if (file.isFile() == false) { - char SEP = File.separatorChar; - File dir = new File(System.getProperty("java.home") + SEP - + "lib" + SEP + "security"); - file = new File(dir, "jssecacerts"); - if (file.isFile() == false) { - file = new File(dir, "cacerts"); - } - } - System.out.println("Loading KeyStore " + file + "..."); - InputStream in = new FileInputStream(file); - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - ks.load(in, passphrase); - in.close(); - - SSLContext context = SSLContext.getInstance("TLS"); - TrustManagerFactory tmf = - TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - tmf.init(ks); - X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; - SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); - context.init(null, new TrustManager[]{tm}, null); - SSLSocketFactory factory = context.getSocketFactory(); - - System.out.println("Opening connection to " + host + ":" + port + "..."); - SSLSocket socket = (SSLSocket) factory.createSocket(host, port); - socket.setSoTimeout(10000); - try { - System.out.println("Starting SSL handshake..."); - socket.startHandshake(); - socket.close(); - System.out.println(); - System.out.println("No errors, certificate is already trusted"); - } catch (SSLException e) { - System.out.println(); - e.printStackTrace(System.out); - } - - X509Certificate[] chain = tm.chain; - if (chain == null) { - System.out.println("Could not obtain server certificate chain"); - return; - } - - BufferedReader reader = - new BufferedReader(new InputStreamReader(System.in)); - - System.out.println(); - System.out.println("Server sent " + chain.length + " certificate(s):"); - System.out.println(); - MessageDigest sha1 = MessageDigest.getInstance("SHA1"); - MessageDigest md5 = MessageDigest.getInstance("MD5"); - for (int i = 0; i < chain.length; i++) { - X509Certificate cert = chain[i]; - System.out.println - (" " + (i + 1) + " Subject " + cert.getSubjectDN()); - System.out.println(" Issuer " + cert.getIssuerDN()); - sha1.update(cert.getEncoded()); - System.out.println(" sha1 " + toHexString(sha1.digest())); - md5.update(cert.getEncoded()); - System.out.println(" md5 " + toHexString(md5.digest())); - System.out.println(); - } - - System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]"); - String line = reader.readLine().trim(); - int k; - try { - k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; - } catch (NumberFormatException e) { - System.out.println("KeyStore not changed"); - return; - } - - X509Certificate cert = chain[k]; - String alias = host + "-" + (k + 1); - ks.setCertificateEntry(alias, cert); - - OutputStream out = new FileOutputStream("jssecacerts"); - ks.store(out, passphrase); - out.close(); - - System.out.println(); - System.out.println(cert); - System.out.println(); - System.out.println - ("Added certificate to keystore 'jssecacerts' using alias '" - + alias + "'"); - } - - private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray(); - - private static String toHexString(byte[] bytes) { - StringBuilder sb = new StringBuilder(bytes.length * 3); - for (int b : bytes) { - b &= 0xff; - sb.append(HEXDIGITS[b >> 4]); - sb.append(HEXDIGITS[b & 15]); - sb.append(' '); - } - return sb.toString(); - } - - private static class SavingTrustManager implements X509TrustManager { - - private final X509TrustManager tm; - private X509Certificate[] chain; - - SavingTrustManager(X509TrustManager tm) { - this.tm = tm; - } - - public X509Certificate[] getAcceptedIssuers() { - throw new UnsupportedOperationException(); - } - - public void checkClientTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - throw new UnsupportedOperationException(); - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - this.chain = chain; - tm.checkServerTrusted(chain, authType); - } - } -}