/
SingleCertValidatingFactory.java
202 lines (189 loc) · 7.64 KB
/
SingleCertValidatingFactory.java
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
/*
* Copyright (c) 2004, PostgreSQL Global Development Group
* See the LICENSE file in the project root for more information.
*/
package org.postgresql.ssl;
import org.postgresql.util.GT;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.UUID;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
/**
* <p>Provides a SSLSocketFactory that authenticates the remote server against an explicit pre-shared
* SSL certificate. This is more secure than using the NonValidatingFactory as it prevents "man in
* the middle" attacks. It is also more secure than relying on a central CA signing your server's
* certificate as it pins the server's certificate.</p>
*
* <p>This class requires a single String parameter specified by setting the connection property
* <code>sslfactoryarg</code>. The value of this property is the PEM-encoded remote server's SSL
* certificate.</p>
*
* <p>Where the certificate is loaded from is based upon the prefix of the <code>sslfactoryarg</code> property.
* The following table lists the valid set of prefixes.</p>
*
* <table border="1">
* <caption>Valid prefixes for sslfactoryarg</caption>
* <tr>
* <th>Prefix</th>
* <th>Example</th>
* <th>Explanation</th>
* </tr>
* <tr>
* <td><code>classpath:</code></td>
* <td><code>classpath:ssl/server.crt</code></td>
* <td>Loaded from the classpath.</td>
* </tr>
* <tr>
* <td><code>file:</code></td>
* <td><code>file:/foo/bar/server.crt</code></td>
* <td>Loaded from the filesystem.</td>
* </tr>
* <tr>
* <td><code>env:</code></td>
* <td><code>env:mydb_cert</code></td>
* <td>Loaded from string value of the <code>mydb_cert</code> environment variable.</td>
* </tr>
* <tr>
* <td><code>sys:</code></td>
* <td><code>sys:mydb_cert</code></td>
* <td>Loaded from string value of the <code>mydb_cert</code> system property.</td>
* </tr>
* <tr>
* <td><pre>-----BEGIN CERTIFICATE------</pre></td>
* <td>
* <pre>
* -----BEGIN CERTIFICATE-----
* MIIDQzCCAqygAwIBAgIJAOd1tlfiGoEoMA0GCSqGSIb3DQEBBQUAMHUxCzAJBgNV
* [... truncated ...]
* UCmmYqgiVkAGWRETVo+byOSDZ4swb10=
* -----END CERTIFICATE-----
* </pre>
* </td>
* <td>Loaded from string value of the argument.</td>
* </tr>
* </table>
*/
public class SingleCertValidatingFactory extends WrappedFactory {
private static final String FILE_PREFIX = "file:";
private static final String CLASSPATH_PREFIX = "classpath:";
private static final String ENV_PREFIX = "env:";
private static final String SYS_PROP_PREFIX = "sys:";
public SingleCertValidatingFactory(String sslFactoryArg) throws GeneralSecurityException {
if (sslFactoryArg == null || sslFactoryArg.equals("")) {
throw new GeneralSecurityException(GT.tr("The sslfactoryarg property may not be empty."));
}
InputStream in = null;
try {
if (sslFactoryArg.startsWith(FILE_PREFIX)) {
String path = sslFactoryArg.substring(FILE_PREFIX.length());
in = new BufferedInputStream(new FileInputStream(path));
} else if (sslFactoryArg.startsWith(CLASSPATH_PREFIX)) {
String path = sslFactoryArg.substring(CLASSPATH_PREFIX.length());
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream;
if (classLoader != null) {
inputStream = classLoader.getResourceAsStream(path);
if (inputStream == null) {
throw new IllegalArgumentException(
GT.tr("Unable to find resource {0} via Thread contextClassLoader {1}",
path, classLoader)
);
}
} else {
inputStream = getClass().getResourceAsStream(path);
if (inputStream == null) {
throw new IllegalArgumentException(
GT.tr("Unable to find resource {0} via class {1} ClassLoader {2}",
path, getClass(), getClass().getClassLoader())
);
}
}
in = new BufferedInputStream(inputStream);
} else if (sslFactoryArg.startsWith(ENV_PREFIX)) {
String name = sslFactoryArg.substring(ENV_PREFIX.length());
String cert = System.getenv(name);
if (cert == null || "".equals(cert)) {
throw new GeneralSecurityException(GT.tr(
"The environment variable containing the server's SSL certificate must not be empty."));
}
in = new ByteArrayInputStream(cert.getBytes("UTF-8"));
} else if (sslFactoryArg.startsWith(SYS_PROP_PREFIX)) {
String name = sslFactoryArg.substring(SYS_PROP_PREFIX.length());
String cert = System.getProperty(name);
if (cert == null || "".equals(cert)) {
throw new GeneralSecurityException(GT.tr(
"The system property containing the server's SSL certificate must not be empty."));
}
in = new ByteArrayInputStream(cert.getBytes("UTF-8"));
} else if (sslFactoryArg.startsWith("-----BEGIN CERTIFICATE-----")) {
in = new ByteArrayInputStream(sslFactoryArg.getBytes("UTF-8"));
} else {
throw new GeneralSecurityException(GT.tr(
"The sslfactoryarg property must start with the prefix file:, classpath:, env:, sys:, or -----BEGIN CERTIFICATE-----."));
}
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{new SingleCertTrustManager(in)}, null);
factory = ctx.getSocketFactory();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
if (e instanceof GeneralSecurityException) {
throw (GeneralSecurityException) e;
}
throw new GeneralSecurityException(GT.tr("An error occurred reading the certificate"), e);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e2) {
// ignore
}
}
}
}
public static class SingleCertTrustManager implements X509TrustManager {
X509Certificate cert;
X509TrustManager trustManager;
public SingleCertTrustManager(InputStream in) throws IOException, GeneralSecurityException {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
// Note: KeyStore requires it be loaded even if you don't load anything into it:
ks.load(null);
CertificateFactory cf = CertificateFactory.getInstance("X509");
cert = (X509Certificate) cf.generateCertificate(in);
ks.setCertificateEntry(UUID.randomUUID().toString(), cert);
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
trustManager = (X509TrustManager) tm;
break;
}
}
if (trustManager == null) {
throw new GeneralSecurityException(GT.tr("No X509TrustManager found"));
}
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
trustManager.checkServerTrusted(chain, authType);
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{cert};
}
}
}