This repository has been archived by the owner on Mar 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 190
/
SSLLogger.java
596 lines (535 loc) · 23.3 KB
/
SSLLogger.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
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
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.ssl;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.nio.ByteBuffer;
import java.security.cert.Certificate;
import java.security.cert.Extension;
import java.security.cert.X509Certificate;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import sun.security.action.GetPropertyAction;
import sun.security.util.HexDumpEncoder;
import sun.security.x509.*;
/**
* Implementation of SSL logger.
*
* If the system property "javax.net.debug" is not defined, the debug logging
* is turned off. If the system property "javax.net.debug" is defined as
* empty, the debug logger is specified by System.getLogger("javax.net.ssl"),
* and applications can customize and configure the logger or use external
* logging mechanisms. If the system property "javax.net.debug" is defined
* and non-empty, a private debug logger implemented in this class is used.
*/
public final class SSLLogger {
private static final System.Logger logger;
private static final String property;
public static final boolean isOn;
static {
String p = GetPropertyAction.privilegedGetProperty("javax.net.debug");
if (p != null) {
if (p.isEmpty()) {
property = "";
logger = System.getLogger("javax.net.ssl");
} else {
property = p.toLowerCase(Locale.ENGLISH);
if (property.equals("help")) {
help();
}
logger = new SSLConsoleLogger("javax.net.ssl", p);
}
isOn = true;
} else {
property = null;
logger = null;
isOn = false;
}
}
private static void help() {
System.err.println();
System.err.println("help print the help messages");
System.err.println("expand expand debugging information");
System.err.println();
System.err.println("all turn on all debugging");
System.err.println("ssl turn on ssl debugging");
System.err.println();
System.err.println("The following can be used with ssl:");
System.err.println("\trecord enable per-record tracing");
System.err.println("\thandshake print each handshake message");
System.err.println("\tkeygen print key generation data");
System.err.println("\tsession print session activity");
System.err.println("\tdefaultctx print default SSL initialization");
System.err.println("\tsslctx print SSLContext tracing");
System.err.println("\tsessioncache print session cache tracing");
System.err.println("\tkeymanager print key manager tracing");
System.err.println("\ttrustmanager print trust manager tracing");
System.err.println("\tpluggability print pluggability tracing");
System.err.println();
System.err.println("\thandshake debugging can be widened with:");
System.err.println("\tdata hex dump of each handshake message");
System.err.println("\tverbose verbose handshake message printing");
System.err.println();
System.err.println("\trecord debugging can be widened with:");
System.err.println("\tplaintext hex dump of record plaintext");
System.err.println("\tpacket print raw SSL/TLS packets");
System.err.println();
System.exit(0);
}
/**
* Return true if the "javax.net.debug" property contains the
* debug check points, or System.Logger is used.
*/
public static boolean isOn(String checkPoints) {
if (property == null) { // debugging is turned off
return false;
} else if (property.isEmpty()) { // use System.Logger
return true;
} // use provider logger
String[] options = checkPoints.split(",");
for (String option : options) {
option = option.trim();
if (!SSLLogger.hasOption(option)) {
return false;
}
}
return true;
}
private static boolean hasOption(String option) {
option = option.toLowerCase(Locale.ENGLISH);
if (property.contains("all")) {
return true;
} else {
int offset = property.indexOf("ssl");
if (offset != -1 && property.indexOf("sslctx", offset) != -1) {
// don't enable data and plaintext options by default
if (!(option.equals("data")
|| option.equals("packet")
|| option.equals("plaintext"))) {
return true;
}
}
}
return property.contains(option);
}
public static void severe(String msg, Object... params) {
SSLLogger.log(Level.ERROR, msg, params);
}
public static void warning(String msg, Object... params) {
SSLLogger.log(Level.WARNING, msg, params);
}
public static void info(String msg, Object... params) {
SSLLogger.log(Level.INFO, msg, params);
}
public static void fine(String msg, Object... params) {
SSLLogger.log(Level.DEBUG, msg, params);
}
public static void finer(String msg, Object... params) {
SSLLogger.log(Level.TRACE, msg, params);
}
public static void finest(String msg, Object... params) {
SSLLogger.log(Level.ALL, msg, params);
}
private static void log(Level level, String msg, Object... params) {
if (logger.isLoggable(level)) {
if (params == null || params.length == 0) {
logger.log(level, msg);
} else {
try {
String formatted =
SSLSimpleFormatter.formatParameters(params);
logger.log(level, msg, formatted);
} catch (Exception exp) {
// ignore it, just for debugging.
}
}
}
}
static String toString(Object... params) {
try {
return SSLSimpleFormatter.formatParameters(params);
} catch (Exception exp) {
return "unexpected exception thrown: " + exp.getMessage();
}
}
private static class SSLConsoleLogger implements Logger {
private final String loggerName;
private final boolean useCompactFormat;
SSLConsoleLogger(String loggerName, String options) {
this.loggerName = loggerName;
options = options.toLowerCase(Locale.ENGLISH);
this.useCompactFormat = !options.contains("expand");
}
@Override
public String getName() {
return loggerName;
}
@Override
public boolean isLoggable(Level level) {
return (level != Level.OFF);
}
@Override
public void log(Level level,
ResourceBundle rb, String message, Throwable thrwbl) {
if (isLoggable(level)) {
try {
String formatted =
SSLSimpleFormatter.format(this, level, message, thrwbl);
System.err.write(formatted.getBytes("UTF-8"));
} catch (Exception exp) {
// ignore it, just for debugging.
}
}
}
@Override
public void log(Level level,
ResourceBundle rb, String message, Object... params) {
if (isLoggable(level)) {
try {
String formatted =
SSLSimpleFormatter.format(this, level, message, params);
System.err.write(formatted.getBytes("UTF-8"));
} catch (Exception exp) {
// ignore it, just for debugging.
}
}
}
}
private static class SSLSimpleFormatter {
private static final ThreadLocal<SimpleDateFormat> dateFormat =
new ThreadLocal<SimpleDateFormat>() {
@Override protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(
"yyyy-MM-dd kk:mm:ss.SSS z", Locale.ENGLISH);
}
};
private static final MessageFormat basicCertFormat = new MessageFormat(
"\"version\" : \"v{0}\",\n" +
"\"serial number\" : \"{1}\",\n" +
"\"signature algorithm\": \"{2}\",\n" +
"\"issuer\" : \"{3}\",\n" +
"\"not before\" : \"{4}\",\n" +
"\"not after\" : \"{5}\",\n" +
"\"subject\" : \"{6}\",\n" +
"\"subject public key\" : \"{7}\"\n",
Locale.ENGLISH);
private static final MessageFormat extendedCertFormart =
new MessageFormat(
"\"version\" : \"v{0}\",\n" +
"\"serial number\" : \"{1}\",\n" +
"\"signature algorithm\": \"{2}\",\n" +
"\"issuer\" : \"{3}\",\n" +
"\"not before\" : \"{4}\",\n" +
"\"not after\" : \"{5}\",\n" +
"\"subject\" : \"{6}\",\n" +
"\"subject public key\" : \"{7}\",\n" +
"\"extensions\" : [\n" +
"{8}\n" +
"]\n",
Locale.ENGLISH);
//
// private static MessageFormat certExtFormat = new MessageFormat(
// "{0} [{1}] '{'\n" +
// " critical: {2}\n" +
// " value: {3}\n" +
// "'}'",
// Locale.ENGLISH);
//
private static final MessageFormat messageFormatNoParas =
new MessageFormat(
"'{'\n" +
" \"logger\" : \"{0}\",\n" +
" \"level\" : \"{1}\",\n" +
" \"thread id\" : \"{2}\",\n" +
" \"thread name\" : \"{3}\",\n" +
" \"time\" : \"{4}\",\n" +
" \"caller\" : \"{5}\",\n" +
" \"message\" : \"{6}\"\n" +
"'}'\n",
Locale.ENGLISH);
private static final MessageFormat messageCompactFormatNoParas =
new MessageFormat(
"{0}|{1}|{2}|{3}|{4}|{5}|{6}\n",
Locale.ENGLISH);
private static final MessageFormat messageFormatWithParas =
new MessageFormat(
"'{'\n" +
" \"logger\" : \"{0}\",\n" +
" \"level\" : \"{1}\",\n" +
" \"thread id\" : \"{2}\",\n" +
" \"thread name\" : \"{3}\",\n" +
" \"time\" : \"{4}\",\n" +
" \"caller\" : \"{5}\",\n" +
" \"message\" : \"{6}\",\n" +
" \"specifics\" : [\n" +
"{7}\n" +
" ]\n" +
"'}'\n",
Locale.ENGLISH);
private static final MessageFormat messageCompactFormatWithParas =
new MessageFormat(
"{0}|{1}|{2}|{3}|{4}|{5}|{6} (\n" +
"{7}\n" +
")\n",
Locale.ENGLISH);
private static final MessageFormat keyObjectFormat = new MessageFormat(
"\"{0}\" : '{'\n" +
"{1}" +
"'}'\n",
Locale.ENGLISH);
// INFO: [TH: 123450] 2011-08-20 23:12:32.3225 PDT
// log message
// log message
// ...
private static String format(SSLConsoleLogger logger, Level level,
String message, Object ... parameters) {
if (parameters == null || parameters.length == 0) {
Object[] messageFields = {
logger.loggerName,
level.getName(),
Utilities.toHexString(Thread.currentThread().getId()),
Thread.currentThread().getName(),
dateFormat.get().format(new Date(System.currentTimeMillis())),
formatCaller(),
message
};
if (logger.useCompactFormat) {
return messageCompactFormatNoParas.format(messageFields);
} else {
return messageFormatNoParas.format(messageFields);
}
}
Object[] messageFields = {
logger.loggerName,
level.getName(),
Utilities.toHexString(Thread.currentThread().getId()),
Thread.currentThread().getName(),
dateFormat.get().format(new Date(System.currentTimeMillis())),
formatCaller(),
message,
(logger.useCompactFormat ?
formatParameters(parameters) :
Utilities.indent(formatParameters(parameters)))
};
if (logger.useCompactFormat) {
return messageCompactFormatWithParas.format(messageFields);
} else {
return messageFormatWithParas.format(messageFields);
}
}
private static String formatCaller() {
return StackWalker.getInstance().walk(s ->
s.dropWhile(f ->
f.getClassName().startsWith("sun.security.ssl.SSLLogger") ||
f.getClassName().startsWith("java.lang.System"))
.map(f -> f.getFileName() + ":" + f.getLineNumber())
.findFirst().orElse("unknown caller"));
}
private static String formatParameters(Object ... parameters) {
StringBuilder builder = new StringBuilder(512);
boolean isFirst = true;
for (Object parameter : parameters) {
if (isFirst) {
isFirst = false;
} else {
builder.append(",\n");
}
if (parameter instanceof Throwable) {
builder.append(formatThrowable((Throwable)parameter));
} else if (parameter instanceof Certificate) {
builder.append(formatCertificate((Certificate)parameter));
} else if (parameter instanceof ByteArrayInputStream) {
builder.append(formatByteArrayInputStream(
(ByteArrayInputStream)parameter));
} else if (parameter instanceof ByteBuffer) {
builder.append(formatByteBuffer((ByteBuffer)parameter));
} else if (parameter instanceof byte[]) {
builder.append(formatByteArrayInputStream(
new ByteArrayInputStream((byte[])parameter)));
} else if (parameter instanceof Map.Entry) {
@SuppressWarnings("unchecked")
Map.Entry<String, ?> mapParameter =
(Map.Entry<String, ?>)parameter;
builder.append(formatMapEntry(mapParameter));
} else {
builder.append(formatObject(parameter));
}
}
return builder.toString();
}
// "throwable": {
// ...
// }
private static String formatThrowable(Throwable throwable) {
StringBuilder builder = new StringBuilder(512);
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
try (PrintStream out = new PrintStream(bytesOut)) {
throwable.printStackTrace(out);
builder.append(Utilities.indent(bytesOut.toString()));
}
Object[] fields = {
"throwable",
builder.toString()
};
return keyObjectFormat.format(fields);
}
// "certificate": {
// ...
// }
private static String formatCertificate(Certificate certificate) {
if (!(certificate instanceof X509Certificate)) {
return Utilities.indent(certificate.toString());
}
StringBuilder builder = new StringBuilder(512);
try {
X509CertImpl x509 =
X509CertImpl.toImpl((X509Certificate)certificate);
X509CertInfo certInfo =
(X509CertInfo)x509.get(X509CertImpl.NAME + "." +
X509CertImpl.INFO);
CertificateExtensions certExts = (CertificateExtensions)
certInfo.get(X509CertInfo.EXTENSIONS);
if (certExts == null) {
Object[] certFields = {
x509.getVersion(),
Utilities.toHexString(
x509.getSerialNumber().toByteArray()),
x509.getSigAlgName(),
x509.getIssuerX500Principal().toString(),
dateFormat.get().format(x509.getNotBefore()),
dateFormat.get().format(x509.getNotAfter()),
x509.getSubjectX500Principal().toString(),
x509.getPublicKey().getAlgorithm()
};
builder.append(Utilities.indent(
basicCertFormat.format(certFields)));
} else {
StringBuilder extBuilder = new StringBuilder(512);
boolean isFirst = true;
for (Extension certExt : certExts.getAllExtensions()) {
if (isFirst) {
isFirst = false;
} else {
extBuilder.append(",\n");
}
extBuilder.append("{\n" +
Utilities.indent(certExt.toString()) + "\n}");
}
Object[] certFields = {
x509.getVersion(),
Utilities.toHexString(
x509.getSerialNumber().toByteArray()),
x509.getSigAlgName(),
x509.getIssuerX500Principal().toString(),
dateFormat.get().format(x509.getNotBefore()),
dateFormat.get().format(x509.getNotAfter()),
x509.getSubjectX500Principal().toString(),
x509.getPublicKey().getAlgorithm(),
Utilities.indent(extBuilder.toString())
};
builder.append(Utilities.indent(
extendedCertFormart.format(certFields)));
}
} catch (Exception ce) {
// ignore the exception
}
Object[] fields = {
"certificate",
builder.toString()
};
return Utilities.indent(keyObjectFormat.format(fields));
}
private static String formatByteArrayInputStream(
ByteArrayInputStream bytes) {
StringBuilder builder = new StringBuilder(512);
try (ByteArrayOutputStream bytesOut = new ByteArrayOutputStream()) {
HexDumpEncoder hexEncoder = new HexDumpEncoder();
hexEncoder.encodeBuffer(bytes, bytesOut);
builder.append(Utilities.indent(bytesOut.toString()));
} catch (IOException ioe) {
// ignore it, just for debugging.
}
return builder.toString();
}
private static String formatByteBuffer(ByteBuffer byteBuffer) {
StringBuilder builder = new StringBuilder(512);
try (ByteArrayOutputStream bytesOut = new ByteArrayOutputStream()) {
HexDumpEncoder hexEncoder = new HexDumpEncoder();
hexEncoder.encodeBuffer(byteBuffer.duplicate(), bytesOut);
builder.append(Utilities.indent(bytesOut.toString()));
} catch (IOException ioe) {
// ignore it, just for debugging.
}
return builder.toString();
}
private static String formatMapEntry(Map.Entry<String, ?> entry) {
String key = entry.getKey();
Object value = entry.getValue();
String formatted;
if (value instanceof String) {
// "key": "value"
formatted = "\"" + key + "\": \"" + (String)value + "\"";
} else if (value instanceof String[]) {
// "key": [ "string a",
// "string b",
// "string c"
// ]
StringBuilder builder = new StringBuilder(512);
String[] strings = (String[])value;
builder.append("\"" + key + "\": [\n");
for (String string : strings) {
builder.append(" \"" + string + "\"");
if (string != strings[strings.length - 1]) {
builder.append(",");
}
builder.append("\n");
}
builder.append(" ]");
formatted = builder.toString();
} else if (value instanceof byte[]) {
formatted = "\"" + key + "\": \"" +
Utilities.toHexString((byte[])value) + "\"";
} else if (value instanceof Byte) {
formatted = "\"" + key + "\": \"" +
Utilities.toHexString((byte)value) + "\"";
} else {
formatted = "\"" + key + "\": " +
"\"" + value.toString() + "\"";
}
return Utilities.indent(formatted);
}
private static String formatObject(Object obj) {
return obj.toString();
}
}
}