suricata
log-tlsstore.c
Go to the documentation of this file.
1 /* Copyright (C) 2014 Open Information Security Foundation
2  *
3  * You can copy, redistribute or modify this Program under the terms of
4  * the GNU General Public License version 2 as published by the Free
5  * Software Foundation.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * version 2 along with this program; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
15  * 02110-1301, USA.
16  */
17 
18 /**
19  * \file
20  *
21  * \author Roliers Jean-Paul <popof.fpn@gmail.co>
22  * \author Eric Leblond <eric@regit.org>
23  * \author Victor Julien <victor@inliniac.net>
24  *
25  * Implements TLS store portion of the engine.
26  *
27  */
28 
29 #include "suricata-common.h"
30 #include "log-tlsstore.h"
31 
32 #include "decode.h"
33 
34 #include "app-layer-parser.h"
35 #include "app-layer-ssl.h"
36 
37 #include "output.h"
38 #include "log-tlslog.h"
39 
40 #include "util-conf.h"
41 #include "util-path.h"
42 #include "util-time.h"
43 
44 #define MODULE_NAME "LogTlsStoreLog"
45 
46 static char tls_logfile_base_dir[PATH_MAX] = "/tmp";
47 SC_ATOMIC_DECLARE(unsigned int, cert_id);
48 static char logging_dir_not_writable;
49 
50 #define LOGGING_WRITE_ISSUE_LIMIT 6
51 
52 typedef struct LogTlsStoreLogThread_ {
53  uint8_t* enc_buf;
54  size_t enc_buf_len;
56 
57 static int CreateFileName(
58  const Packet *p, SSLState *state, char *filename, size_t filename_size, const bool client)
59 {
60  char path[PATH_MAX];
61  int file_id = SC_ATOMIC_ADD(cert_id, 1);
62 
63  const char *dir = client ? "client-" : "";
64 
65  /* Use format : packet time + incremental ID
66  * When running on same pcap it will overwrite
67  * On a live device, we will not be able to overwrite */
68  if (snprintf(path, sizeof(path), "%s/%s%ld.%ld-%d.pem", tls_logfile_base_dir, dir,
69  (long int)SCTIME_SECS(p->ts), (long int)SCTIME_USECS(p->ts),
70  file_id) == sizeof(path))
71  return 0;
72 
73  strlcpy(filename, path, filename_size);
74  return 1;
75 }
76 
77 static void LogTlsLogPem(LogTlsStoreLogThread *aft, const Packet *p, SSLState *state,
78  SSLStateConnp *connp, int ipproto)
79 {
80 #define PEMHEADER "-----BEGIN CERTIFICATE-----\n"
81 #define PEMFOOTER "-----END CERTIFICATE-----\n"
82  //Logging pem certificate
83  char filename[PATH_MAX] = "";
84  FILE* fp = NULL;
85  FILE* fpmeta = NULL;
86  unsigned long pemlen;
87  unsigned char* pembase64ptr = NULL;
88  int ret;
89  uint8_t *ptmp;
90  SSLCertsChain *cert;
91 
92  if (TAILQ_EMPTY(&connp->certs)) {
93  SCReturn;
94  }
95 
96  const bool client = connp == &state->client_connp;
97  CreateFileName(p, state, filename, sizeof(filename), client);
98  if (strlen(filename) == 0) {
99  SCLogWarning("Can't create PEM filename");
100  SCReturn;
101  }
102 
103  fp = fopen(filename, "w");
104  if (fp == NULL) {
105  if (logging_dir_not_writable < LOGGING_WRITE_ISSUE_LIMIT) {
106  SCLogWarning(
107  "Can't create PEM file '%s' in '%s' directory", filename, tls_logfile_base_dir);
108  logging_dir_not_writable++;
109  }
110  SCReturn;
111  }
112 
113  TAILQ_FOREACH (cert, &connp->certs, next) {
114  pemlen = Base64EncodeBufferSize(cert->cert_len);
115  if (pemlen > aft->enc_buf_len) {
116  ptmp = (uint8_t*) SCRealloc(aft->enc_buf, sizeof(uint8_t) * pemlen);
117  if (ptmp == NULL) {
118  SCFree(aft->enc_buf);
119  aft->enc_buf = NULL;
120  aft->enc_buf_len = 0;
121  SCLogWarning("Can't allocate data for base64 encoding");
122  goto end_fp;
123  }
124  aft->enc_buf = ptmp;
125  aft->enc_buf_len = pemlen;
126  }
127 
128  memset(aft->enc_buf, 0, aft->enc_buf_len);
129 
130  ret = Base64Encode((unsigned char*) cert->cert_data, cert->cert_len, aft->enc_buf, &pemlen);
131  if (ret != SC_BASE64_OK) {
132  SCLogWarning("Invalid return of Base64Encode function");
133  goto end_fwrite_fp;
134  }
135 
136  if (fprintf(fp, PEMHEADER) < 0)
137  goto end_fwrite_fp;
138 
139  pembase64ptr = aft->enc_buf;
140  while (pemlen > 0) {
141  size_t loffset = pemlen >= 64 ? 64 : pemlen;
142  if (fwrite(pembase64ptr, 1, loffset, fp) != loffset)
143  goto end_fwrite_fp;
144  if (fwrite("\n", 1, 1, fp) != 1)
145  goto end_fwrite_fp;
146  pembase64ptr += 64;
147  if (pemlen < 64)
148  break;
149  pemlen -= 64;
150  }
151 
152  if (fprintf(fp, PEMFOOTER) < 0)
153  goto end_fwrite_fp;
154  }
155  fclose(fp);
156 
157  //Logging certificate informations
158  memcpy(filename + (strlen(filename) - 3), "meta", 4);
159  fpmeta = fopen(filename, "w");
160  if (fpmeta != NULL) {
161  #define PRINT_BUF_LEN 46
162  char srcip[PRINT_BUF_LEN], dstip[PRINT_BUF_LEN];
163  char timebuf[64];
164  Port sp, dp;
165  CreateTimeString(p->ts, timebuf, sizeof(timebuf));
166  if (!TLSGetIPInformations(p, srcip, PRINT_BUF_LEN, &sp, dstip, PRINT_BUF_LEN, &dp, ipproto))
167  goto end_fwrite_fpmeta;
168  if (fprintf(fpmeta, "TIME: %s\n", timebuf) < 0)
169  goto end_fwrite_fpmeta;
170  if (p->pcap_cnt > 0) {
171  if (fprintf(fpmeta, "PCAP PKT NUM: %"PRIu64"\n", p->pcap_cnt) < 0)
172  goto end_fwrite_fpmeta;
173  }
174  if (fprintf(fpmeta, "SRC IP: %s\n", srcip) < 0)
175  goto end_fwrite_fpmeta;
176  if (fprintf(fpmeta, "DST IP: %s\n", dstip) < 0)
177  goto end_fwrite_fpmeta;
178  if (fprintf(fpmeta, "PROTO: %" PRIu32 "\n", p->proto) < 0)
179  goto end_fwrite_fpmeta;
180  if (PacketIsTCP(p) || PacketIsUDP(p)) {
181  if (fprintf(fpmeta, "SRC PORT: %" PRIu16 "\n", sp) < 0)
182  goto end_fwrite_fpmeta;
183  if (fprintf(fpmeta, "DST PORT: %" PRIu16 "\n", dp) < 0)
184  goto end_fwrite_fpmeta;
185  }
186 
187  if (fprintf(fpmeta,
188  "TLS SUBJECT: %s\n"
189  "TLS ISSUERDN: %s\n"
190  "TLS FINGERPRINT: %s\n",
191  connp->cert0_subject, connp->cert0_issuerdn, connp->cert0_fingerprint) < 0)
192  goto end_fwrite_fpmeta;
193 
194  fclose(fpmeta);
195  } else {
196  if (logging_dir_not_writable < LOGGING_WRITE_ISSUE_LIMIT) {
197  SCLogWarning("Can't create meta file '%s' in '%s' directory", filename,
198  tls_logfile_base_dir);
199  logging_dir_not_writable++;
200  }
201  SCReturn;
202  }
203 
204  /* Reset the store flag */
205  connp->cert_log_flag &= ~SSL_TLS_LOG_PEM;
206  SCReturn;
207 
208 end_fwrite_fp:
209  fclose(fp);
210  if (logging_dir_not_writable < LOGGING_WRITE_ISSUE_LIMIT) {
211  SCLogWarning("Unable to write certificate");
212  logging_dir_not_writable++;
213  }
214 end_fwrite_fpmeta:
215  if (fpmeta) {
216  fclose(fpmeta);
217  if (logging_dir_not_writable < LOGGING_WRITE_ISSUE_LIMIT) {
218  SCLogWarning("Unable to write certificate metafile");
219  logging_dir_not_writable++;
220  }
221  }
222  SCReturn;
223 end_fp:
224  fclose(fp);
225  SCReturn;
226 }
227 
228 /** \internal
229  * \brief Condition function for TLS logger
230  * \retval bool true or false -- log now?
231  */
232 static bool LogTlsStoreCondition(
233  ThreadVars *tv, const Packet *p, void *state, void *tx, uint64_t tx_id)
234 {
235  if (p->flow == NULL) {
236  return false;
237  }
238 
239  if (!(PacketIsTCP(p))) {
240  return false;
241  }
242 
243  SSLState *ssl_state = (SSLState *)state;
244  if (ssl_state == NULL) {
245  SCLogDebug("no tls state, so no request logging");
246  goto dontlog;
247  }
248 
249  if ((ssl_state->server_connp.cert_log_flag & SSL_TLS_LOG_PEM) == 0) {
250  goto dontlog;
251  }
252 
253  if (ssl_state->server_connp.cert0_issuerdn == NULL ||
254  ssl_state->server_connp.cert0_subject == NULL) {
255  goto dontlog;
256  }
257 
258  return true;
259 dontlog:
260  return false;
261 }
262 
263 static bool LogTlsStoreConditionClient(
264  ThreadVars *tv, const Packet *p, void *state, void *tx, uint64_t tx_id)
265 {
266  if (p->flow == NULL) {
267  return false;
268  }
269 
270  if (!(PacketIsTCP(p))) {
271  return false;
272  }
273 
274  SSLState *ssl_state = (SSLState *)state;
275  if (ssl_state == NULL) {
276  SCLogDebug("no tls state, so no request logging");
277  goto dontlog;
278  }
279 
280  if ((ssl_state->client_connp.cert_log_flag & SSL_TLS_LOG_PEM) == 0) {
281  goto dontlog;
282  }
283 
284  if ((ssl_state->client_connp.cert0_issuerdn == NULL ||
285  ssl_state->client_connp.cert0_subject == NULL)) {
286  goto dontlog;
287  }
288 
289  return true;
290 dontlog:
291  return false;
292 }
293 
294 static int LogTlsStoreLoggerClient(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f,
295  void *state, void *tx, uint64_t tx_id)
296 {
297  LogTlsStoreLogThread *aft = (LogTlsStoreLogThread *)thread_data;
298  int ipproto = (PacketIsIPv4(p)) ? AF_INET : AF_INET6;
299 
300  SSLState *ssl_state = (SSLState *)state;
301  if (unlikely(ssl_state == NULL)) {
302  return 0;
303  }
304  /* client cert */
305  SSLStateConnp *connp = &ssl_state->client_connp;
306  if (connp->cert_log_flag & SSL_TLS_LOG_PEM) {
307  LogTlsLogPem(aft, p, ssl_state, connp, ipproto);
308  }
309 
310  return 0;
311 }
312 
313 static int LogTlsStoreLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f,
314  void *state, void *tx, uint64_t tx_id)
315 {
316  LogTlsStoreLogThread *aft = (LogTlsStoreLogThread *)thread_data;
317  int ipproto = (PacketIsIPv4(p)) ? AF_INET : AF_INET6;
318 
319  SSLState *ssl_state = (SSLState *)state;
320  if (unlikely(ssl_state == NULL)) {
321  return 0;
322  }
323  /* server cert */
324  SSLStateConnp *connp = &ssl_state->server_connp;
325  if (connp->cert_log_flag & SSL_TLS_LOG_PEM) {
326  LogTlsLogPem(aft, p, ssl_state, connp, ipproto);
327  }
328 
329  return 0;
330 }
331 
332 static TmEcode LogTlsStoreLogThreadInit(ThreadVars *t, const void *initdata, void **data)
333 {
335  if (unlikely(aft == NULL))
336  return TM_ECODE_FAILED;
337 
338  if (initdata == NULL) {
339  SCLogDebug("Error getting context for LogTLSStore. \"initdata\" argument NULL");
340  SCFree(aft);
341  return TM_ECODE_FAILED;
342  }
343 
344  struct stat stat_buf;
345  /* coverity[toctou] */
346  if (stat(tls_logfile_base_dir, &stat_buf) != 0) {
347  int ret;
348  /* coverity[toctou] */
349  ret = SCMkDir(tls_logfile_base_dir, S_IRWXU|S_IXGRP|S_IRGRP);
350  if (ret != 0) {
351  int err = errno;
352  if (err != EEXIST) {
353  SCLogError("Cannot create certs drop directory %s: %s", tls_logfile_base_dir,
354  strerror(err));
355  exit(EXIT_FAILURE);
356  }
357  } else {
358  SCLogInfo("Created certs drop directory %s",
359  tls_logfile_base_dir);
360  }
361 
362  }
363 
364  *data = (void *)aft;
365  return TM_ECODE_OK;
366 }
367 
368 static TmEcode LogTlsStoreLogThreadDeinit(ThreadVars *t, void *data)
369 {
371  if (aft == NULL) {
372  return TM_ECODE_OK;
373  }
374 
375  if (aft->enc_buf != NULL)
376  SCFree(aft->enc_buf);
377 
378  /* clear memory */
379  memset(aft, 0, sizeof(LogTlsStoreLogThread));
380 
381  SCFree(aft);
382  return TM_ECODE_OK;
383 }
384 
385 /**
386  * \internal
387  *
388  * \brief deinit the log ctx and write out the waldo
389  *
390  * \param output_ctx output context to deinit
391  */
392 static void LogTlsStoreLogDeInitCtx(OutputCtx *output_ctx)
393 {
394  SCFree(output_ctx);
395 }
396 
397 /** \brief Create a new http log LogFilestoreCtx.
398  * \param conf Pointer to ConfNode containing this loggers configuration.
399  * \return NULL if failure, LogFilestoreCtx* to the file_ctx if succesful
400  * */
401 static OutputInitResult LogTlsStoreLogInitCtx(ConfNode *conf)
402 {
403  OutputInitResult result = { NULL, false };
404  OutputCtx *output_ctx = SCCalloc(1, sizeof(OutputCtx));
405  if (unlikely(output_ctx == NULL))
406  return result;
407 
408  output_ctx->data = NULL;
409  output_ctx->DeInit = LogTlsStoreLogDeInitCtx;
410 
411  const char *s_default_log_dir = ConfigGetLogDirectory();
412  const char *s_base_dir = ConfNodeLookupChildValue(conf, "certs-log-dir");
413  if (s_base_dir == NULL || strlen(s_base_dir) == 0) {
414  strlcpy(tls_logfile_base_dir,
415  s_default_log_dir, sizeof(tls_logfile_base_dir));
416  } else {
417  if (PathIsAbsolute(s_base_dir)) {
418  strlcpy(tls_logfile_base_dir,
419  s_base_dir, sizeof(tls_logfile_base_dir));
420  } else {
421  snprintf(tls_logfile_base_dir, sizeof(tls_logfile_base_dir),
422  "%s/%s", s_default_log_dir, s_base_dir);
423  }
424  }
425 
426  SCLogInfo("storing certs in %s", tls_logfile_base_dir);
427 
428  /* enable the logger for the app layer */
430 
431  result.ctx = output_ctx;
432  result.ok = true;
433  SCReturnCT(result, "OutputInitResult");
434 }
435 
437 {
439  LogTlsStoreLogInitCtx, ALPROTO_TLS, LogTlsStoreLogger, LogTlsStoreCondition,
440  LogTlsStoreLogThreadInit, LogTlsStoreLogThreadDeinit);
441 
443  LogTlsStoreLogInitCtx, ALPROTO_TLS, LogTlsStoreLoggerClient, LogTlsStoreConditionClient,
444  LogTlsStoreLogThreadInit, LogTlsStoreLogThreadDeinit);
445 
446  SC_ATOMIC_INIT(cert_id);
447  SC_ATOMIC_SET(cert_id, 1);
448 
449  SCLogDebug("registered");
450 }
LogTlsStoreRegister
void LogTlsStoreRegister(void)
Definition: log-tlsstore.c:436
SSLStateConnp_::cert0_subject
char * cert0_subject
Definition: app-layer-ssl.h:255
Packet_::proto
uint8_t proto
Definition: decode.h:498
SSLState_
SSLv[2.0|3.[0|1|2|3]] state structure.
Definition: app-layer-ssl.h:296
SSLCertsChain_::cert_len
uint32_t cert_len
Definition: app-layer-ssl.h:225
SC_ATOMIC_INIT
#define SC_ATOMIC_INIT(name)
wrapper for initializing an atomic variable.
Definition: util-atomic.h:314
unlikely
#define unlikely(expr)
Definition: util-optimize.h:35
SC_ATOMIC_SET
#define SC_ATOMIC_SET(name, val)
Set the value for the atomic variable.
Definition: util-atomic.h:386
SSLState_::client_connp
SSLStateConnp client_connp
Definition: app-layer-ssl.h:314
ALPROTO_TLS
@ ALPROTO_TLS
Definition: app-layer-protos.h:33
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:269
Packet_::pcap_cnt
uint64_t pcap_cnt
Definition: decode.h:595
next
struct HtpBodyChunk_ * next
Definition: app-layer-htp.h:0
SSLState_::server_connp
SSLStateConnp server_connp
Definition: app-layer-ssl.h:315
SSLStateConnp_
Definition: app-layer-ssl.h:235
Flow_
Flow data structure.
Definition: flow.h:356
SC_ATOMIC_ADD
#define SC_ATOMIC_ADD(name, val)
add a value to our atomic variable
Definition: util-atomic.h:332
TAILQ_EMPTY
#define TAILQ_EMPTY(head)
Definition: queue.h:248
TAILQ_FOREACH
#define TAILQ_FOREACH(var, head, field)
Definition: queue.h:252
TM_ECODE_FAILED
@ TM_ECODE_FAILED
Definition: tm-threads-common.h:81
LogTlsStoreLogThread_
Definition: log-tlsstore.c:52
SSLStateConnp_::cert0_issuerdn
char * cert0_issuerdn
Definition: app-layer-ssl.h:256
OutputCtx_::data
void * data
Definition: tm-modules.h:87
TM_ECODE_OK
@ TM_ECODE_OK
Definition: tm-threads-common.h:80
OutputCtx_
Definition: tm-modules.h:84
strlcpy
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: util-strlcpyu.c:43
OutputRegisterTxModuleWithCondition
void OutputRegisterTxModuleWithCondition(LoggerId id, const char *name, const char *conf_name, OutputInitFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, TxLoggerCondition TxLogCondition, ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit)
Register a tx output module with condition.
Definition: output.c:320
decode.h
OutputInitResult_::ctx
OutputCtx * ctx
Definition: output.h:47
Packet_::ts
SCTime_t ts
Definition: decode.h:524
AppLayerParserRegisterLogger
void AppLayerParserRegisterLogger(uint8_t ipproto, AppProto alproto)
Definition: app-layer-parser.c:457
SSLCertsChain_
Definition: app-layer-ssl.h:223
ThreadVars_
Per thread variable structure.
Definition: threadvars.h:58
LogTlsStoreLogThread
struct LogTlsStoreLogThread_ LogTlsStoreLogThread
util-time.h
OutputInitResult_::ok
bool ok
Definition: output.h:48
log-tlslog.h
SCLogWarning
#define SCLogWarning(...)
Macro used to log WARNING messages.
Definition: util-debug.h:249
app-layer-parser.h
LogTlsStoreLogThread_::enc_buf_len
size_t enc_buf_len
Definition: log-tlsstore.c:54
SCReturn
#define SCReturn
Definition: util-debug.h:273
Packet_
Definition: decode.h:476
Port
uint16_t Port
Definition: decode.h:214
TmEcode
TmEcode
Definition: tm-threads-common.h:79
SSLCertsChain_::cert_data
uint8_t * cert_data
Definition: app-layer-ssl.h:224
SCLogInfo
#define SCLogInfo(...)
Macro used to log INFORMATIONAL messages.
Definition: util-debug.h:224
TLSGetIPInformations
int TLSGetIPInformations(const Packet *p, char *srcip, socklen_t srcip_len, Port *sp, char *dstip, socklen_t dstip_len, Port *dp, int ipproto)
Definition: log-tlslog.c:81
SCRealloc
#define SCRealloc(ptr, sz)
Definition: util-mem.h:50
OutputInitResult_
Definition: output.h:46
util-conf.h
Packet_::flow
struct Flow_ * flow
Definition: decode.h:515
suricata-common.h
OutputCtx_::DeInit
void(* DeInit)(struct OutputCtx_ *)
Definition: tm-modules.h:90
PEMFOOTER
#define PEMFOOTER
util-path.h
SCTIME_SECS
#define SCTIME_SECS(t)
Definition: util-time.h:57
PathIsAbsolute
int PathIsAbsolute(const char *path)
Check if a path is absolute.
Definition: util-path.c:44
PRINT_BUF_LEN
#define PRINT_BUF_LEN
SCMkDir
#define SCMkDir(a, b)
Definition: util-path.h:45
MODULE_NAME
#define MODULE_NAME
Definition: log-tlsstore.c:44
tv
ThreadVars * tv
Definition: fuzz_decodepcapfile.c:32
SSL_TLS_LOG_PEM
#define SSL_TLS_LOG_PEM
Definition: app-layer-ssl.h:138
ConfigGetLogDirectory
const char * ConfigGetLogDirectory(void)
Definition: util-conf.c:38
SCLogError
#define SCLogError(...)
Macro used to log ERROR messages.
Definition: util-debug.h:261
SCFree
#define SCFree(p)
Definition: util-mem.h:61
ConfNode_
Definition: conf.h:32
SSLStateConnp_::cert_log_flag
uint32_t cert_log_flag
Definition: app-layer-ssl.h:275
LOGGER_TLS_STORE_CLIENT
@ LOGGER_TLS_STORE_CLIENT
Definition: suricata-common.h:466
SCReturnCT
#define SCReturnCT(x, type)
Definition: util-debug.h:285
LOGGING_WRITE_ISSUE_LIMIT
#define LOGGING_WRITE_ISSUE_LIMIT
Definition: log-tlsstore.c:50
LogTlsStoreLogThread_::enc_buf
uint8_t * enc_buf
Definition: log-tlsstore.c:53
LOGGER_TLS_STORE
@ LOGGER_TLS_STORE
Definition: suricata-common.h:465
SSLStateConnp_::cert0_fingerprint
char * cert0_fingerprint
Definition: app-layer-ssl.h:260
SC_ATOMIC_DECLARE
SC_ATOMIC_DECLARE(unsigned int, cert_id)
log-tlsstore.h
SCCalloc
#define SCCalloc(nm, sz)
Definition: util-mem.h:53
app-layer-ssl.h
PEMHEADER
#define PEMHEADER
CreateTimeString
void CreateTimeString(const SCTime_t ts, char *str, size_t size)
Definition: util-time.c:272
output.h
SCTIME_USECS
#define SCTIME_USECS(t)
Definition: util-time.h:56
ConfNodeLookupChildValue
const char * ConfNodeLookupChildValue(const ConfNode *node, const char *name)
Lookup the value of a child configuration node by name.
Definition: conf.c:809