/
SpnegoContext.java
498 lines (420 loc) · 14.8 KB
/
SpnegoContext.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
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
/*
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package jcifs.smb;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.DERSequence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jcifs.CIFSException;
import jcifs.Configuration;
import jcifs.spnego.NegTokenInit;
import jcifs.spnego.NegTokenTarg;
import jcifs.spnego.SpnegoException;
import jcifs.spnego.SpnegoToken;
import jcifs.util.Hexdump;
/**
* This class used to wrap a {@link SSPContext} to provide SPNEGO feature.
*
* @author Shun
*
*/
class SpnegoContext implements SSPContext {
private static final Logger log = LoggerFactory.getLogger(SpnegoContext.class);
private static ASN1ObjectIdentifier SPNEGO_MECH_OID;
static {
try {
SPNEGO_MECH_OID = new ASN1ObjectIdentifier("1.3.6.1.5.5.2");
}
catch ( IllegalArgumentException e ) {
log.error("Failed to initialize OID", e);
}
}
private SSPContext mechContext;
private boolean firstResponse = true;
private boolean completed;
private ASN1ObjectIdentifier[] mechs;
private ASN1ObjectIdentifier selectedMech;
private ASN1ObjectIdentifier[] remoteMechs;
private boolean disableMic;
private boolean requireMic;
/**
* Instance a <code>SpnegoContext</code> object by wrapping a {@link SSPContext}
* with the same mechanism this {@link SSPContext} used.
*
* @param source
* the {@link SSPContext} to be wrapped
*/
SpnegoContext ( Configuration config, SSPContext source ) {
this(config, source, source.getSupportedMechs());
}
/**
* Instance a <code>SpnegoContext</code> object by wrapping a {@link SSPContext}
* with specified mechanism.
*
* @param source
* the {@link SSPContext} to be wrapped
* @param mech
* the mechanism is being used for this context.
*/
SpnegoContext ( Configuration config, SSPContext source, ASN1ObjectIdentifier[] mech ) {
this.mechContext = source;
this.mechs = mech;
this.disableMic = !config.isEnforceSpnegoIntegrity() && config.isDisableSpnegoIntegrity();
this.requireMic = config.isEnforceSpnegoIntegrity();
}
/**
* {@inheritDoc}
*
* @see jcifs.smb.SSPContext#getSupportedMechs()
*/
@Override
public ASN1ObjectIdentifier[] getSupportedMechs () {
return new ASN1ObjectIdentifier[] {
SPNEGO_MECH_OID
};
}
/**
* {@inheritDoc}
*
* @see jcifs.smb.SSPContext#getFlags()
*/
@Override
public int getFlags () {
return this.mechContext.getFlags();
}
@Override
public boolean isSupported ( ASN1ObjectIdentifier mechanism ) {
// prevent nesting
return false;
}
/**
* Determines what mechanism is being used for this context.
*
* @return the Oid of the mechanism being used
*/
ASN1ObjectIdentifier[] getMechs () {
return this.mechs;
}
/**
* @return the mechanisms announced by the remote end
*/
ASN1ObjectIdentifier[] getRemoteMechs () {
return this.remoteMechs;
}
/**
* Set what mechanism is being used for this context.
*
* @param mechs
*/
void setMechs ( ASN1ObjectIdentifier[] mechs ) {
this.mechs = mechs;
}
/**
* {@inheritDoc}
*
* @see jcifs.smb.SSPContext#getNetbiosName()
*/
@Override
public String getNetbiosName () {
return null;
}
/**
* {@inheritDoc}
*
* @see jcifs.smb.SSPContext#getSigningKey()
*/
@Override
public byte[] getSigningKey () throws CIFSException {
return this.mechContext.getSigningKey();
}
/**
* Initialize the GSSContext to provide SPNEGO feature.
*
* @param inputBuf
* @param offset
* @param len
* @return response token
*/
@Override
public byte[] initSecContext ( byte[] inputBuf, int offset, int len ) throws CIFSException {
SpnegoToken resp;
if ( this.completed ) {
throw new CIFSException("Already complete");
}
else if ( len == 0 ) {
resp = initialToken();
}
else {
resp = negotitate(inputBuf, offset, len);
}
if ( resp == null ) {
return null;
}
return resp.toByteArray();
}
private SpnegoToken negotitate ( byte[] inputBuf, int offset, int len ) throws CIFSException {
SpnegoToken spToken = getToken(inputBuf, offset, len);
byte[] inputToken = null;
if ( spToken instanceof NegTokenInit ) {
NegTokenInit tinit = (NegTokenInit) spToken;
ASN1ObjectIdentifier[] rm = tinit.getMechanisms();
this.remoteMechs = rm;
ASN1ObjectIdentifier prefMech = rm[ 0 ];
// only use token if the optimistic mechanism is supported
if ( this.mechContext.isSupported(prefMech) ) {
inputToken = tinit.getMechanismToken();
}
else {
ASN1ObjectIdentifier found = null;
for ( ASN1ObjectIdentifier mech : rm ) {
if ( this.mechContext.isSupported(mech) ) {
found = mech;
break;
}
}
if ( found == null ) {
throw new SmbException("Server does advertise any supported mechanism");
}
}
}
else if ( spToken instanceof NegTokenTarg ) {
NegTokenTarg targ = (NegTokenTarg) spToken;
if ( this.firstResponse ) {
if ( !this.mechContext.isSupported(targ.getMechanism()) ) {
throw new SmbException("Server chose an unsupported mechanism " + targ.getMechanism());
}
this.selectedMech = targ.getMechanism();
if ( targ.getResult() == NegTokenTarg.REQUEST_MIC ) {
this.requireMic = true;
}
this.firstResponse = false;
}
else {
if ( targ.getMechanism() != null && !targ.getMechanism().equals(this.selectedMech) ) {
throw new SmbException("Server switched mechanism");
}
}
inputToken = targ.getMechanismToken();
}
else {
throw new SmbException("Invalid token");
}
if ( spToken instanceof NegTokenTarg && this.mechContext.isEstablished() ) {
// already established, but server hasn't completed yet
NegTokenTarg targ = (NegTokenTarg) spToken;
if ( targ.getResult() == NegTokenTarg.ACCEPT_INCOMPLETE && targ.getMechanismToken() == null && targ.getMechanismListMIC() != null ) {
// this indicates that mechlistMIC is required by the server
verifyMechListMIC(targ.getMechanismListMIC());
return new NegTokenTarg(NegTokenTarg.UNSPECIFIED_RESULT, null, null, calculateMechListMIC());
}
else if ( targ.getResult() != NegTokenTarg.ACCEPT_COMPLETED ) {
throw new SmbException("SPNEGO negotiation did not complete");
}
verifyMechListMIC(targ.getMechanismListMIC());
this.completed = true;
return null;
}
if ( inputToken == null ) {
return initialToken();
}
byte[] mechMIC = null;
byte[] responseToken = this.mechContext.initSecContext(inputToken, 0, inputToken.length);
if ( spToken instanceof NegTokenTarg ) {
NegTokenTarg targ = (NegTokenTarg) spToken;
if ( targ.getResult() == NegTokenTarg.ACCEPT_COMPLETED && this.mechContext.isEstablished() ) {
// server sent final token
verifyMechListMIC(targ.getMechanismListMIC());
if ( !this.disableMic || this.requireMic ) {
mechMIC = calculateMechListMIC();
}
this.completed = true;
}
else if ( this.mechContext.isMICAvailable() && ( !this.disableMic || this.requireMic ) ) {
// we need to send our final data
mechMIC = calculateMechListMIC();
}
else if ( targ.getResult() == NegTokenTarg.REJECTED ) {
throw new SmbException("SPNEGO mechanism was rejected");
}
}
if ( responseToken == null && this.mechContext.isEstablished() ) {
return null;
}
return new NegTokenTarg(NegTokenTarg.UNSPECIFIED_RESULT, null, responseToken, mechMIC);
}
private byte[] calculateMechListMIC () throws CIFSException {
if ( !this.mechContext.isMICAvailable() ) {
return null;
}
ASN1ObjectIdentifier[] lm = this.mechs;
byte[] ml = encodeMechs(lm);
byte[] mechanismListMIC = this.mechContext.calculateMIC(ml);
if ( log.isDebugEnabled() ) {
log.debug("Out Mech list " + Arrays.toString(lm));
log.debug("Out Mech list encoded " + Hexdump.toHexString(ml));
log.debug("Out Mech list MIC " + Hexdump.toHexString(mechanismListMIC));
}
return mechanismListMIC;
}
private void verifyMechListMIC ( byte[] mechanismListMIC ) throws CIFSException {
if ( this.disableMic ) {
return;
}
// No MIC verification if not present and not required
// or if the chosen mechanism is our preferred one
if ( ( mechanismListMIC == null || !this.mechContext.supportsIntegrity() ) && this.requireMic
&& !this.mechContext.isPreferredMech(this.selectedMech) ) {
throw new CIFSException("SPNEGO integrity is required but not available");
}
// otherwise we ignore the absence of a MIC
if ( !this.mechContext.isMICAvailable() || mechanismListMIC == null ) {
return;
}
try {
ASN1ObjectIdentifier[] lm = this.mechs;
byte[] ml = encodeMechs(lm);
if ( log.isInfoEnabled() ) {
log.debug("In Mech list " + Arrays.toString(lm));
log.debug("In Mech list encoded " + Hexdump.toHexString(ml));
log.debug("In Mech list MIC " + Hexdump.toHexString(mechanismListMIC));
}
this.mechContext.verifyMIC(ml, mechanismListMIC);
}
catch ( CIFSException e ) {
throw new CIFSException("Failed to verify mechanismListMIC", e);
}
}
/**
* @param mechs
* @return
* @throws CIFSException
*/
private static byte[] encodeMechs ( ASN1ObjectIdentifier[] mechs ) throws CIFSException {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ASN1OutputStream dos = ASN1OutputStream.create(bos, ASN1Encoding.DER);
dos.writeObject(new DERSequence(mechs));
dos.close();
return bos.toByteArray();
}
catch ( IOException e ) {
throw new CIFSException("Failed to encode mechList", e);
}
}
private SpnegoToken initialToken () throws CIFSException {
byte[] mechToken = this.mechContext.initSecContext(new byte[0], 0, 0);
return new NegTokenInit(this.mechs, this.mechContext.getFlags(), mechToken, null);
}
@Override
public boolean isEstablished () {
return this.completed && this.mechContext.isEstablished();
}
private static SpnegoToken getToken ( byte[] token, int off, int len ) throws SpnegoException {
byte[] b = new byte[len];
if ( off == 0 && token.length == len ) {
b = token;
}
else {
System.arraycopy(token, off, b, 0, len);
}
return getToken(b);
}
private static SpnegoToken getToken ( byte[] token ) throws SpnegoException {
SpnegoToken spnegoToken = null;
try {
switch ( token[ 0 ] ) {
case (byte) 0x60:
spnegoToken = new NegTokenInit(token);
break;
case (byte) 0xa1:
spnegoToken = new NegTokenTarg(token);
break;
default:
throw new SpnegoException("Invalid token type");
}
return spnegoToken;
}
catch ( IOException e ) {
throw new SpnegoException("Invalid token");
}
}
@Override
public boolean supportsIntegrity () {
return this.mechContext.supportsIntegrity();
}
/**
* {@inheritDoc}
*
* @see jcifs.smb.SSPContext#isPreferredMech(org.bouncycastle.asn1.ASN1ObjectIdentifier)
*/
@Override
public boolean isPreferredMech ( ASN1ObjectIdentifier mech ) {
return this.mechContext.isPreferredMech(mech);
}
@Override
public byte[] calculateMIC ( byte[] data ) throws CIFSException {
if ( !this.completed ) {
throw new CIFSException("Context is not established");
}
return this.mechContext.calculateMIC(data);
}
/**
* {@inheritDoc}
*
* @see jcifs.smb.SSPContext#verifyMIC(byte[], byte[])
*/
@Override
public void verifyMIC ( byte[] data, byte[] mic ) throws CIFSException {
if ( !this.completed ) {
throw new CIFSException("Context is not established");
}
this.mechContext.verifyMIC(data, mic);
}
/**
* {@inheritDoc}
*
* @see jcifs.smb.SSPContext#isMICAvailable()
*/
@Override
public boolean isMICAvailable () {
if ( !this.completed ) {
return false;
}
return this.mechContext.isMICAvailable();
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#toString()
*/
@Override
public String toString () {
return "SPNEGO[" + this.mechContext + "]";
}
/**
*
*/
@Override
public void dispose () throws CIFSException {
this.mechContext.dispose();
}
}