1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
|
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2015 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.client;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status.Family;
import javax.ws.rs.core.Response.StatusType;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.ProtocolException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.auth.params.AuthPNames;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.AuthPolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeLayeredSocketFactory;
import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.ClientParamsStack;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.client.EntityEnclosingRequestWrapper;
import org.apache.http.impl.client.RequestWrapper;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.jboss.resteasy.client.jaxrs.ProxyBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
import org.mozilla.jss.CryptoManager;
import org.mozilla.jss.CryptoManager.NotInitializedException;
import org.mozilla.jss.ssl.SSLAlertDescription;
import org.mozilla.jss.ssl.SSLAlertEvent;
import org.mozilla.jss.ssl.SSLAlertLevel;
import org.mozilla.jss.ssl.SSLCertificateApprovalCallback;
import org.mozilla.jss.ssl.SSLHandshakeCompletedEvent;
import org.mozilla.jss.ssl.SSLSocket;
import org.mozilla.jss.ssl.SSLSocketListener;
import com.netscape.certsrv.base.PKIException;
public class PKIConnection {
boolean verbose;
ClientConfig config;
DefaultHttpClient httpClient = new DefaultHttpClient();
SSLCertificateApprovalCallback callback;
ApacheHttpClient4Engine engine;
ResteasyClient resteasyClient;
int requestCounter;
int responseCounter;
File output;
public PKIConnection(ClientConfig config) {
this.config = config;
// Register https scheme.
Scheme scheme = new Scheme("https", 443, new JSSProtocolSocketFactory());
httpClient.getConnectionManager().getSchemeRegistry().register(scheme);
// Don't retry operations.
httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
if (config.getUsername() != null && config.getPassword() != null) {
List<String> authPref = new ArrayList<String>();
authPref.add(AuthPolicy.BASIC);
httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authPref);
httpClient.getCredentialsProvider().setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(config.getUsername(), config.getPassword()));
}
httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
requestCounter++;
if (verbose) {
System.out.println("HTTP request: "+request.getRequestLine());
for (Header header : request.getAllHeaders()) {
System.out.println(" "+header.getName()+": "+header.getValue());
}
}
if (output != null) {
File file = new File(output, "http-request-"+requestCounter);
storeRequest(file, request);
}
// Set the request parameter to follow redirections.
HttpParams params = request.getParams();
if (params instanceof ClientParamsStack) {
ClientParamsStack paramsStack = (ClientParamsStack)request.getParams();
params = paramsStack.getRequestParams();
}
HttpClientParams.setRedirecting(params, true);
}
});
httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
responseCounter++;
if (verbose) {
System.out.println("HTTP response: "+response.getStatusLine());
for (Header header : response.getAllHeaders()) {
System.out.println(" "+header.getName()+": "+header.getValue());
}
}
if (output != null) {
File file = new File(output, "http-response-"+responseCounter);
storeResponse(file, response);
}
}
});
httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context)
throws ProtocolException {
HttpUriRequest uriRequest = super.getRedirect(request, response, context);
URI uri = uriRequest.getURI();
if (verbose) System.out.println("HTTP redirect: "+uri);
// Redirect the original request to the new URI.
RequestWrapper wrapper;
if (request instanceof HttpEntityEnclosingRequest) {
wrapper = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest)request);
} else {
wrapper = new RequestWrapper(request);
}
wrapper.setURI(uri);
return wrapper;
}
@Override
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
throws ProtocolException {
// The default redirection policy does not redirect POST or PUT.
// This overrides the policy to follow redirections for all HTTP methods.
return response.getStatusLine().getStatusCode() == 302;
}
});
engine = new ApacheHttpClient4Engine(httpClient);
resteasyClient = new ResteasyClientBuilder().httpEngine(engine).build();
resteasyClient.register(PKIRESTProvider.class);
}
public boolean isVerbose() {
return verbose;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
public void setCallback(SSLCertificateApprovalCallback callback) {
this.callback = callback;
}
public void storeRequest(File file, HttpRequest request) throws IOException {
try (PrintStream out = new PrintStream(file)) {
out.println(request.getRequestLine());
for (Header header : request.getAllHeaders()) {
out.println(header.getName()+": "+header.getValue());
}
out.println();
if (request instanceof EntityEnclosingRequestWrapper) {
EntityEnclosingRequestWrapper wrapper = (EntityEnclosingRequestWrapper) request;
HttpEntity entity = wrapper.getEntity();
if (entity == null) return;
if (!entity.isRepeatable()) {
BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity);
wrapper.setEntity(bufferedEntity);
entity = bufferedEntity;
}
storeEntity(out, entity);
}
}
}
public void storeResponse(File file, HttpResponse response) throws IOException {
try (PrintStream out = new PrintStream(file)) {
out.println(response.getStatusLine());
for (Header header : response.getAllHeaders()) {
out.println(header.getName()+": "+header.getValue());
}
out.println();
if (response instanceof BasicHttpResponse) {
BasicHttpResponse basicResponse = (BasicHttpResponse) response;
HttpEntity entity = basicResponse.getEntity();
if (entity == null) return;
if (!entity.isRepeatable()) {
BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity);
basicResponse.setEntity(bufferedEntity);
entity = bufferedEntity;
}
storeEntity(out, entity);
}
}
}
public void storeEntity(OutputStream out, HttpEntity entity) throws IOException {
byte[] buffer = new byte[1024];
int c;
try (InputStream in = entity.getContent()) {
while ((c = in.read(buffer)) > 0) {
out.write(buffer, 0, c);
}
}
}
private class JSSProtocolSocketFactory implements SchemeSocketFactory, SchemeLayeredSocketFactory {
@Override
public Socket createSocket(HttpParams params) throws IOException {
return null;
}
@Override
public Socket connectSocket(Socket sock,
InetSocketAddress remoteAddress,
InetSocketAddress localAddress,
HttpParams params)
throws IOException,
UnknownHostException,
ConnectTimeoutException {
// Make sure certificate database is already initialized,
// otherwise SSLSocket will throw UnsatisfiedLinkError.
try {
CryptoManager.getInstance();
} catch (NotInitializedException e) {
throw new Error("Certificate database not initialized.", e);
}
String hostName = null;
int port = 0;
if (remoteAddress != null) {
hostName = remoteAddress.getHostName();
port = remoteAddress.getPort();
}
int localPort = 0;
InetAddress localAddr = null;
if (localAddress != null) {
localPort = localAddress.getPort();
localAddr = localAddress.getAddress();
}
SSLSocket socket;
if (sock == null) {
socket = new SSLSocket(InetAddress.getByName(hostName),
port,
localAddr,
localPort,
callback,
null);
} else {
socket = new SSLSocket(sock, hostName, callback, null);
}
// SSLSocket.setSSLVersionRange() needs to be exposed in JSS
// socket.setSSLVersionRange(SSLVersionRange.tls1_0, SSLVersionRange.tls1_2);
String certNickname = config.getCertNickname();
if (certNickname != null) {
if (verbose) System.out.println("Client certificate: "+certNickname);
socket.setClientCertNickname(certNickname);
}
socket.addSocketListener(new SSLSocketListener() {
@Override
public void alertReceived(SSLAlertEvent event) {
int intLevel = event.getLevel();
SSLAlertLevel level = SSLAlertLevel.valueOf(intLevel);
int intDescription = event.getDescription();
SSLAlertDescription description = SSLAlertDescription.valueOf(intDescription);
if (level == SSLAlertLevel.FATAL || verbose) {
System.err.println(level + ": SSL alert received: " + description);
}
}
@Override
public void alertSent(SSLAlertEvent event) {
int intLevel = event.getLevel();
SSLAlertLevel level = SSLAlertLevel.valueOf(intLevel);
int intDescription = event.getDescription();
SSLAlertDescription description = SSLAlertDescription.valueOf(intDescription);
if (level == SSLAlertLevel.FATAL || verbose) {
System.err.println(level + ": SSL alert sent: " + description);
}
}
@Override
public void handshakeCompleted(SSLHandshakeCompletedEvent event) {
}
});
return socket;
}
@Override
public boolean isSecure(Socket sock) {
// We only use this factory in the case of SSL Connections.
return true;
}
@Override
public Socket createLayeredSocket(Socket socket, String target, int port, HttpParams params)
throws IOException, UnknownHostException {
// This method implementation is required to get SSL working.
return null;
}
}
public <T> T createProxy(URI uri, Class<T> clazz) throws URISyntaxException {
ResteasyWebTarget target = resteasyClient.target(uri);
ProxyBuilder<T> builder = ProxyBuilder.builder(clazz, target);
String messageFormat = config.getMessageFormat();
if (messageFormat == null) messageFormat = PKIClient.MESSAGE_FORMATS[0];
if (!Arrays.asList(PKIClient.MESSAGE_FORMATS).contains(messageFormat)) {
throw new Error("Unsupported message format: " + messageFormat);
}
MediaType contentType = MediaType.valueOf("application/" + messageFormat);
builder.defaultConsumes(contentType);
builder.defaultProduces(contentType);
return builder.build();
}
public <T> T getEntity(Response response, Class<T> clazz) {
try {
Family family = response.getStatusInfo().getFamily();
if (!family.equals(Family.CLIENT_ERROR) && !family.equals(Family.SERVER_ERROR)) {
if (response.hasEntity())
return response.readEntity(clazz);
return null;
}
handleErrorResponse(response);
return null;
} finally {
response.close();
}
}
public <T> T getEntity(Response response, GenericType<T> clazz) {
try {
Family family = response.getStatusInfo().getFamily();
if (!family.equals(Family.CLIENT_ERROR) && !family.equals(Family.SERVER_ERROR)) {
if (response.hasEntity())
return response.readEntity(clazz);
return null;
}
handleErrorResponse(response);
return null;
} finally {
response.close();
}
}
private void handleErrorResponse(Response response) {
StatusType status = response.getStatusInfo();
MediaType contentType = response.getMediaType();
if (!MediaType.APPLICATION_XML_TYPE.equals(contentType)
&& !MediaType.APPLICATION_JSON_TYPE.equals(contentType))
throw new PKIException(status.getStatusCode(), status.getReasonPhrase());
PKIException.Data data = response.readEntity(PKIException.Data.class);
Class<?> exceptionClass;
try {
exceptionClass = Class.forName(data.getClassName());
} catch (ClassNotFoundException e) {
throw new PKIException(e.getMessage(), e);
}
try {
throw (PKIException) exceptionClass.getConstructor(PKIException.Data.class).newInstance(data);
} catch (InstantiationException
| IllegalAccessException
| IllegalArgumentException
| InvocationTargetException
| NoSuchMethodException
| SecurityException e) {
throw new PKIException(e.getMessage(), e);
}
}
public Response get(String path) throws Exception {
return get(path, Response.class);
}
public <T> T get(String path, Class<T> responseType) throws Exception {
String uri = config.getServerURI().toString();
if (path != null) {
uri += path;
}
ResteasyWebTarget target = resteasyClient.target(uri);
return target.request().get(responseType);
}
public String post(String path, MultivaluedMap<String, String> content) throws Exception {
String uri = config.getServerURI().toString();
if (path != null) {
uri += path;
}
ResteasyWebTarget target = resteasyClient.target(uri);
return target.request().post(Entity.form(content), String.class);
}
public File getOutput() {
return output;
}
public void setOutput(File output) {
this.output = output;
}
}
|