From 065d2df5e1df70d21534c6cbda608dca5b7d500b Mon Sep 17 00:00:00 2001 From: tkellner Date: Mon, 1 Oct 2012 08:30:37 +0000 Subject: Configuration Changes git-svn-id: https://svn.iaik.tugraz.at/svn/egiz/prj/current/12PDF-OVER-4.0@12530 3a0b52a2-8410-0410-bc02-ff6273a87459 --- .../gui/workflow/states/ConfigurationUIState.java | 93 ++++++++ .../pdfover/gui/workflow/states/ErrorState.java | 6 +- .../pdfover/gui/workflow/states/LocalBKUState.java | 2 + .../gui/workflow/states/MobileBKUState.java | 12 +- .../workflow/states/PrepareConfigurationState.java | 237 +++++++++++++++++++-- .../states/mobilebku/ASITTrustManager.java | 179 +++++++++++++++- .../workflow/states/mobilebku/ATrustHelper.java | 112 ++++++++-- .../states/mobilebku/TrustedSocketFactory.java | 4 +- 8 files changed, 597 insertions(+), 48 deletions(-) create mode 100644 trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/ConfigurationUIState.java (limited to 'trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states') diff --git a/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/ConfigurationUIState.java b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/ConfigurationUIState.java new file mode 100644 index 00000000..4b468ad8 --- /dev/null +++ b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/ConfigurationUIState.java @@ -0,0 +1,93 @@ +/* + * Copyright 2012 by A-SIT, Secure Information Technology Center Austria + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://joinup.ec.europa.eu/software/page/eupl + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + */ +package at.asit.pdfover.gui.workflow.states; + +// Imports +import org.eclipse.swt.SWT; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import at.asit.pdfover.gui.composites.ConfigurationComposite; +import at.asit.pdfover.gui.workflow.StateMachine; +import at.asit.pdfover.gui.workflow.Status; + +/** + * + */ +public class ConfigurationUIState extends State { + /** + * SLF4J Logger instance + **/ + private static final Logger log = LoggerFactory + .getLogger(ConfigurationUIState.class); + + + private ConfigurationComposite configurationComposite = null; + + private ConfigurationComposite getConfigurationComposite() { + if (this.configurationComposite == null) { + this.configurationComposite = + this.stateMachine.getGUIProvider().createComposite(ConfigurationComposite.class, SWT.RESIZE, this); + this.configurationComposite.setConfigManipulator(this.stateMachine.getConfigManipulator()); + } + + return this.configurationComposite; + } + + /** + * @param stateMachine + */ + public ConfigurationUIState(StateMachine stateMachine) { + super(stateMachine); + } + + + /* (non-Javadoc) + * @see at.asit.pdfover.gui.workflow.states.State#run() + */ + @Override + public void run() { + Status status = this.stateMachine.getStatus(); + + ConfigurationComposite config = this.getConfigurationComposite(); + + this.stateMachine.getGUIProvider().display(config); + + if(config.isUserDone()) + { + this.setNextState(status.getPreviousState()); + } + } + + + /* (non-Javadoc) + * @see at.asit.pdfover.gui.workflow.states.State#cleanUp() + */ + @Override + public void cleanUp() { + if(this.configurationComposite != null) + this.configurationComposite.dispose(); + } + + + /* (non-Javadoc) + * @see at.asit.pdfover.gui.workflow.states.State#updateMainWindowBehavior() + */ + @Override + public void updateMainWindowBehavior() { + // Leave the state as it is + } + +} diff --git a/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/ErrorState.java b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/ErrorState.java index 47485a0c..af648dfd 100644 --- a/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/ErrorState.java +++ b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/ErrorState.java @@ -22,7 +22,6 @@ import org.slf4j.LoggerFactory; import at.asit.pdfover.gui.composites.ErrorComposite; import at.asit.pdfover.gui.workflow.StateMachine; -import at.asit.pdfover.gui.workflow.Status; /** * @@ -67,8 +66,6 @@ public class ErrorState extends State { */ @Override public void run() { - Status status = this.stateMachine.getStatus(); - ErrorComposite errorComposite = this.getComposite(); if(this.exception != null && !errorComposite.isUserOk()) { @@ -94,7 +91,8 @@ public class ErrorState extends State { */ @Override public void cleanUp() { - // TODO + if (this.errorComposite != null) + this.errorComposite.dispose(); } /* (non-Javadoc) diff --git a/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/LocalBKUState.java b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/LocalBKUState.java index deec44dd..ca0e164c 100644 --- a/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/LocalBKUState.java +++ b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/LocalBKUState.java @@ -121,6 +121,8 @@ public class LocalBKUState extends State { } catch (Exception e) { log.error("SignLocalBKUThread: ", e); //$NON-NLS-1$ + // TODO: Is local BKU running? + this.state.threadException = e; } finally { this.state.stateMachine.invokeUpdate(); } diff --git a/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/MobileBKUState.java b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/MobileBKUState.java index 25df5b7e..234cd215 100644 --- a/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/MobileBKUState.java +++ b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/MobileBKUState.java @@ -199,7 +199,7 @@ public class MobileBKUState extends State { postCredentialsThread.start(); } else { - // We need at least number of password => show UI! + // We need number and password => show UI! // set possible error message ui.setErrorMessage(mobileStatus.getErrorMessage()); @@ -257,7 +257,12 @@ public class MobileBKUState extends State { */ @Override public void cleanUp() { - // No composite - no cleanup necessary + if(this.mobileBKUEnterNumberComposite != null) + this.mobileBKUEnterNumberComposite.dispose(); + if(this.mobileBKUEnterTANComposite != null) + this.mobileBKUEnterTANComposite.dispose(); + if(this.waitingComposite != null) + this.waitingComposite.dispose(); } /* @@ -280,6 +285,9 @@ public class MobileBKUState extends State { return this.getClass().getName(); } + /** + * invoke state machine update in main thread + */ public void invokeUpdate() { this.stateMachine.invokeUpdate(); } diff --git a/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/PrepareConfigurationState.java b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/PrepareConfigurationState.java index 2a71890d..b4b05318 100644 --- a/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/PrepareConfigurationState.java +++ b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/PrepareConfigurationState.java @@ -16,12 +16,28 @@ package at.asit.pdfover.gui.workflow.states; //Imports +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import at.asit.pdfover.gui.cliarguments.ArgumentHandler; +import at.asit.pdfover.gui.cliarguments.BKUArgument; +import at.asit.pdfover.gui.cliarguments.ConfigFileArgument; +import at.asit.pdfover.gui.cliarguments.HelpArgument; +import at.asit.pdfover.gui.cliarguments.PhoneNumberArgument; +import at.asit.pdfover.gui.exceptions.InitializationException; +import at.asit.pdfover.gui.workflow.ConfigManipulator; import at.asit.pdfover.gui.workflow.StateMachine; +import at.asit.pdfover.signator.BKUs; import at.asit.pdfover.signator.Signator; - +import at.asit.pdfover.signator.SignaturePosition; /** * Starting state of workflow proccess @@ -30,35 +46,222 @@ import at.asit.pdfover.signator.Signator; */ public class PrepareConfigurationState extends State { + /** + * Regex for parsing signature position + */ + public static final String SIGN_POS_REGEX = "(x=(\\d\\.?\\d?);y=(\\d\\.?\\d?);p=(\\d))|(auto)|(x=(\\d\\.?\\d?);y=(\\d\\.?\\d?))"; //$NON-NLS-1$ + /** * @param stateMachine */ public PrepareConfigurationState(StateMachine stateMachine) { super(stateMachine); + this.handler = new ArgumentHandler(this.stateMachine); + this.handler.addCLIArgument(new HelpArgument()); + this.handler.addCLIArgument(new BKUArgument()); + this.handler.addCLIArgument(new PhoneNumberArgument()); + + // adding config file argument to this handler so it appears in help + this.handler.addCLIArgument(new ConfigFileArgument()); + + this.configFilehandler = new ArgumentHandler(this.stateMachine); + this.configFilehandler.addCLIArgument(new ConfigFileArgument()); } + private ArgumentHandler handler; + + private ArgumentHandler configFilehandler; + /** * SFL4J Logger instance **/ - @SuppressWarnings("unused") private static final Logger log = LoggerFactory .getLogger(PrepareConfigurationState.class); + private void initializeFromConfigurationFile(String filename) + throws InitializationException { + try { + Properties config = new Properties(); + + try { + config.load(new FileInputStream(filename)); + } catch (FileNotFoundException ex) { + if (filename.equals(ConfigManipulator.DEFAULT_CONFIG_FILE)) { + // we only check for resource config file if it is the + // default value! + try { + InputStream is = this.getClass().getResourceAsStream( + "/" + filename); //$NON-NLS-1$ + config.load(is); + } catch (Exception eex) { + throw ex; + } + } else { + throw ex; + } + } + + // Load ok ... + ConfigManipulator configManipulator = this.stateMachine + .getConfigManipulator(); + + // Set Emblem + configManipulator.setDefaultEmblem(config + .getProperty(ConfigManipulator.EMBLEM_CONFIG)); + + // Set Mobile Phone Number + configManipulator.setDefaultMobileNumber(config + .getProperty(ConfigManipulator.MOBILE_NUMBER_CONFIG)); + + // Set Proxy Host + configManipulator.setProxyHost(config + .getProperty(ConfigManipulator.PROXY_HOST_CONFIG)); + + // Set Proxy Port + String proxyPortString = config + .getProperty(ConfigManipulator.PROXY_PORT_CONFIG); + + if (proxyPortString != null && !proxyPortString.trim().equals("")) { //$NON-NLS-1$ + int port = Integer.parseInt(proxyPortString); + + if (port > 0 && port <= 0xFFFF) { + configManipulator.setProxyPort(port); + } else { + log.warn("Proxy port is out of range!: " + port); //$NON-NLS-1$ + } + } + + // Set Default BKU + String bkuString = config.getProperty(ConfigManipulator.BKU_CONFIG); + + BKUs defaultBKU = BKUs.NONE; + + try { + defaultBKU = BKUs.valueOf(bkuString); + } catch (IllegalArgumentException ex) { + log.error("Invalid BKU config value " + bkuString + " using none!"); //$NON-NLS-1$ //$NON-NLS-2$ + defaultBKU = BKUs.NONE; + } catch (NullPointerException ex) { + log.error("Invalid BKU config value " + bkuString + " using none!"); //$NON-NLS-1$ //$NON-NLS-2$ + defaultBKU = BKUs.NONE; + } + + configManipulator.setDefaultBKU(defaultBKU); + + // Set Signature Position + String signaturePosition = config + .getProperty(ConfigManipulator.SIGNATURE_POSITION_CONFIG); + + SignaturePosition position = null; + + if (signaturePosition != null + && !signaturePosition.trim().equals("")) { //$NON-NLS-1$ + + signaturePosition = signaturePosition.trim().toLowerCase(); + + Pattern pattern = Pattern.compile(SIGN_POS_REGEX); + + Matcher matcher = pattern.matcher(signaturePosition); + + if (matcher.matches()) { + if (matcher.groupCount() == 8) { + if (matcher.group(1) != null) { + // we have format: x=..;y=..;p=... + try { + // group 2 = x value + float x = Float.parseFloat(matcher.group(2)); + + // group 3 = y value + float y = Float.parseFloat(matcher.group(3)); + + // group 4 = p value + int p = Integer.parseInt(matcher.group(3)); + + position = new SignaturePosition(x, y, p); + } catch (NumberFormatException ex) { + log.error( + "Signature Position read from config failed: Not a valid number", ex); //$NON-NLS-1$ + } + } else if (matcher.group(5) != null) { + // we have format auto + position = new SignaturePosition(); + } else if (matcher.group(6) != null) { + // we have format x=...;y=...; + // group 7 = x value + float x = Float.parseFloat(matcher.group(7)); + + // group 8 = y value + float y = Float.parseFloat(matcher.group(8)); + + position = new SignaturePosition(x, y); + } + } else { + log.error("Signature Position read from config failed: wrong group Count!"); //$NON-NLS-1$ + } + } else { + log.error("Signature Position read from config failed: not matching string"); //$NON-NLS-1$ + } + + } + + configManipulator.setDefaultSignaturePosition(position); + + } catch (IOException ex) { + throw new InitializationException( + "Failed to read configuration from config file", ex); //$NON-NLS-1$ + } + } + + private void initializeFromArguments(String[] args, ArgumentHandler handler) + throws InitializationException { + handler.handleArguments(args); + + if (handler.IsRequireExit()) { + this.stateMachine.exit(); + } + } + @Override public void run() { - // TODO: Read config file and command line arguments - // Set usedSignerLib ... - this.stateMachine.getPDFSigner().setUsedPDFSignerLibrary(Signator.Signers.PDFAS); - - // Create PDF Signer - this.stateMachine.getStatus().setBKU(this.stateMachine.getConfigProvider().getDefaultBKU()); - - this.stateMachine.getStatus().setSignaturePosition(this.stateMachine.getConfigProvider().getDefaultSignaturePosition()); - - this.setNextState(new OpenState(this.stateMachine)); + // Read config file + try { + // Read cli arguments with for config file! + this.initializeFromArguments(this.stateMachine.getCmdArgs(), + this.configFilehandler); + + // initialize from config file + this.initializeFromConfigurationFile(this.stateMachine + .getConfigProvider().getConfigurationFile()); + + // Read cli arguments + this.initializeFromArguments(this.stateMachine.getCmdArgs(), + this.handler); + + // Set usedSignerLib ... + this.stateMachine.getPDFSigner().setUsedPDFSignerLibrary( + Signator.Signers.PDFAS); + + // Create PDF Signer + this.stateMachine.getStatus().setBKU( + this.stateMachine.getConfigProvider().getDefaultBKU()); + + this.stateMachine.getStatus().setSignaturePosition( + this.stateMachine.getConfigProvider() + .getDefaultSignaturePosition()); + + this.setNextState(new OpenState(this.stateMachine)); + + } catch (InitializationException e) { + log.error("Failed to initialize: ", e); //$NON-NLS-1$ + ErrorState error = new ErrorState(this.stateMachine); + error.setException(e); + this.setNextState(error); + } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see at.asit.pdfover.gui.workflow.states.State#cleanUp() */ @Override @@ -66,16 +269,18 @@ public class PrepareConfigurationState extends State { // No composite - no cleanup necessary } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see at.asit.pdfover.gui.workflow.states.State#setMainWindowBehavior() */ @Override public void updateMainWindowBehavior() { - //no behavior necessary yet + // no behavior necessary yet } @Override - public String toString() { + public String toString() { return this.getClass().getName(); } } diff --git a/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/mobilebku/ASITTrustManager.java b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/mobilebku/ASITTrustManager.java index 2428ef65..6f557bc6 100644 --- a/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/mobilebku/ASITTrustManager.java +++ b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/mobilebku/ASITTrustManager.java @@ -16,13 +16,22 @@ package at.asit.pdfover.gui.workflow.states.mobilebku; // Imports +import java.security.KeyStore; import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; - +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.apache.commons.lang.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; /** * @@ -34,31 +43,181 @@ public class ASITTrustManager implements X509TrustManager { private static final Logger log = LoggerFactory .getLogger(ASITTrustManager.class); - /* (non-Javadoc) - * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], java.lang.String) + /* + * The default X509TrustManager returned by SunX509. We'll delegate + * decisions to it, and fall back to the logic in this class if the default + * X509TrustManager doesn't trust it. + */ + X509TrustManager sunJSSEX509TrustManager; + + /** + * Trust Manager for A-Trust Certificates + */ + X509TrustManager atrustTrustManager; + + /** + * Constructs the TrustManager + * + * @throws Exception + */ + public ASITTrustManager() throws Exception { + // create a "default" JSSE X509TrustManager. + + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); //$NON-NLS-1$ + tmf.init((KeyStore) null); + + TrustManager tms[] = tmf.getTrustManagers(); + + /* + * Iterate over the returned trustmanagers, look for an instance of + * X509TrustManager. If found, use that as our "default" trust manager. + */ + for (int i = 0; i < tms.length; i++) { + if (tms[i] instanceof X509TrustManager) { + this.sunJSSEX509TrustManager = (X509TrustManager) tms[i]; + break; + } + } + + /* + * A-Trust Certificates + */ + + KeyStore atrustKeyStore = KeyStore.getInstance(KeyStore + .getDefaultType()); + + atrustKeyStore.load(null); + + String usedCertificates = "/certificates/used_certificates.xml"; //$NON-NLS-1$ + + Document doc = DocumentBuilderFactory.newInstance() + .newDocumentBuilder() + .parse(this.getClass().getResourceAsStream(usedCertificates)); + + Node certificates = doc.getFirstChild(); + + if (!certificates.getNodeName().equals("certificates")) { //$NON-NLS-1$ + throw new Exception( + "Used certificates xml is invalid! no certificates node"); //$NON-NLS-1$ + } + + NodeList certificateList = certificates.getChildNodes(); + + for (int i = 0; i < certificateList.getLength(); i++) { + try { + + Node certificateNode = certificateList.item(i); + + if (certificateNode.getNodeName().equals("#text")) { //$NON-NLS-1$ + continue; // Ignore dummy text node .. + } + + if (!certificateNode.getNodeName().equals("certificate")) { //$NON-NLS-1$ + log.warn("Ignoring XML node: " + certificateNode.getNodeName()); //$NON-NLS-1$ + continue; + } + + String certResource = "/certificates/" + certificateNode.getTextContent() + ".crt"; //$NON-NLS-1$ //$NON-NLS-2$ + + X509Certificate cert = (X509Certificate) CertificateFactory + .getInstance("X509"). //$NON-NLS-1$ + generateCertificate( + this.getClass().getResourceAsStream( + certResource)); + + atrustKeyStore.setCertificateEntry(certificateNode.getTextContent(), cert); + + log.debug("Loaded certificate : " + certResource); //$NON-NLS-1$ + + } catch (Exception ex) { + log.error("Failed to load certificate [" + "]", ex); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + tmf.init(atrustKeyStore); + + tms = tmf.getTrustManagers(); + + /* + * Iterate over the returned trustmanagers, look for an instance of + * X509TrustManager. If found, use that as our "default" trust manager. + */ + for (int i = 0; i < tms.length; i++) { + if (tms[i] instanceof X509TrustManager) { + this.atrustTrustManager = (X509TrustManager) tms[i]; + break; + } + } + + if (this.sunJSSEX509TrustManager != null + && this.atrustTrustManager != null) { + return; + } + + /* + * Find some other way to initialize, or else we have to fail the + * constructor. + */ + throw new Exception("Couldn't initialize ASITTrustManager"); //$NON-NLS-1$ + } + + /* + * (non-Javadoc) + * + * @see + * javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert. + * X509Certificate[], java.lang.String) */ @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { - // Ignore client certificates ... + try { + this.atrustTrustManager.checkServerTrusted(arg0, arg1); + } catch (CertificateException ex) { + try { + this.sunJSSEX509TrustManager.checkClientTrusted(arg0, arg1); + } catch (CertificateException ex2) { + log.info("checkClientTrusted: ", ex2); //$NON-NLS-1$ + throw ex2; + } + } } - /* (non-Javadoc) - * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], java.lang.String) + /* + * (non-Javadoc) + * + * @see + * javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert. + * X509Certificate[], java.lang.String) */ @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { - // TODO: Check trusted server certificate! + try { + this.atrustTrustManager.checkServerTrusted(arg0, arg1); + } catch (CertificateException ex) { + try { + this.sunJSSEX509TrustManager.checkServerTrusted(arg0, arg1); + } catch (CertificateException ex2) { + log.info("checkServerTrusted: ", ex2); //$NON-NLS-1$ + throw ex2; + } + } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() */ @Override public X509Certificate[] getAcceptedIssuers() { - // TODO: Build accepted issuers - return null; + + X509Certificate[] default_certs = this.sunJSSEX509TrustManager.getAcceptedIssuers(); + + X509Certificate[] atrust_cerst = this.atrustTrustManager.getAcceptedIssuers(); + + return (X509Certificate[]) ArrayUtils.addAll(default_certs, atrust_cerst); } } diff --git a/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/mobilebku/ATrustHelper.java b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/mobilebku/ATrustHelper.java index c9254317..1ea265ad 100644 --- a/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/mobilebku/ATrustHelper.java +++ b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/mobilebku/ATrustHelper.java @@ -16,9 +16,18 @@ package at.asit.pdfover.gui.workflow.states.mobilebku; // Imports +import java.util.regex.Matcher; +import java.util.regex.Pattern; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import at.asit.pdfover.gui.composites.MobileBKUEnterNumberComposite; +import at.asit.pdfover.gui.exceptions.InvalidNumberException; +import at.asit.pdfover.gui.exceptions.InvalidPasswordException; +import at.asit.pdfover.gui.exceptions.PasswordTooLongException; +import at.asit.pdfover.gui.exceptions.PasswordTooShortException; + /** * */ @@ -30,36 +39,111 @@ public class ATrustHelper { .getLogger(ATrustHelper.class); /** + * Regular expression for mobile phone numbers: this allows the entrance of + * mobile numbers in the following formats: + * + * +(countryCode)99999999999 00(countryCode)99999999999 099999999999 + * 1030199999999999 (A-Trust Test bku) + */ + private static final String NUMBER_REGEX = "^((\\+[\\d]{2})|(00[\\d]{2})|(0)|(10301))([1-9][\\d]+)$"; //$NON-NLS-1$ + + /** + * Extracts a substring from data starting after start and ending with end + * * @param data + * the whole data string * @param start + * the start marker * @param end - * @return + * the end marker + * @return the substring * @throws Exception */ - public static String extractTag(String data, String start, String end) throws Exception { + public static String extractTag(String data, String start, String end) + throws Exception { int startidx = data.indexOf(start); - if(startidx > 0) { - startidx = startidx+start.length(); + if (startidx > 0) { + startidx = startidx + start.length(); int endidx = data.indexOf(end, startidx); - if(endidx > startidx) { + if (endidx > startidx) { return data.substring(startidx, endidx); - } else { - // TODO: throw exception - throw new Exception("end tag not available!"); } - } else { - // TODO: throw exception - throw new Exception("start tag not available!"); + // TODO: throw proper exception + log.error("extracting Tag: end tag not valid!: " + start + " ... " + end); //$NON-NLS-1$//$NON-NLS-2$ + throw new Exception("end tag not available!"); //$NON-NLS-1$ } + // TODO: throw proper exception + log.error("extracting Tag: start tag not valid!: " + start + " ... " + end); //$NON-NLS-1$//$NON-NLS-2$ + throw new Exception("start tag not available!"); //$NON-NLS-1$ } - + + /** + * Validates the Mobile phone number + * + * @param number + * @return the normalized Phone number + * @throws InvalidNumberException + */ + public static String normalizeMobileNumber(String number) + throws InvalidNumberException { + // Verify number and normalize + + // Compile and use regular expression + Pattern pattern = Pattern.compile(NUMBER_REGEX); + Matcher matcher = pattern.matcher(number); + + if (!matcher.find()) { + throw new InvalidNumberException(); + } + + if (matcher.groupCount() != 6) { + throw new InvalidNumberException(); + } + + String countryCode = matcher.group(1); + + String normalNumber = matcher.group(6); + + if (countryCode.equals("10301")) { //$NON-NLS-1$ + // A-Trust Testnumber! Don't change + return number; + } + + countryCode = countryCode.replace("00", "+"); //$NON-NLS-1$ //$NON-NLS-2$ + + if (countryCode.equals("0")) { //$NON-NLS-1$ + countryCode = "+43"; //$NON-NLS-1$ + } + + return countryCode + normalNumber; + } + + /** + * Validate given Password for Mobile BKU + * + * @param password + * @throws InvalidPasswordException + */ + public static void validatePassword(String password) + throws InvalidPasswordException { + if (password.length() < 6 || password.length() > 20) { + if (password.length() < 6) { + throw new PasswordTooShortException(); + } + throw new PasswordTooLongException(); + } + } + /** + * Removes file extension from URL + * * @param query - * @return + * the url string + * @return the stripped url */ public static String stripQueryString(String query) { int pathidx = query.lastIndexOf('/'); - if(pathidx > 0) { + if (pathidx > 0) { return query.substring(0, pathidx); } return query; diff --git a/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/mobilebku/TrustedSocketFactory.java b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/mobilebku/TrustedSocketFactory.java index bfe84605..5e9d8159 100644 --- a/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/mobilebku/TrustedSocketFactory.java +++ b/trunk/pdf-over-gui/src/main/java/at/asit/pdfover/gui/workflow/states/mobilebku/TrustedSocketFactory.java @@ -46,8 +46,8 @@ public class TrustedSocketFactory implements ProtocolSocketFactory { private static final Logger log = LoggerFactory .getLogger(TrustedSocketFactory.class); - private static SSLSocketFactory getFactory() throws NoSuchAlgorithmException, - KeyManagementException { + private SSLSocketFactory getFactory() throws NoSuchAlgorithmException, + KeyManagementException, Exception { SSLContext sslContext = SSLContext.getInstance("TLS"); //$NON-NLS-1$ sslContext.init(null, new TrustManager[] { new ASITTrustManager() }, new java.security.SecureRandom()); -- cgit v1.2.3