-
Notifications
You must be signed in to change notification settings - Fork 130
/
LogFile.java
1708 lines (1462 loc) · 60.1 KB
/
LogFile.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
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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// --- BEGIN COPYRIGHT BLOCK ---
// This program 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; version 2 of the License.
//
// This program 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-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.logging;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.Signature;
import java.security.SignatureException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import javax.servlet.ServletException;
import org.apache.commons.lang.StringUtils;
import org.mozilla.jss.CryptoManager;
import org.mozilla.jss.crypto.CryptoToken;
import org.mozilla.jss.crypto.ObjectNotFoundException;
import org.mozilla.jss.crypto.TokenException;
import org.mozilla.jss.crypto.X509Certificate;
import org.mozilla.jss.util.Base64OutputStream;
import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.IExtendedPluginInfo;
import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.common.Constants;
import com.netscape.certsrv.common.NameValuePairs;
import com.netscape.certsrv.logging.AuditEvent;
import com.netscape.certsrv.logging.ConsoleError;
import com.netscape.certsrv.logging.ELogException;
import com.netscape.certsrv.logging.ILogEvent;
import com.netscape.certsrv.logging.ILogEventListener;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.logging.LogSource;
import com.netscape.certsrv.logging.SignedAuditEvent;
import com.netscape.certsrv.logging.SystemEvent;
import com.netscape.cmscore.apps.CMSEngine;
import com.netscape.cmsutil.util.Utils;
import netscape.ldap.client.JDAPAVA;
import netscape.ldap.client.JDAPFilter;
import netscape.ldap.client.JDAPFilterAnd;
import netscape.ldap.client.JDAPFilterEqualityMatch;
import netscape.ldap.client.JDAPFilterNot;
import netscape.ldap.client.JDAPFilterOr;
import netscape.ldap.client.JDAPFilterPresent;
import netscape.ldap.client.JDAPFilterSubString;
/**
* A log event listener which write logs to log files
*
* @version $Revision$, $Date$
**/
public class LogFile implements ILogEventListener, IExtendedPluginInfo {
private static Logger signedAuditLogger = SignedAuditLogger.getLogger();
public static final String PROP_TYPE = "type";
public static final String PROP_REGISTER = "register";
public static final String PROP_ON = "enable";
public static final String PROP_TRACE = "trace";
public static final String PROP_SIGNED_AUDIT_LOG_SIGNING = "logSigning";
public static final String PROP_SIGNED_AUDIT_CERT_NICKNAME =
"signedAuditCertNickname";
public static final String PROP_SIGNED_AUDIT_SELECTED_EVENTS = "events";
public static final String PROP_SIGNED_AUDIT_UNSELECTED_EVENTS = "unselected.events";
public static final String PROP_SIGNED_AUDIT_MANDATORY_EVENTS = "mandatory.events";
public static final String PROP_SIGNED_AUDIT_FILTERS = "filters";
public static final String PROP_LEVEL = "level";
static final String PROP_FILE_NAME = "fileName";
static final String PROP_LAST_HASH_FILE_NAME = "lastHashFileName";
static final String PROP_BUFFER_SIZE = "bufferSize";
static final String PROP_FLUSH_INTERVAL = "flushInterval";
private final static String LOG_SIGNED_AUDIT_EXCEPTION =
"LOG_SIGNED_AUDIT_EXCEPTION_1";
protected IConfigStore mConfig = null;
/**
* The date string used in the log file name
*/
static final String DATE_PATTERN = "yyyyMMddHHmmss";
//It may be interesting to make this flexable someday....
protected SimpleDateFormat mLogFileDateFormat = new SimpleDateFormat(DATE_PATTERN);
/**
* The default output stream buffer size in bytes
*/
static final int BUFFER_SIZE = 512;
/**
* The default output flush interval in seconds
*/
static final int FLUSH_INTERVAL = 5;
/**
* The log file
*/
protected File mFile = null;
/**
* The log file name
*/
protected String mFileName = null;
/**
* The log file output stream
*/
protected BufferedWriter mLogWriter = null;
/**
* The log date entry format pattern
*/
protected String mDatePattern = "dd/MMM/yyyy:HH:mm:ss z";
/**
* The log date entry format
*/
protected SimpleDateFormat mLogDateFormat = new SimpleDateFormat(mDatePattern);
/**
* The date object used for log entries
*/
protected Date mDate = new Date();
/**
* The number of bytes written to the current log file
*/
protected int mBytesWritten = 0;
/**
* The output buffer size in bytes
*/
protected int mBufferSize = BUFFER_SIZE;
/**
* The output buffer flush interval
*/
protected int mFlushInterval = FLUSH_INTERVAL;
/**
* The number of unflushed bytes
*/
protected int mBytesUnflushed = 0;
/**
* The output buffer flush interval thread
*/
private Thread mFlushThread = null;
/**
* The mandatory log event types
*/
protected Set<String> mandatoryEvents = new LinkedHashSet<String>();
/**
* The selected log event types
*/
protected Set<String> selectedEvents = new LinkedHashSet<String>();
/**
* The unselected log event types
*/
protected Set<String> unselectedEvents = new LinkedHashSet<String>();
/**
* The event filters
*/
protected Map<String, JDAPFilter> filters = new HashMap<String, JDAPFilter>();
/**
* The eventType that this log is triggered
*/
protected String mType = null;
/**
* The log is turned on/off
*/
protected boolean mOn = false;
/**
* Should this log listener self-register or not
*/
protected boolean mRegister = false;
protected boolean mTrace = false;
/**
* Log signing is on/off
*/
protected boolean mLogSigning = false;
/**
* Nickname of certificate to use to sign log.
*/
private String mSAuditCertNickName = "";
/**
* The provider used by the KeyGenerator and Mac
*/
static final String CRYPTO_PROVIDER = "Mozilla-JSS";
/**
* The log level threshold
* Only logs with level greater or equal than this value will be written
*/
protected long mLevel = 1;
/**
* Constructor for a LogFile.
*
*/
public LogFile() {
}
public void init(ISubsystem owner, IConfigStore config)
throws EBaseException {
mConfig = config;
try {
mOn = config.getBoolean(PROP_ON, true);
} catch (EBaseException e) {
throw new ELogException(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED",
config.getName() + "." + PROP_ON));
}
try {
mLogSigning = config.getBoolean(PROP_SIGNED_AUDIT_LOG_SIGNING,
false);
} catch (EBaseException e) {
throw new ELogException(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED",
config.getName() + "." + PROP_SIGNED_AUDIT_LOG_SIGNING));
}
if (mOn && mLogSigning) {
try {
mSAuditCertNickName = config.getString(
PROP_SIGNED_AUDIT_CERT_NICKNAME);
CMS.debug("LogFile: init(): audit log signing enabled. signedAuditCertNickname=" + mSAuditCertNickName);
} catch (EBaseException e) {
throw new ELogException(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED",
config.getName() + "."
+ PROP_SIGNED_AUDIT_CERT_NICKNAME));
}
if (mSAuditCertNickName == null ||
mSAuditCertNickName.trim().equals("")) {
throw new ELogException(CMS.getUserMessage(
"CMS_BASE_GET_PROPERTY_FAILED",
config.getName() + "."
+ PROP_SIGNED_AUDIT_CERT_NICKNAME));
}
}
// mandatory events
String mandatoryEventsList = config.getString(PROP_SIGNED_AUDIT_MANDATORY_EVENTS, "");
for (String event : StringUtils.split(mandatoryEventsList, ", ")) {
mandatoryEvents.add(event);
}
// selected events
String selectedEventsList = config.getString(PROP_SIGNED_AUDIT_SELECTED_EVENTS, "");
for (String event : StringUtils.split(selectedEventsList, ", ")) {
selectedEvents.add(event);
}
// unselected events
String unselectedEventsList = config.getString(PROP_SIGNED_AUDIT_UNSELECTED_EVENTS, "");
for (String event : StringUtils.split(unselectedEventsList, ", ")) {
unselectedEvents.add(event);
}
CMS.debug("Event filters:");
IConfigStore filterStore = config.getSubStore(PROP_SIGNED_AUDIT_FILTERS);
for (Enumeration<String> e = filterStore.getPropertyNames(); e.hasMoreElements(); ) {
String eventType = e.nextElement();
// get event filter
String strFilter = filterStore.get(eventType);
CMS.debug(" - " + eventType + ": " + strFilter);
// parse filter
JDAPFilter filter = JDAPFilter.getFilter(strFilter);
filters.put(eventType, filter);
}
try {
init(config);
} catch (IOException e) {
throw new ELogException(CMS.getUserMessage("CMS_LOG_UNEXPECTED_EXCEPTION", e.toString()));
}
// set up signing here to ensure audit logs generated during
// subsequent component initialization are signed properly
if (mOn && mLogSigning) {
try {
CMS.debug("LogFile: setting up log signing");
setupSigning();
signedAuditLogger.log(CMS.getLogMessage(
AuditEvent.AUDIT_LOG_STARTUP,
ILogger.SYSTEM_UID,
ILogger.SUCCESS));
} catch (EBaseException e) {
signedAuditLogger.log(CMS.getLogMessage(
AuditEvent.AUDIT_LOG_STARTUP,
ILogger.SYSTEM_UID,
ILogger.FAILURE));
throw e;
}
}
}
/**
* add the event to the selected events list
*
* @param event to be selected
*/
public void selectEvent(String event) {
selectedEvents.add(event);
unselectedEvents.remove(event);
}
/**
* remove the event from the selected events list
*
* @param event to be de-selected
*/
public void deselectEvent(String event) {
selectedEvents.remove(event);
unselectedEvents.add(event);
}
/**
* replace the selected events list
*
* @param events comma-separated event list
*/
public void replaceEvents(String events) {
// unselect all events
unselectedEvents.addAll(selectedEvents);
selectedEvents.clear();
// select specified events
for (String event : StringUtils.split(events, ", ")) {
selectEvent(event);
}
}
public static String base64Encode(byte[] bytes) throws IOException {
// All this streaming is lame, but Base64OutputStream needs a
// PrintStream
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (Base64OutputStream b64 = new Base64OutputStream(
new PrintStream(new FilterOutputStream(output)))) {
b64.write(bytes);
b64.flush();
// This is internationally safe because Base64 chars are
// contained within 8859_1
return output.toString("8859_1");
}
}
private static boolean mInSignedAuditLogFailureMode = false;
private static synchronized void shutdownCMS() {
if (mInSignedAuditLogFailureMode == false) {
// Set signed audit log failure mode true
// No, this isn't a race condition, because the method is
// synchronized. We just want to avoid an infinite loop.
mInSignedAuditLogFailureMode = true;
CMS.debug("LogFile: Disabling subsystem due to signed logging failure");
CMSEngine engine = (CMSEngine) CMS.getCMSEngine();
engine.disableSubsystem();
}
}
/**
* Initialize and open the log using the parameters from a config store
*
* @param config The property config store to find values in
*/
public void init(IConfigStore config) throws IOException,
EBaseException {
String fileName = null;
String defaultFileName = null;
String signedAuditDefaultFileName = "";
mConfig = config;
try {
mTrace = config.getBoolean(PROP_TRACE, false);
} catch (EBaseException e) {
throw new ELogException(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED",
config.getName() + "." + PROP_TRACE));
}
try {
mType = config.getString(PROP_TYPE, "system");
} catch (EBaseException e) {
throw new ELogException(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED",
config.getName() + "." + PROP_TYPE));
}
try {
mRegister = config.getBoolean(PROP_REGISTER, true);
} catch (EBaseException e) {
throw new ELogException(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED",
config.getName() + "." + PROP_REGISTER));
}
if (mOn) {
if (mRegister) {
CMS.getLogger().getLogQueue().addLogEventListener(this);
}
} else {
// shutdown the listener, remove the listener
if (mRegister) {
CMS.getLogger().getLogQueue().removeLogEventListener(this);
shutdown();
}
}
try {
mLevel = config.getInteger(PROP_LEVEL, 3);
} catch (EBaseException e) {
e.printStackTrace();
throw new ELogException(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED",
config.getName() + "." + PROP_LEVEL));
}
try {
// retrieve the subsystem
String subsystem = "";
ISubsystem caSubsystem = CMS.getSubsystem("ca");
if (caSubsystem != null) {
subsystem = "ca";
}
ISubsystem raSubsystem = CMS.getSubsystem("ra");
if (raSubsystem != null) {
subsystem = "ra";
}
ISubsystem kraSubsystem = CMS.getSubsystem("kra");
if (kraSubsystem != null) {
subsystem = "kra";
}
ISubsystem ocspSubsystem = CMS.getSubsystem("ocsp");
if (ocspSubsystem != null) {
subsystem = "ocsp";
}
// retrieve the instance name
String instIDPath = CMS.getInstanceDir();
int index = instIDPath.lastIndexOf("/");
String instID = instIDPath.substring(index + 1);
// build the default signedAudit file name
signedAuditDefaultFileName = subsystem + "_"
+ instID + "_" + "audit";
} catch (Exception e2) {
throw new ELogException(
CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED",
config.getName() + "." +
PROP_FILE_NAME));
}
// the default value is determined by the eventType.
if (mType.equals(ILogger.PROP_SIGNED_AUDIT)) {
defaultFileName = "logs/signedAudit/" + signedAuditDefaultFileName;
} else if (mType.equals(ILogger.PROP_SYSTEM)) {
defaultFileName = "logs/system";
} else if (mType.equals(ILogger.PROP_AUDIT)) {
defaultFileName = "logs/transactions";
} else {
throw new ELogException(CMS.getUserMessage("CMS_LOG_INVALID_LOG_TYPE",
config.getName(), mType));
}
try {
fileName = config.getString(PROP_FILE_NAME, defaultFileName);
} catch (EBaseException e) {
throw new ELogException(CMS.getUserMessage("CMS_BASE_GET_PROPERTY_FAILED",
config.getName() + "." + PROP_FILE_NAME));
}
if (mOn) {
init(fileName, config.getInteger(PROP_BUFFER_SIZE, BUFFER_SIZE),
config.getInteger(PROP_FLUSH_INTERVAL, FLUSH_INTERVAL));
}
}
/**
* Initialize and open the log
*
* @param bufferSize The buffer size for the output stream in bytes
* @param flushInterval The interval in seconds to flush the log
*/
public void init(String fileName, int bufferSize, int flushInterval) throws IOException, ELogException {
if (fileName == null)
throw new ELogException(CMS.getUserMessage("CMS_LOG_INVALID_FILE_NAME", "null"));
CMS.debug("Creating " + getClass().getSimpleName() + "(" + fileName + ")");
//If we want to reuse the old log files
//mFileName = fileName + "." + mLogFileDateFormat.format(mDate);
mFileName = fileName;
if (!Utils.isNT()) {
// Always insure that a physical file exists!
Utils.exec("touch " + mFileName);
Utils.exec("chmod 00640 " + mFileName);
}
mFile = new File(mFileName);
mBufferSize = bufferSize;
setFlushInterval(flushInterval);
open();
}
private PrivateKey mSigningKey = null;
private Signature mSignature = null;
private void setupSigning() throws EBaseException {
try {
Provider[] providers = java.security.Security.getProviders();
int ps = providers.length;
for (int i = 0; i < ps; i++) {
CMS.debug("LogFile: provider " + i + "= " + providers[i].getName());
}
CryptoManager cm = CryptoManager.getInstance();
// find CertServer's private key
X509Certificate cert = cm.findCertByNickname(mSAuditCertNickName);
if (cert != null) {
CMS.debug("LogFile: setupSignig(): found cert:" + mSAuditCertNickName);
} else {
CMS.debug("LogFile: setupSignig(): cert not found:" + mSAuditCertNickName);
}
mSigningKey = cm.findPrivKeyByCert(cert);
String sigAlgorithm;
if (mSigningKey.getAlgorithm().equalsIgnoreCase("RSA")) {
sigAlgorithm = "SHA-256/RSA";
} else if (mSigningKey.getAlgorithm().equalsIgnoreCase("EC")) {
sigAlgorithm = "SHA-256/EC";
} else {
throw new NoSuchAlgorithmException("Unknown private key type");
}
CryptoToken savedToken = cm.getThreadToken();
try {
CryptoToken keyToken =
((org.mozilla.jss.pkcs11.PK11PrivKey) mSigningKey)
.getOwningToken();
cm.setThreadToken(keyToken);
mSignature = java.security.Signature.getInstance(sigAlgorithm,
CRYPTO_PROVIDER);
} finally {
cm.setThreadToken(savedToken);
}
mSignature.initSign(mSigningKey);
// get the last signature from the currently-opened file
String entry = getLastSignature(mFile);
if (entry != null) {
mSignature.update(entry.getBytes("UTF-8"));
mSignature.update(LINE_SEP_BYTE);
}
// Always start off with a signature. That way, even if there
// were problems with the log file we inherited, we will
// get a fresh start with this instance.
pushSignature();
} catch (CryptoManager.NotInitializedException nie) {
setupSigningFailure("BASE_CRYPTOMANAGER_UNINITIALIZED", nie);
} catch (ObjectNotFoundException onfe) {
setupSigningFailure("LOG_SIGNING_CERT_NOT_FOUND", onfe);
} catch (TokenException te) {
setupSigningFailure("BASE_TOKEN_ERROR_0", te);
} catch (NoSuchAlgorithmException nsae) {
setupSigningFailure("LOG_NO_SUCH_ALGORITHM_0", nsae);
} catch (NoSuchProviderException nspe) {
setupSigningFailure("BASE_PROVIDER_NOT_SUPPORTED", nspe);
} catch (InvalidKeyException ike) {
setupSigningFailure("BASE_INVALID_KEY", ike);
} catch (SignatureException se) {
setupSigningFailure("LOG_SIGNING_OP_FAILED", se);
} catch (UnsupportedEncodingException uee) {
setupSigningFailure("LOG_UNEXPECTED_EXCEPTION", uee);
} catch (IOException ioe) {
setupSigningFailure("LOG_UNEXPECTED_EXCEPTION", ioe);
} catch (Exception e) {
setupSigningFailure("LOG_UNEXPECTED_EXCEPTION", e);
}
}
private static void setupSigningFailure(String logMessageCode, Exception e)
throws EBaseException {
try {
ConsoleError.send(new SystemEvent(
CMS.getLogMessage(logMessageCode)));
} catch (Exception e2) {
// don't allow an exception while printing to the console
// prevent us from running the rest of this function.
e2.printStackTrace();
}
e.printStackTrace();
shutdownCMS();
throw new EBaseException(e.toString());
}
/**
* Startup the instance
* <P>
*
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_AUDIT_LOG_STARTUP used at audit function startup
* </ul>
*
* @exception EBaseException if an internal error occurred
*/
public void startup() throws EBaseException {
}
/**
* Retrieves the eventType this log is triggered.
*/
public String getType() {
return mType;
}
/**
* Retrieves the log on/off.
*/
public String getOn() {
return String.valueOf(mOn);
}
/**
* Retrieves the log level threshold.
*/
public long getLevel() {
return mLevel;
}
/**
* Retrieves the base log file name.
*/
public String getName() {
return mFileName;
}
/**
* Record that the signed audit log has been signed
* <P>
*
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_SIGNING used when a signature on the audit log is generated (same as
* "flush" time)
* </ul>
*
* @exception IOException for input/output problems
* @exception ELogException when plugin implementation fails
* @exception SignatureException when signing fails
* @exception InvalidKeyException when an invalid key is utilized
*/
private void pushSignature() throws IOException, ELogException,
SignatureException, InvalidKeyException {
byte[] sigBytes = null;
if (mSignature == null) {
return;
}
sigBytes = mSignature.sign();
mSignature.initSign(mSigningKey);
Object o[] = new Object[1];
o[0] = null;
// cook up a signed audit log message to record mac
// so as to avoid infinite recursiveness of calling
// the log() method
String auditMessage = CMS.getLogMessage(
AuditEvent.AUDIT_LOG_SIGNING,
ILogger.SYSTEM_UID,
ILogger.SUCCESS,
base64Encode(sigBytes));
ILogEvent ev = signedAuditLogger.create(
ILogger.LL_SECURITY,
auditMessage,
o,
ILogger.L_SINGLELINE);
doLog(ev, true);
}
private static String getLastSignature(File f) throws IOException {
BufferedReader r = new BufferedReader(new FileReader(f));
String lastSig = null;
String curLine = null;
while ((curLine = r.readLine()) != null) {
if (curLine.indexOf("AUDIT_LOG_SIGNING") != -1) {
lastSig = curLine;
}
}
r.close();
return lastSig;
}
/**
* Open the log file. This creates the buffered FileWriter
*
*/
protected synchronized void open() throws IOException {
RandomAccessFile out;
try {
out = new RandomAccessFile(mFile, "rw");
out.seek(out.length());
//XXX int or long?
mBytesWritten = (int) out.length();
if (!Utils.isNT()) {
try {
Utils.exec("chmod 00640 " + mFile.getCanonicalPath());
} catch (IOException e) {
CMS.debug("Unable to change file permissions on "
+ mFile.toString());
}
}
mLogWriter = new BufferedWriter(
new FileWriter(out.getFD()), mBufferSize);
// The first time we open, mSignature will not have been
// initialized yet. That's ok, we will push our first signature
// in setupSigning().
if (mLogSigning && (mSignature != null)) {
try {
pushSignature();
} catch (ELogException le) {
ConsoleError.send(
new SystemEvent(CMS.getUserMessage("CMS_LOG_ILLEGALARGUMENT",
mFileName)));
}
}
} catch (IllegalArgumentException iae) {
ConsoleError.send(
new SystemEvent(CMS.getUserMessage("CMS_LOG_ILLEGALARGUMENT",
mFileName)));
} catch (GeneralSecurityException gse) {
// error with signed audit log, shutdown CMS
ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_OPEN_FAILED", mFileName, gse.toString())));
gse.printStackTrace();
shutdownCMS();
}
mBytesUnflushed = 0;
}
/**
* Flush the log file. Also update the MAC for hash protected logs
*
*/
public synchronized void flush() {
try {
if (mLogSigning) {
try {
pushSignature();
} catch (ELogException le) {
ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_FLUSH_LOG_FAILED", mFileName,
le.toString())));
le.printStackTrace();
shutdownCMS();
}
}
if (mLogWriter != null) {
mLogWriter.flush();
}
} catch (IOException e) {
ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_FLUSH_LOG_FAILED", mFileName, e.toString())));
if (mLogSigning) {
//error in writing to signed audit log, shut down CMS
e.printStackTrace();
shutdownCMS();
}
} catch (GeneralSecurityException gse) {
// error with signed audit log, shutdown CMS
ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_FLUSH_LOG_FAILED", mFileName, gse.toString())));
gse.printStackTrace();
shutdownCMS();
} catch (Exception ee) {
ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_FLUSH_LOG_FAILED", mFileName, ee.toString())));
if(mLogSigning) {
ee.printStackTrace();
shutdownCMS();
}
}
mBytesUnflushed = 0;
}
/**
* Close the log file
*
*/
protected synchronized void close() {
try {
flush();
if (mLogWriter != null) {
mLogWriter.close();
}
} catch (IOException e) {
ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_CLOSE_FAILED", mFileName, e.toString())));
}
mLogWriter = null;
}
/**
* Shutdown this log file.
* <P>
*
* <ul>
* <li>signed.audit LOGGING_SIGNED_AUDIT_AUDIT_LOG_SHUTDOWN used at audit function shutdown
* </ul>
*/
public synchronized void shutdown() {
CMS.debug("Destroying LogFile(" + mFileName + ")");
String auditMessage = null;
setFlushInterval(0);
// log signed audit shutdown success
auditMessage = CMS.getLogMessage(
AuditEvent.AUDIT_LOG_SHUTDOWN,
ILogger.SYSTEM_UID,
ILogger.SUCCESS);
signedAuditLogger.log(auditMessage);
close();
}
/**
* Set the flush interval
* <P>
*
* @param flushInterval The amount of time in seconds until the log
* is flush. A value of 0 will disable autoflush. This will also set
* the update period for hash protected logs.
**/
public synchronized void setFlushInterval(int flushInterval) {
mFlushInterval = flushInterval * 1000;
if (mFlushThread == null && mFlushInterval > 0) {
mFlushThread = new FlushThread();
mFlushThread.setDaemon(true);
mFlushThread.start();
} else if (mFlushThread != null && mFlushInterval == 0) {
mFlushThread.interrupt();
}
this.notify();
}
/**
* Log flush thread. Sleep for the flush interval and flush the
* log. Changing flush interval to 0 will cause this thread to exit.
*/
final class FlushThread extends Thread {
/**
* Flush thread constructor including thread name
*/
public FlushThread() {
super();
super.setName(mFileName + ".flush-" + (Thread.activeCount() + 1));
}
public void run() {
while (mFlushInterval > 0) {
// Sleep for the interval and then flush the log
synchronized (LogFile.this) {
try {
LogFile.this.wait(mFlushInterval);
} catch (InterruptedException e) {
// shutdown
}
}
if (mFlushInterval == 0) {
break;
}
if (mBytesUnflushed > 0) {
flush();
}
}
mFlushThread = null;
}
}
/**
* Synchronized method to write an event to the log file.
*
* @param event The log event
*/
protected synchronized void doLog(ILogEvent event) throws ELogException {
doLog(event, false);
}
// Standard line separator byte. We always sign this line separator,
// regardless of what we actually write to the file, so that signature
// verification is platform-independent.
private static final byte LINE_SEP_BYTE = 0x0a;
/**
* This method actually does the logging, and is not overridden
* by subclasses, so you can call it and know that it will do exactly
* what you see below.
*/
private synchronized void doLog(ILogEvent event, boolean noFlush)
throws ELogException {
String entry = logEvt2String(event);
if (mLogWriter == null) {
String[] params = { mFileName, entry };
if (mLogSigning) {
ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_LOGFILE_CLOSED", params)));
// Failed to write to audit log, shut down CMS
shutdownCMS();