KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > ui > cli > CaImportCertCommand


1 /*************************************************************************
2  * *
3  * EJBCA: The OpenSource Certificate Authority *
4  * *
5  * This software is free software; you can redistribute it and/or *
6  * modify it under the terms of the GNU Lesser General Public *
7  * License as published by the Free Software Foundation; either *
8  * version 2.1 of the License, or any later version. *
9  * *
10  * See terms of license at gnu.org. *
11  * *
12  *************************************************************************/

13
14 package org.ejbca.ui.cli;
15
16 import java.io.File JavaDoc;
17 import java.security.cert.X509Certificate JavaDoc;
18 import java.util.Collection JavaDoc;
19 import java.util.Iterator JavaDoc;
20
21 import org.ejbca.core.ejb.ca.store.CertificateDataBean;
22 import org.ejbca.core.model.SecConst;
23 import org.ejbca.core.model.ca.caadmin.CAInfo;
24 import org.ejbca.core.model.ra.UserDataConstants;
25 import org.ejbca.core.model.ra.UserDataVO;
26 import org.ejbca.util.CertTools;
27 import org.ejbca.util.FileTools;
28
29
30
31
32
33 /**
34  * Imports a certificate file in the database.
35  *
36  * @author Marco Ferrante, (c) 2005 CSITA - University of Genoa (Italy)
37  * @version $Id: CaImportCertCommand.java,v 1.5 2006/08/12 09:49:30 herrvendil Exp $
38  */

39 public class CaImportCertCommand extends BaseCaAdminCommand {
40     /**
41      * Creates a new instance of CaInfoCommand
42      *
43      * @param args command line arguments
44      */

45     public CaImportCertCommand(String JavaDoc[] args) {
46         super(args);
47     }
48     
49     protected void usage() {
50         getOutputStream().println();
51         getOutputStream().println("Usage: importcert <username> <password> <caname> <status> "
52                 + "<certificate file> "
53                 + "[<endentityprofile> | <endentityprofile> <certificateprofile>]");
54         
55         getOutputStream().print(" Existing CAs: ");
56         try {
57             Collection JavaDoc cas = getCAAdminSessionRemote().getAvailableCAs(administrator);
58             boolean first = true;
59             Iterator JavaDoc iter = cas.iterator();
60             while (iter.hasNext()) {
61                 int caid = ((Integer JavaDoc)iter.next()).intValue();
62                 if (first) {
63                     first = false;
64                 } else {
65                     getOutputStream().print(", ");
66                 }
67                 CAInfo info = getCAAdminSessionRemote().getCAInfo(administrator, caid);
68                 getOutputStream().print(info.getName());
69             }
70         } catch (Exception JavaDoc e) {
71             getOutputStream().print("<unable to fetch available CA>");
72         }
73         getOutputStream().println();
74         getOutputStream().println(" Status: ACTIVE, REVOKED");
75         getOutputStream().println(" Certificate: must be PEM encoded");
76         getOutputStream().print(" End entity profiles: ");
77         try {
78             Collection JavaDoc eps = getRaAdminSession().getAuthorizedEndEntityProfileIds(administrator);
79             boolean first = true;
80             Iterator JavaDoc iter = eps.iterator();
81             while (iter.hasNext()) {
82                 int epid = ((Integer JavaDoc)iter.next()).intValue();
83                 if (first) {
84                     first = false;
85                 } else {
86                     getOutputStream().print(", ");
87                 }
88                 getOutputStream().print(getRaAdminSession().getEndEntityProfileName(administrator, epid));
89             }
90         }
91         catch (Exception JavaDoc e) {
92             getOutputStream().print("<unable to fetch available end entity profiles>");
93         }
94         getOutputStream().println();
95         getOutputStream().print(" Certificate profiles: ");
96         try {
97             Collection JavaDoc cps = getCertificateStoreSession().getAuthorizedCertificateProfileIds(administrator, CertificateDataBean.CERTTYPE_ENDENTITY);
98             boolean first = true;
99             Iterator JavaDoc iter = cps.iterator();
100             while (iter.hasNext()) {
101                 int cpid = ((Integer JavaDoc)iter.next()).intValue();
102                 if (first) {
103                     first = false;
104                 } else {
105                     getOutputStream().print(", ");
106                 }
107                 getOutputStream().print(getCertificateStoreSession().getCertificateProfileName(administrator, cpid));
108             }
109         } catch (Exception JavaDoc e) {
110             getOutputStream().print("<unable to fetch available certificate profile>");
111         }
112         getOutputStream().println();
113         getOutputStream().println(" If an End entity profile is selected it must allow selected Certificate profiles.");
114         getOutputStream().println();
115     }
116     
117     protected X509Certificate JavaDoc loadcert(String JavaDoc filename) throws Exception JavaDoc {
118         File JavaDoc certfile = new File JavaDoc(filename);
119         if (!certfile.exists()) {
120             throw new Exception JavaDoc(filename + " is not a file.");
121         }
122         try {
123             byte[] bytes = FileTools.getBytesFromPEM(
124                     FileTools.readFiletoBuffer(filename),
125                     "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");
126             X509Certificate JavaDoc cert = CertTools.getCertfromByteArray(bytes);
127             return cert;
128         } catch (java.io.IOException JavaDoc ioe) {
129             throw new Exception JavaDoc("Error reading " + filename + ": " + ioe.toString());
130         } catch (java.security.cert.CertificateException JavaDoc ce) {
131             throw new Exception JavaDoc(filename + " is not a valid X.509 certificate: " + ce.toString());
132         } catch (Exception JavaDoc e) {
133             throw new Exception JavaDoc("Error parsing certificate from " + filename + ": " + e.toString());
134         }
135     }
136         
137     
138     public void execute() throws IllegalAdminCommandException, ErrorAdminCommandException {
139         //getOutputStream().println("Certificate import tool. V 1.1, (c) 2005 CSITA - University of Genoa (Italy)");
140
debug(">execute()");
141         if ((args.length < 6) || (args.length > 8)) {
142             usage();
143             return;
144         }
145         
146         try {
147             int type = SecConst.USER_ENDUSER;
148             int status;
149             if ("ACTIVE".equalsIgnoreCase(args[4])) {
150                 status = CertificateDataBean.CERT_ACTIVE;
151             }
152             else if ("REVOKED".equalsIgnoreCase(args[4])) {
153                 status = CertificateDataBean.CERT_REVOKED;
154             }
155             else {
156                 throw new Exception JavaDoc("Invalid certificate status.");
157             }
158             
159             X509Certificate JavaDoc certificate = loadcert(args[5]);
160             String JavaDoc fingerprint = CertTools.getFingerprintAsString(certificate);
161             if (getCertificateStoreSession().findCertificateByFingerprint(administrator, fingerprint) != null) {
162                 throw new Exception JavaDoc("Certificate number '" + certificate.getSerialNumber().toString() + "' is already present.");
163             }
164             if (certificate.getNotAfter().compareTo(new java.util.Date JavaDoc()) < 0) {
165                 status = CertificateDataBean.CERT_EXPIRED;
166             }
167             
168             String JavaDoc username = args[1];
169             // Check if username already exists.
170
UserDataVO userdata = getAdminSession().findUser(administrator, username);
171             if (userdata != null) {
172                 if (userdata.getStatus() != UserDataConstants.STATUS_REVOKED) {
173                     throw new Exception JavaDoc("User " + username +
174                     " already exists; only revoked user can be overwrite.");
175                 }
176             }
177             String JavaDoc password = args[2];
178             CAInfo cainfo = getCAInfo(args[3]);
179             
180             CertTools.verify(certificate, cainfo.getCertificateChain());
181             
182             String JavaDoc email = CertTools.getEMailAddress(certificate);
183             
184             int endentityprofileid = SecConst.EMPTY_ENDENTITYPROFILE;
185             if (args.length > 6) {
186                 debug("Searching for End Entity Profile " + args[6]);
187                 endentityprofileid = getRaAdminSession().getEndEntityProfileId(administrator, args[6]);
188                 if (endentityprofileid == 0) {
189                     error("End Entity Profile " + args[6] + " doesn't exists.");
190                     throw new Exception JavaDoc("End Entity Profile '" + args[6] + "' doesn't exists.");
191                 }
192             }
193             
194             int certificateprofileid = SecConst.CERTPROFILE_FIXED_ENDUSER;
195             if (args.length > 7) {
196                 debug("Searching for Certificate Profile " + args[7]);
197                 certificateprofileid = getCertificateStoreSession().getCertificateProfileId(administrator, args[7]);
198                 if (certificateprofileid == SecConst.PROFILE_NO_PROFILE) {
199                     error("Certificate Profile " + args[7] + " doesn't exists.");
200                     throw new Exception JavaDoc("Certificate Profile '" + args[7] + "' doesn't exists.");
201                 }
202             }
203             
204             getOutputStream().println("Trying to add user:");
205             getOutputStream().println("Username: " + username);
206             getOutputStream().println("Password (hashed only): " + password);
207             getOutputStream().println("DN: " + certificate.getSubjectDN());
208             getOutputStream().println("CA Name: " + args[3]);
209             getOutputStream().println("Certificate Profile: " + getCertificateStoreSession().getCertificateProfileName(administrator, certificateprofileid));
210             getOutputStream().println("End Entity Profile: " +
211                     getRaAdminSession().getEndEntityProfileName(administrator, endentityprofileid));
212             
213             String JavaDoc subjectAltName = CertTools.getSubjectAlternativeName(certificate);
214             if (subjectAltName != null) {
215                 getOutputStream().println("SubjectAltName: " + subjectAltName);
216             }
217             getOutputStream().println("Type: " + type);
218             
219             debug("Loading/updating user " + username);
220             if (userdata == null) {
221                 getAdminSession().addUser(administrator,
222                         username, password,
223                         certificate.getSubjectDN().getName(),
224                         subjectAltName, email,
225                         false,
226                         endentityprofileid,
227                         certificateprofileid,
228                         type,
229                         SecConst.TOKEN_SOFT_BROWSERGEN,
230                         SecConst.NO_HARDTOKENISSUER,
231                         cainfo.getCAId());
232                 if (status == CertificateDataBean.CERT_ACTIVE) {
233                     getAdminSession().setUserStatus(administrator, username, UserDataConstants.STATUS_GENERATED);
234                 }
235                 else {
236                     getAdminSession().setUserStatus(administrator, username, UserDataConstants.STATUS_REVOKED);
237                 }
238                 getOutputStream().println("User '" + args[1] + "' has been added.");
239             }
240             else {
241                 getAdminSession().changeUser(administrator,
242                         username, password,
243                         certificate.getSubjectDN().getName(),
244                         subjectAltName, email,
245                         false,
246                         endentityprofileid,
247                         certificateprofileid,
248                         type,
249                         SecConst.TOKEN_SOFT_BROWSERGEN,
250                         SecConst.NO_HARDTOKENISSUER,
251                         (status == CertificateDataBean.CERT_ACTIVE ?
252                                 UserDataConstants.STATUS_GENERATED :
253                                     UserDataConstants.STATUS_REVOKED),
254                                     cainfo.getCAId());
255                 getOutputStream().println("User '" + args[1] + "' has been updated.");
256             }
257             
258             getCertificateStoreSession().storeCertificate(administrator,
259                     certificate, username,
260                     fingerprint,
261                     status, type);
262             
263             getOutputStream().println("Certificate number '" + certificate.getSerialNumber().toString() + "' has been added.");
264         }
265         catch (Exception JavaDoc e) {
266             getOutputStream().println("Error: " + e.getMessage());
267             usage();
268         }
269         debug("<execute()");
270     }
271 }
272
Popular Tags