Beispiel #1
0
    def test_tcp_states(self):
        nc = NetworkConnection()
        nc.source_tcp_state = "LISTEN"
        nc.destination_tcp_state = "ESTABLISHED"

        nc2 = round_trip(nc)
        self.assertEqual(nc.to_dict(), nc2.to_dict())
    def test_tcp_states(self):
        nc = NetworkConnection()
        nc.source_tcp_state = "LISTEN"
        nc.destination_tcp_state = "ESTABLISHED"

        nc2 = round_trip(nc)
        self.assertEqual(nc.to_dict(), nc2.to_dict())
    def builder_to_stix_object(self, object_data):
        network_connection = NetworkConnection()

        src_socket_address = ObservableObjectGenerator._generate_socket_object(
            object_data['source_socket_address'])
        dst_socket_address = ObservableObjectGenerator._generate_socket_object(
            object_data['destination_socket_address'])

        network_connection.source_socket_address = src_socket_address
        network_connection.destination_socket_address = dst_socket_address

        return network_connection
Beispiel #4
0
def create_network_connection_closed_observable(ct):
    obj = NetworkConnection()
    obj.creation_time = d[ct]['timestamp']
    sock = SocketAddress()
    sock.ip_address = d[ct]['src_ip']
    obj.source_socket_address = sock
    obj.custom_properties = CustomProperties()
    create_custom_properties(obj, "Event_Name", d[ct]['eventid'])
    create_custom_properties(obj, "Message", d[ct]['message'])
    create_custom_properties(obj, "Service", d[ct]['system'])
    create_custom_properties(obj, "Host", d[ct]['sensor'])
    create_custom_properties(obj, "session_Duration", d[ct]['duration'])
    return obj
Beispiel #5
0
def DNSRequestObj(dnsinfo):
    networkconnection = NetworkConnection()
    networkconnection.layer3_protocol = "IPv4"
    networkconnection.layer4_protocol = "UDP"
    networkconnection.layer7_protocol = "DNS"
    ssocketaddress = SocketAddress()
    sport = Port()
    sport.port_value = dnsinfo[1]
    sport.layer4_protocol = "UDP"
    ssocketaddress.port = sport
    networkconnection.source_socket_address = ssocketaddress
    dsocketaddress = SocketAddress()
    dsocketaddress.ip_address = dnsinfo[2]
    dport = Port()
    dport.port_value = dnsinfo[3]
    dport.layer4_protocol = "UDP"
    dsocketaddress.port = dport
    networkconnection.destination_socket_address = dsocketaddress
    layer7connections = Layer7Connections()
    dqr = DNSQuery()
    indicator = Indicator()
    dnsques = DNSQuestion()
    dnsques.qname = dnsinfo[4]
    dnsques.qtype = translateType(dnsinfo[5])
    dqr.question = dnsques
    indicator.title = "DNS Request"
    indicator.description = (
        "An indicator containing information about a DNS Request")
    layer7connections.dns_query = dqr
    networkconnection.layer7_connections = layer7connections
    indicator.set_produced_time(utils.dates.now())
    indicator.add_object(networkconnection)
    return indicator
Beispiel #6
0
def TCPConnectionEstablishedObj(tcpinfo):
    networkconnection = NetworkConnection()
    networkconnection.layer3_protocol = "IPv4"
    networkconnection.layer4_protocol = "TCP"
    if tcpinfo[0] != VMIP:  # incoming connection
        networkconnection.destination_tcp_state = "ESTABLISHED"
        ssocketaddress = SocketAddress()
        ssocketaddress.ip_address = tcpinfo[0]
        sport = Port()
        sport.port_value = tcpinfo[2]
        sport.layer4_protocol = "TCP"
        ssocketaddress.port = sport
        networkconnection.source_socket_address = ssocketaddress
    elif tcpinfo[1] != VMIP:  # outgoing connection
        networkconnection.source_tcp_state = "ESTABLISHED"
        dsocketaddress = SocketAddress()
        dsocketaddress.ip_address = tcpinfo[1]
        dport = Port()
        dport.port_value = tcpinfo[3]
        dport.layer4_protocol = "TCP"
        dsocketaddress.port = dport
        networkconnection.destination_socket_address = dsocketaddress
    indicator = Indicator()
    indicator.title = "TCP Connection Established"
    indicator.description = (
        "An indicator containing information about a successful TCP hand shake"
    )
    indicator.set_produced_time(utils.dates.now())
    indicator.add_object(networkconnection)
    return indicator
    def from_dict(process_dict, process_cls = None):
        if not process_dict:
            return None                
        if process_cls == None:
            process_ = Process()
        else:
            process_ = process_cls
        
        ObjectProperties.from_dict(process_dict, process_)
        process_.is_hidden = process_dict.get('is_hidden')
        process_.pid = UnsignedInteger.from_dict(process_dict.get('pid'))
        process_.name = String.from_dict(process_dict.get('name'))
        process_.creation_time = DateTime.from_dict(process_dict.get('creation_time'))
        process_.parent_pid = UnsignedInteger.from_dict(process_dict.get('parent_pid'))
        process_.child_pid_list = [UnsignedInteger.from_dict(x) for x in process_dict.get('child_pid_list', [])]
        process_.image_info = ImageInfo.from_dict(process_dict.get('image_info'))
        process_.argument_list = [String.from_dict(x) for x in process_dict.get('argument_list', [])]
        process_.environment_variable_list = EnvironmentVariableList.from_list(process_dict.get('environment_variable_list'))
        process_.kernel_time = Duration.from_dict(process_dict.get('kernel_time'))
        process_.port_list = [Port.from_dict(x) for x in process_dict.get('port_list', [])]
        process_.network_connection_list = [NetworkConnection.from_dict(x) for x in process_dict.get('network_connection_list', [])]
        process_.start_time = DateTime.from_dict(process_dict.get('start_time'))
        process_.username = String.from_dict(process_dict.get('username'))
        process_.user_time = Duration.from_dict(process_dict.get('user_time'))
        process_.extracted_features = None

        return process_
Beispiel #8
0
def SSHObj(SSH):
    networkconnection = NetworkConnection()
    networkconnection.layer3_protocol = "IPv4"
    networkconnection.layer4_protocol = "TCP"
    networkconnection.layer7_protocol = "SSH"
    if SSH[0] != VMIP and SSH[4] == 1 and SSH[5] == 0:  # incoming connection
        ssocketaddress = SocketAddress()
        ssocketaddress.ip_address = SSH[0]
        sport = Port()
        sport.port_value = SSH[1]
        sport.layer4_protocol = "TCP"
        ssocketaddress.port = sport
        networkconnection.source_socket_address = ssocketaddress
    elif SSH[2] != VMIP and SSH[4] == 1 and SSH[5] == 0:  # outgoing connection
        dsocketaddress = SocketAddress()
        dsocketaddress.ip_address = SSH[2]
        dport = Port()
        dport.port_value = SSH[3]
        dport.layer4_protocol = "TCP"
        dsocketaddress.port = dport
        networkconnection.destination_socket_address = dsocketaddress
    indicator = Indicator()
    if SSH[6] != '':
        indicator.title = "SSH Request with pulic key"
        indicator.description = ("SSH public key: " + SSH[6])
    else:
        indicator.title = "SSH Request"
        indicator.description = (
            "An indicator containing information about a SSH request")
    indicator.set_produced_time(utils.dates.now())
    indicator.add_object(networkconnection)
    return indicator
Beispiel #9
0
def ICMPObj(icmp):
    # block types 0 (ping response), 8 (ping request)
    nc = NetworkConnection()
    indicator = Indicator()
    nc.layer3_protocol = "ICMP"
    if icmp[0] == 0:  # echo-reply
        if icmp[1] != VMIP:  # incoming reply from a server VM pinged
            ssocketaddress = SocketAddress()
            ssocketaddress.ip_address = icmp[1]
            nc.source_socket_address = ssocketaddress
            indicator.title = "ICMP echo-reply"
            indicator.description = ("0")
        else:  # outgoing reply to a server that pinged you
            dsocketaddress = SocketAddress()
            dsocketaddress.ip_address = icmp[2]
            nc.destination_socket_address = dsocketaddress
            indicator.title = "ICMP echo-reply"
            indicator.description = ("0")
    elif icmp[0] == 8:  # echo-request
        if icmp[1] != VMIP:  # incoming ping request from a server
            ssocketaddress = SocketAddress()
            ssocketaddress.ip_address = icmp[1]
            nc.source_socket_address = ssocketaddress
            indicator.title = "ICMP echo-request"
            indicator.description = ("8")
        else:  # VM is sending a ping request
            dsocketaddress = SocketAddress()
            dsocketaddress.ip_address = icmp[2]
            nc.destination_socket_address = dsocketaddress
            indicator.title = "ICMP echo-request"
            indicator.description = ("8")
    indicator.set_produced_time(utils.dates.now())
    indicator.add_object(nc)
    return indicator
Beispiel #10
0
def UDPRequestObj(udpinfo):
    u = NetworkConnection()
    u.layer3_protocol = "IPv4"
    u.layer4_protocol = "UDP"
    ssocketaddress = SocketAddress()
    if udpinfo[3] != VMIP:
        ssocketaddress.ip_address = udpinfo[3]
        sport = Port()
        sport.port_value = udpinfo[0]
        sport.layer4_protocol = "UDP"
        ssocketaddress.port = sport
        u.source_socket_address = ssocketaddress
    dsocketaddress = SocketAddress()
    if udpinfo[2] != VMIP:
        dsocketaddress.ip_address = udpinfo[2]
        dport = Port()
        dport.port_value = udpinfo[1]
        dport.layer4_protocol = "UDP"
        dsocketaddress.port = dport
        u.destination_socket_address = dsocketaddress
    indicator = Indicator()
    indicator.title = "UDP connection"
    indicator.description = (
        "An indicator containing information about a UDP connection")
    indicator.set_produced_time(utils.dates.now())
    indicator.add_object(u)
    return indicator
def _address_ssh(addressParam,indicatorIns):
    
    from cybox.objects.address_object import Address
    from cybox.objects.uri_object import URI
    from cybox.core import observable
    from cybox import helper
    from cybox.objects.network_connection_object import NetworkConnection as Connection
    
    thisIndicDesc = addressParam['indicDesc']
    if testMode:
        print "ipV4 and ssh"
    
    tmpProto =  protocolsList.get(addressParam['strProtocol'])
    if testMode:             
        print "Protocol" + tmpProto
    
    if tmpProto is not None:
        connDict = {'layer7_protocol':addressParam['strDescShort'],'layer4_protocol':tmpProto,'source_socket_address':{'ip_address':addressParam['strAddress'],'port':{'port_value':addressParam['strPortList']}}}
    else:
        connDict = {'layer7_protocol':addressParam['strDescShort'],'layer4_protocol':'TCP','source_socket_address':{'ip_address':addressParam['strAddress'],'port':{'port_value':addressParam['strPortList']}}}
    
    indicatorIns.add_observable(observable.Observable(Connection.from_dict(connDict)))
                
    #IP address +asn,rir,cc,prefix
    if addressParam['strAsn'] and addressParam['strAsnDesc'] and addressParam['strCc'] and addressParam['strRir']:
        thisIndicDesc = thisIndicDesc + "asn_desc = " + addressParam['strAsnDesc'] + "; Internet Registry = " + addressParam['strRir'] + "; Country Code = " + addressParam['strCc']
        indicatorIns.add_observable(observable.Observable(Address(addressParam['strAsn'],'asn')))
        if testMode:
            print "it's asn"
                
    if addressParam['strRdata']:
        indicatorIns.add_observable(observable.Observable(URI(addressParam['strRdata'],'Domain Name')))
        if testMode:
            print "It's domain"
                    
    if addressParam['strPrefix']:
        thisIndicDesc = thisIndicDesc + "; Prefix = " + addressParam['strPrefix']
        if testMode:
            print "it's prefix"
            
    return thisIndicDesc
Beispiel #12
0
def create_network_connection_observable(ct):
    obj = NetworkConnection()
    obj.creation_time = d[ct]['timestamp']
    obj.layer7_protocol = d[ct]['protocol']

    # src_info
    obj.source_socket_address = create_socket_address(d[ct]['src_ip'],
                                                      d[ct]['src_port'])

    # dst_info
    obj.destination_socket_address = create_socket_address(
        d[ct]['dst_ip'], d[ct]['dst_port'])

    #create_custom_properties
    obj.custom_properties = CustomProperties()
    create_custom_properties(obj, "Event_Name", d[ct]['eventid'])
    create_custom_properties(obj, "Message", d[ct]['message'])
    create_custom_properties(obj, "Service", d[ct]['system'])
    create_custom_properties(obj, "Host", d[ct]['sensor'])
    return obj
    def from_obj(process_obj, process_cls = None):
        if not process_obj:
            return None                
        if process_cls == None:
            process_ = Process()
        else:
            process_ = process_cls

        ObjectProperties.from_obj(process_obj, process_)
        process_.is_hidden = process_obj.get_is_hidden()
        process_.pid = UnsignedInteger.from_obj(process_obj.get_PID())
        process_.name = String.from_obj(process_obj.get_Name())
        process_.creation_time = DateTime.from_obj(process_obj.get_Creation_Time())
        process_.parent_pid = UnsignedInteger.from_obj(process_obj.get_Parent_PID())
        process_.image_info = ImageInfo.from_obj(process_obj.get_Image_Info())
        process_.environment_variable_list = EnvironmentVariableList.from_obj(process_obj.get_Environment_Variable_List())
        process_.kernel_time = Duration.from_obj(process_obj.get_Kernel_Time())
        process_.start_time = DateTime.from_obj(process_obj.get_Start_Time())
        process_.username = String.from_obj(process_obj.get_Username())
        process_.user_time = Duration.from_obj(process_obj.get_User_Time())
        process_.extracted_features = None
        if process_obj.get_Argument_List() is not None : process_.argument_list = [String.from_obj(x) for x in process_obj.get_Argument_List().get_Argument()]
        if process_obj.get_Child_PID_List() is not None : process_.child_pid_list = [UnsignedInteger.from_obj(x) for x in process_obj.get_Child_PID_List().get_Child_PID()]
        if process_obj.get_Port_List() is not None : process_.port_list = [Port.from_obj(x) for x in process_obj.get_Port_List().get_Port()]
        if process_obj.get_Network_Connection_List() is not None : process_.network_connection_list = [NetworkConnection.from_obj(x) for x in process_obj.get_Network_Connection_List().get_Network_Connection()]
        return process_
Beispiel #14
0
def createDynamicIndicators(stix_package, dynamicindicators):
    filescreated = False
    processesstarted = False
    regkeyscreated = False
    mutexescreated = False
    hostscontacted = False
    hasdynamicindicators = False

    # Here we are just testing to see if the report had any
    # of the various dynamic indicator types so we know whether
    # or not to process them at all
    if len(dynamicindicators['droppedfiles']) > 0:
        filescreated = True
        hasdynamicindicators = True
    if len(dynamicindicators['processes']) > 0:
        processesstarted = True
        hasdynamicindicators = True
    if len(dynamicindicators['regkeys']) > 0:
        regkeyscreated = True
        hasdynamicindicators = True
    if len(dynamicindicators['mutexes']) > 0:
        mutexescreated = True
        hasdynamicindicators = True
    if len(dynamicindicators['hosts']) > 0:
        hostscontacted = True
        hasdynamicindicators = True

    if not hasdynamicindicators:
        return

    if filescreated:
        createdfilesind = Indicator()
        for createdfile in dynamicindicators['droppedfiles']:
            createdfilename = File()
            createdfilename.file_name = createdfile[0]
            createdfilename.size_in_bytes = createdfile[1]
            createdfilename.md5 = createdfile[2]
            createdfilename.sha1 = createdfile[3]
            createdfilename.sha256 = createdfile[4]
            createdfilesind.add_observable(Observable(createdfilename))

        stix_package.add_indicator(createdfilesind)
    if processesstarted:
        procindicator = Indicator()
        for process in dynamicindicators['processes']:
            # Process name
            processname = process[0]
            # Process pid
            processpid = process[1]
            # Process parent pid
            processparentpid = process[2]

        proc = Process()
        proc.name = processname
        proc.pid = processpid
        proc.parent_pid = processparentpid
        procindicator.add_observable(Observable(proc))

        stix_package.add_indicator(procindicator)
    if regkeyscreated:
        regindicator = Indicator()
        keypath = WinRegistryKey()

        for regkey in dynamicindicators['regkeys']:
            keypath = WinRegistryKey()
            keypath.key = regkey
            regindicator.add_observable(Observable(keypath))

        stix_package.add_indicator(regindicator)
    if not mutexescreated:
        mutexind = Indicator()
        for mutex in dynamicindicators['mutexes']:
            winhandle = WinHandle()
            winhandle.name = mutex
            winmutex = WinMutex()
            winmutex.handle = winhandle
            mutexind.add_observable(Observable(winmutex))
        stix_package.add_indicator(mutexind)
    if hostscontacted:
        networkconnectionind = Indicator()
        for host in dynamicindicators['hosts']:
            networkconnection = NetworkConnection()
            socketaddress = SocketAddress()
            socketaddress.ip_address = host
            networkconnection.destination_socket_address = socketaddress
            networkconnectionind.add_observable(Observable(networkconnection))
        stix_package.add_indicator(networkconnectionind)
        return
Beispiel #15
0
    def transform(self, event):
        self._set_namespace(self.config['contact_domain'], self.config['contact_name'])
        stix_package = STIXPackage()
        self._add_header(stix_package, "Unauthorized traffic to honeypot", "Describes one or more honeypot incidents")

        incident = Incident(id_="%s:%s-%s" % (self.config['contact_name'], 'incident', event['session_id']))
        initial_time = StixTime()
        initial_time.initial_compromise = event['timestamp'].isoformat()
        incident.time = initial_time
        incident.title = "Conpot Event"
        incident.short_description = "Traffic to Conpot ICS honeypot"
        incident.add_category(VocabString(value='Scans/Probes/Attempted Access'))

        tool_list = ToolInformationList()
        tool_list.append(ToolInformation.from_dict({
            'name': "Conpot",
            'vendor': "Conpot Team",
            'version': conpot.__version__,
            'description': textwrap.dedent('Conpot is a low interactive server side Industrial Control Systems '
                                           'honeypot designed to be easy to deploy, modify and extend.')
        }))
        incident.reporter = InformationSource(tools=tool_list)

        incident.add_discovery_method("Monitoring Service")
        incident.confidence = "High"

        # Victim Targeting by Sector
        ciq_identity = CIQIdentity3_0Instance()
        #identity_spec = STIXCIQIdentity3_0()
        #identity_spec.organisation_info = OrganisationInfo(industry_type="Electricity, Industrial Control Systems")
        #ciq_identity.specification = identity_spec
        ttp = TTP(title="Victim Targeting: Electricity Sector and Industrial Control System Sector")
        ttp.victim_targeting = VictimTargeting()
        ttp.victim_targeting.identity = ciq_identity

        incident.leveraged_ttps.append(ttp)

        indicator = Indicator(title="Conpot Event")
        indicator.description = "Conpot network event"
        indicator.confidence = "High"
        source_port = Port.from_dict({'port_value': event['remote'][1], 'layer4_protocol': 'tcp'})
        dest_port = Port.from_dict({'port_value': self.protocol_to_port_mapping[event['data_type']],
                                    'layer4_protocol': 'tcp'})
        source_ip = Address.from_dict({'address_value': event['remote'][0], 'category': Address.CAT_IPV4})
        dest_ip = Address.from_dict({'address_value': event['public_ip'], 'category': Address.CAT_IPV4})
        source_address = SocketAddress.from_dict({'ip_address': source_ip.to_dict(), 'port': source_port.to_dict()})
        dest_address = SocketAddress.from_dict({'ip_address': dest_ip.to_dict(), 'port': dest_port.to_dict()})
        network_connection = NetworkConnection.from_dict(
            {'source_socket_address': source_address.to_dict(),
             'destination_socket_address': dest_address.to_dict(),
             'layer3_protocol': u"IPv4",
             'layer4_protocol': u"TCP",
             'layer7_protocol': event['data_type'],
             'source_tcp_state': u"ESTABLISHED",
             'destination_tcp_state': u"ESTABLISHED",
             }
        )
        indicator.add_observable(Observable(network_connection))

        artifact = Artifact()
        artifact.data = json.dumps(event['data'])
        artifact.packaging.append(ZlibCompression())
        artifact.packaging.append(Base64Encoding())
        indicator.add_observable(Observable(artifact))

        incident.related_indicators.append(indicator)
        stix_package.add_incident(incident)

        stix_package_xml = stix_package.to_xml()
        return stix_package_xml
Beispiel #16
0
def home(request):
    """
		Name: home
		Desc: Main GUI view

	"""

    # Forms:Job,target and relay creation
    create_job_form = CreateJob(request=request, prefix="create_job")
    create_target_form = CreateTarget(request=request, prefix="create_target")
    create_relay_form = CreateRelay(request=request, prefix="create_relay")

    if request.method == "POST":

        # Remove a relay
        if "delete_relay_id" in request.POST:

            try:

                Relay.objects.get(pk=request.POST["delete_relay_id"]).delete()

            except ObjectDoesNotExist, e:

                pass

        # Create new relay
        if "create_relay-name" in request.POST:

            # Actuator creation
            create_relay_form = CreateRelay(request.POST,
                                            request=request,
                                            prefix="create_relay")
            if create_relay_form.is_valid():

                host = create_relay_form.save()
                host.save()

            # TODO - Call a sync here

        # Job Creations
        if "create_job-raw_message" in request.POST:

            new_job = Job(capability=Capability.objects.get(
                pk=request.POST["create_job-capability"]),
                          target=Target.objects.get(
                              pk=request.POST["create_job-target"]),
                          raw_message="Pending",
                          status=JobStatus.objects.get(status="Pending"),
                          created_by=request.user)

            new_job.save()

            # Now we have a pk - update the id

            command = json.loads(request.POST["create_job-raw_message"])
            command["modifiers"]["command-ref"] = new_job.id

            logger.info("Job Created\n%s" % json.dumps(command))

            new_job.raw_message = json.dumps(command, sort_keys=True,
                                             indent=4).replace(
                                                 "\t", u'\xa0\xa0\xa0\xa0\xa0')
            new_job.save()

        # Target Creations

        namespace_url = getattr(settings, "NAMESPACE_URL", None)
        namespace_id = getattr(settings, "NAMESPACE_ID", None)

        set_id_namespace(Namespace(namespace_url, namespace_id))

        if "create_target-cybox_type" in request.POST:

            cybox_type = CybOXType.objects.get(
                pk=request.POST["create_target-cybox_type"])

            if cybox_type.identifier == "cybox:NetworkConnectionObjectType":

                obs = NetworkConnection()

                # Source
                sock = SocketAddress()
                sock.ip_address = request.POST["create_target-source_address"]
                sock.ip_address.category = "ipv4-addr"
                sock.ip_address.condition = "Equals"
                sport = Port()
                sport.port_value = int(
                    request.POST["create_target-source_port"])
                sock.port = sport
                obs.source_socket_address = sock

                # Dest
                sock = SocketAddress()
                sock.ip_address = request.POST[
                    "create_target-destination_address"]
                sock.ip_address.category = "ipv4-addr"
                sock.ip_address.condition = "Equals"
                dport = Port()
                dport.port_value = int(
                    request.POST["create_target-destination_port"])
                sock.port = dport
                obs.destination_socket_address = sock

                name = "Network Connection %s:%s -> %s:%s (%s)" % (
                    request.POST["create_target-source_address"],
                    request.POST["create_target-source_port"],
                    request.POST["create_target-destination_address"],
                    request.POST["create_target-destination_port"],
                    request.POST["create_target-protocol"])

                raw_message = Observable(item=obs, title=name).to_json()

            elif cybox_type.identifier == "cybox:AddressObjectType":

                name = "Address %s " % (request.POST["create_target-address"])
                raw_message = Observable(item=Address(
                    address_value=request.POST["create_target-address"],
                    category=Address.CAT_IPV4),
                                         title=name).to_json()

            elif cybox_type.identifier == "cybox:URIObjectType":
                name = "URI %s " % (request.POST["create_target-uri"])
                obs = URI()
                obs.value = request.POST["create_target-uri"]
                obs.type_ = URI.TYPE_URL
                obs.condition = "Equals"
                raw_message = Observable(item=obs, title=name).to_json()

            elif cybox_type.identifier == "cybox:EmailMessageObjectType":
                name = "Email %s " % (
                    request.POST["create_target-email_subject"])
                obs = EmailMessage()
                obs.raw_body = request.POST["create_target-email_message"]
                obs.header = EmailHeader()
                obs.header.subject = request.POST[
                    "create_target-email_subject"]
                obs.header.subject.condition = "StartsWith"
                obs.header.to = request.POST["create_target-email_to"]
                obs.header.from_ = request.POST["create_target-email_from"]
                raw_message = Observable(item=obs, title=name).to_json()
            else:

                # Should never reach here
                raw_message = {}
                name = "Undefined Object"

            create_target_form = CreateTarget(request.POST,
                                              request=request,
                                              prefix="create_target")

            if create_target_form.is_valid():

                target = create_target_form.save(commit=False)

                target.name = name

                target.raw_message = raw_message

                target.save()
Beispiel #17
0
def make_cybox_object(type_, name=None, value=None):
    """
    Converts type_, name, and value to a CybOX object instance.

    :param type_: The object type.
    :type type_: str
    :param name: The object name.
    :type name: str
    :param value: The object value.
    :type value: str
    :returns: CybOX object
    """

    if type_ == "Account":
        acct = Account()
        acct.description = value
        return acct
    elif type_ == "Address":
        return Address(category=name, address_value=value)
    elif type_ == "Email Message":
        e = EmailMessage()
        e.raw_body = value
        return e
    elif type_ == "API":
        api = API()
        api.description = value
        return api
    elif type_ == "Artifact":
        if name == "Data Region":
            atype = Artifact.TYPE_GENERIC
        elif name == 'FileSystem Fragment':
            atype = Artifact.TYPE_FILE_SYSTEM
        elif name == 'Memory Region':
            atype = Artifact.TYPE_MEMORY
        else:
            raise UnsupportedCybOXObjectTypeError(type_, name)
        return Artifact(value, atype)
    elif type_ == "Code":
        obj = Code()
        obj.code_segment = value
        obj.type = name
        return obj
    elif type_ == "Disk":
        disk = Disk()
        disk.disk_name = type_
        disk.type = name
        return disk
    elif type_ == "Disk Partition":
        disk = DiskPartition()
        disk.device_name = type_
        disk.type = name
        return disk
    elif type_ == "DNS Query":
        r = URI()
        r.value = value
        dq = DNSQuestion()
        dq.qname = r
        d = DNSQuery()
        d.question = dq
        return d
    elif type_ == "DNS Record":
        # DNS Record indicators in CRITs are just a free form text box, there
        # is no good way to map them into the attributes of a DNSRecord cybox
        # object. So just stuff it in the description until someone tells me
        # otherwise.
        d = StructuredText(value=value)
        dr = DNSRecord()
        dr.description = d
        return dr
    elif type_ == "GUI Dialogbox":
        obj = GUIDialogbox()
        obj.box_text = value
        return obj
    elif type_ == "GUI Window":
        obj = GUIWindow()
        obj.window_display_name = value
        return obj
    elif type_ == "HTTP Request Header Fields" and name and name == "User-Agent":
        # TODO/NOTE: HTTPRequestHeaderFields has a ton of fields for info.
        #    we should revisit this as UI is reworked or CybOX is improved.
        obj = HTTPRequestHeaderFields()
        obj.user_agent = value
        return obj
    elif type_ == "Library":
        obj = Library()
        obj.name = value
        obj.type = name
        return obj
    elif type_ == "Memory":
        obj = Memory()
        obj.memory_source = value
        return obj
    elif type_ == "Mutex":
        m = Mutex()
        m.named = True
        m.name = String(value)
        return m
    elif type_ == "Network Connection":
        obj = NetworkConnection()
        obj.layer7_protocol = value
        return obj
    elif type_ == "Pipe":
        p = Pipe()
        p.named = True
        p.name = String(value)
        return p
    elif type_ == "Port":
        p = Port()
        try:
            p.port_value = PositiveInteger(value)
        except ValueError:  # XXX: Raise a better exception...
            raise UnsupportedCybOXObjectTypeError(type_, name)
        return p
    elif type_ == "Process":
        p = Process()
        p.name = String(value)
        return p
    elif type_ == "String":
        c = Custom()
        c.custom_name = "crits:String"
        c.description = ("This is a generic string used as the value of an "
                         "Indicator or Object within CRITs.")
        c.custom_properties = CustomProperties()

        p1 = Property()
        p1.name = "value"
        p1.description = "Generic String"
        p1.value = value
        c.custom_properties.append(p1)
        return c
    elif type_ == "System":
        s = System()
        s.hostname = String(value)
        return s
    elif type_ == "URI":
        r = URI()
        r.type_ = name
        r.value = value
        return r
    elif type_ == "User Account":
        obj = UserAccount()
        obj.username = value
        return obj
    elif type_ == "Volume":
        obj = Volume()
        obj.name = value
        return obj
    elif type_ == "Win Driver":
        w = WinDriver()
        w.driver_name = String(value)
        return w
    elif type_ == "Win Event Log":
        obj = WinEventLog()
        obj.log = value
        return obj
    elif type_ == "Win Event":
        w = WinEvent()
        w.name = String(value)
        return w
    elif type_ == "Win Handle":
        obj = WinHandle()
        obj.type_ = name
        obj.object_address = value
        return obj
    elif type_ == "Win Kernel Hook":
        obj = WinKernelHook()
        obj.description = value
        return obj
    elif type_ == "Win Mailslot":
        obj = WinMailslot()
        obj.name = value
        return obj
    elif type_ == "Win Network Share":
        obj = WinNetworkShare()
        obj.local_path = value
        return obj
    elif type_ == "Win Process":
        obj = WinProcess()
        obj.window_title = value
        return obj
    elif type_ == "Win Registry Key":
        obj = WinRegistryKey()
        obj.key = value
        return obj
    elif type_ == "Win Service":
        obj = WinService()
        obj.service_name = value
        return obj
    elif type_ == "Win System":
        obj = WinSystem()
        obj.product_name = value
        return obj
    elif type_ == "Win Task":
        obj = WinTask()
        obj.name = value
        return obj
    elif type_ == "Win User Account":
        obj = WinUser()
        obj.security_id = value
        return obj
    elif type_ == "Win Volume":
        obj = WinVolume()
        obj.drive_letter = value
        return obj
    elif type_ == "X509 Certificate":
        obj = X509Certificate()
        obj.raw_certificate = value
        return obj
    """
    The following are types that are listed in the 'Indicator Type' box of
    the 'New Indicator' dialog in CRITs. These types, unlike those handled
    above, cannot be written to or read from CybOX at this point.

    The reason for the type being omitted is written as a comment inline.
    This can (and should) be revisited as new versions of CybOX are released.
    NOTE: You will have to update the corresponding make_crits_object function
    with handling for the reverse direction.

    In the mean time, these types will raise unsupported errors.
    """
    #elif type_ == "Device": # No CybOX API
    #elif type_ == "DNS Cache": # No CybOX API
    #elif type_ == "GUI": # revisit when CRITs supports width & height specification
    #elif type_ == "HTTP Session": # No good mapping between CybOX/CRITs
    #elif type_ == "Linux Package": # No CybOX API
    #elif type_ == "Network Packet": # No good mapping between CybOX/CRITs
    #elif type_ == "Network Route Entry": # No CybOX API
    #elif type_ == "Network Route": # No CybOX API
    #elif type_ == "Network Subnet": # No CybOX API
    #elif type_ == "Semaphore": # No CybOX API
    #elif type_ == "Socket": # No good mapping between CybOX/CRITs
    #elif type_ == "UNIX File": # No CybOX API
    #elif type_ == "UNIX Network Route Entry": # No CybOX API
    #elif type_ == "UNIX Pipe": # No CybOX API
    #elif type_ == "UNIX Process": # No CybOX API
    #elif type_ == "UNIX User Account": # No CybOX API
    #elif type_ == "UNIX Volume": # No CybOX API
    #elif type_ == "User Session": # No CybOX API
    #elif type_ == "Whois": # No good mapping between CybOX/CRITs
    #elif type_ == "Win Computer Account": # No CybOX API
    #elif type_ == "Win Critical Section": # No CybOX API
    #elif type_ == "Win Executable File": # No good mapping between CybOX/CRITs
    #elif type_ == "Win File": # No good mapping between CybOX/CRITs
    #elif type_ == "Win Kernel": # No CybOX API
    #elif type_ == "Win Mutex": # No good mapping between CybOX/CRITs
    #elif type_ == "Win Network Route Entry": # No CybOX API
    #elif type_ == "Win Pipe": # No good mapping between CybOX/CRITs
    #elif type_ == "Win Prefetch": # No CybOX API
    #elif type_ == "Win Semaphore": # No CybOX API
    #elif type_ == "Win System Restore": # No CybOX API
    #elif type_ == "Win Thread": # No good mapping between CybOX/CRITs
    #elif type_ == "Win Waitable Timer": # No CybOX API
    raise UnsupportedCybOXObjectTypeError(type_, name)
Beispiel #18
0
def main():
    # NOTE: ID values will differ due to being regenerated on each script execution
    pkg = STIXPackage()
    pkg.title = "Examples of Observable Composition"

    # USE CASE: single obj with single condition
    obs = File()
    obs.file_name = "foo.exe"
    obs.file_name.condition = "Contains"
    pkg.add_observable(obs)

    # USE CASE: single obj with multiple conditions
    obs = File()
    obs.file_name = "foo"
    obs.file_name.condition = "Contains"
    obs.size_in_bytes = '1896000'
    obs.size_in_bytes.condition = "Equals"
    pkg.add_observable(obs)

    # USE CASE: multiple obj with individual conditions
    obs = EmailMessage()

    obs.subject = "Syria strategic plans leaked"
    obs.subject.condition = "Equals"
    file_obj = File()
    file_obj.file_name = "bombISIS.pdf"
    file_obj.file_name.condition = "Equals"
    obs.add_related(file_obj, "Contains")

    pkg.add_observable(obs)

    # USE CASE: multiple objects  with complex condition like (A OR B) AND C

    # orcomp = either of a mutex or file are present

    orcomp = ObservableComposition()
    orcomp.operator = "OR"
    obs = Mutex()
    obs.name = 'foo'
    obs.name.condition = "Contains"

    orcomp.add(obs)

    obs = File()
    obs.file_name = "barfoobar"
    obs.file_name.condition = "Equals"

    orcomp.add(obs)

    # andcomp = the above is true AND a network connection is present
    andcomp = ObservableComposition()
    andcomp.operator = "AND"

    andcomp.add(orcomp)

    obs = NetworkConnection()
    sock = SocketAddress()
    sock.ip_address = "46.123.99.25"
    sock.ip_address.category = "ipv4-addr"
    sock.ip_address.condition = "Equals"
    obs.destination_socket_address = sock
    andcomp.add(obs)

    pkg.add_observable(andcomp)

    # USE CASE:  single object, one property with multiple values
    obs = SocketAddress()
    obs.ip_address = ['10.0.0.0', '10.0.0.1', '10.0.0.2']  # comma delimiter automagically added
    obs.ip_address.condition = "Equals"
    obs.ip_address.apply_condition = "ANY"

    pkg.add_observable(obs)

    print pkg.to_xml()
Beispiel #19
0
    def create_object(self, ce1sus_object, event_permissions, user):
        definition_name = ce1sus_object.definition.name
        obj = Object()
        identifier = 'ce1sus:Object-{0}'.format(ce1sus_object.uuid)
        obj.id_ = identifier
        # try to find automatic the object container
        try:
            clazz = get_class(
                'cybox.objects.{0}_object'.format(definition_name.lower()),
                definition_name)
            instance = clazz()
            if definition_name == 'Disk':
                # TODO: check why this must be set stix bug?
                setattr(instance, 'type_', None)
        except ImportError:
            if definition_name == 'WinEventLog':
                instance = WinEventLog()
                # TODO: check why this must be set stix bug?
                setattr(instance, 'type_', None)
            elif definition_name == 'UserAccount':
                instance = UserAccount()
            elif definition_name == 'WinService':
                instance = WinService()
            elif definition_name == 'WindowsRegistryKey':
                instance = WinRegistryKey()
            elif definition_name == 'NetworkConnection':
                instance = NetworkConnection()
            elif definition_name == 'WinVolume':
                instance = WinVolume()
                # TODO: check why this must be set stix bug?
                setattr(instance, 'drive_type', None)
            elif definition_name == 'WinKernelHook':
                instance = WinKernelHook()
            elif definition_name == 'WinDriver':
                instance = WinDriver()
            elif definition_name == 'DomainName':
                instance = DomainName()
            # TODO: try to map it manually
            elif definition_name == 'email':
                instance = EmailMessage()
            else:
                raise Ce1susStixMapperException(
                    'Required to map manually {0}'.format(definition_name))

        obj.properties = instance

        attributes = ce1sus_object.get_attributes_for_permissions(
            event_permissions, user)
        for attribute in attributes:
            self.map_attribtue(instance, attribute)

        rel_objects = ce1sus_object.get_related_objects_for_permissions(
            event_permissions, user)
        for rel_object in rel_objects:
            ob = self.create_object(rel_object.object, event_permissions, user)
            if ob:
                rel_obj = self.create_related_object(rel_object,
                                                     event_permissions, user)

                # cybox_rel_object = RelatedObject(properties=ob.properties, relationship=rel_object.relation)

                obj.related_objects.append(rel_obj)
        return obj
def main():
    # NOTE: ID values will differ due to being regenerated on each script execution
    pkg1 = STIXPackage()
    pkg1.title = "Example of Indicator Composition for an aggregate indicator composition"

    # USE CASE: Indicator with aggregate pattern

    # Add TTP for malware usage
    malware_ttp = TTP()
    malware_ttp.behavior = Behavior()

    malware = MalwareInstance()
    malware.title = "foobar malware"
    malware.add_type("Remote Access Trojan")
    malware_ttp.behavior.add_malware_instance(malware)

    c2_ttp = TTP()
    c2_ttp.resources = Resource()
    c2_ttp.resources.infrastructure = Infrastructure()
    c2_ttp.resources.infrastructure.add_type(VocabString("Malware C2"))

    pkg1.add_ttp(c2_ttp)
    pkg1.add_ttp(malware_ttp)

    nw_ind = Indicator()
    nw_ind.description = "Indicator for a particular C2 infstructure IP address."
    # add network network connection to this indicator
    obs = NetworkConnection()
    sock = SocketAddress()
    sock.ip_address = "46.123.99.25"
    sock.ip_address.category = "ipv4-addr"
    sock.ip_address.condition = "Equals"
    obs.destination_socket_address = sock
    nw_ind.add_observable(obs)

    nw_ind.add_indicated_ttp(TTP(idref=c2_ttp.id_))

    # create File Hash indicator w/ embedded Observable
    file_ind = Indicator()

    file_ind.description = "Indicator for the hash of the foobar malware."
    file_ind.add_indicator_type("File Hash Watchlist")

    file_obs = File()
    file_obs.add_hash("01234567890abcdef01234567890abcdef")
    file_obs.hashes[0].type_ = "MD5"
    file_obs.hashes[0].type_.condition = "Equals"
    file_ind.add_observable(file_obs)

    # create references
    file_ind.add_indicated_ttp(TTP(idref=malware_ttp.id_))

    # create container indicator
    ind = Indicator()
    ind.add_indicator_type(VocabString("Campaign Characteristics"))
    ind.description = "Indicator for a composite of characteristics for the use of specific malware and C2 infrastructure within a Campaign."

    # Add campaign with related
    camp = Campaign()
    camp.title = "holy grail"
    pkg1.add_campaign(camp)
    camp.related_ttps.append(TTP(idref=c2_ttp.id_))
    camp.related_ttps.append(TTP(idref=malware_ttp.id_))

    # Add threat actor
    ta = ThreatActor()
    ta.identity = Identity()
    ta.identity.name = "boobear"
    ta.observed_ttps.append(TTP(idref=malware_ttp.id_))
    pkg1.add_threat_actor(ta)

    # Create composite expression

    ind.composite_indicator_expression = CompositeIndicatorExpression()
    ind.composite_indicator_expression.operator = "AND"

    ind.composite_indicator_expression.append(file_ind)
    ind.composite_indicator_expression.append(nw_ind)

    pkg1.add_indicator(ind)

    print pkg1.to_xml()

#  USE CASE: Indicator with partial matching

    pkg2 = STIXPackage()
    pkg2.title = "Example of Indicator Composition for a one of many indicator composition"

    # create container indicator
    watchlistind = Indicator()
    watchlistind.add_indicator_type("IP Watchlist")
    watchlistind.description = "This Indicator specifies a pattern where any one or more of a set of three IP addresses are observed."

    watchlistind.add_indicated_ttp(TTP(idref=c2_ttp.id_))

    # Create composite expression
    watchlistind.composite_indicator_expression = CompositeIndicatorExpression()
    watchlistind.composite_indicator_expression.operator = "OR"

    ips = ['23.5.111.68', '23.5.111.99', '46.123.99.25']
    for ip in ips:
        new_ind = Indicator()
        new_ind.description = "This Indicator specifies a pattern where one specific IP address is observed"
        # add network network connection to this indicator
        obs = Address()
        obs.address_value = ip
        obs.address_value.condition = "Equals"
        new_ind.add_observable(obs)

        new_ind.add_indicated_ttp(TTP(idref=c2_ttp.id_))

        watchlistind.composite_indicator_expression.append(new_ind)

    pkg2.add_indicator(watchlistind)

    print pkg2.to_xml()

    #  USE CASE: Indicator with compound detection

    pkg3 = STIXPackage()
    pkg3.title = "Example of Indicator Composition for compound detection"

    # create container indicator
    watchlistind2 = Indicator()
    watchlistind2.add_indicator_type("IP Watchlist")
    watchlistind2.description = "This Indicator specifies a composite condition of two preexisting Indicators (each identifying a particular TTP with low confidence) that in aggregate identify the particular TTP with high confidence."
    # Create composite expression
    watchlistind2.composite_indicator_expression = CompositeIndicatorExpression()
    watchlistind2.composite_indicator_expression.operator = "OR"

    watchlistind2.add_indicated_ttp(TTP(idref=c2_ttp.id_))
    watchlistind2.confidence = "High"

    nw_ind.description = "Indicator for a particular C2 IP address used by a malware variant."
    nw_ind.confidence = "Low"
    nw_ind.indicator_types = ["C2"]
    file_ind.description = "Indicator that contains malicious file hashes for a particular malware variant."
    file_ind.confidence = "Low"
    watchlistind2.composite_indicator_expression.append(nw_ind)
    watchlistind2.composite_indicator_expression.append(file_ind)

    pkg3.add_indicator(watchlistind2)

    print pkg3.to_xml()
    def create_network_connection(self,creation_time=None,destination_socket_address=None,destination_tcp_state=None,source_socket_address=None,source_tcp_state=None,tls_used=None,
                                layer7_protocol=None,layer4_protocol=None,layer3_protocol=None,layer7_connections=None):
        network_connection = NetworkConnection()
        network_connection.creation_time= DateTime(creation_time)
        network_connection.destination_socket_address = destination_socket_address
        network_connection.destination_tcp_state = destination_tcp_state
        network_connection.source_socket_address = source_socket_address
        network_connection.source_tcp_state = source_tcp_state
        network_connection.tls_used =tls_used
        network_connection.layer7_protocol= layer7_protocol
        network_connection.layer4_protocol =layer4_protocol
        network_connection.layer3_protocol = layer3_protocol
        network_connection.layer7_connections = layer7_connections

        return network_connection
def main():
    # NOTE: ID values will differ due to being regenerated on each script execution
    pkg1 = STIXPackage()
    pkg1.title = "Example of Indicator Composition for an aggregate indicator composition"

    # USE CASE: Indicator with aggregate pattern

    # Add TTP for malware usage
    malware_ttp = TTP()
    malware_ttp.behavior = Behavior()

    malware = MalwareInstance()
    malware.title = "foobar malware"
    malware.add_type("Remote Access Trojan")
    malware_ttp.behavior.add_malware_instance(malware)

    c2_ttp = TTP()
    c2_ttp.resources = Resource()
    c2_ttp.resources.infrastructure = Infrastructure()
    c2_ttp.resources.infrastructure.add_type(VocabString("Malware C2"))

    pkg1.add_ttp(c2_ttp)
    pkg1.add_ttp(malware_ttp)

    nw_ind = Indicator()
    nw_ind.description = "Indicator for a particular C2 infstructure IP address."
    # add network network connection to this indicator
    obs = NetworkConnection()
    sock = SocketAddress()
    sock.ip_address = "46.123.99.25"
    sock.ip_address.category = "ipv4-addr"
    sock.ip_address.condition = "Equals"
    obs.destination_socket_address = sock
    nw_ind.add_observable(obs)

    nw_ind.add_indicated_ttp(TTP(idref=c2_ttp.id_))

    # create File Hash indicator w/ embedded Observable
    file_ind = Indicator()

    file_ind.description = "Indicator for the hash of the foobar malware."
    file_ind.add_indicator_type("File Hash Watchlist")

    file_obs = File()
    file_obs.add_hash("01234567890abcdef01234567890abcdef")
    file_obs.hashes[0].type_ = "MD5"
    file_obs.hashes[0].type_.condition = "Equals"
    file_ind.add_observable(file_obs)

    # create references
    file_ind.add_indicated_ttp(TTP(idref=malware_ttp.id_))

    # create container indicator
    ind = Indicator()
    ind.add_indicator_type(VocabString("Campaign Characteristics"))
    ind.description = "Indicator for a composite of characteristics for the use of specific malware and C2 infrastructure within a Campaign."

    # Add campaign with related
    camp = Campaign()
    camp.title = "holy grail"
    pkg1.add_campaign(camp)
    camp.related_ttps.append(TTP(idref=c2_ttp.id_))
    camp.related_ttps.append(TTP(idref=malware_ttp.id_))

    # Add threat actor
    ta = ThreatActor()
    ta.identity = Identity()
    ta.identity.name = "boobear"
    ta.observed_ttps.append(TTP(idref=malware_ttp.id_))
    pkg1.add_threat_actor(ta)

    # Create composite expression

    ind.composite_indicator_expression = CompositeIndicatorExpression()
    ind.composite_indicator_expression.operator = "AND"

    ind.composite_indicator_expression.append(file_ind)
    ind.composite_indicator_expression.append(nw_ind)

    pkg1.add_indicator(ind)

    print pkg1.to_xml()

    #  USE CASE: Indicator with partial matching

    pkg2 = STIXPackage()
    pkg2.title = "Example of Indicator Composition for a one of many indicator composition"

    # create container indicator
    watchlistind = Indicator()
    watchlistind.add_indicator_type("IP Watchlist")
    watchlistind.description = "This Indicator specifies a pattern where any one or more of a set of three IP addresses are observed."

    watchlistind.add_indicated_ttp(TTP(idref=c2_ttp.id_))

    # Create composite expression
    watchlistind.composite_indicator_expression = CompositeIndicatorExpression(
    )
    watchlistind.composite_indicator_expression.operator = "OR"

    ips = ['23.5.111.68', '23.5.111.99', '46.123.99.25']
    for ip in ips:
        new_ind = Indicator()
        new_ind.description = "This Indicator specifies a pattern where one specific IP address is observed"
        # add network network connection to this indicator
        obs = Address()
        obs.address_value = ip
        obs.address_value.condition = "Equals"
        new_ind.add_observable(obs)

        new_ind.add_indicated_ttp(TTP(idref=c2_ttp.id_))

        watchlistind.composite_indicator_expression.append(new_ind)

    pkg2.add_indicator(watchlistind)

    print pkg2.to_xml()

    #  USE CASE: Indicator with compound detection

    pkg3 = STIXPackage()
    pkg3.title = "Example of Indicator Composition for compound detection"

    # create container indicator
    watchlistind2 = Indicator()
    watchlistind2.add_indicator_type("IP Watchlist")
    watchlistind2.description = "This Indicator specifies a composite condition of two preexisting Indicators (each identifying a particular TTP with low confidence) that in aggregate identify the particular TTP with high confidence."
    # Create composite expression
    watchlistind2.composite_indicator_expression = CompositeIndicatorExpression(
    )
    watchlistind2.composite_indicator_expression.operator = "OR"

    watchlistind2.add_indicated_ttp(TTP(idref=c2_ttp.id_))
    watchlistind2.confidence = "High"

    nw_ind.description = "Indicator for a particular C2 IP address used by a malware variant."
    nw_ind.confidence = "Low"
    nw_ind.indicator_types = ["C2"]
    file_ind.description = "Indicator that contains malicious file hashes for a particular malware variant."
    file_ind.confidence = "Low"
    watchlistind2.composite_indicator_expression.append(nw_ind)
    watchlistind2.composite_indicator_expression.append(file_ind)

    pkg3.add_indicator(watchlistind2)

    print pkg3.to_xml()
Beispiel #23
0
def HTTPFullObj(http):
    httprequestline = HTTPRequestLine()
    httprequestline.http_method = http[0]
    httprequestline.value = http[1]
    httprequestline.version = http[2]
    hostfield = HostField()
    h = URI()
    h.value = str(http[14])
    hostfield.domain_name = h
    port = Port()
    port.port_value = http[3]
    hostfield.port = port
    httprequestheaderfields = HTTPRequestHeaderFields()
    if http[4] != '':
        httprequestheaderfields.accept = http[4]
    if http[5] != '':
        httprequestheaderfields.accept_language = http[5]
    if http[6] != '':
        httprequestheaderfields.accept_encoding = http[6]
    if http[7] != '':
        httprequestheaderfields.authorization = http[7]
    if http[8] != '':
        httprequestheaderfields.cache_control = http[8]
    if http[9] != '':
        httprequestheaderfields.connection = http[9]
    if http[10] != '':
        httprequestheaderfields.cookie = http[10]
    if http[11] != '':
        httprequestheaderfields.content_length = http[11]  # integer
    if http[12] != '':
        httprequestheaderfields.content_type = http[12]
    if http[13] != '':
        httprequestheaderfields.date = http[13]  # datetime
    if http[14] != '':
        httprequestheaderfields.host = hostfield
    if http[15] != '':
        httprequestheaderfields.proxy_authorization = http[15]
    httprequestheader = HTTPRequestHeader()
    httprequestheader.parsed_header = httprequestheaderfields
    httpclientrequest = HTTPClientRequest()
    httpclientrequest.http_request_line = httprequestline
    httpclientrequest.http_request_header = httprequestheader

    http_request_response = HTTPRequestResponse()
    http_request_response.http_client_request = httpclientrequest

    httpsession = HTTPSession()
    httpsession.http_request_response = http_request_response
    layer7connections = Layer7Connections()
    layer7connections.http_session = httpsession
    networkconnection = NetworkConnection()
    networkconnection.layer3_protocol = "IPv4"
    networkconnection.layer4_protocol = "TCP"
    networkconnection.layer7_protocol = "HTTP"
    networkconnection.layer7_connections = layer7connections
    indicator = Indicator()
    indicator.title = "HTTP request"
    indicator.description = (
        "An indicator containing information about a HTTP request")
    indicator.set_produced_time(utils.dates.now())
    indicator.add_object(networkconnection)
    return indicator
Beispiel #24
0
    def transform(self, event):
        stix_package = STIXPackage()
        self._add_header(stix_package, "Unauthorized traffic to honeypot",
                         "Describes one or more honeypot incidents")

        incident = Incident(
            id_="%s:%s-%s" %
            (CONPOT_NAMESPACE, 'incident', event['session_id']))
        initial_time = StixTime()
        initial_time.initial_compromise = event['timestamp'].isoformat()
        incident.time = initial_time
        incident.title = "Conpot Event"
        incident.short_description = "Traffic to Conpot ICS honeypot"
        incident.add_category(
            VocabString(value='Scans/Probes/Attempted Access'))

        tool_list = ToolInformationList()
        tool_list.append(
            ToolInformation.from_dict({
                'name':
                "Conpot",
                'vendor':
                "Conpot Team",
                'version':
                conpot.__version__,
                'description':
                textwrap.dedent(
                    'Conpot is a low interactive server side Industrial Control Systems '
                    'honeypot designed to be easy to deploy, modify and extend.'
                )
            }))
        incident.reporter = InformationSource(tools=tool_list)

        incident.add_discovery_method("Monitoring Service")
        incident.confidence = "High"

        # Victim Targeting by Sector
        ciq_identity = CIQIdentity3_0Instance()
        #identity_spec = STIXCIQIdentity3_0()
        #identity_spec.organisation_info = OrganisationInfo(industry_type="Electricity, Industrial Control Systems")
        #ciq_identity.specification = identity_spec
        ttp = TTP(
            title=
            "Victim Targeting: Electricity Sector and Industrial Control System Sector"
        )
        ttp.victim_targeting = VictimTargeting()
        ttp.victim_targeting.identity = ciq_identity

        incident.leveraged_ttps.append(ttp)

        indicator = Indicator(title="Conpot Event")
        indicator.description = "Conpot network event"
        indicator.confidence = "High"
        source_port = Port.from_dict({
            'port_value': event['remote'][1],
            'layer4_protocol': 'tcp'
        })
        dest_port = Port.from_dict({
            'port_value':
            self.protocol_to_port_mapping[event['data_type']],
            'layer4_protocol':
            'tcp'
        })
        source_ip = Address.from_dict({
            'address_value': event['remote'][0],
            'category': Address.CAT_IPV4
        })
        dest_ip = Address.from_dict({
            'address_value': event['public_ip'],
            'category': Address.CAT_IPV4
        })
        source_address = SocketAddress.from_dict({
            'ip_address':
            source_ip.to_dict(),
            'port':
            source_port.to_dict()
        })
        dest_address = SocketAddress.from_dict({
            'ip_address': dest_ip.to_dict(),
            'port': dest_port.to_dict()
        })
        network_connection = NetworkConnection.from_dict({
            'source_socket_address':
            source_address.to_dict(),
            'destination_socket_address':
            dest_address.to_dict(),
            'layer3_protocol':
            "IPv4",
            'layer4_protocol':
            "TCP",
            'layer7_protocol':
            event['data_type'],
            'source_tcp_state':
            "ESTABLISHED",
            'destination_tcp_state':
            "ESTABLISHED",
        })
        indicator.add_observable(Observable(network_connection))

        artifact = Artifact()
        artifact.data = json.dumps(event['data'])
        artifact.packaging.append(ZlibCompression())
        artifact.packaging.append(Base64Encoding())
        indicator.add_observable(Observable(artifact))

        incident.related_indicators.append(indicator)
        stix_package.add_incident(incident)

        stix_package_xml = stix_package.to_xml()
        return stix_package_xml
Beispiel #25
0
def FTPObj(ftp):
    networkconnection = NetworkConnection()
    networkconnection.layer3_protocol = "IPv4"
    networkconnection.layer4_protocol = "TCP"
    networkconnection.layer7_protocol = "FTP"
    indicator = Indicator()
    if ftp[4] == '220':
        if ftp[0] != VMIP:  # incoming connection
            ssocketaddress = SocketAddress()
            ssocketaddress.ip_address = ftp[0]
            sport = Port()
            sport.port_value = ftp[1]
            sport.layer4_protocol = "TCP"
            ssocketaddress.port = sport
            networkconnection.source_socket_address = ssocketaddress
        elif ftp[2] != VMIP:  # outgoing connection
            dsocketaddress = SocketAddress()
            dsocketaddress.ip_address = ftp[2]
            dport = Port()
            dport.port_value = ftp[3]
            dport.layer4_protocol = "TCP"
            dsocketaddress.port = dport
            networkconnection.destination_socket_address = dsocketaddress
        indicator.title = "FTP"
        indicator.description = ("Service ready for new user: "******"TCP"
            ssocketaddress.port = sport
            networkconnection.source_socket_address = ssocketaddress
        elif ftp[2] != VMIP:  # outgoing connection
            dsocketaddress = SocketAddress()
            dsocketaddress.ip_address = ftp[2]
            dport = Port()
            dport.port_value = ftp[3]
            dport.layer4_protocol = "TCP"
            dsocketaddress.port = dport
            networkconnection.destination_socket_address = dsocketaddress
        indicator.title = "FTP"
        indicator.description = ("User logged in")
        indicator.set_produced_time(utils.dates.now())
        indicator.add_object(networkconnection)
        return indicator
    elif ftp[4] == '250':
        if ftp[0] != VMIP:  # incoming connection
            ssocketaddress = SocketAddress()
            ssocketaddress.ip_address = ftp[0]
            sport = Port()
            sport.port_value = ftp[1]
            sport.layer4_protocol = "TCP"
            ssocketaddress.port = sport
            networkconnection.source_socket_address = ssocketaddress
        elif ftp[2] != VMIP:  # outgoing connection
            dsocketaddress = SocketAddress()
            dsocketaddress.ip_address = ftp[2]
            dport = Port()
            dport.port_value = ftp[3]
            dport.layer4_protocol = "TCP"
            dsocketaddress.port = dport
            networkconnection.destination_socket_address = dsocketaddress
        indicator.title = "FTP"
        indicator.description = ("Requested file action okay, completed.")
        indicator.set_produced_time(utils.dates.now())
        indicator.add_object(networkconnection)
        return indicator
    elif ftp[5] == "USER":
        if ftp[0] != VMIP:  # incoming connection
            ssocketaddress = SocketAddress()
            ssocketaddress.ip_address = ftp[0]
            sport = Port()
            sport.port_value = ftp[1]
            sport.layer4_protocol = "TCP"
            ssocketaddress.port = sport
            networkconnection.source_socket_address = ssocketaddress
        elif ftp[2] != VMIP:  # outgoing connection
            dsocketaddress = SocketAddress()
            dsocketaddress.ip_address = ftp[2]
            dport = Port()
            dport.port_value = ftp[3]
            dport.layer4_protocol = "TCP"
            dsocketaddress.port = dport
            networkconnection.destination_socket_address = dsocketaddress
        indicator.title = "FTP"
        indicator.description = ("Requested username: "******"PASS":
        if ftp[0] != VMIP:  # incoming connection
            ssocketaddress = SocketAddress()
            ssocketaddress.ip_address = ftp[0]
            sport = Port()
            sport.port_value = ftp[1]
            sport.layer4_protocol = "TCP"
            ssocketaddress.port = sport
            networkconnection.source_socket_address = ssocketaddress
        elif ftp[2] != VMIP:  # outgoing connection
            dsocketaddress = SocketAddress()
            dsocketaddress.ip_address = ftp[2]
            dport = Port()
            dport.port_value = ftp[3]
            dport.layer4_protocol = "TCP"
            dsocketaddress.port = dport
            networkconnection.destination_socket_address = dsocketaddress
        indicator.title = "FTP"
        indicator.description = ("Requested Password: "******"STOR":
        if ftp[0] != VMIP:  # incoming connection
            ssocketaddress = SocketAddress()
            ssocketaddress.ip_address = ftp[0]
            sport = Port()
            sport.port_value = ftp[1]
            sport.layer4_protocol = "TCP"
            ssocketaddress.port = sport
            networkconnection.source_socket_address = ssocketaddress
        elif ftp[2] != VMIP:  # outgoing connection
            dsocketaddress = SocketAddress()
            dsocketaddress.ip_address = ftp[2]
            dport = Port()
            dport.port_value = ftp[3]
            dport.layer4_protocol = "TCP"
            dsocketaddress.port = dport
            networkconnection.destination_socket_address = dsocketaddress
        indicator.title = "FTP"
        indicator.description = ("Upload file to server: " + ftp[6])
        indicator.set_produced_time(utils.dates.now())
        indicator.add_object(networkconnection)
        return indicator
    elif ftp[5] == "RETR":
        if ftp[0] != VMIP:  # incoming connection
            ssocketaddress = SocketAddress()
            ssocketaddress.ip_address = ftp[0]
            sport = Port()
            sport.port_value = ftp[1]
            sport.layer4_protocol = "TCP"
            ssocketaddress.port = sport
            networkconnection.source_socket_address = ssocketaddress
        elif ftp[2] != VMIP:  # outgoing connection
            dsocketaddress = SocketAddress()
            dsocketaddress.ip_address = ftp[2]
            dport = Port()
            dport.port_value = ftp[3]
            dport.layer4_protocol = "TCP"
            dsocketaddress.port = dport
            networkconnection.destination_socket_address = dsocketaddress
        indicator.title = "FTP"
        indicator.description = ("Retrieve a copy of the file: " + ftp[6])
        indicator.set_produced_time(utils.dates.now())
        indicator.add_object(networkconnection)
        return indicator