File: 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 (291 lines) | stat: -rw-r--r-- 8,294 bytes parent folder | download | duplicates (3)
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
/*
 * 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 "plugin.h"
#include "template/simple-function.h"
#include "cfg.h"
#include "uuid.h"
#include "str-format.h"
#include "plugin-types.h"
#include "compat/openssl_support.h"
#include <openssl/evp.h>

#include <glib.h>

#include <openssl/rand.h>
#include <sys/mman.h>

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

/*
 * $(slog [opts] $RAWMSG)
 *
 * Maintains the state of the secure logging template
 *
 * Returns the current encryption key and MAC for the next
 * round and maintains the counter for the total number of
 * of log entries processed.
 *
 * Note: The flag store-raw-message has to be enabled in the
 *       source configuration in order to use the $RAWMSG macro.
 *
 * Options:
 *      -k        Full path to encryption key file
 *      -m        Full path to MAC file
 */
typedef struct _TFSlogState
{
  TFSimpleFuncState super;

  gchar *keypath;
  gchar *macpath;
  guint64 numberOfLogEntries;

  gboolean badKey;
  guchar key[KEY_LENGTH];
  guchar bigMAC[CMAC_LENGTH];
} TFSlogState;

/*
 * Initialize the secure logging template
 */
static gboolean
tf_slog_prepare(LogTemplateFunction *self, gpointer s, LogTemplate *parent, gint argc, gchar *argv[], GError **error)
{
  // Get key filename and store in internal state
  // generate initial BigMAC file
  TFSlogState *state = (TFSlogState *) s;

  gchar *keypathbuffer = NULL;
  gchar *macpathbuffer = NULL;
  GOptionContext *ctx;
  GOptionGroup *grp;

  if ((mlock(state->key, KEY_LENGTH)!=0)||(mlock(state->bigMAC, CMAC_LENGTH)!=0))
    {
      msg_warning("[SLOG] WARNING: Unable to acquire memory lock");
    }

  state->badKey = FALSE;

  SLogOptions options[] =
  {
    { "key-file", 'k', "Name of the host key file", "FILE", NULL },
    { "mac-file", 'm', "Name of the MAC file", "FILE", NULL },
    { NULL }
  };

  GOptionEntry slog_options[] =
  {
    { options[0].longname, options[0].shortname, 0, G_OPTION_ARG_CALLBACK, &validFileNameArg, options[0].description, options[0].type },
    { options[1].longname, options[1].shortname, 0, G_OPTION_ARG_FILENAME, &macpathbuffer, options[1].description, options[1].type },
    { NULL }
  };

  ctx = g_option_context_new("- Secure logging template");
  grp = g_option_group_new("Basic options", "Basic template options", "basic", &options, NULL);

  g_option_group_add_entries(grp, slog_options);
  g_option_context_set_main_group(ctx, grp);

  GError *argError = NULL;

  if (!g_option_context_parse(ctx, &argc, &argv, &argError))
    {
      if (argError != NULL)
        {
          g_propagate_error (error, argError);
        }

      g_option_context_free(ctx);
      return FALSE;
    }

  if (argc < 2)
    {
      state->badKey = TRUE;
      g_set_error(error, LOG_TEMPLATE_ERROR, LOG_TEMPLATE_ERROR_COMPILE,
                  "[SLOG] ERROR: Template parsing failed. Invalid number of arguments. Usage: $(slog --key-file FILE --mac-file FILE $RAWMSG)\\n");
      g_option_context_free(ctx);
      return FALSE;
    }

  keypathbuffer = options[0].arg;

  if(keypathbuffer == NULL)
    {
      state->badKey = TRUE;

      g_set_error(error, LOG_TEMPLATE_ERROR, LOG_TEMPLATE_ERROR_COMPILE,
                  "[SLOG] ERROR: Template parsing failed. Invalid or missing key file");
      g_option_context_free(ctx);
      return FALSE;
    }

  if(macpathbuffer == NULL)
    {
      state->badKey = TRUE;

      g_set_error(error, LOG_TEMPLATE_ERROR, LOG_TEMPLATE_ERROR_COMPILE,
                  "[SLOG] ERROR: Template parsing failed. Invalid or missing MAC file");
      g_option_context_free(ctx);
      return FALSE;
    }

  if (!tf_simple_func_prepare(self, state, parent, argc, argv, error))
    {
      state->badKey = TRUE;
      g_option_context_free(ctx);
      return FALSE;
    }

  state->numberOfLogEntries = 0;
  state->keypath = keypathbuffer;
  state->macpath = macpathbuffer;

  // Done with argument parsing
  g_option_context_free(ctx);

  int res = readKey((char *)state->key, (guint64 *)&(state->numberOfLogEntries), state->keypath);

  if (res == 0)
    {
      state->badKey = TRUE;
      msg_warning("[SLOG] WARNING: Template parsing failed, key file not found or invalid. Reverting to clear text logging.");
      return TRUE;
    }

  msg_debug("[SLOG] INFO: Key successfully loaded");

  res = readBigMAC(state->macpath, (char *)state->bigMAC);

  if (res == 0 && state->numberOfLogEntries > 0)
    {
      msg_warning("[SLOG] ERROR: Aggregated MAC not found or invalid", evt_tag_str("File", state->macpath));
    }
  else
    {
      msg_debug("[SLOG] INFO: Template with key and MAC file successfully initialized.");
    }

  return TRUE;
}

/*
 * Create a new encrypted log entry
 */
static void
tf_slog_call(LogTemplateFunction *self, gpointer s, const LogTemplateInvokeArgs *args, GString *result,
             LogMessageValueType *type)
{

  TFSlogState *state = (TFSlogState *) s;

  *type = LM_VT_STRING;
  // If we do not have a good key, just forward input
  if (state->badKey == TRUE)
    {
      g_string_append (result, args->argv[0]->str);
      return;
    }

  // Compute authenticated encryption of input
  guchar outputmacdata[CMAC_LENGTH];

  // Empty string received? Parsing error?
  if(args->argv[0]->len==0)
    {
      msg_error("[SLOG] ERROR: String of length 0 received");
      GString *errorString = g_string_new("[SLOG] ERROR: String of length 0 received");
      sLogEntry(state->numberOfLogEntries, errorString, state->key, state->bigMAC, result, outputmacdata,
                G_N_ELEMENTS(outputmacdata));
      g_string_free(errorString, TRUE);
    }
  else
    {
      sLogEntry(state->numberOfLogEntries, args->argv[0], state->key, state->bigMAC, result, outputmacdata,
                G_N_ELEMENTS(outputmacdata));
    }

  memcpy(state->bigMAC, outputmacdata, CMAC_LENGTH);
  evolveKey(state->key);
  state->numberOfLogEntries++;

  int res = writeKey((char *)state->key, state->numberOfLogEntries, state->keypath);

  if (res == 0)
    {
      msg_error("[SLOG] ERROR: Cannot write key to file");
      return;
    }

  res = writeBigMAC(state->macpath, (char *)state->bigMAC);

  if (res == 0)
    {
      msg_error("[SLOG] ERROR: Unable to write aggregated MAC", evt_tag_str("File", state->macpath));
      return;
    }
}

// Secure logging free state function
void
tf_slog_func_free_state(gpointer s)
{
  TFSlogState *state = (TFSlogState *) s;

  free(state->keypath);
  free(state->macpath);

  tf_simple_func_free_state((gpointer)&state->super);
}


/*
 * Declare the template function for secure logging
 */
TEMPLATE_FUNCTION(TFSlogState, tf_slog, tf_slog_prepare, tf_simple_func_eval, tf_slog_call, tf_slog_func_free_state,
                  NULL);

static Plugin secure_logging_plugins[] =
{
  TEMPLATE_FUNCTION_PLUGIN(tf_slog, "slog"),
};

gboolean
secure_logging_module_init(PluginContext *context, CfgArgs *args)
{
  plugin_register(context, secure_logging_plugins, G_N_ELEMENTS(secure_logging_plugins));
  return TRUE;
}

const ModuleInfo module_info =
{
  .canonical_name = "secure_logging",
  .version = SYSLOG_NG_VERSION,
  .description = "The secure logging module provides template functions enabling forward integrity and confidentiality of logs.",
  .core_revision = SYSLOG_NG_SOURCE_REVISION,
  .plugins = secure_logging_plugins,
  .plugins_len = G_N_ELEMENTS(secure_logging_plugins),
};