KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > se > anatom > ejbca > protocol > ProtocolScepHttpTest


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 se.anatom.ejbca.protocol;
15
16 import java.io.ByteArrayOutputStream JavaDoc;
17 import java.io.IOException JavaDoc;
18 import java.io.InputStream JavaDoc;
19 import java.io.OutputStream JavaDoc;
20 import java.net.HttpURLConnection JavaDoc;
21 import java.net.URL JavaDoc;
22 import java.net.URLEncoder JavaDoc;
23 import java.rmi.RemoteException JavaDoc;
24 import java.security.InvalidAlgorithmParameterException JavaDoc;
25 import java.security.InvalidKeyException JavaDoc;
26 import java.security.KeyPair JavaDoc;
27 import java.security.NoSuchAlgorithmException JavaDoc;
28 import java.security.NoSuchProviderException JavaDoc;
29 import java.security.PrivateKey JavaDoc;
30 import java.security.PublicKey JavaDoc;
31 import java.security.Signature JavaDoc;
32 import java.security.SignatureException JavaDoc;
33 import java.security.cert.CRLException JavaDoc;
34 import java.security.cert.CertStore JavaDoc;
35 import java.security.cert.CertStoreException JavaDoc;
36 import java.security.cert.CertificateEncodingException JavaDoc;
37 import java.security.cert.CertificateException JavaDoc;
38 import java.security.cert.X509CRL JavaDoc;
39 import java.security.cert.X509Certificate JavaDoc;
40 import java.util.Collection JavaDoc;
41 import java.util.Iterator JavaDoc;
42
43 import javax.ejb.DuplicateKeyException JavaDoc;
44 import javax.ejb.FinderException JavaDoc;
45 import javax.naming.Context JavaDoc;
46 import javax.naming.NamingException JavaDoc;
47
48 import junit.framework.TestCase;
49 import junit.framework.TestSuite;
50
51 import org.apache.commons.lang.StringUtils;
52 import org.apache.log4j.Logger;
53 import org.bouncycastle.asn1.ASN1OctetString;
54 import org.bouncycastle.asn1.ASN1Set;
55 import org.bouncycastle.asn1.DERObjectIdentifier;
56 import org.bouncycastle.asn1.DERPrintableString;
57 import org.bouncycastle.asn1.DERString;
58 import org.bouncycastle.asn1.cms.Attribute;
59 import org.bouncycastle.asn1.cms.AttributeTable;
60 import org.bouncycastle.cms.CMSEnvelopedData;
61 import org.bouncycastle.cms.CMSException;
62 import org.bouncycastle.cms.CMSProcessable;
63 import org.bouncycastle.cms.CMSSignedData;
64 import org.bouncycastle.cms.CMSSignedGenerator;
65 import org.bouncycastle.cms.RecipientInformation;
66 import org.bouncycastle.cms.RecipientInformationStore;
67 import org.bouncycastle.cms.SignerId;
68 import org.bouncycastle.cms.SignerInformation;
69 import org.bouncycastle.cms.SignerInformationStore;
70 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionHome;
71 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionRemote;
72 import org.ejbca.core.ejb.ra.IUserAdminSessionHome;
73 import org.ejbca.core.ejb.ra.IUserAdminSessionRemote;
74 import org.ejbca.core.model.SecConst;
75 import org.ejbca.core.model.approval.ApprovalException;
76 import org.ejbca.core.model.approval.WaitingForApprovalException;
77 import org.ejbca.core.model.authorization.AuthorizationDeniedException;
78 import org.ejbca.core.model.ca.caadmin.CAInfo;
79 import org.ejbca.core.model.ca.catoken.CATokenConstants;
80 import org.ejbca.core.model.log.Admin;
81 import org.ejbca.core.model.ra.UserDataConstants;
82 import org.ejbca.core.model.ra.raadmin.UserDoesntFullfillEndEntityProfile;
83 import org.ejbca.core.protocol.ResponseStatus;
84 import org.ejbca.core.protocol.ScepRequestMessage;
85 import org.ejbca.util.Base64;
86 import org.ejbca.util.CertTools;
87 import org.ejbca.util.KeyTools;
88
89 import com.meterware.httpunit.GetMethodWebRequest;
90 import com.meterware.httpunit.HttpUnitOptions;
91 import com.meterware.httpunit.WebConversation;
92 import com.meterware.httpunit.WebRequest;
93 import com.meterware.httpunit.WebResponse;
94
95 /** Tests http pages of scep
96  **/

97 public class ProtocolScepHttpTest extends TestCase {
98     private static Logger log = Logger.getLogger(ProtocolScepHttpTest.class);
99
100     private static final String JavaDoc httpReqPath = "http://127.0.0.1:8080/ejbca";
101     private static final String JavaDoc resourceScep = "publicweb/apply/scep/pkiclient.exe";
102     private static final String JavaDoc resourceScepNoCA = "publicweb/apply/scep/noca/pkiclient.exe";
103
104     static byte[] openscep = Base64.decode(("MIIGqwYJKoZIhvcNAQcCoIIGnDCCBpgCAQExDjAMBggqhkiG9w0CBQUAMIICuwYJ" +
105             "KoZIhvcNAQcBoIICrASCAqgwggKkBgkqhkiG9w0BBwOgggKVMIICkQIBADGB1TCB" +
106             "0gIBADA7MC8xDzANBgNVBAMTBlRlc3RDQTEPMA0GA1UEChMGQW5hVG9tMQswCQYD" +
107             "VQQGEwJTRQIIbzEhUVZYO3gwDQYJKoZIhvcNAQEBBQAEgYCksIoSXYsCQPot2DDW" +
108             "dexdFqLj1Fuz3xSpu/rLozXKxEY0n0W0JXRR9OxxuyqNw9cLZhiyWkNsJGbP/rEz" +
109             "yrXe9NXuLK5U8+qqE8OhnY9BhCxjeUJSLni6oCSi7YzwOqdg2KmifJrQQI/jZIiC" +
110             "tSISAtE6qi6DKQwLCkQLmokLrjCCAbIGCSqGSIb3DQEHATARBgUrDgMCBwQILYvZ" +
111             "rBWuC02AggGQW9o5MB/7LN4o9G4ZD1l2mHzS+g+Y/dT2qD/qIaQi1Mamv2oKx9eO" +
112             "uFtaGkBBGWZlIKg4mm/DFtvXqW8Y5ijAiQVHHPuRKNyIV6WVuFjNjhNlM+DWLJR+" +
113             "rpHEhvB6XeDo/pd+TyOKFcxedMPTD7U+j46yd46vKdmoKAiIF21R888uVSz3GDts" +
114             "NlqgvZ7VlaI++Tj7aPdOI7JTdQXZk2FWF7Ql0LBIPwk9keffptF5if5Y+aHqB0a2" +
115             "uQj1aE8Em15VG8p8MmLJOX0OA1aeqfxR0wk343r44UebliY2DE8cEnym/fmya30/" +
116             "7WYzJ7erWofO2ukg1yc93wUpyIKxt2RGIy5geqQCjCYSSGgaNFafEV2pnOVSx+7N" +
117             "9z/ICNQfDBD6b83MO7yPHC1cXcdREKHHeqaKyQLiVRk9+R/3D4vEZt682GRaUKOY" +
118             "PQXK1Be2nyZoo4gZs62nZVAliJ+chFkEUog9k9OsIvZRG7X+VEjVYBqxlE1S3ikt" +
119             "igFXiuLC/LDCi3IgVwQjfNx1/mhxsO7GSaCCAfswggH3MIIBYKADAgEDAiA4OEUy" +
120             "REVFNDcwNjhCQjM3RjE5QkE2NDdCRjAyRkQwRjANBgkqhkiG9w0BAQQFADAyMQsw" +
121             "CQYDVQQGEwJTZTERMA8GA1UEChMIUHJpbWVLZXkxEDAOBgNVBAMTB1RvbWFzIEcw" +
122             "HhcNMDMwNjAxMDgzNDQyWhcNMDMwNzAxMDgzNDQyWjAyMQswCQYDVQQGEwJTZTER" +
123             "MA8GA1UEChMIUHJpbWVLZXkxEDAOBgNVBAMTB1RvbWFzIEcwgZ8wDQYJKoZIhvcN" +
124             "AQEBBQADgY0AMIGJAoGBAOu47fpIQfzfSnEBTG2WJpKZz1891YLNulc7XgMk8hl3" +
125             "nVC4m34SaR7eXR3nCsorYEpPPmL3affaPFsBnNBQNoZLxKmQ1RKiDyu8dj90AKCP" +
126             "CFlIM2aJbKMiQad+dt45qse6k0yTrY3Yx0hMH76tRkDif4DjM5JUvdf4d/zlYcCz" +
127             "AgMBAAEwDQYJKoZIhvcNAQEEBQADgYEAGNoWI02kXNEA5sPHb3KEY8QZoYM5Kha1" +
128             "JA7HLmlXKy6geeJmk329CUnvF0Cr7zxbMkFRdUDUtR8omDDnGlBSOCkV6LLYH939" +
129             "Z8iysfaxigZkxUqUYGLtYHhsEjVgcpfKZVxTz0E2ocR2P+IuU04Duel/gU4My6Qv" +
130             "LDpwo1CQC10xggHDMIIBvwIBATBWMDIxCzAJBgNVBAYTAlNlMREwDwYDVQQKEwhQ" +
131             "cmltZUtleTEQMA4GA1UEAxMHVG9tYXMgRwIgODhFMkRFRTQ3MDY4QkIzN0YxOUJB" +
132             "NjQ3QkYwMkZEMEYwDAYIKoZIhvcNAgUFAKCBwTASBgpghkgBhvhFAQkCMQQTAjE5" +
133             "MBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTAzMDYw" +
134             "MTA4MzQ0MlowHwYJKoZIhvcNAQkEMRIEEBqGJFo7n4B8sFBCi54PckIwIAYKYIZI" +
135             "AYb4RQEJBTESBBA77Owxh2rbflhXsDYw3xsLMDAGCmCGSAGG+EUBCQcxIhMgODhF" +
136             "MkRFRTQ3MDY4QkIzN0YxOUJBNjQ3QkYwMkZEMEYwDQYJKoZIhvcNAQEBBQAEgYB4" +
137             "BPcw4NPIt4nMOFKSGg5oM1nGDPGFN7eorZV+/2uWiQfdtK4B4lzCTuNxWRT853dW" +
138             "dRDzXBCGEArlG8ef+vDD/HP9SX3MQ0NJWym48VI9bTpP/mJlUKSsfgDYHohvUlVI" +
139             "E5QFC6ILVLUmuWPGchUEAb8t30DDnmeXs8QxdqHfbQ==").getBytes());
140
141     private static Context JavaDoc ctx;
142     private static IUserAdminSessionRemote usersession;
143     private static int caid = 0;
144     private static Admin admin;
145     private static X509Certificate JavaDoc cacert = null;
146     private static KeyPair JavaDoc keys = null;
147     private static String JavaDoc caname = null;
148     private String JavaDoc transId = null;
149     private String JavaDoc senderNonce = null;
150
151     public static void main(String JavaDoc args[]) {
152         junit.textui.TestRunner.run(suite());
153     }
154
155
156     public static TestSuite suite() {
157         return new TestSuite(ProtocolScepHttpTest.class);
158     }
159
160
161     public ProtocolScepHttpTest(String JavaDoc name) throws Exception JavaDoc {
162         super(name);
163         // Install BouncyCastle provider
164
CertTools.installBCProvider();
165
166         // We want to get error responses without exceptions
167
HttpUnitOptions.setExceptionsThrownOnErrorStatus(false);
168
169         admin = new Admin(Admin.TYPE_BATCHCOMMANDLINE_USER);
170
171         ctx = getInitialContext();
172         Object JavaDoc obj = ctx.lookup("CAAdminSession");
173         ICAAdminSessionHome cahome = (ICAAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, ICAAdminSessionHome.class);
174         ICAAdminSessionRemote casession = cahome.create();
175         Collection JavaDoc caids = casession.getAvailableCAs(admin);
176         Iterator JavaDoc iter = caids.iterator();
177         if (iter.hasNext()) {
178             caid = ((Integer JavaDoc) iter.next()).intValue();
179         } else {
180             assertTrue("No active CA! Must have at least one active CA to run tests!", false);
181         }
182         CAInfo cainfo = casession.getCAInfo(admin, caid);
183         caname = cainfo.getName();
184         Collection JavaDoc certs = cainfo.getCertificateChain();
185         if (certs.size() > 0) {
186             Iterator JavaDoc certiter = certs.iterator();
187             X509Certificate JavaDoc cert = (X509Certificate JavaDoc) certiter.next();
188             String JavaDoc subject = CertTools.getSubjectDN(cert);
189             if (StringUtils.equals(subject, cainfo.getSubjectDN())) {
190                 // Make sure we have a BC certificate
191
cacert = CertTools.getCertfromByteArray(cert.getEncoded());
192             }
193         } else {
194             log.error("NO CACERT for caid " + caid);
195         }
196         obj = ctx.lookup("UserAdminSession");
197         IUserAdminSessionHome userhome = (IUserAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, IUserAdminSessionHome.class);
198         usersession = userhome.create();
199
200         if (keys == null) {
201             // Pre-generate key for all requests to speed things up a bit
202
keys = KeyTools.genKeys("512", CATokenConstants.KEYALGORITHM_RSA);
203         }
204     }
205
206     protected void setUp() throws Exception JavaDoc {
207     }
208
209     protected void tearDown() throws Exception JavaDoc {
210     }
211
212     private Context JavaDoc getInitialContext() throws NamingException JavaDoc {
213         Context JavaDoc ctx = new javax.naming.InitialContext JavaDoc();
214         return ctx;
215     }
216  
217     public void test01Access() throws Exception JavaDoc {
218         WebConversation wc = new WebConversation();
219         // Hit scep, gives a 400: Bad Request
220
WebRequest request = new GetMethodWebRequest(httpReqPath + '/' + resourceScep);
221         WebResponse response = wc.getResponse(request);
222         assertEquals("Response code", 400, response.getResponseCode());
223     }
224
225     /** Tests a random old scep message from OpenScep
226      * @throws Exception error
227      */

228     public void test02OpenScep() throws Exception JavaDoc {
229         log.debug(">test02OpenScep()");
230         // send message to server and see what happens
231
WebConversation wc = new WebConversation();
232         WebRequest request = new GetMethodWebRequest(httpReqPath + '/' + resourceScep);
233         request.setParameter("operation", "PKIOperation");
234         request.setParameter("message", new String JavaDoc(Base64.encode(openscep)));
235         WebResponse response = wc.getResponse(request);
236         // TODO: since our request most certainly uses the wrong CA cert to encrypt the
237
// request, it will fail. If we get something back, we came a little bit at least :)
238
// We should get a NOT_FOUND error back.
239
assertEquals("Response code", 404, response.getResponseCode());
240         log.debug("<test02OpenScep()");
241     }
242
243     public void test03ScepRequestOKSHA1() throws Exception JavaDoc {
244         log.debug(">test03ScepRequestOKSHA1()");
245         // find a CA create a user and
246
// send SCEP req to server and get good response with cert
247

248         // Make user that we know...
249
createScepUser();
250         
251         byte[] msgBytes = genScepRequest(false, CMSSignedGenerator.DIGEST_SHA1);
252         // Send message with GET
253
byte[] retMsg = sendScep(false, msgBytes, false);
254         assertNotNull(retMsg);
255         checkScepResponse(retMsg, "C=SE,O=PrimeKey,CN=sceptest", senderNonce, transId, false, CMSSignedGenerator.DIGEST_SHA1, false);
256         log.debug("<test03ScepRequestOKSHA1()");
257     }
258
259     public void test04ScepRequestOKMD5() throws Exception JavaDoc {
260         log.debug(">test04ScepRequestOKMD5()");
261         // find a CA create a user and
262
// send SCEP req to server and get good response with cert
263

264         // Make user that we know...
265
createScepUser();
266         
267         byte[] msgBytes = genScepRequest(false, CMSSignedGenerator.DIGEST_MD5);
268         // Send message with GET
269
byte[] retMsg = sendScep(false, msgBytes, false);
270         assertNotNull(retMsg);
271         checkScepResponse(retMsg, "C=SE,O=PrimeKey,CN=sceptest", senderNonce, transId, false, CMSSignedGenerator.DIGEST_MD5, false);
272         log.debug("<test04ScepRequestOKMD5()");
273     }
274
275     public void test05ScepRequestPostOK() throws Exception JavaDoc {
276         log.debug(">test05ScepRequestPostOK()");
277         // find a CA, create a user and
278
// send SCEP req to server and get good response with cert
279

280         createScepUser();
281         
282         byte[] msgBytes = genScepRequest(false, CMSSignedGenerator.DIGEST_SHA1);
283         // Send message with GET
284
byte[] retMsg = sendScep(true, msgBytes, false);
285         assertNotNull(retMsg);
286         checkScepResponse(retMsg, "C=SE,O=PrimeKey,CN=sceptest", senderNonce, transId, false, CMSSignedGenerator.DIGEST_SHA1, false);
287         log.debug(">test05ScepRequestPostOK()");
288     }
289
290     public void test06ScepRequestPostOKNoCA() throws Exception JavaDoc {
291         log.debug(">test06ScepRequestPostOKNoCA()");
292         // find a CA, create a user and
293
// send SCEP req to server and get good response with cert
294

295         createScepUser();
296         
297         byte[] msgBytes = genScepRequest(false, CMSSignedGenerator.DIGEST_SHA1);
298         // Send message with GET
299
byte[] retMsg = sendScep(true, msgBytes, true);
300         assertNotNull(retMsg);
301         checkScepResponse(retMsg, "C=SE,O=PrimeKey,CN=sceptest", senderNonce, transId, false, CMSSignedGenerator.DIGEST_SHA1, true);
302         log.debug(">test06ScepRequestPostOKNoCA()");
303     }
304
305     public void test07ScepGetCACert() throws Exception JavaDoc {
306         log.debug(">test07ScepGetCACert()");
307         String JavaDoc reqUrl = httpReqPath + '/' + resourceScep+"?operation=GetCACert&message="+URLEncoder.encode(caname, "UTF-8");
308         URL JavaDoc url = new URL JavaDoc(reqUrl);
309         HttpURLConnection JavaDoc con = (HttpURLConnection JavaDoc)url.openConnection();
310         con.setRequestMethod("GET");
311         con.getDoOutput();
312         con.connect();
313         assertEquals("Response code", 200, con.getResponseCode());
314         assertEquals("Content-Type", "application/x-x509-ca-cert", con.getContentType());
315         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
316         // This works for small requests, and SCEP requests are small enough
317
InputStream JavaDoc in = con.getInputStream();
318         int b = in.read();
319         while (b != -1) {
320             baos.write(b);
321             b = in.read();
322         }
323         baos.flush();
324         in.close();
325         byte[] respBytes = baos.toByteArray();
326         assertNotNull("Response can not be null.", respBytes);
327         assertTrue(respBytes.length > 0);
328         X509Certificate JavaDoc cert = CertTools.getCertfromByteArray(respBytes);
329         // Check that we got the right cert back
330
assertEquals(cacert.getSubjectDN().getName(), cert.getSubjectDN().getName());
331         log.debug(">test07ScepGetCACert()");
332     }
333
334     public void test08ScepGetCrl() throws Exception JavaDoc {
335         log.debug(">test08ScepGetCrl()");
336         byte[] msgBytes = genScepRequest(true, CMSSignedGenerator.DIGEST_SHA1);
337         // Send message with GET
338
byte[] retMsg = sendScep(false, msgBytes, false);
339         assertNotNull(retMsg);
340         checkScepResponse(retMsg, "C=SE,O=PrimeKey,CN=sceptest", senderNonce, transId, true, CMSSignedGenerator.DIGEST_SHA1, false);
341         log.debug(">test08ScepGetCrl()");
342     }
343     public void test09ScepGetCACaps() throws Exception JavaDoc {
344         log.debug(">test09ScepGetCACaps()");
345         String JavaDoc reqUrl = httpReqPath + '/' + resourceScep+"?operation=GetCACaps&message="+URLEncoder.encode(caname, "UTF-8");
346         URL JavaDoc url = new URL JavaDoc(reqUrl);
347         HttpURLConnection JavaDoc con = (HttpURLConnection JavaDoc)url.openConnection();
348         con.setRequestMethod("GET");
349         con.getDoOutput();
350         con.connect();
351         assertEquals("Response code", 200, con.getResponseCode());
352         assertEquals("Content-Type", "text/plain", con.getContentType());
353         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
354         // This works for small requests, and SCEP requests are small enough
355
InputStream JavaDoc in = con.getInputStream();
356         int b = in.read();
357         while (b != -1) {
358             baos.write(b);
359             b = in.read();
360         }
361         baos.flush();
362         in.close();
363         byte[] respBytes = baos.toByteArray();
364         assertNotNull("Response can not be null.", respBytes);
365         assertTrue(respBytes.length > 0);
366         assertEquals(new String JavaDoc(respBytes), "POSTPKIOperation\nSHA-1");
367         log.debug(">test09ScepGetCACaps()");
368     }
369     public void test99CleanUp() throws Exception JavaDoc {
370         // remove user
371
usersession.deleteUser(admin,"sceptest");
372         log.debug("deleted user: sceptest");
373     }
374     
375     //
376
// Private helper methods
377
//
378
private void createScepUser() throws RemoteException JavaDoc, AuthorizationDeniedException, FinderException JavaDoc, UserDoesntFullfillEndEntityProfile, ApprovalException, WaitingForApprovalException {
379         // Make user that we know...
380
boolean userExists = false;
381         try {
382             usersession.addUser(admin,"sceptest","foo123","C=SE,O=PrimeKey,CN=sceptest",null,"ocsptest@anatom.se",false,SecConst.EMPTY_ENDENTITYPROFILE,SecConst.CERTPROFILE_FIXED_ENDUSER,SecConst.USER_ENDUSER,SecConst.TOKEN_SOFT_PEM,0,caid);
383             log.debug("created user: sceptest, foo123, C=SE, O=PrimeKey, CN=sceptest");
384         } catch (RemoteException JavaDoc re) {
385             if (re.detail instanceof DuplicateKeyException JavaDoc) {
386                 userExists = true;
387             }
388         } catch (DuplicateKeyException JavaDoc dke) {
389             userExists = true;
390         }
391
392         if (userExists) {
393             log.debug("User sceptest already exists.");
394             usersession.setUserStatus(admin,"sceptest",UserDataConstants.STATUS_NEW);
395             log.debug("Reset status to NEW");
396         }
397         
398     }
399
400     private byte[] genScepRequest(boolean makeCrlReq, String JavaDoc digestoid) throws InvalidKeyException JavaDoc, NoSuchAlgorithmException JavaDoc, NoSuchProviderException JavaDoc, SignatureException JavaDoc, InvalidAlgorithmParameterException JavaDoc, CertStoreException JavaDoc, IOException JavaDoc, CMSException, CertificateEncodingException JavaDoc, IllegalStateException JavaDoc {
401         ScepRequestGenerator gen = new ScepRequestGenerator();
402         gen.setKeys(keys);
403         gen.setDigestOid(digestoid);
404         byte[] msgBytes = null;
405         if (makeCrlReq) {
406             msgBytes = gen.generateCrlReq("C=SE, O=PrimeKey, CN=sceptest", cacert);
407         } else {
408             msgBytes = gen.generateCertReq("C=SE, O=PrimeKey, CN=sceptest", "foo123", cacert);
409         }
410         assertNotNull(msgBytes);
411         transId = gen.getTransactionId();
412         assertNotNull(transId);
413         byte[] idBytes = Base64.decode(transId.getBytes());
414         assertTrue(idBytes.length == 16);
415         senderNonce = gen.getSenderNonce();
416         byte[] nonceBytes = Base64.decode(senderNonce.getBytes());
417         assertTrue(nonceBytes.length == 16);
418         return msgBytes;
419     }
420     
421     private void checkScepResponse(byte[] retMsg, String JavaDoc userDN, String JavaDoc senderNonce, String JavaDoc transId, boolean crlRep, String JavaDoc digestOid, boolean noca) throws CMSException, NoSuchProviderException JavaDoc, NoSuchAlgorithmException JavaDoc, CertStoreException JavaDoc, InvalidKeyException JavaDoc, CertificateException JavaDoc, SignatureException JavaDoc, CRLException JavaDoc {
422         //
423
// Parse response message
424
//
425
CMSSignedData s = new CMSSignedData(retMsg);
426         // The signer, i.e. the CA, check it's the right CA
427
SignerInformationStore signers = s.getSignerInfos();
428         Collection JavaDoc col = signers.getSigners();
429         assertTrue(col.size() > 0);
430         Iterator JavaDoc iter = col.iterator();
431         SignerInformation signerInfo = (SignerInformation)iter.next();
432         // Check that the message is signed with the correct digest alg
433
assertEquals(signerInfo.getDigestAlgOID(), digestOid);
434         SignerId sinfo = signerInfo.getSID();
435         // Check that the signer is the expected CA
436
assertEquals(CertTools.stringToBCDNString(cacert.getIssuerDN().getName()), CertTools.stringToBCDNString(sinfo.getIssuerAsString()));
437         // Verify the signature
438
boolean ret = signerInfo.verify(cacert.getPublicKey(), "BC");
439         assertTrue(ret);
440         // Get authenticated attributes
441
AttributeTable tab = signerInfo.getSignedAttributes();
442         // --Fail info
443
Attribute attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_failInfo));
444         // No failInfo on this success message
445
assertNull(attr);
446         // --Message type
447
attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_messageType));
448         assertNotNull(attr);
449         ASN1Set values = attr.getAttrValues();
450         assertEquals(values.size(), 1);
451         DERString str = DERPrintableString.getInstance((values.getObjectAt(0)));
452         String JavaDoc messageType = str.getString();
453         assertEquals("3", messageType);
454         // --Success status
455
attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_pkiStatus));
456         assertNotNull(attr);
457         values = attr.getAttrValues();
458         assertEquals(values.size(), 1);
459         str = DERPrintableString.getInstance((values.getObjectAt(0)));
460         assertEquals(ResponseStatus.SUCCESS.getValue(), str.getString());
461         // --SenderNonce
462
attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_senderNonce));
463         assertNotNull(attr);
464         values = attr.getAttrValues();
465         assertEquals(values.size(), 1);
466         ASN1OctetString octstr = ASN1OctetString.getInstance(values.getObjectAt(0));
467         // SenderNonce is something the server came up with, but it should be 16 chars
468
assertTrue(octstr.getOctets().length == 16);
469         // --Recipient Nonce
470
attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_recipientNonce));
471         assertNotNull(attr);
472         values = attr.getAttrValues();
473         assertEquals(values.size(), 1);
474         octstr = ASN1OctetString.getInstance(values.getObjectAt(0));
475         // recipient nonce should be the same as we sent away as sender nonce
476
assertEquals(senderNonce, new String JavaDoc(Base64.encode(octstr.getOctets())));
477         // --Transaction ID
478
attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_transId));
479         assertNotNull(attr);
480         values = attr.getAttrValues();
481         assertEquals(values.size(), 1);
482         str = DERPrintableString.getInstance((values.getObjectAt(0)));
483         // transid should be the same as the one we sent
484
assertEquals(transId, str.getString());
485         
486         //
487
// Check different message types
488
//
489
if (messageType.equals("3")) {
490             // First we extract the encrypted data from the CMS enveloped data contained
491
// within the CMS signed data
492
CMSProcessable sp = s.getSignedContent();
493             byte[] content = (byte[])sp.getContent();
494             CMSEnvelopedData ed = new CMSEnvelopedData(content);
495             RecipientInformationStore recipients = ed.getRecipientInfos();
496             Collection JavaDoc c = recipients.getRecipients();
497             assertEquals(c.size(), 1);
498             Iterator JavaDoc it = c.iterator();
499             byte[] decBytes = null;
500             RecipientInformation recipient = (RecipientInformation) it.next();
501             decBytes = recipient.getContent(keys.getPrivate(), "BC");
502             // This is yet another CMS signed data
503
CMSSignedData sd = new CMSSignedData(decBytes);
504             // Get certificates from the signed data
505
CertStore JavaDoc certstore = sd.getCertificatesAndCRLs("Collection","BC");
506             if (crlRep) {
507                 // We got a reply with a requested CRL
508
Collection JavaDoc crls = certstore.getCRLs(null);
509                 assertEquals(crls.size(), 1);
510                 it = crls.iterator();
511                 X509CRL JavaDoc retCrl = null;
512                 // CRL is first (and only)
513
retCrl = (X509CRL JavaDoc)it.next();
514                 System.out.println("Got CRL with DN: "+ retCrl.getIssuerDN().getName());
515 // try {
516
// FileOutputStream fos = new FileOutputStream("sceptest.der");
517
// fos.write(retCrl.getEncoded());
518
// fos.close();
519
// } catch (Exception e) {}
520
// check the returned CRL
521
assertEquals(cacert.getSubjectDN().getName(), retCrl.getIssuerDN().getName());
522                 retCrl.verify(cacert.getPublicKey());
523             } else {
524                 // We got a reply with a requested certificate
525
Collection JavaDoc certs = certstore.getCertificates(null);
526                 // EJBCA returns the issued cert and the CA cert (cisco vpn client requires that the ca cert is included)
527
if (noca) {
528                     assertEquals(certs.size(), 1);
529                 } else {
530                     assertEquals(certs.size(), 2);
531                 }
532                 it = certs.iterator();
533                 // Issued certificate must be first
534
boolean verified = false;
535                 boolean gotcacert = false;
536                 String JavaDoc mysubjectdn = CertTools.stringToBCDNString("C=SE,O=PrimeKey,CN=sceptest");
537                 while (it.hasNext()) {
538                     X509Certificate JavaDoc retcert = (X509Certificate JavaDoc)it.next();
539                     System.out.println("Got cert with DN: "+ retcert.getSubjectDN().getName());
540 // try {
541
// FileOutputStream fos = new FileOutputStream("sceptest.der");
542
// fos.write(retcert.getEncoded());
543
// fos.close();
544
// } catch (Exception e) {}
545

546                     // check the returned certificate
547
String JavaDoc subjectdn = CertTools.stringToBCDNString(retcert.getSubjectDN().getName());
548                     if (mysubjectdn.equals(subjectdn)) {
549                         // issued certificate
550
assertEquals(CertTools.stringToBCDNString("C=SE,O=PrimeKey,CN=sceptest"), subjectdn);
551                         assertEquals(cacert.getSubjectDN().getName(), retcert.getIssuerDN().getName());
552                         retcert.verify(cacert.getPublicKey());
553                         assertTrue(checkKeys(keys.getPrivate(), retcert.getPublicKey()));
554                         verified = true;
555                     } else {
556                         // ca certificate
557
assertEquals(cacert.getSubjectDN().getName(), retcert.getSubjectDN().getName());
558                         gotcacert = true;
559                     }
560                 }
561                 assertTrue(verified);
562                 if (noca) {
563                     assertFalse(gotcacert);
564                 } else {
565                     assertTrue(gotcacert);
566                 }
567             }
568         }
569         
570     }
571     /**
572      * checks that a public and private key matches by signing and verifying a message
573      */

574     private boolean checkKeys(PrivateKey JavaDoc priv, PublicKey JavaDoc pub) throws SignatureException JavaDoc, NoSuchAlgorithmException JavaDoc, InvalidKeyException JavaDoc {
575         Signature JavaDoc signer = Signature.getInstance("SHA1WithRSA");
576         signer.initSign(priv);
577         signer.update("PrimeKey".getBytes());
578         byte[] signature = signer.sign();
579         
580         Signature JavaDoc signer2 = Signature.getInstance("SHA1WithRSA");
581         signer2.initVerify(pub);
582         signer2.update("PrimeKey".getBytes());
583         return signer2.verify(signature);
584     }
585     private byte[] sendScep(boolean post, byte[] scepPackage, boolean noca) throws IOException JavaDoc, NoSuchProviderException JavaDoc {
586         // POST the SCEP request
587
// we are going to do a POST
588
String JavaDoc resource = resourceScep;
589         if (noca) {
590             resource = resourceScepNoCA;
591         }
592         String JavaDoc urlString = httpReqPath + '/' + resource+"?operation=PKIOperation";
593         log.debug("UrlString =" + urlString);
594         HttpURLConnection JavaDoc con = null;
595         if (post) {
596             URL JavaDoc url = new URL JavaDoc(urlString);
597             con = (HttpURLConnection JavaDoc)url.openConnection();
598             con.setDoOutput(true);
599             con.setRequestMethod("POST");
600             con.connect();
601             // POST it
602
OutputStream JavaDoc os = con.getOutputStream();
603             os.write(scepPackage);
604             os.close();
605         } else {
606             String JavaDoc reqUrl = urlString + "&message=" + URLEncoder.encode(new String JavaDoc(Base64.encode(scepPackage)),"UTF-8");
607             URL JavaDoc url = new URL JavaDoc(reqUrl);
608             con = (HttpURLConnection JavaDoc)url.openConnection();
609             con.setRequestMethod("GET");
610             con.getDoOutput();
611             con.connect();
612         }
613
614         assertEquals("Response code", 200, con.getResponseCode());
615         assertEquals("Content-Type", "application/x-pki-message", con.getContentType());
616         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
617         // This works for small requests, and SCEP requests are small enough
618
InputStream JavaDoc in = con.getInputStream();
619         int b = in.read();
620         while (b != -1) {
621             baos.write(b);
622             b = in.read();
623         }
624         baos.flush();
625         in.close();
626         byte[] respBytes = baos.toByteArray();
627         assertNotNull("Response can not be null.", respBytes);
628         assertTrue(respBytes.length > 0);
629         return respBytes;
630     }
631
632 }
633
Popular Tags