-
Notifications
You must be signed in to change notification settings - Fork 435
/
Copy pathKerbAuthentication.java
284 lines (258 loc) · 13.8 KB
/
KerbAuthentication.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
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
/*
* Microsoft JDBC Driver for SQL Server Copyright(c) Microsoft Corporation All rights reserved. This program is made
* available under the terms of the MIT License. See the LICENSE file in the project root for more information.
*/
package com.microsoft.sqlserver.jdbc;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.text.MessageFormat;
import java.util.logging.Level;
import javax.security.auth.Subject;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.ietf.jgss.Oid;
/**
* KerbAuthentication for integrated authentication.
*/
final class KerbAuthentication extends SSPIAuthentication {
private static final java.util.logging.Logger authLogger = java.util.logging.Logger
.getLogger("com.microsoft.sqlserver.jdbc.internals.KerbAuthentication");
private final SQLServerConnection con;
private final String spn;
private final GSSManager manager = GSSManager.getInstance();
private LoginContext lc = null;
private boolean isUserCreatedCredential = false;
private GSSCredential peerCredentials = null;
private boolean useDefaultNativeGSSCredential = false;
private GSSContext peerContext = null;
/**
* Initializes the Kerberos client security context
*
* @throws SQLServerException
*/
@SuppressWarnings("deprecation")
private void initAuthInit() throws SQLServerException {
try {
// If we need to support NTLM as well, we can use null
// Kerberos OID
Oid kerberos = new Oid("1.2.840.113554.1.2.2");
// http://blogs.sun.com/harcey/entry/of_java_kerberos_and_access
// We pass null to indicate that the system should interpret the SPN
// as it is.
GSSName remotePeerName = manager.createName(spn, null);
if (useDefaultNativeGSSCredential) {
peerCredentials = manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME, kerberos,
GSSCredential.INITIATE_ONLY);
}
if (null != peerCredentials) {
peerContext = manager.createContext(remotePeerName, kerberos, peerCredentials,
GSSContext.DEFAULT_LIFETIME);
peerContext.requestCredDeleg(false);
peerContext.requestMutualAuth(true);
peerContext.requestInteg(true);
} else {
String configName = con.activeConnectionProperties.getProperty(
SQLServerDriverStringProperty.JAAS_CONFIG_NAME.toString(),
SQLServerDriverStringProperty.JAAS_CONFIG_NAME.getDefaultValue());
boolean useDefaultJaas = Boolean.parseBoolean(con.activeConnectionProperties.getProperty(
SQLServerDriverBooleanProperty.USE_DEFAULT_JAAS_CONFIG.toString(),
Boolean.toString(SQLServerDriverBooleanProperty.USE_DEFAULT_JAAS_CONFIG.getDefaultValue())));
if (!configName.equals(SQLServerDriverStringProperty.JAAS_CONFIG_NAME.getDefaultValue())
&& useDefaultJaas) {
// Reset configName to default -- useDefaultJaas setting takes priority over jaasConfigName
if (authLogger.isLoggable(Level.WARNING)) {
authLogger.warning(toString()
+ String.format("Using default JAAS configuration, configured %s=%s will not be used.",
SQLServerDriverStringProperty.JAAS_CONFIG_NAME, configName));
}
configName = SQLServerDriverStringProperty.JAAS_CONFIG_NAME.getDefaultValue();
}
Subject currentSubject;
KerbCallback callback = new KerbCallback(con);
try {
try {
java.security.AccessControlContext context = java.security.AccessController.getContext();
currentSubject = Subject.getSubject(context);
} catch (UnsupportedOperationException ue) {
if (authLogger.isLoggable(Level.FINE)) {
authLogger.fine("JDK version does not support Subject.getSubject(), " +
"falling back to Subject.current() : " + ue.getMessage());
}
Method current = Subject.class.getDeclaredMethod("current");
current.setAccessible(true);
currentSubject = (Subject) current.invoke(null);
}
if (null == currentSubject) {
if (useDefaultJaas) {
lc = new LoginContext(configName, null, callback, new JaasConfiguration(null));
} else {
lc = new LoginContext(configName, callback);
}
lc.login();
// per documentation LoginContext will instantiate a new subject.
currentSubject = lc.getSubject();
}
} catch (LoginException le) {
if (authLogger.isLoggable(Level.FINE)) {
authLogger.fine(toString() + "Failed to login using Kerberos due to " + le.getClass().getName()
+ ":" + le.getMessage());
}
try {
// Not very clean since it raises an Exception, but we are sure we are cleaning well everything
con.terminate(SQLServerException.DRIVER_ERROR_NONE,
SQLServerException.getErrString("R_integratedAuthenticationFailed"), le);
} catch (SQLServerException alwaysTriggered) {
String message = MessageFormat.format(SQLServerException.getErrString("R_kerberosLoginFailed"),
alwaysTriggered.getMessage(), le.getClass().getName(), le.getMessage());
if (callback.getUsernameRequested() != null) {
message = MessageFormat.format(
SQLServerException.getErrString("R_kerberosLoginFailedForUsername"),
callback.getUsernameRequested(), message);
}
// By throwing Exception with LOGON_FAILED -> we avoid looping for connection
// In this case, authentication will never work anyway -> fail fast
throw new SQLServerException(message, alwaysTriggered.getSQLState(),
SQLServerException.LOGON_FAILED, le);
}
return;
}
if (authLogger.isLoggable(Level.FINER)) {
authLogger.finer(toString() + " Getting client credentials");
}
peerCredentials = getClientCredential(currentSubject, manager, kerberos);
if (authLogger.isLoggable(Level.FINER)) {
authLogger.finer(toString() + " creating security context");
}
peerContext = manager.createContext(remotePeerName, kerberos, peerCredentials,
GSSContext.DEFAULT_LIFETIME);
// The following flags should be inline with our native implementation.
peerContext.requestCredDeleg(true);
peerContext.requestMutualAuth(true);
peerContext.requestInteg(true);
}
} catch (GSSException ge) {
if (authLogger.isLoggable(Level.FINER)) {
authLogger.finer(toString() + "initAuthInit failed GSSException:-" + ge);
}
con.terminate(SQLServerException.DRIVER_ERROR_NONE,
SQLServerException.getErrString("R_integratedAuthenticationFailed"), ge);
} catch (PrivilegedActionException ge) {
if (authLogger.isLoggable(Level.FINER)) {
authLogger.finer(toString() + "initAuthInit failed privileged exception:-" + ge);
}
con.terminate(SQLServerException.DRIVER_ERROR_NONE,
SQLServerException.getErrString("R_integratedAuthenticationFailed"), ge);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
if (authLogger.isLoggable(Level.FINER)) {
authLogger.finer(toString() + "initAuthInit failed reflection exception:-" + ex);
}
con.terminate(SQLServerException.DRIVER_ERROR_NONE,
SQLServerException.getErrString("R_integratedAuthenticationFailed"), ex);
}
}
// We have to do a privileged action to create the credential of the user in the current context
private static GSSCredential getClientCredential(final Subject subject, final GSSManager gssManager,
final Oid kerboid) throws PrivilegedActionException {
final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() {
public GSSCredential run() throws GSSException {
return gssManager.createCredential(null, // use the default principal
GSSCredential.DEFAULT_LIFETIME, kerboid, GSSCredential.INITIATE_ONLY);
}
};
// TO support java 5, 6 we have to do this
// The signature for Java 5 returns an object 6 returns GSSCredential, immediate casting throws
// warning in Java 6.
Object credential = Subject.doAs(subject, action);
return (GSSCredential) credential;
}
private byte[] initAuthHandShake(byte[] pin, boolean[] done) throws SQLServerException {
try {
if (authLogger.isLoggable(Level.FINER)) {
authLogger.finer(toString() + " Sending token to server over secure context");
}
byte[] byteToken = peerContext.initSecContext(pin, 0, pin.length);
if (peerContext.isEstablished()) {
done[0] = true;
if (authLogger.isLoggable(Level.FINER)) {
authLogger.finer(toString() + "Authentication done.");
}
} else if (null == byteToken) {
// The documentation is not clear on when this can happen but it does say this could happen
if (authLogger.isLoggable(Level.INFO)) {
authLogger.info(toString() + "byteToken is null in initSecContext.");
}
con.terminate(SQLServerException.DRIVER_ERROR_NONE,
SQLServerException.getErrString("R_integratedAuthenticationFailed"));
}
return byteToken;
} catch (GSSException ge) {
if (authLogger.isLoggable(Level.FINER)) {
authLogger.finer(toString() + "initSecContext Failed :-" + ge);
}
con.terminate(SQLServerException.DRIVER_ERROR_NONE,
SQLServerException.getErrString("R_integratedAuthenticationFailed"), ge);
}
// keep the compiler happy
return null;
}
// Package visible members below.
KerbAuthentication(SQLServerConnection con, String address, int port) {
this.con = con;
this.spn = null != con ? getSpn(con) : null;
}
/**
*
* @param con
* @param address
* @param port
* @param impersonatedUserCred
*/
KerbAuthentication(SQLServerConnection con, String address, int port, GSSCredential impersonatedUserCred,
boolean isUserCreated, boolean useDefaultNativeGSSCredential) {
this(con, address, port);
this.peerCredentials = impersonatedUserCred;
this.isUserCreatedCredential = isUserCreated;
this.useDefaultNativeGSSCredential = useDefaultNativeGSSCredential;
}
byte[] generateClientContext(byte[] pin, boolean[] done) throws SQLServerException {
if (null == peerContext) {
initAuthInit();
}
return initAuthHandShake(pin, done);
}
void releaseClientContext() {
try {
if (null != peerCredentials && !isUserCreatedCredential && !useDefaultNativeGSSCredential) {
peerCredentials.dispose();
} else if (null != peerCredentials && (isUserCreatedCredential || useDefaultNativeGSSCredential)) {
peerCredentials = null;
}
if (null != peerContext) {
peerContext.dispose();
}
if (null != lc) {
lc.logout();
}
} catch (LoginException e) {
// yes we are eating exceptions here but this should not fail in the normal circumstances and we do not want
// to eat previous login errors if caused before which is more useful to the user than the cleanup errors.
if (authLogger.isLoggable(Level.FINE)) {
authLogger.fine(toString() + " Release of the credentials failed LoginException: " + e);
}
} catch (GSSException e) {
// yes we are eating exceptions here but this should not fail in the normal circumstances and we do not want
// to eat previous login errors if caused before which is more useful to the user than the cleanup errors.
if (authLogger.isLoggable(Level.FINE)) {
authLogger.fine(toString() + " Release of the credentials failed GSSException: " + e);
}
}
}
}