1 /* $Id */
2
3 /*
4 ** Copyright (C) 2014-2021 Cisco and/or its affiliates. All rights reserved.
5 ** Copyright (C) 2011-2013 Sourcefire, Inc.
6 **
7 **
8 ** This program is free software; you can redistribute it and/or modify
9 ** it under the terms of the GNU General Public License Version 2 as
10 ** published by the Free Software Foundation. You may not use, modify or
11 ** distribute this program under any other version of the GNU General
12 ** Public License.
13 **
14 ** This program is distributed in the hope that it will be useful,
15 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ** GNU General Public License for more details.
18 **
19 ** You should have received a copy of the GNU General Public License
20 ** along with this program; if not, write to the Free Software
21 ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 */
23
24
25 /*
26 * SIP preprocessor
27 *
28 * This is the main entry point for this preprocessor
29 *
30 * Author: Hui Cao
31 * Date: 03-15-2011
32 */
33
34 #ifdef HAVE_CONFIG_H
35 #include "config.h"
36 #endif /* HAVE_CONFIG_H */
37
38 #include "sf_types.h"
39 #include "sf_snort_packet.h"
40 #include "sf_dynamic_preprocessor.h"
41 #include "sf_snort_plugin_api.h"
42 #include "snort_debug.h"
43
44 #include "preprocids.h"
45 #include "spp_sip.h"
46 #include "sip_config.h"
47 #include "sip_roptions.h"
48 #include "sip_parser.h"
49 #include "sip_dialog.h"
50 #include "sip_paf.h"
51
52 #include <assert.h>
53 #include <stdio.h>
54 #include <syslog.h>
55 #include <string.h>
56 #include <time.h>
57 #ifndef WIN32
58 #include <strings.h>
59 #include <sys/time.h>
60 #endif
61 #include <stdlib.h>
62 #include <ctype.h>
63
64 #ifdef REG_TEST
65 #include "reg_test.h"
66 #endif
67
68 #include "profiler.h"
69 #ifdef PERF_PROFILING
70 PreprocStats sipPerfStats;
71 #endif
72
73 #include "sf_types.h"
74
75 #ifdef DUMP_BUFFER
76 #include "sip_buffer_dump.h"
77 #endif
78
79 #ifdef SNORT_RELOAD
80 #include "appdata_adjuster.h"
81 #endif
82
83 const int MAJOR_VERSION = 1;
84 const int MINOR_VERSION = 1;
85 const int BUILD_VERSION = 1;
86
87 const char *PREPROC_NAME = "SF_SIP";
88
89 #define SetupSIP DYNAMIC_PREPROC_SETUP
90
91 #ifdef TARGET_BASED
92 int16_t sip_app_id = SFTARGET_UNKNOWN_PROTOCOL;
93 #endif
94
95 /*
96 * Session state flags for SIPData::state_flags
97 */
98
99 #define SIP_FLG_MISSED_PACKETS (0x10000)
100
101 /*
102 * Function prototype(s)
103 */
104 SIPData * SIPGetNewSession(SFSnortPacket *, tSfPolicyId);
105 static void SIPInit( struct _SnortConfig *, char* );
106 static bool SIPGlobalIsEnabled(struct _SnortConfig *sc, tSfPolicyUserContextId sip_config);
107 static int SIPPolicyIsEnabled(struct _SnortConfig *sc, tSfPolicyUserContextId pContext, tSfPolicyId policyId, void* config);
108 static int SIPCheckConfig(struct _SnortConfig *);
109 static void FreeSIPData( void* );
110 static inline int SIP_Process(SFSnortPacket *, SIPData*);
111 static void SIPmain( void*, void* );
112 static inline int CheckSIPPort( uint16_t );
113 static void SIPFreeConfig(tSfPolicyUserContextId);
114 static void registerPortsForDispatch( struct _SnortConfig *sc, SIPConfig *policy );
115 static void registerPortsForReassembly( SIPConfig *policy, int direction );
116 static void _addPortsToStreamFilter(struct _SnortConfig *, SIPConfig *, tSfPolicyId);
117 static void SIP_PrintStats(int);
118 static void DisplaySIPStats (uint16_t type, void *old_context, struct _THREAD_ELEMENT *te, ControlDataSendFunc f);
119 #ifdef TARGET_BASED
120 static void _addServicesToStreamFilter(struct _SnortConfig *, tSfPolicyId);
121 #endif
122
123 static void SIPCleanExit(int, void *);
124
125 /********************************************************************
126 * Global variables
127 ********************************************************************/
128 uint32_t numSessions = 0;
129 SIP_Stats sip_stats;
130 SIPConfig *sip_eval_config;
131 tSfPolicyUserContextId sip_config;
132
133 #ifdef SNORT_RELOAD
134 static APPDATA_ADJUSTER *ada;
135 #endif
136
SIP_NumSessions()137 static size_t SIP_NumSessions()
138 {
139 return (size_t) numSessions;
140 }
141
142 #ifdef SNORT_RELOAD
143 static void SIPReload(struct _SnortConfig *, char *, void **);
144 static int SIPReloadVerify(struct _SnortConfig *, void *);
145 static void * SIPReloadSwap(struct _SnortConfig *, void *);
146 static void SIPReloadSwapFree(void *);
147 #endif
148
149 static SIPMsg sipMsg;
150
SIPPrintMemStats(FILE * fd,char * buffer,PreprocMemInfo * meminfo)151 int SIPPrintMemStats(FILE *fd, char *buffer, PreprocMemInfo *meminfo)
152 {
153 int len = 0;
154 time_t curr_time;
155
156 if (fd)
157 {
158 len = fprintf(fd, ",%lu,%u"
159 ",%lu,%u,%u"
160 ",%lu,%u,%u,%lu"
161 , sip_stats.sessions
162 , numSessions
163 , meminfo[PP_MEM_CATEGORY_SESSION].used_memory
164 , meminfo[PP_MEM_CATEGORY_SESSION].num_of_alloc
165 , meminfo[PP_MEM_CATEGORY_SESSION].num_of_free
166 , meminfo[PP_MEM_CATEGORY_CONFIG].used_memory
167 , meminfo[PP_MEM_CATEGORY_CONFIG].num_of_alloc
168 , meminfo[PP_MEM_CATEGORY_CONFIG].num_of_free
169 , meminfo[PP_MEM_CATEGORY_SESSION].used_memory +
170 meminfo[PP_MEM_CATEGORY_CONFIG].used_memory);
171
172 return len;
173 }
174
175 curr_time = time(NULL);
176
177 if (buffer)
178 {
179 len = snprintf(buffer, CS_STATS_BUF_SIZE, "\n\nMemory Statistics of SIP on: %s\n"
180 " Total Sessions : %lu\n"
181 " Current Active Sessions : %u\n\n"
182 , ctime(&curr_time)
183 , sip_stats.sessions
184 , numSessions);
185 } else {
186 _dpd.logMsg("\n");
187 _dpd.logMsg("Memory Statistics of SIP on: %s\n", ctime(&curr_time));
188 _dpd.logMsg(" Total Sessions : %lu\n", sip_stats.sessions);
189 _dpd.logMsg(" Current Active Sessions : %u\n\n", numSessions);
190 }
191
192 return len;
193 }
194
195 /* Called at preprocessor setup time. Links preprocessor keyword
196 * to corresponding preprocessor initialization function.
197 *
198 * PARAMETERS: None.
199 *
200 * RETURNS: Nothing.
201 *
202 */
SetupSIP(void)203 void SetupSIP(void)
204 {
205 _dpd.registerMemoryStatsFunc(PP_SIP, SIPPrintMemStats);
206 /* Link preprocessor keyword to initialization function
207 * in the preprocessor list. */
208 #ifndef SNORT_RELOAD
209 _dpd.registerPreproc( "sip", SIPInit );
210 #else
211 _dpd.registerPreproc("sip", SIPInit, SIPReload,
212 SIPReloadVerify, SIPReloadSwap, SIPReloadSwapFree);
213 #endif
214 #ifdef DUMP_BUFFER
215 _dpd.registerBufferTracer(getSIPBuffers, SIP_BUFFER_DUMP_FUNC);
216 #endif
217 }
218
getParsingSIPConfig(struct _SnortConfig * sc)219 SIPConfig *getParsingSIPConfig(struct _SnortConfig *sc)
220 {
221 SIPConfig * sip_parsing_config;
222 #ifdef SNORT_RELOAD
223 tSfPolicyUserContextId sip_swap_config = (tSfPolicyUserContextId)_dpd.getRelatedReloadData(sc, "sip");
224 if (sip_swap_config)
225 sip_parsing_config = sfPolicyUserDataGetCurrent(sip_swap_config);
226 else
227 #endif
228 sip_parsing_config = sfPolicyUserDataGetCurrent(sip_config);
229 return sip_parsing_config;
230 }
231
232 #ifdef REG_TEST
PrintSIPSize(void)233 static inline void PrintSIPSize(void)
234 {
235 _dpd.logMsg("\nSIP Session Size: %lu\n", (long unsigned int)sizeof(SIPData));
236 }
237 #endif
238
239 /* Initializes the SIP preprocessor module and registers
240 * it in the preprocessor list.
241 *
242 * PARAMETERS:
243 *
244 * argp: Pointer to argument string to process for config
245 * data.
246 *
247 * RETURNS: Nothing.
248 */
SIPInit(struct _SnortConfig * sc,char * argp)249 static void SIPInit(struct _SnortConfig *sc, char *argp)
250 {
251 tSfPolicyId policy_id = _dpd.getParserPolicy(sc);
252 SIPConfig *pDefaultPolicyConfig = NULL;
253 SIPConfig *pPolicyConfig = NULL;
254
255 #ifdef REG_TEST
256 PrintSIPSize();
257 #endif
258 /* For SFR CLI */
259 _dpd.controlSocketRegisterHandler(CS_TYPE_SIP_STATS, NULL, NULL, &DisplaySIPStats);
260
261 if (sip_config == NULL)
262 {
263 //create a context
264 sip_config = sfPolicyConfigCreate();
265 if (sip_config == NULL)
266 {
267 DynamicPreprocessorFatalMessage("Failed to allocate memory "
268 "for SIP config.\n");
269 }
270
271 _dpd.addPreprocConfCheck(sc, SIPCheckConfig);
272 _dpd.registerPreprocStats(SIP_NAME, SIP_PrintStats);
273 _dpd.addPreprocExit(SIPCleanExit, NULL, PRIORITY_LAST, PP_SIP);
274
275 #ifdef PERF_PROFILING
276 _dpd.addPreprocProfileFunc("sip", (void *)&sipPerfStats, 0, _dpd.totalPerfStats, NULL);
277 #endif
278
279 #ifdef TARGET_BASED
280 sip_app_id = _dpd.findProtocolReference("sip");
281 if (sip_app_id == SFTARGET_UNKNOWN_PROTOCOL)
282 sip_app_id = _dpd.addProtocolReference("sip");
283
284 // register with session to handle applications
285 _dpd.sessionAPI->register_service_handler( PP_SIP, sip_app_id );
286
287 #endif
288 }
289
290 sfPolicyUserPolicySet (sip_config, policy_id);
291 pDefaultPolicyConfig = (SIPConfig *)sfPolicyUserDataGetDefault(sip_config);
292 pPolicyConfig = (SIPConfig *)sfPolicyUserDataGetCurrent(sip_config);
293 if ((pPolicyConfig != NULL) && (pDefaultPolicyConfig == NULL))
294 {
295 DynamicPreprocessorFatalMessage("SIP preprocessor can only be "
296 "configured once.\n");
297 }
298
299 pPolicyConfig = (SIPConfig *)_dpd.snortAlloc(1, sizeof(SIPConfig), PP_SIP,
300 PP_MEM_CATEGORY_CONFIG);
301 if (!pPolicyConfig)
302 {
303 DynamicPreprocessorFatalMessage("Could not allocate memory for "
304 "SIP preprocessor configuration.\n");
305 }
306
307 sfPolicyUserDataSetCurrent(sip_config, pPolicyConfig);
308 SIP_RegRuleOptions(sc);
309 ParseSIPArgs(pPolicyConfig, (u_char *)argp);
310 #ifdef SNORT_RELOAD
311 pDefaultPolicyConfig = (SIPConfig *)sfPolicyUserDataGetDefault(sip_config);
312 //we don't know the order in which policies are init
313 //maybe default (policy 0) isn't init until after another policy is init
314 //however a default policy is guranteed
315 //avoid core
316 //Also, if SIP isn't enabled, then why waste memory?
317 #ifdef REG_TEST
318 if (REG_TEST_FLAG_RELOAD & getRegTestFlags())
319 {
320 printf("SIP-reload SIPInit-before : %p\n", ada);
321 }
322 #endif
323 if (pDefaultPolicyConfig != NULL && ada == NULL && SIPGlobalIsEnabled(sc, sip_config))
324 {
325 ada = ada_init(SIP_NumSessions, PP_SIP, (size_t)pDefaultPolicyConfig->maxNumSessions);
326 if (ada == NULL)
327 DynamicPreprocessorFatalMessage("Could not allocate memory for SIP ada\n");
328 }
329 #ifdef REG_TEST
330 if (REG_TEST_FLAG_RELOAD & getRegTestFlags())
331 {
332 printf("SIP-reload SIPInit-after : %p\n", ada);
333 }
334 #endif
335 #endif
336
337 }
338
339 /*********************************************************************
340 * Overload PCRE options: this is to support the "H"
341 *
342 * For SIP messages, uri Buffers will point to SIP instead of HTTP
343 *
344 * Arguments:
345 * SFSnortPacket * - pointer to packet structure
346 *
347 * Returns:
348 * None
349 *
350 *********************************************************************/
SIP_overloadURI(SFSnortPacket * p,SIPMsg * sipMsg)351 static inline void SIP_overloadURI(SFSnortPacket *p, SIPMsg *sipMsg)
352 {
353 if ( sipMsg->header )
354 _dpd.setHttpBuffer(HTTP_BUFFER_HEADER, sipMsg->header, sipMsg->headerLen);
355
356 if ( sipMsg->body_data )
357 _dpd.setHttpBuffer(HTTP_BUFFER_CLIENT_BODY, sipMsg->body_data, sipMsg->bodyLen);
358 }
359
360
361 /*********************************************************************
362 * Main entry point for SIP processing.
363 *
364 * Arguments:
365 * SFSnortPacket * - pointer to packet structure
366 *
367 * Returns:
368 * int - SIP_SUCCESS
369 * SIP_FAILURE
370 *
371 *********************************************************************/
SIP_Process(SFSnortPacket * p,SIPData * sessp)372 static inline int SIP_Process(SFSnortPacket *p, SIPData* sessp)
373 {
374 int status;
375 char* sip_buff = (char*) p->payload;
376 char* end;
377 SIP_Roptions *pRopts;
378
379 memset(&sipMsg, 0, SIPMSG_ZERO_LEN);
380
381
382 /*Input parameters*/
383 sipMsg.isTcp = IsTCP(p);
384
385 end = sip_buff + p->payload_size;
386
387
388 status = sip_parse(&sipMsg, sip_buff, end);
389
390 if (SIP_SUCCESS == status)
391 {
392 SIP_overloadURI(p, &sipMsg);
393 /*Update the dialog state*/
394 SIP_updateDialog(&sipMsg, &(sessp->dialogs), p);
395 }
396 /*Update the session data*/
397 pRopts = &(sessp->ropts);
398 pRopts->methodFlag = sipMsg.methodFlag;
399 pRopts->header_data = sipMsg.header;
400 pRopts->header_len = sipMsg.headerLen;
401 pRopts->body_len = sipMsg.bodyLen;
402 pRopts->body_data = sipMsg.body_data;
403 pRopts->status_code = sipMsg.status_code;
404
405
406 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "SIP message header length: %d\n",
407 sipMsg.headerLen));
408 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "Parsed method: %.*s, Flag: 0x%x\n",
409 sipMsg.methodLen, sipMsg.method, sipMsg.methodFlag));
410 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "Parsed status code: %d\n",
411 sipMsg.status_code));
412 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "Parsed header address: %p.\n",
413 sipMsg.header));
414 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "Parsed body address: %p.\n",
415 sipMsg.body_data));
416
417 sip_freeMsg(&sipMsg);
418
419 return status;
420 }
421 /* Main runtime entry point for SIP preprocessor.
422 * Analyzes SIP packets for anomalies/exploits.
423 *
424 * PARAMETERS:
425 *
426 * packetp: Pointer to current packet to process.
427 * contextp: Pointer to context block, not used.
428 *
429 * RETURNS: Nothing.
430 */
SIPmain(void * ipacketp,void * contextp)431 static void SIPmain( void* ipacketp, void* contextp )
432 {
433 SIPData* sessp = NULL;
434 uint8_t source = 0;
435 uint8_t dest = 0;
436
437 SFSnortPacket* packetp;
438 #ifdef TARGET_BASED
439 int16_t app_id = SFTARGET_UNKNOWN_PROTOCOL;
440 #endif
441 tSfPolicyId policy_id = _dpd.getNapRuntimePolicy();
442 PROFILE_VARS;
443
444 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "%s\n", SIP_DEBUG__START_MSG));
445
446 packetp = (SFSnortPacket*) ipacketp;
447 sfPolicyUserPolicySet (sip_config, policy_id);
448
449 // preconditions - what we registered for
450 assert((IsUDP(packetp) || IsTCP(packetp)) &&
451 packetp->payload && packetp->payload_size);
452
453 if (IsTCP(packetp))
454 {
455 if (!_dpd.readyForProcess(packetp))
456 {
457 /* Packet will be rebuilt, so wait for it */
458 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "Packet will be reassembled\n"));
459 return;
460 }
461 if (_dpd.sessionAPI->get_application_data(packetp->stream_session, PP_SSL) &&
462 !_dpd.streamAPI->is_session_decrypted(packetp->stream_session))
463 {
464 /* Packet is a non-SIP/encrypted SIP one, skip those */
465 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "Packet is encrypted or not a SIP packet\n"));
466 return;
467 }
468 }
469
470 PREPROC_PROFILE_START(sipPerfStats);
471
472 sip_eval_config = sfPolicyUserDataGetCurrent(sip_config);
473
474 /* Attempt to get a previously allocated SIP block. */
475 sessp = _dpd.sessionAPI->get_application_data(packetp->stream_session, PP_SIP);
476 if (sessp != NULL)
477 {
478 sip_eval_config = sfPolicyUserDataGet(sessp->config, sessp->policy_id);
479
480 }
481
482 if (sessp == NULL)
483 {
484 /* If not doing autodetection, check the ports to make sure this is
485 * running on an SIP port, otherwise no need to examine the traffic.
486 */
487 #ifdef TARGET_BASED
488 app_id = _dpd.sessionAPI->get_application_protocol_id(packetp->stream_session);
489 if (app_id == SFTARGET_UNKNOWN_PROTOCOL)
490 {
491 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "Unknown protocol - not inspecting.\n"));
492 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "%s\n", SIP_DEBUG__END_MSG));
493 PREPROC_PROFILE_END(sipPerfStats);
494 return;
495 }
496
497 else if (app_id && (app_id != sip_app_id))
498 {
499 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "Not SIP - not inspecting.\n"));
500 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "%s\n", SIP_DEBUG__END_MSG));
501 PREPROC_PROFILE_END(sipPerfStats);
502 return;
503 }
504
505 else if (!app_id)
506 {
507 #endif
508 source = (uint8_t)CheckSIPPort( packetp->src_port );
509 dest = (uint8_t)CheckSIPPort( packetp->dst_port );
510
511 if ( !source && !dest )
512 {
513 /* Not one of the ports we care about. */
514 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "Not SIP ports - not inspecting.\n"));
515 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "%s\n", SIP_DEBUG__END_MSG));
516 PREPROC_PROFILE_END(sipPerfStats);
517 return;
518 }
519 #ifdef TARGET_BASED
520 }
521 #endif
522 /* Check the stream session. If it does not currently
523 * have our SIP data-block attached, create one.
524 */
525 sessp = SIPGetNewSession(packetp, policy_id);
526
527 if ( !sessp )
528 {
529 /* Could not get/create the session data for this packet. */
530 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "Create session error - not inspecting.\n"));
531 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "%s\n", SIP_DEBUG__END_MSG));
532 PREPROC_PROFILE_END(sipPerfStats);
533 return;
534 }
535
536 }
537
538 /* Don't process if we've missed packets */
539 if (sessp->state_flags & SIP_FLG_MISSED_PACKETS)
540 {
541 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "Missed packets - not inspecting.\n"));
542 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "%s\n", SIP_DEBUG__END_MSG));
543 PREPROC_PROFILE_END(sipPerfStats);
544 return;
545 }
546
547 /* If we picked up mid-stream or missed any packets (midstream pick up
548 * means we've already missed packets) set missed packets flag and make
549 * sure we don't do any more reassembly on this session */
550 if (IsTCP(packetp))
551 {
552 if ((_dpd.sessionAPI->get_session_flags(packetp->stream_session) & SSNFLAG_MIDSTREAM)
553 || _dpd.streamAPI->missed_packets(packetp->stream_session, SSN_DIR_BOTH))
554 {
555 _dpd.streamAPI->set_reassembly(packetp->stream_session,
556 STREAM_FLPOLICY_IGNORE, SSN_DIR_BOTH,
557 STREAM_FLPOLICY_SET_ABSOLUTE);
558
559 sessp->state_flags |= SIP_FLG_MISSED_PACKETS;
560 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "Missed packets - not inspecting.\n"));
561 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "%s\n", SIP_DEBUG__END_MSG));
562 PREPROC_PROFILE_END(sipPerfStats);
563 return;
564 }
565 }
566
567 /*
568 * Start process PAYLOAD
569 */
570 SIP_Process(packetp,sessp);
571
572 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "%s\n", SIP_DEBUG__END_MSG));
573 PREPROC_PROFILE_END(sipPerfStats);
574
575 }
576
577 /**********************************************************************
578 * Retrieves the SIP data block registered with the stream
579 * session associated w/ the current packet. If none exists,
580 * allocates it and registers it with the stream API.
581 *
582 * Arguments:
583 *
584 * packetp: Pointer to the packet from which/in which to
585 * retrieve/store the SIP data block.
586 *
587 * RETURNS: Pointer to an SIP data block, upon success.
588 * NULL, upon failure.
589 **********************************************************************/
SIPGetNewSession(SFSnortPacket * packetp,tSfPolicyId policy_id)590 SIPData * SIPGetNewSession(SFSnortPacket *packetp, tSfPolicyId policy_id)
591 {
592 SIPData* datap = NULL;
593 static int MaxSessionsAlerted = 0;
594 /* Sanity check(s) */
595 assert( packetp );
596 if ( !packetp->stream_session )
597 {
598 return NULL;
599 }
600 if(numSessions > ((SIPConfig *)sfPolicyUserDataGetCurrent(sip_config))->maxNumSessions)
601 {
602 if (!MaxSessionsAlerted)
603 ALERT(SIP_EVENT_MAX_SESSIONS,SIP_EVENT_MAX_SESSIONS_STR);
604 MaxSessionsAlerted = 1;
605 return NULL;
606 }
607 else
608 {
609 MaxSessionsAlerted = 0;
610 }
611 datap = (SIPData *)_dpd.snortAlloc(1, sizeof(SIPData), PP_SIP,
612 PP_MEM_CATEGORY_SESSION);
613
614 if ( !datap )
615 return NULL;
616
617 /*Register the new SIP data block in the stream session. */
618 _dpd.sessionAPI->set_application_data(
619 packetp->stream_session,
620 PP_SIP, datap, FreeSIPData );
621
622 /* We're interested in this session. Turn on stream reassembly. */
623 if ( !(_dpd.streamAPI->get_reassembly_direction(packetp->stream_session) & SSN_DIR_BOTH ))
624 {
625 _dpd.streamAPI->set_reassembly(packetp->stream_session,
626 STREAM_FLPOLICY_FOOTPRINT, SSN_DIR_BOTH, STREAM_FLPOLICY_SET_ABSOLUTE);
627 }
628
629 #ifdef SNORT_RELOAD
630 ada_add(ada, (void *)datap, packetp->stream_session);
631 #endif
632
633 datap->policy_id = policy_id;
634 datap->config = sip_config;
635 ((SIPConfig *)sfPolicyUserDataGetCurrent(sip_config))->ref_count++;
636 numSessions++;
637 sip_stats.sessions++;
638 DEBUG_WRAP(DebugMessage(DEBUG_SIP, "Number of sessions created: %u\n", numSessions));
639
640 return datap;
641 }
642
643
644 /***********************************************************************
645 * Registered as a callback with our SIP data blocks when
646 * they are added to the underlying stream session. Called
647 * by the stream preprocessor when a session is about to be
648 * destroyed.
649 *
650 * PARAMETERS:
651 *
652 * idatap: Pointer to the moribund data.
653 *
654 * RETURNS: Nothing.
655 ***********************************************************************/
FreeSIPData(void * idatap)656 static void FreeSIPData( void* idatap )
657 {
658 SIPData *ssn = (SIPData *)idatap;
659 SIPConfig *config = NULL;
660
661 if (ssn == NULL)
662 return;
663 if (numSessions > 0)
664 numSessions--;
665
666 #ifdef SNORT_RELOAD
667 ada_appdata_freed( ada, idatap );
668 #endif
669
670 /*Free all the dialog data*/
671 sip_freeDialogs(&ssn->dialogs);
672
673 /*Clean the configuration data*/
674 if (ssn->config != NULL)
675 {
676 config = (SIPConfig *)sfPolicyUserDataGet(ssn->config, ssn->policy_id);
677 }
678
679 if (config == NULL)
680 {
681 _dpd.snortFree(ssn, sizeof(SIPData), PP_SIP, PP_MEM_CATEGORY_SESSION);
682 return;
683 }
684
685 config->ref_count--;
686 if ((config->ref_count == 0) && (ssn->config != sip_config))
687 {
688 sfPolicyUserDataClear (ssn->config, ssn->policy_id);
689 _dpd.snortFree(config, sizeof(SIPConfig), PP_SIP, PP_MEM_CATEGORY_CONFIG);
690
691 if (sfPolicyUserPolicyGetActive(ssn->config) == 0)
692 {
693 /* No more outstanding configs - free the config array */
694 SIPFreeConfig(ssn->config);
695 }
696
697 }
698
699 _dpd.snortFree(ssn, sizeof(SIPData), PP_SIP, PP_MEM_CATEGORY_SESSION);
700 }
701 /* **********************************************************************
702 * Validates given port as an SIP server port.
703 *
704 * PARAMETERS:
705 *
706 * port: Port to validate.
707 *
708 * RETURNS: SIP_TRUE, if the port is indeed an SIP server port.
709 * SIP_FALSE, otherwise.
710 ***********************************************************************/
CheckSIPPort(uint16_t port)711 static inline int CheckSIPPort( uint16_t port )
712 {
713 if ( sip_eval_config->ports[ PORT_INDEX(port) ] & CONV_PORT( port ) )
714 {
715 return SIP_TRUE;
716 }
717
718 return SIP_FALSE;
719 }
720
registerPortsForDispatch(struct _SnortConfig * sc,SIPConfig * policy)721 static void registerPortsForDispatch( struct _SnortConfig *sc, SIPConfig *policy )
722 {
723 if ( _dpd.isPreprocEnabled( sc, PP_APP_ID ) )
724 {
725 _dpd.sessionAPI->enable_preproc_all_ports( sc,
726 PP_SIP,
727 PROTO_BIT__UDP | PROTO_BIT__TCP );
728 }
729 else
730 {
731 int port;
732 for ( port = 0; port < MAXPORTS; port++ )
733 {
734 if( isPortEnabled( policy->ports, port ) )
735 _dpd.sessionAPI->enable_preproc_for_port( sc,
736 PP_SIP,
737 PROTO_BIT__UDP | PROTO_BIT__TCP,
738 port );
739 }
740 }
741 }
742
registerPortsForReassembly(SIPConfig * policy,int direction)743 static void registerPortsForReassembly( SIPConfig *policy, int direction )
744 {
745 uint32_t port;
746
747 for ( port = 0; port < MAXPORTS; port++ )
748 {
749 if( isPortEnabled( policy->ports, port ) )
750 _dpd.streamAPI->register_reassembly_port( NULL, port, direction );
751 }
752 }
753
_addPortsToStreamFilter(struct _SnortConfig * sc,SIPConfig * config,tSfPolicyId policy_id)754 static void _addPortsToStreamFilter(struct _SnortConfig *sc, SIPConfig *config, tSfPolicyId policy_id)
755 {
756 uint32_t portNum;
757
758 assert(config);
759 assert(_dpd.streamAPI);
760
761 for (portNum = 0; portNum < MAXPORTS; portNum++)
762 {
763 if(config->ports[(portNum/8)] & (1<<(portNum%8)))
764 {
765 //Add port the port
766 _dpd.streamAPI->set_port_filter_status(sc, IPPROTO_UDP, (uint16_t)portNum, PORT_MONITOR_SESSION, policy_id, 1);
767 _dpd.streamAPI->set_port_filter_status(sc, IPPROTO_TCP, (uint16_t)portNum, PORT_MONITOR_SESSION, policy_id, 1);
768 register_sip_paf_port(sc, portNum, policy_id);
769 }
770 }
771 }
772
773 #ifdef TARGET_BASED
774
_addServicesToStreamFilter(struct _SnortConfig * sc,tSfPolicyId policy_id)775 static void _addServicesToStreamFilter(struct _SnortConfig *sc, tSfPolicyId policy_id)
776 {
777 _dpd.streamAPI->set_service_filter_status(sc, sip_app_id, PORT_MONITOR_SESSION, policy_id, 1);
778 register_sip_paf_service(sc, sip_app_id, policy_id);
779 }
780 #endif
781
SIPCheckPolicyConfig(struct _SnortConfig * sc,tSfPolicyUserContextId config,tSfPolicyId policy_id,void * pData)782 static int SIPCheckPolicyConfig(struct _SnortConfig *sc, tSfPolicyUserContextId config, tSfPolicyId policy_id, void* pData)
783 {
784 SIPConfig *sip_policy = ( SIPConfig * ) pData;
785
786 if ( sip_policy->disabled )
787 return 0;
788
789 if (!_dpd.isPreprocEnabled(sc, PP_STREAM))
790 {
791 _dpd.errMsg("SIPCheckPolicyConfig(): The Stream preprocessor must be enabled.\n");
792 return -1;
793 }
794
795 if (policy_id != 0)
796 {
797 SIPConfig *default_sip_policy = ( SIPConfig * ) sfPolicyUserDataGetDefault( config );
798 if(default_sip_policy == NULL)
799 {
800 _dpd.errMsg("SIPCheckPolicyConfig(): SIP default policy must be configured\n");
801 return -1;
802 }
803
804 sip_policy->maxNumSessions = default_sip_policy->maxNumSessions;
805 }
806
807 _dpd.setParserPolicy( sc, policy_id );
808 _dpd.addPreproc( sc, SIPmain, PRIORITY_APPLICATION, PP_SIP, PROTO_BIT__UDP|PROTO_BIT__TCP );
809
810 // register ports with session and stream
811 registerPortsForDispatch( sc, sip_policy );
812 registerPortsForReassembly( sip_policy, SSN_DIR_FROM_SERVER | SSN_DIR_FROM_CLIENT );
813 _addPortsToStreamFilter(sc, sip_policy, policy_id);
814
815 #ifdef TARGET_BASED
816 _addServicesToStreamFilter(sc, policy_id);
817 #endif
818
819 return 0;
820 }
821
SIPGlobalIsEnabled(struct _SnortConfig * sc,tSfPolicyUserContextId config)822 static bool SIPGlobalIsEnabled(struct _SnortConfig *sc, tSfPolicyUserContextId config)
823 {
824 return sfPolicyUserDataIterate(sc, config, SIPPolicyIsEnabled) != 0;
825 }
826
SIPPolicyIsEnabled(struct _SnortConfig * sc,tSfPolicyUserContextId pContext,tSfPolicyId policyId,void * config)827 static int SIPPolicyIsEnabled(struct _SnortConfig *sc, tSfPolicyUserContextId pContext, tSfPolicyId policyId, void* config)
828 {
829 SIPConfig *sip_policy_config = (SIPConfig *) config;
830 if (sip_policy_config == NULL || sip_policy_config->disabled)
831 return 0;
832
833 return 1;
834 }
835
SIPCheckConfig(struct _SnortConfig * sc)836 int SIPCheckConfig(struct _SnortConfig *sc)
837 {
838 int rval;
839
840 if ((rval = sfPolicyUserDataIterate (sc, sip_config, SIPCheckPolicyConfig)))
841 return rval;
842
843 return 0;
844 }
845
SIPCleanExit(int signal,void * data)846 static void SIPCleanExit(int signal, void *data)
847 {
848 if (sip_config != NULL)
849 {
850 SIPFreeConfig(sip_config);
851 sip_config = NULL;
852 #ifdef SNORT_RELOAD
853 ada_delete(ada);
854 ada = NULL;
855 #endif
856 }
857 }
SIPFreeConfigPolicy(tSfPolicyUserContextId config,tSfPolicyId policyId,void * pData)858 static int SIPFreeConfigPolicy(
859 tSfPolicyUserContextId config,
860 tSfPolicyId policyId,
861 void* pData
862 )
863 {
864 SIPConfig *pPolicyConfig = (SIPConfig *)pData;
865
866 //do any housekeeping before freeing SIPConfig
867
868 sfPolicyUserDataClear (config, policyId);
869
870 SIP_FreeConfig(pPolicyConfig);
871 return 0;
872 }
873
SIPFreeConfig(tSfPolicyUserContextId config)874 void SIPFreeConfig(tSfPolicyUserContextId config)
875 {
876 if (config == NULL)
877 return;
878
879 sfPolicyUserDataFreeIterate (config, SIPFreeConfigPolicy);
880 sfPolicyConfigDelete(config);
881 }
882
DisplaySIPStats(uint16_t type,void * old_context,struct _THREAD_ELEMENT * te,ControlDataSendFunc f)883 static void DisplaySIPStats (uint16_t type, void *old_context, struct _THREAD_ELEMENT *te, ControlDataSendFunc f)
884 {
885 char buffer[CS_STATS_BUF_SIZE + 1];
886 int i = 0;
887 int len = 0;
888
889 if (sip_stats.sessions) {
890 len += snprintf(buffer, CS_STATS_BUF_SIZE, "SIP Preprocessor Statistics\n"
891 " Total sessions: "STDu64"\n", sip_stats.sessions);
892 if (sip_stats.events)
893 len += snprintf(buffer+len, CS_STATS_BUF_SIZE-len, " SIP anomalies : "STDu64"\n", sip_stats.events);
894
895 if (sip_stats.dialogs)
896 len += snprintf(buffer+len, CS_STATS_BUF_SIZE-len, " Total dialogs: "STDu64"\n", sip_stats.dialogs);
897
898 len += snprintf(buffer+len, CS_STATS_BUF_SIZE-len, " Requests: "STDu64"\n", sip_stats.requests[0]);
899 while (NULL != StandardMethods[i].name && len < CS_STATS_BUF_SIZE) {
900 len += snprintf(buffer+len, CS_STATS_BUF_SIZE-len, "%16s: "STDu64"\n",
901 StandardMethods[i].name, sip_stats.requests[StandardMethods[i].methodFlag]);
902 i++;
903 }
904 len += snprintf(buffer+len, CS_STATS_BUF_SIZE-len, " Responses: "STDu64"\n", sip_stats.responses[TOTAL_RESPONSES]);
905 for (i = 1; i <NUM_OF_RESPONSE_TYPES && len < CS_STATS_BUF_SIZE; i++) {
906 len += snprintf(buffer+len, CS_STATS_BUF_SIZE-len, " %dxx: "STDu64"\n", i, sip_stats.responses[i]);
907 }
908 len += snprintf(buffer+len, CS_STATS_BUF_SIZE-len, " Ignore sessions: "STDu64"\n"
909 " Ignore channels: "STDu64"\n", sip_stats.ignoreSessions, sip_stats.ignoreChannels);
910 } else {
911 len = snprintf(buffer, CS_STATS_BUF_SIZE, "SIP Stats not available\n Total Sessions:"STDu64"\n", sip_stats.sessions );
912 }
913
914 if (-1 == f(te, (const uint8_t *)buffer, len)) {
915 _dpd.logMsg("Unable to send data to the frontend\n");
916 }
917 }
918
919 /******************************************************************
920 * Print statistics being kept by the preprocessor.
921 *
922 * Arguments:
923 * int - whether Snort is exiting or not
924 *
925 * Returns: None
926 *
927 ******************************************************************/
SIP_PrintStats(int exiting)928 static void SIP_PrintStats(int exiting)
929 {
930 int i;
931 _dpd.logMsg("SIP Preprocessor Statistics\n");
932 _dpd.logMsg(" Total sessions: "STDu64"\n", sip_stats.sessions);
933 if (sip_stats.sessions > 0)
934 {
935 if (sip_stats.events > 0)
936 _dpd.logMsg(" SIP anomalies : "STDu64"\n", sip_stats.events);
937 if (sip_stats.dialogs > 0)
938 _dpd.logMsg(" Total dialogs: "STDu64"\n", sip_stats.dialogs);
939
940 _dpd.logMsg(" Requests: "STDu64"\n", sip_stats.requests[0]);
941 i = 0;
942 while (NULL != StandardMethods[i].name)
943 {
944 _dpd.logMsg("%16s: "STDu64"\n",
945 StandardMethods[i].name, sip_stats.requests[StandardMethods[i].methodFlag]);
946 i++;
947 }
948
949 _dpd.logMsg(" Responses: "STDu64"\n", sip_stats.responses[TOTAL_RESPONSES]);
950 for (i = 1; i <NUM_OF_RESPONSE_TYPES; i++ )
951 {
952 _dpd.logMsg(" %dxx: "STDu64"\n", i, sip_stats.responses[i]);
953 }
954
955 _dpd.logMsg(" Ignore sessions: "STDu64"\n", sip_stats.ignoreSessions);
956 _dpd.logMsg(" Ignore channels: "STDu64"\n", sip_stats.ignoreChannels);
957 }
958 }
959 #ifdef SNORT_RELOAD
SIPReload(struct _SnortConfig * sc,char * args,void ** new_config)960 static void SIPReload(struct _SnortConfig *sc, char *args, void **new_config)
961 {
962 tSfPolicyUserContextId sip_swap_config = (tSfPolicyUserContextId)*new_config;
963 tSfPolicyId policy_id = _dpd.getParserPolicy(sc);
964 SIPConfig *pDefaultPolicyConfig = NULL;
965 SIPConfig * pPolicyConfig = NULL;
966
967 if (sip_swap_config == NULL)
968 {
969 //create a context
970 sip_swap_config = sfPolicyConfigCreate();
971 if (sip_swap_config == NULL)
972 {
973 DynamicPreprocessorFatalMessage("Failed to allocate memory for SIP config.\n");
974 }
975 *new_config = (void *)sip_swap_config;
976 }
977
978 sfPolicyUserPolicySet (sip_swap_config, policy_id);
979 pPolicyConfig = (SIPConfig *)sfPolicyUserDataGetCurrent(sip_swap_config);
980 if (pPolicyConfig != NULL)
981 {
982 DynamicPreprocessorFatalMessage("SIP preprocessor can only be configured once.\n");
983 }
984
985 pPolicyConfig = (SIPConfig *)_dpd.snortAlloc(1, sizeof(SIPConfig), PP_SIP,
986 PP_MEM_CATEGORY_CONFIG);
987 if (!pPolicyConfig)
988 {
989 DynamicPreprocessorFatalMessage("Could not allocate memory for "
990 "SIP preprocessor configuration.\n");
991 }
992 sfPolicyUserDataSetCurrent(sip_swap_config, pPolicyConfig);
993 SIP_RegRuleOptions(sc);
994 ParseSIPArgs(pPolicyConfig, (u_char *)args);
995
996 pDefaultPolicyConfig = (SIPConfig *)sfPolicyUserDataGetDefault(sip_config);
997 //we don't know the order in which policies are init
998 //maybe default (policy 0) isn't init until after another policy is init
999 //however a default policy is guranteed
1000 //avoid core
1001 //Also, if SIP isn't enabled, then why waste memory?
1002 #ifdef REG_TEST
1003 if (REG_TEST_FLAG_RELOAD & getRegTestFlags())
1004 {
1005 printf("SIP-reload SIPReload-before : %p\n", ada);
1006 }
1007 #endif
1008 if (pDefaultPolicyConfig != NULL && SIPGlobalIsEnabled(sc, sip_swap_config) && ada == NULL)
1009 {
1010 ada = ada_init(SIP_NumSessions, PP_SIP, (size_t)pDefaultPolicyConfig->maxNumSessions);
1011 if (ada == NULL)
1012 DynamicPreprocessorFatalMessage("Could not allocate memory for SIP ada\n");
1013 }
1014 #ifdef REG_TEST
1015 if (REG_TEST_FLAG_RELOAD & getRegTestFlags())
1016 {
1017 printf("SIP-reload SIPReload-after : %p\n", ada);
1018 }
1019 #endif
1020 }
1021
SIPReloadVerify(struct _SnortConfig * sc,void * swap_config)1022 static int SIPReloadVerify(struct _SnortConfig *sc, void *swap_config)
1023 {
1024 tSfPolicyUserContextId sip_swap_config = (tSfPolicyUserContextId)swap_config;
1025 SIPConfig * default_swap_config = NULL;
1026 SIPConfig * current_default_config = NULL;
1027 int rval;
1028
1029 if (sip_swap_config == NULL)
1030 return 0;
1031
1032 // validate each policy and do per policy initialization processing
1033 if ((rval = sfPolicyUserDataIterate (sc, sip_swap_config, SIPCheckPolicyConfig)))
1034 return rval;
1035
1036 default_swap_config = (SIPConfig *)sfPolicyUserDataGet(sip_swap_config, _dpd.getDefaultPolicy());
1037
1038 if (sip_config != NULL)
1039 {
1040 current_default_config = (SIPConfig *)sfPolicyUserDataGet(sip_config, _dpd.getDefaultPolicy());
1041 //not possible
1042 if (!current_default_config)
1043 return 0;
1044
1045 tSfPolicyId policy_id = _dpd.getParserPolicy(sc);
1046 if (!SIPGlobalIsEnabled(sc, sip_swap_config))
1047 {
1048 ada_reload_disable(&ada, sc, "sip-disable-mem-dump", policy_id);
1049 }
1050 else if (SIPGlobalIsEnabled(sc, sip_config) && default_swap_config->maxNumSessions < current_default_config->maxNumSessions)
1051 {
1052 ada_reload_adjust_register(ada, policy_id, sc, "sip-mem-reloader",
1053 (size_t) default_swap_config->maxNumSessions);
1054 }
1055 }
1056
1057 return 0;
1058 }
1059
SIPFreeUnusedConfigPolicy(tSfPolicyUserContextId config,tSfPolicyId policyId,void * pData)1060 static int SIPFreeUnusedConfigPolicy(
1061 tSfPolicyUserContextId config,
1062 tSfPolicyId policyId,
1063 void* pData
1064 )
1065 {
1066 SIPConfig *pPolicyConfig = (SIPConfig *)pData;
1067
1068 //do any housekeeping before freeing SIPConfig
1069 if (pPolicyConfig->ref_count == 0)
1070 {
1071 sfPolicyUserDataClear (config, policyId);
1072 SIP_FreeConfig(pPolicyConfig);
1073 }
1074 return 0;
1075 }
1076
SIPReloadSwap(struct _SnortConfig * sc,void * swap_config)1077 static void * SIPReloadSwap(struct _SnortConfig *sc, void *swap_config)
1078 {
1079 tSfPolicyUserContextId sip_swap_config = (tSfPolicyUserContextId)swap_config;
1080 tSfPolicyUserContextId old_config = sip_config;
1081
1082 if (sip_swap_config == NULL)
1083 return NULL;
1084
1085 sip_config = sip_swap_config;
1086
1087 sfPolicyUserDataFreeIterate (old_config, SIPFreeUnusedConfigPolicy);
1088 if (sfPolicyUserPolicyGetActive(old_config) == 0)
1089 {
1090 /* No more outstanding configs - free the config array */
1091 return (void *)old_config;
1092 }
1093
1094 return NULL;
1095 }
1096
SIPReloadSwapFree(void * data)1097 static void SIPReloadSwapFree(void *data)
1098 {
1099 if (data == NULL)
1100 return;
1101
1102 SIPFreeConfig((tSfPolicyUserContextId)data);
1103 }
1104 #endif
1105