forked from fizzed/cloudhopper-smpp
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathCertificateValidator.java
More file actions
290 lines (257 loc) · 10 KB
/
CertificateValidator.java
File metadata and controls
290 lines (257 loc) · 10 KB
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
package com.cloudhopper.smpp.ssl;
/*
* #%L
* ch-smpp
* %%
* Copyright (C) 2009 - 2013 Cloudhopper by Twitter
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.security.GeneralSecurityException;
import java.security.InvalidParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Security;
import java.security.cert.CRL;
import java.security.cert.CertPathBuilder;
import java.security.cert.CertPathBuilderResult;
import java.security.cert.CertPathValidator;
import java.security.cert.CertStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.PKIXBuilderParameters;
import java.security.cert.X509CertSelector;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Convenience class to handle validation of certificates, aliases and keystores
*
* Allows specifying Certificate Revocation List (CRL), as well as enabling
* CRL Distribution Points Protocol (CRLDP) certificate extension support,
* and also enabling On-Line Certificate Status Protocol (OCSP) support.
*
* IMPORTANT: at least one of the above mechanisms *MUST* be configured and
* operational, otherwise certificate validation *WILL FAIL* unconditionally.
*
* @author Jetty7
*/
public class CertificateValidator
{
private static final Logger logger = LoggerFactory.getLogger(CertificateValidator.class);
private static AtomicLong aliasCount = new AtomicLong();
private KeyStore trustStore;
private Collection<? extends CRL> crls;
/** Maximum certification path length (n - number of intermediate certs, -1 for unlimited) */
private int maxCertPathLength = -1;
/** CRL Distribution Points (CRLDP) support */
private boolean enableCRLDP = false;
/** On-Line Certificate Status Protocol (OCSP) support */
private boolean enableOCSP = false;
/** Location of OCSP Responder */
private String ocspResponderURL;
/**
* creates an instance of the certificate validator
*
* @param trustStore
* @param crls
*/
public CertificateValidator(KeyStore trustStore, Collection<? extends CRL> crls) {
if (trustStore == null) {
throw new InvalidParameterException("TrustStore must be specified for CertificateValidator.");
}
this.trustStore = trustStore;
this.crls = crls;
}
/**
* validates all aliases inside of a given keystore
*
* @param keyStore
* @throws CertificateException
*/
public void validate(KeyStore keyStore) throws CertificateException {
try {
Enumeration<String> aliases = keyStore.aliases();
for ( ; aliases.hasMoreElements(); ) {
String alias = aliases.nextElement();
validate(keyStore,alias);
}
} catch (KeyStoreException kse) {
throw new CertificateException("Unable to retrieve aliases from keystore", kse);
}
}
/**
* validates a specific alias inside of the keystore being passed in
*
* @param keyStore
* @param keyAlias
* @return the keyAlias if valid
* @throws CertificateException
*/
public String validate(KeyStore keyStore, String keyAlias) throws CertificateException {
String result = null;
if (keyAlias != null) {
try {
validate(keyStore, keyStore.getCertificate(keyAlias));
} catch (KeyStoreException kse) {
logger.debug("", kse);
throw new CertificateException("Unable to validate certificate" +
" for alias [" + keyAlias + "]: " + kse.getMessage(), kse);
}
result = keyAlias;
}
return result;
}
/**
* validates a specific certificate inside of the keystore being passed in
*
* @param keyStore
* @param cert
* @throws CertificateException
*/
public void validate(KeyStore keyStore, Certificate cert) throws CertificateException {
Certificate[] certChain;
if (cert != null && cert instanceof X509Certificate) {
((X509Certificate)cert).checkValidity();
String certAlias = null;
try {
if (keyStore == null) {
throw new InvalidParameterException("Keystore cannot be null");
}
certAlias = keyStore.getCertificateAlias((X509Certificate)cert);
if (certAlias == null) {
certAlias = "CHSMPP" + String.format("%016X", aliasCount.incrementAndGet());
keyStore.setCertificateEntry(certAlias, cert);
}
certChain = keyStore.getCertificateChain(certAlias);
if (certChain == null || certChain.length == 0) {
throw new IllegalStateException("Unable to retrieve certificate chain");
}
}
catch (KeyStoreException kse) {
logger.debug("", kse);
throw new CertificateException("Unable to validate certificate" +
(certAlias == null ? "":" for alias [" +certAlias + "]") + ": " + kse.getMessage(), kse);
}
validate(certChain);
}
}
public void validate(Certificate[] certChain) throws CertificateException {
try {
ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
for (Certificate item : certChain) {
if (item == null) continue;
if (!(item instanceof X509Certificate)) {
throw new IllegalStateException("Invalid certificate type in chain");
}
certList.add((X509Certificate)item);
}
if (certList.isEmpty()) {
throw new IllegalStateException("Invalid certificate chain");
}
X509CertSelector certSelect = new X509CertSelector();
certSelect.setCertificate(certList.get(0));
// Configure certification path builder parameters
PKIXBuilderParameters pbParams = new PKIXBuilderParameters(trustStore, certSelect);
pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList)));
// Set maximum certification path length
pbParams.setMaxPathLength(maxCertPathLength);
// Enable revocation checking
pbParams.setRevocationEnabled(true);
// Set static Certificate Revocation List
if (crls != null && !crls.isEmpty()) {
pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crls)));
}
// Enable On-Line Certificate Status Protocol (OCSP) support
if (enableOCSP) {
Security.setProperty("ocsp.enable","true");
}
// Enable Certificate Revocation List Distribution Points (CRLDP) support
if (enableCRLDP) {
System.setProperty("com.sun.security.enableCRLDP","true");
}
// Build certification path
CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams);
// Validate certification path
CertPathValidator.getInstance("PKIX").validate(buildResult.getCertPath(),pbParams);
} catch (GeneralSecurityException gse) {
logger.debug("", gse);
throw new CertificateException("Unable to validate certificate: " + gse.getMessage(), gse);
}
}
public KeyStore getTrustStore() {
return trustStore;
}
public Collection<? extends CRL> getCrls() {
return crls;
}
/**
* @return Maximum number of intermediate certificates in
* the certification path (-1 for unlimited)
*/
public int getMaxCertPathLength() {
return maxCertPathLength;
}
/**
* @param maxCertPathLength maximum number of intermediate certificates in
* the certification path (-1 for unlimited)
*/
public void setMaxCertPathLength(int maxCertPathLength) {
maxCertPathLength = maxCertPathLength;
}
/**
* @return true if CRL Distribution Points support is enabled
*/
public boolean isEnableCRLDP() {
return enableCRLDP;
}
/**
* Enables CRL Distribution Points Support
* @param enableCRLDP true - turn on, false - turns off
*/
public void setEnableCRLDP(boolean enableCRLDP) {
enableCRLDP = enableCRLDP;
}
/**
* @return true if On-Line Certificate Status Protocol support is enabled
*/
public boolean isEnableOCSP() {
return enableOCSP;
}
/**
* Enables On-Line Certificate Status Protocol support
* @param enableOCSP true - turn on, false - turn off
*/
public void setEnableOCSP(boolean enableOCSP) {
enableOCSP = enableOCSP;
}
/**
* @return Location of the OCSP Responder
*/
public String getOcspResponderURL() {
return ocspResponderURL;
}
/**
* Set the location of the OCSP Responder.
* @param ocspResponderURL location of the OCSP Responder
*/
public void setOcspResponderURL(String ocspResponderURL) {
ocspResponderURL = ocspResponderURL;
}
}