File: test_secure_logging.c

package info (click to toggle)
syslog-ng 4.8.1-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,456 kB
  • sloc: ansic: 177,631; python: 13,035; cpp: 11,611; makefile: 7,012; sh: 5,147; java: 3,651; xml: 3,344; yacc: 1,377; lex: 599; perl: 193; awk: 190; objc: 162
file content (732 lines) | stat: -rw-r--r-- 21,928 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (c) 2024 Gergo Ferenc Kovacs
 * Copyright (c) 2019 Airbus Commercial Aircraft
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * As an additional exemption you are allowed to compile & link against the
 * OpenSSL libraries as published by the OpenSSL project. See the file
 * COPYING for details.
 *
 */

#include <criterion/criterion.h>
#include "libtest/cr_template.h"
#include "libtest/msg_parse_lib.h"
#include "libtest/stopwatch.h"

// Secure logging functions
#include "slog.h"


#include "apphook.h"
#include "cfg.h"
#include "logmatcher.h"
#include "timeutils/cache.h"

#include <errno.h>
#include <string.h>
#include <unistd.h>


#define MAX_TEST_MESSAGES 1000
#define MIN_TEST_MESSAGES 10
#define PERFORMANCE_COUNTER 100000

// Local parse options
static MsgFormatOptions test_parse_options;

// Filenames and directory templates
static gchar *testDirTmpl = "/tmp/slog-XXXXXX/";
static gchar *hostKeyFile = "host.key";
static gchar *macFile = "mac.dat";

// Test data for secure logging
static gchar *macAddr = "a08cefa7b520";
static gchar *serial = "CAC7119N43";
static gchar *prefix = "slog/";
static gchar *context_id = "test-context-id";

// Data needed to run a test
typedef struct _testData
{
  guchar hostKey[KEY_LENGTH];
  GString *testName;
  GString *keyFile;
  GString *macFile;
  GString *testDir;
} TestData;

/*************************************************************************/
/* Utility functions needed for testing the secure logging functionality */
/*************************************************************************/

// Generate random number between low and high
int randomNumber(int low, int high)
{
  return rand()%((high+1)-low)+low;
}

// Generate a sample message with a fixed and a random part
LogMessage *create_random_sample_message(void)
{
  LogMessage *msg;

  GString *msg_str = g_string_new("<155>2019-07-11T10:34:56+01:00 aicorp syslog-ng[23323]:");

  // Append a random string
  int num = randomNumber(10, 500);
  for (int i = 0; i<num; i++)
    {
      // 65 to 90 are upper case letters
      g_string_append_c(msg_str, randomNumber(65, 90));
    }

  msg = msg_format_parse(&test_parse_options, (const guchar *) msg_str->str, msg_str->len);
  log_msg_set_saddr_ref(msg, g_sockaddr_inet_new("10.11.12.13", 1010));
  log_msg_set_match(msg, 0, "whole-match", -1);
  log_msg_set_match(msg, 1, "first-match", -1);
  log_msg_set_tag_by_name(msg, "alma");
  log_msg_set_tag_by_name(msg, "korte");
  log_msg_clear_tag_by_name(msg, "narancs");
  log_msg_set_tag_by_name(msg, "citrom");
  log_msg_set_tag_by_name(msg, "tag,containing,comma");
  msg->rcptid = 555;
  msg->host_id = 0xcafebabe;

  // Fix some externally or automatically defined values
  log_msg_set_value(msg, LM_V_HOST_FROM, "kismacska", -1);
  msg->timestamps[LM_TS_RECVD].ut_sec = 1139684315;
  msg->timestamps[LM_TS_RECVD].ut_usec = 639000;
  msg->timestamps[LM_TS_RECVD].ut_gmtoff = get_local_timezone_ofs(1139684315);

  g_string_free(msg_str, TRUE);
  return msg;
}

// Create a slog template instance
LogTemplate *createTemplate(TestData *testData)
{
  GString *slog_templ_str = g_string_new("slog");

  // Initialize the template
  g_string_printf(slog_templ_str, "$(slog -k %s -m %s $RAWMSG)", testData->keyFile->str, testData->macFile->str);

  LogTemplate *slog_templ = compile_template(slog_templ_str->str);

  cr_assert(slog_templ != NULL, "Template '%s' does not compile correctly", slog_templ_str->str);

  g_string_free(slog_templ_str, TRUE);

  return slog_templ;
}

// Create a collection of random log messages for testing purposes
void createLogMessages(gint num, LogMessage **log)
{
  if(num <= 0)
    {
      cr_log_error("Invalid argument passed to createLog. num = %d", num);
    }

  for(int i = 0; i < num; i++)
    {
      log[i] = create_random_sample_message();
    }
}

// Apply the template to a single log message
GString *applyTemplate(LogTemplate *templ, LogMessage *msg)
{
  GString *output = g_string_new(prefix);

  LogTemplateEvalOptions options = {NULL, LTZ_LOCAL, 999, context_id, LM_VT_STRING};
  // Execute secure logging template
  log_template_append_format_with_context(
    templ,       // Secure logging template
    &msg,        // Message(s) to pass to the template
    1,           // Number of message to pass to the template
    &options,
    output);     // Output string after applying the template

  return output;
}

// Find an integer in an array of integers
int findInArray(int index, int *buffer, int size)
{
  for (int i = 0; i<size; i++)
    {
      if (buffer[i]==index)
        {
          return 1;
        }
    }
  return 0;
}

// Verify messages with malicious modification and detect which entry is corrupted
GString **verifyMaliciousMessages(guchar *hostkey, gchar *macFileName, GString **templateOutput,
                                  size_t totalNumberOfMessages, int *brokenEntries)
{
  unsigned char keyZero[KEY_LENGTH];
  memcpy(keyZero, hostkey, KEY_LENGTH);

  GHashTable *tab = NULL;

  guint64 next = 0;
  guint64 start = 0;
  guint64 numberOfLogEntries = 0UL;

  GString **outputBuffer = g_new0(GString *, totalNumberOfMessages);

  gchar mac[CMAC_LENGTH];

  int ret = readBigMAC(macFileName, mac);
  cr_assert(ret == 1, "Unable to read aggregated MAC from file %s", macFileName);
  int problemsFound = 0;
  unsigned char cmac_tag[CMAC_LENGTH];
  gsize cmac_tag_capacity = G_N_ELEMENTS(cmac_tag);
  initVerify(totalNumberOfMessages, hostkey, &next, &start, templateOutput, &tab);

  for (int i = 0; i<totalNumberOfMessages; i++)
    {
      ret = iterateBuffer(1, &templateOutput[i], &next, hostkey, keyZero, 0, &outputBuffer[i], &numberOfLogEntries, cmac_tag,
                          cmac_tag_capacity, tab);
      if (ret == 0)
        {
          brokenEntries[problemsFound] = i;
          problemsFound++;
        }
    }
  ret = finalizeVerify(start, totalNumberOfMessages, (guchar *)mac, cmac_tag, tab);

  cr_assert(ret == 0, "Aggregated MAC is correct.");

  return outputBuffer;
}

// Verify log messages and compare them with the original
void verifyMessages(guchar *hostkey, gchar *macFileName, GString **templateOutput, LogMessage **original,
                    size_t totalNumberOfMessages)
{
  unsigned char keyZero[KEY_LENGTH];
  memcpy(keyZero, hostkey, KEY_LENGTH);

  GHashTable *tab = NULL;

  guint64 next = 0;
  guint64 start = 0;
  guint64 numberOfLogEntries = 0UL;

  GString **outputBuffer = g_new0(GString *, totalNumberOfMessages);

  gchar mac[CMAC_LENGTH];

  int ret =  readBigMAC(macFileName, mac);
  cr_assert(ret == 1, "Unable to read aggregated MAC from file %s", macFileName);

  unsigned char cmac_tag[CMAC_LENGTH];
  gsize cmac_tag_capacity = G_N_ELEMENTS(cmac_tag);
  ret = initVerify(totalNumberOfMessages, hostkey, &next, &start, templateOutput, &tab);
  cr_assert(ret == 1, "initVerify failed");

  ret = iterateBuffer(totalNumberOfMessages, templateOutput, &next, hostkey, keyZero, 0, outputBuffer,
                      &numberOfLogEntries, cmac_tag, cmac_tag_capacity, tab);
  cr_assert(ret == 1, "iterateBuffer failed");

  ret = finalizeVerify(start, totalNumberOfMessages, (guchar *)mac, cmac_tag, tab);
  cr_assert(ret == 1, "finalizeVerify failed");


  for (int i=0; i<totalNumberOfMessages; i++)
    {
      char *plaintextMessage = (outputBuffer[i]->str) + CTR_LEN_SIMPLE + COLON + BLANK;
      LogMessage *result = msg_format_parse(&test_parse_options, (const guchar *) plaintextMessage, strlen(plaintextMessage));
      log_msg_set_saddr(result, original[i]->saddr);
      assert_log_messages_equal(original[i], result);
      g_string_free(outputBuffer[i], TRUE);
      log_msg_unref(result);
    }

  g_free(outputBuffer);
}

// Generate keys to be used for the tests
void generateHostKey(guchar *hostkey, gchar *hostKeyFileName)
{
  // Create keys for the test
  guchar masterkey[KEY_LENGTH];
  int ret = generateMasterKey(masterkey);
  cr_assert(ret == 1, "Unable to generate master key");

  ret = deriveHostKey(masterkey, macAddr, serial, hostkey);
  cr_assert(ret == 1, "Unable to derive host key from master key for addr %s and serial number %s", macAddr, serial);

  ret = writeKey((gchar *)hostkey, 0, hostKeyFileName);
  cr_assert(ret == 1, "Unable to write host key to file %s", hostKeyFileName);
}

// Create a temporary directory
GString *createTemporaryDirectory(gchar *template)
{
  gchar buf[PATH_MAX];

  // Buffer for temporary path
  g_strlcpy(buf, template, strlen(template)+1);

  // Create random directory
  gchar *tmpDir = g_mkdtemp(buf);

  cr_assert(tmpDir != NULL, "Unable to create temporary directory %s: %s", template, strerror(errno));

  GString *result = g_string_new(tmpDir);

  return result;
}

// Create a fully qualified path to a temporary file
GString *createTemporaryFilePath(GString *dirname, gchar *basename)
{
  GString *filePath = g_string_new(dirname->str);

  g_string_append(filePath, basename);

  return filePath;
}

// Delete temporary file generated by a test
void removeTemporaryFile(gchar *fileName, gboolean force)
{
  // Remove file
  int ret = unlink(fileName);
  if(!force && ret != 0)
    {
      cr_log_info("removeTemporaryFile %s: %s", strerror(errno), fileName);
    }
}

// Remove temporary directory generated by a test
void removeTemporaryDirectory(gchar *dirName, gboolean force)
{
  // Remove directory
  int ret = rmdir(dirName);
  if(!force && ret != 0)
    {
      cr_log_info("removeTemporaryDirectory %s: %s", strerror(errno), dirName);
    }
}

// Initialize a test
TestData *initialize(gchar *name)
{
  cr_log_info("[%s] Initialization", name);

  TestData *testData = g_new0(TestData, 1);

  testData->testName = g_string_new(name);
  testData->testDir = createTemporaryDirectory(testDirTmpl);
  testData->keyFile = createTemporaryFilePath(testData->testDir, hostKeyFile);
  testData->macFile = createTemporaryFilePath(testData->testDir, macFile);

  generateHostKey(testData->hostKey, testData->keyFile->str);

  return testData;
}

// Close a test and free resources
void closure(TestData *testData)
{
  cr_log_info("[%s] Closure", testData->testName->str);

  removeTemporaryFile(testData->keyFile->str, TRUE);
  removeTemporaryFile(testData->macFile->str, TRUE);
  removeTemporaryDirectory(testData->testDir->str, TRUE);

  g_string_free(testData->testName, TRUE);
  g_string_free(testData->testDir, TRUE);
  g_string_free(testData->keyFile, TRUE);
  g_string_free(testData->macFile, TRUE);

  g_free(testData);
}

void corruptKey(TestData *testData)
{
  GError *error = NULL;
  GIOChannel *keyfile = g_io_channel_new_file(testData->keyFile->str, "w+", &error);

  cr_assert(keyfile != NULL, "Cannot open key file: %s", testData->keyFile->str);

  GIOStatus status = g_io_channel_set_encoding(keyfile, NULL, &error);

  cr_assert(status == G_IO_STATUS_NORMAL, " Unable to set encoding for key file %s", testData->keyFile->str);

  gsize outlen = 0;

  int buflen = KEY_LENGTH + CMAC_LENGTH + sizeof(guint64);

  gchar data[buflen];

  // Overwrite the first 8 byte of the key with random values
  for(int i = 0; i < buflen; i++)
    {
      data[i] = randomNumber(1, 128);
    }

  // Overwrite the first 8 byte of the key with random values
  for(int i = 0; i < 8; i++)
    {
      testData->hostKey[i] = randomNumber(1, 128);
    }

  // Copy the corrupted key to the buffer
  memcpy(data, testData->hostKey, KEY_LENGTH);

  // Write garbage to key file
  status = g_io_channel_write_chars(keyfile, data, buflen, &outlen, &error);

  cr_assert(status == G_IO_STATUS_NORMAL, "Unable to write updated key to file %s", testData->keyFile->str);

  status = g_io_channel_shutdown(keyfile, TRUE, &error);
  g_io_channel_unref(keyfile);

  cr_assert(status == G_IO_STATUS_NORMAL, " Unable to close key file %s", testData->keyFile->str);
}


/*************************************************************************/
/* Unit test setup and teardown                                          */
/*************************************************************************/

void setup(void)
{
  srand(time(NULL));
  app_startup();
  init_parse_options_and_load_syslogformat(&test_parse_options);

  // This flag is required in order to pass the unaltered message to the slog template
  // It is required to be set after the initialization of the template tests above,
  // as this sets the parse options to the defaults
  test_parse_options.flags |= LP_STORE_RAW_MESSAGE;

  cfg_load_module(configuration, "secure-logging");
}

void teardown(void)
{
  deinit_template_tests();
  app_shutdown();
}

/*************************************************************************/
/* Test suite                                                            */
/*************************************************************************/
TestSuite(secure_logging, .init = setup, .fini = teardown);

void test_slog_template_format(void)
{
  TestData *testData = initialize("test_slog_template_format");

  GString *templ = g_string_new("");

  // $(slog -k keyfile)
  g_string_printf(templ, "$(slog -k %s)", testData->keyFile->str);
  assert_template_failure(templ->str, "[SLOG] ERROR: Template parsing failed. Invalid number of arguments");

  // $(slog -k keyfile -m)
  g_string_printf(templ, "$(slog -k %s -m)", testData->keyFile->str);
  assert_template_failure(templ->str, "Missing argument for -m");

  // $(slog -k -m macfile)
  g_string_printf(templ, "$(slog -k -m %s)", testData->macFile->str);
  assert_template_failure(templ->str, "Invalid path or non existing regular file: -m");

  // $(slog -k keyfile -m macfile)
  g_string_printf(templ, "$(slog -k %s -m %s)", testData->keyFile->str, testData->macFile->str);
  assert_template_failure(templ->str, "[SLOG] ERROR: Template parsing failed. Invalid number of arguments");

  g_string_free(templ, TRUE);

  closure(testData);
}

void test_slog_verification(void)
{
  TestData *testData = initialize("test_slog_verification");

  LogMessage *msg = create_random_sample_message();
  LogTemplate *slog_templ = createTemplate(testData);

  GString *output = applyTemplate(slog_templ, msg);
  size_t num = 1;

  verifyMessages(testData->hostKey, testData->macFile->str, &output, &msg, num);

  log_template_unref(slog_templ);

  closure(testData);
}

void test_slog_verification_bulk(void)
{
  TestData *testData = initialize("test_slog_verification_bulk");

  LogTemplate *slog_templ = createTemplate(testData);

  // Create a collection of log messages
  size_t num = randomNumber(MIN_TEST_MESSAGES, MAX_TEST_MESSAGES);
  LogMessage **logs = g_new0(LogMessage *, num);

  createLogMessages(num, logs);

  // Template output
  GString **output = g_new0(GString *, num);

  // Apply slog template to each message
  for(size_t i = 0; i < num; i++)
    {
      output[i] = applyTemplate(slog_templ, logs[i]);
    }

  // Verify the previously created log
  verifyMessages(testData->hostKey, testData->macFile->str, output, logs, num);

  // Release message resources
  for(size_t i = 0; i < num; i++)
    {
      log_msg_unref(logs[i]);
      g_string_free(output[i], TRUE);
    }

  log_template_unref(slog_templ);
  g_free(output);
  g_free(logs);

  closure(testData);
}

void test_slog_corrupted_key(void)
{
  TestData *testData = initialize("test_slog_corrupted_key");

  // Part 1: Log several messages -> They must be encrypted
  // Part 2: Corrupt the key
  // Log several messages -> They should be logged in plain text

  LogTemplate *slog_templ = createTemplate(testData);

  // Create a collection of log messages
  size_t num = randomNumber(MIN_TEST_MESSAGES, MAX_TEST_MESSAGES);

  LogMessage **logs = g_new0(LogMessage *, num);
  createLogMessages(num, logs);

  GString **output = g_new0(GString *, num);

  // Part 1: Apply slog template to each message
  for(size_t i = 0; i < num; i++)
    {
      output[i] = applyTemplate(slog_templ, logs[i]);
    }

  // Verify messages
  verifyMessages(testData->hostKey, testData->macFile->str, output, logs, num);

  // Release message resources
  for(size_t i = 0; i < num; i++)
    {
      log_msg_unref(logs[i]);
      g_string_free(output[i], TRUE);
    }

  log_template_unref(slog_templ);
  g_free(logs);
  g_free(output);

  // Part 2: Corrupt the key
  corruptKey(testData);

  // Re-initialize the template
  slog_templ = createTemplate(testData);

  // Create a collection of log messages
  num = randomNumber(MIN_TEST_MESSAGES, MAX_TEST_MESSAGES);
  logs = g_new0(LogMessage *, num);
  createLogMessages(num, logs);

  output = g_new0(GString *, num);

  // Apply slog template to each message
  for(size_t i = 0; i < num; i++)
    {
      output[i] = applyTemplate(slog_templ, logs[i]);

      // Create new message from the text content of the original message
      LogMessage *myOut = msg_format_parse(&test_parse_options, (const guchar *) output[i]->str, output[i]->len);

      // Initialize the new message with value from the original
      log_msg_set_saddr(myOut, logs[i]->saddr);
      myOut->timestamps[LM_TS_STAMP].ut_sec = logs[i]->timestamps[LM_TS_STAMP].ut_sec;
      myOut->timestamps[LM_TS_STAMP].ut_usec = logs[i]->timestamps[LM_TS_STAMP].ut_usec;
      myOut->timestamps[LM_TS_STAMP].ut_gmtoff = logs[i]->timestamps[LM_TS_STAMP].ut_gmtoff;
      myOut->pri = logs[i]->pri;
      gssize dlen;
      log_msg_set_value(myOut, LM_V_HOST, log_msg_get_value(logs[i], LM_V_HOST, &dlen), -1);
      log_msg_set_value(myOut, LM_V_PROGRAM, log_msg_get_value(logs[i], LM_V_PROGRAM, &dlen), -1);
      log_msg_set_value(myOut, LM_V_MESSAGE, log_msg_get_value(logs[i], LM_V_MESSAGE, &dlen), -1);
      log_msg_set_value(myOut, LM_V_PID, log_msg_get_value(logs[i], LM_V_PID, &dlen), -1);
      log_msg_set_value(myOut, LM_V_MSGID, log_msg_get_value(logs[i], LM_V_MSGID, &dlen), -1);
      assert_log_messages_equal(myOut, logs[i]);

      // Release message resources
      log_msg_unref(myOut);
      log_msg_unref(logs[i]);
      g_string_free(output[i], TRUE);
    }

  log_template_unref(slog_templ);
  g_free(output);
  g_free(logs);

  closure(testData);
}

void test_slog_malicious_modifications(void)
{
  TestData *testData = initialize("test_slog_malicious_modifications");

  LogTemplate *slog_templ = createTemplate(testData);

  // Create a collection of log messages
  size_t num = randomNumber(MIN_TEST_MESSAGES, MAX_TEST_MESSAGES);

  LogMessage **logs = g_new0(LogMessage *, num);

  createLogMessages(num, logs);

  // Template output
  GString **output = g_new0(GString *, num);

  // Apply slog template to each message
  for(size_t i = 0; i < num; i++)
    {
      output[i] = applyTemplate(slog_templ, logs[i]);
    }

  int mods = randomNumber(1, num-1);
  int entriesToModify[mods];

  // We might modify the same entry twice
  for (int i = 0; i < mods; i++)
    {
      entriesToModify[i] = randomNumber(0, num-1);

      // Overwrite with invalid string (invalid with high probability!)
      g_string_overwrite(output[entriesToModify[i]], randomNumber(COUNTER_LENGTH + COLON,
                                                                  (output[entriesToModify[i]]->len)-1), "999999999999999999999999999999999999999999999999999999999999999");
    }

  // Verify the previously created log
  int brokenEntries[mods];
  for (int i=0; i<mods; i++)
    {
      brokenEntries[i] = -1;
    }
  GString **ob = verifyMaliciousMessages(testData->hostKey, testData->macFile->str, output, num, brokenEntries);

  for (int i=0; i<num; i++)
    {
      if(1 == findInArray(i, entriesToModify, mods))
        {
          cr_assert(1 == findInArray(i, brokenEntries, mods), "Modified entry %d not detected.", i);
        }
      else
        {
          cr_assert(0 == findInArray(i, brokenEntries, mods), "Unmodified entry %d detected as modified.", i);
        }
    }

  // Release message resources
  for(size_t i = 0; i < num; i++)
    {
      log_msg_unref(logs[i]);
      g_string_free(output[i], TRUE);
    }

  log_template_unref(slog_templ);
  g_free(output);
  g_free(logs);
  g_free(ob);

  closure(testData);
}

void test_slog_performance(void)
{
  TestData *testData = initialize("test_slog_performance");

  LogTemplate *slog_templ = createTemplate(testData);

  GString *res = g_string_sized_new(1024);
  gint i;

  LogMessage *msg = create_random_sample_message();

  start_stopwatch();
  for (i = 0; i < PERFORMANCE_COUNTER; i++)
    {
      log_template_format(slog_templ, msg, &DEFAULT_TEMPLATE_EVAL_OPTIONS, res);
    }
  stop_stopwatch_and_display_result(PERFORMANCE_COUNTER, "%-90.*s", (int)strlen(slog_templ->template_str) - 1,
                                    slog_templ->template_str);

  // Free resources
  log_template_unref(slog_templ);
  g_string_free(res, TRUE);
  log_msg_unref(msg);

  closure(testData);
}

Test(secure_logging, test_slog_template_format)
{
  test_slog_template_format();
}

Test(secure_logging, test_slog_performance)
{
  test_slog_performance();
}

Test(secure_logging, test_slog_verification_bulk)
{
  test_slog_verification_bulk();
}

Test(secure_logging, test_slog_verification)
{
  test_slog_verification();
}

Test(secure_logging, test_slog_corrupted_key)
{
  test_slog_corrupted_key();
}

Test(secure_logging, test_slog_malicious_modifications)
{
  test_slog_malicious_modifications();
}