001    /**
002     *
003     *  Licensed to the Apache Software Foundation (ASF) under one or more
004     *  contributor license agreements.  See the NOTICE file distributed with
005     *  this work for additional information regarding copyright ownership.
006     *  The ASF licenses this file to You under the Apache License, Version 2.0
007     *  (the "License"); you may not use this file except in compliance with
008     *  the License.  You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     *  Unless required by applicable law or agreed to in writing, software
013     *  distributed under the License is distributed on an "AS IS" BASIS,
014     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015     *  See the License for the specific language governing permissions and
016     *  limitations under the License.
017     */
018    package org.apache.geronimo.console.ca;
019    
020    import java.io.IOException;
021    import java.math.BigInteger;
022    import java.net.URI;
023    import java.text.DateFormat;
024    import java.text.SimpleDateFormat;
025    import java.util.Date;
026    
027    import javax.portlet.ActionRequest;
028    import javax.portlet.ActionResponse;
029    import javax.portlet.PortletException;
030    import javax.portlet.PortletRequest;
031    import javax.portlet.RenderRequest;
032    import javax.portlet.RenderResponse;
033    
034    import org.apache.commons.logging.Log;
035    import org.apache.commons.logging.LogFactory;
036    import org.apache.geronimo.console.MultiPageModel;
037    import org.apache.geronimo.console.util.PortletManager;
038    import org.apache.geronimo.gbean.AbstractName;
039    import org.apache.geronimo.gbean.GBeanData;
040    import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory;
041    import org.apache.geronimo.kernel.Naming;
042    import org.apache.geronimo.kernel.proxy.GeronimoManagedBean;
043    import org.apache.geronimo.kernel.repository.Artifact;
044    import org.apache.geronimo.management.geronimo.CertificationAuthority;
045    import org.apache.geronimo.management.geronimo.KeystoreInstance;
046    import org.apache.geronimo.security.ca.FileCertificateRequestStore;
047    import org.apache.geronimo.security.ca.FileCertificateStore;
048    import org.apache.geronimo.security.ca.GeronimoCertificationAuthority;
049    import org.apache.geronimo.system.serverinfo.ServerInfo;
050    
051    /**
052     * Handler for the CA confirmation screen.
053     *
054     * @version $Rev: 514091 $ $Date: 2007-03-03 01:26:39 -0500 (Sat, 03 Mar 2007) $
055     */
056    public class ConfirmCAHandler extends BaseCAHandler {
057        private final static Log log = LogFactory.getLog(ConfirmCAHandler.class);
058        public ConfirmCAHandler() {
059            super(CONFIRM_CA_MODE, "/WEB-INF/view/ca/confirmCA.jsp");
060        }
061    
062        public String actionBeforeView(ActionRequest request, ActionResponse response, MultiPageModel model) throws PortletException, IOException {
063            String[] params = {ERROR_MSG, INFO_MSG, "caCN", "caOU", "caO", "caL", "caST", "caC", "alias", "keyAlgorithm", "keySize", "algorithm", "validFrom", "validTo", "sNo", "password"};
064            for(int i = 0; i < params.length; ++i) {
065                String value = request.getParameter(params[i]);
066                if(value != null) response.setRenderParameter(params[i], value);
067            }
068            return getMode();
069        }
070    
071        public void renderView(RenderRequest request, RenderResponse response, MultiPageModel model) throws PortletException, IOException {
072            String[] params = {ERROR_MSG, INFO_MSG, "caCN", "caOU", "caO", "caL", "caST", "caC", "alias", "keyAlgorithm", "keySize", "algorithm", "validFrom", "validTo", "sNo", "password"};
073            for(int i = 0; i < params.length; ++i) {
074                String value = request.getParameter(params[i]);
075                if(value != null) request.setAttribute(params[i], value);
076            }
077        }
078    
079        public String actionAfterView(ActionRequest request, ActionResponse response, MultiPageModel model) throws PortletException, IOException {
080            String caCN = request.getParameter("caCN");
081            String caOU = request.getParameter("caOU");
082            String caO = request.getParameter("caO");
083            String caL = request.getParameter("caL");
084            String caST = request.getParameter("caST");
085            String caC = request.getParameter("caC");
086            String alias = request.getParameter("alias");
087            String password = request.getParameter("password");
088            String keyAlgorithm = request.getParameter("keyAlgorithm");
089            String keySize = request.getParameter("keySize");
090            String algorithm = request.getParameter("algorithm");
091            String validFrom = request.getParameter("validFrom");
092            String validTo = request.getParameter("validTo");
093            String sNo = request.getParameter("sNo");
094            String errorMsg = null;
095            
096            try {
097                // Generate keypair
098                // Check if the key algorithm is same as defaultKeyAlgorithm (which is "RSA")
099                if(!defaultKeyAlgorithm.equalsIgnoreCase(keyAlgorithm)) {
100                    throw new Exception("Key Algorithm '"+keyAlgorithm+"' is not supported.");
101                }
102                // Create a KeystoreInstance and generate keypair
103                KeystoreInstance caKeystore = createCAKeystoreInstance(request, password);
104                caKeystore.unlockKeystore(password.toCharArray());
105                caKeystore.generateKeyPair(alias, password.toCharArray(), password.toCharArray(), keyAlgorithm, Integer.parseInt(keySize),
106                        algorithm, 365, caCN, caOU, caO, caL, caST, caC);
107                caKeystore.unlockPrivateKey(alias, password.toCharArray(), password.toCharArray());
108                
109                // Create CertificationAuthority, CertificateStore and CertificateRequestStore GBeans
110                createCARelatedGBeans(request, (GeronimoManagedBean)caKeystore, defaultCAStoreDir, defaultCSRStoreDir);
111    
112                CertificationAuthority ca = getCertificationAuthority(request);
113                ca.unlock(password.toCharArray());
114    
115                // Certificate validity and serial number.
116                // Validity of these have been checked before loading the confirmation page.
117                Date validFromDate = null, validToDate = null;
118                DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
119                validFromDate = df.parse(validFrom);
120                validToDate = df.parse(validTo);
121                BigInteger serialNum = new BigInteger(sNo);
122                
123                // Instruct the CA to issue a self-signed certificate.
124                ca.issueOwnCertificate(serialNum, validFromDate, validToDate, algorithm);
125                // Publish the CA's certificate to CertificateStore.
126                getCertificateStore(request).storeCACertificate(ca.getCertificate());
127                
128                // CA Setup is succeessful.
129                // Load a page to show CA details.
130                response.setRenderParameter(INFO_MSG, "CA Setup is successful!");
131                log.info("CA Setup is successful.");
132                
133                return CADETAILS_MODE+BEFORE_ACTION;
134            } catch(Exception e) {
135                errorMsg = e.toString();
136                log.error("Errors in CA Setup process.", e);
137            }
138            
139            // An error occurred.  Go back to CA details entry page so that user can correct the errors.
140            if(errorMsg != null) response.setRenderParameter(ERROR_MSG, errorMsg);
141            return SETUPCA_MODE+BEFORE_ACTION;
142        }
143        
144        /**
145         * This method creates CerificationAuthority, CertificateStore and CertificateRequestStore GBeans.  The GBeans are
146         * created and added to the same configuration containing the caKeystore GBean.
147         * @param request PortletRequest to execute any kernel api's
148         * @param caKeystore Keystore to be used by the CA
149         * @param certStorePath Path for CertificateStore directory.  Note: This CA uses FileCertificateStore
150         * @param certReqStorePath Path for CertificateRequestStore directory: Note: This CA uses FileCertificateRequestStore
151         */
152        private void createCARelatedGBeans(PortletRequest request, GeronimoManagedBean caKeystore, String certStorePath, String certReqStorePath) {
153            // Get hold of configuration containing caKeystore GBean
154            AbstractName caKeystoreName = PortletManager.getNameFor(request, caKeystore);
155            Artifact configurationId =  PortletManager.getConfigurationFor(request, caKeystoreName);
156            ServerInfo serverInfo = PortletManager.getCurrentServer(request).getServerInfo();
157            AbstractName serverInfoName = PortletManager.getNameFor(request, serverInfo);
158            Naming naming = PortletManager.getManagementHelper(request).getNaming();
159            
160            // Add a CertificateStore GBean
161            AbstractName certStoreName = naming.createSiblingName(caKeystoreName, "geronimo-ca-cert-store", NameFactory.CERTIFICATE_STORE);
162            GBeanData certStore = new GBeanData(certStoreName, FileCertificateStore.GBEAN_INFO);
163            certStore.setAttribute("directoryPath", URI.create(certStorePath));
164            certStore.setReferencePattern("ServerInfo", serverInfoName);
165            PortletManager.addGBeanToConfiguration(request, configurationId, certStore, true);
166            
167            // Add a CertificateRequestStore GBean
168            AbstractName certReqStoreName = naming.createSiblingName(caKeystoreName, "geronimo-ca-cert-req-store", NameFactory.CERTIFICATE_REQUEST_STORE);
169            GBeanData certReqStore = new GBeanData(certReqStoreName, FileCertificateRequestStore.GBEAN_INFO);
170            certReqStore.setAttribute("directoryPath", URI.create(certReqStorePath));
171            certReqStore.setReferencePattern("ServerInfo", serverInfoName);
172            PortletManager.addGBeanToConfiguration(request, configurationId, certReqStore, true);
173            
174            // Add a CertificationAuthority GBean
175            AbstractName caName = naming.createSiblingName(caKeystoreName, "geronimo-ca", NameFactory.CERTIFICATION_AUTHORITY);
176            GBeanData ca = new GBeanData(caName, GeronimoCertificationAuthority.GBEAN_INFO);
177            ca.setReferencePattern("ServerInfo", serverInfoName);
178            ca.setReferencePattern("KeystoreInstance", caKeystoreName);
179            ca.setReferencePattern("CertificateStore", certStoreName);
180            ca.setReferencePattern("CertificateRequestStore", certReqStoreName);
181            PortletManager.addGBeanToConfiguration(request, configurationId, ca, true);
182        }
183    }