From d781f0e89f16c650f70cc47d1ed5c4da2673b4d1 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 11 Apr 2019 09:45:25 +0200 Subject: add EAAF module for authentication method based on Security-Layer 2.0 communication --- .../auth/sl20/utils/SL20JSONExtractorUtils.java | 353 +++++++++++++++++++++ 1 file changed, 353 insertions(+) create mode 100644 eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JSONExtractorUtils.java (limited to 'eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JSONExtractorUtils.java') diff --git a/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JSONExtractorUtils.java b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JSONExtractorUtils.java new file mode 100644 index 00000000..827b5970 --- /dev/null +++ b/eaaf_modules/eaaf_module_auth_sl20/src/main/java/at/gv/egiz/eaaf/modules/auth/sl20/utils/SL20JSONExtractorUtils.java @@ -0,0 +1,353 @@ +package at.gv.egiz.eaaf.modules.auth.sl20.utils; + +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.utils.URIBuilder; +import org.apache.log4j.Logger; +import org.jose4j.base64url.Base64Url; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + +import at.gv.egiz.eaaf.modules.auth.sl20.data.VerificationResult; +import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SL20Exception; +import at.gv.egiz.eaaf.modules.auth.sl20.exceptions.SLCommandoParserException; + +public class SL20JSONExtractorUtils { + private static final Logger log = Logger.getLogger(SL20JSONExtractorUtils.class); + private static JsonMapper mapper = new JsonMapper(); + + + /** + * Extract String value from JSON + * + * @param input + * @param keyID + * @param isRequired + * @return + * @throws SLCommandoParserException + */ + public static String getStringValue(JsonNode input, String keyID, boolean isRequired) throws SLCommandoParserException { + try { + JsonNode internal = getAndCheck(input, keyID, isRequired); + + if (internal != null) + return internal.asText(); + else + return null; + + } catch (SLCommandoParserException e) { + throw e; + + } catch (Exception e) { + throw new SLCommandoParserException("Can not extract String value with keyId: " + keyID, e); + + } + } + + /** + * Extract Boolean value from JSON + * + * @param input + * @param keyID + * @param isRequired + * @return + * @throws SLCommandoParserException + */ + public static boolean getBooleanValue(ObjectNode input, String keyID, boolean isRequired, boolean defaultValue) throws SLCommandoParserException { + try { + JsonNode internal = getAndCheck(input, keyID, isRequired); + + if (internal != null) + return internal.asBoolean(); + else + return defaultValue; + + } catch (SLCommandoParserException e) { + throw e; + + } catch (Exception e) { + throw new SLCommandoParserException("Can not extract Boolean value with keyId: " + keyID, e); + + } + } + + /** + * Extract JSONObject value from JSON + * + * @param input + * @param keyID + * @param isRequired + * @return + * @throws SLCommandoParserException + */ + public static JsonNode getJSONObjectValue(JsonNode input, String keyID, boolean isRequired) throws SLCommandoParserException { + try { + JsonNode internal = getAndCheck(input, keyID, isRequired); + + if (internal != null) + return internal; + else + return null; + + } catch (SLCommandoParserException e) { + throw e; + + } catch (Exception e) { + throw new SLCommandoParserException("Can not extract Boolean value with keyId: " + keyID, e); + + } + } + + /** + * Extract a List of String elements from a JSON element + * + * @param input + * @return + * @throws SLCommandoParserException + */ + public static List getListOfStringElements(JsonNode input) throws SLCommandoParserException { + List result = new ArrayList(); + if (input != null) { + if (input.isArray()) { + Iterator arrayIterator = input.iterator(); + while(arrayIterator.hasNext()) { + JsonNode next = arrayIterator.next(); + if (next.isTextual()) + result.add(next.asText()); + } + + } else if (input.isTextual()) { + result.add(input.asText()); + + } else { + log.warn("JSON Element IS NOT a JSON array or a JSON Primitive"); + throw new SLCommandoParserException("JSON Element IS NOT a JSON array or a JSON Primitive"); + + } + } + + return result; + } + + /** + * Extract Map of Key/Value pairs from a JSON Element + * + * @param input parent JSON object + * @param keyID KeyId of the child that should be parsed + * @param isRequired + * @return + * @throws SLCommandoParserException + */ + public static Map getMapOfStringElements(JsonNode input, String keyID, boolean isRequired) throws SLCommandoParserException { + JsonNode internal = getAndCheck(input, keyID, isRequired); + return getMapOfStringElements(internal); + + } + + /** + * Extract Map of Key/Value pairs from a JSON Element + * + * @param input + * @return + * @throws SLCommandoParserException + */ + public static Map getMapOfStringElements(JsonNode input) throws SLCommandoParserException { + Map result = new HashMap(); + + if (input != null) { + if (input.isArray()) { + Iterator arrayIterator = input.iterator(); + while(arrayIterator.hasNext()) { + JsonNode next = arrayIterator.next(); + Iterator> entry = next.fields(); + entitySetToMap(result, entry); + + } + + } else if (input.isObject()) { + Iterator> objectKeys = input.fields(); + entitySetToMap(result, objectKeys); + + } else + throw new SLCommandoParserException("JSON Element IS NOT a JSON array or a JSON object"); + + } + + return result; + } + + private static void entitySetToMap(Map result, Iterator> entry) { + while (entry.hasNext()) { + Entry el = entry.next(); + if (result.containsKey(el.getKey())) + log.info("Attr. Map already contains Element with Key: " + el.getKey() + ". Overwrite element ... "); + + result.put(el.getKey(), el.getValue().asText()); + + } + + } + + + public static JsonNode extractSL20Result(JsonNode command, IJOSETools decrypter, boolean mustBeEncrypted) throws SL20Exception { + JsonNode result = command.get(SL20Constants.SL20_COMMAND_CONTAINER_RESULT); + JsonNode encryptedResult = command.get(SL20Constants.SL20_COMMAND_CONTAINER_ENCRYPTEDRESULT); + + if (result == null && encryptedResult == null) + throw new SLCommandoParserException("NO result OR encryptedResult FOUND."); + + else if (encryptedResult == null && mustBeEncrypted) + throw new SLCommandoParserException("result MUST be signed."); + + else if (encryptedResult != null && encryptedResult.isTextual()) { + try { + return decrypter.decryptPayload(encryptedResult.asText()); + + } catch (Exception e) { + log.info("Can NOT decrypt SL20 result. Reason:" + e.getMessage()); + if (!mustBeEncrypted) { + log.warn("Decrypted results are disabled by configuration. Parse result in plain if it is possible"); + + //dummy code + try { + String[] signedPayload = encryptedResult.toString().split("\\."); + JsonNode payLoad = mapper.getMapper().readTree(new String(Base64.getUrlDecoder().decode(signedPayload[1]))); + return payLoad; + + } catch (Exception e1) { + log.debug("DummyCode FAILED, Reason: " + e1.getMessage() + " Ignore it ..."); + throw new SL20Exception(e.getMessage(), null, e); + + } + + } else + throw e; + + } + + } else if (result != null) { + return result; + + } else + throw new SLCommandoParserException("Internal build error"); + + + } + + /** + * Extract payLoad from generic transport container + * + * @param container + * @param joseTools + * @return + * @throws SLCommandoParserException + */ + public static VerificationResult extractSL20PayLoad(JsonNode container, IJOSETools joseTools, boolean mustBeSigned) throws SL20Exception { + + JsonNode sl20Payload = container.get(SL20Constants.SL20_PAYLOAD); + JsonNode sl20SignedPayload = container.get(SL20Constants.SL20_SIGNEDPAYLOAD); + + if (mustBeSigned && joseTools == null) + throw new SLCommandoParserException("'joseTools' MUST be set if 'mustBeSigned' is 'true'"); + + if (sl20Payload == null && sl20SignedPayload == null) + throw new SLCommandoParserException("NO payLoad OR signedPayload FOUND."); + + else if (sl20SignedPayload == null && mustBeSigned) + throw new SLCommandoParserException("payLoad MUST be signed."); + + else if (joseTools != null && sl20SignedPayload != null && sl20SignedPayload.isTextual()) { + return joseTools.validateSignature(sl20SignedPayload.asText()); + + } else if (sl20Payload != null) + return new VerificationResult(sl20Payload); + + else + throw new SLCommandoParserException("Internal build error"); + + + } + + + /** + * Extract generic transport container from httpResponse + * + * @param httpResp + * @return + * @throws SLCommandoParserException + */ + public static JsonNode getSL20ContainerFromResponse(HttpResponse httpResp) throws SLCommandoParserException { + try { + JsonNode sl20Resp = null; + if (httpResp.getStatusLine().getStatusCode() == 307) { + Header[] locationHeader = httpResp.getHeaders("Location"); + if (locationHeader == null) + throw new SLCommandoParserException("Find Redirect statuscode but not Location header"); + + String sl20RespString = new URIBuilder(locationHeader[0].getValue()).getQueryParams().get(0).getValue(); + sl20Resp = mapper.getMapper().readTree(Base64Url.encode((sl20RespString.getBytes()))); + + } else if (httpResp.getStatusLine().getStatusCode() == 200) { + if (!httpResp.getEntity().getContentType().getValue().startsWith("application/json")) + throw new SLCommandoParserException("SL20 response with a wrong ContentType: " + httpResp.getEntity().getContentType().getValue()); + sl20Resp = parseSL20ResultFromResponse(httpResp.getEntity()); + + } else if ( (httpResp.getStatusLine().getStatusCode() == 500) || + (httpResp.getStatusLine().getStatusCode() == 401) || + (httpResp.getStatusLine().getStatusCode() == 400) ) { + log.info("SL20 response with http-code: " + httpResp.getStatusLine().getStatusCode() + + ". Search for error message"); + sl20Resp = parseSL20ResultFromResponse(httpResp.getEntity()); + + + } else + throw new SLCommandoParserException("SL20 response with http-code: " + httpResp.getStatusLine().getStatusCode()); + + log.info("Find JSON object in http response"); + return sl20Resp; + + } catch (Exception e) { + throw new SLCommandoParserException("SL20 response parsing FAILED! Reason: " + e.getMessage(), e); + + } + } + + private static JsonNode parseSL20ResultFromResponse(HttpEntity resp) throws Exception { + if (resp != null && resp.getContent() != null) { + JsonNode sl20Resp = mapper.getMapper().readTree(new InputStreamReader(resp.getContent())); + + //TODO: check sl20Resp type like && sl20Resp.isJsonObject() + if (sl20Resp != null) { + return sl20Resp; + + } else + throw new SLCommandoParserException("SL2.0 can NOT parse to a JSON object"); + + + } else + throw new SLCommandoParserException("Can NOT find content in http response"); + + } + + + private static JsonNode getAndCheck(JsonNode input, String keyID, boolean isRequired) throws SLCommandoParserException { + JsonNode internal = input.get(keyID); + + if (internal == null && isRequired) + throw new SLCommandoParserException("REQUIRED Element with keyId: " + keyID + " does not exist"); + + return internal; + + } +} -- cgit v1.2.3