Merge remote-tracking branch 'origin/sni'

This commit is contained in:
Peter Hormanns 2015-11-25 17:00:39 +01:00
commit 74d4bef786
20 changed files with 28 additions and 1303 deletions

View File

@ -269,11 +269,20 @@ public class DomainProcessorFactory implements EntityProcessorFactory {
ifOption(templateVars, query, "multiviews", "+MultiViews", "-MultiViews"); ifOption(templateVars, query, "multiviews", "+MultiViews", "-MultiViews");
ifOption(templateVars, query, "htdocsfallback", Boolean.TRUE, Boolean.FALSE); ifOption(templateVars, query, "htdocsfallback", Boolean.TRUE, Boolean.FALSE);
final Processor domSetupProcessor = new CompoundProcessor( final Processor domSetupProcessor = new CompoundProcessor(
new ShellProcessor("export PEMS_DIR=/etc/apache2/pems-enabled/" + dom.getUser().getName() + " && " new CreateFileProcessor("/de/hsadmin/mods/dom/openssl-sna.cnf", templateVars, dom, "/tmp/openssl-sna.cnf", "root", "root", "644", true),
+ "mkdir -p $PEMS_DIR/ && " new ShellProcessor("export PEMS_DIR=/etc/apache2/pems-generated && "
+ "mkdir -p $PEMS_DIR && "
+ "cd $PEMS_DIR && " + "cd $PEMS_DIR && "
+ "( ls " + domName + ".crt || ( echo \"\" > " + domName + ".chain && " + "( 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 + "' ) ) &&" + "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 + "*"), + "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 CreateFileProcessor("/de/hsadmin/mods/dom/apache-vhost.vm", templateVars, dom, "/etc/apache2/sites-available/" + domName + ".tmp", "root", "root", "644", true),
new ShellProcessor( new ShellProcessor(

View File

@ -90,9 +90,9 @@
#end #end
SSLEngine On SSLEngine On
SSLCertificateFile /etc/apache2/pems-enabled/${dom.user.name}/${dom.name}.crt SSLCertificateFile /etc/apache2/pems-enabled/${dom.name}.crt
SSLCertificateKeyFile /etc/apache2/pems-enabled/${dom.user.name}/${dom.name}.key SSLCertificateKeyFile /etc/apache2/pems-enabled/${dom.name}.key
SSLCertificateChainFile /etc/apache2/pems-enabled/${dom.user.name}/${dom.name}.chain SSLCertificateChainFile /etc/apache2/pems-enabled/${dom.name}.chain
DocumentRoot /home/doms/${dom.name}/htdocs-ssl DocumentRoot /home/doms/${dom.name}/htdocs-ssl

View File

@ -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}

View File

@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="resource"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
<classpathentry kind="lib" path="/usr/share/java/commons-cli.jar"/>
<classpathentry kind="lib" path="/usr/share/java/ws-commons-util.jar"/>
<classpathentry kind="lib" path="/usr/share/java/jline.jar"/>
<classpathentry kind="lib" path="/usr/share/java/xmlrpc-client.jar"/>
<classpathentry kind="lib" path="/usr/share/java/xmlrpc-common.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

2
hsarjcli/.gitignore vendored
View File

@ -1,2 +0,0 @@
/build
/bin

View File

@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>hsarjcli</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@ -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

View File

@ -1,60 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="hsarweb" default="jar">
<property name="build.home" value="${basedir}/build" />
<property name="lib.home" value="/usr/share/java" />
<property name="conf.home" value="${basedir}/conf" />
<property name="src.home" value="${basedir}/src" />
<property name="resource.home" value="${basedir}/resource" />
<property name="test.home" value="${basedir}/test" />
<property name="dist.home" value="${basedir}/dist" />
<property file="${user.home}/.hsar.ant.properties" />
<!-- Optionen für Java-Compiler-->
<property name="compile.debug" value="true" />
<property name="compile.deprecation" value="true" />
<property name="compile.optimize" value="true" />
<path id="cp">
<fileset dir="${lib.home}">
<include name="jline.jar"/>
<include name="ws-commons-util.jar"/>
<include name="xmlrpc-client.jar"/>
<include name="xmlrpc-common.jar"/>
<include name="commons-cli.jar"/>
</fileset>
</path>
<target name="clean" description="aufräumen">
<delete dir="${build.home}" />
<delete dir="${dist.home}" />
</target>
<target name="jar" depends="compile">
<copy todir="${build.home}/cls">
<fileset dir="${resource.home}" />
</copy>
<jar destfile="build/hsscript.jar" basedir="build/cls">
<manifest>
<attribute name="Main-Class" value="de.hsadmin.jscli.Main"/>
<attribute name="Class-Path" value="/usr/share/java/commons-cli.jar /usr/share/java/jline.jar /usr/share/java/ws-commons-util.jar /usr/share/java/xmlrpc-client.jar /usr/share/java/xmlrpc-common.jar"/>
</manifest>
</jar>
</target>
<target name="compile" description="compilieren">
<mkdir dir="${build.home}" />
<mkdir dir="${build.home}/cls" />
<javac
srcdir="${src.home}"
destdir="${build.home}/cls"
classpathref="cp"
debug="${compile.debug}"
deprecation="${compile.deprecation}"
optimize="${compile.optimize}"
encoding="UTF8"
includeantruntime="false" />
</target>
</project>

View File

@ -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<unixusers.length; idx++) {
if (unixusers[idx]['name'].length() > 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<domains.length; idx++) {
if ( ! (domains[idx]['name'] == pacname + '.hostsharing.net')) {
file.write('domain.add({set:{\n');
file.write('name: "' + domains[idx]['name'] + '",\n');
file.write('user: "' + domains[idx]['user'] + '"\n');
file.write('}});\n');
}
file.write('domain.update({where:{\n');
file.write('name: "' + domains[idx]['name'] + '"\n');
file.write('},set:{\n');
file.write('domainoptions: [\n');
if (domains[idx]['domainoptions']) {
for (jdx=0; jdx<domains[idx]['domainoptions'].length; jdx++) {
file.write(' "' + domains[idx]['domainoptions'][jdx] + '",\n');
}
}
file.write(' ]\n');
file.write('}});\n');
}
// Alias
var aliases = emailalias.search();
for (idx=0; idx<aliases.length; idx++) {
file.write('emailalias.add({set:{\n');
file.write('name: "' + aliases[idx]['name'] + '",\n');
file.write('target: [\n');
if (aliases[idx]['target']) {
for (jdx=0; jdx<aliases[idx]['target'].length; jdx++) {
file.write(' "' + aliases[idx]['target'][jdx] + '",\n');
}
}
file.write(' ]\n');
file.write('}});\n');
}
// E-Mail Address
var addresses = emailaddress.search();
for (idx=0; idx<addresses.length; idx++) {
if (addresses[idx]['domain'] == pacname + '.hostsharing.net') {
file.write('emailaddress.update({where:{\n');
file.write('localpart: "' + addresses[idx]['localpart'] + '",\n');
file.write('domain: "' + addresses[idx]['domain'] + '",\n');
if (addresses[idx]['subdomain']) {
file.write('subdomain: "' + addresses[idx]['subdomain'] + '":q\n');
}
file.write('},set:{\n');
file.write('target: [\n');
if (addresses[idx]['target']) {
for (jdx=0; jdx<addresses[idx]['target'].length; jdx++) {
file.write(' \'' + addresses[idx]['target'][jdx] + '\',\n');
}
}
file.write(' ]\n');
file.write('}});\n');
} else {
var locpart = addresses[idx]['localpart'];
var subdom = addresses[idx]['subdomain'];
if (subdom == null && ('abuse' == locpart || 'postmaster' == locpart || 'webmaster' == locpart)) {
file.write('emailaddress.update({where:{\n');
file.write('localpart: "' + addresses[idx]['localpart'] + '",\n');
file.write('domain: "' + addresses[idx]['domain'] + '",\n');
if (addresses[idx]['subdomain']) {
file.write('subdomain: "' + addresses[idx]['subdomain'] + '":q\n');
}
file.write('},set:{\n');
file.write('target: [\n');
if (addresses[idx]['target']) {
for (jdx=0; jdx<addresses[idx]['target'].length; jdx++) {
file.write(' "' + addresses[idx]['target'][jdx] + '",\n');
}
}
file.write(' ]\n');
file.write('}});\n');
} else {
file.write('emailaddress.add({set:{\n');
file.write('localpart: "' + addresses[idx]['localpart'] + '",\n');
file.write('domain: "' + addresses[idx]['domain'] + '",\n');
if (addresses[idx]['subdomain']) {
file.write('subdomain: "' + addresses[idx]['subdomain'] + '",\n');
}
file.write('target: [\n');
if (addresses[idx]['target']) {
for (jdx=0; jdx<addresses[idx]['target'].length; jdx++) {
file.write(' "' + addresses[idx]['target'][jdx] + '",\n');
}
}
file.write(' ]\n');
file.write('}});\n');
}
}
}
// PostgreSQL
var pguserold = postgresqluser.search();
for (idx=0; idx<pguserold.length; idx++) {
file.write('postgresqluser.add({set:{\n');
file.write('name: "' + pguserold[idx]['name'] + '",\n');
file.write('password: "' + password + '"\n');
file.write('}});\n');
}
var pgdbold = postgresqldb.search();
for (idx=0; idx<pgdbold.length; idx++) {
file.write('postgresqldb.add({set:{\n');
file.write('name: "' + pgdbold[idx]['name'] + '",\n');
file.write('owner: "' + pgdbold[idx]['owner'] + '",\n');
file.write('encoding: "' + pgdbold[idx]['encoding'] + '"\n');
file.write('}});\n');
pgsqldump(pacname, pgdbold[idx]['name']);
}
// MySQL
var myuserold = mysqluser.search();
for (idx=0; idx<myuserold.length; idx++) {
file.write('mysqluser.add({set:{\n');
file.write('name: "' + myuserold[idx]['name'] + '",\n');
file.write('password: "' + password + '"\n');
file.write('}});\n');
}
var mydbold = mysqldb.search();
for (idx=0; idx<mydbold.length; idx++) {
file.write('mysqldb.add({set:{\n');
file.write('name: "' + mydbold[idx]['name'] + '",\n');
file.write('owner: "' + mydbold[idx]['owner'] + '",\n');
file.write('encoding: "' + mydbold[idx]['encoding'] + '"\n');
file.write('}});\n');
mysqldump(pacname, mydbold[idx]['name']);
}
file.close();
shadowdump(pacname);
mysqlaclsdump(pacname);
pgsqlpasswddump(pacname);
} else {
print('run as pac-owner!\n');
}

View File

@ -1,80 +0,0 @@
package de.hsadmin.jscli;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import de.hsadmin.jscli.conf.CommandlineParser;
import de.hsadmin.jscli.console.ConsoleWrapper;
import de.hsadmin.jscli.json.JSONFormatter;
public class Main {
public static void main(String[] args) {
final ConsoleWrapper console = new ConsoleWrapper();
final JSONFormatter formatter = new JSONFormatter();
try {
final CommandlineParser cmdParser = new CommandlineParser(args);
final String runAs = cmdParser.getRunAs();
console.open(runAs + "@hsadmin> ");
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);
}
}
}

View File

@ -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<XmlRpcClient> clientList;
private final Map<String, XmlRpcClient> clientMap;
public RpcClient(final CASTicketProvider tgt) throws JSCliException {
clientList = new ArrayList<XmlRpcClient>();
clientMap = new HashMap<String, XmlRpcClient>();
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<String> listMethods() throws JSCliException {
final List<String> methodList = new ArrayList<String>();
for (final XmlRpcClient client : clientList) {
final List<Object> 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<Object> execute(final XmlRpcClient client, final String method) throws JSCliException {
return execute(client, method, new ArrayList<Object>());
}
private List<Object> execute(final XmlRpcClient client, final String method, final List<?> params) throws JSCliException {
try {
final Object execute = client.execute(method, params);
final ArrayList<Object> list = new ArrayList<Object>();
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<Object> 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);
}
}
}

View File

@ -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<String> 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<String>();
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<String> 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);
}
}
}

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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));
}
}

View File

@ -1,9 +0,0 @@
package de.hsadmin.jscli.console;
import de.hsadmin.jscli.exception.JSCliException;
public interface PasswordReader {
String readPassword() throws JSCliException;
}

View File

@ -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);
}
}

View File

@ -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<String> 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);
}
}

View File

@ -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);
}
}
}