Search in sources :

Example 1 with PolicyLexiconParser

use of org.nhindirect.policy.PolicyLexiconParser in project nhin-d by DirectProject.

the class RESTSmtpAgentConfig method addPolicyToMap.

public void addPolicyToMap(Map<String, Collection<PolicyExpression>> policyMap, String domainName, CertPolicyGroupUse policyReltn) {
    // check to see if the domain is in the map
    Collection<PolicyExpression> policyExpressionCollection = policyMap.get(domainName);
    if (policyExpressionCollection == null) {
        policyExpressionCollection = new ArrayList<PolicyExpression>();
        policyMap.put(domainName, policyExpressionCollection);
    }
    final CertPolicy policy = policyReltn.getPolicy();
    final PolicyLexicon lexicon = policy.getLexicon();
    final InputStream inStr = new ByteArrayInputStream(policy.getPolicyData());
    try {
        // grab a parser and compile this policy
        final PolicyLexiconParser parser = PolicyLexiconParserFactory.getInstance(lexicon);
        policyExpressionCollection.add(parser.parse(inStr));
    } catch (PolicyParseException ex) {
        throw new SmtpAgentException(SmtpAgentError.InvalidConfigurationFormat, "Failed parse policy into policy expression: " + ex.getMessage(), ex);
    } finally {
        IOUtils.closeQuietly(inStr);
    }
}
Also used : PolicyLexicon(org.nhindirect.policy.PolicyLexicon) SmtpAgentException(org.nhindirect.gateway.smtp.SmtpAgentException) CertPolicy(org.nhindirect.config.model.CertPolicy) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) PolicyLexiconParser(org.nhindirect.policy.PolicyLexiconParser) PolicyExpression(org.nhindirect.policy.PolicyExpression) PolicyParseException(org.nhindirect.policy.PolicyParseException)

Example 2 with PolicyLexiconParser

use of org.nhindirect.policy.PolicyLexiconParser in project nhin-d by DirectProject.

the class PoliciesController method checkPolicyContent.

@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value = "/checkPolicyContent", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String checkPolicyContent(@RequestHeader(value = "X-Requested-With", required = false) String requestedWith, HttpServletResponse response, HttpServletRequest request, Object command) throws Exception {
    final org.nhindirect.policy.PolicyLexicon parseLexicon;
    String jsonResponse = "";
    String content = request.getParameter("content");
    String lexicon = "";
    if (log.isDebugEnabled()) {
        log.debug("Checking policy content for format and validation");
    }
    lexicon = request.getParameter("lexicon");
    org.nhind.config.PolicyLexicon lex = null;
    // Check the file for three types of policies
    if (lexicon.isEmpty()) {
        lex = org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1;
    } else {
        try {
            // Convert string of file contents to lexicon object
            lex = org.nhind.config.PolicyLexicon.fromString(lexicon);
        } catch (Exception e) {
            log.error("Invalid lexicon name.");
        }
    }
    // Determine lexicon type
    if (lex.equals(org.nhind.config.PolicyLexicon.JAVA_SER)) {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.JAVA_SER;
    } else if (lex.equals(org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1)) {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.SIMPLE_TEXT_V1;
    } else {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.XML;
    }
    InputStream inStr = null;
    try {
        // Convert policy file upload to byte stream
        inStr = new ByteArrayInputStream(content.getBytes());
        // Initialize parser engine
        final PolicyLexiconParser parser = PolicyLexiconParserFactory.getInstance(parseLexicon);
        // Attempt to parse the lexicon file for validity
        parser.parse(inStr);
    } catch (PolicyParseException e) {
        log.error("Syntax error in policy content " + " : " + e.getMessage());
        jsonResponse = "{\"Status\":\"Policy content was not valid.\",\"Error\":\"" + e.getMessage() + "\"}";
    } finally {
        IOUtils.closeQuietly(inStr);
    }
    if (jsonResponse.isEmpty()) {
        jsonResponse = "{\"Status\":\"Success\"}";
    }
    return jsonResponse;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) PolicyLexicon(org.nhindirect.policy.PolicyLexicon) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) PolicyLexiconParser(org.nhindirect.policy.PolicyLexiconParser) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PolicyParseException(org.nhindirect.policy.PolicyParseException) MalformedURLException(java.net.MalformedURLException) ServiceException(org.nhindirect.common.rest.exceptions.ServiceException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) FileUploadException(org.apache.commons.fileupload.FileUploadException) PolicyParseException(org.nhindirect.policy.PolicyParseException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 3 with PolicyLexiconParser

use of org.nhindirect.policy.PolicyLexiconParser in project nhin-d by DirectProject.

the class PoliciesController method checkLexiconFile.

/*********************************
     *
     * Check Lexicon File Method
     *
     *********************************/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value = "/checkLexiconFile", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String checkLexiconFile(@RequestHeader(value = "X-Requested-With", required = false) String requestedWith, HttpServletResponse response, Object command, @RequestHeader(value = "lexicon", required = false) String lexicon, MultipartHttpServletRequest request) throws FileUploadException, IOException, Exception {
    final org.nhindirect.policy.PolicyLexicon parseLexicon;
    String jsonResponse = "";
    String uploadToString = "";
    if (log.isDebugEnabled()) {
        log.debug("Checking uploaded lexicon file for format and validation");
    }
    // Grab uploaded file from the post submission
    UploadedFile ufile = new UploadedFile();
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = request.getFile(itr.next());
    try {
        ufile.length = mpf.getBytes().length;
        ufile.bytes = mpf.getBytes();
        ufile.type = mpf.getContentType();
        ufile.name = mpf.getOriginalFilename();
    } catch (IOException e) {
    }
    // Convert upload content to string
    uploadToString = new String(ufile.bytes);
    uploadToString = JSONObject.escape(uploadToString);
    lexicon = request.getParameter("lexicon");
    org.nhind.config.PolicyLexicon lex = null;
    // Check the file for three types of policies
    if (lexicon.isEmpty()) {
        lex = org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1;
    } else {
        try {
            // Convert string of file contents to lexicon object
            lex = org.nhind.config.PolicyLexicon.fromString(lexicon);
        } catch (Exception e) {
            log.error("Invalid lexicon name.");
        }
    }
    // Determine lexicon type
    if (lex.equals(org.nhind.config.PolicyLexicon.JAVA_SER)) {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.JAVA_SER;
    } else if (lex.equals(org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1)) {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.SIMPLE_TEXT_V1;
    } else {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.XML;
    }
    InputStream inStr = null;
    try {
        // Convert policy file upload to byte stream
        inStr = new ByteArrayInputStream(ufile.bytes);
        // Initialize parser engine
        final PolicyLexiconParser parser = PolicyLexiconParserFactory.getInstance(parseLexicon);
        // Attempt to parse the lexicon file for validity
        parser.parse(inStr);
    } catch (PolicyParseException e) {
        log.error("Syntax error in policy file " + " : " + e.getMessage());
        jsonResponse = "{\"Status\":\"File was not a valid file.\",\"Content\":\"" + uploadToString + "\"}";
    } finally {
        IOUtils.closeQuietly(inStr);
    }
    if (jsonResponse.isEmpty()) {
        jsonResponse = "{\"Status\":\"Success\",\"Content\":\"" + uploadToString + "\"}";
    }
    return jsonResponse;
}
Also used : PolicyLexicon(org.nhindirect.policy.PolicyLexicon) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PolicyParseException(org.nhindirect.policy.PolicyParseException) MalformedURLException(java.net.MalformedURLException) ServiceException(org.nhindirect.common.rest.exceptions.ServiceException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) FileUploadException(org.apache.commons.fileupload.FileUploadException) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) ByteArrayInputStream(java.io.ByteArrayInputStream) PolicyLexiconParser(org.nhindirect.policy.PolicyLexiconParser) PolicyParseException(org.nhindirect.policy.PolicyParseException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 4 with PolicyLexiconParser

use of org.nhindirect.policy.PolicyLexiconParser in project nhin-d by DirectProject.

the class PolicyCommands method importPolicy.

@Command(name = "ImportPolicy", usage = IMPORT_POLICY_USAGE)
public void importPolicy(String[] args) {
    final String policyName = StringArrayUtil.getRequiredValue(args, 0);
    final String fileLoc = StringArrayUtil.getRequiredValue(args, 1);
    final String lexicon = StringArrayUtil.getOptionalValue(args, 2, "");
    // check if the policy already exists
    try {
        org.nhind.config.CertPolicy policy = proxy.getPolicyByName(policyName);
        if (policy != null) {
            System.out.println("Policy with name " + policyName + " already exists.");
            return;
        }
    } catch (Exception e) {
        System.out.println("Failed to lookup policy: " + e.getMessage());
        return;
    }
    PolicyLexicon lex;
    if (lexicon.isEmpty())
        lex = PolicyLexicon.SIMPLE_TEXT_V1;
    else {
        try {
            lex = PolicyLexicon.fromString(lexicon);
        } catch (Exception e) {
            System.out.println("Invalid lexicon name.");
            return;
        }
    }
    // validate the policy syntax
    final org.nhindirect.policy.PolicyLexicon parseLexicon;
    if (lex.equals(org.nhind.config.PolicyLexicon.JAVA_SER))
        parseLexicon = org.nhindirect.policy.PolicyLexicon.JAVA_SER;
    else if (lex.equals(org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1))
        parseLexicon = org.nhindirect.policy.PolicyLexicon.SIMPLE_TEXT_V1;
    else
        parseLexicon = org.nhindirect.policy.PolicyLexicon.XML;
    byte[] policyBytes;
    InputStream inStr = null;
    try {
        policyBytes = FileUtils.readFileToByteArray(new File(fileLoc));
        inStr = new ByteArrayInputStream(policyBytes);
        final PolicyLexiconParser parser = PolicyLexiconParserFactory.getInstance(parseLexicon);
        parser.parse(inStr);
    } catch (PolicyParseException e) {
        System.out.println("Syntax error in policy file " + fileLoc + " : " + e.getMessage());
        return;
    } catch (IOException e) {
        System.out.println("Error reading file " + fileLoc + " : " + e.getMessage());
        return;
    } finally {
        IOUtils.closeQuietly(inStr);
    }
    try {
        org.nhind.config.CertPolicy addPolicy = new org.nhind.config.CertPolicy();
        addPolicy.setPolicyData(policyBytes);
        addPolicy.setPolicyName(policyName);
        addPolicy.setLexicon(lex);
        proxy.addPolicy(addPolicy);
        System.out.println("Successfully imported policy.");
    } catch (IOException e) {
        System.out.println("Error reading file " + fileLoc + " : " + e.getMessage());
        return;
    } catch (Exception e) {
        System.out.println("Error importing certificate " + fileLoc + " : " + e.getMessage());
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) IOException(java.io.IOException) PolicyParseException(org.nhindirect.policy.PolicyParseException) PolicyLexicon(org.nhind.config.PolicyLexicon) ByteArrayInputStream(java.io.ByteArrayInputStream) PolicyLexiconParser(org.nhindirect.policy.PolicyLexiconParser) File(java.io.File) PolicyParseException(org.nhindirect.policy.PolicyParseException) Command(org.nhindirect.dns.tools.utils.Command)

Example 5 with PolicyLexiconParser

use of org.nhindirect.policy.PolicyLexiconParser in project nhin-d by DirectProject.

the class ConfigServiceDNSStore method configCertPolicy.

/**
	 * Checks to see if a certificate policy has been configured.
	 */
protected void configCertPolicy() throws DNSException {
    // check to see if there is a certificate policy set
    final String polName = System.getProperty(DNS_CERT_POLICY_NAME_VAR);
    if (!StringUtils.isEmpty(polName)) {
        InputStream inStream = null;
        LOGGER.info("Certificate policy name " + polName + " has been configured.");
        try {
            // get the policy by name
            final org.nhind.config.CertPolicy policy = proxy.getPolicyByName(polName);
            if (policy == null) {
                LOGGER.warn("Certificate policy " + polName + " could not be found in the system.  Falling back to no policy.");
                return;
            }
            // now compile the policy into an expression
            final PolicyLexiconParser parser = PolicyLexiconParserFactory.getInstance(PolicyLexicon.valueOf(policy.getLexicon().getValue()));
            inStream = new ByteArrayInputStream(policy.getPolicyData());
            this.polExpression = parser.parse(inStream);
            // now create the filter
            this.polFilter = PolicyFilterFactory.getInstance();
        } catch (Exception e) {
            // it's OK if can't find the certificate policy that was configured, we'll just log a warning
            // it's also OK if we can't download or parse the policy, but we need to log the error
            LOGGER.warn("Error loading and compling certificate policy " + polName + ".  Will fallback to no policy filter.", e);
        } finally {
            IOUtils.closeQuietly(inStream);
        }
    } else
        LOGGER.info("No certificate policy has been configured.");
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) PolicyLexiconParser(org.nhindirect.policy.PolicyLexiconParser) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException)

Aggregations

PolicyLexiconParser (org.nhindirect.policy.PolicyLexiconParser)8 InputStream (java.io.InputStream)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 PolicyParseException (org.nhindirect.policy.PolicyParseException)5 PolicyExpression (org.nhindirect.policy.PolicyExpression)4 PolicyLexicon (org.nhindirect.policy.PolicyLexicon)4 IOException (java.io.IOException)3 File (java.io.File)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 MalformedURLException (java.net.MalformedURLException)2 URISyntaxException (java.net.URISyntaxException)2 CertificateException (java.security.cert.CertificateException)2 FileUploadException (org.apache.commons.fileupload.FileUploadException)2 ServiceException (org.nhindirect.common.rest.exceptions.ServiceException)2 SmtpAgentException (org.nhindirect.gateway.smtp.SmtpAgentException)2 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)2 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)2 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 PrintStream (java.io.PrintStream)1