Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/java/security/testlibrary/SimpleOCSPServer.java
41149 views
1
/*
2
* Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package sun.security.testlibrary;
27
28
import java.io.*;
29
import java.net.*;
30
import java.security.*;
31
import java.security.cert.CRLReason;
32
import java.security.cert.X509Certificate;
33
import java.security.cert.Extension;
34
import java.security.cert.CertificateException;
35
import java.security.cert.CertificateEncodingException;
36
import java.security.Signature;
37
import java.util.*;
38
import java.util.concurrent.*;
39
import java.text.SimpleDateFormat;
40
import java.math.BigInteger;
41
42
import sun.security.x509.*;
43
import sun.security.x509.PKIXExtensions;
44
import sun.security.provider.certpath.ResponderId;
45
import sun.security.provider.certpath.CertId;
46
import sun.security.provider.certpath.OCSPResponse;
47
import sun.security.provider.certpath.OCSPResponse.ResponseStatus;
48
import sun.security.util.*;
49
50
51
/**
52
* This is a simple OCSP server designed to listen and respond to incoming
53
* requests.
54
*/
55
public class SimpleOCSPServer {
56
private final Debug debug = Debug.getInstance("oserv");
57
private static final ObjectIdentifier OCSP_BASIC_RESPONSE_OID =
58
ObjectIdentifier.of(KnownOIDs.OCSPBasicResponse);
59
60
private static final SimpleDateFormat utcDateFmt =
61
new SimpleDateFormat("MMM dd yyyy, HH:mm:ss z");
62
63
static final int FREE_PORT = 0;
64
65
// CertStatus values
66
public static enum CertStatus {
67
CERT_STATUS_GOOD,
68
CERT_STATUS_REVOKED,
69
CERT_STATUS_UNKNOWN,
70
}
71
72
// Fields used for the networking portion of the responder
73
private ServerSocket servSocket;
74
private InetAddress listenAddress;
75
private int listenPort;
76
77
// Keystore information (certs, keys, etc.)
78
private KeyStore keystore;
79
private X509Certificate issuerCert;
80
private X509Certificate signerCert;
81
private PrivateKey signerKey;
82
83
// Fields used for the operational portions of the server
84
private boolean logEnabled = false;
85
private ExecutorService threadPool;
86
private volatile boolean started = false;
87
private volatile boolean serverReady = false;
88
private volatile boolean receivedShutdown = false;
89
private volatile boolean acceptConnections = true;
90
private volatile long delayMsec = 0;
91
92
// Fields used in the generation of responses
93
private long nextUpdateInterval = -1;
94
private Date nextUpdate = null;
95
private ResponderId respId;
96
private AlgorithmId sigAlgId;
97
private Map<CertId, CertStatusInfo> statusDb =
98
Collections.synchronizedMap(new HashMap<>());
99
100
/**
101
* Construct a SimpleOCSPServer using keystore, password, and alias
102
* parameters.
103
*
104
* @param ks the keystore to be used
105
* @param password the password to access key material in the keystore
106
* @param issuerAlias the alias of the issuer certificate
107
* @param signerAlias the alias of the signer certificate and key. A
108
* value of {@code null} means that the {@code issuerAlias} will be used
109
* to look up the signer key.
110
*
111
* @throws GeneralSecurityException if there are problems accessing the
112
* keystore or finding objects within the keystore.
113
* @throws IOException if a {@code ResponderId} cannot be generated from
114
* the signer certificate.
115
*/
116
public SimpleOCSPServer(KeyStore ks, String password, String issuerAlias,
117
String signerAlias) throws GeneralSecurityException, IOException {
118
this(null, FREE_PORT, ks, password, issuerAlias, signerAlias);
119
}
120
121
/**
122
* Construct a SimpleOCSPServer using specific network parameters,
123
* keystore, password, and alias.
124
*
125
* @param addr the address to bind the server to. A value of {@code null}
126
* means the server will bind to all interfaces.
127
* @param port the port to listen on. A value of {@code 0} will mean that
128
* the server will randomly pick an open ephemeral port to bind to.
129
* @param ks the keystore to be used
130
* @param password the password to access key material in the keystore
131
* @param issuerAlias the alias of the issuer certificate
132
* @param signerAlias the alias of the signer certificate and key. A
133
* value of {@code null} means that the {@code issuerAlias} will be used
134
* to look up the signer key.
135
*
136
* @throws GeneralSecurityException if there are problems accessing the
137
* keystore or finding objects within the keystore.
138
* @throws IOException if a {@code ResponderId} cannot be generated from
139
* the signer certificate.
140
*/
141
public SimpleOCSPServer(InetAddress addr, int port, KeyStore ks,
142
String password, String issuerAlias, String signerAlias)
143
throws GeneralSecurityException, IOException {
144
Objects.requireNonNull(ks, "Null keystore provided");
145
Objects.requireNonNull(issuerAlias, "Null issuerName provided");
146
147
utcDateFmt.setTimeZone(TimeZone.getTimeZone("GMT"));
148
149
keystore = ks;
150
issuerCert = (X509Certificate)ks.getCertificate(issuerAlias);
151
if (issuerCert == null) {
152
throw new IllegalArgumentException("Certificate for alias " +
153
issuerAlias + " not found");
154
}
155
156
if (signerAlias != null) {
157
signerCert = (X509Certificate)ks.getCertificate(signerAlias);
158
if (signerCert == null) {
159
throw new IllegalArgumentException("Certificate for alias " +
160
signerAlias + " not found");
161
}
162
signerKey = (PrivateKey)ks.getKey(signerAlias,
163
password.toCharArray());
164
if (signerKey == null) {
165
throw new IllegalArgumentException("PrivateKey for alias " +
166
signerAlias + " not found");
167
}
168
} else {
169
signerCert = issuerCert;
170
signerKey = (PrivateKey)ks.getKey(issuerAlias,
171
password.toCharArray());
172
if (signerKey == null) {
173
throw new IllegalArgumentException("PrivateKey for alias " +
174
issuerAlias + " not found");
175
}
176
}
177
178
sigAlgId = AlgorithmId.get("Sha256withRSA");
179
respId = new ResponderId(signerCert.getSubjectX500Principal());
180
listenAddress = addr;
181
listenPort = port;
182
}
183
184
/**
185
* Start the server. The server will bind to the specified network
186
* address and begin listening for incoming connections.
187
*
188
* @throws IOException if any number of things go wonky.
189
*/
190
public synchronized void start() throws IOException {
191
// You cannot start the server twice.
192
if (started) {
193
log("Server has already been started");
194
return;
195
} else {
196
started = true;
197
}
198
199
// Create and start the thread pool
200
threadPool = Executors.newFixedThreadPool(32, new ThreadFactory() {
201
@Override
202
public Thread newThread(Runnable r) {
203
Thread t = Executors.defaultThreadFactory().newThread(r);
204
t.setDaemon(true);
205
return t;
206
}
207
});
208
209
threadPool.submit(new Runnable() {
210
@Override
211
public void run() {
212
try (ServerSocket sSock = new ServerSocket()) {
213
servSocket = sSock;
214
servSocket.setReuseAddress(true);
215
servSocket.setSoTimeout(500);
216
servSocket.bind(new InetSocketAddress(listenAddress,
217
listenPort), 128);
218
log("Listening on " + servSocket.getLocalSocketAddress());
219
220
// Singal ready
221
serverReady = true;
222
223
// Update the listenPort with the new port number. If
224
// the server is restarted, it will bind to the same
225
// port rather than picking a new one.
226
listenPort = servSocket.getLocalPort();
227
228
// Main dispatch loop
229
while (!receivedShutdown) {
230
try {
231
Socket newConnection = servSocket.accept();
232
if (!acceptConnections) {
233
try {
234
log("Reject connection");
235
newConnection.close();
236
} catch (IOException e) {
237
// ignore
238
}
239
continue;
240
}
241
threadPool.submit(new OcspHandler(newConnection));
242
} catch (SocketTimeoutException timeout) {
243
// Nothing to do here. If receivedShutdown
244
// has changed to true then the loop will
245
// exit on its own.
246
} catch (IOException ioe) {
247
// Something bad happened, log and force a shutdown
248
log("Unexpected Exception: " + ioe);
249
stop();
250
}
251
}
252
253
log("Shutting down...");
254
threadPool.shutdown();
255
} catch (IOException ioe) {
256
err(ioe);
257
} finally {
258
// Reset state variables so the server can be restarted
259
receivedShutdown = false;
260
started = false;
261
serverReady = false;
262
}
263
}
264
});
265
}
266
267
/**
268
* Make the OCSP server reject incoming connections.
269
*/
270
public synchronized void rejectConnections() {
271
log("Reject OCSP connections");
272
acceptConnections = false;
273
}
274
275
/**
276
* Make the OCSP server accept incoming connections.
277
*/
278
public synchronized void acceptConnections() {
279
log("Accept OCSP connections");
280
acceptConnections = true;
281
}
282
283
284
/**
285
* Stop the OCSP server.
286
*/
287
public synchronized void stop() {
288
if (started) {
289
receivedShutdown = true;
290
log("Received shutdown notification");
291
}
292
}
293
294
/**
295
* Print {@code SimpleOCSPServer} operating parameters.
296
*
297
* @return the {@code SimpleOCSPServer} operating parameters in
298
* {@code String} form.
299
*/
300
@Override
301
public String toString() {
302
StringBuilder sb = new StringBuilder();
303
sb.append("OCSP Server:\n");
304
sb.append("----------------------------------------------\n");
305
sb.append("issuer: ").append(issuerCert.getSubjectX500Principal()).
306
append("\n");
307
sb.append("signer: ").append(signerCert.getSubjectX500Principal()).
308
append("\n");
309
sb.append("ResponderId: ").append(respId).append("\n");
310
sb.append("----------------------------------------------");
311
312
return sb.toString();
313
}
314
315
/**
316
* Helpful debug routine to hex dump byte arrays.
317
*
318
* @param data the array of bytes to dump to stdout.
319
*
320
* @return the hexdump of the byte array
321
*/
322
private static String dumpHexBytes(byte[] data) {
323
return dumpHexBytes(data, 16, "\n", " ");
324
}
325
326
/**
327
*
328
* @param data the array of bytes to dump to stdout.
329
* @param itemsPerLine the number of bytes to display per line
330
* if the {@code lineDelim} character is blank then all bytes will be
331
* printed on a single line.
332
* @param lineDelim the delimiter between lines
333
* @param itemDelim the delimiter between bytes
334
*
335
* @return The hexdump of the byte array
336
*/
337
private static String dumpHexBytes(byte[] data, int itemsPerLine,
338
String lineDelim, String itemDelim) {
339
StringBuilder sb = new StringBuilder();
340
if (data != null) {
341
for (int i = 0; i < data.length; i++) {
342
if (i % itemsPerLine == 0 && i != 0) {
343
sb.append(lineDelim);
344
}
345
sb.append(String.format("%02X", data[i])).append(itemDelim);
346
}
347
}
348
349
return sb.toString();
350
}
351
352
/**
353
* Enable or disable the logging feature.
354
*
355
* @param enable {@code true} to enable logging, {@code false} to
356
* disable it. The setting must be activated before the server calls
357
* its start method. Any calls after that have no effect.
358
*/
359
public void enableLog(boolean enable) {
360
if (!started) {
361
logEnabled = enable;
362
}
363
}
364
365
/**
366
* Sets the nextUpdate interval. Intervals will be calculated relative
367
* to the server startup time. When first set, the nextUpdate date is
368
* calculated based on the current time plus the interval. After that,
369
* calls to getNextUpdate() will return this date if it is still
370
* later than current time. If not, the Date will be updated to the
371
* next interval that is later than current time. This value must be set
372
* before the server has had its start method called. Calls made after
373
* the server has been started have no effect.
374
*
375
* @param interval the recurring time interval in seconds used to
376
* calculate nextUpdate times. A value less than or equal to 0 will
377
* disable the nextUpdate feature.
378
*/
379
public synchronized void setNextUpdateInterval(long interval) {
380
if (!started) {
381
if (interval <= 0) {
382
nextUpdateInterval = -1;
383
nextUpdate = null;
384
log("nexUpdate support has been disabled");
385
} else {
386
nextUpdateInterval = interval * 1000;
387
nextUpdate = new Date(System.currentTimeMillis() +
388
nextUpdateInterval);
389
log("nextUpdate set to " + nextUpdate);
390
}
391
}
392
}
393
394
/**
395
* Return the nextUpdate {@code Date} object for this server. If the
396
* nextUpdate date has already passed, set a new nextUpdate based on
397
* the nextUpdate interval and return that date.
398
*
399
* @return a {@code Date} object set to the nextUpdate field for OCSP
400
* responses.
401
*/
402
private synchronized Date getNextUpdate() {
403
if (nextUpdate != null && nextUpdate.before(new Date())) {
404
long nuEpochTime = nextUpdate.getTime();
405
long currentTime = System.currentTimeMillis();
406
407
// Keep adding nextUpdate intervals until you reach a date
408
// that is later than current time.
409
while (currentTime >= nuEpochTime) {
410
nuEpochTime += nextUpdateInterval;
411
}
412
413
// Set the nextUpdate for future threads
414
nextUpdate = new Date(nuEpochTime);
415
log("nextUpdate updated to new value: " + nextUpdate);
416
}
417
return nextUpdate;
418
}
419
420
/**
421
* Add entries into the responder's status database.
422
*
423
* @param newEntries a map of {@code CertStatusInfo} objects, keyed on
424
* their serial number (as a {@code BigInteger}). All serial numbers
425
* are assumed to have come from this responder's issuer certificate.
426
*
427
* @throws IOException if a CertId cannot be generated.
428
*/
429
public void updateStatusDb(Map<BigInteger, CertStatusInfo> newEntries)
430
throws IOException {
431
if (newEntries != null) {
432
for (BigInteger serial : newEntries.keySet()) {
433
CertStatusInfo info = newEntries.get(serial);
434
if (info != null) {
435
CertId cid = new CertId(issuerCert,
436
new SerialNumber(serial));
437
statusDb.put(cid, info);
438
log("Added entry for serial " + serial + "(" +
439
info.getType() + ")");
440
}
441
}
442
}
443
}
444
445
/**
446
* Check the status database for revocation information one one or more
447
* certificates.
448
*
449
* @param reqList the list of {@code LocalSingleRequest} objects taken
450
* from the incoming OCSP request.
451
*
452
* @return a {@code Map} of {@code CertStatusInfo} objects keyed by their
453
* {@code CertId} values, for each single request passed in. Those
454
* CertIds not found in the statusDb will have returned List members with
455
* a status of UNKNOWN.
456
*/
457
private Map<CertId, CertStatusInfo> checkStatusDb(
458
List<LocalOcspRequest.LocalSingleRequest> reqList) {
459
// TODO figure out what, if anything to do with request extensions
460
Map<CertId, CertStatusInfo> returnMap = new HashMap<>();
461
462
for (LocalOcspRequest.LocalSingleRequest req : reqList) {
463
CertId cid = req.getCertId();
464
CertStatusInfo info = statusDb.get(cid);
465
if (info != null) {
466
log("Status for SN " + cid.getSerialNumber() + ": " +
467
info.getType());
468
returnMap.put(cid, info);
469
} else {
470
log("Status for SN " + cid.getSerialNumber() +
471
" not found, using CERT_STATUS_UNKNOWN");
472
returnMap.put(cid,
473
new CertStatusInfo(CertStatus.CERT_STATUS_UNKNOWN));
474
}
475
}
476
477
return Collections.unmodifiableMap(returnMap);
478
}
479
480
/**
481
* Set the digital signature algorithm used to sign OCSP responses.
482
*
483
* @param algName The algorithm name
484
*
485
* @throws NoSuchAlgorithmException if the algorithm name is invalid.
486
*/
487
public void setSignatureAlgorithm(String algName)
488
throws NoSuchAlgorithmException {
489
if (!started) {
490
sigAlgId = AlgorithmId.get(algName);
491
}
492
}
493
494
/**
495
* Get the port the OCSP server is running on.
496
*
497
* @return the port that the OCSP server is running on, or -1 if the
498
* server has not yet been bound to a port.
499
*/
500
public int getPort() {
501
if (serverReady) {
502
InetSocketAddress inetSock =
503
(InetSocketAddress)servSocket.getLocalSocketAddress();
504
return inetSock.getPort();
505
} else {
506
return -1;
507
}
508
}
509
510
/**
511
* Use to check if OCSP server is ready to accept connection.
512
*
513
* @return true if server ready, false otherwise
514
*/
515
public boolean isServerReady() {
516
return serverReady;
517
}
518
519
/**
520
* Set a delay between the reception of the request and production of
521
* the response.
522
*
523
* @param delayMillis the number of milliseconds to wait before acting
524
* on the incoming request.
525
*/
526
public void setDelay(long delayMillis) {
527
delayMsec = delayMillis > 0 ? delayMillis : 0;
528
if (delayMsec > 0) {
529
log("OCSP latency set to " + delayMsec + " milliseconds.");
530
} else {
531
log("OCSP latency disabled");
532
}
533
}
534
535
/**
536
* Log a message to stdout.
537
*
538
* @param message the message to log
539
*/
540
private synchronized void log(String message) {
541
if (logEnabled || debug != null) {
542
System.out.println("[" + Thread.currentThread().getName() + "]: " +
543
message);
544
}
545
}
546
547
/**
548
* Log an error message on the stderr stream.
549
*
550
* @param message the message to log
551
*/
552
private static synchronized void err(String message) {
553
System.out.println("[" + Thread.currentThread().getName() + "]: " +
554
message);
555
}
556
557
/**
558
* Log exception information on the stderr stream.
559
*
560
* @param exc the exception to dump information about
561
*/
562
private static synchronized void err(Throwable exc) {
563
System.out.print("[" + Thread.currentThread().getName() +
564
"]: Exception: ");
565
exc.printStackTrace(System.out);
566
}
567
568
/**
569
* The {@code CertStatusInfo} class defines an object used to return
570
* information from the internal status database. The data in this
571
* object may be used to construct OCSP responses.
572
*/
573
public static class CertStatusInfo {
574
private CertStatus certStatusType;
575
private CRLReason reason;
576
private Date revocationTime;
577
578
/**
579
* Create a Certificate status object by providing the status only.
580
* If the status is {@code REVOKED} then current time is assumed
581
* for the revocation time.
582
*
583
* @param statType the status for this entry.
584
*/
585
public CertStatusInfo(CertStatus statType) {
586
this(statType, null, null);
587
}
588
589
/**
590
* Create a CertStatusInfo providing both type and revocation date
591
* (if applicable).
592
*
593
* @param statType the status for this entry.
594
* @param revDate if applicable, the date that revocation took place.
595
* A value of {@code null} indicates that current time should be used.
596
* If the value of {@code statType} is not {@code CERT_STATUS_REVOKED},
597
* then the {@code revDate} parameter is ignored.
598
*/
599
public CertStatusInfo(CertStatus statType, Date revDate) {
600
this(statType, revDate, null);
601
}
602
603
/**
604
* Create a CertStatusInfo providing type, revocation date
605
* (if applicable) and revocation reason.
606
*
607
* @param statType the status for this entry.
608
* @param revDate if applicable, the date that revocation took place.
609
* A value of {@code null} indicates that current time should be used.
610
* If the value of {@code statType} is not {@code CERT_STATUS_REVOKED},
611
* then the {@code revDate} parameter is ignored.
612
* @param revReason the reason the certificate was revoked. A value of
613
* {@code null} means that no reason was provided.
614
*/
615
public CertStatusInfo(CertStatus statType, Date revDate,
616
CRLReason revReason) {
617
Objects.requireNonNull(statType, "Cert Status must be non-null");
618
certStatusType = statType;
619
switch (statType) {
620
case CERT_STATUS_GOOD:
621
case CERT_STATUS_UNKNOWN:
622
revocationTime = null;
623
break;
624
case CERT_STATUS_REVOKED:
625
revocationTime = revDate != null ? (Date)revDate.clone() :
626
new Date();
627
break;
628
default:
629
throw new IllegalArgumentException("Unknown status type: " +
630
statType);
631
}
632
}
633
634
/**
635
* Get the cert status type
636
*
637
* @return the status applied to this object (e.g.
638
* {@code CERT_STATUS_GOOD}, {@code CERT_STATUS_UNKNOWN}, etc.)
639
*/
640
public CertStatus getType() {
641
return certStatusType;
642
}
643
644
/**
645
* Get the revocation time (if applicable).
646
*
647
* @return the revocation time as a {@code Date} object, or
648
* {@code null} if not applicable (i.e. if the certificate hasn't been
649
* revoked).
650
*/
651
public Date getRevocationTime() {
652
return (revocationTime != null ? (Date)revocationTime.clone() :
653
null);
654
}
655
656
/**
657
* Get the revocation reason.
658
*
659
* @return the revocation reason, or {@code null} if one was not
660
* provided.
661
*/
662
public CRLReason getRevocationReason() {
663
return reason;
664
}
665
}
666
667
/**
668
* Runnable task that handles incoming OCSP Requests and returns
669
* responses.
670
*/
671
private class OcspHandler implements Runnable {
672
private final Socket sock;
673
InetSocketAddress peerSockAddr;
674
675
/**
676
* Construct an {@code OcspHandler}.
677
*
678
* @param incomingSocket the socket the server created on accept()
679
*/
680
private OcspHandler(Socket incomingSocket) {
681
sock = incomingSocket;
682
}
683
684
/**
685
* Run the OCSP Request parser and construct a response to be sent
686
* back to the client.
687
*/
688
@Override
689
public void run() {
690
// If we have implemented a delay to simulate network latency
691
// wait out the delay here before any other processing.
692
try {
693
if (delayMsec > 0) {
694
Thread.sleep(delayMsec);
695
}
696
} catch (InterruptedException ie) {
697
// Just log the interrupted sleep
698
log("Delay of " + delayMsec + " milliseconds was interrupted");
699
}
700
701
try (Socket ocspSocket = sock;
702
InputStream in = ocspSocket.getInputStream();
703
OutputStream out = ocspSocket.getOutputStream()) {
704
peerSockAddr =
705
(InetSocketAddress)ocspSocket.getRemoteSocketAddress();
706
String[] headerTokens = readLine(in).split(" ");
707
LocalOcspRequest ocspReq = null;
708
LocalOcspResponse ocspResp = null;
709
ResponseStatus respStat = ResponseStatus.INTERNAL_ERROR;
710
try {
711
if (headerTokens[0] != null) {
712
log("Received incoming HTTP " + headerTokens[0] +
713
" from " + peerSockAddr);
714
switch (headerTokens[0]) {
715
case "POST":
716
ocspReq = parseHttpOcspPost(in);
717
break;
718
case "GET":
719
ocspReq = parseHttpOcspGet(headerTokens);
720
break;
721
default:
722
respStat = ResponseStatus.MALFORMED_REQUEST;
723
throw new IOException("Not a GET or POST");
724
}
725
} else {
726
respStat = ResponseStatus.MALFORMED_REQUEST;
727
throw new IOException("Unable to get HTTP method");
728
}
729
730
if (ocspReq != null) {
731
log(ocspReq.toString());
732
// Get responses for all CertIds in the request
733
Map<CertId, CertStatusInfo> statusMap =
734
checkStatusDb(ocspReq.getRequests());
735
if (statusMap.isEmpty()) {
736
respStat = ResponseStatus.UNAUTHORIZED;
737
} else {
738
ocspResp = new LocalOcspResponse(
739
ResponseStatus.SUCCESSFUL, statusMap,
740
ocspReq.getExtensions());
741
}
742
} else {
743
respStat = ResponseStatus.MALFORMED_REQUEST;
744
throw new IOException("Found null request");
745
}
746
} catch (IOException | RuntimeException exc) {
747
err(exc);
748
}
749
if (ocspResp == null) {
750
ocspResp = new LocalOcspResponse(respStat);
751
}
752
sendResponse(out, ocspResp);
753
} catch (IOException | CertificateException exc) {
754
err(exc);
755
}
756
}
757
758
/**
759
* Send an OCSP response on an {@code OutputStream}.
760
*
761
* @param out the {@code OutputStream} on which to send the response.
762
* @param resp the OCSP response to send.
763
*
764
* @throws IOException if an encoding error occurs.
765
*/
766
public void sendResponse(OutputStream out, LocalOcspResponse resp)
767
throws IOException {
768
StringBuilder sb = new StringBuilder();
769
770
byte[] respBytes;
771
try {
772
respBytes = resp.getBytes();
773
} catch (RuntimeException re) {
774
err(re);
775
return;
776
}
777
778
sb.append("HTTP/1.0 200 OK\r\n");
779
sb.append("Content-Type: application/ocsp-response\r\n");
780
sb.append("Content-Length: ").append(respBytes.length);
781
sb.append("\r\n\r\n");
782
783
out.write(sb.toString().getBytes("UTF-8"));
784
out.write(respBytes);
785
log(resp.toString());
786
}
787
788
/**
789
* Parse the incoming HTTP POST of an OCSP Request.
790
*
791
* @param inStream the input stream from the socket bound to this
792
* {@code OcspHandler}.
793
*
794
* @return the OCSP Request as a {@code LocalOcspRequest}
795
*
796
* @throws IOException if there are network related issues or problems
797
* occur during parsing of the OCSP request.
798
* @throws CertificateException if one or more of the certificates in
799
* the OCSP request cannot be read/parsed.
800
*/
801
private LocalOcspRequest parseHttpOcspPost(InputStream inStream)
802
throws IOException, CertificateException {
803
boolean endOfHeader = false;
804
boolean properContentType = false;
805
int length = -1;
806
807
while (!endOfHeader) {
808
String[] lineTokens = readLine(inStream).split(" ");
809
if (lineTokens[0].isEmpty()) {
810
endOfHeader = true;
811
} else if (lineTokens[0].equalsIgnoreCase("Content-Type:")) {
812
if (lineTokens[1] == null ||
813
!lineTokens[1].equals(
814
"application/ocsp-request")) {
815
log("Unknown Content-Type: " +
816
(lineTokens[1] != null ?
817
lineTokens[1] : "<NULL>"));
818
return null;
819
} else {
820
properContentType = true;
821
log("Content-Type = " + lineTokens[1]);
822
}
823
} else if (lineTokens[0].equalsIgnoreCase("Content-Length:")) {
824
if (lineTokens[1] != null) {
825
length = Integer.parseInt(lineTokens[1]);
826
log("Content-Length = " + length);
827
}
828
}
829
}
830
831
// Okay, make sure we got what we needed from the header, then
832
// read the remaining OCSP Request bytes
833
if (properContentType && length >= 0) {
834
byte[] ocspBytes = new byte[length];
835
inStream.read(ocspBytes);
836
return new LocalOcspRequest(ocspBytes);
837
} else {
838
return null;
839
}
840
}
841
842
/**
843
* Parse the incoming HTTP GET of an OCSP Request.
844
*
845
* @param headerTokens the individual String tokens from the first
846
* line of the HTTP GET.
847
*
848
* @return the OCSP Request as a {@code LocalOcspRequest}
849
*
850
* @throws IOException if there are network related issues or problems
851
* occur during parsing of the OCSP request.
852
* @throws CertificateException if one or more of the certificates in
853
* the OCSP request cannot be read/parsed.
854
*/
855
private LocalOcspRequest parseHttpOcspGet(String[] headerTokens)
856
throws IOException, CertificateException {
857
// We have already established headerTokens[0] to be "GET".
858
// We should have the URL-encoded base64 representation of the
859
// OCSP request in headerTokens[1]. We need to strip any leading
860
// "/" off before decoding.
861
return new LocalOcspRequest(Base64.getMimeDecoder().decode(
862
URLDecoder.decode(headerTokens[1].replaceAll("/", ""),
863
"UTF-8")));
864
}
865
866
/**
867
* Read a line of text that is CRLF-delimited.
868
*
869
* @param is the {@code InputStream} tied to the socket
870
* for this {@code OcspHandler}
871
*
872
* @return a {@code String} consisting of the line of text
873
* read from the stream with the CRLF stripped.
874
*
875
* @throws IOException if any I/O error occurs.
876
*/
877
private String readLine(InputStream is) throws IOException {
878
PushbackInputStream pbis = new PushbackInputStream(is);
879
ByteArrayOutputStream bos = new ByteArrayOutputStream();
880
boolean done = false;
881
while (!done) {
882
byte b = (byte)pbis.read();
883
if (b == '\r') {
884
byte bNext = (byte)pbis.read();
885
if (bNext == '\n' || bNext == -1) {
886
done = true;
887
} else {
888
pbis.unread(bNext);
889
bos.write(b);
890
}
891
} else if (b == -1) {
892
done = true;
893
} else {
894
bos.write(b);
895
}
896
}
897
898
return new String(bos.toByteArray(), "UTF-8");
899
}
900
}
901
902
903
/**
904
* Simple nested class to handle OCSP requests without making
905
* changes to sun.security.provider.certpath.OCSPRequest
906
*/
907
public class LocalOcspRequest {
908
909
private byte[] nonce;
910
private byte[] signature = null;
911
private AlgorithmId algId = null;
912
private int version = 0;
913
private GeneralName requestorName = null;
914
private Map<String, Extension> extensions = Collections.emptyMap();
915
private final List<LocalSingleRequest> requestList = new ArrayList<>();
916
private final List<X509Certificate> certificates = new ArrayList<>();
917
918
/**
919
* Construct a {@code LocalOcspRequest} from its DER encoding.
920
*
921
* @param requestBytes the DER-encoded bytes
922
*
923
* @throws IOException if decoding errors occur
924
* @throws CertificateException if certificates are found in the
925
* OCSP request and they do not parse correctly.
926
*/
927
private LocalOcspRequest(byte[] requestBytes) throws IOException,
928
CertificateException {
929
Objects.requireNonNull(requestBytes, "Received null input");
930
931
DerInputStream dis = new DerInputStream(requestBytes);
932
933
// Parse the top-level structure, it should have no more than
934
// two elements.
935
DerValue[] topStructs = dis.getSequence(2);
936
for (DerValue dv : topStructs) {
937
if (dv.tag == DerValue.tag_Sequence) {
938
parseTbsRequest(dv);
939
} else if (dv.isContextSpecific((byte)0)) {
940
parseSignature(dv);
941
} else {
942
throw new IOException("Unknown tag at top level: " +
943
dv.tag);
944
}
945
}
946
}
947
948
/**
949
* Parse the signature block from an OCSP request
950
*
951
* @param sigSequence a {@code DerValue} containing the signature
952
* block at the outer sequence datum.
953
*
954
* @throws IOException if any non-certificate-based parsing errors occur
955
* @throws CertificateException if certificates are found in the
956
* OCSP request and they do not parse correctly.
957
*/
958
private void parseSignature(DerValue sigSequence)
959
throws IOException, CertificateException {
960
DerValue[] sigItems = sigSequence.data.getSequence(3);
961
if (sigItems.length != 3) {
962
throw new IOException("Invalid number of signature items: " +
963
"expected 3, got " + sigItems.length);
964
}
965
966
algId = AlgorithmId.parse(sigItems[0]);
967
signature = sigItems[1].getBitString();
968
969
if (sigItems[2].isContextSpecific((byte)0)) {
970
DerValue[] certDerItems = sigItems[2].data.getSequence(4);
971
int i = 0;
972
for (DerValue dv : certDerItems) {
973
X509Certificate xc = new X509CertImpl(dv);
974
certificates.add(xc);
975
}
976
} else {
977
throw new IOException("Invalid tag in signature block: " +
978
sigItems[2].tag);
979
}
980
}
981
982
/**
983
* Parse the to-be-signed request data
984
*
985
* @param tbsReqSeq a {@code DerValue} object containing the to-be-
986
* signed OCSP request at the outermost SEQUENCE tag.
987
* @throws IOException if any parsing errors occur
988
*/
989
private void parseTbsRequest(DerValue tbsReqSeq) throws IOException {
990
while (tbsReqSeq.data.available() > 0) {
991
DerValue dv = tbsReqSeq.data.getDerValue();
992
if (dv.isContextSpecific((byte)0)) {
993
// The version was explicitly called out
994
version = dv.data.getInteger();
995
} else if (dv.isContextSpecific((byte)1)) {
996
// A GeneralName was provided
997
requestorName = new GeneralName(dv.data.getDerValue());
998
} else if (dv.isContextSpecific((byte)2)) {
999
// Parse the extensions
1000
DerValue[] extItems = dv.data.getSequence(2);
1001
extensions = parseExtensions(extItems);
1002
} else if (dv.tag == DerValue.tag_Sequence) {
1003
while (dv.data.available() > 0) {
1004
requestList.add(new LocalSingleRequest(dv.data));
1005
}
1006
}
1007
}
1008
}
1009
1010
/**
1011
* Parse a SEQUENCE of extensions. This routine is used both
1012
* at the overall request level and down at the singleRequest layer.
1013
*
1014
* @param extDerItems an array of {@code DerValue} items, each one
1015
* consisting of a DER-encoded extension.
1016
*
1017
* @return a {@code Map} of zero or more extensions,
1018
* keyed by its object identifier in {@code String} form.
1019
*
1020
* @throws IOException if any parsing errors occur.
1021
*/
1022
private Map<String, Extension> parseExtensions(DerValue[] extDerItems)
1023
throws IOException {
1024
Map<String, Extension> extMap = new HashMap<>();
1025
1026
if (extDerItems != null && extDerItems.length != 0) {
1027
for (DerValue extDerVal : extDerItems) {
1028
sun.security.x509.Extension ext =
1029
new sun.security.x509.Extension(extDerVal);
1030
extMap.put(ext.getId(), ext);
1031
}
1032
}
1033
1034
return extMap;
1035
}
1036
1037
/**
1038
* Return the list of single request objects in this OCSP request.
1039
*
1040
* @return an unmodifiable {@code List} of zero or more requests.
1041
*/
1042
private List<LocalSingleRequest> getRequests() {
1043
return Collections.unmodifiableList(requestList);
1044
}
1045
1046
/**
1047
* Return the list of X.509 Certificates in this OCSP request.
1048
*
1049
* @return an unmodifiable {@code List} of zero or more
1050
* {@cpde X509Certificate} objects.
1051
*/
1052
private List<X509Certificate> getCertificates() {
1053
return Collections.unmodifiableList(certificates);
1054
}
1055
1056
/**
1057
* Return the map of OCSP request extensions.
1058
*
1059
* @return an unmodifiable {@code Map} of zero or more
1060
* {@code Extension} objects, keyed by their object identifiers
1061
* in {@code String} form.
1062
*/
1063
private Map<String, Extension> getExtensions() {
1064
return Collections.unmodifiableMap(extensions);
1065
}
1066
1067
/**
1068
* Display the {@code LocalOcspRequest} in human readable form.
1069
*
1070
* @return a {@code String} representation of the
1071
* {@code LocalOcspRequest}
1072
*/
1073
@Override
1074
public String toString() {
1075
StringBuilder sb = new StringBuilder();
1076
1077
sb.append(String.format("OCSP Request: Version %d (0x%X)",
1078
version + 1, version)).append("\n");
1079
if (requestorName != null) {
1080
sb.append("Requestor Name: ").append(requestorName).
1081
append("\n");
1082
}
1083
1084
int requestCtr = 0;
1085
for (LocalSingleRequest lsr : requestList) {
1086
sb.append("Request [").append(requestCtr++).append("]\n");
1087
sb.append(lsr).append("\n");
1088
}
1089
if (!extensions.isEmpty()) {
1090
sb.append("Extensions (").append(extensions.size()).
1091
append(")\n");
1092
for (Extension ext : extensions.values()) {
1093
sb.append("\t").append(ext).append("\n");
1094
}
1095
}
1096
if (signature != null) {
1097
sb.append("Signature: ").append(algId).append("\n");
1098
sb.append(dumpHexBytes(signature)).append("\n");
1099
int certCtr = 0;
1100
for (X509Certificate cert : certificates) {
1101
sb.append("Certificate [").append(certCtr++).append("]").
1102
append("\n");
1103
sb.append("\tSubject: ");
1104
sb.append(cert.getSubjectX500Principal()).append("\n");
1105
sb.append("\tIssuer: ");
1106
sb.append(cert.getIssuerX500Principal()).append("\n");
1107
sb.append("\tSerial: ").append(cert.getSerialNumber());
1108
}
1109
}
1110
1111
return sb.toString();
1112
}
1113
1114
/**
1115
* Inner class designed to handle the decoding/representation of
1116
* single requests within a {@code LocalOcspRequest} object.
1117
*/
1118
public class LocalSingleRequest {
1119
private final CertId cid;
1120
private Map<String, Extension> extensions = Collections.emptyMap();
1121
1122
private LocalSingleRequest(DerInputStream dis)
1123
throws IOException {
1124
DerValue[] srItems = dis.getSequence(2);
1125
1126
// There should be 1, possibly 2 DerValue items
1127
if (srItems.length == 1 || srItems.length == 2) {
1128
// The first parsable item should be the mandatory CertId
1129
cid = new CertId(srItems[0].data);
1130
if (srItems.length == 2) {
1131
if (srItems[1].isContextSpecific((byte)0)) {
1132
DerValue[] extDerItems = srItems[1].data.getSequence(2);
1133
extensions = parseExtensions(extDerItems);
1134
} else {
1135
throw new IOException("Illegal tag in Request " +
1136
"extensions: " + srItems[1].tag);
1137
}
1138
}
1139
} else {
1140
throw new IOException("Invalid number of items in " +
1141
"Request (" + srItems.length + ")");
1142
}
1143
}
1144
1145
/**
1146
* Get the {@code CertId} for this single request.
1147
*
1148
* @return the {@code CertId} for this single request.
1149
*/
1150
private CertId getCertId() {
1151
return cid;
1152
}
1153
1154
/**
1155
* Return the map of single request extensions.
1156
*
1157
* @return an unmodifiable {@code Map} of zero or more
1158
* {@code Extension} objects, keyed by their object identifiers
1159
* in {@code String} form.
1160
*/
1161
private Map<String, Extension> getExtensions() {
1162
return Collections.unmodifiableMap(extensions);
1163
}
1164
1165
/**
1166
* Display the {@code LocalSingleRequest} in human readable form.
1167
*
1168
* @return a {@code String} representation of the
1169
* {@code LocalSingleRequest}
1170
*/
1171
@Override
1172
public String toString() {
1173
StringBuilder sb = new StringBuilder();
1174
sb.append("CertId, Algorithm = ");
1175
sb.append(cid.getHashAlgorithm()).append("\n");
1176
sb.append("\tIssuer Name Hash: ");
1177
sb.append(dumpHexBytes(cid.getIssuerNameHash(), 256, "", ""));
1178
sb.append("\n");
1179
sb.append("\tIssuer Key Hash: ");
1180
sb.append(dumpHexBytes(cid.getIssuerKeyHash(), 256, "", ""));
1181
sb.append("\n");
1182
sb.append("\tSerial Number: ").append(cid.getSerialNumber());
1183
if (!extensions.isEmpty()) {
1184
sb.append("Extensions (").append(extensions.size()).
1185
append(")\n");
1186
for (Extension ext : extensions.values()) {
1187
sb.append("\t").append(ext).append("\n");
1188
}
1189
}
1190
1191
return sb.toString();
1192
}
1193
}
1194
}
1195
1196
/**
1197
* Simple nested class to handle OCSP requests without making
1198
* changes to sun.security.provider.certpath.OCSPResponse
1199
*/
1200
public class LocalOcspResponse {
1201
private final int version = 0;
1202
private final OCSPResponse.ResponseStatus responseStatus;
1203
private final Map<CertId, CertStatusInfo> respItemMap;
1204
private final Date producedAtDate;
1205
private final List<LocalSingleResponse> singleResponseList =
1206
new ArrayList<>();
1207
private final Map<String, Extension> responseExtensions;
1208
private byte[] signature;
1209
private final List<X509Certificate> certificates;
1210
private final byte[] encodedResponse;
1211
1212
/**
1213
* Constructor for the generation of non-successful responses
1214
*
1215
* @param respStat the OCSP response status.
1216
*
1217
* @throws IOException if an error happens during encoding
1218
* @throws NullPointerException if {@code respStat} is {@code null}
1219
* or {@code respStat} is successful.
1220
*/
1221
public LocalOcspResponse(OCSPResponse.ResponseStatus respStat)
1222
throws IOException {
1223
this(respStat, null, null);
1224
}
1225
1226
/**
1227
* Construct a response from a list of certificate
1228
* status objects and extensions.
1229
*
1230
* @param respStat the status of the entire response
1231
* @param itemMap a {@code Map} of {@code CertId} objects and their
1232
* respective revocation statuses from the server's response DB.
1233
* @param reqExtensions a {@code Map} of request extensions
1234
*
1235
* @throws IOException if an error happens during encoding
1236
* @throws NullPointerException if {@code respStat} is {@code null}
1237
* or {@code respStat} is successful, and a {@code null} {@code itemMap}
1238
* has been provided.
1239
*/
1240
public LocalOcspResponse(OCSPResponse.ResponseStatus respStat,
1241
Map<CertId, CertStatusInfo> itemMap,
1242
Map<String, Extension> reqExtensions) throws IOException {
1243
responseStatus = Objects.requireNonNull(respStat,
1244
"Illegal null response status");
1245
if (responseStatus == ResponseStatus.SUCCESSFUL) {
1246
respItemMap = Objects.requireNonNull(itemMap,
1247
"SUCCESSFUL responses must have a response map");
1248
producedAtDate = new Date();
1249
1250
// Turn the answerd from the response DB query into a list
1251
// of single responses.
1252
for (CertId id : itemMap.keySet()) {
1253
singleResponseList.add(
1254
new LocalSingleResponse(id, itemMap.get(id)));
1255
}
1256
1257
responseExtensions = setResponseExtensions(reqExtensions);
1258
certificates = new ArrayList<>();
1259
if (signerCert != issuerCert) {
1260
certificates.add(signerCert);
1261
}
1262
certificates.add(issuerCert);
1263
} else {
1264
respItemMap = null;
1265
producedAtDate = null;
1266
responseExtensions = null;
1267
certificates = null;
1268
}
1269
encodedResponse = this.getBytes();
1270
}
1271
1272
/**
1273
* Set the response extensions based on the request extensions
1274
* that were received. Right now, this is limited to the
1275
* OCSP nonce extension.
1276
*
1277
* @param reqExts a {@code Map} of zero or more request extensions
1278
*
1279
* @return a {@code Map} of zero or more response extensions, keyed
1280
* by the extension object identifier in {@code String} form.
1281
*/
1282
private Map<String, Extension> setResponseExtensions(
1283
Map<String, Extension> reqExts) {
1284
Map<String, Extension> respExts = new HashMap<>();
1285
String ocspNonceStr = PKIXExtensions.OCSPNonce_Id.toString();
1286
1287
if (reqExts != null) {
1288
for (String id : reqExts.keySet()) {
1289
if (id.equals(ocspNonceStr)) {
1290
// We found a nonce, add it into the response extensions
1291
Extension ext = reqExts.get(id);
1292
if (ext != null) {
1293
respExts.put(id, ext);
1294
log("Added OCSP Nonce to response");
1295
} else {
1296
log("Error: Found nonce entry, but found null " +
1297
"value. Skipping");
1298
}
1299
}
1300
}
1301
}
1302
1303
return respExts;
1304
}
1305
1306
/**
1307
* Get the DER-encoded response bytes for this response
1308
*
1309
* @return a byte array containing the DER-encoded bytes for
1310
* the response
1311
*
1312
* @throws IOException if any encoding errors occur
1313
*/
1314
private byte[] getBytes() throws IOException {
1315
DerOutputStream outerSeq = new DerOutputStream();
1316
DerOutputStream responseStream = new DerOutputStream();
1317
responseStream.putEnumerated(responseStatus.ordinal());
1318
if (responseStatus == ResponseStatus.SUCCESSFUL &&
1319
respItemMap != null) {
1320
encodeResponseBytes(responseStream);
1321
}
1322
1323
// Commit the outermost sequence bytes
1324
outerSeq.write(DerValue.tag_Sequence, responseStream);
1325
return outerSeq.toByteArray();
1326
}
1327
1328
private void encodeResponseBytes(DerOutputStream responseStream)
1329
throws IOException {
1330
DerOutputStream explicitZero = new DerOutputStream();
1331
DerOutputStream respItemStream = new DerOutputStream();
1332
1333
respItemStream.putOID(OCSP_BASIC_RESPONSE_OID);
1334
1335
byte[] basicOcspBytes = encodeBasicOcspResponse();
1336
respItemStream.putOctetString(basicOcspBytes);
1337
explicitZero.write(DerValue.tag_Sequence, respItemStream);
1338
responseStream.write(DerValue.createTag(DerValue.TAG_CONTEXT,
1339
true, (byte)0), explicitZero);
1340
}
1341
1342
private byte[] encodeBasicOcspResponse() throws IOException {
1343
DerOutputStream outerSeq = new DerOutputStream();
1344
DerOutputStream basicORItemStream = new DerOutputStream();
1345
1346
// Encode the tbsResponse
1347
byte[] tbsResponseBytes = encodeTbsResponse();
1348
basicORItemStream.write(tbsResponseBytes);
1349
1350
try {
1351
sigAlgId.derEncode(basicORItemStream);
1352
1353
// Create the signature
1354
Signature sig = Signature.getInstance(sigAlgId.getName());
1355
sig.initSign(signerKey);
1356
sig.update(tbsResponseBytes);
1357
signature = sig.sign();
1358
basicORItemStream.putBitString(signature);
1359
} catch (GeneralSecurityException exc) {
1360
err(exc);
1361
throw new IOException(exc);
1362
}
1363
1364
// Add certificates
1365
try {
1366
DerOutputStream certStream = new DerOutputStream();
1367
ArrayList<DerValue> certList = new ArrayList<>();
1368
if (signerCert != issuerCert) {
1369
certList.add(new DerValue(signerCert.getEncoded()));
1370
}
1371
certList.add(new DerValue(issuerCert.getEncoded()));
1372
DerValue[] dvals = new DerValue[certList.size()];
1373
certStream.putSequence(certList.toArray(dvals));
1374
basicORItemStream.write(DerValue.createTag(DerValue.TAG_CONTEXT,
1375
true, (byte)0), certStream);
1376
} catch (CertificateEncodingException cex) {
1377
err(cex);
1378
throw new IOException(cex);
1379
}
1380
1381
// Commit the outermost sequence bytes
1382
outerSeq.write(DerValue.tag_Sequence, basicORItemStream);
1383
return outerSeq.toByteArray();
1384
}
1385
1386
private byte[] encodeTbsResponse() throws IOException {
1387
DerOutputStream outerSeq = new DerOutputStream();
1388
DerOutputStream tbsStream = new DerOutputStream();
1389
1390
// Note: We're not going explicitly assert the version
1391
tbsStream.write(respId.getEncoded());
1392
tbsStream.putGeneralizedTime(producedAtDate);
1393
1394
// Sequence of responses
1395
encodeSingleResponses(tbsStream);
1396
1397
// TODO: add response extension support
1398
encodeExtensions(tbsStream);
1399
1400
outerSeq.write(DerValue.tag_Sequence, tbsStream);
1401
return outerSeq.toByteArray();
1402
}
1403
1404
private void encodeSingleResponses(DerOutputStream tbsStream)
1405
throws IOException {
1406
DerValue[] srDerVals = new DerValue[singleResponseList.size()];
1407
int srDvCtr = 0;
1408
1409
for (LocalSingleResponse lsr : singleResponseList) {
1410
srDerVals[srDvCtr++] = new DerValue(lsr.getBytes());
1411
}
1412
1413
tbsStream.putSequence(srDerVals);
1414
}
1415
1416
private void encodeExtensions(DerOutputStream tbsStream)
1417
throws IOException {
1418
DerOutputStream extSequence = new DerOutputStream();
1419
DerOutputStream extItems = new DerOutputStream();
1420
1421
for (Extension ext : responseExtensions.values()) {
1422
ext.encode(extItems);
1423
}
1424
extSequence.write(DerValue.tag_Sequence, extItems);
1425
tbsStream.write(DerValue.createTag(DerValue.TAG_CONTEXT, true,
1426
(byte)1), extSequence);
1427
}
1428
1429
@Override
1430
public String toString() {
1431
StringBuilder sb = new StringBuilder();
1432
1433
sb.append("OCSP Response: ").append(responseStatus).append("\n");
1434
if (responseStatus == ResponseStatus.SUCCESSFUL) {
1435
sb.append("Response Type: ").
1436
append(OCSP_BASIC_RESPONSE_OID.toString()).append("\n");
1437
sb.append(String.format("Version: %d (0x%X)", version + 1,
1438
version)).append("\n");
1439
sb.append("Responder Id: ").append(respId.toString()).
1440
append("\n");
1441
sb.append("Produced At: ").
1442
append(utcDateFmt.format(producedAtDate)).append("\n");
1443
1444
int srCtr = 0;
1445
for (LocalSingleResponse lsr : singleResponseList) {
1446
sb.append("SingleResponse [").append(srCtr++).append("]\n");
1447
sb.append(lsr);
1448
}
1449
1450
if (!responseExtensions.isEmpty()) {
1451
sb.append("Extensions (").append(responseExtensions.size()).
1452
append(")\n");
1453
for (Extension ext : responseExtensions.values()) {
1454
sb.append("\t").append(ext).append("\n");
1455
}
1456
} else {
1457
sb.append("\n");
1458
}
1459
1460
if (signature != null) {
1461
sb.append("Signature: ").append(sigAlgId).append("\n");
1462
sb.append(dumpHexBytes(signature)).append("\n");
1463
int certCtr = 0;
1464
for (X509Certificate cert : certificates) {
1465
sb.append("Certificate [").append(certCtr++).append("]").
1466
append("\n");
1467
sb.append("\tSubject: ");
1468
sb.append(cert.getSubjectX500Principal()).append("\n");
1469
sb.append("\tIssuer: ");
1470
sb.append(cert.getIssuerX500Principal()).append("\n");
1471
sb.append("\tSerial: ").append(cert.getSerialNumber());
1472
sb.append("\n");
1473
}
1474
}
1475
}
1476
1477
return sb.toString();
1478
}
1479
1480
private class LocalSingleResponse {
1481
private final CertId certId;
1482
private final CertStatusInfo csInfo;
1483
private final Date thisUpdate;
1484
private final Date lsrNextUpdate;
1485
private final Map<String, Extension> singleExtensions;
1486
1487
public LocalSingleResponse(CertId cid, CertStatusInfo info) {
1488
certId = Objects.requireNonNull(cid, "CertId must be non-null");
1489
csInfo = Objects.requireNonNull(info,
1490
"CertStatusInfo must be non-null");
1491
1492
// For now, we'll keep things simple and make the thisUpdate
1493
// field the same as the producedAt date.
1494
thisUpdate = producedAtDate;
1495
lsrNextUpdate = getNextUpdate();
1496
1497
// TODO Add extensions support
1498
singleExtensions = Collections.emptyMap();
1499
}
1500
1501
@Override
1502
public String toString() {
1503
StringBuilder sb = new StringBuilder();
1504
sb.append("Certificate Status: ").append(csInfo.getType());
1505
sb.append("\n");
1506
if (csInfo.getType() == CertStatus.CERT_STATUS_REVOKED) {
1507
sb.append("Revocation Time: ");
1508
sb.append(utcDateFmt.format(csInfo.getRevocationTime()));
1509
sb.append("\n");
1510
if (csInfo.getRevocationReason() != null) {
1511
sb.append("Revocation Reason: ");
1512
sb.append(csInfo.getRevocationReason()).append("\n");
1513
}
1514
}
1515
1516
sb.append("CertId, Algorithm = ");
1517
sb.append(certId.getHashAlgorithm()).append("\n");
1518
sb.append("\tIssuer Name Hash: ");
1519
sb.append(dumpHexBytes(certId.getIssuerNameHash(), 256, "", ""));
1520
sb.append("\n");
1521
sb.append("\tIssuer Key Hash: ");
1522
sb.append(dumpHexBytes(certId.getIssuerKeyHash(), 256, "", ""));
1523
sb.append("\n");
1524
sb.append("\tSerial Number: ").append(certId.getSerialNumber());
1525
sb.append("\n");
1526
sb.append("This Update: ");
1527
sb.append(utcDateFmt.format(thisUpdate)).append("\n");
1528
if (lsrNextUpdate != null) {
1529
sb.append("Next Update: ");
1530
sb.append(utcDateFmt.format(lsrNextUpdate)).append("\n");
1531
}
1532
1533
if (!singleExtensions.isEmpty()) {
1534
sb.append("Extensions (").append(singleExtensions.size()).
1535
append(")\n");
1536
for (Extension ext : singleExtensions.values()) {
1537
sb.append("\t").append(ext).append("\n");
1538
}
1539
}
1540
1541
return sb.toString();
1542
}
1543
1544
public byte[] getBytes() throws IOException {
1545
byte[] nullData = { };
1546
DerOutputStream responseSeq = new DerOutputStream();
1547
DerOutputStream srStream = new DerOutputStream();
1548
1549
// Encode the CertId
1550
certId.encode(srStream);
1551
1552
// Next, encode the CertStatus field
1553
CertStatus csiType = csInfo.getType();
1554
switch (csiType) {
1555
case CERT_STATUS_GOOD:
1556
srStream.write(DerValue.createTag(DerValue.TAG_CONTEXT,
1557
false, (byte)0), nullData);
1558
break;
1559
case CERT_STATUS_REVOKED:
1560
DerOutputStream revInfo = new DerOutputStream();
1561
revInfo.putGeneralizedTime(csInfo.getRevocationTime());
1562
CRLReason revReason = csInfo.getRevocationReason();
1563
if (revReason != null) {
1564
byte[] revDer = new byte[3];
1565
revDer[0] = DerValue.tag_Enumerated;
1566
revDer[1] = 1;
1567
revDer[2] = (byte)revReason.ordinal();
1568
revInfo.write(DerValue.createTag(
1569
DerValue.TAG_CONTEXT, true, (byte)0),
1570
revDer);
1571
}
1572
srStream.write(DerValue.createTag(
1573
DerValue.TAG_CONTEXT, true, (byte)1),
1574
revInfo);
1575
break;
1576
case CERT_STATUS_UNKNOWN:
1577
srStream.write(DerValue.createTag(DerValue.TAG_CONTEXT,
1578
false, (byte)2), nullData);
1579
break;
1580
default:
1581
throw new IOException("Unknown CertStatus: " + csiType);
1582
}
1583
1584
// Add the necessary dates
1585
srStream.putGeneralizedTime(thisUpdate);
1586
if (lsrNextUpdate != null) {
1587
DerOutputStream nuStream = new DerOutputStream();
1588
nuStream.putGeneralizedTime(lsrNextUpdate);
1589
srStream.write(DerValue.createTag(DerValue.TAG_CONTEXT,
1590
true, (byte)0), nuStream);
1591
}
1592
1593
// TODO add singleResponse Extension support
1594
1595
// Add the single response to the response output stream
1596
responseSeq.write(DerValue.tag_Sequence, srStream);
1597
return responseSeq.toByteArray();
1598
}
1599
}
1600
}
1601
}
1602
1603