Simple test for pcap magic bytes in supplied file.

    :param pcap: File path to Pcap file to check
    :returns: True if content is pcap (magic bytes present), otherwise False.
496641
def is_pcap(pcap):
    
    with open(pcap, 'rb') as tmp:
        header = tmp.read(4)
        # check for both big/little endian
        if header == b"\xa1\xb2\xc3\xd4" or \
           header == b"\xd4\xc3\xb2\xa1":
            return True
        return False
871020
private static boolean hasMagic(byte[] edata) {
        try {
            int i = 0;
            while (i < edata.length) {
                if (get16(edata, i) == JAR_MAGIC) {
                    return true;
                }
                i += get16(edata, i + 2) + 4;
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            // Invalid extra field data
        }
        return false;
    }
1171417
def isPe64(self):
        
        if self.ntHeaders.optionalHeader.magic.value == consts.PE64:
            return True
        return False
344138
private static boolean isORC(Path file, FileSystem fs)
      throws IOException {
    try {
      FSDataInputStream inputStream = fs.open(file);
      long size = fs.getFileStatus(file).getLen();
      byte[] buffer = new byte[Math.toIntExact(Math.min(size, EXPECTED_FOOTER_SIZE))];
      if (size < buffer.length) {
        return false;
      }

      inputStream.readFully(size - buffer.length, buffer);

      // get length of PostScript - last byte of the file
      int postScriptSize = buffer[buffer.length - 1] & 0xff;
      int magicLen = MAGIC_BUFFER.remaining();

      if (postScriptSize < magicLen + 1 || postScriptSize >= buffer.length) {
        return false;
      }

      if (!MAGIC_BUFFER.equals(ByteBuffer.wrap(buffer, buffer.length - 1 - magicLen, magicLen))) {
        // Old versions of ORC (0.11) wrote the magic to the head of the file
        byte[] headerMagic = new byte[magicLen];
        inputStream.readFully(0, headerMagic);

        // if it isn't there, this isn't an ORC file
        if (!MAGIC_BUFFER.equals(ByteBuffer.wrap(headerMagic))) {
          return false;
        }
      }

      return true;
    } catch (Exception e) {
      throw new RuntimeException("Error occured when checking the type of file:" + file);
    }
  }
127250
def check_data_is_empty(data):
    # type: (bytes) -> bool
    
    contentmd5 = compute_md5_for_data_asbase64(data)
    datalen = len(data)
    if datalen == _MAX_PAGE_SIZE_BYTES:
        if contentmd5 == _EMPTY_MAX_PAGE_SIZE_MD5:
            return True
    else:
        data_chk = b'\0' * datalen
        if compute_md5_for_data_asbase64(data_chk) == contentmd5:
            return True
    return False
77357
def guess_filetype(filepath):
    """"""
    # If we have python-magic, use it to determine file type
    typ = None

    # Some specific checks for known file suffixes
    _fn = filepath.lower()
    _name, _ext = os.path.splitext(_fn)
    if _ext in known_types:
        typ = known_types[_ext]

    if typ is None and have_magic:
        try:
            # it seems there are conflicting versions of a 'magic'
            # module for python floating around...*sigh*
            if hasattr(magic, 'from_file'):
                typ = magic.from_file(filepath, mime=True)

            elif magic_tester is not None:
                descrip = magic_tester.file(filepath)
                if descrip.startswith("FITS image data"):
                    return ('image', 'fits')

        except Exception as e:
            pass

    if typ is None:
        # if no magic, or magic fails, fall back to mimetypes
        try:
            typ, enc = mimetypes.guess_type(filepath)

        except Exception as e:
            # fail
            pass

    if typ:
        typ, subtyp = typ.split('/')
        return (typ, subtyp)

    raise ValueError("Can't determine file type of '%s'" % (filepath))
387295
def guess_type_tag(self, input_bytes, filename):
        
        mime_to_type = {'application/jar': 'jar',
                        'application/java-archive': 'jar',
                        'application/octet-stream': 'data',
                        'application/pdf': 'pdf',
                        'application/vnd.ms-cab-compressed': 'cab',
                        'application/vnd.ms-fontobject': 'ms_font',
                        'application/vnd.tcpdump.pcap': 'pcap',
                        'application/x-dosexec': 'exe',
                        'application/x-empty': 'empty',
                        'application/x-shockwave-flash': 'swf',
                        'application/xml': 'xml',
                        'application/zip': 'zip',
                        'image/gif': 'gif',
                        'text/html': 'html',
                        'image/jpeg': 'jpg',
                        'image/png': 'png',
                        'image/x-icon': 'icon',
                        'text/plain': 'txt'
                        }

        # See what filemagic can determine
        with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as mag:
            mime_type = mag.id_buffer(input_bytes[:1024])
            if mime_type in mime_to_type:
                type_tag = mime_to_type[mime_type]

                # If we get 'data' back look at the filename
                if type_tag == 'data':
                    print 'Info: File -- Trying to Determine Type from filename...'
                    ext = os.path.splitext(filename)[1][1:]
                    if ext in ['mem','vmem']:
                        type_tag = 'mem'
                    else:
                        print 'Alert: Failed to Determine Type for %s' % filename
                        exit(1) # Temp
                return type_tag
            else:
                print 'Alert: Sample Type could not be Determined'
                return 'unknown'
230519
def is_file(cls, file):
        ''''''
        peeked_data = wpull.string.printable_bytes(
            wpull.util.peek_file(file)).lower()

        if b'<html' in peeked_data:
            return VeryFalse

        if re.search(br'@import |color:|background[a-z-]*:|font[a-z-]*:',
                     peeked_data):
            return True
637808
def verify(sigfilename, filefilename=None):
    """"""

    if gnupg is None:
        return False

    gpg = gnupg.GPG()

    with open(sigfilename, "rb") as sigfile:
        verified = gpg.verify_file(sigfile, filefilename)

        pyspread_keyid = fingerprint2keyid(config["gpg_key_fingerprint"])

        if verified.valid and verified.key_id == pyspread_keyid:
            return True

    return False
934233
def contains_rva(self, rva):
        """"""
        
        # Check if the SizeOfRawData is realistic. If it's bigger than the size of
        # the whole PE file minus the start address of the section it could be
        # either truncated or the SizeOfRawData contain a misleading value.
        # In either of those cases we take the VirtualSize
        #
        if len(self.pe.__data__) - adjust_FileAlignment( self.PointerToRawData,
            self.pe.OPTIONAL_HEADER.FileAlignment ) < self.SizeOfRawData:
            # PECOFF documentation v8 says:
            # VirtualSize: The total size of the section when loaded into memory.
            # If this value is greater than SizeOfRawData, the section is zero-padded.
            # This field is valid only for executable images and should be set to zero
            # for object files.
            #
            size = self.Misc_VirtualSize
        else:
            size = max(self.SizeOfRawData, self.Misc_VirtualSize)
        
        VirtualAddress_adj = adjust_SectionAlignment( self.VirtualAddress, 
            self.pe.OPTIONAL_HEADER.SectionAlignment, self.pe.OPTIONAL_HEADER.FileAlignment )
        
        return VirtualAddress_adj <= rva < VirtualAddress_adj + size
260662
def p_common_scalar_magic_file(p):
    ''
    value = getattr(p.lexer, 'filename', None)
    p[0] = ast.MagicConstant(p[1].upper(), value, lineno=p.lineno(1))
644215
def file_verified?(path, expected_digest, digest_type=:md5)
      return false unless file_exists?(path)
      raise "Unknown disgest type: #{digest_type}" unless can?("digest_#{digest_type}")
      digest = self.send("digest_#{digest_type}", path).first
      info "#{digest_type} (#{path}) = #{digest}"
      digest.to_s == expected_digest.to_s
    end
1368462
def _pcap_check(cls):
        """"""
        if not conf.use_winpcapy:
            # Winpcap/Npcap isn't installed
            return

        _detect = pcap_service_status()

        def _ask_user():
            if not conf.interactive:
                return False
            msg = "Do you want to start it ? (yes/no) [y]: "
            try:
                # Better IPython compatibility
                import IPython
                return IPython.utils.io.ask_yes_no(msg, default='y')
            except (NameError, ImportError):
                while True:
                    _confir = input(msg)
                    _confir = _confir.lower().strip()
                    if _confir in ["yes", "y", ""]:
                        return True
                    elif _confir in ["no", "n"]:
                        return False
                return False
        _error_msg = ("No match between your pcap and windows "
                      "network interfaces found. ")
        if _detect:
            # No action needed
            return
        else:
            warning(
                "Scapy has detected that your pcap service is not running !"
            )
            if not conf.interactive or _ask_user():
                succeed = pcap_service_start(askadmin=conf.interactive)
                if succeed:
                    log_loading.info("Pcap service started !")
                    return
            _error_msg = "Could not start the pcap service ! "
        warning(_error_msg +
                "You probably won't be able to send packets. "
                "Deactivating unneeded interfaces and restarting "
                "Scapy might help. Check your winpcap/npcap installation "
                "and access rights.")
1166081
def matches_packet(self, pkt):
        '''
        
        '''
        match = []
        wildbits = _make_bitmap(self._wildcards)
        for mf,pkttuple in OpenflowMatch._match_field_to_packet.items():
            mf = "_{}".format(mf)

            # if the attribute is a network address, respect the bits
            if mf == '_nw_src' or mf == '_nw_dst':
                # FIXME: clean me up.  lots of dup w/above and below :(
                wattr = "{}_wildcard".format(mf)
                bits = 32 - getattr(self, wattr)
                if bits < 32:
                    netaddr = ip_network("{}/{}".format(getattr(self, mf), bits), strict=False)
                    for pktcls,field in pkttuple: 
                        if pkt.has_header(pktcls):
                            match.append(getattr(pkt[pktcls], field) in netaddr)
                    continue

            # if attribute is simple wildcard, just ignore the attr
            elif _wildcard_attr_map[mf].value & wildbits:
                continue

            # compare concrete values in packet with match object value
            for pktcls,field in pkttuple:
                if pkt.has_header(pktcls):
                    match.append(getattr(pkt[pktcls], field) == getattr(self, mf))
        return all(match)
824252
def is_applicable_python_file(rel_path: str) -> bool:
    
    return (rel_path.endswith('.py') and
            not any(re.search(pat, rel_path) for pat in IGNORED_FILE_PATTERNS))
737007
def read_file_bytes(input_file_path):
    
    contents = None
    try:
        with io.open(input_file_path, "rb") as input_file:
            contents = input_file.read()
    except:
        pass
    return contents
12074
def get_magic_guesses(fullpath):
    
    if CFG_HAS_MAGIC == 1:
        magic_cookies = _get_magic_cookies()
        magic_result = []
        for key in magic_cookies.keys():
            magic_result.append(magic_cookies[key].file(fullpath))
        return tuple(magic_result)
    elif CFG_HAS_MAGIC == 2:
        magic_result = []
        for key in ({'mime': False, 'mime_encoding': False},
                    {'mime': True, 'mime_encoding': False},
                    {'mime': False, 'mime_encoding': True}):
            magic_result.append(_magic_wrapper(fullpath, **key))
        return tuple(magic_result)