Advertisement
tsnaik

fw_appid

Feb 10th, 2016
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
4CS 152.79 KB | None | 0 0
  1. /*
  2. ** Copyright (C) 2014-2015 Cisco and/or its affiliates. All rights reserved.
  3. ** Copyright (C) 2005-2013 Sourcefire, Inc.
  4. **
  5. ** This program is free software; you can redistribute it and/or modify
  6. ** it under the terms of the GNU General Public License Version 2 as
  7. ** published by the Free Software Foundation.  You may not use, modify or
  8. ** distribute this program under any other version of the GNU General
  9. ** Public License.
  10. **
  11. ** This program is distributed in the hope that it will be useful,
  12. ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. ** GNU General Public License for more details.
  15. **
  16. ** You should have received a copy of the GNU General Public License
  17. ** along with this program; if not, write to the Free Software
  18. ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
  19. */
  20.  
  21. #include <stdint.h>
  22. #include <stdbool.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <sys/types.h>
  27. #include <sys/stat.h>
  28. #include <stdlib.h>
  29. #include <ctype.h>
  30. #include <dlfcn.h>
  31. #include <fcntl.h>
  32. #include <syslog.h>
  33. #ifndef WIN32
  34. #include <strings.h>
  35. #include <sys/time.h>
  36. #endif
  37. #include <pthread.h>
  38. #include "appIdApi.h"
  39. #include "fw_appid.h"
  40. #include "profiler.h"
  41. #include "client_app_base.h"
  42. #include "httpCommon.h"
  43. #include "luaDetectorApi.h"
  44. #include "http_url_patterns.h"
  45. #include "fw_appid.h"
  46. #include "detector_http.h"
  47. #include "service_ssl.h"
  48. #include "detector_dns.h"
  49. #include "flow.h"
  50. #include "common_util.h"
  51. #include "spp_appid.h"
  52. #include "hostPortAppCache.h"
  53. #include "lengthAppCache.h"
  54. #include "appInfoTable.h"
  55. #include "appIdStats.h"
  56. #include "sf_mlmp.h"
  57. #include "ip_funcs.h"
  58. #include "app_forecast.h"
  59. #include "thirdparty_appid_types.h"
  60. #include "thirdparty_appid_utils.h"
  61. #include "appInfoTable.h"
  62. #include "service_base.h"
  63. #include"appid_sessionstore.c"
  64. #include"appid_hashing.c"
  65. #include"appid_sessid.c"
  66.  
  67. //#define DEBUG_APP_ID_SESSIONS   1
  68. //#define DEBUG_FW_APPID  1
  69. #define DEBUG_FW_APPID_PORT 80
  70.  
  71. #define MAX_ATTR_LEN           1024
  72. #define GENERIC_APP_OFFSET 2000000000
  73. #define HTTP_PREFIX "http://"
  74.  
  75. #define APP_MAPPING_FILE "appMapping.data"
  76.  
  77. #ifdef RNA_DEBUG_PE
  78. static const char *MODULE_NAME = "fw_appid";
  79. #endif
  80.  
  81. #define MAX_TP_PACKETS_PER_SESSION 5
  82.  
  83. static volatile int app_id_debug_flag;
  84. static FWDebugSessionConstraints app_id_debug_info;
  85. char app_id_debug_session[FW_DEBUG_SESSION_ID_SIZE];
  86. bool app_id_debug_session_flag;
  87.  
  88. #ifdef PERF_PROFILING
  89. PreprocStats tpPerfStats;
  90. PreprocStats tpLibPerfStats;
  91. PreprocStats httpPerfStats;
  92. PreprocStats clientMatchPerfStats;
  93. PreprocStats serviceMatchPerfStats;
  94. #endif
  95.  
  96. #define HTTP_PATTERN_MAX_LEN    1024
  97. #define PORT_MAX 65535
  98.  
  99. int ipCount=0, tcpCount=0, udpCount=0;
  100.  
  101.  
  102.  
  103. unsigned long app_id_raw_packet_count = 0;
  104. unsigned long app_id_processed_packet_count = 0;
  105. unsigned long app_id_ignored_packet_count = 0;
  106. static tAppIdData *app_id_free_list;
  107. static tTmpAppIdData *tmp_app_id_free_list;
  108. int app_id_debug;
  109. static int ptype_scan_counts[NUMBER_OF_PTYPES];
  110.  
  111. static void ProcessThirdPartyResults(tAppIdData* appIdSession, int confidence, tAppId* proto_list, ThirdPartyAppIDAttributeData* attribute_data);
  112. static void ExamineRtmpMetadata(tAppIdData *appIdSession);
  113.  
  114. static void appSharedDataFree(tAppIdData * sharedData)
  115. {
  116.     sharedData->next = app_id_free_list;
  117.     app_id_free_list = sharedData;
  118. }
  119.  
  120. static void appTmpSharedDataFree(tTmpAppIdData * sharedData)
  121. {
  122.     sharedData->next = tmp_app_id_free_list;
  123.     tmp_app_id_free_list = sharedData;
  124. }
  125.  
  126. static void appHttpFieldClear (httpSession *hsession)
  127. {
  128.     if (hsession == NULL) return;
  129.  
  130.     if (hsession->referer)
  131.     {
  132.         free(hsession->referer);
  133.         hsession->referer = NULL;
  134.     }
  135.     if (hsession->cookie)
  136.     {
  137.         free(hsession->cookie);
  138.         hsession->cookie = NULL;
  139.     }
  140.     if (hsession->url)
  141.     {
  142.         free(hsession->url);
  143.         hsession->url = NULL;
  144.     }
  145.     if (hsession->useragent)
  146.     {
  147.         free(hsession->useragent);
  148.         hsession->useragent = NULL;
  149.     }
  150.     if (hsession->host)
  151.     {
  152.         free(hsession->host);
  153.         hsession->host = NULL;
  154.     }
  155.     if (hsession->uri)
  156.     {
  157.         free(hsession->uri);
  158.         hsession->uri = NULL;
  159.     }
  160.     if (hsession->content_type)
  161.     {
  162.         free(hsession->content_type);
  163.         hsession->content_type = NULL;
  164.     }
  165.     if (hsession->location)
  166.     {
  167.         free(hsession->location);
  168.         hsession->location = NULL;
  169.     }
  170.     if (hsession->body)
  171.     {
  172.         free(hsession->body);
  173.         hsession->body = NULL;
  174.     }
  175.     if (hsession->req_body)
  176.     {
  177.         free(hsession->req_body);
  178.         hsession->req_body = NULL;
  179.     }
  180. }
  181.  
  182. static void appHttpSessionDataFree (httpSession *hsession)
  183. {
  184.     if (hsession == NULL) return;
  185.  
  186.     appHttpFieldClear(hsession);
  187.  
  188.     if (hsession->new_url)
  189.     {
  190.         free(hsession->new_url);
  191.         hsession->new_url = NULL;
  192.     }
  193.     if (hsession->new_cookie)
  194.     {
  195.         free(hsession->new_cookie);
  196.         hsession->new_cookie = NULL;
  197.     }
  198.     if (hsession->fflow)
  199.     {
  200.         free(hsession->fflow);
  201.         hsession->fflow = NULL;
  202.     }
  203.     if (hsession->via)
  204.     {
  205.         free(hsession->via);
  206.         hsession->via = NULL;
  207.     }
  208.     if (hsession->content_type)
  209.     {
  210.         free(hsession->content_type);
  211.         hsession->content_type = NULL;
  212.     }
  213.     if (hsession->response_code)
  214.     {
  215.         free(hsession->response_code);
  216.         hsession->response_code = NULL;
  217.     }
  218.  
  219.     free(hsession);
  220. }
  221.  
  222. static void appDNSSessionDataFree(dnsSession *dsession)
  223. {
  224.     if (dsession == NULL) return;
  225.     if (dsession->host)
  226.     {
  227.         free(dsession->host);
  228.         dsession->host = NULL;
  229.     }
  230.     free(dsession);
  231. }
  232.  
  233. static void appTlsSessionDataFree (tlsSession *tsession)
  234. {
  235.     if (tsession == NULL) return;
  236.  
  237.     if (tsession->tls_host)
  238.         free(tsession->tls_host);
  239.     if (tsession->tls_cname)
  240.         free(tsession->tls_cname);
  241.     if (tsession->tls_orgUnit)
  242.         free(tsession->tls_orgUnit);
  243.     free(tsession);
  244. }
  245.  
  246. void appSharedDataDelete(tAppIdData * sharedData)
  247. {
  248.     RNAServiceSubtype *subtype;
  249.  
  250.     if (sharedData)
  251.     {
  252. #ifdef DEBUG_FW_APPID
  253. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  254.         if (sharedData->service_port == DEBUG_FW_APPID_PORT)
  255. #endif
  256.             fprintf(SF_DEBUG_FILE, "Deleting session %p\n", sharedData);
  257. #endif
  258.         /*check daq flag */
  259.         appIdStatsUpdate(sharedData);
  260.  
  261.         if (sharedData->ssn)
  262.             FailInProcessService(sharedData, pAppidActiveConfig);
  263.         AppIdFlowdataFree(sharedData);
  264.  
  265.         if (thirdparty_appid_module)
  266.         {
  267.             thirdparty_appid_module->session_delete(sharedData->tpsession, 0);    // we're completely done with it
  268.             sharedData->tpsession = NULL;
  269.         }
  270.         free(sharedData->clientVersion);
  271.         free(sharedData->serviceVendor);
  272.         free(sharedData->serviceVersion);
  273.         free(sharedData->netbios_name);
  274.         while ((subtype = sharedData->subtype))
  275.         {
  276.             sharedData->subtype = subtype->next;
  277.             free(*(void **)&subtype->service);
  278.             free(*(void **)&subtype->vendor);
  279.             free(*(void **)&subtype->version);
  280.             free(subtype);
  281.         }
  282.         if (sharedData->candidate_service_list != NULL)
  283.         {
  284.             sflist_free(sharedData->candidate_service_list);
  285.             sharedData->candidate_service_list = NULL;
  286.         }
  287.         if (sharedData->candidate_client_list != NULL)
  288.         {
  289.             sflist_free(sharedData->candidate_client_list);
  290.             sharedData->candidate_client_list = NULL;
  291.         }
  292.         free(sharedData->username);
  293.         free(sharedData->netbiosDomain);
  294.         free(sharedData->payloadVersion);
  295.         appHttpSessionDataFree(sharedData->hsession);
  296.         appTlsSessionDataFree(sharedData->tsession);
  297.         appDNSSessionDataFree(sharedData->dsession);
  298.         sharedData->tsession = NULL;
  299.  
  300.         free(sharedData->firewallEarlyData);
  301.         sharedData->firewallEarlyData = NULL;
  302.  
  303.         appSharedDataFree(sharedData);
  304.     }
  305. }
  306. /* The UNSYNCED_SNORT_ID value is to cheaply insure we get
  307.    the value from snort rather than assume */
  308. #define UNSYNCED_SNORT_ID   0x5555
  309.  
  310. tAppIdData* appSharedDataAlloc(uint8_t proto, sfaddr_t *ip)
  311. {
  312.     static uint32_t gFlowId;
  313.     tAppIdData *data;
  314.  
  315.     if (app_id_free_list)
  316.     {
  317.         data = app_id_free_list;
  318.         app_id_free_list = data->next;
  319.         memset(data, 0, sizeof(*data));
  320.     }
  321.     else if (!(data = calloc(1, sizeof(*data))))
  322.         DynamicPreprocessorFatalMessage("Could not allocate tAppIdData data");
  323.  
  324.     if (thirdparty_appid_module)
  325.         if (!(data->tpsession = thirdparty_appid_module->session_create()))
  326.             DynamicPreprocessorFatalMessage("Could not allocate tAppIdData->tpsession data");
  327.  
  328.     data->flowId = ++gFlowId;
  329.     data->common.fsf_type.flow_type = APPID_SESSION_TYPE_NORMAL;
  330.     data->proto = proto;
  331.     data->common.initiator_ip = *ip;
  332.     data->snortId = UNSYNCED_SNORT_ID;
  333.     return data;
  334. }
  335.  
  336. static tAppIdData* appSharedCreateData(const SFSnortPacket *p, uint8_t proto, int direction)
  337. {
  338. #ifdef DEBUG_FW_APPID
  339.     static unsigned long packet_count;
  340. #endif
  341.     tAppIdData *data;
  342.     sfaddr_t *ip;
  343.  
  344.     ip = (direction == APP_ID_FROM_INITIATOR) ? GET_SRC_IP(p) : GET_DST_IP(p);
  345.     data = appSharedDataAlloc(proto, ip);
  346.  
  347.     if ((proto == IPPROTO_TCP || proto == IPPROTO_UDP) && p->src_port != p->dst_port)
  348.         data->common.initiator_port = (direction == APP_ID_FROM_INITIATOR) ? p->src_port : p->dst_port;
  349.     data->ssn = p->stream_session;
  350. #ifdef DEBUG_FW_APPID
  351. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  352.         if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  353. #endif
  354.             fprintf(SF_DEBUG_FILE, "pkt %lu : tAppIdData: Allocated %p\n", ++packet_count, data);
  355. #endif
  356.     data->stats.firstPktsecond = p->pkt_header->ts.tv_sec;
  357.  
  358.     _dpd.sessionAPI->set_application_data(p->stream_session, PP_APP_ID, data,
  359.             (void (*)(void *))appSharedDataDelete);
  360.     return data;
  361. }
  362.  
  363. static void appSaveEncryptedApps(tAppIdData* session)
  364. {
  365.     session->encrypted.serviceAppId = pickServiceAppId(session);
  366.     session->encrypted.payloadAppId = pickPayloadId(session);
  367.     session->encrypted.clientAppId = pickClientAppId(session);
  368.     session->encrypted.miscAppId = pickMiscAppId(session);
  369.     session->encrypted.referredAppId = pickReferredPayloadId(session);
  370. }
  371. static void appSharedReInitData(tAppIdData* session)
  372. {
  373.     session->miscAppId = APP_ID_NONE;
  374.  
  375.     //payload
  376.     if (isSslServiceAppId(session->tpAppId))
  377.     {
  378.         session->payloadAppId = session->referredPayloadAppId = session->tpPayloadAppId =  APP_ID_NONE;
  379.         clearAppIdExtFlag(session, APPID_SESSION_CONTINUE);
  380.         if (session->payloadVersion)
  381.         {
  382.             free(session->payloadVersion);
  383.             session->payloadVersion = NULL;
  384.         }
  385.         if (session->hsession && session->hsession->url)
  386.         {
  387.             free(session->hsession->url);
  388.             session->hsession->url = NULL;
  389.         }
  390.     }
  391.  
  392.     //service
  393.     if (!getAppIdIntFlag(session, APPID_SESSION_STICKY_SERVICE))
  394.     {
  395.         clearAppIdIntFlag(session, APPID_SESSION_STICKY_SERVICE);
  396.  
  397.         session->tpAppId = session->serviceAppId = session->portServiceAppId = APP_ID_NONE;
  398.         if (session->serviceVendor)
  399.         {
  400.             free(session->serviceVendor);
  401.             session->serviceVendor = NULL;
  402.         }
  403.         if (session->serviceVersion)
  404.         {
  405.             free(session->serviceVersion);
  406.             session->serviceVersion = NULL;
  407.         }
  408.  
  409.         IP_CLEAR(session->service_ip);
  410.         session->service_port = 0;
  411.         session->rnaServiceState = RNA_STATE_NONE;
  412.         session->serviceData = NULL;
  413.         AppIdFlowdataDeleteAllByMask(session, APPID_SESSION_DATA_SERVICE_MODSTATE_BIT);
  414.     }
  415.  
  416.     //client
  417.     session->clientAppId = session->clientServiceAppId = APP_ID_NONE;
  418.     if (session->clientVersion)
  419.     {
  420.         free(session->clientVersion);
  421.         session->clientVersion = NULL;
  422.     }
  423.     session->rnaClientState = RNA_STATE_NONE;
  424.     AppIdFlowdataDeleteAllByMask(session, APPID_SESSION_DATA_CLIENT_MODSTATE_BIT);
  425.  
  426.     //3rd party cleaning
  427.     if (thirdparty_appid_module)
  428.         thirdparty_appid_module->session_delete(session->tpsession, 1);
  429.     session->init_tpPackets = 0;
  430.     session->resp_tpPackets = 0;
  431.  
  432.     session->scan_flags &= ~SCAN_HTTP_HOST_URL_FLAG;
  433.     clearAppIdExtFlag(session, APPID_SESSION_SERVICE_DETECTED|APPID_SESSION_CLIENT_DETECTED|APPID_SESSION_SSL_SESSION|APPID_SESSION_HTTP_SESSION);
  434.     clearAppIdIntFlag(session, APPID_SESSION_APP_REINSPECT);
  435. }
  436. void fwAppIdFini(tAppIdConfig *pConfig)
  437. {
  438. #ifdef RNA_FULL_CLEANUP
  439.     tAppIdData *app_id;
  440.     tTmpAppIdData *tmp_app_id;
  441.  
  442.     while ((app_id = app_id_free_list))
  443.     {
  444.         app_id_free_list = app_id->next;
  445.         free(app_id);
  446.     }
  447.  
  448.     while ((tmp_app_id = tmp_app_id_free_list))
  449.     {
  450.         tmp_app_id_free_list = tmp_app_id->next;
  451.         free(tmp_app_id);
  452.     }
  453.     AppIdFlowdataFini();
  454. #endif
  455.  
  456.     appInfoTableFini(pConfig);
  457. }
  458.  
  459. static inline int PENetworkMatch(const sfaddr_t *pktAddr, const PortExclusion *pe)
  460. {
  461.     const uint32_t* pkt = sfaddr_get_ip6_ptr(pktAddr);
  462.     const uint32_t* nm = pe->netmask.s6_addr32;
  463.     const uint32_t* peIP = pe->ip.s6_addr32;
  464.     return (((pkt[0] & nm[0]) == peIP[0])
  465.             && ((pkt[1] & nm[1]) == peIP[1])
  466.             && ((pkt[2] & nm[2]) == peIP[2])
  467.             && ((pkt[3] & nm[3]) == peIP[3]));
  468. }
  469.  
  470. static inline int checkPortExclusion(const SFSnortPacket *pkt, int reversed)
  471. {
  472.     SF_LIST * *src_port_exclusions;
  473.     SF_LIST * *dst_port_exclusions;
  474.     SF_LIST *pe_list;
  475.     PortExclusion *pe;
  476.     sfaddr_t *s_ip;
  477.     uint16_t port;
  478.     tAppIdConfig *pConfig = appIdActiveConfigGet();
  479.  
  480.     if (IsTCP(pkt))
  481.     {
  482.         src_port_exclusions = pConfig->tcp_port_exclusions_src;
  483.         dst_port_exclusions = pConfig->tcp_port_exclusions_dst;
  484.     }
  485.     else if (IsUDP(pkt))
  486.     {
  487.         src_port_exclusions = pConfig->udp_port_exclusions_src;
  488.         dst_port_exclusions = pConfig->udp_port_exclusions_dst;
  489.     }
  490.     else
  491.         return 0;
  492.  
  493.     /* check the source port */
  494.     port = reversed ? pkt->dst_port : pkt->src_port;
  495.     if( port && (pe_list=src_port_exclusions[port]) != NULL )
  496.     {
  497.         s_ip = reversed ? GET_DST_IP(pkt) : GET_SRC_IP(pkt);
  498.  
  499.         /* walk through the list of port exclusions for this port */
  500.         for (pe=(PortExclusion *)sflist_first(pe_list);
  501.                 pe;
  502.                 pe=(PortExclusion *)sflist_next(pe_list))
  503.         {
  504.             if( PENetworkMatch(s_ip, pe))
  505.             {
  506. #ifdef RNA_DEBUG_PE
  507.                 char inetBuffer[INET6_ADDRSTRLEN];
  508.                 inetBuffer[0] = 0;
  509.                 inet_ntop(sfaddr_family(s_ip), (void *)sfaddr_get_ptr(s_ip), inetBuffer, sizeof(inetBuffer));
  510.  
  511.                 SFDEBUG(MODULE_NAME, "excluding src port: %d",port);
  512.                 SFDEBUG(MODULE_NAME, "for addresses src: %s", inetBuffer);
  513. #endif
  514.                 return 1;
  515.             }
  516.         }
  517.     }
  518.  
  519.     /* check the dest port */
  520.     port = reversed ? pkt->src_port : pkt->dst_port;
  521.     if( port && (pe_list=dst_port_exclusions[port]) != NULL )
  522.     {
  523.         s_ip = reversed ? GET_SRC_IP(pkt) : GET_DST_IP(pkt);
  524.  
  525.         /* walk through the list of port exclusions for this port */
  526.         for (pe=(PortExclusion *)sflist_first(pe_list);
  527.                 pe;
  528.                 pe=(PortExclusion *)sflist_next(pe_list))
  529.         {
  530.             if( PENetworkMatch(s_ip, pe))
  531.             {
  532. #ifdef RNA_DEBUG_PE
  533.                 char inetBuffer[INET6_ADDRSTRLEN];
  534.                 inetBuffer[0] = 0;
  535.                 inet_ntop(sfaddr_family(s_ip), (void *)sfaddr_get_ptr(s_ip), inetBuffer, sizeof(inetBuffer));
  536.                 SFDEBUG(MODULE_NAME, "excluding dst port: %d",port);
  537.                 SFDEBUG(MODULE_NAME, "for addresses dst: %s", inetBuffer);
  538. #endif
  539.                 return 1;
  540.             }
  541.         }
  542.     }
  543.  
  544.     return 0;
  545. }
  546.  
  547. static inline bool fwAppIdDebugCheck(void *lwssn, tAppIdData *session, volatile int debug_flag,
  548.         FWDebugSessionConstraints *info, char *debug_session, int direction)
  549. {
  550.     if (debug_flag)
  551.     {
  552.         const StreamSessionKey *key;
  553.  
  554.         key = _dpd.sessionAPI->get_key_from_session_ptr(lwssn);
  555.         if ((!info->protocol || info->protocol == key->protocol) &&
  556.             (((!info->sport || info->sport == key->port_l) &&
  557.               (!info->sip_flag || memcmp(&info->sip, key->ip_l, sizeof(info->sip)) == 0) &&
  558.               (!info->dport || info->dport == key->port_h) &&
  559.               (!info->dip_flag || memcmp(&info->dip, key->ip_h, sizeof(info->dip)) == 0)) ||
  560.              ((!info->sport || info->sport == key->port_h) &&
  561.                (!info->sip_flag || memcmp(&info->sip, key->ip_h, sizeof(info->sip)) == 0) &&
  562.                (!info->dport || info->dport == key->port_l) &&
  563.                (!info->dip_flag || memcmp(&info->dip, key->ip_l, sizeof(info->dip)) == 0))))
  564.         {
  565.             int af;
  566.             const struct in6_addr* sip;
  567.             const struct in6_addr* dip;
  568.             unsigned offset;
  569.             uint16_t sport;
  570.             uint16_t dport;
  571.             char sipstr[INET6_ADDRSTRLEN];
  572.             char dipstr[INET6_ADDRSTRLEN];
  573.             if (session && session->common.fsf_type.flow_type != APPID_SESSION_TYPE_IGNORE)
  574.             {
  575.                 if (session->common.initiator_port)
  576.                 {
  577.                     if (session->common.initiator_port == key->port_l)
  578.                     {
  579.                         sip = (const struct in6_addr*)key->ip_l;
  580.                         dip = (const struct in6_addr*)key->ip_h;
  581.                         sport = key->port_l;
  582.                         dport = key->port_h;
  583.                     }
  584.                     else
  585.                     {
  586.                         sip = (const struct in6_addr*)key->ip_h;
  587.                         dip = (const struct in6_addr*)key->ip_l;
  588.                         sport = key->port_h;
  589.                         dport = key->port_l;
  590.                     }
  591.                 }
  592.                 else if (sfip_fast_eq6((sfaddr_t*)&session->common.initiator_ip, (sfaddr_t*)key->ip_l) == 0)
  593.                 {
  594.                     sip = (const struct in6_addr*)key->ip_l;
  595.                     dip = (const struct in6_addr*)key->ip_h;
  596.                     sport = key->port_l;
  597.                     dport = key->port_h;
  598.                 }
  599.                 else
  600.                 {
  601.                     sip = (const struct in6_addr*)key->ip_h;
  602.                     dip = (const struct in6_addr*)key->ip_l;
  603.                     sport = key->port_h;
  604.                     dport = key->port_l;
  605.                 }
  606.             }
  607.             else
  608.             {
  609.                 sip = (const struct in6_addr*)key->ip_l;
  610.                 dip = (const struct in6_addr*)key->ip_h;
  611.                 sport = key->port_l;
  612.                 dport = key->port_h;
  613.             }
  614.             sipstr[0] = 0;
  615.             if (sip->s6_addr32[0] || sip->s6_addr32[1] || sip->s6_addr16[4] || (sip->s6_addr16[5] && sip->s6_addr16[5] != 0xFFFF))
  616.             {
  617.                 af = AF_INET6;
  618.                 offset = 0;
  619.             }
  620.             else
  621.             {
  622.                 af = AF_INET;
  623.                 offset = 12;
  624.             }
  625.             inet_ntop(af, &sip->s6_addr[offset], sipstr, sizeof(sipstr));
  626.             dipstr[0] = 0;
  627.             if (dip->s6_addr32[0] || dip->s6_addr32[1] || dip->s6_addr16[4] || (dip->s6_addr16[5] && dip->s6_addr16[5] != 0xFFFF))
  628.             {
  629.                 af = AF_INET6;
  630.                 offset = 0;
  631.             }
  632.             else
  633.             {
  634.                 af = AF_INET;
  635.                 offset = 12;
  636.             }
  637.             inet_ntop(af, &dip->s6_addr[offset], dipstr, sizeof(dipstr));
  638.             snprintf(debug_session, FW_DEBUG_SESSION_ID_SIZE, "%s-%u and %s-%u %u%s",
  639.                     sipstr, (unsigned)sport, dipstr, (unsigned)dport, (unsigned)key->protocol,
  640.                     (direction == APP_ID_FROM_INITIATOR) ? "":" R");
  641.             return true;
  642.         }
  643.     }
  644.     return false;
  645. }
  646.  
  647. static void appIdDebugParse(const char *desc, const uint8_t *data, uint32_t length,
  648.                           volatile int *debug_flag, FWDebugSessionConstraints *info)
  649. {
  650.     *debug_flag = 0;
  651.     memset(info, 0, sizeof(*info));
  652.     do
  653.     {
  654.         if (length >= sizeof(info->protocol))
  655.         {
  656.             info->protocol = *data;
  657.             length -= sizeof(info->protocol);
  658.             data += sizeof(info->protocol);
  659.         }
  660.         else
  661.             break;
  662.  
  663.         if (length >= sizeof(info->sip))
  664.         {
  665.  
  666.             memcpy(&info->sip, data, sizeof(info->sip));
  667.             if (info->sip.s6_addr32[1] || info->sip.s6_addr32[2] || info->sip.s6_addr32[3])
  668.                 info->sip_flag = 1;
  669.             else if (info->sip.s6_addr32[0])
  670.             {
  671.                 info->sip.s6_addr32[3] = info->sip.s6_addr32[0];
  672.                 info->sip.s6_addr32[0] = 0;
  673.                 info->sip.s6_addr16[5] = 0xFFFF;
  674.                 info->sip_flag = 1;
  675.             }
  676.             length -= sizeof(info->sip);
  677.             data += sizeof(info->sip);
  678.         }
  679.         else
  680.             break;
  681.  
  682.         if (length >= sizeof(info->sport))
  683.         {
  684.             memcpy(&info->sport, data, sizeof(info->sport));
  685.             length -= sizeof(info->sport);
  686.             data += sizeof(info->sport);
  687.         }
  688.         else
  689.             break;
  690.  
  691.         if (length >= sizeof(info->dip))
  692.         {
  693.             memcpy(&info->dip, data, sizeof(info->dip));
  694.             if (info->dip.s6_addr32[1] || info->dip.s6_addr32[2] || info->dip.s6_addr32[3])
  695.                 info->dip_flag = 1;
  696.             else if (info->dip.s6_addr32[0])
  697.             {
  698.                 info->dip.s6_addr32[3] = info->dip.s6_addr32[0];
  699.                 info->dip.s6_addr32[0] = 0;
  700.                 info->dip.s6_addr16[5] = 0xFFFF;
  701.                 info->dip_flag = 1;
  702.             }
  703.             length -= sizeof(info->dip);
  704.             data += sizeof(info->dip);
  705.         }
  706.         else
  707.             break;
  708.  
  709.         if (length >= sizeof(info->dport))
  710.         {
  711.             memcpy(&info->dport, data, sizeof(info->dport));
  712.             length -= sizeof(info->dport);
  713.             data += sizeof(info->dport);
  714.         }
  715.         else
  716.             break;
  717.     } while (0);
  718.  
  719.     if (info->protocol || info->sip_flag || info->sport || info->dip_flag || info->dport)
  720.     {
  721.         int saf;
  722.         int daf;
  723.         char sipstr[INET6_ADDRSTRLEN];
  724.         char dipstr[INET6_ADDRSTRLEN];
  725.  
  726.         if (!info->sip.s6_addr32[0] && !info->sip.s6_addr32[0] && !info->sip.s6_addr16[4] &&
  727.             info->sip.s6_addr16[5] == 0xFFFF)
  728.         {
  729.             saf = AF_INET;
  730.         }
  731.         else
  732.             saf = AF_INET6;
  733.         if (!info->dip.s6_addr32[0] && !info->dip.s6_addr32[0] && !info->dip.s6_addr16[4] &&
  734.             info->dip.s6_addr16[5] == 0xFFFF)
  735.         {
  736.             daf = AF_INET;
  737.         }
  738.         else
  739.             daf = AF_INET6;
  740.         if (!info->sip_flag)
  741.             saf = daf;
  742.         if (!info->dip_flag)
  743.             daf = saf;
  744.         sipstr[0] = 0;
  745.         inet_ntop(saf, saf == AF_INET ? &info->sip.s6_addr32[3] : info->sip.s6_addr32, sipstr, sizeof(sipstr));
  746.         dipstr[0] = 0;
  747.         inet_ntop(daf, daf == AF_INET ? &info->dip.s6_addr32[3] : info->dip.s6_addr32, dipstr, sizeof(dipstr));
  748.         _dpd.logMsg("Debugging %s with %s-%u and %s-%u %u\n", desc,
  749.                     sipstr, (unsigned)info->sport,
  750.                     dipstr, (unsigned)info->dport,
  751.                     (unsigned)info->protocol);
  752.         *debug_flag = 1;
  753.     }
  754.     else
  755.         _dpd.logMsg("Debugging %s disabled\n", desc);
  756. }
  757. int AppIdDebug(uint16_t type, const uint8_t *data, uint32_t length, void **new_context,
  758.                char* statusBuf, int statusBuf_len)
  759. {
  760.     appIdDebugParse("appId", data, length, &app_id_debug_flag, &app_id_debug_info);
  761.     return 0;
  762. }
  763.  
  764. unsigned isIPv4HostMonitored(uint32_t ip4, int32_t zone)
  765. {
  766.     NetworkSet *net_list;
  767.     unsigned flags;
  768.     tAppIdConfig *pConfig = appIdActiveConfigGet();
  769.  
  770.     if (zone >= 0 && zone < MAX_ZONES && pConfig->net_list_by_zone[zone])
  771.         net_list = pConfig->net_list_by_zone[zone];
  772.     else
  773.         net_list = pConfig->net_list;
  774.  
  775.     NetworkSet_ContainsEx(net_list, ip4, &flags);
  776.     return flags;
  777. }
  778.  
  779. static inline unsigned isIPMonitored(const SFSnortPacket *p, int dst)
  780. {
  781.     uint32_t ipAddr;
  782.     sfaddr_t *sf_ip;
  783.     struct in_addr ip;
  784.     NetworkSet *net_list;
  785.     unsigned flags;
  786.     int32_t zone;
  787.     NSIPv6Addr ip6;
  788.     tAppIdConfig *pConfig = appIdActiveConfigGet();
  789.  
  790.     if (!dst)
  791.     {
  792.         zone = p->pkt_header->ingress_group;
  793.         sf_ip = GET_SRC_IP(p);
  794.     }
  795.     else
  796.     {
  797.         zone = (p->pkt_header->egress_index == DAQ_PKTHDR_UNKNOWN) ? p->pkt_header->ingress_group : p->pkt_header->egress_group;
  798.         if (zone == DAQ_PKTHDR_FLOOD)
  799.             return 0;
  800.         sf_ip = GET_DST_IP(p);
  801.     }
  802.     if (zone >= 0 && zone < MAX_ZONES && pConfig->net_list_by_zone[zone])
  803.         net_list = pConfig->net_list_by_zone[zone];
  804.     else
  805.         net_list = pConfig->net_list;
  806.     if (sfaddr_family(sf_ip) == AF_INET)
  807.     {
  808.         ip.s_addr = sfaddr_get_ip4_value(sf_ip);
  809.         if (ip.s_addr == 0xFFFFFFFF)
  810.             return IPFUNCS_CHECKED;
  811.         ipAddr = ntohl(ip.s_addr);
  812.         NetworkSet_ContainsEx(net_list, ipAddr, &flags);
  813.     }
  814.     else
  815.     {
  816.         memcpy(&ip6, sfaddr_get_ptr(sf_ip), sizeof(ip6));
  817.         NSIPv6AddrNtoH(&ip6);
  818.         NetworkSet_Contains6Ex(net_list, &ip6, &flags);
  819.     }
  820.     return flags | IPFUNCS_CHECKED;
  821. }
  822.  
  823. static inline int isSpecialSessionMonitored(const SFSnortPacket *p)
  824. {
  825.     sfaddr_t *srcAddr;
  826.  
  827.     srcAddr = GET_SRC_IP(p);
  828.     if (sfaddr_family(srcAddr) == AF_INET)
  829.     {
  830.         if (IsUDP(p) && ((p->src_port == 68 && p->dst_port == 67) || (p->src_port == 67 && p->dst_port == 68)))
  831.         {
  832.             return 1;
  833.         }
  834.     }
  835.     return 0;
  836. }
  837. static inline unsigned isSessionMonitored(const SFSnortPacket *p, int dir, tAppIdData *session)
  838. {
  839.     unsigned flags;
  840.     unsigned flow_flags = _dpd.isAppIdRequired() ? APPID_SESSION_DISCOVER_APP : 0;
  841.  
  842.     flow_flags |= (dir == APP_ID_FROM_INITIATOR) ? APPID_SESSION_INITIATOR_SEEN : APPID_SESSION_RESPONDER_SEEN;
  843.     if (session)
  844.     {
  845.         flow_flags |= session->common.externalFlags;
  846.         if (session->common.policyId != appIdPolicyId)
  847.         {
  848.             if (checkPortExclusion(p, dir == APP_ID_FROM_RESPONDER))
  849.             {
  850.                 flow_flags |= APPID_SESSION_INITIATOR_SEEN | APPID_SESSION_RESPONDER_SEEN | APPID_SESSION_INITIATOR_CHECKED | APPID_SESSION_RESPONDER_CHECKED;
  851.                 flow_flags &= ~(APPID_SESSION_INITIATOR_MONITORED | APPID_SESSION_RESPONDER_MONITORED);
  852.                 return flow_flags;
  853.             }
  854.             if (dir == APP_ID_FROM_INITIATOR)
  855.             {
  856.                 if (getAppIdExtFlag(session, APPID_SESSION_INITIATOR_CHECKED))
  857.                 {
  858.                     flags = isIPMonitored(p, 0);
  859.                     if (flags & IPFUNCS_HOSTS_IP)
  860.                         flow_flags |= APPID_SESSION_INITIATOR_MONITORED;
  861.                     else
  862.                         flow_flags &= ~APPID_SESSION_INITIATOR_MONITORED;
  863.                 }
  864.  
  865.                 if (getAppIdExtFlag(session, APPID_SESSION_RESPONDER_CHECKED))
  866.                 {
  867.                     flags = isIPMonitored(p, 1);
  868.                     if (flags & IPFUNCS_HOSTS_IP)
  869.                         flow_flags |= APPID_SESSION_RESPONDER_MONITORED;
  870.                     else
  871.                         flow_flags &= ~APPID_SESSION_RESPONDER_MONITORED;
  872.                 }
  873.             }
  874.             else
  875.             {
  876.                 if (getAppIdExtFlag(session, APPID_SESSION_RESPONDER_CHECKED))
  877.                 {
  878.                     flags = isIPMonitored(p, 0);
  879.                     if (flags & IPFUNCS_HOSTS_IP)
  880.                         flow_flags |= APPID_SESSION_RESPONDER_MONITORED;
  881.                     else
  882.                         flow_flags &= ~APPID_SESSION_RESPONDER_MONITORED;
  883.                 }
  884.  
  885.                 if (getAppIdExtFlag(session, APPID_SESSION_INITIATOR_CHECKED))
  886.                 {
  887.                     flags = isIPMonitored(p, 1);
  888.                     if (flags & IPFUNCS_HOSTS_IP)
  889.                         flow_flags |= APPID_SESSION_INITIATOR_MONITORED;
  890.                     else
  891.                         flow_flags &= ~APPID_SESSION_INITIATOR_MONITORED;
  892.                 }
  893.             }
  894.         }
  895.  
  896.         if (getAppIdExtFlag(session, APPID_SESSION_BIDIRECTIONAL_CHECKED) == APPID_SESSION_BIDIRECTIONAL_CHECKED)
  897.             return flow_flags;
  898.  
  899.         if (dir == APP_ID_FROM_INITIATOR)
  900.         {
  901.             if (!getAppIdExtFlag(session, APPID_SESSION_INITIATOR_CHECKED))
  902.             {
  903.                 flags = isIPMonitored(p, 0);
  904.                 flow_flags |= APPID_SESSION_INITIATOR_CHECKED;
  905.                 if (flags & IPFUNCS_HOSTS_IP)
  906.                     flow_flags |= APPID_SESSION_INITIATOR_MONITORED;
  907.                 if (flags & IPFUNCS_USER_IP)
  908.                     flow_flags |= APPID_SESSION_DISCOVER_USER;
  909.                 if (flags & IPFUNCS_APPLICATION)
  910.                     flow_flags |= APPID_SESSION_DISCOVER_APP;
  911.  
  912.                 if (isSpecialSessionMonitored(p))
  913.                 {
  914.                     flow_flags |= APPID_SESSION_SPECIAL_MONITORED;
  915.                 }
  916.             }
  917.             if (!(flow_flags & APPID_SESSION_DISCOVER_APP) && !getAppIdExtFlag(session, APPID_SESSION_RESPONDER_CHECKED))
  918.             {
  919.                 flags = isIPMonitored(p, 1);
  920.                 if (flags & IPFUNCS_CHECKED)
  921.                     flow_flags |= APPID_SESSION_RESPONDER_CHECKED;
  922.                 if (flags & IPFUNCS_HOSTS_IP)
  923.                     flow_flags |= APPID_SESSION_RESPONDER_MONITORED;
  924.                 if (flags & IPFUNCS_APPLICATION)
  925.                     flow_flags |= APPID_SESSION_DISCOVER_APP;
  926.                 if (isSpecialSessionMonitored(p))
  927.                 {
  928.                     flow_flags |= APPID_SESSION_SPECIAL_MONITORED;
  929.                 }
  930.             }
  931.         }
  932.         else
  933.         {
  934.             if (!getAppIdExtFlag(session, APPID_SESSION_RESPONDER_CHECKED))
  935.             {
  936.                 flags = isIPMonitored(p, 0);
  937.                 flow_flags |= APPID_SESSION_RESPONDER_CHECKED;
  938.                 if (flags & IPFUNCS_HOSTS_IP)
  939.                     flow_flags |= APPID_SESSION_RESPONDER_MONITORED;
  940.                 if (flags & IPFUNCS_APPLICATION)
  941.                     flow_flags |= APPID_SESSION_DISCOVER_APP;
  942.                 if (isSpecialSessionMonitored(p))
  943.                 {
  944.                     flow_flags |= APPID_SESSION_SPECIAL_MONITORED;
  945.                 }
  946.             }
  947.             if (!(flow_flags & APPID_SESSION_DISCOVER_APP) && !getAppIdExtFlag(session, APPID_SESSION_INITIATOR_CHECKED))
  948.             {
  949.                 flags = isIPMonitored(p, 1);
  950.                 if (flags & IPFUNCS_CHECKED)
  951.                     flow_flags |= APPID_SESSION_INITIATOR_CHECKED;
  952.                 if (flags & IPFUNCS_HOSTS_IP)
  953.                     flow_flags |= APPID_SESSION_INITIATOR_MONITORED;
  954.                 if (flags & IPFUNCS_USER_IP)
  955.                     flow_flags |= APPID_SESSION_DISCOVER_USER;
  956.                 if (flags & IPFUNCS_APPLICATION)
  957.                     flow_flags |= APPID_SESSION_DISCOVER_APP;
  958.                 if (isSpecialSessionMonitored(p))
  959.                 {
  960.                     flow_flags |= APPID_SESSION_SPECIAL_MONITORED;
  961.                 }
  962.             }
  963.         }
  964.     }
  965.     else if (checkPortExclusion(p, 0))
  966.     {
  967.         flow_flags |= APPID_SESSION_INITIATOR_SEEN | APPID_SESSION_RESPONDER_SEEN | APPID_SESSION_INITIATOR_CHECKED | APPID_SESSION_RESPONDER_CHECKED;
  968.     }
  969.     else if (dir == APP_ID_FROM_INITIATOR)
  970.     {
  971.         flags = isIPMonitored(p, 0);
  972.         flow_flags |= APPID_SESSION_INITIATOR_CHECKED;
  973.         if (flags & IPFUNCS_HOSTS_IP)
  974.             flow_flags |= APPID_SESSION_INITIATOR_MONITORED;
  975.         if (flags & IPFUNCS_USER_IP)
  976.             flow_flags |= APPID_SESSION_DISCOVER_USER;
  977.         if (flags & IPFUNCS_APPLICATION)
  978.             flow_flags |= APPID_SESSION_DISCOVER_APP;
  979.         if (!(flow_flags & APPID_SESSION_DISCOVER_APP))
  980.         {
  981.             flags = isIPMonitored(p, 1);
  982.             if (flags & IPFUNCS_CHECKED)
  983.                 flow_flags |= APPID_SESSION_RESPONDER_CHECKED;
  984.             if (flags & IPFUNCS_HOSTS_IP)
  985.                 flow_flags |= APPID_SESSION_RESPONDER_MONITORED;
  986.             if (flags & IPFUNCS_APPLICATION)
  987.                 flow_flags |= APPID_SESSION_DISCOVER_APP;
  988.         }
  989.         if (isSpecialSessionMonitored(p))
  990.         {
  991.             flow_flags |= APPID_SESSION_SPECIAL_MONITORED;
  992.         }
  993.     }
  994.     else
  995.     {
  996.         flags = isIPMonitored(p, 0);
  997.         flow_flags |= APPID_SESSION_RESPONDER_CHECKED;
  998.         if (flags & IPFUNCS_HOSTS_IP)
  999.             flow_flags |= APPID_SESSION_RESPONDER_MONITORED;
  1000.         if (flags & IPFUNCS_APPLICATION)
  1001.             flow_flags |= APPID_SESSION_DISCOVER_APP;
  1002.         if (!(flow_flags & APPID_SESSION_DISCOVER_APP))
  1003.         {
  1004.             flags = isIPMonitored(p, 1);
  1005.             if (flags & IPFUNCS_CHECKED)
  1006.                 flow_flags |= APPID_SESSION_INITIATOR_CHECKED;
  1007.             if (flags & IPFUNCS_HOSTS_IP)
  1008.                 flow_flags |= APPID_SESSION_INITIATOR_MONITORED;
  1009.             if (flags & IPFUNCS_USER_IP)
  1010.                 flow_flags |= APPID_SESSION_DISCOVER_USER;
  1011.             if (flags & IPFUNCS_APPLICATION)
  1012.                 flow_flags |= APPID_SESSION_DISCOVER_APP;
  1013.         }
  1014.  
  1015.         if (isSpecialSessionMonitored(p))
  1016.         {
  1017.             flow_flags |= APPID_SESSION_SPECIAL_MONITORED;
  1018.         }
  1019.     }
  1020.  
  1021.     return flow_flags;
  1022. }
  1023.  
  1024. static void setServiceAppIdData(tAppIdData *session, tAppId serviceAppId, char *vendor, char **version)
  1025. {
  1026.     if (serviceAppId <= APP_ID_NONE)
  1027.         return;
  1028.  
  1029.     //in drambuie, 3rd party is in INIT state after processing first GET requuest.
  1030.     if (serviceAppId == APP_ID_HTTP)
  1031.     {
  1032.         if (session->clientServiceAppId == APP_ID_NONE)
  1033.         {
  1034.             session->clientServiceAppId = serviceAppId;
  1035.         }
  1036.         return;
  1037.     }
  1038.  
  1039.     if (session->serviceAppId != serviceAppId)
  1040.     {
  1041.         session->serviceAppId = serviceAppId;
  1042.  
  1043.         checkSandboxDetection(serviceAppId);
  1044.  
  1045.         /* Clear out previous values of vendor & version */
  1046.         if (session->serviceVendor)
  1047.         {
  1048.             free(session->serviceVendor);
  1049.             session->serviceVendor = NULL;
  1050.         }
  1051.         if (session->serviceVersion)
  1052.         {
  1053.             free(session->serviceVersion);
  1054.             session->serviceVersion = NULL;
  1055.         }
  1056.  
  1057.         if (vendor)
  1058.             session->serviceVendor = vendor;
  1059.  
  1060.         if (version && *version)
  1061.         {
  1062.             session->serviceVersion = *version;
  1063.             *version = NULL;
  1064.         }
  1065.     }
  1066.     else
  1067.     {
  1068.         if (vendor || version)
  1069.         {
  1070.             /* Clear previous values */
  1071.             if (session->serviceVendor)
  1072.                 free(session->serviceVendor);
  1073.             if (session->serviceVersion)
  1074.                 free(session->serviceVersion);
  1075.  
  1076.             /* set vendor */
  1077.             if (vendor)
  1078.                 session->serviceVendor = vendor;
  1079.             else
  1080.                 session->serviceVendor = NULL;
  1081.  
  1082.             /* set version */
  1083.             if (version && *version)
  1084.             {
  1085.                 session->serviceVersion = *version;
  1086.                 *version = NULL;
  1087.             }
  1088.             else
  1089.                 session->serviceVersion = NULL;
  1090.         }
  1091.     }
  1092. }
  1093.  
  1094. static void setClientAppIdData(tAppIdData *session, tAppId clientAppId, char **version)
  1095. {
  1096.     tAppIdConfig *pConfig = appIdActiveConfigGet();
  1097.     if (clientAppId <= APP_ID_NONE || clientAppId == APP_ID_HTTP)
  1098.         return;
  1099.  
  1100.     if (session->clientAppId != clientAppId)
  1101.     {
  1102.         unsigned prev_priority = appInfoEntryPriorityGet(session->clientAppId, pConfig);
  1103.         unsigned curr_priority = appInfoEntryPriorityGet(clientAppId, pConfig) ;
  1104.  
  1105.         checkSandboxDetection(clientAppId);
  1106.  
  1107.         if ((session->clientAppId) && (prev_priority > curr_priority ))
  1108.             return;
  1109.         session->clientAppId = clientAppId;
  1110.  
  1111.         if (session->clientVersion)
  1112.             free(session->clientVersion);
  1113.  
  1114.         if (version && *version)
  1115.         {
  1116.             session->clientVersion = *version;
  1117.             *version = NULL;
  1118.         }
  1119.         else
  1120.             session->clientVersion = NULL;
  1121.     }
  1122.     else if (version && *version)
  1123.     {
  1124.         if (session->clientVersion)
  1125.             free(session->clientVersion);
  1126.         session->clientVersion = *version;
  1127.         *version = NULL;
  1128.     }
  1129. }
  1130.  
  1131. static void setReferredPayloadAppIdData(tAppIdData *session, tAppId referredPayloadAppId)
  1132. {
  1133.     if (referredPayloadAppId <= APP_ID_NONE)
  1134.         return;
  1135.  
  1136.     if (session->referredPayloadAppId != referredPayloadAppId)
  1137.     {
  1138.         checkSandboxDetection(referredPayloadAppId);
  1139.  
  1140.         session->referredPayloadAppId = referredPayloadAppId;
  1141.     }
  1142. }
  1143.  
  1144. static void setPayloadAppIdData(tAppIdData *session, tAppId payloadAppId, char **version)
  1145. {
  1146.     tAppIdConfig *pConfig = appIdActiveConfigGet();
  1147.  
  1148.     if (payloadAppId <= APP_ID_NONE)
  1149.         return;
  1150.  
  1151.     if (session->payloadAppId != payloadAppId)
  1152.     {
  1153.         unsigned prev_priority = appInfoEntryPriorityGet(session->payloadAppId, pConfig);
  1154.         unsigned curr_priority = appInfoEntryPriorityGet(payloadAppId, pConfig);
  1155.  
  1156.         checkSandboxDetection(payloadAppId);
  1157.  
  1158.         if ((session->payloadAppId ) && (prev_priority > curr_priority ))
  1159.             return;
  1160.  
  1161.         session->payloadAppId = payloadAppId;
  1162.  
  1163.         if (session->payloadVersion)
  1164.             free(session->payloadVersion);
  1165.  
  1166.         if (version && *version)
  1167.         {
  1168.             session->payloadVersion = *version;
  1169.             *version = NULL;
  1170.         }
  1171.         else
  1172.             session->payloadVersion = NULL;
  1173.     }
  1174.     else if (version && *version)
  1175.     {
  1176.         if (session->payloadVersion)
  1177.             free(session->payloadVersion);
  1178.         session->payloadVersion = *version;
  1179.         *version = NULL;
  1180.     }
  1181. }
  1182.  
  1183. static void clearSessionAppIdData(tAppIdData *session)
  1184. {
  1185.     session->payloadAppId = APP_ID_UNKNOWN;
  1186.     session->serviceAppId = APP_ID_UNKNOWN;
  1187.     session->tpPayloadAppId = APP_ID_UNKNOWN;
  1188.     session->tpAppId = APP_ID_UNKNOWN;
  1189.     if (session->payloadVersion)
  1190.     {
  1191.         free(session->payloadVersion);
  1192.         session->payloadVersion = NULL;
  1193.     }
  1194.     if (session->serviceVendor)
  1195.     {
  1196.         free(session->serviceVendor);
  1197.         session->serviceVendor = NULL;
  1198.     }
  1199.     if (session->serviceVersion)
  1200.     {
  1201.         free(session->serviceVersion);
  1202.         session->serviceVersion = NULL;
  1203.     }
  1204.     if (session->tsession)
  1205.     {
  1206.         appTlsSessionDataFree(session->tsession);
  1207.         session->tsession = NULL;
  1208.     }
  1209.     if (session->hsession)
  1210.     {
  1211.         appHttpSessionDataFree(session->hsession);
  1212.         session->hsession = NULL;
  1213.     }
  1214.     if (session->dsession)
  1215.     {
  1216.         appDNSSessionDataFree(session->dsession);
  1217.         session->dsession = NULL;
  1218.     }
  1219.     if (thirdparty_appid_module)
  1220.         thirdparty_appid_module->session_delete(session->tpsession, 1);
  1221. }
  1222.  
  1223. static int initial_CHP_sweep (PatternType current_ptype, char* chp_buffer,
  1224.         char **version, char **user, char **new_url,
  1225.         char **new_cookie, tAppIdData *session,
  1226.         const tAppIdConfig *pConfig)
  1227. {
  1228.     CHPApp* cah = NULL;
  1229.     tAppId candidate;
  1230.     int size, i;
  1231.     int found_in_buffer = 0;
  1232.     httpSession *hsession;
  1233.     int retVal = 0;
  1234.  
  1235.     hsession = session->hsession;
  1236.  
  1237.     if (chp_buffer && (size = strlen(chp_buffer)) &&
  1238.             (candidate = scanCHP(current_ptype, chp_buffer,
  1239.                                  size, version, user, new_url, new_cookie,
  1240.                                  &found_in_buffer, hsession, NULL, &pConfig->detectorHttpConfig)))
  1241.     {
  1242.         if ((cah = (CHPApp *)sfxhash_find(pConfig->CHP_glossary, &candidate)))
  1243.         {
  1244.             for (i = 0; i < NUMBER_OF_PTYPES; i++)
  1245.             {
  1246.                 ptype_scan_counts[i] = cah->ptype_scan_counts[i];
  1247.                 hsession->ptype_req_counts[i] = cah->ptype_req_counts[i];
  1248.                 if (i > 3 && !cah->ptype_scan_counts[i] && !getAppIdExtFlag(session, APPID_SESSION_SPDY_SESSION))
  1249.                 {
  1250.                     clearAppIdIntFlag(session, APPID_SESSION_CHP_INSPECTING);
  1251.                     if (thirdparty_appid_module)
  1252.                         thirdparty_appid_module->session_attr_clear(session->tpsession, TP_ATTR_CONTINUE_MONITORING);
  1253.                 }
  1254.             }
  1255.             hsession->chp_candidate = cah->appId;
  1256.             hsession->app_type_flags = cah->app_type_flags;
  1257.             hsession->num_matches = cah->num_matches;
  1258.             hsession->num_scans = cah->num_scans;
  1259.             // we can only skip re-matching this if it is the only pattern of its type.
  1260.             if (ptype_scan_counts[current_ptype] == 1)
  1261.             {
  1262.                 ptype_scan_counts[current_ptype]--;
  1263.                 hsession->ptype_req_counts[current_ptype]--;
  1264.                 hsession->num_scans--;
  1265.                 hsession->total_found++;
  1266.             }
  1267.  
  1268.             retVal = 1;
  1269.         }
  1270.     }
  1271.     if (thirdparty_appid_module)
  1272.     {
  1273.         if ((ptype_scan_counts[CONTENT_TYPE_PT]))
  1274.             thirdparty_appid_module->session_attr_set(session->tpsession, TP_ATTR_COPY_RESPONSE_CONTENT);
  1275.         else
  1276.             thirdparty_appid_module->session_attr_clear(session->tpsession, TP_ATTR_COPY_RESPONSE_CONTENT);
  1277.  
  1278.         if ((ptype_scan_counts[LOCATION_PT]))
  1279.             thirdparty_appid_module->session_attr_set(session->tpsession, TP_ATTR_COPY_RESPONSE_LOCATION);
  1280.         else
  1281.             thirdparty_appid_module->session_attr_clear(session->tpsession, TP_ATTR_COPY_RESPONSE_LOCATION);
  1282.  
  1283.         if ((ptype_scan_counts[BODY_PT]))
  1284.             thirdparty_appid_module->session_attr_set(session->tpsession, TP_ATTR_COPY_RESPONSE_BODY);
  1285.         else
  1286.             thirdparty_appid_module->session_attr_clear(session->tpsession, TP_ATTR_COPY_RESPONSE_BODY);
  1287.     }
  1288.  
  1289.     return retVal;
  1290. }
  1291.  
  1292. static void processCHP(tAppIdData *session, char **version, SFSnortPacket *p, const tAppIdConfig *pConfig)
  1293. {
  1294.     int i, size;
  1295.     int found_in_buffer = 0;
  1296.     char *new_url = NULL;
  1297.     char *new_cookie = NULL;
  1298.     char *user = NULL;
  1299.     tAppId chp_final;
  1300.     tAppId ret = 0;
  1301.     httpSession *http_session = session->hsession;
  1302.  
  1303.     char *chp_buffers[NUMBER_OF_PTYPES] = {
  1304.         http_session->useragent,
  1305.         http_session->host,
  1306.         http_session->referer,
  1307.         http_session->uri,
  1308.         http_session->cookie,
  1309.         http_session->req_body,
  1310.         http_session->content_type,
  1311.         http_session->location,
  1312.         http_session->body,
  1313.     };
  1314.  
  1315.     if (http_session->chp_hold_flow)
  1316.         http_session->chp_finished = 0;
  1317.  
  1318.     // For fragmented HTTP headers, do not process if none of the fields are set.
  1319.     // These fields will get set when the HTTP header is reassembled.
  1320.     if ((!http_session->useragent) && (!http_session->host) && (!http_session->referer) && (!http_session->uri))
  1321.         return;
  1322.  
  1323.     if (!http_session->chp_candidate)
  1324.     {
  1325.         for (i = 0; i < 4; i++)
  1326.         {
  1327.             if ((initial_CHP_sweep((PatternType)i, chp_buffers[i],
  1328.                             version, &user, &new_url, &new_cookie,
  1329.                             session, pConfig)))
  1330.                 break;
  1331.         }
  1332.         if (!http_session->chp_candidate)
  1333.             http_session->chp_finished = 1;
  1334.     }
  1335.     if (!http_session->chp_finished && http_session->chp_candidate)
  1336.     {
  1337.         for (i = 0; i < NUMBER_OF_PTYPES; i++)
  1338.         {
  1339.             if (ptype_scan_counts[i] && chp_buffers[i] && (size = strlen(chp_buffers[i])) > 0)
  1340.             {
  1341.                 found_in_buffer = 0;
  1342.                 ret = scanCHP((PatternType)i, chp_buffers[i], size, version,
  1343.                         &user, &new_url, &new_cookie, &found_in_buffer,
  1344.                         http_session, p, &pConfig->detectorHttpConfig);
  1345.                 http_session->total_found += found_in_buffer;
  1346.                 http_session->num_scans--;
  1347.                 ptype_scan_counts[i] = 0;
  1348.                 // Give up if scanCHP returns nothing, OR
  1349.                 // (if we did not match the right numbher of patterns in this field AND EITHER
  1350.                 // (there is no match quota [all must match]) OR
  1351.                 // (the total number of matches is less than our match quota))
  1352.                 if (!ret ||
  1353.                         (found_in_buffer < http_session->ptype_req_counts[i] &&
  1354.                          (!http_session->num_matches ||
  1355.                           http_session->total_found < http_session->num_matches)))
  1356.                 {
  1357.                     http_session->chp_candidate = 0;
  1358.                     break;
  1359.                 }
  1360.                 /* We are finished if we have a num_matches target and we've met it or
  1361.                    if we have done all the scans */
  1362.                 if (!http_session->num_scans ||
  1363.                         (http_session->num_matches && http_session->total_found >= http_session->num_matches))
  1364.  
  1365.                 {
  1366.                     http_session->chp_finished = 1;
  1367.                     break;
  1368.                 }
  1369.             }
  1370.             else if (ptype_scan_counts[i] && !http_session->chp_hold_flow)
  1371.             {
  1372.                 /* we have a scan count, but nothing in the buffer, so we should drop out of CHP */
  1373.                 http_session->chp_candidate = 0;
  1374.                 break;
  1375.             }
  1376.         }
  1377.         if (!http_session->chp_candidate)
  1378.         {
  1379.             http_session->chp_finished = 1;
  1380.             if (*version)
  1381.             {
  1382.                 free(*version);
  1383.                 *version = NULL;
  1384.             }
  1385.             if (user)
  1386.             {
  1387.                 free(user);
  1388.                 user = NULL;
  1389.             }
  1390.             if (new_url)
  1391.             {
  1392.                 free(new_url);
  1393.                 new_url = NULL;
  1394.             }
  1395.             if (new_cookie)
  1396.             {
  1397.                 free(new_cookie);
  1398.                 new_cookie = NULL;
  1399.             }
  1400.             memset(ptype_scan_counts, 0, 7 * sizeof(ptype_scan_counts[0]));
  1401.  
  1402.             // Make it possible for other detectors to run.
  1403.             http_session->skip_simple_detect = false;
  1404.             return;
  1405.         }
  1406.         if (http_session->chp_candidate && http_session->chp_finished)
  1407.         {
  1408.             chp_final = http_session->chp_alt_candidate ? http_session->chp_alt_candidate : http_session->chp_candidate;
  1409.             if (http_session->app_type_flags & APP_TYPE_SERVICE)
  1410.             {
  1411.                 setServiceAppIdData(session, chp_final, NULL, version);
  1412.             }
  1413.             if (http_session->app_type_flags & APP_TYPE_CLIENT)
  1414.             {
  1415.                 setClientAppIdData(session, chp_final, version);
  1416.             }
  1417.             if (http_session->app_type_flags & APP_TYPE_PAYLOAD)
  1418.             {
  1419.                 setPayloadAppIdData(session, chp_final, version);
  1420.             }
  1421.             if (http_session->fflow && http_session->fflow->flow_prepared)
  1422.             {
  1423.                 finalizeFflow(http_session->fflow, http_session->app_type_flags,
  1424.                               (http_session->fflow->appId ? http_session->fflow->appId : chp_final), p);
  1425.                 free(http_session->fflow);
  1426.                 http_session->fflow = NULL;
  1427.             }
  1428.             if (*version)
  1429.                 *version = NULL;
  1430.             if (user)
  1431.             {
  1432.                 session->username = user;
  1433.                 user = NULL;
  1434.                 if (http_session->app_type_flags & APP_TYPE_SERVICE)
  1435.                     session->usernameService = chp_final;
  1436.                 else
  1437.                     session->usernameService = session->serviceAppId;
  1438.                 setAppIdExtFlag(session, APPID_SESSION_LOGIN_SUCCEEDED);
  1439.             }
  1440.             if (new_url)
  1441.             {
  1442.                 if (app_id_debug_session_flag)
  1443.                     _dpd.logMsg("AppIdDbg %s rewritten url: %s\n", app_id_debug_session, new_url);
  1444.                 if (http_session->new_url)
  1445.                     free(http_session->new_url);
  1446.                 http_session->new_url = new_url;
  1447.                 new_url = NULL;
  1448.             }
  1449.             if (new_cookie)
  1450.             {
  1451.                 if (app_id_debug_session_flag)
  1452.                     _dpd.logMsg("AppIdDbg %s rewritten cookie: %s\n", app_id_debug_session, new_cookie);
  1453.                 if (http_session->new_cookie)
  1454.                     free(http_session->new_cookie);
  1455.                 http_session->new_cookie = new_cookie;
  1456.                 new_cookie = NULL;
  1457.             }
  1458.             http_session->chp_candidate = 0;
  1459.             //if we're doing safesearch rewrites, we want to continue to hold the flow
  1460.             if (!http_session->get_offsets_from_rebuilt)
  1461.                 http_session->chp_hold_flow = 0;
  1462.             session->scan_flags &= ~SCAN_HTTP_VIA_FLAG;
  1463.             session->scan_flags &= ~SCAN_HTTP_USER_AGENT_FLAG;
  1464.             session->scan_flags &= ~SCAN_HTTP_HOST_URL_FLAG;
  1465.             memset(ptype_scan_counts, 0, 7 * sizeof(ptype_scan_counts[0]));
  1466.         }
  1467.         else /* if we have a candidate, but we're not finished */
  1468.         {
  1469.             if (user)
  1470.             {
  1471.                 free(user);
  1472.                 user = NULL;
  1473.             }
  1474.             if (new_url)
  1475.             {
  1476.                 free(new_url);
  1477.                 new_url = NULL;
  1478.             }
  1479.             if (new_cookie)
  1480.             {
  1481.                 free(new_cookie);
  1482.                 new_cookie = NULL;
  1483.             }
  1484.         }
  1485.     }
  1486. }
  1487.  
  1488. static inline bool payloadAppIdIsSet(tAppIdData *session)
  1489. {
  1490.     return ( session->payloadAppId || session->tpPayloadAppId );
  1491. }
  1492.  
  1493. STATIC int processHTTPPacket(SFSnortPacket *p, tAppIdData *session, int direction, HttpParsedHeaders *const headers, const tAppIdConfig *pConfig)
  1494. {
  1495. #define RESPONSE_CODE_LENGTH 3
  1496.     HeaderMatchedPatterns hmp;
  1497.     httpSession *http_session;
  1498.     int start, end, size;
  1499.     char *version = NULL;
  1500.     char *vendorVersion = NULL;
  1501.     char *vendor = NULL;
  1502.     tAppId serviceAppId = 0;
  1503.     tAppId clientAppId = 0;
  1504.     tAppId payloadAppId = 0;
  1505.     tAppId referredPayloadAppId = 0;
  1506.     char *host;
  1507.     char *url;
  1508.     char *useragent;
  1509.     char *referer;
  1510.     char *via;
  1511.     PROFILE_VARS;
  1512.     PREPROC_PROFILE_START(httpPerfStats);
  1513.  
  1514.     http_session = session->hsession;
  1515.     if (!http_session)
  1516.     {
  1517.         clearSessionAppIdData(session);
  1518.         if (app_id_debug_session_flag)
  1519.             _dpd.logMsg("AppIdDbg %s attempt to process HTTP packet with no HTTP data\n", app_id_debug_session);
  1520.         PREPROC_PROFILE_END(httpPerfStats);
  1521.         return 0;
  1522.     }
  1523.  
  1524.     if (direction == APP_ID_FROM_RESPONDER && !getAppIdIntFlag(session, APPID_SESSION_RESPONSE_CODE_CHECKED))
  1525.     {
  1526.         if (http_session->response_code)
  1527.         {
  1528.             setAppIdIntFlag(session, APPID_SESSION_RESPONSE_CODE_CHECKED);
  1529.             if (strlen(http_session->response_code) != RESPONSE_CODE_LENGTH)
  1530.             {
  1531.                 /* received bad response code. Stop processing this session */
  1532.                 clearSessionAppIdData(session);
  1533.                 if (app_id_debug_session_flag)
  1534.                     _dpd.logMsg("AppIdDbg %s bad http response code\n", app_id_debug_session);
  1535.                 PREPROC_PROFILE_END(httpPerfStats);
  1536.                 return 0;
  1537.             }
  1538.         }
  1539. #if RESPONSE_CODE_PACKET_THRESHHOLD
  1540.         else if (++(http_session->response_code_packets) == RESPONSE_CODE_PACKET_THRESHHOLD)
  1541.         {
  1542.             setAppIdIntFlag(session, APPID_SESSION_RESPONSE_CODE_CHECKED);
  1543.             /* didn't receive response code in first X packets. Stop processing this session */
  1544.             clearSessionAppIdData(session);
  1545.             if (app_id_debug_session_flag)
  1546.                 _dpd.logMsg("AppIdDbg %s no response code received\n", app_id_debug_session);
  1547.             PREPROC_PROFILE_END(httpPerfStats);
  1548.             return 0;
  1549.         }
  1550. #endif
  1551.     }
  1552.  
  1553.     host = http_session->host;
  1554.     url = http_session->url;
  1555.     via = http_session->via;
  1556.     useragent = http_session->useragent;
  1557.     referer = http_session->referer;
  1558.     memset(&hmp, 0, sizeof(hmp));
  1559.  
  1560.     if (session->serviceAppId == APP_ID_NONE)
  1561.     {
  1562.         session->serviceAppId = APP_ID_HTTP;
  1563.         checkSandboxDetection(APP_ID_HTTP);
  1564.     }
  1565.  
  1566.     if (app_id_debug_session_flag)
  1567.         _dpd.logMsg("AppIdDbg %s chp_finished %d chp_hold_flow %d\n", app_id_debug_session, http_session->chp_finished, http_session->chp_hold_flow);
  1568.  
  1569.     if (!http_session->chp_finished || http_session->chp_hold_flow)
  1570.         processCHP(session, &version, p, pConfig);
  1571.  
  1572.     if (!http_session->skip_simple_detect)  // false unless a match happened with a call to processCHP().
  1573.     {
  1574.         if (!getAppIdIntFlag(session, APPID_SESSION_APP_REINSPECT))
  1575.         {
  1576.             // Scan Server Header for Vendor & Version
  1577.             if (getHTTPHeaderLocation(p->payload, p->payload_size, HTTP_ID_SERVER, &start, &end, &hmp, &pConfig->detectorHttpConfig) == 1)
  1578.             {
  1579.                 if (session->serviceAppId == APP_ID_NONE || session->serviceAppId == APP_ID_HTTP)
  1580.                 {
  1581.                     RNAServiceSubtype *subtype = NULL;
  1582.                     RNAServiceSubtype **tmpSubtype;
  1583.                     int len = end - start;
  1584.  
  1585.                     getServerVendorVersion(p->payload + start, len, &vendorVersion, &vendor, &subtype);
  1586.                     if (vendor || vendorVersion)
  1587.                     {
  1588.                         if (session->serviceVendor)
  1589.                         {
  1590.                             free(session->serviceVendor);
  1591.                             session->serviceVendor = NULL;
  1592.                         }
  1593.                         if (session->serviceVersion)
  1594.                         {
  1595.                             free(session->serviceVersion);
  1596.                             session->serviceVersion = NULL;
  1597.                         }
  1598.                         if (vendor)
  1599.                             session->serviceVendor = vendor;
  1600.                         if (vendorVersion)
  1601.                             session->serviceVersion = vendorVersion;
  1602.                     }
  1603.                     if (subtype)
  1604.                     {
  1605.                         for (tmpSubtype = &session->subtype; *tmpSubtype; tmpSubtype = &(*tmpSubtype)->next);
  1606.  
  1607.                         *tmpSubtype = subtype;
  1608.                     }
  1609.                 }
  1610.             }
  1611.  
  1612.             if (webdav_found(&hmp))
  1613.             {
  1614.                 if (app_id_debug_session_flag && payloadAppId > APP_ID_NONE && session->payloadAppId != payloadAppId)
  1615.                     _dpd.logMsg("AppIdDbg %s payload is webdav\n", app_id_debug_session);
  1616.                 setPayloadAppIdData(session, APP_ID_WEBDAV, NULL);
  1617.             }
  1618.  
  1619.             // Scan User-Agent for Browser types or Skype
  1620.             if ((session->scan_flags & SCAN_HTTP_USER_AGENT_FLAG) && session->clientAppId <= APP_ID_NONE && useragent && (size = strlen(useragent)) > 0)
  1621.             {
  1622.                 if (version)
  1623.                 {
  1624.                     free(version);
  1625.                     version = NULL;
  1626.                 }
  1627.                 identifyUserAgent((uint8_t *)useragent, size, &serviceAppId, &clientAppId, &version, &pConfig->detectorHttpConfig);
  1628.                 if (app_id_debug_session_flag && serviceAppId > APP_ID_NONE && serviceAppId != APP_ID_HTTP && session->serviceAppId != serviceAppId)
  1629.                     _dpd.logMsg("AppIdDbg %s User Agent is service %d\n", app_id_debug_session, serviceAppId);
  1630.                 setServiceAppIdData(session, serviceAppId, NULL, NULL);
  1631.                 if (app_id_debug_session_flag && clientAppId > APP_ID_NONE && clientAppId != APP_ID_HTTP && session->clientAppId != clientAppId)
  1632.                     _dpd.logMsg("AppIdDbg %s User Agent is client %d\n", app_id_debug_session, clientAppId);
  1633.                 setClientAppIdData(session, clientAppId, &version);
  1634.                 session->scan_flags &= ~SCAN_HTTP_USER_AGENT_FLAG;
  1635.             }
  1636.  
  1637.             /* Scan Via Header for squid */
  1638.             if (!payloadAppIdIsSet(session) && (session->scan_flags & SCAN_HTTP_VIA_FLAG) && via && (size = strlen(via)) > 0)
  1639.             {
  1640.                 if (version)
  1641.                 {
  1642.                     free(version);
  1643.                     version = NULL;
  1644.                 }
  1645.                 payloadAppId = getAppidByViaPattern((uint8_t *)via, size, &version, &pConfig->detectorHttpConfig);
  1646.                 if (app_id_debug_session_flag && payloadAppId > APP_ID_NONE && session->payloadAppId != payloadAppId)
  1647.                     _dpd.logMsg("AppIdDbg %s VIA is payload %d\n", app_id_debug_session, payloadAppId);
  1648.                 setPayloadAppIdData(session, payloadAppId, NULL);
  1649.                 session->scan_flags &= ~SCAN_HTTP_VIA_FLAG;
  1650.             }
  1651.         }
  1652.  
  1653.         /* Scan X-Working-With HTTP header */
  1654.         if (getHTTPHeaderLocation(p->payload, p->payload_size, HTTP_ID_X_WORKING_WITH, &start, &end, &hmp, &pConfig->detectorHttpConfig) == 1)
  1655.         {
  1656.             tAppId appId;
  1657.  
  1658.             appId = scan_header_x_working_with(p->payload + start, end - start, &version);
  1659.             if (appId)
  1660.             {
  1661.                 if (direction == APP_ID_FROM_INITIATOR)
  1662.                 {
  1663.                     if (app_id_debug_session_flag && clientAppId > APP_ID_NONE && clientAppId != APP_ID_HTTP && session->clientAppId != clientAppId)
  1664.                         _dpd.logMsg("AppIdDbg %s X is client %d\n", app_id_debug_session, appId);
  1665.                     setClientAppIdData(session, appId, &version);
  1666.                 }
  1667.                 else
  1668.                 {
  1669.                     if (app_id_debug_session_flag && serviceAppId > APP_ID_NONE && serviceAppId != APP_ID_HTTP && session->serviceAppId != serviceAppId)
  1670.                         _dpd.logMsg("AppIdDbg %s X is service %d\n", app_id_debug_session, appId);
  1671.                     setServiceAppIdData(session, appId, NULL, &version);
  1672.                 }
  1673.             }
  1674.         }
  1675.  
  1676.         // Scan Content-Type Header for multimedia types and scan contents
  1677.         if (!payloadAppIdIsSet(session) &&
  1678.             getHTTPHeaderLocation(p->payload, p->payload_size, HTTP_ID_CONTENT_TYPE, &start, &end, &hmp, &pConfig->detectorHttpConfig) == 1)
  1679.         {
  1680.             payloadAppId = getAppidByContentType(p->payload + start, end - start, &pConfig->detectorHttpConfig);
  1681.             if (app_id_debug_session_flag && payloadAppId > APP_ID_NONE && session->payloadAppId != payloadAppId)
  1682.                 _dpd.logMsg("AppIdDbg %s Content-Type is payload %d\n", app_id_debug_session, payloadAppId);
  1683.             setPayloadAppIdData(session, payloadAppId, NULL);
  1684.         }
  1685.  
  1686.         if (session->scan_flags & SCAN_HTTP_HOST_URL_FLAG)
  1687.         {
  1688.             if (version)
  1689.             {
  1690.                 free(version);
  1691.                 version = NULL;
  1692.             }
  1693.             if (getAppIdFromUrl(host, url, &version, referer, &clientAppId, &serviceAppId, &payloadAppId, &referredPayloadAppId, 0, &pConfig->detectorHttpConfig) == 1)
  1694.             {
  1695.                 // do not overwrite a previously-set client or service
  1696.                 if (session->clientAppId <= APP_ID_NONE)
  1697.                 {
  1698.                     if (app_id_debug_session_flag && clientAppId > APP_ID_NONE && clientAppId != APP_ID_HTTP && session->clientAppId != clientAppId)
  1699.                         _dpd.logMsg("AppIdDbg %s URL is client %d\n", app_id_debug_session, clientAppId);
  1700.                     setClientAppIdData(session, clientAppId, NULL);
  1701.                 }
  1702.                 if (session->serviceAppId <= APP_ID_NONE)
  1703.                 {
  1704.                     if (app_id_debug_session_flag && serviceAppId > APP_ID_NONE && serviceAppId != APP_ID_HTTP && session->serviceAppId != serviceAppId)
  1705.                         _dpd.logMsg("AppIdDbg %s URL is service %d\n", app_id_debug_session, serviceAppId);
  1706.                     setServiceAppIdData(session, serviceAppId, NULL, NULL);
  1707.                 }
  1708.                 // DO overwrite a previously-set payload
  1709.                 if (app_id_debug_session_flag && payloadAppId > APP_ID_NONE && session->payloadAppId != payloadAppId)
  1710.                     _dpd.logMsg("AppIdDbg %s URL is payload %d\n", app_id_debug_session, payloadAppId);
  1711.                 setPayloadAppIdData(session, payloadAppId, &version);
  1712.                 setReferredPayloadAppIdData(session, referredPayloadAppId);
  1713.             }
  1714.             session->scan_flags &= ~SCAN_HTTP_HOST_URL_FLAG;
  1715.         }
  1716.  
  1717.         if (session->clientAppId == APP_ID_APPLE_CORE_MEDIA)
  1718.         {
  1719.             if (session->tpPayloadAppId > APP_ID_NONE)
  1720.             {
  1721.                 session->miscAppId = session->clientAppId;
  1722.                 session->clientAppId = session->tpPayloadAppId + GENERIC_APP_OFFSET;
  1723.             }
  1724.             else if (session->payloadAppId > APP_ID_NONE)
  1725.             {
  1726.                 session->miscAppId = session->clientAppId;
  1727.                 session->clientAppId = session->payloadAppId + GENERIC_APP_OFFSET;
  1728.             }
  1729.         }
  1730.  
  1731.         if (!getAppIdExtFlag(session, APPID_SESSION_SPDY_SESSION))
  1732.         {
  1733.             clearAppIdIntFlag(session, APPID_SESSION_CHP_INSPECTING);
  1734.             if (thirdparty_appid_module)
  1735.                 thirdparty_appid_module->session_attr_clear(session->tpsession, TP_ATTR_CONTINUE_MONITORING);
  1736.         }
  1737.     }  // end DON'T skip_simple_detect
  1738.  
  1739.     PREPROC_PROFILE_END(httpPerfStats);
  1740.     return 0;
  1741. }
  1742.  
  1743. static  inline void stopRnaServiceInspection(SFSnortPacket *p, tAppIdData* session, int direction)
  1744. {
  1745.     sfaddr_t *ip;
  1746.     if (direction == APP_ID_FROM_INITIATOR)
  1747.     {
  1748.         ip = GET_DST_IP(p);
  1749.         session->service_ip = *ip;
  1750.         session->service_port = p->dst_port;
  1751.     }
  1752.     else
  1753.     {
  1754.         ip = GET_SRC_IP(p);
  1755.         session->service_ip = *ip;
  1756.         session->service_port = p->src_port;
  1757.     }
  1758.     session->rnaServiceState = RNA_STATE_FINISHED;
  1759.     setAppIdExtFlag(session, APPID_SESSION_SERVICE_DETECTED);
  1760.     clearAppIdExtFlag(session, APPID_SESSION_CONTINUE);
  1761. #ifdef DEBUG_FW_APPID
  1762. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  1763.     if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  1764. #endif
  1765.         fprintf(SF_DEBUG_FILE, "%u -> %u %d stopping RNA service inspection\n",
  1766.             (unsigned)p->src_port, (unsigned)p->dst_port, IsTCP(p)? IPPROTO_TCP:IPPROTO_UDP);
  1767. #endif
  1768. }
  1769. static bool isSslDecryptionEnabled(tAppIdData *session)
  1770. {
  1771.     if (getAppIdExtFlag(session, APPID_SESSION_DECRYPTED))
  1772.         return 1;
  1773. #ifdef UNIT_TESTING
  1774.     if (session->session_packet_count >= 12)
  1775.         return 1;
  1776.     return 0;
  1777. #else
  1778.     return _dpd.streamAPI->is_session_decrypted(session->ssn);
  1779. #endif
  1780. }
  1781.  
  1782. static void  checkRestartAppDetection(tAppIdData *session)
  1783. {
  1784.     if (getAppIdExtFlag(session, APPID_SESSION_DECRYPTED)) return;
  1785.     if (!isSslDecryptionEnabled(session)) return;
  1786.  
  1787.     bool isSsl = isSslServiceAppId(pickServiceAppId(session));
  1788.  
  1789.     // A session could either:
  1790.     // 1. Start of as SSL - captured with isSsl flag, OR
  1791.     // 2. It could start of as a non-SSL session and later change to SSL. For example, FTP->FTPS.
  1792.     //    In this case APPID_SESSION_ENCRYPTED flag is set by the protocol state machine.
  1793.     if (getAppIdExtFlag(session, APPID_SESSION_ENCRYPTED) || isSsl)
  1794.     {
  1795. #ifdef DEBUG_FW_APPID
  1796.         fprintf(SF_DEBUG_FILE, "SSL decryption is available, restarting app Detection\n");
  1797. #endif
  1798.         setAppIdExtFlag(session, APPID_SESSION_DECRYPTED);
  1799.         appSaveEncryptedApps(session);
  1800.         appSharedReInitData(session);
  1801.         if (app_id_debug_session_flag)
  1802.             _dpd.logMsg("AppIdDbg %s SSL decryption is available, restarting app Detection\n", app_id_debug_session);
  1803.  
  1804.         // APPID_SESSION_ENCRYPTED is set upon receiving a command which upgrades the session to SSL.
  1805.         // Next packet after the command will have encrypted traffic.
  1806.         // In the case of a session which starts as SSL, current packet itself is encrypted. Set the special flag
  1807.         // APPID_SESSION_APP_REINSPECT_SSL which allows reinspection of this pcaket.
  1808.         if (isSsl) setAppIdIntFlag(session, APPID_SESSION_APP_REINSPECT_SSL);
  1809.     }
  1810. }
  1811.  
  1812. static void updateEncryptedAppId( tAppIdData *session)
  1813. {
  1814.     if (getAppIdExtFlag(session, APPID_SESSION_DECRYPTED))
  1815.     {
  1816.         switch (pickServiceAppId(session))
  1817.         {
  1818.             case APP_ID_HTTP:
  1819.                 if (session->miscAppId == APP_ID_NSIIOPS || session->miscAppId == APP_ID_DDM_SSL
  1820.                         || session->miscAppId == APP_ID_MSFT_GC_SSL || session->miscAppId == APP_ID_SF_APPLIANCE_MGMT)
  1821.                 {
  1822.                     break;
  1823.                 }
  1824.                 session->miscAppId = APP_ID_HTTPS;
  1825.                 break;
  1826.             case APP_ID_SMTP:
  1827.                 session->miscAppId = APP_ID_SMTPS;
  1828.                 break;
  1829.             case APP_ID_NNTP:
  1830.                 session->miscAppId = APP_ID_NNTPS;
  1831.                 break;
  1832.             case APP_ID_IMAP:
  1833.                 session->miscAppId = APP_ID_IMAPS;
  1834.                 break;
  1835.             case APP_ID_SHELL:
  1836.                 session->miscAppId = APP_ID_SSHELL;
  1837.                 break;
  1838.             case APP_ID_LDAP:
  1839.                 session->miscAppId = APP_ID_LDAPS;
  1840.                 break;
  1841.             case APP_ID_FTP_DATA:
  1842.                 session->miscAppId = APP_ID_FTPSDATA;
  1843.                 break;
  1844.             case APP_ID_FTP:
  1845.                 session->miscAppId = APP_ID_FTPS;
  1846.                 break;
  1847.             case APP_ID_TELNET:
  1848.                 session->miscAppId = APP_ID_TELNET;
  1849.                 break;
  1850.             case APP_ID_IRC:
  1851.                 session->miscAppId = APP_ID_IRCS;
  1852.                 break;
  1853.             case APP_ID_POP3:
  1854.                 session->miscAppId = APP_ID_POP3S;
  1855.                 break;
  1856.             default:
  1857.                 break;
  1858.         }
  1859.     }
  1860. }
  1861.  
  1862. static void ExamineSslMetadata(SFSnortPacket *p, tAppIdData *session, tAppIdConfig *pConfig)
  1863. {
  1864.     size_t size;
  1865.     int ret;
  1866.     tAppId clientAppId = 0;
  1867.     tAppId payloadAppId = 0;
  1868.  
  1869.     if ((session->scan_flags & SCAN_SSL_HOST_FLAG) && session->tsession->tls_host)
  1870.     {
  1871.         size = strlen(session->tsession->tls_host);
  1872.         if ((ret = ssl_scan_hostname((const u_int8_t *)session->tsession->tls_host, size, &clientAppId, &payloadAppId, &pConfig->serviceSslConfig)))
  1873.         {
  1874.             setClientAppIdData(session, clientAppId, NULL);
  1875.             setPayloadAppIdData(session, payloadAppId, NULL);
  1876.             setSSLSquelch(p, ret, (ret == 1 ? payloadAppId : clientAppId));
  1877.         }
  1878.         session->scan_flags &= ~SCAN_SSL_HOST_FLAG;
  1879.         // ret = 0;
  1880.     }
  1881.     if (session->tsession->tls_cname)
  1882.     {
  1883.         size = strlen(session->tsession->tls_cname);
  1884.         if ((ret = ssl_scan_cname((const u_int8_t *)session->tsession->tls_cname, size, &clientAppId, &payloadAppId, &pConfig->serviceSslConfig)))
  1885.         {
  1886.             setClientAppIdData(session, clientAppId, NULL);
  1887.             setPayloadAppIdData(session, payloadAppId, NULL);
  1888.             setSSLSquelch(p, ret, (ret == 1 ? payloadAppId : clientAppId));
  1889.         }
  1890.         free(session->tsession->tls_cname);
  1891.         session->tsession->tls_cname = NULL;
  1892.         // ret = 0;
  1893.     }
  1894.     if (session->tsession->tls_orgUnit)
  1895.     {
  1896.         size = strlen(session->tsession->tls_orgUnit);
  1897.         if ((ret = ssl_scan_cname((const u_int8_t *)session->tsession->tls_orgUnit, size, &clientAppId, &payloadAppId, &pConfig->serviceSslConfig)))
  1898.         {
  1899.             setClientAppIdData(session, clientAppId, NULL);
  1900.             setPayloadAppIdData(session, payloadAppId, NULL);
  1901.             setSSLSquelch(p, ret, (ret == 1 ? payloadAppId : clientAppId));
  1902.         }
  1903.         free(session->tsession->tls_orgUnit);
  1904.         session->tsession->tls_orgUnit = NULL;
  1905.         // ret = 0;
  1906.     }
  1907. }
  1908.  
  1909. static int RunClientDetectors(tAppIdData *session,
  1910.                               SFSnortPacket *p,
  1911.                               int direction,
  1912.                               tAppIdConfig *pConfig)
  1913. {
  1914.     int ret = CLIENT_APP_INPROCESS;
  1915.  
  1916.     if (session->clientData != NULL)
  1917.     {
  1918.         ret = session->clientData->validate(p->payload, p->payload_size, direction,
  1919.                                             session, p, session->clientData->userData, pConfig);
  1920.         if (app_id_debug_session_flag)
  1921.             _dpd.logMsg("AppIdDbg %s %s client detector returned %d\n", app_id_debug_session,
  1922.                         session->clientData->name ? session->clientData->name:"UNKNOWN", ret);
  1923.     }
  1924.     else if (    (session->candidate_client_list != NULL)
  1925.               && (sflist_count(session->candidate_client_list) > 0) )
  1926.     {
  1927.         SF_LNODE *node;
  1928.         tRNAClientAppModule *client;
  1929.  
  1930.         ret = CLIENT_APP_INPROCESS;
  1931.         node = sflist_first_node(session->candidate_client_list);
  1932.         while (node != NULL)
  1933.         {
  1934.             int result;
  1935.             SF_LNODE *node_tmp;
  1936.  
  1937.             client = (tRNAClientAppModule*)SFLIST_NODE_TO_DATA(node);
  1938.             result = client->validate(p->payload, p->payload_size, direction,
  1939.                                       session, p, client->userData, pConfig);
  1940.             if (app_id_debug_session_flag)
  1941.                 _dpd.logMsg("AppIdDbg %s %s client detector returned %d\n", app_id_debug_session,
  1942.                             client->name ? client->name:"UNKNOWN", ret);
  1943.  
  1944.             node_tmp = node;
  1945.             node = sflist_next_node(session->candidate_client_list);
  1946.             if (result == CLIENT_APP_SUCCESS)
  1947.             {
  1948.                 ret = CLIENT_APP_SUCCESS;
  1949.                 session->clientData = client;
  1950.                 sflist_free(session->candidate_client_list);
  1951.                 session->candidate_client_list = NULL;
  1952.                 break;    /* done */
  1953.             }
  1954.             else if (result != CLIENT_APP_INPROCESS)    /* fail */
  1955.             {
  1956.                 sflist_remove_node(session->candidate_client_list, node_tmp);
  1957.             }
  1958.         }
  1959.     }
  1960.  
  1961.     return ret;
  1962. }
  1963.  
  1964. void getOffsetsFromRebuilt(SFSnortPacket *pkt, httpSession *hsession)
  1965. {
  1966. // size of "GET /\r\n\r\n"
  1967. #define MIN_HTTP_REQ_HEADER_SIZE 9
  1968.     const uint8_t cookieStr[] = "Cookie: ";
  1969.     unsigned cookieStrLen = sizeof(cookieStr)-1;
  1970.     const uint8_t crlf[] = "\r\n";
  1971.     unsigned crlfLen = sizeof(crlf)-1;
  1972.     const uint8_t crlfcrlf[] = "\r\n\r\n";
  1973.     unsigned crlfcrlfLen = sizeof(crlfcrlf)-1;
  1974.     const uint8_t* p;
  1975.     uint8_t *headerEnd;
  1976.     uint16_t headerSize;
  1977.  
  1978.     if (!pkt || !pkt->payload || pkt->payload_size < MIN_HTTP_REQ_HEADER_SIZE)
  1979.         return;
  1980.  
  1981.     p = pkt->payload;
  1982.  
  1983.     if (!(headerEnd = (uint8_t *)service_strstr(p, pkt->payload_size, crlfcrlf, crlfcrlfLen)))
  1984.         return;
  1985.  
  1986.     headerEnd += crlfcrlfLen;
  1987.  
  1988.     headerSize = headerEnd - p;
  1989.  
  1990.     //uri offset is the index of the first char after the first space in the payload
  1991.     if (!(p = (uint8_t *)memchr(pkt->payload, ' ', headerSize)))
  1992.         return;
  1993.     hsession->uriOffset = ++p - pkt->payload;
  1994.     headerSize = headerEnd - p;
  1995.  
  1996.     //uri end offset is the index of the first CRLF sequence after uri offset
  1997.     if (!(p = (uint8_t *)service_strstr(p, headerSize, crlf, crlfLen)))
  1998.     {
  1999.         // clear uri offset if we can't find an end offset
  2000.         hsession->uriOffset = 0;
  2001.         return;
  2002.     }
  2003.     hsession->uriEndOffset = p - pkt->payload;
  2004.     headerSize = headerEnd - p;
  2005.  
  2006.     //cookie offset is the index of the first char after the cookie header, "Cookie: "
  2007.     if (!(p = (uint8_t *)service_strstr(p, headerSize, cookieStr, cookieStrLen)))
  2008.         return;
  2009.     hsession->cookieOffset = p + cookieStrLen - pkt->payload;
  2010.     headerSize = headerEnd - p;
  2011.  
  2012.     //cookie end offset is the index of the first CRLF sequence after cookie offset
  2013.     if (!(p = (uint8_t *)service_strstr(p, headerSize, crlf, crlfLen)))
  2014.     {
  2015.         // clear cookie offset if we can't find a cookie end offset
  2016.         hsession->cookieOffset = 0;
  2017.         return;
  2018.     }
  2019.     hsession->cookieEndOffset = p - pkt->payload;
  2020. }
  2021.  
  2022. static inline void setAppIdContinueForSSL(tAppIdData *session)
  2023. {
  2024.     if (!getAppIdExtFlag(session, APPID_SESSION_DECRYPTED) &&
  2025.         isSslServiceAppId(pickServiceAppId(session)) &&
  2026.         _dpd.isSSLPolicyEnabled(NULL))
  2027.     {
  2028.         setAppIdExtFlag(session, APPID_SESSION_CONTINUE);
  2029.     }
  2030. }
  2031.  
  2032. static int16_t snortId_for_ftp;
  2033. static int16_t snortId_for_ftp_data;
  2034. static int16_t snortId_for_imap;
  2035. static int16_t snortId_for_pop3;
  2036. static int16_t snortId_for_smtp;
  2037.  
  2038. static inline void synchAppIdWithSnortId(tAppId newAppId, SFSnortPacket *p, tAppIdData *session, tAppIdConfig *pConfig)
  2039. {
  2040.     AppInfoTableEntry *entry;
  2041.     int16_t tempSnortId = session->snortId;
  2042.  
  2043.     if (tempSnortId == UNSYNCED_SNORT_ID)
  2044.     {
  2045.         tempSnortId = session->snortId = _dpd.sessionAPI->get_application_protocol_id(p->stream_session);
  2046.     }
  2047.     if (tempSnortId == snortId_for_ftp || tempSnortId == snortId_for_ftp_data ||
  2048.         tempSnortId == snortId_for_imap || tempSnortId == snortId_for_pop3 ||
  2049.         tempSnortId == snortId_for_smtp)
  2050.     {
  2051.         return; // FTP, IMAP, POP3, and SMTP preprocessors, in snort proper, already know and expect these to remain unchanged.
  2052.     }
  2053.     if ((entry = appInfoEntryGet(newAppId, pConfig)) && (tempSnortId = entry->snortId) && tempSnortId != session->snortId)
  2054.     {
  2055.         _dpd.sessionAPI->set_application_protocol_id(p->stream_session, tempSnortId);
  2056.         session->snortId = tempSnortId;
  2057.     }
  2058. }
  2059.  
  2060. void fwAppIdInit(void)
  2061. {
  2062.     /* init globals for snortId compares */
  2063.     snortId_for_ftp      = _dpd.findProtocolReference("ftp");
  2064.     snortId_for_ftp_data = _dpd.findProtocolReference("ftp-data");
  2065.     snortId_for_imap     = _dpd.findProtocolReference("imap");
  2066.     snortId_for_pop3     = _dpd.findProtocolReference("pop3");
  2067.     snortId_for_smtp     = _dpd.findProtocolReference("smtp");
  2068. }
  2069. int tcp_count=0,udp_count=0,count=0;
  2070. //const FILE *fps = fopen("/root/Desktop/sessions.txt","a");
  2071. const char* getField(char *line, int num)
  2072. {
  2073.     const char *tok;
  2074.     for(tok=strtok(line,",");tok && *tok;tok=strtok(NULL,",\n"))
  2075.     {
  2076.         if(!--num)
  2077.         {
  2078.             return tok;
  2079.         }
  2080.     }
  2081.     return NULL;
  2082.    
  2083. }
  2084. void fwAppIdSearch(SFSnortPacket *p)
  2085. {
  2086.  
  2087.     tAppIdData *session;
  2088.     uint8_t protocol;
  2089.     tAppId tpAppId = 0;
  2090.     tAppId clientAppId = 0;
  2091.     tAppId payloadAppId = 0;
  2092.     unsigned flow_flags;
  2093.     int direction;
  2094.     sfaddr_t *ip;
  2095.     uint16_t port;
  2096.     size_t size;
  2097.     int tp_confidence;
  2098.     tAppId* tp_proto_list;
  2099.     ThirdPartyAppIDAttributeData* tp_attribute_data;
  2100. #ifdef TARGET_BASED
  2101.     AppInfoTableEntry *entry;
  2102. #endif
  2103.     tAppIdConfig *pConfig = appIdActiveConfigGet();
  2104.  
  2105.     app_id_raw_packet_count++;
  2106.  
  2107. /*tanmay*/
  2108. IP4Hdr *head = (IP4Hdr *)p->ip4h;
  2109.  
  2110. TCPHeader *tcpHead = (TCPHeader *)p->tcp_header;
  2111. UDPHeader *udpHead = (UDPHeader *)p->udp_header;
  2112.  
  2113. FILE *fp = fopen("/root/Desktop/packets.txt","a");
  2114.  
  2115. sfaddr_t *ipsource;
  2116. sfaddr_t *ipdst;
  2117. uint16_t sport, dport;
  2118. int f_tcp=0,f_udp=0;
  2119.    
  2120.  
  2121. if(head != NULL)
  2122. {
  2123.    
  2124.    
  2125.     ipsource = &((IPAddresses *)head->ip_addrs)->ip_src;
  2126.     ipdst = &((IPAddresses *)head->ip_addrs)->ip_dst;
  2127.  
  2128.     char srcip[INET6_ADDRSTRLEN];
  2129.     char dstip[INET6_ADDRSTRLEN];
  2130.  
  2131.     srcip[0] = 0;
  2132.        
  2133.     inet_ntop(sfaddr_family(ipsource), (void *)sfaddr_get_ptr(ipsource), srcip, sizeof(srcip));
  2134.     dstip[0] = 0;
  2135.  
  2136.         inet_ntop(sfaddr_family(ipdst), (void *)sfaddr_get_ptr(ipdst), dstip, sizeof(dstip));
  2137.  
  2138.     uint8_t ipver = head->ip_verhl >> 4;
  2139.     uint8_t iphl = (head->ip_verhl & 15)*4;
  2140.     uint8_t iptos = head->ip_tos;
  2141.     uint16_t iplen = head->ip_len;  //?
  2142.     uint16_t ipid = head->ip_id;
  2143.     uint16_t ipoff = head->ip_off;  //?
  2144.     uint8_t ipttl = head->ip_ttl;
  2145.     uint8_t ipproto = head->ip_proto;
  2146.     uint16_t ipcsum = head->ip_csum;
  2147.  
  2148.     fprintf(fp,"%d\tIP:\t%u,",++count,ipver);
  2149.     fprintf(fp,"%u,",iphl);
  2150.     fprintf(fp,"0x%X,",iptos);
  2151.     fprintf(fp,"%u,",iplen);
  2152.     fprintf(fp,"0x%X,",ipid);
  2153.     fprintf(fp,"flags,");
  2154.     fprintf(fp,"%u,",ipoff);
  2155.     fprintf(fp,"%u,",ipttl);
  2156.     fprintf(fp,"%u,",ipproto);
  2157.     fprintf(fp,"0x%X,",ipcsum);
  2158.     fprintf(fp,"%s,",srcip);
  2159.     fprintf(fp,"%s,",dstip);
  2160.     fprintf(fp,"options\n");
  2161.  
  2162. /*
  2163.     fprintf(fps,"\n%u,",(head->ip_addrs)->ip_src);
  2164.     fprintf(fps,"%u,",(head->ip_addrs)->ip_dst);
  2165. */ 
  2166. }
  2167.  
  2168. if(tcpHead != NULL)
  2169. {
  2170.     tcp_count++;
  2171.     sport = tcpHead->source_port;
  2172.     dport = tcpHead->destination_port;
  2173.     uint32_t seq = tcpHead->sequence;
  2174.     uint32_t ack = tcpHead->acknowledgement;
  2175.     uint8_t offset = tcpHead->offset_reserved;
  2176.     uint8_t flags = tcpHead->flags;
  2177.     uint16_t window = tcpHead->window;
  2178.     uint16_t check = tcpHead->checksum;
  2179.     uint16_t urgent = tcpHead->urgent_pointer;
  2180.  
  2181.     fprintf(fp,"TCP:\t%u,",sport);
  2182.     fprintf(fp,"%u,",dport);
  2183.     fprintf(fp,"%u,",seq);
  2184.     fprintf(fp,"%u,",ack);
  2185.     fprintf(fp,"%u,",offset);
  2186.     fprintf(fp,"%u,",flags);
  2187.     fprintf(fp,"%u,",window);
  2188.     fprintf(fp,"%u,",check);
  2189.     fprintf(fp,"%u\n",urgent);
  2190.  
  2191.     f_tcp=1;
  2192. /*
  2193.     fprintf(fps,"%u,",sport);
  2194.     fprintf(fps,"%u,",dport);
  2195. */ 
  2196. }
  2197. else
  2198. {
  2199.     f_tcp=0;
  2200. }
  2201.  
  2202. if(udpHead != NULL)
  2203. {
  2204.     udp_count++;
  2205.     sport = udpHead->source_port;
  2206.         dport = udpHead->destination_port;
  2207.         uint16_t leng = udpHead->data_length;
  2208.         uint16_t check = udpHead->checksum;
  2209.  
  2210.     fprintf(fp,"UDP:\t%u,",sport);
  2211.     fprintf(fp,"%u,",dport);
  2212.     fprintf(fp,"%u,",leng);
  2213.     fprintf(fp,"%u\n",check);
  2214.     f_udp=1;
  2215. /* 
  2216.     fprintf(fps,"%u,",src);
  2217.     fprintf(fps,"%u,",des);
  2218. */
  2219. }
  2220. else
  2221. {
  2222.     f_udp=0;
  2223. }
  2224.  
  2225. fclose(fp);
  2226.  
  2227. initializeHash(500);
  2228.  
  2229. printf("\n IPSource : %u \t IPDest : %u \t SourcePort : %u \t DestPort : %u \n",(ipsource),(ipdst),sport,dport);
  2230. if(f_tcp || f_udp)
  2231. {
  2232.     printf("\n TCP/UDP ");
  2233. printf(" IPSource : %u \t IPDest : %u \t SourcePort : %u \t DestPort : %u \n",(ipsource),(ipdst),sport,dport);
  2234. //printf("\n IPSource : %u \t IPDest : %u \t SourcePort : %u \t DestPort : %u \n",(ipsource),(ipdst),sport,dport);
  2235.     if(searchInHash((ipsource),(ipdst),sport,dport))
  2236.     {
  2237.     //add cumulative info
  2238.     }
  2239. /*  else
  2240.     {
  2241.  
  2242.         uint16_t sessid= (uint16_t)getSessionId();
  2243.  
  2244.         if(searchElement(sessid))
  2245.         {
  2246.             deleteFromHashbySessId(sessid);
  2247.             deletion(sessid);
  2248.                 //reapeating one need to be removed from both avl and hash
  2249.         }
  2250.  
  2251.         insertToHash(ipsource,ipdst,sport,dport,sessid);
  2252.        
  2253.    
  2254.     }*/
  2255. }
  2256. /*else
  2257. {
  2258.     printf("\n No Source and Destination port \n");
  2259. }*/
  2260.  
  2261. /*FILE *fps = fopen("/root/Desktop/sessions.txt","r");
  2262.  
  2263. char line[1024];
  2264. while(fgets(line,1024,fps))
  2265. {
  2266.     char *tmp = strdup(line);
  2267.     if(((uint32_t)atoi(getField(tmp,1)))== ((uint32_t)ipsource) && ((uint16_t)atoi(getField(tmp,3)))== ((uint16_t)sport))
  2268.     {
  2269.          if(((uint32_t)atoi(getField(tmp,2)))== ((uint32_t)ipdst) && ((uint16_t)atoi(getField(tmp,3)))== ((uint16_t)dport))
  2270.          {
  2271.             //TODO
  2272.             printf("\nsession detected");
  2273.          }
  2274.     }
  2275.     else if(((uint32_t)atoi(getField(tmp,2)))== ((uint32_t)ipdst) && ((uint16_t)atoi(getField(tmp,3)))== ((uint16_t)dport))
  2276.     {
  2277.         if(((uint32_t)atoi(getField(tmp,1)))== ((uint32_t)ipsource) && ((uint16_t)atoi(getField(tmp,3)))== ((uint16_t)sport))
  2278.         {
  2279.             //TODO session detected
  2280.             printf("\nsession detected");
  2281.         }
  2282.     }
  2283. //  printf("%s %s %s %s\n",getField(tmp,1),getField(tmp,2),getField(tmp,3),getField(tmp,4));
  2284.    
  2285. }
  2286.  
  2287. */
  2288. /*tanmay end*/
  2289.  
  2290.     if (!p->stream_session)
  2291.     {
  2292.         app_id_ignored_packet_count++;
  2293.         return;
  2294.     }
  2295.  
  2296.     if (p->flags & FLAG_REBUILT_STREAM && _dpd.streamAPI->is_session_decrypted(p->stream_session) == false)
  2297.     {
  2298.         session = getAppIdData(p->stream_session);
  2299.         if (session && session->hsession && session->hsession->get_offsets_from_rebuilt)
  2300.         {
  2301.             getOffsetsFromRebuilt(p, session->hsession);
  2302.             if (app_id_debug_session_flag)
  2303.                 _dpd.logMsg("AppIdDbg %s offsets from rebuilt packet: uri: %u-%u cookie: %u-%u\n", app_id_debug_session, session->hsession->uriOffset, session->hsession->uriEndOffset, session->hsession->cookieOffset, session->hsession->cookieEndOffset);
  2304.         }
  2305.         app_id_ignored_packet_count++;
  2306.         return;
  2307.     }
  2308.  
  2309.     SetPacketRealTime(p->pkt_header->ts.tv_sec);
  2310.  
  2311.     session = appSharedGetData(p);
  2312.     if (session)
  2313.     {
  2314. #ifdef DEBUG_APP_ID_SESSIONS
  2315. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  2316.         if (session->service_port == DEBUG_FW_APPID_PORT)
  2317. #endif
  2318.         {
  2319.             char src_ip[INET6_ADDRSTRLEN];
  2320.             char dst_ip[INET6_ADDRSTRLEN];
  2321.  
  2322.             src_ip[0] = 0;
  2323.             ip = GET_SRC_IP(p);
  2324.             inet_ntop(sfaddr_family(ip), (void *)sfaddr_get_ptr(ip), src_ip, sizeof(src_ip));
  2325.             dst_ip[0] = 0;
  2326.             ip = GET_DST_IP(p);
  2327.             inet_ntop(sfaddr_family(ip), (void *)sfaddr_get_ptr(ip), dst_ip, sizeof(dst_ip));
  2328.             fprintf(SF_DEBUG_FILE, "AppId Session %p %p for %s-%u -> %s-%u %d\n", session, session->ssn, src_ip,
  2329.                     (unsigned)p->src_port, dst_ip, (unsigned)p->dst_port, IsTCP(p) ? IPPROTO_TCP:IPPROTO_UDP);
  2330.         }
  2331. #endif
  2332.         if (session->common.fsf_type.flow_type == APPID_SESSION_TYPE_IGNORE)
  2333.             return;
  2334.         if (session->common.fsf_type.flow_type == APPID_SESSION_TYPE_NORMAL)
  2335.         {
  2336.             protocol = session->proto;
  2337.             session->ssn = p->stream_session;
  2338.         }
  2339.         else if (IsTCP(p))
  2340.             protocol = IPPROTO_TCP;
  2341.         else
  2342.             protocol = IPPROTO_UDP;
  2343.         ip = GET_SRC_IP(p);
  2344.         if (session->common.initiator_port)
  2345.             direction = (session->common.initiator_port == p->src_port) ? APP_ID_FROM_INITIATOR : APP_ID_FROM_RESPONDER;
  2346.         else
  2347.             direction = (sfip_fast_equals_raw(ip, &session->common.initiator_ip)) ? APP_ID_FROM_INITIATOR : APP_ID_FROM_RESPONDER;
  2348.     }
  2349.     else
  2350.     {
  2351.         if (IsTCP(p))
  2352.             protocol = IPPROTO_TCP;
  2353.         else if (IsUDP(p))
  2354.             protocol = IPPROTO_UDP;
  2355.         else if (p->ip4h)
  2356.             protocol = p->ip4h->ip_proto;
  2357.         else if (p->ip6h)
  2358.             protocol = p->ip6h->next;
  2359.         else
  2360.             return;
  2361.         direction = (_dpd.sessionAPI->get_packet_direction(p) & FLAG_FROM_CLIENT) ? APP_ID_FROM_INITIATOR : APP_ID_FROM_RESPONDER;
  2362.     }
  2363.  
  2364. #ifdef DEBUG_FW_APPID
  2365. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  2366.     if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  2367. #endif
  2368.     {
  2369.         char sipstr[INET6_ADDRSTRLEN];
  2370.         char dipstr[INET6_ADDRSTRLEN];
  2371.  
  2372.         sipstr[0] = 0;
  2373.         ip = GET_SRC_IP(p);
  2374.         inet_ntop(sfaddr_family(ip), (void *)sfaddr_get_ptr(ip), sipstr, sizeof(sipstr));
  2375.         dipstr[0] = 0;
  2376.         ip = GET_DST_IP(p);
  2377.         inet_ntop(sfaddr_family(ip), (void *)sfaddr_get_ptr(ip), dipstr, sizeof(dipstr));
  2378.         fprintf(SF_DEBUG_FILE, "%s-%u -> %s-%u %u\n", sipstr, (unsigned)p->src_port, dipstr, (unsigned)p->dst_port, (unsigned)protocol);
  2379.         /*DumpHex(SF_DEBUG_FILE, p->payload, p->payload_size); */
  2380.     }
  2381. #endif
  2382.  
  2383.     app_id_debug_session_flag = fwAppIdDebugCheck(p->stream_session, session, app_id_debug_flag,
  2384.             &app_id_debug_info, app_id_debug_session, direction);
  2385.  
  2386.     // fwAppIdSearch() is a top-level function that is called by AppIdProcess().
  2387.     // At this point, we know that we need to use the current active config -
  2388.     // pAppidActiveConfig. This function uses pAppidActiveConfig and passes it
  2389.     // to all the functions that need to look at AppId config.
  2390.     flow_flags = isSessionMonitored(p, direction, session);
  2391.     if (!(flow_flags & (APPID_SESSION_DISCOVER_APP | APPID_SESSION_SPECIAL_MONITORED)))
  2392.     {
  2393.         if (!session)
  2394.         {
  2395.             if ((flow_flags & APPID_SESSION_BIDIRECTIONAL_CHECKED) == APPID_SESSION_BIDIRECTIONAL_CHECKED)
  2396.             {
  2397.                 static APPID_SESSION_STRUCT_FLAG ignore_fsf = {.flow_type = APPID_SESSION_TYPE_IGNORE};
  2398.                 _dpd.sessionAPI->set_application_data(p->stream_session, PP_APP_ID, &ignore_fsf, NULL);
  2399.                 if (app_id_debug_session_flag)
  2400.                     _dpd.logMsg("AppIdDbg %s not monitored\n", app_id_debug_session);
  2401.             }
  2402.             else
  2403.             {
  2404.                 tTmpAppIdData *tmp_session;
  2405.  
  2406.                 if (tmp_app_id_free_list)
  2407.                 {
  2408.                     tmp_session = tmp_app_id_free_list;
  2409.                     tmp_app_id_free_list = tmp_session->next;
  2410.                 }
  2411.                 else if (!(tmp_session = malloc(sizeof(*tmp_session))))
  2412.                     DynamicPreprocessorFatalMessage("Could not allocate tTmpAppIdData data");
  2413.                 tmp_session->common.fsf_type.flow_type = APPID_SESSION_TYPE_TMP;
  2414.                 tmp_session->common.externalFlags = flow_flags;
  2415.                 ip = (direction == APP_ID_FROM_INITIATOR) ? GET_SRC_IP(p) : GET_DST_IP(p);
  2416.                 tmp_session->common.initiator_ip = *ip;
  2417.                 if ((protocol == IPPROTO_TCP || protocol == IPPROTO_UDP) && p->src_port != p->dst_port)
  2418.                     tmp_session->common.initiator_port = (direction == APP_ID_FROM_INITIATOR) ? p->src_port : p->dst_port;
  2419.                 else
  2420.                     tmp_session->common.initiator_port = 0;
  2421.                 tmp_session->common.policyId = appIdPolicyId;
  2422.                 _dpd.sessionAPI->set_application_data(p->stream_session, PP_APP_ID,
  2423.                         tmp_session, (void (*)(void*))appTmpSharedDataFree);
  2424.                 if (app_id_debug_session_flag)
  2425.                     _dpd.logMsg("AppIdDbg %s unknown monitoring\n", app_id_debug_session);
  2426.             }
  2427.         }
  2428.         else
  2429.         {
  2430.             session->common.externalFlags = flow_flags;
  2431.             if ((flow_flags & APPID_SESSION_BIDIRECTIONAL_CHECKED) == APPID_SESSION_BIDIRECTIONAL_CHECKED)
  2432.                 session->common.fsf_type.flow_type = APPID_SESSION_TYPE_IGNORE;
  2433.             session->common.policyId = appIdPolicyId;
  2434.             if (app_id_debug_session_flag)
  2435.                 _dpd.logMsg("AppIdDbg %s not monitored\n", app_id_debug_session);
  2436.         }
  2437.         return;
  2438.     }
  2439.  
  2440.     if (!session || session->common.fsf_type.flow_type == APPID_SESSION_TYPE_TMP)
  2441.     {
  2442.         /* This call will free the existing temporary session, if there is one */
  2443.         session = appSharedCreateData(p, protocol, direction);
  2444.         if (app_id_debug_session_flag)
  2445.             _dpd.logMsg("AppIdDbg %s new session\n", app_id_debug_session);
  2446.     }
  2447.  
  2448.     app_id_processed_packet_count++;
  2449.     session->session_packet_count++;
  2450.     if (direction == APP_ID_FROM_INITIATOR)
  2451.         session->stats.initiatorBytes += p->pkt_header->pktlen;
  2452.     else
  2453.         session->stats.responderBytes += p->pkt_header->pktlen;
  2454.  
  2455.     session->common.externalFlags = flow_flags;
  2456.     session->common.policyId = appIdPolicyId;
  2457.  
  2458.     tpAppId = session->tpAppId;
  2459.  
  2460.     session->common.policyId = appIdPolicyId;
  2461.  
  2462. #ifdef DEBUG_FW_APPID
  2463. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  2464.     if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  2465.     {
  2466. #endif
  2467.         fprintf(SF_DEBUG_FILE, "%u %u -> %u %u Begin %d %u - (%d %d %d %d %d) %u %08X %08X (%u %u %u)\n",
  2468.                 (unsigned )session->session_packet_count, (unsigned)p->src_port, (unsigned)p->dst_port, (unsigned)protocol, direction,
  2469.                 (unsigned)p->payload_size, session->serviceAppId, session->clientAppId, session->payloadAppId, tpAppId, session->miscAppId,
  2470.                 session->rnaServiceState, session->common.externalFlags, p->flags, thirdparty_appid_module->session_state_get(session->tpsession),
  2471.                 (unsigned)session->init_tpPackets, (unsigned)session->resp_tpPackets);
  2472.         /*DumpHex(SF_DEBUG_FILE, p->payload, p->payload_size); */
  2473. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  2474.     }
  2475. #endif
  2476. #endif
  2477.  
  2478.     if (p->flags & FLAG_STREAM_ORDER_BAD)
  2479.         setAppIdExtFlag(session, APPID_SESSION_OOO);
  2480.     else if (p->tcp_header)
  2481.     {
  2482.         if ((p->tcp_header->flags & TCPHEADER_RST) && session->previous_tcp_flags == TCPHEADER_SYN)
  2483.         {
  2484.             AppIdServiceIDState *id_state;
  2485.  
  2486.             setAppIdExtFlag(session, APPID_SESSION_SYN_RST);
  2487.             if (sfaddr_is_set(&session->service_ip))
  2488.             {
  2489.                 ip = &session->service_ip;
  2490.                 port = session->service_port;
  2491.             }
  2492.             else
  2493.             {
  2494.                 ip = GET_SRC_IP(p);
  2495.                 port = p->src_port;
  2496.             }
  2497.             id_state = AppIdGetServiceIDState(ip, IPPROTO_TCP, port, AppIdServiceDetectionLevel(session));
  2498.             if (id_state)
  2499.             {
  2500.                 if (!id_state->reset_time)
  2501.                     id_state->reset_time = GetPacketRealTime;
  2502.                 else if ((GetPacketRealTime - id_state->reset_time) >= 60)
  2503.                 {
  2504.                     AppIdRemoveServiceIDState(ip, IPPROTO_TCP, port, AppIdServiceDetectionLevel(session));
  2505.                     setAppIdExtFlag(session, APPID_SESSION_SERVICE_DELETED);
  2506.                 }
  2507.             }
  2508.         }
  2509.         session->previous_tcp_flags = p->tcp_header->flags;
  2510.     }
  2511.  
  2512.  
  2513.     /*HostPort based AppId.  */
  2514.     if (!(session->scan_flags & SCAN_HOST_PORT_FLAG))
  2515.     {
  2516.         tHostPortVal *hv;
  2517.         int16_t snortId;
  2518.  
  2519.         session->scan_flags |= SCAN_HOST_PORT_FLAG;
  2520.         if (direction == APP_ID_FROM_INITIATOR)
  2521.         {
  2522.             ip = GET_DST_IP(p);
  2523.             port = p->dst_port;
  2524.         }
  2525.         else
  2526.         {
  2527.             ip = GET_SRC_IP(p);
  2528.             port = p->src_port;
  2529.         }
  2530.         if ((hv = hostPortAppCacheFind(ip, port, protocol, pConfig)) > APP_ID_NONE)
  2531.         {
  2532.             switch (hv->type)
  2533.             {
  2534.             case 1:
  2535.                 session->clientAppId = hv->appId;
  2536.                 session->rnaClientState = RNA_STATE_FINISHED;
  2537.                 break;
  2538.             case 2:
  2539.                 session->payloadAppId = hv->appId;
  2540.                 break;
  2541.             default:
  2542.                 session->serviceAppId = hv->appId;
  2543.                 synchAppIdWithSnortId(hv->appId, p, session, pConfig);
  2544.                 session->rnaServiceState = RNA_STATE_FINISHED;
  2545.                 session->rnaClientState = RNA_STATE_FINISHED;
  2546.                 setAppIdExtFlag(session, APPID_SESSION_SERVICE_DETECTED);
  2547.                 if (thirdparty_appid_module)
  2548.                     thirdparty_appid_module->session_delete(session->tpsession, 1);
  2549.                 session->tpsession = NULL;
  2550.             }
  2551.         }
  2552.     }
  2553.  
  2554.     checkRestartAppDetection(session);
  2555.  
  2556.     //restart inspection by 3rd party
  2557.     if (TPIsAppIdDone(session->tpsession)
  2558.             && getAppIdExtFlag(session, APPID_SESSION_HTTP_SESSION) && p->payload_size
  2559.             && (direction == APP_ID_FROM_INITIATOR))
  2560.     {
  2561.         setAppIdIntFlag(session, APPID_SESSION_APP_REINSPECT);
  2562.         if (app_id_debug_session_flag)
  2563.             _dpd.logMsg("AppIdDbg %s 3rd allow reinspect http\n", app_id_debug_session);
  2564.         appHttpFieldClear(session->hsession);
  2565.     }
  2566.  
  2567.     if (session->tpAppId == APP_ID_SSH && session->payloadAppId != APP_ID_SFTP && session->session_packet_count >= MIN_SFTP_PACKET_COUNT && session->session_packet_count < MAX_SFTP_PACKET_COUNT)
  2568.     {
  2569.         if (GET_IPH_TOS(p) == 8)
  2570.         {
  2571.             session->payloadAppId = APP_ID_SFTP;
  2572.             if (app_id_debug_session_flag)
  2573.                 _dpd.logMsg("AppIdDbg %s payload is SFTP\n", app_id_debug_session);
  2574.         }
  2575.     }
  2576.  
  2577.     if (thirdparty_appid_module && (!TPIsAppIdDone(session->tpsession) || getAppIdIntFlag(session, APPID_SESSION_APP_REINSPECT | APPID_SESSION_APP_REINSPECT_SSL)))
  2578.     {
  2579.         PROFILE_VARS;
  2580.         PREPROC_PROFILE_START(tpPerfStats);
  2581.  
  2582.         // First SSL decrypted packet is now being inspected. Reset the flag so that SSL decrypted traffic
  2583.         // gets processed like regular traffic from next packet onwards
  2584.         if (getAppIdIntFlag(session, APPID_SESSION_APP_REINSPECT_SSL))
  2585.         {
  2586.             clearAppIdIntFlag(session, APPID_SESSION_APP_REINSPECT_SSL);
  2587.         }
  2588.         if (p->payload_size)
  2589.         {
  2590.             if (protocol != IPPROTO_TCP || (p->flags & FLAG_STREAM_ORDER_OK))
  2591.             {
  2592.                 PREPROC_PROFILE_START(tpLibPerfStats);
  2593.                 if (!session->tpsession)
  2594.                 {
  2595.                     if (!(session->tpsession = thirdparty_appid_module->session_create()))
  2596.                         DynamicPreprocessorFatalMessage("Could not allocate tAppIdData->tpsession data");
  2597.                 }
  2598.                 thirdparty_appid_module->session_process(session->tpsession, p, direction,
  2599.                                                          &tpAppId, &tp_confidence, &tp_proto_list, &tp_attribute_data);
  2600.                 PREPROC_PROFILE_END(tpLibPerfStats);
  2601.                 setAppIdContinueForSSL(session);
  2602.                 if (thirdparty_appid_module->session_state_get(session->tpsession) == TP_STATE_CLASSIFIED)
  2603.                     clearAppIdIntFlag(session, APPID_SESSION_APP_REINSPECT);
  2604.  
  2605.                 ProcessThirdPartyResults(session, tp_confidence, tp_proto_list, tp_attribute_data);
  2606.  
  2607.                 if (getAppIdExtFlag(session, APPID_SESSION_SSL_SESSION) &&
  2608.                     !(session->scan_flags & SCAN_SSL_HOST_FLAG))
  2609.                 {
  2610.                     setSSLSquelch(p, 1, tpAppId);
  2611.                 }
  2612.  
  2613.                 if (app_id_debug_session_flag)
  2614.                     _dpd.logMsg("AppIdDbg %s 3rd party returned %d\n", app_id_debug_session, tpAppId);
  2615. #ifdef DEBUG_FW_APPID
  2616. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  2617.                 if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  2618. #endif
  2619.                     fprintf(SF_DEBUG_FILE, "%u -> %u %u 3rd party returned %d\n",
  2620.                             (unsigned)p->src_port, (unsigned)p->dst_port, (unsigned)protocol, tpAppId);
  2621. #endif
  2622.                 if (appInfoEntryFlagGet(tpAppId, APPINFO_FLAG_IGNORE, pConfig))
  2623.                       tpAppId = APP_ID_NONE;
  2624.             }
  2625.             else
  2626.             {
  2627.                 tpAppId = APP_ID_NONE;
  2628. #ifdef DEBUG_FW_APPID
  2629. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  2630.                 if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  2631. #endif
  2632.                     fprintf(SF_DEBUG_FILE, "%u -> %u %u Skipping ooo\n",
  2633.                             (unsigned)p->src_port, (unsigned)p->dst_port, (unsigned)protocol);
  2634. #endif
  2635.                 if (app_id_debug_session_flag)
  2636.                     _dpd.logMsg("AppIdDbg %s 3rd party packet out-of-order\n", app_id_debug_session);
  2637.             }
  2638.  
  2639.             if (thirdparty_appid_module->session_state_get(session->tpsession) == TP_STATE_MONITORING)
  2640.             {
  2641.                 thirdparty_appid_module->disable_flags(session->tpsession, TP_SESSION_FLAG_ATTRIBUTE | TP_SESSION_FLAG_TUNNELING | TP_SESSION_FLAG_FUTUREFLOW);
  2642.             }
  2643.  
  2644.             if(tpAppId == APP_ID_SSL && (_dpd.sessionAPI->get_application_protocol_id(p->stream_session) == snortId_for_ftp_data))
  2645.             {
  2646.                 //  If we see SSL on an FTP data channel set tpAppId back
  2647.                 //  to APP_ID_NONE so the FTP preprocessor picks up the flow.
  2648.                 tpAppId = APP_ID_NONE;
  2649.             }
  2650.  
  2651.             if (tpAppId > APP_ID_NONE && (!getAppIdIntFlag(session, APPID_SESSION_APP_REINSPECT) || session->payloadAppId > APP_ID_NONE))
  2652.             {
  2653. #ifdef TARGET_BASED
  2654.                 tAppId snortAppId;
  2655.                 int16_t snortId;
  2656. #endif
  2657.  
  2658.                 // if the packet is HTTP, then search for via pattern
  2659.                 if (getAppIdExtFlag(session, APPID_SESSION_HTTP_SESSION) && session->hsession)
  2660.                 {
  2661. #ifdef TARGET_BASED
  2662.                     snortAppId = APP_ID_HTTP;
  2663. #endif
  2664.                     //payload should never be APP_ID_HTTP
  2665.                     if (tpAppId != APP_ID_HTTP)
  2666.                         session->tpPayloadAppId = tpAppId;
  2667.  
  2668. #ifdef DEBUG_FW_APPID
  2669. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  2670.                     if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  2671. #endif
  2672.                         fprintf(SF_DEBUG_FILE, "%u -> %u %u tp identified http payload %d\n",
  2673.                                 (unsigned)p->src_port, (unsigned)p->dst_port, (unsigned)protocol, tpAppId);
  2674. #endif
  2675.  
  2676.                     session->tpAppId = APP_ID_HTTP;
  2677.  
  2678.                     processHTTPPacket(p, session, direction, NULL, appIdActiveConfigGet());
  2679.  
  2680.                     if (TPIsAppIdAvailable(session->tpsession) && session->tpAppId == APP_ID_HTTP
  2681.                                                         && !getAppIdIntFlag(session, APPID_SESSION_APP_REINSPECT))
  2682.                     {
  2683.                         session->rnaClientState = RNA_STATE_FINISHED;
  2684.                         setAppIdExtFlag(session, APPID_SESSION_CLIENT_DETECTED);
  2685.                         session->rnaServiceState = RNA_STATE_FINISHED;
  2686.                         setAppIdExtFlag(session, APPID_SESSION_SERVICE_DETECTED);
  2687.                         clearAppIdExtFlag(session, APPID_SESSION_CONTINUE);
  2688.                         if (direction == APP_ID_FROM_INITIATOR)
  2689.                         {
  2690.                             ip = GET_DST_IP(p);
  2691.                             session->service_ip = *ip;
  2692.                             session->service_port = p->dst_port;
  2693.                         }
  2694.                         else
  2695.                         {
  2696.                             ip = GET_SRC_IP(p);
  2697.                             session->service_ip = *ip;
  2698.                             session->service_port = p->src_port;
  2699.                         }
  2700.                     }
  2701.                 }
  2702.                 else if (getAppIdExtFlag(session, APPID_SESSION_SSL_SESSION) && session->tsession)
  2703.                 {
  2704.                     ExamineSslMetadata(p, session, pConfig);
  2705.  
  2706.                     uint16_t serverPort;
  2707.                     tAppId portAppId;
  2708.  
  2709.                     serverPort = (direction == APP_ID_FROM_INITIATOR)? p->dst_port:p->src_port;
  2710.  
  2711.                     portAppId = getSslServiceAppId(serverPort);
  2712.                     if (tpAppId == APP_ID_SSL )
  2713.                     {
  2714.                         tpAppId = portAppId;
  2715.  
  2716.                         //SSL policy needs to determine IMAPS/POP3S etc before appId sees first server packet
  2717.                         session->portServiceAppId = portAppId;
  2718.  
  2719.                         if (app_id_debug_session_flag)
  2720.                             _dpd.logMsg("AppIdDbg %s SSL is service %d, portServiceAppId %d\n",
  2721.                                     app_id_debug_session, tpAppId, session->portServiceAppId);
  2722.                     }
  2723.                     else
  2724.                     {
  2725.                         session->tpPayloadAppId = tpAppId;
  2726.                         tpAppId = portAppId;
  2727.                         if (app_id_debug_session_flag)
  2728.                             _dpd.logMsg("AppIdDbg %s SSL is https %d\n", app_id_debug_session, tpAppId);
  2729.                     }
  2730.                     session->tpAppId = tpAppId;
  2731. #ifdef TARGET_BASED
  2732.                     snortAppId = APP_ID_SSL;
  2733. #endif
  2734.  
  2735. #ifdef DEBUG_FW_APPID
  2736. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  2737.                     if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  2738. #endif
  2739.                         fprintf(SF_DEBUG_FILE, "%u -> %u %u tp identified ssl service %d\n",
  2740.                                 (unsigned)p->src_port, (unsigned)p->dst_port, (unsigned)protocol, tpAppId);
  2741. #endif
  2742.                 }
  2743.                 else
  2744.                 {
  2745.                     //for non-http protocols, tp id is treated like serviceId
  2746.  
  2747. #ifdef TARGET_BASED
  2748.                     snortAppId = tpAppId;
  2749. #endif
  2750.  
  2751. #ifdef DEBUG_FW_APPID
  2752. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  2753.                     if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  2754. #endif
  2755.                         fprintf(SF_DEBUG_FILE, "%u -> %u %u tp identified non-http service %d\n",
  2756.                                 (unsigned)p->src_port, (unsigned)p->dst_port, (unsigned)protocol, tpAppId);
  2757. #endif
  2758.                     session->tpAppId = tpAppId;
  2759.                 }
  2760.  
  2761. #ifdef TARGET_BASED
  2762.                 synchAppIdWithSnortId(snortAppId, p, session, pConfig);
  2763. #endif
  2764.             }
  2765.             else
  2766.             {
  2767.                 if (protocol != IPPROTO_TCP || (p->flags & (FLAG_STREAM_ORDER_OK | FLAG_STREAM_ORDER_BAD)))
  2768.                 {
  2769.                     if (direction == APP_ID_FROM_INITIATOR)
  2770.                     {
  2771.                         session->init_tpPackets++;
  2772.                         if (session->init_tpPackets >= MAX_TP_PACKETS_PER_SESSION)
  2773.                         {
  2774.                             if (session->tpAppId == APP_ID_NONE)
  2775.                                 session->tpAppId = APP_ID_UNKNOWN;
  2776.                             if (session->payloadAppId == APP_ID_NONE)
  2777.                                 session->payloadAppId = APP_ID_UNKNOWN;
  2778.                             if (thirdparty_appid_module)
  2779.                                 thirdparty_appid_module->session_delete(session->tpsession, 1);
  2780.                         }
  2781.                     }
  2782.                     else
  2783.                     {
  2784.                         session->resp_tpPackets++;
  2785.                         if (session->resp_tpPackets >= MAX_TP_PACKETS_PER_SESSION)
  2786.                         {
  2787.                             if (session->tpAppId == APP_ID_NONE)
  2788.                                 session->tpAppId = APP_ID_UNKNOWN;
  2789.                             if (session->payloadAppId == APP_ID_NONE)
  2790.                                 session->payloadAppId = APP_ID_UNKNOWN;
  2791.                             if (thirdparty_appid_module)
  2792.                                 thirdparty_appid_module->session_delete(session->tpsession, 1);
  2793.                         }
  2794.                     }
  2795.                 }
  2796.             }
  2797.         }
  2798.  
  2799.         PREPROC_PROFILE_END(tpPerfStats);
  2800.     }
  2801.  
  2802.     if (direction == APP_ID_FROM_RESPONDER && !getAppIdExtFlag(session, APPID_SESSION_PORT_SERVICE_DONE|APPID_SESSION_SYN_RST))
  2803.     {
  2804.         setAppIdExtFlag(session, APPID_SESSION_PORT_SERVICE_DONE);
  2805.         session->portServiceAppId = getPortServiceId(protocol, p->src_port, pConfig);
  2806.         if (app_id_debug_session_flag)
  2807.             _dpd.logMsg("AppIdDbg %s port service %d\n", app_id_debug_session, session->portServiceAppId);
  2808.     }
  2809.  
  2810.     /* Length-based detectors. */
  2811.     /* Only check if:
  2812.      *  - Port service didn't find anything (and we haven't yet either).
  2813.      *  - We haven't hit the max packets allowed for detector sequence matches.
  2814.      *  - Packet has data (we'll ignore 0-sized packets in sequencing). */
  2815.     if (   (session->portServiceAppId <= APP_ID_NONE)
  2816.         && (session->length_sequence.sequence_cnt < LENGTH_SEQUENCE_CNT_MAX)
  2817.         && (p->payload_size > 0))
  2818.     {
  2819.         uint8_t index = session->length_sequence.sequence_cnt;
  2820.         session->length_sequence.proto = protocol;
  2821.         session->length_sequence.sequence_cnt++;
  2822.         session->length_sequence.sequence[index].direction = direction;
  2823.         session->length_sequence.sequence[index].length    = p->payload_size;
  2824.         session->portServiceAppId = lengthAppCacheFind(&session->length_sequence, pConfig);
  2825.         if (session->portServiceAppId > APP_ID_NONE)
  2826.         {
  2827.             setAppIdExtFlag(session, APPID_SESSION_PORT_SERVICE_DONE);
  2828.         }
  2829.     }
  2830.  
  2831.     /* exceptions for rexec and any other service detector that needs to see SYN and SYN/ACK */
  2832.     if (getAppIdIntFlag(session, APPID_SESSION_REXEC_STDERR))
  2833.     {
  2834.         AppIdDiscoverService(p, direction, session, pConfig);
  2835.         if(session->serviceAppId == APP_ID_DNS && appidStaticConfig.dns_host_reporting && session->dsession && session->dsession->host )
  2836.         {
  2837.             size = session->dsession->host_len;
  2838.             dns_host_scan_hostname((const u_int8_t *)session->dsession->host, size, &clientAppId, &payloadAppId, &pConfig->serviceDnsConfig);
  2839.             setClientAppIdData(session, clientAppId, NULL);
  2840.         }
  2841.         else if (session->serviceAppId == APP_ID_RTMP)
  2842.             ExamineRtmpMetadata(session);
  2843.         else if (getAppIdExtFlag(session, APPID_SESSION_SSL_SESSION) && session->tsession)
  2844.             ExamineSslMetadata(p, session, pConfig);
  2845.     }
  2846.  
  2847.     //service
  2848.     else if (protocol != IPPROTO_TCP || (p->flags & FLAG_STREAM_ORDER_OK))
  2849.     {
  2850.         if (session->rnaServiceState != RNA_STATE_FINISHED)
  2851.         {
  2852.             uint32_t prevRnaServiceState;
  2853.             PROFILE_VARS;
  2854.             PREPROC_PROFILE_START(serviceMatchPerfStats);
  2855.  
  2856.             tpAppId = session->tpAppId;
  2857.             prevRnaServiceState = session->rnaServiceState;
  2858.  
  2859.             //decision to directly call validator or go through elaborate service_state tracking
  2860.             //is made once at the beginning of sesssion.
  2861.             if (session->rnaServiceState == RNA_STATE_NONE && p->payload_size)
  2862.             {
  2863.                 if (_dpd.sessionAPI->get_session_flags(p->stream_session) & SSNFLAG_MIDSTREAM)
  2864.                 {
  2865.                     // Unless it could be ftp control
  2866.                     if (protocol == IPPROTO_TCP && (p->src_port == 21 || p->dst_port == 21) &&
  2867.                             !(p->tcp_header->flags & (TCPHEADER_FIN | TCPHEADER_RST)))
  2868.                     {
  2869.                         setAppIdExtFlag(session, APPID_SESSION_CLIENT_DETECTED | APPID_SESSION_NOT_A_SERVICE | APPID_SESSION_SERVICE_DETECTED);
  2870.                         if (!AddFTPServiceState(session))
  2871.                         {
  2872.                             setAppIdExtFlag(session, APPID_SESSION_CONTINUE);
  2873.                             if (p->dst_port != 21)
  2874.                                 setAppIdExtFlag(session, APPID_SESSION_RESPONDER_SEEN);
  2875.                         }
  2876.                         session->rnaServiceState = RNA_STATE_STATEFUL;
  2877.                     }
  2878.                     else
  2879.                     {
  2880.                         setAppIdExtFlag(session, APPID_SESSION_MID | APPID_SESSION_SERVICE_DETECTED);
  2881.                         session->rnaServiceState = RNA_STATE_FINISHED;
  2882.                     }
  2883.                 }
  2884.                 else if (TPIsAppIdAvailable(session->tpsession))
  2885.                 {
  2886.                     if (tpAppId > APP_ID_NONE)
  2887.                     {
  2888.                         //tp has positively identified appId, Dig deeper only if sourcefire detector
  2889.                         //identifies additional information or flow is UDP reveresed.
  2890.                         if ((entry = appInfoEntryGet(tpAppId, pConfig))
  2891.                                 && entry->svrValidator &&
  2892.                                 ((entry->flags & APPINFO_FLAG_SERVICE_ADDITIONAL) ||
  2893.                                  ((entry->flags & APPINFO_FLAG_SERVICE_UDP_REVERSED) && protocol == IPPROTO_UDP &&
  2894.                                   getAppIdExtFlag(session, APPID_SESSION_INITIATOR_MONITORED | APPID_SESSION_RESPONDER_MONITORED))))
  2895.                         {
  2896.                             AppIdFlowdataDeleteAllByMask(session, APPID_SESSION_DATA_SERVICE_MODSTATE_BIT);
  2897.  
  2898. #ifdef DEBUG_FW_APPID
  2899.                             if (session->serviceData && compareServiceElements(session->serviceData, entry->svrValidator))
  2900.                             {
  2901.                                 fprintf(stderr, "Mismatched validator Original %s, new tp %s",
  2902.                                         session->serviceData->name, entry->svrValidator->name);
  2903.                             }
  2904. #endif
  2905.                             session->serviceData = entry->svrValidator;
  2906.                             session->rnaServiceState = RNA_STATE_STATEFUL;
  2907. #ifdef DEBUG_FW_APPID
  2908. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  2909.                             if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  2910. #endif
  2911.                                 fprintf(SF_DEBUG_FILE, "%u -> %u %u RNA doing deeper inspection\n",
  2912.                                         (unsigned)p->src_port, (unsigned)p->dst_port, (unsigned)protocol);
  2913. #endif
  2914.                         }
  2915.                         else
  2916.                         {
  2917.                             stopRnaServiceInspection(p, session, direction);
  2918.                         }
  2919.                     }
  2920.                     else
  2921.                         session->rnaServiceState = RNA_STATE_STATEFUL;
  2922.                 }
  2923.                 else
  2924.                     session->rnaServiceState = RNA_STATE_STATEFUL;
  2925.             }
  2926.  
  2927.             //stop rna inspection as soon as tp has classified a valid AppId later in the session
  2928.             if (session->rnaServiceState == RNA_STATE_STATEFUL && prevRnaServiceState == RNA_STATE_STATEFUL
  2929.                     && TPIsAppIdAvailable(session->tpsession) && tpAppId > APP_ID_NONE  && tpAppId < SF_APPID_MAX )
  2930.             {
  2931.                 entry = appInfoEntryGet(tpAppId, pConfig);
  2932.  
  2933.                 if (entry && entry->svrValidator && !(entry->flags & APPINFO_FLAG_SERVICE_ADDITIONAL))
  2934.                 {
  2935.                     stopRnaServiceInspection(p, session, direction);
  2936.                 }
  2937.             }
  2938.  
  2939.             if (session->rnaServiceState == RNA_STATE_STATEFUL)
  2940.             {
  2941. #ifdef DEBUG_FW_APPID
  2942. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  2943.                 if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  2944. #endif
  2945.                     fprintf(SF_DEBUG_FILE, "%u -> %u %u RNA identifying service\n",
  2946.                             (unsigned)p->src_port, (unsigned)p->dst_port, (unsigned)protocol);
  2947. #endif
  2948.                 AppIdDiscoverService(p, direction, session, pConfig);
  2949.                 setAppIdContinueForSSL(session);
  2950.                 //to stop executing validator after service has been detected by RNA.
  2951.                 if (getAppIdExtFlag(session, APPID_SESSION_SERVICE_DETECTED) && !getAppIdExtFlag(session, APPID_SESSION_CONTINUE))
  2952.                     session->rnaServiceState = RNA_STATE_FINISHED;
  2953.  
  2954.                 if(session->serviceAppId == APP_ID_DNS && appidStaticConfig.dns_host_reporting && session->dsession && session->dsession->host  )
  2955.                 {
  2956.                     size = session->dsession->host_len;
  2957.                     dns_host_scan_hostname((const u_int8_t *)session->dsession->host , size, &clientAppId, &payloadAppId, &pConfig->serviceDnsConfig);
  2958.                     setClientAppIdData(session, clientAppId, NULL);
  2959.                 }
  2960.                 else if (session->serviceAppId == APP_ID_RTMP)
  2961.                     ExamineRtmpMetadata(session);
  2962.                 else if (getAppIdExtFlag(session, APPID_SESSION_SSL_SESSION) && session->tsession)
  2963.                     ExamineSslMetadata(p, session, pConfig);
  2964.  
  2965. #ifdef TARGET_BASED
  2966.                 if (tpAppId <= APP_ID_NONE && getAppIdExtFlag(session, APPID_SESSION_SERVICE_DETECTED) &&
  2967.                         !getAppIdExtFlag(session, APPID_SESSION_NOT_A_SERVICE | APPID_SESSION_IGNORE_HOST))
  2968.                 {
  2969.                     synchAppIdWithSnortId(session->serviceAppId, p, session, pConfig);
  2970.                 }
  2971. #endif
  2972.             }
  2973.             PREPROC_PROFILE_END(serviceMatchPerfStats);
  2974.         }
  2975.  
  2976.         if (session->rnaClientState != RNA_STATE_FINISHED)
  2977.         {
  2978.             PROFILE_VARS;
  2979.             PREPROC_PROFILE_START(clientMatchPerfStats);
  2980.             uint32_t prevRnaClientState = session->rnaClientState;
  2981.  
  2982.             //decision to directly call validator or go through elaborate service_state tracking
  2983.             //is made once at the beginning of sesssion.
  2984.             if (session->rnaClientState == RNA_STATE_NONE && p->payload_size && direction == APP_ID_FROM_INITIATOR)
  2985.             {
  2986.                 if (_dpd.sessionAPI->get_session_flags(p->stream_session) & SSNFLAG_MIDSTREAM)
  2987.                     session->rnaClientState = RNA_STATE_FINISHED;
  2988.                 else if (TPIsAppIdAvailable(session->tpsession) && (tpAppId = session->tpAppId) > APP_ID_NONE && tpAppId < SF_APPID_MAX)
  2989.                 {
  2990.                     if ((entry = appInfoEntryGet(tpAppId, pConfig)) && entry->clntValidator &&
  2991.                             ((entry->flags & APPINFO_FLAG_CLIENT_ADDITIONAL) ||
  2992.                              ((entry->flags & APPINFO_FLAG_CLIENT_USER) &&
  2993.                               getAppIdExtFlag(session, APPID_SESSION_DISCOVER_USER))))
  2994.                     {
  2995.                         //tp has positively identified appId, Dig deeper only if sourcefire detector
  2996.                         //identifies additional information
  2997.                         session->clientData = entry->clntValidator;
  2998.                         session->rnaClientState = RNA_STATE_DIRECT;
  2999.                     }
  3000.                     else
  3001.                     {
  3002.                         setAppIdExtFlag(session, APPID_SESSION_CLIENT_DETECTED);
  3003.                         session->rnaClientState = RNA_STATE_FINISHED;
  3004.                     }
  3005.                 }
  3006.                 else if (getAppIdExtFlag(session, APPID_SESSION_HTTP_SESSION))
  3007.                     session->rnaClientState = RNA_STATE_FINISHED;
  3008.                 else
  3009.                     session->rnaClientState = RNA_STATE_STATEFUL;
  3010.             }
  3011.  
  3012.             //stop rna inspection as soon as tp has classified a valid AppId later in the session
  3013.             if ((session->rnaClientState == RNA_STATE_STATEFUL || session->rnaClientState == RNA_STATE_DIRECT) && session->rnaClientState == prevRnaClientState
  3014.                     && TPIsAppIdAvailable(session->tpsession) && tpAppId > APP_ID_NONE  && tpAppId < SF_APPID_MAX )
  3015.             {
  3016.                 entry = appInfoEntryGet(tpAppId, pConfig);
  3017.  
  3018.                 if (!(entry && entry->clntValidator && entry->clntValidator == session->clientData && (entry->flags & (APPINFO_FLAG_CLIENT_ADDITIONAL|APPINFO_FLAG_CLIENT_USER))))
  3019.                 {
  3020.                     session->rnaClientState = RNA_STATE_FINISHED;
  3021.                     setAppIdExtFlag(session, APPID_SESSION_CLIENT_DETECTED);
  3022.                 }
  3023.             }
  3024.  
  3025.             if (session->rnaClientState == RNA_STATE_DIRECT)
  3026.             {
  3027.                 int ret = CLIENT_APP_INPROCESS;
  3028.  
  3029. #ifdef DEBUG_FW_APPID
  3030. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  3031.                 if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  3032. #endif
  3033.                     fprintf(SF_DEBUG_FILE, "%u -> %u %u RNA identifying additional client info\n",
  3034.                             (unsigned)p->src_port, (unsigned)p->dst_port, (unsigned)protocol);
  3035. #endif
  3036.                 if (direction == APP_ID_FROM_INITIATOR)
  3037.                 {
  3038.                     /* get out if we've already tried to validate a client app */
  3039.                     if (!getAppIdExtFlag(session, APPID_SESSION_CLIENT_DETECTED))
  3040.                     {
  3041.                         ret = RunClientDetectors(session, p, direction, pConfig);
  3042.                     }
  3043.                 }
  3044.                 else if (session->rnaServiceState != RNA_STATE_STATEFUL &&
  3045.                          getAppIdExtFlag(session, APPID_SESSION_CLIENT_GETS_SERVER_PACKETS))
  3046.                 {
  3047.                     ret = RunClientDetectors(session, p, direction, pConfig);
  3048.                 }
  3049.  
  3050. #ifdef DEBUG_FW_APPID
  3051. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  3052.                 if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  3053. #endif
  3054.                     fprintf(SF_DEBUG_FILE, "%u -> %u %u direct client validate returned %d\n",
  3055.                             (unsigned)p->src_port, (unsigned)p->dst_port, (unsigned)protocol, ret);
  3056. #endif
  3057.                 switch (ret)
  3058.                 {
  3059.                     case CLIENT_APP_INPROCESS:
  3060.                         break;
  3061.                     default:
  3062.                         session->rnaClientState = RNA_STATE_FINISHED;
  3063.                         break;
  3064.                 }
  3065.             }
  3066.             else if (session->rnaClientState == RNA_STATE_STATEFUL)
  3067.             {
  3068. #ifdef DEBUG_FW_APPID
  3069. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  3070.                 if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  3071. #endif
  3072.                     fprintf(SF_DEBUG_FILE, "%u -> %u %u RNA identifying client\n",
  3073.                             (unsigned)p->src_port, (unsigned)p->dst_port, (unsigned)protocol);
  3074. #endif
  3075.                 AppIdDiscoverClientApp(p, direction, session, pConfig);
  3076.                 setAppIdContinueForSSL(session);
  3077.                 if (session->candidate_client_list != NULL)
  3078.                 {
  3079.                     if (sflist_count(session->candidate_client_list) > 0)
  3080.                     {
  3081.                         int ret = 0;
  3082.                         if (direction == APP_ID_FROM_INITIATOR)
  3083.                         {
  3084.                             /* get out if we've already tried to validate a client app */
  3085.                             if (!getAppIdExtFlag(session, APPID_SESSION_CLIENT_DETECTED))
  3086.                             {
  3087.                                 ret = RunClientDetectors(session, p, direction, pConfig);
  3088.                             }
  3089.                         }
  3090.                         else if (session->rnaServiceState != RNA_STATE_STATEFUL &&
  3091.                                  getAppIdExtFlag(session, APPID_SESSION_CLIENT_GETS_SERVER_PACKETS))
  3092.                         {
  3093.                             ret = RunClientDetectors(session, p, direction, pConfig);
  3094.                         }
  3095.                         if (ret < 0)
  3096.                             setAppIdExtFlag(session, APPID_SESSION_CLIENT_DETECTED);
  3097.                     }
  3098.                     else
  3099.                     {
  3100.                         setAppIdExtFlag(session, APPID_SESSION_CLIENT_DETECTED);
  3101.                     }
  3102.                 }
  3103.             }
  3104.             PREPROC_PROFILE_END(clientMatchPerfStats);
  3105.         }
  3106.  
  3107.         setAppIdExtFlag(session, APPID_SESSION_ADDITIONAL_PACKET);
  3108.     }
  3109.     else
  3110.     {
  3111. #ifdef DEBUG_FW_APPID
  3112. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  3113.                 if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  3114. #endif
  3115.         fprintf(SF_DEBUG_FILE, "Packet not okay\n");
  3116. #endif
  3117.         if (app_id_debug_session_flag && p->payload_size)
  3118.             _dpd.logMsg("AppIdDbg %s packet out-of-order\n", app_id_debug_session);
  3119.     }
  3120.  
  3121.     if ((getAppIdExtFlag(session, APPID_SESSION_DECRYPTED)) && session->miscAppId == APP_ID_NONE && session->serviceAppId > APP_ID_NONE)
  3122.     {
  3123.         updateEncryptedAppId(session);
  3124.     }
  3125.  
  3126.     _dpd.streamAPI->set_application_id(p->stream_session, pickServiceAppId(session), pickClientAppId(session), pickPayloadId(session), pickMiscAppId(session));
  3127.  
  3128.     checkSessionForAFIndicator(session, p, direction, pConfig);
  3129.  
  3130.     checkSessionForAFForecast(session, p, direction, pConfig);
  3131.  
  3132. #ifdef DEBUG_FW_APPID
  3133. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  3134.     if (p->dst_port == DEBUG_FW_APPID_PORT || p->src_port == DEBUG_FW_APPID_PORT)
  3135.     {
  3136. #endif
  3137.         fprintf(SF_DEBUG_FILE, "%u %u -> %u %u End %d %u - (%d %d %d %d %d) %u %08X %u %u %u\n", (unsigned)session->session_packet_count, (unsigned)p->src_port, (unsigned)p->dst_port,
  3138.                 (unsigned)protocol, direction, (unsigned)p->payload_size,
  3139.                 session->serviceAppId, session->clientAppId, session->payloadAppId,
  3140.                 session->tpAppId, session->miscAppId, session->rnaServiceState, session->common.externalFlags, thirdparty_appid_module->session_state_get(session->tpsession),
  3141.                 (unsigned)session->init_tpPackets, (unsigned)session->resp_tpPackets);
  3142.         //DumpHex(SF_DEBUG_FILE, p->payload, p->payload_size);
  3143. #if defined(DEBUG_FW_APPID_PORT) && DEBUG_FW_APPID_PORT
  3144.     }
  3145. #endif
  3146. #endif
  3147. }
  3148.  
  3149. static void ProcessThirdPartyResults(tAppIdData* appIdSession, int confidence, tAppId* proto_list, ThirdPartyAppIDAttributeData* attribute_data)
  3150. {
  3151.     int size;
  3152.     tAppId serviceAppId = 0;
  3153.     tAppId clientAppId = 0;
  3154.     tAppId payloadAppId = 0;
  3155.     tAppId referredPayloadAppId = 0;
  3156.     tAppIdConfig *pConfig = appIdActiveConfigGet();
  3157.  
  3158.     if (ThirdPartyAppIDFoundProto(APP_ID_EXCHANGE, proto_list))
  3159.     {
  3160.         if (!appIdSession->payloadAppId)
  3161.             appIdSession->payloadAppId = APP_ID_EXCHANGE;
  3162.     }
  3163.  
  3164.     if (ThirdPartyAppIDFoundProto(APP_ID_HTTP, proto_list))
  3165.     {
  3166.         if (app_id_debug_session_flag)
  3167.             _dpd.logMsg("AppIdDbg %s flow is HTTP\n", app_id_debug_session);
  3168.         setAppIdExtFlag(appIdSession, APPID_SESSION_HTTP_SESSION);
  3169.     }
  3170.     if (ThirdPartyAppIDFoundProto(APP_ID_SPDY, proto_list))
  3171.     {
  3172.         if (app_id_debug_session_flag)
  3173.             _dpd.logMsg("AppIdDbg %s flow is SPDY\n", app_id_debug_session);
  3174.  
  3175.         setAppIdExtFlag(appIdSession, APPID_SESSION_HTTP_SESSION);
  3176.         setAppIdExtFlag(appIdSession, APPID_SESSION_SPDY_SESSION);
  3177.     }
  3178.  
  3179.     if (getAppIdExtFlag(appIdSession, APPID_SESSION_HTTP_SESSION))
  3180.     {
  3181.         if (!appIdSession->hsession)
  3182.         {
  3183.             if (!(appIdSession->hsession = calloc(1, sizeof(*appIdSession->hsession))))
  3184.                 DynamicPreprocessorFatalMessage("Could not allocate httpSession data");
  3185.             memset(ptype_scan_counts, 0, 7 * sizeof(ptype_scan_counts[0]));
  3186.         }
  3187.  
  3188.         if (getAppIdExtFlag(appIdSession, APPID_SESSION_SPDY_SESSION))
  3189.         {
  3190.             if (attribute_data->spdyRequestHost)
  3191.             {
  3192.                 if (app_id_debug_session_flag)
  3193.                     _dpd.logMsg("AppIdDbg %s SPDY host is %s\n", app_id_debug_session, attribute_data->spdyRequestHost);
  3194.                 if (appIdSession->hsession->host)
  3195.                 {
  3196.                     free(appIdSession->hsession->host);
  3197.                     appIdSession->hsession->chp_finished = 0;
  3198.                 }
  3199.                 if (NULL != (appIdSession->hsession->host = strdup(attribute_data->spdyRequestHost)))
  3200.                     appIdSession->scan_flags |= SCAN_HTTP_HOST_URL_FLAG;
  3201.             }
  3202.             if (attribute_data->spdyRequestPath)
  3203.             {
  3204.                 if (app_id_debug_session_flag)
  3205.                     _dpd.logMsg("AppIdDbg %s SPDY URI is %s\n", app_id_debug_session, attribute_data->spdyRequestPath);
  3206.                 if (appIdSession->hsession->uri)
  3207.                 {
  3208.                     free(appIdSession->hsession->uri);
  3209.                     appIdSession->hsession->chp_finished = 0;
  3210.                 }
  3211.                 appIdSession->hsession->uri = strdup(attribute_data->spdyRequestPath); // mem alloc fail benign
  3212.             }
  3213.             if (attribute_data->spdyRequestScheme &&
  3214.                 attribute_data->spdyRequestHost &&
  3215.                 attribute_data->spdyRequestPath)
  3216.             {
  3217.                 static const char httpsScheme[] = "https";
  3218.                 static const char httpScheme[] = "http";
  3219.                 const char *scheme;
  3220.  
  3221.                 if (appIdSession->hsession->url)
  3222.                 {
  3223.                     free(appIdSession->hsession->url);
  3224.                     appIdSession->hsession->chp_finished = 0;
  3225.                 }
  3226.                 if (getAppIdExtFlag(appIdSession, APPID_SESSION_DECRYPTED)
  3227.                         && memcmp(attribute_data->spdyRequestScheme, httpScheme, sizeof(httpScheme)-1) == 0)
  3228.                 {
  3229.                     scheme = httpsScheme;
  3230.                 }
  3231.                 else
  3232.                 {
  3233.                     scheme = attribute_data->spdyRequestScheme;
  3234.                 }
  3235.  
  3236.                 size = strlen(scheme) +
  3237.                        strlen(attribute_data->spdyRequestHost) +
  3238.                        strlen(attribute_data->spdyRequestPath) +
  3239.                        sizeof("://"); // see sprintf() format
  3240.                 if (NULL != (appIdSession->hsession->url = malloc(size)))
  3241.                 {
  3242.                     sprintf(appIdSession->hsession->url, "%s://%s%s",
  3243.                          scheme, attribute_data->spdyRequestHost,
  3244.                          attribute_data->spdyRequestPath);
  3245.                     appIdSession->scan_flags |= SCAN_HTTP_HOST_URL_FLAG;
  3246.                 }
  3247.             }
  3248.             if (attribute_data->spdyRequestScheme)
  3249.             {
  3250.                 free(attribute_data->spdyRequestScheme);
  3251.                 attribute_data->spdyRequestScheme = NULL;
  3252.             }
  3253.             if (attribute_data->spdyRequestHost)
  3254.             {
  3255.                 free(attribute_data->spdyRequestHost);
  3256.                 attribute_data->spdyRequestHost = NULL;
  3257.             }
  3258.             if (attribute_data->spdyRequestPath)
  3259.             {
  3260.                 free(attribute_data->spdyRequestPath);
  3261.                 attribute_data->spdyRequestPath = NULL;
  3262.             }
  3263.         }
  3264.         else
  3265.         {
  3266.             if (attribute_data->httpRequestHost)
  3267.             {
  3268.                 if (app_id_debug_session_flag)
  3269.                     _dpd.logMsg("AppIdDbg %s HTTP host is %s\n", app_id_debug_session, attribute_data->httpRequestHost);
  3270.                 if (appIdSession->hsession->host)
  3271.                 {
  3272.                     free(appIdSession->hsession->host);
  3273.                     if (!getAppIdIntFlag(appIdSession, APPID_SESSION_APP_REINSPECT))
  3274.                         appIdSession->hsession->chp_finished = 0;
  3275.                 }
  3276.                 appIdSession->hsession->host = attribute_data->httpRequestHost;
  3277.                 attribute_data->httpRequestHost = NULL;
  3278.                 appIdSession->scan_flags |= SCAN_HTTP_HOST_URL_FLAG;
  3279.             }
  3280.             if (attribute_data->httpRequestUrl)
  3281.             {
  3282.                 static const char httpScheme[] = "http://";
  3283.  
  3284.                 if (appIdSession->hsession->url)
  3285.                 {
  3286.                     free(appIdSession->hsession->url);
  3287.                     if (!getAppIdIntFlag(appIdSession, APPID_SESSION_APP_REINSPECT))
  3288.                         appIdSession->hsession->chp_finished = 0;
  3289.                 }
  3290.  
  3291.                 //change http to https if session was decrypted.
  3292.                 if (getAppIdExtFlag(appIdSession, APPID_SESSION_DECRYPTED)
  3293.                         && memcmp(attribute_data->httpRequestUrl, httpScheme, sizeof(httpScheme)-1) == 0)
  3294.                 {
  3295.                     appIdSession->hsession->url = malloc(strlen(attribute_data->httpRequestUrl) + 2);
  3296.  
  3297.                     if (appIdSession->hsession->url)
  3298.                         sprintf(appIdSession->hsession->url, "https://%s", attribute_data->httpRequestUrl + sizeof(httpScheme)-1);
  3299.  
  3300.                     free(attribute_data->httpRequestUrl);
  3301.                     attribute_data->httpRequestUrl = NULL;
  3302.                 }
  3303.                 else
  3304.                 {
  3305.                     appIdSession->hsession->url = attribute_data->httpRequestUrl;
  3306.                     attribute_data->httpRequestUrl = NULL;
  3307.                 }
  3308.  
  3309.                 appIdSession->scan_flags |= SCAN_HTTP_HOST_URL_FLAG;
  3310.             }
  3311.             if (attribute_data->httpRequestUri)
  3312.             {
  3313.                 if (appIdSession->hsession->uri)
  3314.                 {
  3315.                     free(appIdSession->hsession->uri);
  3316.                     if (!getAppIdIntFlag(appIdSession, APPID_SESSION_APP_REINSPECT))
  3317.                         appIdSession->hsession->chp_finished = 0;
  3318.                 }
  3319.                 appIdSession->hsession->uri = attribute_data->httpRequestUri;
  3320.                 appIdSession->hsession->uriOffset = attribute_data->httpRequestUriOffset;
  3321.                 appIdSession->hsession->uriEndOffset = attribute_data->httpRequestUriEndOffset;
  3322.                 attribute_data->httpRequestUri = NULL;
  3323.                 attribute_data->httpRequestUriOffset = 0;
  3324.                 attribute_data->httpRequestUriEndOffset = 0;
  3325.                 if (app_id_debug_session_flag)
  3326.                     _dpd.logMsg("AppIdDbg %s uri (%u-%u) is %s\n", app_id_debug_session, appIdSession->hsession->uriOffset, appIdSession->hsession->uriEndOffset, appIdSession->hsession->uri);
  3327.             }
  3328.         }
  3329.         if (attribute_data->httpRequestVia)
  3330.         {
  3331.             if (appIdSession->hsession->via)
  3332.             {
  3333.                 free(appIdSession->hsession->via);
  3334.                 if (!getAppIdIntFlag(appIdSession, APPID_SESSION_APP_REINSPECT))
  3335.                     appIdSession->hsession->chp_finished = 0;
  3336.             }
  3337.             appIdSession->hsession->via = attribute_data->httpRequestVia;
  3338.             attribute_data->httpRequestVia = NULL;
  3339.             appIdSession->scan_flags |= SCAN_HTTP_VIA_FLAG;
  3340.         }
  3341.         else if (attribute_data->httpResponseVia)
  3342.         {
  3343.             if (appIdSession->hsession->via)
  3344.             {
  3345.                 free(appIdSession->hsession->via);
  3346.                 if (!getAppIdIntFlag(appIdSession, APPID_SESSION_APP_REINSPECT))
  3347.                     appIdSession->hsession->chp_finished = 0;
  3348.             }
  3349.             appIdSession->hsession->via = attribute_data->httpResponseVia;
  3350.             attribute_data->httpResponseVia = NULL;
  3351.             appIdSession->scan_flags |= SCAN_HTTP_VIA_FLAG;
  3352.         }
  3353.         if (attribute_data->httpRequestUserAgent)
  3354.         {
  3355.             if (appIdSession->hsession->useragent)
  3356.             {
  3357.                 free(appIdSession->hsession->useragent);
  3358.                 if (!getAppIdIntFlag(appIdSession, APPID_SESSION_APP_REINSPECT))
  3359.                     appIdSession->hsession->chp_finished = 0;
  3360.             }
  3361.             appIdSession->hsession->useragent = attribute_data->httpRequestUserAgent;
  3362.             attribute_data->httpRequestUserAgent = NULL;
  3363.             appIdSession->scan_flags |= SCAN_HTTP_USER_AGENT_FLAG;
  3364.         }
  3365.         if (attribute_data->httpResponseCode)
  3366.         {
  3367.             if (appIdSession->hsession->response_code)
  3368.             {
  3369.                 free(appIdSession->hsession->response_code);
  3370.                 if (!getAppIdIntFlag(appIdSession, APPID_SESSION_APP_REINSPECT))
  3371.                     appIdSession->hsession->chp_finished = 0;
  3372.             }
  3373.             appIdSession->hsession->response_code = attribute_data->httpResponseCode;
  3374.             attribute_data->httpResponseCode = NULL;
  3375.         }
  3376.         if (!appidStaticConfig.referred_appId_disabled && attribute_data->httpRequestReferer)
  3377.         {
  3378.             if (app_id_debug_session_flag)
  3379.                 _dpd.logMsg("AppIdDbg %s referrer is %s\n", app_id_debug_session, attribute_data->httpRequestReferer);
  3380.             if (appIdSession->hsession->referer)
  3381.             {
  3382.                 free(appIdSession->hsession->referer);
  3383.                 if (!getAppIdIntFlag(appIdSession, APPID_SESSION_APP_REINSPECT))
  3384.                     appIdSession->hsession->chp_finished = 0;
  3385.             }
  3386.             appIdSession->hsession->referer = attribute_data->httpRequestReferer;
  3387.             attribute_data->httpRequestReferer = NULL;
  3388.         }
  3389.         if (attribute_data->httpRequestCookie)
  3390.         {
  3391.             if (appIdSession->hsession->cookie)
  3392.             {
  3393.                 free(appIdSession->hsession->cookie);
  3394.                 if (!getAppIdIntFlag(appIdSession, APPID_SESSION_APP_REINSPECT))
  3395.                     appIdSession->hsession->chp_finished = 0;
  3396.             }
  3397.             appIdSession->hsession->cookie = attribute_data->httpRequestCookie;
  3398.             appIdSession->hsession->cookieOffset = attribute_data->httpRequestCookieOffset;
  3399.             appIdSession->hsession->cookieEndOffset = attribute_data->httpRequestCookieEndOffset;
  3400.             attribute_data->httpRequestCookie = NULL;
  3401.             attribute_data->httpRequestCookieOffset = 0;
  3402.             attribute_data->httpRequestCookieEndOffset = 0;
  3403.             if (app_id_debug_session_flag)
  3404.                 _dpd.logMsg("AppIdDbg %s cookie (%u-%u) is %s\n", app_id_debug_session, appIdSession->hsession->cookieOffset, appIdSession->hsession->cookieEndOffset, appIdSession->hsession->cookie);
  3405.         }
  3406.         if (ptype_scan_counts[CONTENT_TYPE_PT] && attribute_data->httpResponseContent)
  3407.         {
  3408.             if (appIdSession->hsession->content_type)
  3409.             {
  3410.                 free(appIdSession->hsession->content_type);
  3411.                 if (!getAppIdIntFlag(appIdSession, APPID_SESSION_APP_REINSPECT))
  3412.                     appIdSession->hsession->chp_finished = 0;
  3413.             }
  3414.             appIdSession->hsession->content_type = attribute_data->httpResponseContent;
  3415.             attribute_data->httpResponseContent = NULL;
  3416.         }
  3417.         if (ptype_scan_counts[LOCATION_PT] && attribute_data->httpResponseLocation)
  3418.         {
  3419.             if (appIdSession->hsession->location)
  3420.             {
  3421.                 free(appIdSession->hsession->location);
  3422.                 if (!getAppIdIntFlag(appIdSession, APPID_SESSION_APP_REINSPECT))
  3423.                     appIdSession->hsession->chp_finished = 0;
  3424.             }
  3425.             appIdSession->hsession->location = attribute_data->httpResponseLocation;
  3426.             attribute_data->httpResponseLocation = NULL;
  3427.         }
  3428.         if (attribute_data->httpRequestBody)
  3429.         {
  3430.             if (app_id_debug_session_flag)
  3431.                 _dpd.logMsg("AppIdDbg %s got a request body %s\n", app_id_debug_session, attribute_data->httpRequestBody);
  3432.             if (appIdSession->hsession->req_body)
  3433.             {
  3434.                 free(appIdSession->hsession->req_body);
  3435.                 if (!getAppIdIntFlag(appIdSession, APPID_SESSION_APP_REINSPECT))
  3436.                     appIdSession->hsession->chp_finished = 0;
  3437.             }
  3438.             appIdSession->hsession->req_body = attribute_data->httpRequestBody;
  3439.             attribute_data->httpRequestBody = NULL;
  3440.         }
  3441.         if (ptype_scan_counts[BODY_PT] && attribute_data->httpResponseBody)
  3442.         {
  3443.             if (appIdSession->hsession->body)
  3444.             {
  3445.                 free(appIdSession->hsession->body);
  3446.                 if (!getAppIdIntFlag(appIdSession, APPID_SESSION_APP_REINSPECT))
  3447.                     appIdSession->hsession->chp_finished = 0;
  3448.             }
  3449.             appIdSession->hsession->body = attribute_data->httpResponseBody;
  3450.             attribute_data->httpResponseBody = NULL;
  3451.         }
  3452.         if (!appIdSession->hsession->chp_finished || appIdSession->hsession->chp_hold_flow)
  3453.         {
  3454.             setAppIdIntFlag(appIdSession, APPID_SESSION_CHP_INSPECTING);
  3455.             if (thirdparty_appid_module)
  3456.                 thirdparty_appid_module->session_attr_set(appIdSession->tpsession, TP_ATTR_CONTINUE_MONITORING);
  3457.         }
  3458.     }
  3459.     else if (ThirdPartyAppIDFoundProto(APP_ID_RTMP, proto_list) ||
  3460.              ThirdPartyAppIDFoundProto(APP_ID_RTSP, proto_list))
  3461.     {
  3462.         if (!appIdSession->hsession)
  3463.         {
  3464.             if (!(appIdSession->hsession = calloc(1, sizeof(*appIdSession->hsession))))
  3465.                 DynamicPreprocessorFatalMessage("Could not allocate httpSession data");
  3466.         }
  3467.         if (!appIdSession->hsession->url)
  3468.         {
  3469.             if (attribute_data->httpRequestUrl)
  3470.             {
  3471.                 appIdSession->hsession->url = attribute_data->httpRequestUrl;
  3472.                 attribute_data->httpRequestUrl = NULL;
  3473.                 appIdSession->scan_flags |= SCAN_HTTP_HOST_URL_FLAG;
  3474.             }
  3475.         }
  3476.  
  3477.         if (!appidStaticConfig.referred_appId_disabled && !appIdSession->hsession->referer)
  3478.         {
  3479.             if (attribute_data->httpRequestReferer)
  3480.             {
  3481.                 appIdSession->hsession->referer = attribute_data->httpRequestReferer;
  3482.                 attribute_data->httpRequestReferer = NULL;
  3483.             }
  3484.         }
  3485.  
  3486.         if (appIdSession->hsession->url || (confidence == 100 && appIdSession->session_packet_count > appidStaticConfig.rtmp_max_packets))
  3487.         {
  3488.             if (appIdSession->hsession->url)
  3489.             {
  3490.                 if (((getAppIdFromUrl(NULL, appIdSession->hsession->url, NULL,
  3491.                                     appIdSession->hsession->referer, &clientAppId, &serviceAppId,
  3492.                                     &payloadAppId, &referredPayloadAppId, 1, &pConfig->detectorHttpConfig)) ||
  3493.                             (getAppIdFromUrl(NULL, appIdSession->hsession->url, NULL,
  3494.                                              appIdSession->hsession->referer, &clientAppId, &serviceAppId,
  3495.                                              &payloadAppId, &referredPayloadAppId, 0, &pConfig->detectorHttpConfig))) == 1)
  3496.  
  3497.                 {
  3498.                     // do not overwrite a previously-set client or service
  3499.                     if (appIdSession->clientAppId <= APP_ID_NONE)
  3500.                         setClientAppIdData(appIdSession, clientAppId, NULL);
  3501.                     if (appIdSession->serviceAppId <= APP_ID_NONE)
  3502.                         setServiceAppIdData(appIdSession, serviceAppId, NULL, NULL);
  3503.  
  3504.                     // DO overwrite a previously-set payload
  3505.                     setPayloadAppIdData(appIdSession, payloadAppId, NULL);
  3506.                     setReferredPayloadAppIdData(appIdSession, referredPayloadAppId);
  3507.                 }
  3508.             }
  3509.  
  3510.             if (thirdparty_appid_module)
  3511.             {
  3512.                 thirdparty_appid_module->disable_flags(appIdSession->tpsession, TP_SESSION_FLAG_ATTRIBUTE | TP_SESSION_FLAG_TUNNELING | TP_SESSION_FLAG_FUTUREFLOW);
  3513.                 thirdparty_appid_module->session_delete(appIdSession->tpsession, 1);
  3514.             }
  3515.             appIdSession->tpsession = NULL;
  3516.             clearAppIdIntFlag(appIdSession, APPID_SESSION_APP_REINSPECT);
  3517.         }
  3518.     }
  3519.     else if (ThirdPartyAppIDFoundProto(APP_ID_SSL, proto_list))
  3520.     {
  3521.         tAppId tmpAppId = APP_ID_NONE;
  3522.  
  3523.         if (thirdparty_appid_module && appIdSession->tpsession)
  3524.             tmpAppId = thirdparty_appid_module->session_appid_get(appIdSession->tpsession);
  3525.  
  3526.         setAppIdExtFlag(appIdSession, APPID_SESSION_SSL_SESSION);
  3527.  
  3528.         if (!appIdSession->tsession)
  3529.         {
  3530.             if (!(appIdSession->tsession = calloc(1, sizeof(*appIdSession->tsession))))
  3531.                 DynamicPreprocessorFatalMessage("Could not allocate tlsSession data");
  3532.         }
  3533.  
  3534.         if (!appIdSession->clientAppId)
  3535.             setClientAppIdData(appIdSession, APP_ID_SSL_CLIENT, NULL);
  3536.  
  3537.         if (attribute_data->tlsHost)
  3538.         {
  3539.             if (appIdSession->tsession->tls_host)
  3540.                 free(appIdSession->tsession->tls_host);
  3541.             appIdSession->tsession->tls_host = attribute_data->tlsHost;
  3542.             attribute_data->tlsHost = NULL;
  3543.             if (testSSLAppIdForReinspect(tmpAppId))
  3544.                 appIdSession->scan_flags |= SCAN_SSL_HOST_FLAG;
  3545.         }
  3546.         if (testSSLAppIdForReinspect(tmpAppId))
  3547.         {
  3548.             if (attribute_data->tlsCname)
  3549.             {
  3550.                 if (appIdSession->tsession->tls_cname)
  3551.                     free(appIdSession->tsession->tls_cname);
  3552.                 appIdSession->tsession->tls_cname = attribute_data->tlsCname;
  3553.                 attribute_data->tlsCname = NULL;
  3554.             }
  3555.             if (attribute_data->tlsOrgUnit)
  3556.             {
  3557.                 if (appIdSession->tsession->tls_orgUnit)
  3558.                     free(appIdSession->tsession->tls_orgUnit);
  3559.                 appIdSession->tsession->tls_orgUnit = attribute_data->tlsOrgUnit;
  3560.                 attribute_data->tlsOrgUnit = NULL;
  3561.             }
  3562.         }
  3563.     }
  3564.     else if (ThirdPartyAppIDFoundProto(APP_ID_FTP_CONTROL, proto_list))
  3565.     {
  3566.         if (!appidStaticConfig.ftp_userid_disabled && attribute_data->ftpCommandUser)
  3567.         {
  3568.             if (appIdSession->username)
  3569.                 free(appIdSession->username);
  3570.             appIdSession->username = attribute_data->ftpCommandUser;
  3571.             attribute_data->ftpCommandUser = NULL;
  3572.             appIdSession->usernameService = APP_ID_FTP_CONTROL;
  3573.             setAppIdExtFlag(appIdSession, APPID_SESSION_LOGIN_SUCCEEDED);
  3574.         }
  3575.     }
  3576. }
  3577. void appSetServiceValidator(RNAServiceValidationFCN fcn, tAppId appId, unsigned extractsInfo, tAppIdConfig *pConfig)
  3578. {
  3579.     AppInfoTableEntry* pEntry = appInfoEntryGet(appId, pConfig);
  3580.     if (!pEntry)
  3581.     {
  3582.         _dpd.errMsg("AppId", "Invalid direct service AppId, %d, for %p", appId, fcn);
  3583.         return;
  3584.     }
  3585.     extractsInfo &= (APPINFO_FLAG_SERVICE_ADDITIONAL | APPINFO_FLAG_SERVICE_UDP_REVERSED);
  3586.     if (!extractsInfo)
  3587.     {
  3588.         _dpd.debugMsg(DEBUG_LOG, "Ignoring direct service without info for %p with AppId %d", fcn, appId);
  3589.         return;
  3590.     }
  3591.     pEntry->svrValidator = ServiceGetServiceElement(fcn, NULL, pConfig);
  3592.     if (pEntry->svrValidator)
  3593.         pEntry->flags |= extractsInfo;
  3594.     else
  3595.         _dpd.errMsg("AppId", "Failed to find a service element for %p with AppId %d", fcn, appId);
  3596. }
  3597.  
  3598. void appSetLuaServiceValidator(RNAServiceValidationFCN fcn, tAppId appId, unsigned extractsInfo, struct _Detector *data)
  3599. {
  3600.     AppInfoTableEntry *entry;
  3601.     tAppIdConfig *pConfig = appIdNewConfigGet();
  3602.  
  3603.     if ((entry = appInfoEntryGet(appId, pConfig)))
  3604.     {
  3605.  
  3606.         entry->flags |= APPINFO_FLAG_ACTIVE;
  3607.  
  3608.         extractsInfo &= (APPINFO_FLAG_SERVICE_ADDITIONAL | APPINFO_FLAG_SERVICE_UDP_REVERSED);
  3609.         if (!extractsInfo)
  3610.         {
  3611.             _dpd.debugMsg(DEBUG_LOG,"Ignoring direct service without info for %p %p with AppId %d\n",fcn, data, appId);
  3612.             return;
  3613.         }
  3614.  
  3615.         entry->svrValidator = ServiceGetServiceElement(fcn, data, pConfig);
  3616.         if (entry->svrValidator)
  3617.             entry->flags |= extractsInfo;
  3618.         else
  3619.             _dpd.errMsg("AppId: Failed to find a service element for %p %p with AppId %d", fcn, data, appId);
  3620.     }
  3621.     else
  3622.     {
  3623.         _dpd.errMsg("Invalid direct service AppId, %d, for %p %p\n",appId, fcn, data);
  3624.     }
  3625. }
  3626.  
  3627. void appSetClientValidator(RNAClientAppFCN fcn, tAppId appId, unsigned extractsInfo, tAppIdConfig *pConfig)
  3628. {
  3629.     AppInfoTableEntry* pEntry = appInfoEntryGet(appId, pConfig);
  3630.     if (!pEntry)
  3631.     {
  3632.         _dpd.errMsg("AppId", "Invalid direct client application AppId, %d, for %p", appId, fcn);
  3633.         return;
  3634.     }
  3635.     extractsInfo &= (APPINFO_FLAG_CLIENT_ADDITIONAL | APPINFO_FLAG_CLIENT_USER);
  3636.     if (!extractsInfo)
  3637.     {
  3638.         _dpd.debugMsg(DEBUG_LOG, "Ignoring direct client application without info for %p with AppId %d", fcn, appId);
  3639.         return;
  3640.     }
  3641.     pEntry->clntValidator = ClientAppGetClientAppModule(fcn, NULL, &pConfig->clientAppConfig);
  3642.     if (pEntry->clntValidator)
  3643.         pEntry->flags |= extractsInfo;
  3644.     else
  3645.         _dpd.errMsg("AppId", "Failed to find a client application module for %p with AppId %d", fcn, appId);
  3646. }
  3647.  
  3648. void appSetLuaClientValidator(RNAClientAppFCN fcn, tAppId appId, unsigned extractsInfo, struct _Detector *data)
  3649. {
  3650.     AppInfoTableEntry* entry;
  3651.     tAppIdConfig *pConfig = appIdNewConfigGet();
  3652.  
  3653.     if ((entry = appInfoEntryGet(appId, pConfig)))
  3654.     {
  3655.         entry->flags |= APPINFO_FLAG_ACTIVE;
  3656.         extractsInfo &= (APPINFO_FLAG_CLIENT_ADDITIONAL | APPINFO_FLAG_CLIENT_USER);
  3657.         if (!extractsInfo)
  3658.         {
  3659.             _dpd.debugMsg(DEBUG_LOG,"Ignoring direct client application without info for %p %p with AppId %d\n",fcn, data, appId);
  3660.             return;
  3661.         }
  3662.  
  3663.         entry->clntValidator = ClientAppGetClientAppModule(fcn, data, &pConfig->clientAppConfig);
  3664.         if (entry->clntValidator)
  3665.             entry->flags |= extractsInfo;
  3666.         else
  3667.             _dpd.errMsg("AppId: Failed to find a client application module for %p %p with AppId %d", fcn, data, appId);
  3668.     }
  3669.     else
  3670.     {
  3671.         _dpd.errMsg("Invalid direct client application AppId, %d, for %p %p\n",appId, fcn, data);
  3672.         return;
  3673.     }
  3674. }
  3675.  
  3676. void AppIdAddUser(tAppIdData *flowp, const char *username, tAppId appId, int success)
  3677. {
  3678.     if (flowp->username)
  3679.         free(flowp->username);
  3680.     flowp->username = strdup(username);
  3681.     if (!flowp->username)
  3682.         DynamicPreprocessorFatalMessage("Could not allocate username data");
  3683.  
  3684.     flowp->usernameService = appId;
  3685.     if (success)
  3686.         setAppIdExtFlag(flowp, APPID_SESSION_LOGIN_SUCCEEDED);
  3687.     else
  3688.         clearAppIdExtFlag(flowp, APPID_SESSION_LOGIN_SUCCEEDED);
  3689. }
  3690.  
  3691. void AppIdAddDnsQueryInfo(tAppIdData *flow,
  3692.                           uint16_t id,
  3693.                           const uint8_t *host, uint8_t host_len, uint16_t host_offset,
  3694.                           uint16_t record_type)
  3695. {
  3696.     if (!flow->dsession)
  3697.     {
  3698.         if (!(flow->dsession = calloc(1, sizeof(*flow->dsession))))
  3699.             DynamicPreprocessorFatalMessage("Could not allocate dnsSession data");
  3700.     }
  3701.     else if ((flow->dsession->state != 0) && (flow->dsession->id != id))
  3702.     {
  3703.         AppIdResetDnsInfo(flow);
  3704.     }
  3705.  
  3706.     if (flow->dsession->state & DNS_GOT_QUERY)
  3707.         return;
  3708.     flow->dsession->state |= DNS_GOT_QUERY;
  3709.  
  3710.     flow->dsession->id          = id;
  3711.     flow->dsession->record_type = record_type;
  3712.  
  3713.     if (!flow->dsession->host)
  3714.     {
  3715.         if ((host != NULL) && (host_len > 0) && (host_offset > 0))
  3716.         {
  3717.             flow->dsession->host_len    = host_len;
  3718.             flow->dsession->host_offset = host_offset;
  3719.             flow->dsession->host        = dns_parse_host(host, host_len);
  3720.         }
  3721.     }
  3722. }
  3723.  
  3724. void AppIdAddDnsResponseInfo(tAppIdData *flow,
  3725.                              uint16_t id,
  3726.                              const uint8_t *host, uint8_t host_len, uint16_t host_offset,
  3727.                              uint8_t response_type, uint32_t ttl)
  3728. {
  3729.     if (!flow->dsession)
  3730.     {
  3731.         if (!(flow->dsession = calloc(1, sizeof(*flow->dsession))))
  3732.             DynamicPreprocessorFatalMessage("Could not allocate dnsSession data");
  3733.     }
  3734.     else if ((flow->dsession->state != 0) && (flow->dsession->id != id))
  3735.     {
  3736.         AppIdResetDnsInfo(flow);
  3737.     }
  3738.  
  3739.     if (flow->dsession->state & DNS_GOT_RESPONSE)
  3740.         return;
  3741.     flow->dsession->state |= DNS_GOT_RESPONSE;
  3742.  
  3743.     flow->dsession->id            = id;
  3744.     flow->dsession->response_type = response_type;
  3745.     flow->dsession->ttl           = ttl;
  3746.  
  3747.     if (!flow->dsession->host)
  3748.     {
  3749.         if ((host != NULL) && (host_len > 0) && (host_offset > 0))
  3750.         {
  3751.             flow->dsession->host_len    = host_len;
  3752.             flow->dsession->host_offset = host_offset;
  3753.             flow->dsession->host        = dns_parse_host(host, host_len);
  3754.         }
  3755.     }
  3756. }
  3757.  
  3758. void AppIdResetDnsInfo(tAppIdData *flow)
  3759. {
  3760.     if (flow->dsession)
  3761.     {
  3762.         free(flow->dsession->host);
  3763.         memset(flow->dsession, 0, sizeof(*(flow->dsession)));
  3764.     }
  3765. }
  3766.  
  3767. void AppIdAddPayload(tAppIdData *flow, tAppId payload_id)
  3768. {
  3769.     checkSandboxDetection(payload_id);
  3770.     flow->payloadAppId = payload_id;
  3771. }
  3772.  
  3773. tAppId getOpenAppId(void *ssnptr)
  3774. {
  3775.     tAppIdData *session;
  3776.     tAppId payloadAppId = APP_ID_NONE;
  3777.     if (ssnptr && (session = getAppIdData(ssnptr)))
  3778.     {
  3779.         payloadAppId = session->payloadAppId;
  3780.     }
  3781.  
  3782.     return payloadAppId;
  3783. }
  3784.  
  3785. /**
  3786.  * @returns 1 if some appid is found, 0 otherwise.
  3787.  */
  3788. int sslAppGroupIdLookup(void *ssnptr, const char * serverName, const char * commonName,
  3789.         tAppId *serviceAppId, tAppId *clientAppId, tAppId *payloadAppId)
  3790. {
  3791.     tAppIdData *session;
  3792.     *serviceAppId = *clientAppId = *payloadAppId = APP_ID_NONE;
  3793.  
  3794.     if (commonName)
  3795.     {
  3796.         ssl_scan_cname((const uint8_t *)commonName, strlen(commonName), clientAppId, payloadAppId, &pAppidActiveConfig->serviceSslConfig);
  3797.     }
  3798.     if (serverName)
  3799.     {
  3800.         ssl_scan_hostname((const uint8_t *)serverName, strlen(serverName), clientAppId, payloadAppId, &pAppidActiveConfig->serviceSslConfig);
  3801.     }
  3802.  
  3803.     if (ssnptr && (session = getAppIdData(ssnptr)))
  3804.  
  3805.     {
  3806.         *serviceAppId = pickServiceAppId(session);
  3807.         if(*clientAppId == APP_ID_NONE) {
  3808.             *clientAppId = pickClientAppId(session);
  3809.         }
  3810.         if(*payloadAppId == APP_ID_NONE) {
  3811.             *payloadAppId = pickPayloadId(session);
  3812.         }
  3813.  
  3814.     }
  3815.     if(*serviceAppId != APP_ID_NONE ||
  3816.             *clientAppId != APP_ID_NONE ||
  3817.             *payloadAppId != APP_ID_NONE)
  3818.     {
  3819.         return 1;
  3820.     }
  3821.     return 0;
  3822. }
  3823.  
  3824. void httpHeaderCallback (SFSnortPacket *p, HttpParsedHeaders *const headers)
  3825. {
  3826.     tAppIdData *session;
  3827.     int direction;
  3828.     tAppIdConfig *pConfig = appIdActiveConfigGet();
  3829.  
  3830.     if (thirdparty_appid_module)
  3831.         return;
  3832.     if (!p || !(session = getAppIdData(p->stream_session)))
  3833.         return;
  3834.  
  3835.     direction = (_dpd.sessionAPI->get_packet_direction(p) & FLAG_FROM_CLIENT) ? APP_ID_FROM_INITIATOR : APP_ID_FROM_RESPONDER;
  3836.  
  3837. #ifdef DEBUG_APP_ID_SESSIONS
  3838.     {
  3839.             char src_ip[INET6_ADDRSTRLEN];
  3840.             char dst_ip[INET6_ADDRSTRLEN];
  3841.             sfaddr_t *ip;
  3842.  
  3843.             src_ip[0] = 0;
  3844.             ip = GET_SRC_IP(p);
  3845.             inet_ntop(sfaddr_family(ip), (void *)sfaddr_get_ptr(ip), src_ip, sizeof(src_ip));
  3846.             dst_ip[0] = 0;
  3847.             ip = GET_DST_IP(p);
  3848.             inet_ntop(sfaddr_family(ip), (void *)sfaddr_get_ptr(ip), dst_ip, sizeof(dst_ip));
  3849.             fprintf(SF_DEBUG_FILE, "AppId Http Callback Session %s-%u -> %s-%u %d\n", src_ip,
  3850.                     (unsigned)p->src_port, dst_ip, (unsigned)p->dst_port, IsTCP(p) ? IPPROTO_TCP:IPPROTO_UDP);
  3851.     }
  3852. #endif
  3853.  
  3854.     if (!session->hsession)
  3855.     {
  3856.         if (!(session->hsession = calloc(1, sizeof(*session->hsession))))
  3857.             DynamicPreprocessorFatalMessage("Could not allocate httpSession data");
  3858.     }
  3859.  
  3860.     if (direction == APP_ID_FROM_INITIATOR)
  3861.     {
  3862.         if (headers->host.start)
  3863.         {
  3864.             free(session->hsession->host);
  3865.             session->hsession->host = strndup((char *)headers->host.start, headers->host.len);
  3866.             session->scan_flags |= SCAN_HTTP_HOST_URL_FLAG;
  3867.  
  3868.             if (headers->url.start)
  3869.             {
  3870.                 free(session->hsession->url);
  3871.                 session->hsession->url = malloc(sizeof(HTTP_PREFIX) + headers->host.len + headers->url.len);
  3872.                 if (session->hsession->url)
  3873.                 {
  3874.                     strcpy(session->hsession->url, HTTP_PREFIX);
  3875.                     strncat(session->hsession->url, (char *)headers->host.start, headers->host.len);
  3876.                     strncat(session->hsession->url, (char *)headers->url.start, headers->url.len);
  3877.                     session->scan_flags |= SCAN_HTTP_HOST_URL_FLAG;
  3878.                 }
  3879.             }
  3880.         }
  3881.         if (headers->userAgent.start)
  3882.         {
  3883.             free(session->hsession->useragent);
  3884.             session->hsession->useragent  = strndup((char *)headers->userAgent.start, headers->userAgent.len);
  3885.             session->scan_flags |= SCAN_HTTP_USER_AGENT_FLAG;
  3886.         }
  3887.         if (headers->referer.start)
  3888.         {
  3889.             free(session->hsession->referer);
  3890.             session->hsession->referer  = strndup((char *)headers->referer.start, headers->referer.len);
  3891.  
  3892.         }
  3893.         if (headers->via.start)
  3894.         {
  3895.             free(session->hsession->via);
  3896.             session->hsession->via  = strndup((char *)headers->via.start, headers->via.len);
  3897.             session->scan_flags |= SCAN_HTTP_VIA_FLAG;
  3898.         }
  3899.  
  3900.     }
  3901.     else
  3902.     {
  3903.         if (headers->via.start)
  3904.         {
  3905.             free(session->hsession->via);
  3906.             session->hsession->via  = strndup((char *)headers->via.start, headers->via.len);
  3907.             session->scan_flags |= SCAN_HTTP_VIA_FLAG;
  3908.         }
  3909.         if (headers->contentType.start)
  3910.         {
  3911.             free(session->hsession->content_type);
  3912.             session->hsession->content_type  = strndup((char *)headers->contentType.start, headers->contentType.len);
  3913.         }
  3914.         if (headers->responseCode.start)
  3915.         {
  3916.             long responseCodeNum;
  3917.             responseCodeNum = strtoul((char *)headers->responseCode.start, NULL, 10);
  3918.             if (responseCodeNum > 0 && responseCodeNum < 700)
  3919.             {
  3920.                 free(session->hsession->response_code);
  3921.                 session->hsession->response_code  = strndup((char *)headers->responseCode.start, headers->responseCode.len);
  3922.             }
  3923.         }
  3924.     }
  3925.     processHTTPPacket(p, session, direction, headers, pConfig);
  3926.  
  3927.     setAppIdExtFlag(session, APPID_SESSION_SERVICE_DETECTED);
  3928.     setAppIdExtFlag(session, APPID_SESSION_HTTP_SESSION);
  3929.  
  3930.     _dpd.streamAPI->set_application_id(p->stream_session, pickServiceAppId(session), pickClientAppId(session), pickPayloadId(session), pickMiscAppId(session));
  3931. }
  3932.  
  3933. static void ExamineRtmpMetadata(tAppIdData *appIdSession)
  3934. {
  3935.     tAppId serviceAppId = 0;
  3936.     tAppId clientAppId = 0;
  3937.     tAppId payloadAppId = 0;
  3938.     tAppId referredPayloadAppId = 0;
  3939.     char *version = NULL;
  3940.     httpSession *hsession;
  3941.     tAppIdConfig *pConfig = appIdActiveConfigGet();
  3942.  
  3943.     if (!appIdSession->hsession)
  3944.     {
  3945.         if (!(appIdSession->hsession = calloc(1, sizeof(*appIdSession->hsession))))
  3946.             DynamicPreprocessorFatalMessage("Could not allocate httpSession data");
  3947.     }
  3948.  
  3949.     hsession = appIdSession->hsession;
  3950.  
  3951.     if (hsession->url)
  3952.     {
  3953.         if (((getAppIdFromUrl(NULL, hsession->url, &version,
  3954.                             hsession->referer, &clientAppId, &serviceAppId,
  3955.                             &payloadAppId, &referredPayloadAppId, 1, &pConfig->detectorHttpConfig)) ||
  3956.                     (getAppIdFromUrl(NULL, hsession->url, &version,
  3957.                                      hsession->referer, &clientAppId, &serviceAppId,
  3958.                                      &payloadAppId, &referredPayloadAppId, 0, &pConfig->detectorHttpConfig))) == 1)
  3959.  
  3960.         {
  3961.             /* do not overwrite a previously-set client or service */
  3962.             if (appIdSession->clientAppId <= APP_ID_NONE)
  3963.                 setClientAppIdData(appIdSession, clientAppId, NULL);
  3964.             if (appIdSession->serviceAppId <= APP_ID_NONE)
  3965.                 setServiceAppIdData(appIdSession, serviceAppId, NULL, NULL);
  3966.  
  3967.             /* DO overwrite a previously-set payload */
  3968.             setPayloadAppIdData(appIdSession, payloadAppId, NULL);
  3969.             setReferredPayloadAppIdData(appIdSession, referredPayloadAppId);
  3970.         }
  3971.     }
  3972. }
  3973.  
  3974. void checkSandboxDetection(tAppId appId)
  3975. {
  3976.     AppInfoTableEntry *entry;
  3977.     tAppIdConfig *pConfig = appIdActiveConfigGet();
  3978.  
  3979.     if (appidStaticConfig.instance_id && pConfig)
  3980.     {
  3981.         entry = appInfoEntryGet(appId, pConfig);
  3982.         if (entry && entry->flags & APPINFO_FLAG_ACTIVE)
  3983.         {
  3984.             fprintf(SF_DEBUG_FILE, "add service\n");
  3985.             fprintf(SF_DEBUG_FILE, "Detected AppId %d\n", entry->appId);
  3986.         }
  3987.     }
  3988. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement