Example #1
1
def jpgDims(jpegFile):
    jpeg = open(jpegFile, "rb")
    jpeg.read(2)
    b = jpeg.read(1)
    try:
        while b and ord(b) != 0xDA:
            while ord(b) != 0xFF:
                b = jpeg.read
            while ord(b) == 0xFF:
                b = jpeg.read(1)
            if ord(b) >= 0xC0 and ord(b) <= 0xC3:
                jpeg.read(3)
                h, w = struct.unpack(">HH", jpeg.read(4))
                break
            else:
                jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0]) - 2)
            b = jpeg.read(1)
        width = int(w)
        height = int(h)
    except struct.error:
        pass
    except ValueError:
        pass

    return width, height
        def __ior__(self, other):
            assert self.num_bits == other.num_bits

            for byteno in my_range(self.num_chars):
                self.mmap[byteno] = chr(ord(self.mmap[byteno]) | ord(other.mmap[byteno]))

            return self
    def _open(self):

        # Screen
        s = self.fp.read(13)
        if s[:6] not in ["GIF87a", "GIF89a"]:
            raise SyntaxError, "not a GIF file"

        self.info["version"] = s[:6]

        self.size = i16(s[6:]), i16(s[8:])

        self.tile = []

        flags = ord(s[10])

        bits = (flags & 7) + 1

        if flags & 128:
            # get global palette
            self.info["background"] = ord(s[11])
            # check if palette contains colour indices
            p = self.fp.read(3 << bits)
            for i in range(0, len(p), 3):
                if not (chr(i / 3) == p[i] == p[i + 1] == p[i + 2]):
                    p = ImagePalette.raw("RGB", p)
                    self.global_palette = self.palette = p
                    break

        self.__fp = self.fp  # FIXME: hack
        self.__rewind = self.fp.tell()
        self.seek(0)  # get ready to read first frame
def key_for_col_sort(str):
    # A01, B01, C01,...,H01, A02, ..., H12
    sep = list(str)
    letter = sep[0]
    num = (int)("%s%s" % (sep[1], sep[2]))
    res = 100 * num + (ord(letter) - ord("A") + 1)
    return res
Example #5
1
    def _parse_message_queue(self):
        """ Parses for messages in the buffer *buf*.  It is assumed that
        the buffer contains the start character for a message, but that it
        may contain only part of the rest of the message.

        Returns an array of messages, and the buffer remainder that
        didn't contain any full messages."""
        msgs = []
        end_idx = 0
        buf = self._buffer
        while buf:
            frame_type = ord(buf[0])
            if frame_type == 0:
                # Normal message.
                end_idx = buf.find("\xFF")
                if end_idx == -1:  # pragma NO COVER
                    break
                msgs.append(buf[1:end_idx].decode("utf-8", "replace"))
                buf = buf[end_idx + 1 :]
            elif frame_type == 255:
                # Closing handshake.
                assert ord(buf[1]) == 0, "Unexpected closing handshake: %r" % buf
                self.closed = True
                break
            else:
                return None
                # raise ValueError("Don't understand how to parse this type of message: %r" % buf)
        self._buffer = buf
        return msgs
    def field(self):
        #
        # get a IPTC field header
        s = self.fp.read(5)
        if not len(s):
            return None, 0

        tag = ord(s[1]), ord(s[2])

        # syntax
        if ord(s[0]) != 0x1C or tag[0] < 1 or tag[0] > 9:
            raise SyntaxError, "invalid IPTC/NAA file"

        # field size
        size = ord(s[3])
        if size > 132:
            raise IOError, "illegal field length in IPTC/NAA file"
        elif size == 128:
            size = 0
        elif size > 128:
            size = i(self.fp.read(size - 128))
        else:
            size = i16(s[3:])

        return tag, size
Example #7
0
 def custom64(self, string, count=0):
     if count == 0:
         count = len(string)
     output = ""
     i = 0
     itoa64 = self.itoa64
     while 1:
         value = ord(string[i])
         i += 1
         output += itoa64[value & 0x3F]
         if i < count:
             value |= ord(string[i]) << 8
         output += itoa64[(value >> 6) & 0x3F]
         if i >= count:
             break
         i += 1
         if i < count:
             value |= ord(string[i]) << 16
         output += itoa64[(value >> 12) & 0x3F]
         if i >= count:
             break
         i += 1
         output += itoa64[(value >> 18) & 0x3F]
         if i >= count:
             break
     return output
Example #8
0
def hamming_distance(a, b):
    """hamming_distance(a, b): return the hamming distance between two sequences of equal length"""
    # Are the two sequences a and b of equal length?
    if len(a) != len(b):
        raise ValueError("Arguments a and b must be the same length")
    else:
        return sum([0 if (ord(i) ^ ord(j) == 0) else 1 for (i, j) in zip(list(a), list(b))])
 def auto_mavlink_version(self, buf):
     """auto-switch mavlink protocol version"""
     global mavlink
     if len(buf) == 0:
         return
     if not ord(buf[0]) in [85, 254]:
         return
     self.first_byte = False
     if self.WIRE_PROTOCOL_VERSION == "0.9" and ord(buf[0]) == 254:
         self.WIRE_PROTOCOL_VERSION = "1.0"
         set_dialect(current_dialect)
     elif self.WIRE_PROTOCOL_VERSION == "1.0" and ord(buf[0]) == 85:
         self.WIRE_PROTOCOL_VERSION = "0.9"
         set_dialect(current_dialect)
         os.environ["MAVLINK09"] = "1"
     else:
         return
     # switch protocol
     (callback, callback_args, callback_kwargs) = (
         self.mav.callback,
         self.mav.callback_args,
         self.mav.callback_kwargs,
     )
     self.mav = mavlink.MAVLink(self, srcSystem=self.source_system)
     self.mav.robust_parsing = self.robust_parsing
     self.WIRE_PROTOCOL_VERSION = mavlink.WIRE_PROTOCOL_VERSION
     (self.mav.callback, self.mav.callback_args, self.mav.callback_kwargs) = (
         callback,
         callback_args,
         callback_kwargs,
     )
Example #10
0
def isAnagram2(self, s, t):
    dic1, dic2 = [0]*26, [0]*26
    for item in s:
        dic1[ord(item)-ord('a')] += 1
    for item in t:
        dic2[ord(item)-ord('a')] += 1
    return dic1 == dic2
def GetMediaSvrPort(target):
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.connect((target,111))
    sock.send(rpc_portmap_req)
    rec = sock.recv(256)
    sock.close()

    port1 = rec[-4]
    port2 = rec[-3]
    port3 = rec[-2]
    port4 = rec[-1]   
   
    port1 = hex(ord(port1))
    port2 = hex(ord(port2))
    port3 = hex(ord(port3))
    port4 = hex(ord(port4))
    port = '%02x%02x%02x%02x' % (int(port1,16),int(port2,16),int(port3,16),int(port4,16))
   
    port = int(port,16)
    if port < 1100:
        print '[+] Fresh Meat: Mediasvr.exe has not been restarted, Sending Packet 1 to: Target: %s Port: %s' %(target,port)
        ExploitMediaSvr(target,port,1)
    else:
        print '[+] Mediasvr.exe has been restarted, Sending Packet 2 to: Target: %s Port: %s' % (target,port)
        ExploitMediaSvr(target,port,2)
Example #12
0
def findlabels(code):
    """Detect all offsets in a byte code which are jump targets.

    Return the list of offsets.

    """
    labels = []
    n = len(code)
    i = 0
    while i < n:
        c = code[i]
        op = ord(c)
        i = i + 1
        if op >= HAVE_ARGUMENT:
            oparg = ord(code[i]) + ord(code[i + 1]) * 256
            i = i + 2
            label = -1
            if op in hasjrel:
                label = i + oparg
            elif op in hasjabs:
                label = oparg
            if label >= 0:
                if label not in labels:
                    labels.append(label)
    return labels
Example #13
0
def hexdump(s):
    for b in xrange(0, len(s), 16):
        lin = [c for c in s[b : b + 16]]
        hxdat = " ".join("%02X" % ord(c) for c in lin)
        pdat = "".join((c if 32 <= ord(c) <= 126 else ".") for c in lin)
        print "  %04x: %-48s %s" % (b, hxdat, pdat)
    print
    def main(self):
        while not self.shutdown():

            while self.dataReady("inbox"):
                data = self.recv("inbox")

                # extract basic info from this PSI packet - enough to work
                # out what table it is; what section, and the version
                e = [ord(data[i]) for i in range(0, 3)]

                table_id = e[0]
                if table_id != 0x70:
                    continue

                syntax = e[1] & 0x80
                if syntax:
                    continue

                # now were reasonably certain we've got a correct packet
                # we'll convert the rest of the packet
                section_length = ((e[1] << 8) + e[2]) & 0x0FFF

                e = [ord(data[i]) for i in range(0, 8)]

                utc = list(parseMJD((e[3] << 8) + e[4]))
                utc.extend([unBCD(e[5]), unBCD(e[6]), unBCD(e[7])])

                self.send(utc, "outbox")

            self.pause()
            yield 1
Example #15
0
def operation_on_string(string1, string2, op):
    if len(string1) != len(string2):
        raise ValueError("string1 and string2 must be of equal length")
    result = []
    for i in range(len(string1)):
        result.append(chr(op(ord(string1[i]), ord(string2[i]))))
    return "".join(result)
Example #16
0
    def __init__(self, content, index=0, name=None, score=0):
        """Accepts either a filepath or a list of words, possibly with ranks."""
        if isinstance(content, str):
            words = list(read_wordlist(content, score))
            self.path = content
        else:
            self.path = None
            words = [(w if isinstance(w, tuple) else (w, score)) for w in content]
            # for now, concat compound words
            words = [(w.replace(" ", ""), score) for w, score in words]
            # reject all non-alphabet chars
            ord_A = ord("A")
            ord_Z = ord("Z")
            ord_a = ord("a")
            ord_z = ord("z")

            def is_ok(w):
                for c in w:
                    ord_c = ord(c)
                    if not (ord_A <= ord_c <= ord_Z or ord_a <= ord_c <= ord_z):
                        return False
                return True

            words = [item for item in words if is_ok(item[0])]
        self.words = cPalabra.preprocess(words, index)
        # keys of self.words = lengths
        # values = list of words of that length with (word, score)
        self.index = index
        self.name = name
Example #17
0
def recover_key(crypt, keystr_guess, keylen, index, search):

    partial = False

    # this means we haven't found the whole key, some bytes are missing
    if len(keystr_guess) < keylen:
        partial = True

    decrypt = xor(crypt, keystr_guess + "\x00")

    if len(keystr_guess) < keylen:
        logging.info("[?] Some bytes of the key are missing, taking a wild guess (assuming findings ~ search query)")
        logging.info(
            "[?] If results don't make sense, try searching for something with less entropy (e.g. URLs), or use a longer search string"
        )

    while len(keystr_guess) < keylen:
        # we take a wild guess, and suppose the keystream guess was found
        # because of an occurrence of our search term in the plaintext
        findings = decrypt.find(search[: (index % len(keystr_guess))])
        keystr_guess += chr(ord(crypt[index + len(keystr_guess)]) ^ ord(search[len(keystr_guess)]))

        # get the correct start of the keystream
    key = keystr_guess[-(index % keylen) :]
    key += keystr_guess[: -(index % keylen)]

    # repeat key as long as it's needed
    while len(key) < len(crypt):
        key += key

    decrypt = xor(crypt, key)

    return decrypt, key[:keylen]
Example #18
0
    def toQuotedString(self):
        if len(self._name) == 0:
            return "''"
        elif self == Atom.NIL:
            return "[]"

        result = StringIO.StringIO()
        useQuotes = False
        for c in self._name:
            cInt = ord(c)
            if c == "'":
                result.write("''")
                useQuotes = True
            elif (
                c == "_"
                or cInt >= ord("a")
                and cInt <= ord("z")
                or cInt >= ord("A")
                and cInt <= ord("Z")
                or cInt >= ord("0")
                and cInt <= ord("9")
            ):
                result.write(c)
            else:
                # Debug: Need to handle non-printable chars.
                result.write(c)
                useQuotes = True

        if not useQuotes and ord(self._name[0]) >= ord("a") and ord(self._name[0]) <= ord("z"):
            return result.getvalue()
        else:
            # Surround in single quotes.
            result.write("'")
            return "'" + result.getvalue()
def test_at_and_at_put_bytes():
    w_str = wrap("abc")
    prim_fails(primitives.AT_PUT, [w_str, 1, "d"])
    assert prim(primitives.AT_PUT, [w_str, 1, ord("d")]).value == ord("d")
    assert prim(primitives.AT, [w_str, 1]).value == ord("d")
    assert prim(primitives.AT, [w_str, 2]).value == ord("b")
    assert prim(primitives.AT, [w_str, 3]).value == ord("c")
Example #20
0
 def progressive(self, file):
     """
     Try to find out with brute force if the mpeg is interlaced or not.
     Search for the Sequence_Extension in the extension header (01B5)
     """
     file.seek(0)
     buffer = ""
     count = 0
     while 1:
         if len(buffer) < 1000:
             count += 1
             if count > 1000:
                 break
             buffer += file.read(1024)
         if len(buffer) < 1000:
             break
         pos = buffer.find("\x00\x00\x01\xb5")
         if pos == -1 or len(buffer) - pos < 5:
             buffer = buffer[-10:]
             continue
         ext = ord(buffer[pos + 4]) >> 4
         if ext == 8:
             pass
         elif ext == 1:
             if (ord(buffer[pos + 5]) >> 3) & 1:
                 self.keys.append("progressive")
                 self.progressive = 1
             else:
                 self.keys.append("interlaced")
                 self.interlaced = 1
             return True
         else:
             print "ext", ext
         buffer = buffer[pos + 4 :]
     return False
def key_for_row_sort(str):
    # A01, A02, A03, ..., A12, B01, ..., H12
    sep = list(str)
    letter = sep[0]
    num = (int)("%s%s" % (sep[1], sep[2]))
    res = num + 100 * (ord(letter) - ord("A") + 1)
    return res
Example #22
0
 def fmtline(line):
     l = len(line)
     if l <= 26:
         l = chr(ord("A") + l - 1)
     else:
         l = chr(l - 26 + ord("a") - 1)
     return "%c%s\n" % (l, base85.b85encode(line, True))
Example #23
0
    def OnKeyDown(self, event):
        """Key down event handler."""

        key = event.GetKeyCode()
        # If the auto-complete window is up let it do its thing.
        if self.window.AutoCompActive():
            event.Skip()
            return
        controlDown = event.ControlDown()
        altDown = event.AltDown()
        shiftDown = event.ShiftDown()
        # Let Ctrl-Alt-* get handled normally.
        if controlDown and altDown:
            event.Skip()
        # Increase font size.
        elif controlDown and key in (ord("]"),):
            dispatcher.send(signal="FontIncrease")
        # Decrease font size.
        elif controlDown and key in (ord("["),):
            dispatcher.send(signal="FontDecrease")
        # Default font size.
        elif controlDown and key in (ord("="),):
            dispatcher.send(signal="FontDefault")
        else:
            event.Skip()
Example #24
0
    def toString(self):
        ret = ""
        ret += "Type: " + str(self.type) + "\n"
        ret += "Status: " + str(self.status) + "\n"
        ret += "Length: " + str(self.length) + "\n"
        ret += "Channel: " + str(self.chan) + "\n"
        ret += "Packet: " + str(self.packet) + "\n"
        ret += "Window: " + str(self.window) + "\n\n"

        ret += "Payload: "
        ret += ":".join("{0:x}".format(ord(c)) for c in self.payload)
        ret += "\n"

        ret += "First byte is " + str(ord(self.payload[0])) + "\n"

        for token in self.tokens:
            ret += "Token: " + str(token.type) + "\n"
            ret += "Token Position: " + str(token.tokenPosition) + "\n"
            ret += "Position: " + str(token.position) + "\n"
            ret += "Length: " + str(token.length) + "\n"
            ret += "Value: "
            foo = str(
                self.payload[token.position - (self.tokenOffset) : (token.position + token.length - (self.tokenOffset))]
            )
            for char in foo:
                ret += str(ord(char)) + " "
            ret += "\n\n"

        ret += "Payload size: " + str(len(self.payload))

        return ret
Example #25
0
def parseresp(s, quiet):
    while True:
        typ, ver, pay = recvmsg(s)

        if typ == None:
            print "Server closed connection without sending Server Hello Done."
            sys.stdout.flush()
            return 0

        if typ == 22:
            index = 0
            while index < len(pay):
                if not quiet:
                    print "Message Type is 0x%02X" % ord(pay[index])
                sys.stdout.flush()

                # Look for server hello done message.
                if ord(pay[index]) == 0x0E:
                    if not quiet:
                        print "Server sent server hello done"
                    sys.stdout.flush()
                    return ver

                skip = (ord(pay[index + 1]) * 2 ** 16) + (ord(pay[index + 2]) * 2 ** 8) + (ord(pay[index + 3]))
                index += 4 + skip
Example #26
0
def askopen(filename=""):
    if filename == "":
        filename = askopenfilename(
            title="Select plain-text file", filetypes=[("txt file", ".txt"), ("All files", ".*")]
        )
    if filename != "":
        with open(filename, "rb") as f:  # read as binary
            doc = f.read()
            doc = doc.decode("utf_8", "ignore")  # drop any non-ascii bytes

            # if a carriage return is orphaned, replace it with a new line
            doc = list(doc)
            i = 0
            while i < len(doc) - 1:
                if ord(doc[i]) == 13:  # it's a carriage return
                    if ord(doc[i + 1]) != 10:  # it's not followed by a new line
                        doc[i] = chr(10)  # replace it with a new line
                i += 1
            if ord(doc[len(doc) - 1]) == 13:  # end
                doc[len(doc) - 1] = chr(10)

            # drop carriage returns
            i = 0
            while i < len(doc) - 1:
                if ord(doc[i]) == 13:  # it's a carriage return
                    doc.pop(i)
                else:
                    i += 1

            doc = "".join(doc)

            text.delete("1.0", END)
            text.insert("1.0", doc)
            tag_initial()
            root.title(filename + " - IOCextractor")
def format4(input):
    # F4 - unsigned long_24 input, {0-0xffffff} - Byte1 Byte2 Byte3
    byte1 = ord(input[0])
    byte2 = ord(input[1])
    byte3 = ord(input[2])
    value = (byte1 << 16) | (byte2 << 8) | (byte3)
    return value
Example #28
0
def calcula_entropia_orden1(imagen):
    """
    Calculo de la entropia de la imagen
    """

    lista_frecuencias_tmp = []
    for i in range(256):
        lista_frecuencias_tmp.append(0)

    lista_frecuencias = []
    for i in range(256):
        lista_frecuencias.append(lista_frecuencias_tmp)

    for i in range(len(imagen) // 2):
        lista_frecuencias[ord(imagen[i * 2])][ord(imagen[(i * 2) + 1])] += 1
        print ord(imagen[i * 2]), ord(imagen[(i * 2) + 1]),
    entropia = 0.0
    for i in range(256):
        for j in range(256):
            if lista_frecuencias[i][j]:
                frecuencia = lista_frecuencias[i][j] / len(imagen)
                entropia += -(frecuencia * (log10(frecuencia) * 3.3219))
    print "Longitud del fichero %d" % len(imagen)
    print "Bits por byte: %.2f" % entropia
    print "Porcentaje de compresión: %.2f %%" % (100 - ((entropia * 100) / 8))
    print "Longitud teórica del fichero comprimido %d" % ((len(imagen) * (100 - ((entropia * 100) / 8))) // 100)
    print
Example #29
0
def depth_func(d, k):
    global do_depth_edge, do_rgb_edge, do_blur

    # sys.stdout.write('[%s]' % k)
    # sys.stdout.flush()

    if k == ord("e"):
        print "swap do_depth_edge"
        do_depth_edge = not do_depth_edge
    elif k == ord("f"):
        print "swap do_rgb_edge"
        do_rgb_edge = not do_rgb_edge
    elif k == ord("p"):
        pickle({"rgb": rgb_image, "depth": d}, "/tmp/kinect.pickle")
        print "pickled to /tmp/kinect.pickle"
    elif k == ord("b"):
        do_blur = not do_blur
    elif k != "":
        print "key: %s" % k

    d = clip(d)
    if do_blur:
        d = cv2.GaussianBlur(d, (5, 5), 0)
    # d = np.clip(d, 130, 140, d)
    if do_depth_edge:
        e = cv2.Canny(d, cv2.getTrackbarPos("minVal", "Depth"), cv2.getTrackbarPos("maxVal", "Depth"))
        return e
        return where(e == 0, [d, e])
    return d
def parse_data(msg, ie_key):
    global g_code_length
    g_code_length = ord(msg[1]) & 127
    received_length = 0
    if g_code_length == 126:
        g_code_length = struct.unpack(">H", str(msg[2:4]))[0]
        masks = msg[4:8]
        data = msg[8:]
    elif g_code_length == 127:
        g_code_length = struct.unpack(">Q", str(msg[2:10]))[0]
        masks = msg[10:14]
        data = msg[14:]
    else:
        masks = msg[2:6]
        data = msg[6:]

    i = 0
    raw_str = ""

    for d in data:
        raw_str += chr(ord(d) ^ ord(masks[i % 4]))
        i += 1

    if "\x03\xe9" in raw_str.split():
        sys.exit()
    print "输入[%s]" % raw_str
    try:
        raw_str_source = eval(raw_str)
        raw_str = raw_str_source["cmd"]
        selectserver = raw_str_source["selectserver"]

    except Exception, e:
        print "命令格式错误", e
        sys.exit(1)