-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathWolfSSLAuthStore.java
More file actions
803 lines (696 loc) · 28.4 KB
/
WolfSSLAuthStore.java
File metadata and controls
803 lines (696 loc) · 28.4 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
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
/* WolfSSLAuthStore.java
*
* Copyright (C) 2006-2026 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* wolfSSL 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
package com.wolfssl.provider.jsse;
import com.wolfssl.WolfSSL;
import com.wolfssl.WolfSSLDebug;
import com.wolfssl.WolfSSL.TLS_VERSION;
import com.wolfssl.WolfSSLSession;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SNIServerName;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.TrustManagerFactory;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.KeyStoreException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.nio.charset.StandardCharsets;
/**
* Helper class used to store common settings, objects, etc.
*/
public class WolfSSLAuthStore {
private TLS_VERSION currentVersion = TLS_VERSION.INVALID;
private X509KeyManager km = null;
private X509TrustManager tm = null;
private SecureRandom sr = null;
private String alias = null;
private WolfSSLSessionContext serverCtx = null;
private WolfSSLSessionContext clientCtx = null;
private SessionStore<Integer, WolfSSLImplementSSLSession> store = null;
private static final Object storeLock = new Object();
/**
* Protected constructor to create new WolfSSLAuthStore
* @param keyman key manager to use
* @param trustman trust manager to use
* @param random secure random
* @param version TLS protocol version to use
* @param serverCtx server session context (created by WolfSSLContext)
* @param clientCtx client session context (created by WolfSSLContext)
* @throws IllegalArgumentException when bad values are passed in
* @throws KeyManagementException in the case that getting keys fails
*/
protected WolfSSLAuthStore(KeyManager[] keyman, TrustManager[] trustman,
SecureRandom random, TLS_VERSION version,
WolfSSLSessionContext serverCtx, WolfSSLSessionContext clientCtx)
throws IllegalArgumentException, KeyManagementException {
/* default session cache size of 33 to match native wolfSSL
* default cache size */
int defaultCacheSize = 33;
if (version == TLS_VERSION.INVALID) {
throw new IllegalArgumentException("Invalid SSL/TLS version");
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Creating new WolfSSLAuthStore");
initKeyManager(keyman);
initTrustManager(trustman);
initSecureRandom(random);
this.currentVersion = version;
if (store == null) {
store = new SessionStore<>(defaultCacheSize);
}
/* Use session contexts passed in from WolfSSLContext, allowing
* session context access before init() is called */
this.serverCtx = serverCtx;
this.clientCtx = clientCtx;
}
/**
* Initialize key manager.
* The first instance of X509KeyManager found will be used. If null is
* passed in, installed security providers with be searched for highest
* priority implementation of the required factory.
*/
private void initKeyManager(KeyManager[] in)
throws KeyManagementException {
KeyManager[] managers = in;
if (managers == null || managers.length == 0) {
try {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "searching installed providers for X509KeyManager " +
"(type: " + KeyManagerFactory.getDefaultAlgorithm() +")");
/* use key managers from installed security providers */
KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmFactory.init(null, null);
managers = kmFactory.getKeyManagers();
} catch (NoSuchAlgorithmException nsae) {
throw new KeyManagementException(nsae);
} catch (KeyStoreException kse) {
throw new KeyManagementException(kse);
} catch (UnrecoverableKeyException uke) {
throw new KeyManagementException(uke);
}
}
if (managers != null) {
for (int i = 0; i < managers.length; i++) {
if (managers[i] instanceof X509KeyManager) {
km = (X509KeyManager)managers[i];
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "located X509KeyManager instance: " + km);
break;
}
}
}
}
/**
* Initialize trust manager.
* The first instance of X509TrustManager found will be used. If null is
* passed in, installed security providers with be searched for highest
* priority implementation of the required factory.
*/
private void initTrustManager(TrustManager[] in)
throws KeyManagementException {
TrustManager[] managers = in;
if (managers == null || managers.length == 0) {
try {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "searching installed providers for X509TrustManager");
/* use trust managers from installed security providers */
TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmFactory.init((KeyStore)null);
managers = tmFactory.getTrustManagers();
} catch (NoSuchAlgorithmException nsae) {
throw new KeyManagementException(nsae);
} catch (KeyStoreException kse) {
throw new KeyManagementException(kse);
}
}
if (managers != null) {
for (int i = 0; i < managers.length; i++) {
if (managers[i] instanceof X509TrustManager) {
tm = (X509TrustManager)managers[i];
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "located X509TrustManager instance: " + tm);
break;
}
}
}
}
/**
* Initialize secure random.
* If SecureRandom passed in is null, default implementation will
* be used.
*/
private void initSecureRandom(SecureRandom random) {
if (random == null) {
sr = new SecureRandom();
}
sr = random;
}
/**
* Get X509KeyManager for this object
* @return get the key manager used
*/
protected X509KeyManager getX509KeyManager() {
return this.km;
}
/**
* Get X509TrustManager for this object
* @return get the trust manager used
*/
protected X509TrustManager getX509TrustManager() {
return this.tm;
}
/**
* Get the SecureRandom for this object
* @return get secure random
*/
protected SecureRandom getSecureRandom() {
return this.sr;
}
/**
* Get protocol version set
* @return get the current protocol version set
*/
protected TLS_VERSION getProtocolVersion() {
return this.currentVersion;
}
/**
* Set certificate alias
* @param in alias to set for certificate used
*/
protected void setCertAlias(String in) {
this.alias = in;
}
/**
* Get certificate alias
* @return alias name
*/
protected String getCertAlias() {
return this.alias;
}
/**
* Getter function for WolfSSLSessionContext associated with store
* @return pointer to the context set
*/
protected WolfSSLSessionContext getServerContext() {
this.serverCtx.setWolfSSLAuthStore(this);
return this.serverCtx;
}
/**
* Getter function for WolfSSLSessionContext associated with store
* @return pointer to the context set
*/
protected WolfSSLSessionContext getClientContext() {
this.clientCtx.setWolfSSLAuthStore(this);
return this.clientCtx;
}
/**
* Reset the size of the array to cache sessions
* @param sz new array size
* @param side server/client side for cache resize
*/
protected void resizeCache(int sz, int side) {
SessionStore<Integer, WolfSSLImplementSSLSession> newStore =
new SessionStore<>(sz);
/* @TODO check for side server/client, currently a resize is for all */
synchronized (storeLock) {
newStore.putAll(store);
store = newStore;
}
}
/**
* Get and return either an existing session from the Java session cache
* table, or create a new session if one does not exist.
*
* This method can return null if ether an error occurs getting a session,
* or a new session could not be created.
*
* If called on the server side (clientMode == false), a new
* WolfSSLImplementSSLSession will be created and returned, since the
* server-side session cache is managed and maintained interal to native
* wolfSSL.
*
* @param ssl WolfSSLSession (WOLFSSL) for which the returned session
* is stored back into (ie: wolfSSL_set_session(ssl, session))
* @param port port number of peer being connected to
* @param host host of the peer being connected to
* @param clientMode if is client side then true, otherwise false
* @param enabledCipherSuites String array containing enabled cipher
* suites for the SSLSocket/SSLEngine requesting this session.
* Used to compare cipher suite of cached session against enabled
* cipher suites.
* @param enabledProtocols String array containing enabled protocols
* for the SSLSocket/SSLEngine requesting this session.
* Used to compare protocol of cached session against enabled
* protocols.
*
* @return an existing SSLSession from Java session cache, or a new
* object if not in cache, called on server side, or host
* is null
*/
protected WolfSSLImplementSSLSession getSession(
WolfSSLSession ssl, int port, String host, boolean clientMode,
String[] enabledCipherSuites, String[] enabledProtocols) {
boolean needNewSession = false;
WolfSSLImplementSSLSession ses = null;
String toHash = null;
int hashCode = 0;
if (ssl == null) {
return null;
}
/* Unknown port (-1) is a valid SSLEngine host hint.
* Skip cache keying. */
if (!clientMode || host == null || port < 0) {
return this.getSession(ssl, clientMode, host, port);
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "attempting to look up session (host: " + host +
", port: " + port + ")");
/* Print current size and contents of SessionStore / LinkedHashMap.
* Synchronizes on storeLock internally. */
printSessionStoreStatus();
/* Generate cache key hash (host:port), outside lock */
toHash = host.concat(Integer.toString(port));
hashCode = toHash.hashCode();
/* Lock on static/global storeLock while getting session out of
* store, since Java session cache table is shared between all
* threads */
synchronized (storeLock) {
/* Try getting session out of Java store */
ses = store.get(hashCode);
/* Remove old entry from table. TLS 1.3 binder changes between
* resumptions and stored session should only be used to
* resume once. New session structure/object will be cached
* after the resumed session completes the handshake, for
* subsequent resumption attempts to use. */
store.remove(hashCode);
}
/* Check conditions where we need to create a new new session:
* 1. Session not found in cache
* 2. Session marked as not resumable
* 3. Original session cipher suite not available
* 4. Original session protocol version not available
*/
if (ses == null ||
!ses.isResumable() ||
!sessionCipherSuiteAvailable(ses, enabledCipherSuites) ||
!sessionProtocolAvailable(ses, enabledProtocols)) {
needNewSession = true;
}
if (needNewSession) {
if (ses == null) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "session not found in cache table, " +
"creating new session");
}
else if (!ses.isResumable()) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "native WOLFSSL_SESSION not resumable, " +
"creating new session");
}
else if (!sessionCipherSuiteAvailable(
ses, enabledCipherSuites)) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "cipher suite used in original WOLFSSL_SESSION " +
"not available, creating new session");
}
/* Not found in stored sessions create a new one */
ses = new WolfSSLImplementSSLSession(ssl, port, host, this);
ses.setValid(true); /* new sessions marked as valid */
ses.isFromTable = false;
ses.setPseudoSessionId(Integer.toString(ssl.hashCode())
.getBytes(StandardCharsets.UTF_8));
}
else {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "session found in cache, trying to resume");
ses.isFromTable = true;
if (ses.resume(ssl) != WolfSSL.SSL_SUCCESS) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "native wolfSSL_set_session() failed, " +
"creating new session");
ses = new WolfSSLImplementSSLSession(ssl, port, host, this);
ses.setValid(true);
ses.isFromTable = false;
ses.setPseudoSessionId(Integer.toString(ssl.hashCode())
.getBytes(StandardCharsets.UTF_8));
}
}
return ses;
}
/**
* Check if cipher suite from original WOLFSSL_SESSION
* (WolfSSLImplementSSLSession) is available in new WolfSSLSession
* WolfSSLParameters.
*
* This is used in getSession(), since if we try resuming an old session
* but the cipher suite used in that session is not available in the
* ClientHello, the server will close the connection and send back an
* alert. If wolfSSL on the server side, this will be an illegal_parameter
* alert.
*
* @param ses WolfSSLImplementSSLSession to get existing cipher suite from
* to check.
* @param enabledCipherSuites cipher suites enabled, usually coming from
* WolfSSLEngineHelper.getCiphers().
*
* @return true if cipher suite from session is available in
* WolfSSLParameters enabled suites, otherwise false.
*/
private boolean sessionCipherSuiteAvailable(WolfSSLImplementSSLSession ses,
String[] enabledCipherSuites) {
final String sessionCipher;
if (ses == null || enabledCipherSuites == null) {
return false;
}
sessionCipher = ses.getSessionCipherSuite();
if (Arrays.asList(enabledCipherSuites).contains(sessionCipher)) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "WOLFSSL_SESSION cipher suite available in " +
"enabled ciphers");
return true;
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "WOLFSSL_SESSION cipher suite (" + sessionCipher +
") differs from enabled suites list");
return false;
}
/**
* Check if protocol from original WOLFSSL_SESSION
* (WolfSSLImplementSSLSession) is available in new WolfSSLSession
* WolfSSLParameters.
*
* @param ses WolfSSLImplementSSLSession to get existing protocol from
* to check
* @param enabledProtocols protocols enabled on this SSLSocket/SSLEngine,
* usually coming from WolfSSLEngineHelper.getProtocols().
*
* @return true if protocol from session is available in WolfSSLParameters
* enabled protocols, otherwise false.
*/
private boolean sessionProtocolAvailable(WolfSSLImplementSSLSession ses,
String[] enabledProtocols) {
final String sessionProtocol;
if (ses == null || enabledProtocols == null) {
return false;
}
sessionProtocol = ses.getProtocol();
if (sessionProtocol == null) {
return false;
}
if (Arrays.asList(enabledProtocols).contains(sessionProtocol)) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "WOLFSSL_SESSION protocol available in " +
"enabled protocols");
return true;
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "WOLFSSL_SESSION protocol (" + sessionProtocol +
") differs from enabled protocol list: " +
Arrays.asList(enabledProtocols));
return false;
}
/**
* Print summary of current SessionStore (LinkedHashMap) status.
* Prints out size of current SessionStore. If size is greater than zero,
* prints out host:port of all sessions stored in the store.
* Called by getSession(). */
private void printSessionStoreStatus() {
if (!WolfSSLDebug.isDebugEnabled(WolfSSLDebug.Component.JSSE)) {
return;
}
synchronized (storeLock) {
Collection<WolfSSLImplementSSLSession> values =
store.values();
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "SessionStore Status : (" + this +
") --------------------------");
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> " size: " + store.size());
if (store.size() > 0) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> " values: ");
for (WolfSSLImplementSSLSession s : values) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> " " + s.getHost() + ": " + s.getPort());
}
}
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "------------------------------------------------");
}
}
/** Returns a new session, does not check/save for resumption
*
* @param ssl WOLFSSL class to reference with new session
* @param clientMode true if on client side, false if server
* @param host hostname of peer, or null if not available
* @param port port of peer
*
* @return a new SSLSession on success
*/
protected synchronized WolfSSLImplementSSLSession getSession(
WolfSSLSession ssl, boolean clientMode, String host, int port) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "creating new session");
WolfSSLImplementSSLSession ses =
new WolfSSLImplementSSLSession(ssl, this, host, port);
ses.setValid(true);
ses.isFromTable = false;
ses.setPseudoSessionId(Integer.toString(ssl.hashCode())
.getBytes(StandardCharsets.UTF_8));
return ses;
}
/**
* Internal helper function to check if session ID is all zeros.
* Used by addSession()
*
* @param id session ID
* @return true if array is all zeros (0x00), otherwise false
*/
private boolean idAllZeros(byte[] id) {
boolean ret = true;
if (id == null) {
return true;
}
for (int i = 0; i < id.length; i++) {
if (id[i] != 0x00) {
return false;
}
}
return true;
}
/**
* Add SSLSession into wolfJSSE Java session cache table, to be used
* for session resumption.
*
* Session is stored into the session table using a hash code as the key.
* If the peer host is not null, the hash code is based on a concatenation
* of the peer host and port. If the peer host is null, the hash code
* is based on the session ID (if ID is not null, and non-zero length).
* Otherwise, no hash code is generated and the session is not stored into
* the session cache table.
*
* This method synchronizes on the static/global storeLock object, since
* the session cache is global and shared amongst all threads.
*
* @param session SSLSession to be stored in Java session cache
* @return WolfSSL.SSL_SUCCESS on success
*/
protected int addSession(WolfSSLImplementSSLSession session) {
String toHash;
final int hashCode;
/* Don't store session if invalid (or not complete with sesPtr
* if on client side, or not resumable). Server-side still needs to
* store session for things like returning the session ID, even though
* sesPtr will be 0 since server manages session cache at native
* level. */
if (!session.isValid() ||
(session.getSide() == WolfSSL.WOLFSSL_CLIENT_END &&
(!session.sessionPointerSet() || !session.isResumable()))) {
if (!session.isResumable()) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Not storing session in Java client cache since " +
"native WOLFSSL_SESSION is not resumable");
}
return WolfSSL.SSL_FAILURE;
}
if (session.getPeerHost() != null) {
/* Generate key for storing into session table (host:port) */
toHash = session.getPeerHost().concat(Integer.toString(
session.getPeerPort()));
hashCode = toHash.hashCode();
}
else {
/* If no peer host is available then create hash key from
* session ID if not null, not zero length, and not all zeros */
byte[] sessionId = session.getId();
if (sessionId != null && sessionId.length > 0 &&
(idAllZeros(sessionId) == false)) {
hashCode = Arrays.toString(session.getId()).hashCode();
} else {
hashCode = 0;
}
}
/* Always try to store session into cache table, as long as we
* have a hashCode. If session already exists for hashCode, it
* will be overwritten with new/refreshed version */
if (hashCode != 0) {
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "stored session in cache table (host: " +
session.getPeerHost() + ", port: " +
session.getPeerPort() + ") " + "hashCode = " + hashCode +
" side = " + session.getSideString());
/* Lock access to store while adding new session, store is global */
synchronized (storeLock) {
session.isInTable = true;
store.put(hashCode, session);
}
printSessionStoreStatus();
}
return WolfSSL.SSL_SUCCESS;
}
/**
* Internal function to return a list of valid session IDs.
*
* Expired sessions should already have been invalidated before this call
* via updateTimeouts(), but callers may also invalidate sessions for
* other reasons. Filter validity here so callers can avoid an extra
* per-ID lookup.
*
* @param side server or client side to get list of ID's from
* @return enumerated valid session IDs
*/
protected Enumeration<byte[]> getAllIDs(int side) {
List<byte[]> ret = new ArrayList<>();
synchronized (storeLock) {
for (Object obj : store.values()) {
WolfSSLImplementSSLSession current =
(WolfSSLImplementSSLSession)obj;
if (current.getSide() == side && current.isValid()) {
ret.add(current.getId());
}
}
return Collections.enumeration(ret);
}
}
/**
* Getter function for session with session id 'ID'
* @param ID the session id to search for
* @param side if the session is expected on the server or client side
* @return session from the store that has session id 'ID'
*/
protected WolfSSLImplementSSLSession getSession(byte[] ID, int side) {
WolfSSLImplementSSLSession ret = null;
synchronized (storeLock) {
for (Object obj : store.values()) {
WolfSSLImplementSSLSession current =
(WolfSSLImplementSSLSession)obj;
if (current.getSide() == side &&
java.util.Arrays.equals(ID, current.getId())) {
ret = current;
break;
}
}
return ret;
}
}
/**
* Goes through the list of sessions and checks for timeouts. If timed out
* then the session is invalidated.
* @param in the updated timeout value to check against
* @param side server or client side getting the timeout update
*/
protected void updateTimeouts(int in, int side) {
Date currentDate = new Date();
long now = currentDate.getTime();
synchronized (storeLock) {
for (Object obj : store.values()) {
long diff;
WolfSSLImplementSSLSession current =
(WolfSSLImplementSSLSession)obj;
if (current.getSide() == side) {
/* difference in seconds */
diff = (now - current.creation.getTime()) / 1000;
if (diff < 0) {
/* session is from the future ... */ /* TODO */
}
if (in > 0 && diff >= in) {
current.invalidate();
}
try {
current.setNativeTimeout(in);
} catch (IllegalStateException e) {
/* Native WolfSSLSession has been freed,
* invalidate this session entry */
WolfSSLDebug.log(getClass(), WolfSSLDebug.INFO,
() -> "Native session freed while updating " +
"timeout, invalidating cache entry: " +
e.getMessage());
current.invalidate();
}
}
}
}
}
private static class SessionStore<K, V> extends LinkedHashMap<K, V> {
/**
* user defined ID
*/
private static final long serialVersionUID = 1L;
private final int maxSz;
/**
* @param in max size of hash map before oldest entry is overwritten
*/
protected SessionStore(int in) {
maxSz = in;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> oldest) {
return size() > maxSz;
}
}
@SuppressWarnings({"deprecation", "removal"})
@Override
protected synchronized void finalize() throws Throwable {
/* Clear LinkedHashMap and set to null to allow
* for garbage collection */
if (store != null) {
store.clear();
store = null;
}
super.finalize();
}
}