Commit 0799f1f7 authored by Patrick Dowler's avatar Patrick Dowler
Browse files

initial commit for cadcCDP-Server module with cdoe from org.astrogrid.security.delegation library

parent 22924316
Loading
Loading
Loading
Loading
+108 −0
Original line number Diff line number Diff line
<!--
************************************************************************
*******************  CANADIAN ASTRONOMY DATA CENTRE  *******************
**************  CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES  **************
*
*  (c) 2009.                            (c) 2009.
*  Government of Canada                 Gouvernement du Canada
*  National Research Council            Conseil national de recherches
*  Ottawa, Canada, K1A 0R6              Ottawa, Canada, K1A 0R6
*  All rights reserved                  Tous droits réservés
*
*  NRC disclaims any warranties,        Le CNRC dénie toute garantie
*  expressed, implied, or               énoncée, implicite ou légale,
*  statutory, of any kind with          de quelque nature que ce
*  respect to the software,             soit, concernant le logiciel,
*  including without limitation         y compris sans restriction
*  any warranty of merchantability      toute garantie de valeur
*  or fitness for a particular          marchande ou de pertinence
*  purpose. NRC shall not be            pour un usage particulier.
*  liable in any event for any          Le CNRC ne pourra en aucun cas
*  damages, whether direct or           être tenu responsable de tout
*  indirect, special or general,        dommage, direct ou indirect,
*  consequential or incidental,         particulier ou général,
*  arising from the use of the          accessoire ou fortuit, résultant
*  software.  Neither the name          de l'utilisation du logiciel. Ni
*  of the National Research             le nom du Conseil National de
*  Council of Canada nor the            Recherches du Canada ni les noms
*  names of its contributors may        de ses  participants ne peuvent
*  be used to endorse or promote        être utilisés pour approuver ou
*  products derived from this           promouvoir les produits dérivés
*  software without specific prior      de ce logiciel sans autorisation
*  written permission.                  préalable et particulière
*                                       par écrit.
*
*  This file is part of the             Ce fichier fait partie du projet
*  OpenCADC project.                    OpenCADC.
*
*  OpenCADC is free software:           OpenCADC est un logiciel libre ;
*  you can redistribute it and/or       vous pouvez le redistribuer ou le
*  modify it under the terms of         modifier suivant les termes de
*  the GNU Affero General Public        la “GNU Affero General Public
*  License as published by the          License” telle que publiée
*  Free Software Foundation,            par la Free Software Foundation
*  either version 3 of the              : soit la version 3 de cette
*  License, or (at your option)         licence, soit (à votre gré)
*  any later version.                   toute version ultérieure.
*
*  OpenCADC is distributed in the       OpenCADC est distribué
*  hope that it will be useful,         dans l’espoir qu’il vous
*  but WITHOUT ANY WARRANTY;            sera utile, mais SANS AUCUNE
*  without even the implied             GARANTIE : sans même la garantie
*  warranty of MERCHANTABILITY          implicite de COMMERCIALISABILITÉ
*  or FITNESS FOR A PARTICULAR          ni d’ADÉQUATION À UN OBJECTIF
*  PURPOSE.  See the GNU Affero         PARTICULIER. Consultez la Licence
*  General Public License for           Générale Publique GNU Affero
*  more details.                        pour plus de détails.
*
*  You should have received             Vous devriez avoir reçu une
*  a copy of the GNU Affero             copie de la Licence Générale
*  General Public License along         Publique GNU Affero avec
*  with OpenCADC.  If not, see          OpenCADC ; si ce n’est
*  <http://www.gnu.org/licenses/>.      pas le cas, consultez :
*                                       <http://www.gnu.org/licenses/>.
*
*  $Revision: 4 $
*
************************************************************************
-->


<!DOCTYPE project>
<project default="build" basedir=".">
    <property environment="env"/>
    <property file="local.build.properties" />

    <!-- site-specific build properties or overrides of values in opencadc.properties -->
    <property file="${env.CADC_PREFIX}/etc/local.properties" />

    <!-- site-specific targets, e.g. install, cannot duplicate those in opencadc.targets.xml -->
    <import file="${env.CADC_PREFIX}/etc/local.targets.xml" optional="true" />

    <!-- default properties and targets -->
    <property file="${env.CADC_PREFIX}/etc/opencadc.properties" />
    <import file="${env.CADC_PREFIX}/etc/opencadc.targets.xml"/>

    <!-- developer convenience: place for extra targets and properties -->
    <import file="extras.xml" optional="true" />

    <property name="project" value="cadcCDP-Server" />

    <property name="cadcLog"             value="${lib}/cadcLog.jar" />
    <property name="cadcUtil"            value="${lib}/cadcUtil.jar" />
    <property name="cadcVOSI"            value="${lib}/cadcVOSI.jar" />
    <property name="log4j"               value="${ext.lib}/log4j.jar" />
    <property name="servlet"             value="${ext.lib}/servlet-api.jar" />
    <property name="bouncy"              value="${ext.lib}/bcprov.jar" />
    <property name="spring"              value="${ext.lib}/spring.jar" />

    <property name="jars" value="${log4j}:${servlet}:${bouncy}:${cadcLog}:${cadcUtil}:${cadcVOSI}:${spring}" />

    <target name="build" depends="compile">
        <jar jarfile="${build}/lib/${project}.jar"
                    basedir="${build}/class"
                    update="no">
                <include name="**/**.class" />
        </jar>
    </target>
</project>
+260 −0
Original line number Diff line number Diff line
/*
 ************************************************************************
 ****  C A N A D I A N   A S T R O N O M Y   D A T A   C E N T R E  *****
 *
 * (c) 2010.                            (c) 2010.
 * National Research Council            Conseil national de recherches
 * Ottawa, Canada, K1A 0R6              Ottawa, Canada, K1A 0R6
 * All rights reserved                  Tous droits reserves
 *
 * NRC disclaims any warranties         Le CNRC denie toute garantie
 * expressed, implied, or statu-        enoncee, implicite ou legale,
 * tory, of any kind with respect       de quelque nature que se soit,
 * to the software, including           concernant le logiciel, y com-
 * without limitation any war-          pris sans restriction toute
 * ranty of merchantability or          garantie de valeur marchande
 * fitness for a particular pur-        ou de pertinence pour un usage
 * pose.  NRC shall not be liable       particulier.  Le CNRC ne
 * in any event for any damages,        pourra en aucun cas etre tenu
 * whether direct or indirect,          responsable de tout dommage,
 * special or general, consequen-       direct ou indirect, particul-
 * tial or incidental, arising          ier ou general, accessoire ou
 * from the use of the software.        fortuit, resultant de l'utili-
 *                                      sation du logiciel.
 *
 *
 * @version $Revision: $
 * 
 * 
 ****  C A N A D I A N   A S T R O N O M Y   D A T A   C E N T R E  *****
 ************************************************************************
 */

package ca.nrc.cadc.cdp.server;

import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.sql.Types;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.security.auth.x500.X500Principal;
import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SingleColumnRowMapper;

import ca.nrc.cadc.auth.AuthenticationUtil;
import ca.nrc.cadc.auth.SSLUtil;
import ca.nrc.cadc.auth.X509CertificateChain;
import ca.nrc.cadc.db.DBUtil;
import ca.nrc.cadc.profiler.Profiler;
import ca.nrc.cadc.vosi.avail.CheckDataSource;
import ca.nrc.cadc.vosi.avail.CheckResource;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.spec.InvalidKeySpecException;
import javax.naming.NamingException;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Sybase implementation of CertificateDAO.
 * 
 * @author pdowler
 *
 */
public class CertificateDAO
{
    private static Logger logger = Logger.getLogger(CertificateDAO.class);

    private String certTable;

    private String dataSourceName = "jdbc/sybase";
    private DataSource dataSource;
    
    // TODO: make these configurable
    private String database = "archive";
    private String schema = "dbo";
    private String table = "x509_certificates";

    public CertificateDAO()
    {
        try
        {
            this.dataSource = DBUtil.getDataSource(dataSourceName);
        }
        catch(NamingException ex)
        {
            throw new RuntimeException("CONFIG: failed to find DataSource " + dataSourceName);
        }
        this.certTable = database + "." + schema + "." + table;
    }
    
    // for tests
    CertificateDAO(DataSource dataSource, String db, String schema)
    {
        this.dataSource = dataSource;
        this.database = db;
        this.schema = schema;
        this.certTable = database + "." + schema + "." + table;
    }

    public CheckResource getCheckResource()
    {
        String sql = "select top 1 hash_dn from " + certTable;
        return new CheckDataSource(dataSource, sql);
    }

    public void put(X509CertificateChain chain)
    {
        Profiler profiler = new Profiler(this.getClass());
        String hashKey = chain.getHashKey();
        String canonDn = AuthenticationUtil.canonizeDistinguishedName(chain.getPrincipal().getName());
        Date expDate = chain.getExpiryDate();
        String certChainStr = chain.certificateString();
        byte[] bytesPrivateKey = chain.getPrivateKey().getEncoded();
        //TODO just for testing - padded with zeros
        byte[] testBytesPrivateKey = Arrays.copyOf(bytesPrivateKey, bytesPrivateKey.length+1);
        testBytesPrivateKey[testBytesPrivateKey.length-1]=1;
        String csr = chain.getCsrString();
        
        JdbcTemplate jdbc = new JdbcTemplate(dataSource);
        if (recordExists(hashKey))
        {
            String sql = "update " + this.certTable
                    + " set canon_dn = ?, exp_date = ?, cert_chain = ?, private_key = ?, csr = ? where hash_dn=?";
            Object[] args = new Object[] { canonDn, expDate, certChainStr, testBytesPrivateKey, csr, hashKey };
            int[] argTypes = new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR, Types.VARBINARY, Types.VARCHAR, Types.VARCHAR };
            jdbc.update(sql, args, argTypes);
        }
        else
        {
            String sql = "insert into " + this.certTable
                + " (canon_dn, exp_date, cert_chain, private_key, csr, hash_dn) values (?,?,?,?,?,?)";
            Object[] args = new Object[] { canonDn, expDate, certChainStr, testBytesPrivateKey, csr, hashKey };
            int[] argTypes = 
                new int[] { Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR, Types.VARBINARY, Types.VARCHAR, Types.VARCHAR };

            jdbc.update(sql, args, argTypes);
        }
        profiler.checkpoint("put");
    }

    public X509CertificateChain get(X500Principal principal)
    {
        if (principal == null) return null;
        String canonizedDn = AuthenticationUtil.canonizeDistinguishedName(principal.getName());
        X500Principal p = new X500Principal(canonizedDn);
        String hashKey = Integer.toString(p.hashCode());
        return get(hashKey);
    }

    public X509CertificateChain get(String hashKey)
    {
        Profiler profiler = new Profiler(this.getClass());
        X509CertificateChain x509CertificateChain = null;

        String query = "select canon_dn, exp_date, cert_chain, private_key, csr from " + this.certTable + " where hash_dn = ? ";

        
        try
        {
            JdbcTemplate jdbc = new JdbcTemplate(dataSource);
            Map<String, Object> map = jdbc.queryForMap(query, new String[] { hashKey });
            String canonDn = (String) map.get("canon_dn");
            Date expDate = (Date) map.get("exp_date");
            String certChainStr = (String) map.get("cert_chain");
            byte[] bytesPrivateKey = (byte[]) map.get("private_key");
            
            // Sybase trims the trailing 0's of a varbinary. To compensate we add 0's to the 
            // privateKey byte array. Extra bytes in the private key array are ignored
            // when the key is built so the added 0's are only used when needed.
            // ad 20/07/2011
            bytesPrivateKey = Arrays.copyOf(bytesPrivateKey, bytesPrivateKey.length+10);
            
            String csrStr = (String) map.get("csr");

            PrivateKey privateKey = SSLUtil.readPrivateKey(bytesPrivateKey);
            X500Principal principal = new X500Principal(canonDn);

            if (certChainStr != null)
            {
                byte[] bytesCertChain = certChainStr.getBytes();
                X509Certificate[] certs = SSLUtil.readCertificateChain(bytesCertChain);

                x509CertificateChain = new X509CertificateChain(Arrays.asList(certs));
            }
            else
            {
                x509CertificateChain = new X509CertificateChain(principal, privateKey, csrStr);
            }
            x509CertificateChain.setCsrString(csrStr);
            x509CertificateChain.setExpiryDate(expDate);
            x509CertificateChain.setHashKey(hashKey);
            x509CertificateChain.setKey(privateKey);
            x509CertificateChain.setPrincipal(principal);
        }
        catch (EmptyResultDataAccessException e)
        {
            // Record not exists.
            return null;
        }
        catch(InvalidKeySpecException ex)
        {
            throw new RuntimeException("BUG: failed to read private key", ex);
        }
        catch(NoSuchAlgorithmException ex)
        {
            throw new RuntimeException("BUG: failed to read private key", ex);
        }
        catch(CertificateException ex)
        {
            throw new RuntimeException("BUG: failed to read certficate chain", ex);
        }
        catch(IOException ex)
        {
            throw new RuntimeException("BUG: failed to read certificate chain", ex);
        }
        profiler.checkpoint("get");
        return x509CertificateChain;
    }

    /* (non-Javadoc)
     * @see ca.nrc.cadc.accesscontrol.dao.CertificateDAO#delete(java.lang.String)
     */
    public void delete(String hashKey)
    {
        Profiler profiler = new Profiler(this.getClass());
        String sql = "delete from " + this.certTable + " where hash_dn = ? ";
        JdbcTemplate jdbc = new JdbcTemplate(dataSource);
        jdbc.update(sql, new String[] { hashKey });
        profiler.checkpoint("delete");
    }

    private boolean recordExists(String hashKey)
    {
        RowMapper rowMapper = new SingleColumnRowMapper(String.class);
        String query = "select canon_dn from " + this.certTable + " where hash_dn = ? ";
        JdbcTemplate jdbc = new JdbcTemplate(dataSource);
        List<String> dnList = jdbc.query(query, new String[] { hashKey }, rowMapper);
        return (dnList != null && dnList.size() == 1);
    }

    public List<String> getAllHashKeys()
    {
        Profiler profiler = new Profiler(this.getClass());
        String query = "select hash_dn from " + this.certTable;
        RowMapper rowMapper = new SingleColumnRowMapper(String.class);
        JdbcTemplate jdbc = new JdbcTemplate(dataSource);
        List<String> hashKeyList = jdbc.query(query, rowMapper);
        profiler.checkpoint("getAllHashKeys");
        return hashKeyList;
    }


}
+146 −0
Original line number Diff line number Diff line
package org.astrogrid.security.delegation;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ca.nrc.cadc.auth.SSLUtil;
import org.apache.log4j.Logger;

/**
 * 
 * @author Guy Rixon
 */
public class CertificateProcessor extends ResourceProcessor
{

    private static final Logger log = Logger.getLogger(CertificateProcessor.class);

    /**
     * Responds to HTTP requests.
     */
    @Override
    public void service(HttpServletRequest request, DelegationUri path,
            HttpServletResponse response) throws IOException
    {
        if (request.getMethod().equals("GET"))
        {
            sendCertificate(path.getUser(), response);
        }
        else if (request.getMethod().equals("PUT"))
        {
            receiveCertificate(request, path.getUser(), response);
        }
        else
        {
            response.setHeader("Accept", "GET");
            response.sendError(response.SC_METHOD_NOT_ALLOWED);
        }
    }

    /**
     * Writes to the client the X.509 certificate for an identity.
     */
    private void sendCertificate(String hashKey,
            HttpServletResponse response) throws IOException
    {
        if (Delegations.getInstance().hasCertificate(hashKey))
        {
            response.setContentType("text/plain");
            Delegations.getInstance().writeCertificate(hashKey,
                    response.getWriter());
        }
        else
        {
            response.sendError(response.SC_NOT_FOUND);
        }
    }

    /**
     * Receives an uploaded identity certificate. The certificate becomes
     * the content for they identity's /certificate resource.
     */
    private void receiveCertificate(HttpServletRequest request,
            String hashKey, HttpServletResponse response)
            throws IOException
    {
        if (Delegations.getInstance().isKnown(hashKey))
        {
            try
            {
                // the Certificate factory is quite fragile when it comes to
                // reading the PEM string. So we consume the stream, and 
                // extracts just the Certificates information from the 
                // stream by calling SSLUtil.getCertificates() and fed
                // it to the CertificateFactory
               
                int bytesRead = 0;
                int bytesToRead = 10000; // max size accepted for the input
                                         // stream
                byte[] input = new byte[bytesToRead];
                while (bytesRead < bytesToRead)
                {
                    int result = request.getInputStream().read(input,
                            bytesRead, bytesToRead - bytesRead);
                    if (result == -1)
                    {
                        break;
                    }
                    bytesRead += result;
                }
                
                if(bytesRead == bytesToRead)
                {
                    throw new 
                    CertificateException("Certificate to read too large (>" + 
                            bytesToRead + " bytes)");
                }

                byte[] code = SSLUtil.getCertificates(input);
                

                CertificateFactory factory = CertificateFactory
                .getInstance("X509");
                BufferedInputStream istream = new BufferedInputStream(
                        new ByteArrayInputStream(code));
                Collection certificates = 
                    factory.generateCertificates(istream);
                //certificate.checkValidity(); ???
                
                try
                {
                    X509Certificate[] certsArray = new X509Certificate[certificates.size()];
                    Delegations.getInstance().setCertificates(hashKey,
                            (X509Certificate[])certificates.toArray(certsArray));
                }
                catch (InvalidKeyException ex)
                {
                    throw new RuntimeException(ex);
                }
                log.info("Received a certificate for "
                        + ((X509Certificate) certificates.iterator()
                                .next()).getSubjectX500Principal() + " ("
                        + hashKey + ").");
            }
            catch (CertificateException ex)
            {
                System.out.println(ex);
                response.sendError(response.SC_BAD_REQUEST,
                        "Failed to parse the certificate: " + ex);
            }
        }
        else
        {
            response.sendError(response.SC_NOT_FOUND);
        }
    }

}
+72 −0
Original line number Diff line number Diff line
package org.astrogrid.security.delegation;

import java.io.IOException;
import java.io.Writer;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SignatureException;

import org.bouncycastle.asn1.DERObject;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DERPrintableString;
import org.bouncycastle.asn1.DERUTF8String;
import org.bouncycastle.asn1.x509.X509DefaultEntryConverter;
import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.jce.PKCS10CertificationRequest;
import org.bouncycastle.openssl.PEMWriter;

/**
 * A CSR that can write itself out in PEM'd PKCS#10 format.
 *
 * @author Guy Rixon
 */
public class CertificateSigningRequest extends PKCS10CertificationRequest {
   
  /**
   * Constructs a CertificateSigningRequest.
   * The subject is taken in as a plain string. The signing
   * algorithm is fixed as MD5 digest, RSA encryption. This means that the
   * key-pair passed in must be RSA keys.
   *
   * @throws NoSuchAlgorithmException If the JCE-provider doesn't know MD5WITHRSA.
   * @throws NoSuchProviderException If the JCE-provider "BC" isn't registered.
   * @throws InvalidKeyException If the given keys are not RSA keys.
   */
  public CertificateSigningRequest(String identity, KeyPair keys) 
      throws InvalidKeyException, 
             SignatureException, NoSuchAlgorithmException, NoSuchProviderException {
    super("SHA256WITHRSA",
            new X509Name(identity, new X509DefaultEntryConverter() {
                @Override
                public DERObject getConvertedValue(DERObjectIdentifier oid,  String 
            val) {
                    DERObject obj = super.getConvertedValue(oid, val);
                    if (obj instanceof DERUTF8String)
                        return new DERPrintableString(val);
                    else
                        return obj;
                    }
                }),
            keys.getPublic(),
            null,
            keys.getPrivate(),
            "BC");
  }
  
  public CertificateSigningRequest(PKCS10CertificationRequest req)
  {
      super(req.getEncoded());
  }
  
    /**
     * Writes out the CSR as a PEM-encoded PKCS#10 artifact.
     */
    public void writePem(Writer out) throws IOException
    {
        PEMWriter pem = new PEMWriter(out);
        pem.writeObject(this);
        pem.flush();
    }
}
+54 −0

File added.

Preview size limit exceeded, changes collapsed.

Loading