Example #1
0
def _yenc_decode(text_lines):
    RE_YENC_BEGIN = re.compile('=ybegin .*name=(.+)')
    RE_YENC_PART = re.compile('=ypart .*begin=(.+) ')

    yenc_decoder = None
    content_file_name = None
    content_file_offset = 0

    for text_line in text_lines:
        if not yenc_decoder:
            match_result = RE_YENC_BEGIN.match(text_line)
            if match_result:
                content_file_name = match_result.group(1)
                yenc_decoder = yenc.Decoder()
            continue
        if text_line.startswith('=ypart '):
            content_file_offset = int(
                RE_YENC_PART.match(text_line).group(1)) - 1
            continue
        if text_line.startswith('=yend '):
            break

        yenc_decoder.feed(text_line)

    return yenc_decoder.getDecoded()
def start(file_name, output):

    data = ''
    hexdata = ''
    decoder = yenc.Decoder()

    cap = rdpcap(file_name)
    packet_len = len(cap)
    num_written = 0
    for i in cap:
        # If the ICMP packet is of type = request
        if i[ICMP].type == 8:
            try:
                if output in ['a', 'h']:
                    # Get the raw payload from the ICMP packet. This i[Raw] returns the hex encoded payload as ascii, , hence we have to use '-o h' option to print literal hex values
                    data = data + str(i[Raw])
                if output == 'y':
                    decoder.feed(str(i[Raw]))
                num_written = num_written + 1
            except Exception as e:
                print("Exception: {}".format(e))
                continue

    if output == 'a':
        # Print raw payload
        print(data, end="")

    if output == 'h':
        # Get raw hex characters instead of printable ascii like how the '-o a' option returns becuase of i[Raw] returning ascii encoded characters
        print(str(binascii.hexlify(data)), end="")

    if output == 'y':
        print(decoder.getDecoded(), end="")

    print("\nInput File : {}".format(file_name), file=sys.stderr)
    print("Output Type : {}".format(output), file=sys.stderr)
    print("Packet Length : {}".format(packet_len), file=sys.stderr)
    print("Number of payload packets written : {}\n".format(num_written),
          file=sys.stderr)

    exit()
Example #3
0
    def _testEncoderDecoder(self, filename):
        file_data, crc = self._readFile(filename)

        file_out = open(filename + '.out', 'wb')
        encoder = yenc.Encoder(file_out)

        with open(filename, 'rb') as file_in:
            data = file_in.read(BLOCK_SIZE)
            while len(data):
                encoder.feed(data)
                data = file_in.read(BLOCK_SIZE)
        encoder.terminate()
        logging.info("orig: %s enc: %s" % (crc, encoder.getCrc32()))
        self.assertEqual(crc, encoder.getCrc32())

        # deleting forces files to be flushed
        del encoder

        file_out = open(filename + '.dec', 'wb')
        decoder = yenc.Decoder(file_out)

        with open(filename + '.out', 'rb') as file_in:
            data = file_in.read(BLOCK_SIZE)
            while len(data) > 0:
                decoder.feed(data)
                data = file_in.read(BLOCK_SIZE)
        decoder.flush()
        logging.info("orig: %s dec: %s" % (crc, decoder.getCrc32()))
        self.assertEqual(crc, decoder.getCrc32())

        # deleting forces files to be flushed
        # if __del__ is not called further tests are going to fail
        del decoder

        data_dec, crc_dec = self._readFile(filename + '.dec')
        self.assertEqual(file_data, data_dec)
        self.assertEqual(crc, crc_dec)
Example #4
0
 def reset(self):
     self._state = YencLineHandler.STATE_WAITING
     self._decoder = yenc.Decoder()
def main():
    head_crc = trail_crc = None
    if len(sys.argv) > 1:
        file_in = open(sys.argv[1], "rb")
    else:
        try:  # Python 3
            file_in = sys.stdin.detach()
        except:  # Python < 3
            file_in = sys.stdin
        sys.stdin = None
    with file_in:
        while True:
            line = file_in.readline()
            if line.startswith(b"=ybegin "):
                try:
                    name, size = NAME_RE.match(line).group(1), int(
                        SIZE_RE.match(line).group(1))
                    m_obj = CRC32_RE.match(line)
                    if m_obj:
                        head_crc = m_obj.group(1)
                except re.error:
                    sys.stderr.write(
                        "err-critical: malformed =ybegin header\n")
                    sys.exit(1)
                break
            elif not line:
                sys.stderr.write(
                    "err-critical: no valid =ybegin header found\n")
                sys.exit(1)
        file_out = open(name, "wb")
        dec = yenc.Decoder(file_out)
        trailer = None
        garbage = False
        while True:
            data = file_in.readline()
            if data.startswith(b"=yend"):
                trailer = data
                break
            elif dec.getSize() >= size:
                garbage = True
            else:
                dec.feed(data)
                dec.flush()
    if trailer:
        try:
            size = int(SIZE_RE.match(trailer).group(1))
            m_obj = CRC32_RE.search(trailer)
            if m_obj:
                trail_crc = m_obj.group(1)
        except re.error:
            sys.stderr.write("err: malformed =yend trailer\n")
    else:
        sys.stderr.write("warning: couldn't find =yend trailer\n")
    if garbage:
        sys.stderr.write("warning: garbage before =yend trailer\n")
    if head_crc:
        tmp_crc = head_crc.decode("ascii").lower()
    elif trail_crc:
        tmp_crc = trail_crc.decode("ascii").lower()
    else:
        sys.exit(0)


#    sys.stderr.write("comparing\n")
    if tmp_crc != dec.getCrc32():
        sys.stderr.write("err: header: %s dec: %s CRC32 mismatch\n" %
                         (tmp_crc, dec.getCrc32()))
        sys.exit(1)
    else:
        sys.exit(0)
Example #6
0
 def testDecodeFlushInMemory(self):
     decoder = yenc.Decoder()
     self.assertRaises(ValueError, decoder.flush)
Example #7
0
 def testDecoderCloseInMemory(self):
     decoder = yenc.Decoder()
     self.assertRaises(ValueError, decoder.close)
Example #8
0
 def testDecodeInMemory(self):
     decoder = yenc.Decoder()
     decoder.feed(b'r\x8f\x96\x96\x99J\xa1\x99\x9c\x96\x8eK')
     self.assertEqual(b"Hello world!", decoder.getDecoded())
     self.assertEqual(decoder.getCrc32(),
                      "%08x" % (crc32(b"Hello world!") & 0xffffffff))
Example #9
0
 def testDecoderClose(self):
     decoder = yenc.Decoder(open('afile.out', 'wb'))
     decoder.feed(b'some data')
     decoder.close()
     self.assertFalse(decoder._output_file)
Example #10
0
def parse_data(data, my_decode_flag, my_caesar_flag):
    my_answers = list()

    if my_decode_flag is True:

        for name in ('hex_codec', 'base64_codec', 'rot_13', 'utf_8',
                     'utf_16_be', 'utf_16_le', 'bz2', 'zip', 'idna', 'palmos',
                     'punycode', 'quopri_codec', 'utf_7'):
            try:
                result = data.decode(name)
                if verbose_flag:
                    print "%s succeeded" % name
                my_answers.append([name, repr(result)])
            except Exception as ex:
                if verbose_flag:
                    print "%s FAILED: %s" % (name, ex)

        name = 'base32'
        try:
            result = base64.b32decode(data)
            if verbose_flag:
                print "%s succeeded" % name
            my_answers.append([name, repr(result)])
        except Exception as ex:
            if verbose_flag:
                print "%s FAILED: %s" % (name, ex)

        name = 'uuencode'
        try:
            result = binascii.a2b_uu(data)
            if verbose_flag:
                print "%s succeeded" % name
            my_answers.append([name, repr(result)])
        except Exception as ex:
            if verbose_flag:
                print "%s FAILED: %s" % (name, ex)

        name = 'quotable'
        try:
            result = binascii.a2b_qp(data)
            if verbose_flag:
                print "%s succeeded" % name
            my_answers.append([name, repr(result)])
        except Exception as ex:
            if verbose_flag:
                print "%s FAILED: %s" % (name, ex)

        name = 'binhex4'
        try:
            result = binascii.rledecode_hqx(binascii.a2b_hqx(data))
            if verbose_flag:
                print "%s succeeded" % name
            my_answers.append([name, repr(result)])
        except Exception as ex:
            if verbose_flag:
                print "%s FAILED: %s" % (name, ex)

        name = 'yenc'
        try:
            decoder = yenc.Decoder()
            decoder.feed(data)
            result = decoder.getDecoded()
            if verbose_flag:
                print "%s succeeded" % name
            my_answers.append([name, repr(result)])
        except Exception as ex:
            if verbose_flag:
                print "%s FAILED: %s" % (name, ex)

    else:

        for name in ('hex_codec', 'base64_codec', 'rot_13', 'utf_8',
                     'utf_16_be', 'utf_16_le', 'bz2', 'zip', 'idna', 'palmos',
                     'punycode', 'quopri_codec', 'utf_7'):
            try:
                result = data.encode(name)
                if verbose_flag:
                    print "%s succeeded" % name
                my_answers.append([name, repr(result)])
            except Exception as ex:
                if verbose_flag:
                    print "%s FAILED: %s" % (name, ex)

        name = 'base32'
        try:
            result = base64.b32encode(data)
            if verbose_flag:
                print "%s succeeded" % name
            my_answers.append([name, repr(result)])
        except Exception as ex:
            if verbose_flag:
                print "%s FAILED: %s" % (name, ex)

        name = 'uuencode'
        try:
            result = binascii.b2a_uu(data)
            if verbose_flag:
                print "%s succeeded" % name
            my_answers.append([name, repr(result)])
        except Exception as ex:
            if verbose_flag:
                print "%s FAILED: %s" % (name, ex)

        name = 'quotable'
        try:
            result = binascii.b2a_qp(data)
            if verbose_flag:
                print "%s succeeded" % name
            my_answers.append([name, repr(result)])
        except Exception as ex:
            if verbose_flag:
                print "%s FAILED: %s" % (name, ex)

        name = 'binhex4'
        try:
            result = binascii.b2a_hqx(binascii.rlecode_hqx(data))
            if verbose_flag:
                print "%s succeeded" % name
            my_answers.append([name, repr(result)])
        except Exception as ex:
            if verbose_flag:
                print "%s FAILED: %s" % (name, ex)

        name = 'yenc'
        try:
            encoder = yenc.Encoder()
            encoder.feed(data)
            result = encoder.getEncoded()
            if verbose_flag:
                print "%s succeeded" % name
            my_answers.append([name, repr(result)])
        except Exception as ex:
            if verbose_flag:
                print "%s FAILED: %s" % (name, ex)

    if my_caesar_flag:
        for i in range(1, 256):
            my_answers.append([
                "Caesar_%d" % i,
                repr(''.join([chr((ord(c) + i) % 256) for c in data]))
            ])
            my_answers.append([
                "xor_%d" % i,
                repr(''.join([chr((ord(c) ^ i) % 256) for c in data]))
            ])

    return my_answers