def share(self):
        fileName = input('Ingrese el nombre del archivo: ')
        clave = input('Ingrese la clave del archivo: ')
        # verificar que la clave sea correcta

        usuarios = input(
            "Ingrese los nombres de usuario que quiere dar acceso separados por coma (ej: 'usuario1,usuario2'): "
        )
        if usuarios == "":
            print("No ingreso ningun usuario.")
            return
        self.connection.send({"nombreArchivo": fileName, "usuarios": usuarios})

        response = self.connection.receive()
        if response['operacion'] == 'share' and response[
                'resultado'] == 'error':
            print('El archivo no existe')
            return

        while (response['operacion'] == 'envioUsuarios'):
            pubKey = eval(response['publicKey'])
            public_key = Security.getPubKey(pubKey)

            encrypted_key = Security.encryptAsymPub(clave.encode('utf-8'),
                                                    public_key)

            self.connection.send({
                'resultado': 'OK',
                'claveEncriptada': str(encrypted_key)
            })
            response = self.connection.receive()
        print('Archivo compartido con exito\n')
Exemplo n.º 2
0
    def __init__(self):
        self.error = ''

        self.config = self.loadConfig()
        self.verbosity, result = self.getConfiguration("TRACELEVEL", True,
                                                       True)
        self.Security = Security()
    def download(self):
        self.connection.send({'resultado': 'OK'})
        data = self.connection.receive()

        if data['listaArchivos'] == []:
            print('No tiene archivos')
            self.connection.send({'operation': 'download', 'resultado': 'end'})
            return

        i = 0
        for file in data['listaArchivos']:
            filePathData = file.split('/')
            name = filePathData[2]
            print(str(i) + ' - ' + name + '\n')
            i = i + 1

        fileIndex = int(input('Escriba el numero del archivo a descargar: '))

        self.connection.send({
            'operation': 'download',
            'filePath': data['listaArchivos'][fileIndex],
            'resultado': 'OK'
        })

        response = self.connection.receive()

        bEncFileRaw = response['dataArchivo']
        fileName = data['listaArchivos'][fileIndex].split('/')[-1]

        bEncFile = eval(bEncFileRaw)

        bClave = input('Ingrese la clave del archivo: ').encode('utf-8')

        Security.decrypt_file(bClave, fileName, bEncFile)
Exemplo n.º 4
0
 def keyError(failure):
     Security.logProtectedCall(failure,
                               path,
                               args,
                               user,
                               allowed=False)
     result.errback(failure)
Exemplo n.º 5
0
 def receiveLogin(self):
     encodedData = self.receiveData()
     encryptedData = Helpers.decode(encodedData)
     jsonData = Security.decryptAsymPriv(eval(encryptedData),
                                         Security.getPrivKey())
     data = Helpers.fromJson(jsonData)
     return data
Exemplo n.º 6
0
 def test_functions_missing(self):
     # On 10.13.4 (beta) both functions are found, but crash...
     return
     self.assertIsInstance(Security.SecDecryptTransformGetTypeID(),
                           (int, long))
     self.assertIsInstance(Security.SecEncryptTransformGetTypeID(),
                           (int, long))
Exemplo n.º 7
0
 def __init__(self):
     self.security = Security()
     self.sym_key = None
     self.sock = socket.socket()
     self.AES = AESCrypt()
     self.ExplorerManager = ExplorerManager()
     self.permmisions = permmisions()
     self.Folder_Encrypt = Folder_Encrypt()
Exemplo n.º 8
0
    def login_request(self):
        passwd = Security.personal_encrypt(self.user_password)
        userid = Security.personal_encrypt(self.user_id)
        pubkey = Security.personal_encrypt(self.publicKey)
        pkt_typ = Security.personal_encrypt('login')

        drop = [passwd, userid, pubkey, pkt_typ]
        packet = pickle.dumps(drop)
        transmit_packet(self.client, packet)
Exemplo n.º 9
0
def restore_set_root(rpin):
    """Set data dir, restore_root and index, or return None if fail

	The idea here is to keep backing up on the path until we find
	a directory that contains "rdiff-backup-data".  That is the
	mirror root.  If the path from there starts
	"rdiff-backup-data/increments*", then the index is the
	remainder minus that.  Otherwise the index is just the path
	minus the root.

	All this could fail if the increment file is pointed to in a
	funny way, using symlinks or somesuch.

	"""
    global restore_root, restore_index, restore_root_set
    if rpin.isincfile(): relpath = rpin.getincbase().path
    else: relpath = rpin.path
    if rpin.conn is not Globals.local_connection:
        # For security checking consistency, don't get absolute path
        pathcomps = relpath.split('/')
    else:
        pathcomps = os.path.join(os.getcwd(), relpath).split("/")
    if not pathcomps[0]: min_len_pathcomps = 2  # treat abs paths differently
    else: min_len_pathcomps = 1

    i = len(pathcomps)
    while i >= min_len_pathcomps:
        parent_dir = rpath.RPath(rpin.conn, "/".join(pathcomps[:i]))
        if (parent_dir.isdir() and parent_dir.readable()
                and "rdiff-backup-data" in parent_dir.listdir()):
            break
        if parent_dir.path == rpin.conn.Globals.get('restrict_path'):
            return None
        i = i - 1
    else:
        return None

    restore_root = parent_dir
    Log("Using mirror root directory %s" % restore_root.path, 6)
    if restore_root.conn is Globals.local_connection:
        Security.reset_restrict_path(restore_root)
    SetConnections.UpdateGlobal('rbdir',
                                restore_root.append_path("rdiff-backup-data"))
    if not Globals.rbdir.isdir():
        Log.FatalError("Unable to read rdiff-backup-data directory %s" %
                       Globals.rbdir.path)

    from_datadir = tuple(pathcomps[i:])
    if not from_datadir or from_datadir[0] != "rdiff-backup-data":
        restore_index = from_datadir  # in mirror, not increments
    else:
        assert (from_datadir[1] == "increments" or
                (len(from_datadir) == 2
                 and from_datadir[1].startswith('increments'))), from_datadir
        restore_index = from_datadir[2:]
    restore_root_set = 1
    return 1
Exemplo n.º 10
0
def rcd_packet(code: int):

    if code == -100:
        typ = Security.encrypt_data('IDS_Warning',
                                    __client_initial_public_key__)
    else:
        typ = Security.encrypt_data('exception', __client_initial_public_key__)

    er = Security.encrypt_data(rcd[str(code)], __client_initial_public_key__)
    return pickle.dumps([er, typ])
Exemplo n.º 11
0
def write_new_acc(loggin: str, new_password: str, way: str):
    try:
        Security.decode_sys_files(way)
    except FileNotFoundError:
        pass
    with open(way, 'a', encoding='utf-8') as config_acc:
        string = ''
        password_new = Security.hash_password(new_password)
        string = string + str(loggin) + ' ' + str(password_new) + '\n'
        config_acc.write(string)
    Security.security_sys_files(way)
Exemplo n.º 12
0
def restore_set_root(rpin):
	"""Set data dir, restore_root and index, or return None if fail

	The idea here is to keep backing up on the path until we find
	a directory that contains "rdiff-backup-data".  That is the
	mirror root.  If the path from there starts
	"rdiff-backup-data/increments*", then the index is the
	remainder minus that.  Otherwise the index is just the path
	minus the root.

	All this could fail if the increment file is pointed to in a
	funny way, using symlinks or somesuch.

	"""
	global restore_root, restore_index, restore_root_set
	if rpin.isincfile(): relpath = rpin.getincbase().path
	else: relpath = rpin.path
	if rpin.conn is not Globals.local_connection:
		# For security checking consistency, don't get absolute path
		pathcomps = relpath.split('/')
	else: pathcomps = os.path.join(os.getcwd(), relpath).split("/")
	if not pathcomps[0]: min_len_pathcomps = 2 # treat abs paths differently
	else: min_len_pathcomps = 1

	i = len(pathcomps)
	while i >= min_len_pathcomps:
		parent_dir = rpath.RPath(rpin.conn, "/".join(pathcomps[:i]))
		if (parent_dir.isdir() and parent_dir.readable() and
			"rdiff-backup-data" in parent_dir.listdir()): break
		if parent_dir.path == rpin.conn.Globals.get('restrict_path'):
			return None
		i = i-1
	else: return None

	restore_root = parent_dir
	Log("Using mirror root directory %s" % restore_root.path, 6)
	if restore_root.conn is Globals.local_connection:
		Security.reset_restrict_path(restore_root)
	SetConnections.UpdateGlobal('rbdir',
								restore_root.append_path("rdiff-backup-data"))
	if not Globals.rbdir.isdir():
		Log.FatalError("Unable to read rdiff-backup-data directory %s" %
					   Globals.rbdir.path)

	from_datadir = tuple(pathcomps[i:])
	if not from_datadir or from_datadir[0] != "rdiff-backup-data":
		restore_index = from_datadir # in mirror, not increments
	else:
		assert (from_datadir[1] == "increments" or
				(len(from_datadir) == 2 and
				 from_datadir[1].startswith('increments'))), from_datadir
		restore_index = from_datadir[2:]
	restore_root_set = 1
	return 1
Exemplo n.º 13
0
def Main(arglist):
	"""Start everything up!"""
	parse_cmdlineoptions(arglist)
	check_action()
	cmdpairs = SetConnections.get_cmd_pairs(args, remote_schema, remote_cmd)
	Security.initialize(action or "mirror", cmdpairs)
	rps = map(SetConnections.cmdpair2rp, cmdpairs)
	final_set_action(rps)
	misc_setup(rps)
	take_action(rps)
	cleanup()
	if return_val is not None: sys.exit(return_val)
Exemplo n.º 14
0
    def test_structs(self):
        v = Security.SecKeychainSettings()
        self.assertEqual(v.version, 0)
        self.assertEqual(v.lockOnSleep, False)
        self.assertEqual(v.useLockInterval, False)
        self.assertEqual(v.lockInterval, 0)

        v = Security.SecKeychainCallbackInfo()
        self.assertEqual(v.version, 0)
        self.assertEqual(v.item, None)
        self.assertEqual(v.keychain, None)
        self.assertEqual(v.pid, 0)
Exemplo n.º 15
0
def Main(arglist):
	"""Start everything up!"""
	parse_cmdlineoptions(arglist)
	check_action()
	cmdpairs = SetConnections.get_cmd_pairs(args, remote_schema, remote_cmd)
	Security.initialize(action or "mirror", cmdpairs)
	rps = map(SetConnections.cmdpair2rp, cmdpairs)
	final_set_action(rps)
	misc_setup(rps)
	take_action(rps)
	cleanup()
	if return_val is not None: sys.exit(return_val)
 def __init__(self, pythonServer, clientSock, addr, sym_key):
     threading.Thread.__init__(self)
     self.security = Security()
     # reference to parent server
     self.pythonServer = pythonServer
     # new open socket  for client
     self.clientSock = clientSock
     # address connection : IP and Port
     self.addr = addr
     self.sym_key = None
     # Dictionary of ptotocols functions : Key - level  Value - referance to function
     #       self.operFnPtrDict = { 1 : self.oper1Fun, 2 : self.oper1Fun }
     self.AES = AESCrypt()
Exemplo n.º 17
0
    def signup_request(self, user_id, username):
        try:
            pkt_typ = 'signup'
            data = [user_id, self.user_password, self.publicKey, username]
            metadata = list()
            for value in data:
                metadata.append(Security.personal_encrypt(value))
            pkt_typ = Security.personal_encrypt(pkt_typ)

            packet = pickle.dumps([metadata, pkt_typ])
            self.client.send(packet)
        except Exception as e:
            print(e)
Exemplo n.º 18
0
class Communication:
    def __init__(self):

        HOST = 'localhost'  # IP host
        PORT = 8031  # The same port as used by the server

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Create socket object
        self.sock.connect((HOST, PORT))  # socket connects to the server

        self.sec = Security()  # Creates Security instance (object)

    def send(self, data):
        """
        Sends encrypted data to the server
        :param data: client data (string)
        :return: If data has been sent or if hasn't (boolean)
        """

        try:
            time.sleep(1)
            self.sock.settimeout(10)
            self.sock.send(self.sec.encrypt(json.dumps(data)))  # Sends cncrypted data to the server
            return True  # Returns if the data has been sent

        except socket.SO_ERROR:
            print "Couldn't send data: %s to the server" % data
            return False

    def recv(self, timeout=True):
        """
        Recives encrypted data from the server
        :param timeout: If the client needs timeout (True for default)
        :return: encrypted data (string)
        """
        temp_data = self.sock.recv(BUFFER_SIZE)

        if timeout:
            self.sock.settimeout(5)

        decrypted_data = self.sec.decrypt(temp_data)
        try:
            return json.loads(decrypted_data)

        except Exception as e:
            print e
            return

    def close(self):
        self.sock.close()
Exemplo n.º 19
0
    def manifest_packet(self, payload, rcvd_metadata, handler) -> bytes:

        drop = list()
        drop.append(payload)
        info = [self.user_id, rcvd_metadata[2], rcvd_metadata[3]]
        metadata = list()

        pkey = handler.public_key

        for value in info:
            metadata.append(Security.encrypt_data(value, pkey))

        drop.append(metadata)
        drop.append(Security.encrypt_data('msg', pkey))

        return pickle.dumps(drop)
Exemplo n.º 20
0
	def login(self,username,password):
		if(self.checkRegistered(username)):
			if(Security.check(self.getPassword(username),password)):
				return True
			return False
		else:
			return ""
Exemplo n.º 21
0
 def getParameters(self):
     token = Security.get_Authorization_Header()
     params = {"access_token": token}
     if self.hasPaging():
         params['limit'] = self.limit
         params['offset'] = self.offset
     return params
Exemplo n.º 22
0
    def __init__(self, client_conn, client_address, db_conn):
        super(ClientSession, self).__init__()

        self.db_conn = db_conn
        self.client_sock = client_conn
        self.client_address = client_address
        self.sec = Security()
Exemplo n.º 23
0
    def __init__(self, fsystem, dataserver, ip = "0.0.0.0", port = 5500, sender_id = random.randint(0, 65535),
            q = 0.0, p = 0.0, passwd = ''):
        Thread.__init__(self)

        # TODO Think trough how the program should exit
        #signal.signal(signal.SIGINT, self.signal_handler)
        
        self.fsystem = fsystem
        self.dataserver = dataserver
        self.sender_id = sender_id

        self.logger = logging.getLogger("Signal server")
        self.logger.info("Initializing signal server id: %d at %s" % (self.sender_id, str(time.time())))
        #self.logger.setLevel(logging.WARNING)

        self.sock = LossySocket(socket.AF_INET, socket.SOCK_DGRAM, q = q, p = p)
        self.sock.bind((ip, port))
        self.sock.settimeout(self.polltime) # So we can exit and wont block forever in recvfrom

        self.received_packet = InPacket()
        self.connection_list_lock = thread.allocate_lock()

        self.passwd = passwd
        if len(passwd) != 0:
            self.use_enc = True
            self.security = Security()
            self.privateKey,self.publicKey = self.security.generate_keys(1024)
            self.publicKey_plaintext = self.security.export_key(self.publicKey)
            self.key_hash = self.security.calculate_key_hash(self.publicKey_plaintext, passwd)
        else:
            self.use_enc = False
            self.security = None
            self.privateKey,self.publicKey = None, None
            self.publicKey_plaintext = ''
            self.key_hash = ''
Exemplo n.º 24
0
    def test_functions(self):
        self.assertIsInstance(Security.SecACLGetTypeID(), (int, long))

        self.assertFalse(hasattr(Security, "SecACLCreateFromSimpleContents"))

        self.assertResultHasType(Security.SecACLCreateWithSimpleContents,
                                 objc._C_INT)
        self.assertArgHasType(Security.SecACLCreateWithSimpleContents, 0,
                              objc._C_ID)
        self.assertArgHasType(Security.SecACLCreateWithSimpleContents, 1,
                              objc._C_ID)
        self.assertArgHasType(Security.SecACLCreateWithSimpleContents, 2,
                              objc._C_ID)
        self.assertArgHasType(Security.SecACLCreateWithSimpleContents, 3,
                              objc._C_USHT)
        self.assertArgHasType(
            Security.SecACLCreateWithSimpleContents,
            4,
            objc._C_OUT + objc._C_PTR + objc._C_ID,
        )
        self.assertArgIsCFRetained(Security.SecACLCreateWithSimpleContents, 4)

        self.assertResultHasType(Security.SecACLRemove, objc._C_INT)
        self.assertArgHasType(Security.SecACLRemove, 0, objc._C_ID)

        self.assertFalse(hasattr(Security, "SecACLCopySimpleContents"))

        self.assertResultHasType(Security.SecACLCopyContents, objc._C_INT)
        self.assertArgHasType(Security.SecACLCopyContents, 0, objc._C_ID)
        self.assertArgHasType(Security.SecACLCopyContents, 1,
                              objc._C_OUT + objc._C_PTR + objc._C_ID)
        self.assertArgIsCFRetained(Security.SecACLCopyContents, 1)
        self.assertArgHasType(Security.SecACLCopyContents, 2,
                              objc._C_OUT + objc._C_PTR + objc._C_ID)
        self.assertArgIsCFRetained(Security.SecACLCopyContents, 2)
        self.assertArgHasType(Security.SecACLCopyContents, 3,
                              objc._C_OUT + objc._C_PTR + objc._C_USHT)

        self.assertFalse(hasattr(Security, "SecACLSetSimpleContents"))

        self.assertResultHasType(Security.SecACLSetContents, objc._C_INT)
        self.assertArgHasType(Security.SecACLSetContents, 0, objc._C_ID)
        self.assertArgHasType(Security.SecACLSetContents, 1, objc._C_ID)
        self.assertArgHasType(Security.SecACLSetContents, 2, objc._C_ID)
        self.assertArgHasType(Security.SecACLSetContents, 3, objc._C_USHT)

        self.assertFalse(hasattr(Security, "SecACLGetAuthorizations"))

        self.assertResultHasType(Security.SecACLCopyAuthorizations, objc._C_ID)
        self.assertResultIsCFRetained(Security.SecACLCopyAuthorizations)
        self.assertArgHasType(Security.SecACLCopyAuthorizations, 0, objc._C_ID)

        self.assertFalse(hasattr(Security, "SecACLSetAuthorizations"))

        self.assertResultHasType(Security.SecACLUpdateAuthorizations,
                                 objc._C_INT)
        self.assertArgHasType(Security.SecACLUpdateAuthorizations, 0,
                              objc._C_ID)
        self.assertArgHasType(Security.SecACLUpdateAuthorizations, 1,
                              objc._C_ID)
Exemplo n.º 25
0
    def upload(self):
        fileDirectory = input(
            'Ingresa la dirección donde tienes el archivo a continuación: ')
        if (os.path.isfile(fileDirectory)
            ):  # Verifico si realmente es un archivo
            fileSplit = fileDirectory.split("/")
            fileName = fileSplit[-1]

            clave = input('Ingrese la clave especifica para el archivo: ')
            # chequear que clave sea menor a X caracteres

            # with open(fileDirectory, 'rb') as f:
            #     bFileData = f.read()

            bEncryptedFileData = Security.encrypt_file(clave.encode('utf-8'),
                                                       fileDirectory)

            self.connection.send({
                "nombreArchivo": str(fileName),
                "dataArchivo": str(bEncryptedFileData),
                "operacion": "Upload",
                "resultado": "OK"
            })
            response = self.connection.receive()
            if (response['operacion'] == 'Upload'
                    and response['resultado'] == 'OK'):
                print("Archivo subido con éxito")
        else:
            self.connection.send({
                "nombreArchivo": "None",
                "dataArchivo": "None",
                "operacion": "Upload",
                "resultado": "ERROR"
            })
            print("El directorio introducido no existe o ha sido eliminado")
Exemplo n.º 26
0
    def getWifiPassword(self, ssid):
        def CFDictionaryAddStringKeyValue(d, k, v):
            if type(v) is not bool:
                ck = CoreFoundation.CFStringCreateWithBytes(
                    None, k, len(k), 0, 0)
                cv = CoreFoundation.CFStringCreateWithBytes(
                    None, v, len(v), 0, 0)
                CoreFoundation.CFDictionaryAddValue(d, ck, cv)
                CoreFoundation.CFRelease(ck)
                CoreFoundation.CFRelease(cv)
            else:
                ck = CoreFoundation.CFStringCreateWithBytes(
                    None, k, len(k), 0, 0)
                CoreFoundation.CFDictionaryAddValue(d, ck, v)
                CoreFoundation.CFRelease(ck)

        query = CoreFoundation.CFDictionaryCreateMutable(None, 0, None, None)
        CFDictionaryAddStringKeyValue(query, kSecClass,
                                      kSecClassGenericPassword)
        CFDictionaryAddStringKeyValue(query, kSecAttrAccount,
                                      ssid.encode("utf-8"))
        CFDictionaryAddStringKeyValue(query, kSecReturnData, kCFBooleanTrue)
        _, keychain_item = Security.SecItemCopyMatching(query, None)
        try:
            return keychain_item.bytes().tobytes().decode("utf-8")
        except AttributeError:
            print("Could not find wifi password for ssid {}. Please enter it".
                  format(ssid))
            return getpass.getpass()
Exemplo n.º 27
0
    def getHighestEncStandard(self, destination, index):
        userData = Db.getUserDataAsList(destination)
        alphabet = string.letters
        randomString = ''
        for i in range(16):
            randomString += random.choice(alphabet)

        while index > 0:
            try:
                data = {
                    'sender': self.username,
                    'destination': destination,
                    'message': randomString
                }
                data['encryption'] = str(index)
                data = Security.encryptMessagesFiles(data, self.pubkey, index)
                request = urllib2.Request(
                    'http://' + userData[0]['ip'] + ':' + userData[0]['port'] +
                    '/handshake', self.encJSON(data),
                    {'Content-Type': 'application/json'})
                response = urllib2.urlopen(request).read()
                response = self.decJSON(response)
                print response
                print response['message']
                print randomString
                if response['message'] == randomString:
                    return index
            except:
                pass
            index = index - 1
        return 0
Exemplo n.º 28
0
    def test_regr_security_types(self):
        # Issue #324
        auth_ctx = LocalAuthentication.LAContext.new()
        access_control = Security.SecAccessControlCreateWithFlags(
            None,
            Security.kSecAttrAccessibleWhenUnlocked,
            Security.kSecAccessControlUserPresence,
            None,
        )[0]

        called = False

        def callback(a, b):
            nonlocal called
            called = True

        auth_ctx.evaluateAccessControl_operation_localizedReason_reply_(
            access_control,
            LocalAuthentication.LAAccessControlOperationCreateKey,
            "test",
            callback,
        )

        loop = Foundation.NSRunLoop.currentRunLoop()
        loop.runUntilDate_(Foundation.NSDate.dateWithTimeIntervalSinceNow_(0.2))

        self.assertTrue(called)
Exemplo n.º 29
0
    def test_functions(self):
        self.assertIsInstance(Security.SecRequirementGetTypeID(), int)

        self.assertResultHasType(Security.SecRequirementCreateWithData, objc._C_INT)
        self.assertArgHasType(Security.SecRequirementCreateWithData, 0, objc._C_ID)
        self.assertArgHasType(Security.SecRequirementCreateWithData, 1, objc._C_UINT)
        self.assertArgHasType(
            Security.SecRequirementCreateWithData,
            2,
            objc._C_OUT + objc._C_PTR + objc._C_ID,
        )
        self.assertArgIsCFRetained(Security.SecRequirementCreateWithData, 2)

        self.assertResultHasType(Security.SecRequirementCreateWithString, objc._C_INT)
        self.assertArgHasType(Security.SecRequirementCreateWithString, 0, objc._C_ID)
        self.assertArgHasType(Security.SecRequirementCreateWithString, 1, objc._C_UINT)
        self.assertArgHasType(
            Security.SecRequirementCreateWithString,
            2,
            objc._C_OUT + objc._C_PTR + objc._C_ID,
        )
        self.assertArgIsCFRetained(Security.SecRequirementCreateWithString, 2)

        self.assertResultHasType(
            Security.SecRequirementCreateWithStringAndErrors, objc._C_INT
        )
        self.assertArgHasType(
            Security.SecRequirementCreateWithStringAndErrors, 0, objc._C_ID
        )
        self.assertArgHasType(
            Security.SecRequirementCreateWithStringAndErrors, 1, objc._C_UINT
        )
        self.assertArgHasType(
            Security.SecRequirementCreateWithStringAndErrors,
            2,
            objc._C_OUT + objc._C_PTR + objc._C_ID,
        )
        self.assertArgHasType(
            Security.SecRequirementCreateWithStringAndErrors,
            3,
            objc._C_OUT + objc._C_PTR + objc._C_ID,
        )
        self.assertArgIsCFRetained(Security.SecRequirementCreateWithStringAndErrors, 3)

        self.assertResultHasType(Security.SecRequirementCopyData, objc._C_INT)
        self.assertArgHasType(Security.SecRequirementCopyData, 0, objc._C_ID)
        self.assertArgHasType(Security.SecRequirementCopyData, 1, objc._C_UINT)
        self.assertArgHasType(
            Security.SecRequirementCopyData, 2, objc._C_OUT + objc._C_PTR + objc._C_ID
        )
        self.assertArgIsCFRetained(Security.SecRequirementCopyData, 2)

        self.assertResultHasType(Security.SecRequirementCopyString, objc._C_INT)
        self.assertArgHasType(Security.SecRequirementCopyString, 0, objc._C_ID)
        self.assertArgHasType(Security.SecRequirementCopyString, 1, objc._C_UINT)
        self.assertArgHasType(
            Security.SecRequirementCopyString, 2, objc._C_OUT + objc._C_PTR + objc._C_ID
        )
        self.assertArgIsCFRetained(Security.SecRequirementCopyString, 2)
Exemplo n.º 30
0
 def protected_grantUri(self, uri, uid):
     """Returns a key for the capability ('ruleset.uri', uri).
        This can be used to delegate control of a particular URI's ruleset-
        an administrator would call this function to retrieve a key for a particular
        URI, then hand that to someone else who would only have the ability
        to edit that URI.
        """
     return Security.User(int(uid)).grant(('ruleset.uri', str(uri)))
Exemplo n.º 31
0
 def __init__(self):
     self.security = Security()
     self.sym_key =None
     self.sock = socket.socket()
     self.AES= AESCrypt()
     self.ExplorerManager = ExplorerManager()
     self.permmisions =  permmisions()
     self.Folder_Encrypt = Folder_Encrypt()
Exemplo n.º 32
0
    def send_msg(self, message, receiver_id):
        if self.is_connected:

            drop = list()
            try:
                pkey = self.get_public_key(receiver_id)  # INCOMPLETE
                pubkey = Security.get_Public_key(pkey)
                drop.append(Security.personal_encrypt(message, pubkey))

                metadata = list()
                metadata.append(Security.personal_encrypt(receiver_id))
                metadata.append(Security.personal_encrypt(self.user_id))
                metadata.append(Security.personal_encrypt(str(datetime.now())))
                metadata.append(
                    Security.personal_encrypt(str(sys.getsizeof(drop[0]))))

                drop.append(metadata)
                drop.append(Security.personal_encrypt('msg'))
                packet = pickle.dumps(drop)
            except Exception as e:
                log('-', 'Exception Raised while Sending message')
                return -1

            try:
                self.client.send(packet)
            except:
                log('-', 'Exception Packet Transfer')
                return -1
Exemplo n.º 33
0
    def test_structs(self):
        v = Security.AuthorizationExternalForm()
        self.assertEqual(v.bytes, None)

        v.bytes = b"\x00" * 32

        w = objc.repythonify(v, Security.AuthorizationExternalForm.__typestr__)
        self.assertIsInstance(w, Security.AuthorizationExternalForm)
        self.assertEqual(w.bytes, (0,) * 32)
Exemplo n.º 34
0
    def __init__(self):

        HOST = 'localhost'  # IP host
        PORT = 8031  # The same port as used by the server

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Create socket object
        self.sock.connect((HOST, PORT))  # socket connects to the server

        self.sec = Security()  # Creates Security instance (object)
Exemplo n.º 35
0
	def register(self,username,password):
		if(self.checkRegistered(username)):
			return False
		data = {}
		data["username"] = username
		data["password"] = Security.hash(password)
		data["balance"] = 0
		self.sqlman.insert("users",data)
		return True
Exemplo n.º 36
0
 def __init__(self, pythonServer, clientSock, addr):
     threading.Thread.__init__(self)
     self.security = Security()
     # reference to parent server
     self.pythonServer = pythonServer
     # new open socket  for client
     self.clientSock = clientSock
     # address connection : IP and Port
     self.addr = addr
Exemplo n.º 37
0
    def search_user(self, recv_id):
        pkt_typ = Security.personal_encrypt('publickey')
        recv_id_enc = Security.personal_encrypt(recv_id)
        drop = [recv_id_enc, pkt_typ]
        packet = pickle.dumps(drop)
        self.client.send(packet)

        def capture_response():

            while not self.friends[recv_id]:
                time.sleep(1)

        # thread_capture = threading.Thread(target=capture_response)
        # thread_capture.start()
        # thread_capture.join()
        self.friends[recv_id] = False
        capture_response()
        time.sleep(5)
        return self.get_publicKey(recv_id)
Exemplo n.º 38
0
 def __init__(self ,lid ,firstname ,lastname ,DOB ,age ,salary ,ltype ,exprence ,passcode):
     self.Labour_id = lid
     self.Labour_firstname = firstname
     self.Labour_lastname = lastname
     self.Labour_DOB = DOB
     self.Labour_age = age
     self.Labour_salary = salary
     self.Labour_type = ltype
     self.Labour_exprence = exprence
     self.passcode = Security.User_Passcode(passcode)
Exemplo n.º 39
0
class NetWorkClient:
    def __init__(self):
        self.security = Security()
        self.sym_key =None
        self.sock = socket.socket()
        self.AES= AESCrypt()

    def start(self):
        self.sock.connect((SERVER_ADDRESS, SERVER_PORT))

    def recv_buf(self):
        #content=""
        #while True:
        #    data = self.clientSock.recv(LEN_UNIT_BUF)
        #    if not data:  break
        #    content += data
        #print content
        #return content.split(END_LINE)[0]
        return self.sock.recv(LEN_UNIT_BUF).split(END_LINE)[0]

    def verify_hello(self, data):
        if len(data):
            # Verify Hello at beginning of communication
            if not (data == PROT_START ):
                self.sock.send(ERROR_SOCKET + END_LINE + "Error in protocol establishment ( 'Hello' )" + END_LINE)
                time.sleep(0.5)
                self.sock.close()
                return False
            return True
        return False

    def send(self, data):
        data = self.AES.encryptAES(self.sym_key, data)
        self.sock.send(data)

    def recv(self):
        encrypted_data = self.sock.recv(LEN_UNIT_BUF)
        data = self.AES.decryptAES(self.sym_key, encrypted_data)
        return data

    def run(self):
        self.start()
        self.sock.send(PROT_START)
        data = self.recv_buf()
        if not self.verify_hello(data):
            return
        self.sym_key = self.security.key_exchange_client(self.sock)
        print self.sym_key
        pipe=Pipe()
        loggedindetails=pipe.communication()
        print loggedindetails
        self.send(loggedindetails)
        pipe.pipesend(self.recv())
    def __init__(self, pythonServer, clientSock, addr, sym_key):
        threading.Thread.__init__(self)
        self.security = Security()
        # reference to parent server
        self.pythonServer = pythonServer
        # new open socket  for client
        self.clientSock = clientSock
        # address connection : IP and Port
        self.addr = addr
        self.sym_key = None
        # Dictionary of ptotocols functions : Key - level  Value - referance to function
 #       self.operFnPtrDict = { 1 : self.oper1Fun, 2 : self.oper1Fun }
        self.AES=AESCrypt()
Exemplo n.º 41
0
 def keyError(failure):
     Security.logProtectedCall(failure, path, args, user, allowed=False)
     result.errback(failure)
Exemplo n.º 42
0
class NetWorkClient:
    def __init__(self):
        self.security = Security()
        self.sym_key =None
        self.sock = socket.socket()
        self.AES= AESCrypt()
        self.ExplorerManager = ExplorerManager()
        self.permmisions =  permmisions()
        self.Folder_Encrypt = Folder_Encrypt()


    def start(self):
        self.sock.connect((SERVER_ADDRESS, SERVER_PORT))

    def recv_buf(self):
        #content=""
        #while True:
        #    data = self.clientSock.recv(LEN_UNIT_BUF)
        #    if not data:  break
        #    content += data
        #print content
        #return content.split(END_LINE)[0]
        return self.sock.recv(LEN_UNIT_BUF).split(END_LINE)[0]

    def verify_hello(self, data):
        if len(data):
            # Verify Hello at beginning of communication
            if not (data == PROT_START ):
                self.sock.send(ERROR_SOCKET + END_LINE + "Error in protocol establishment ( 'Hello' )" + END_LINE)
                time.sleep(0.5)
                self.sock.close()
                return False
            return True
        return False

    def send(self, data):
        data = self.AES.encryptAES(self.sym_key, data)
        self.sock.send(data)

    def recv(self):
        encrypted_data = self.sock.recv(LEN_UNIT_BUF)
        data = self.AES.decryptAES(self.sym_key, encrypted_data)
        return data

    def run(self):
        self.start()
        self.sock.send(PROT_START)
        data = self.recv_buf()
        if not self.verify_hello(data):
            return
        self.sym_key = self.security.key_exchange_client(self.sock)
        file_name =  self.recv()
        self.permmisions.Access_Denied(file_name)
        self.ExplorerManager.begin(file_name)
        pipe=Pipe()
        message=""
        while message!="You failed to login 3 times. Access to folder denied." or message != "login successful":
            loggedindetails=pipe.communication()
            print message
            self.send(loggedindetails)
            message = self.recv()
            pipe.pipesend(message)
        if "login failed" in message:
            self.Folder_Encrypt.encrypt_file(os.urandom(32), file_name)



        print
        raw_input()
        self.permmisions.remove_ace(file_name)
Exemplo n.º 43
0
class SyncCFT:
    def __init__(self):
        signal.signal(signal.SIGINT, self.signal_handler)
        self.logger = logging.getLogger("SyncCFT 1.0")
        self.logger.info("Starting SyncCFT 1.0 at %s" % (str(time.time())))
        self.exit_flag = 0

        config = Configuration(sys.argv)

        conf_values = config.load_configuration()
        self.local_password = config.load_password()

        if not conf_values:
            self.logger.error("An error occurred while loading the configuration!")
            return

        (self.port, self.folder, self.p_prob, self.q_prob, self.peers) = conf_values
        #Logging of configuration
        self.logger.info("Listening on UDP port %s" % (str(self.port)))
        self.logger.info("Synchronizing folder %s" % (str(self.folder)))
        self.logger.info("'p' parameter: %s" % (str(self.p_prob)))
        self.logger.info("'q' parameter: %s" % (str(self.q_prob)))

        i=1
        for item in self.peers:
            self.logger.info("Peer %d: %s:%s" % (i,str(item[0]),str(item[1])))
            i+=1

    def start_SyncCFT(self):
        self.packetmanager = PacketManager()
        self.security = Security()
        self.fsystem = FileSystem(self.folder, '.private')

        (self.privateKey,self.publicKey) = self.security.generate_keys(1024)
        self.publicKey_plaintext = self.security.export_key(self.publicKey)

        self.fsystem.start_thread(timeout=1)

        try:
            while not self.exit_flag:
                time.sleep(5)
        except Exception:
            pass

        print self.fsystem.current_dic
        self.fsystem.terminate_thread()

        '''
        print "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
        print "Here comes our new coding!!\n"
        mylist = ['FIL?f1?5?1330560662?5310dab750cabf7e2d1f307554874f9a','RMF?f3?11?1339999999?a73c45107081c08dd4560206b8ef8205']
        print "The difference of the manifests are..."
        print self.fsystem.get_diff_manifest_remote(mylist)
        print "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"

        print self.fsystem.current_dic

        self.fsystem.terminate_thread()


        pwdA= 'passwordA'
        (privateKA,publicKA) = self.security.generate_keys(1024)
        exp_publicKA = self.security.export_key(publicKA)
        hash_A = self.security.calculate_key_hash(exp_publicKA, pwdA)

        #(privateKB,publicKB) = self.security.generate_keys(1024)

        print "Creating the packet..."
        self.packetmanager.create_packet(2, ['SEC'], 0xabcd,0xfeea, 0xfee0, 3150765550, 286331153, "HELLO", "REQUEST", None, None)
        self.packetmanager.append_entry_to_TLVlist('SECURITY', exp_publicKA+'?'+hash_A)
        packet = self.packetmanager.build_packet()

        #self.packetmanager.append_list_to_TLVlist('DATA', ['oneeeeee','twoooooooo','threeeeeeee', 'fourrrrrrr'])
        #self.packetmanager.append_entry_to_TLVlist('DATA', 'data_test')
        #self.packetmanager.append_entry_to_TLVlist('CONTROL', 'control_test')
        #self.packetmanager.append_entry_to_TLVlist('SECURITY', 'security_test')
        #packet = self.packetmanager.build_packet()

        print "This is the packet dump"
        self.packetmanager.hex_packet()

        #raw_data = '\x29\x02\xAB\xCD\xFE\xEA\xFE\xE0\xBB\xCC\xDD\xEE\x11\x11\x11\x11\x01\x01\x4C\xA9\x02\x30\x30\x30\x38\x6F\x6E\x65\x65\x65\x65\x65\x65\x02\x30\x30\x31\x30\x74\x77\x6F\x6F\x6F\x6F\x6F\x6F\x6F\x6F\xFF\x30\x30\x31\x31\x74\x68\x72\x65\x65\x65\x65\x65\x65\x65\x65'
        #raw_packet = self.packetmanager.create_packet(rawdata = raw_data)

        print "\n\n\n"
        print self.packetmanager.get_version()
        print self.packetmanager.get_flags()
        print self.packetmanager.get_senderID()
        print self.packetmanager.get_txlocalID()
        print self.packetmanager.get_txremoteID()
        print self.packetmanager.get_sequence()
        print self.packetmanager.get_ack()
        print self.packetmanager.get_otype()
        print self.packetmanager.get_ocode()
        print "This is the TLV_List"
        print self.packetmanager.get_TLVlist()
        print "This is the get_TLVlist_typevalue"
        print self.packetmanager.get_TLVlist_typevalue()

        print "self.packetmanager.get_TLVlist('SECURITY')"
        print self.packetmanager.get_TLVlist('SECURITY')
        security_payload = self.packetmanager.get_TLVlist('SECURITY')
        recovered_plaintextkey = security_payload[0].split('?')[0]
        recovered_hash = security_payload[0].split('?')[1]

        recovered_key = self.security.import_key(recovered_plaintextkey)
        print recovered_key

        if self.security.calculate_key_hash(recovered_plaintextkey, pwdA) == recovered_hash:
            print "Access granted!"

        '''
        '''
        original_packet = packet[:]

        print "\n\n\n*********************************************************\n\n\n"
        print "The following reprensents a communication between 2 peers"

        password_A= 'ProtocolDesign'
        password_B= 'ProtocolDesig'

        (privateKA,publicKA) = self.security.generate_keys(1024)
        (privateKB,publicKB) = self.security.generate_keys(1024)

        print "Peer-A wants to send"
        self.print_hex(original_packet)

        print "Peer-A encrypts with Public_Key_B"
        encrypted_packet = self.security.encrypt(publicKB, original_packet)
        self.print_hex(encrypted_packet)

        print "Peer-B decrypts with Private_Key_B"
        decrypted_packet = self.security.decrypt(privateKB, encrypted_packet)
        self.print_hex(decrypted_packet)

        if original_packet == decrypted_packet:
            print "Both packets are the same after the crypto!!!"

        #This is the hash sent by A
        exp_publicKA = self.security.export_key(publicKA)
        hash_A = self.security.calculate_key_hash(exp_publicKA, password_A)

        #B calculates the following
        hash_B = self.security.calculate_key_hash(exp_publicKA, password_A)

        if hash_A == hash_B:
            print "Access granted!"
        else:
            print "Wrong password!"
        '''

        return

    def signal_handler(self, signal, frame):
        self.logger.warning("You pressed Ctrl+C")
        print "\nYou pressed Ctrl+C!\n"
        self.exit_flag = 1
        #sys.exit(1)

    def print_hex(self, text):
        l = len(text)
        i = 0
        while i < l:
            print "%04x  " % i,
            for j in range(16):
                if i+j < l:
                    print "%02X" % ord(text[i+j]),
                else:
                    print "  ",
                if j%16 == 7:
                    print "",
            print " ",

            ascii = text[i:i+16]
            r=""
            for i2 in ascii:
                j2 = ord(i2)
                if (j2 < 32) or (j2 >= 127):
                    r=r+"."
                else:
                    r=r+i2
            print r
            i += 16
Exemplo n.º 44
0
    def start_SyncCFT(self):
        self.packetmanager = PacketManager()
        self.security = Security()
        self.fsystem = FileSystem(self.folder, '.private')

        (self.privateKey,self.publicKey) = self.security.generate_keys(1024)
        self.publicKey_plaintext = self.security.export_key(self.publicKey)

        self.fsystem.start_thread(timeout=1)

        try:
            while not self.exit_flag:
                time.sleep(5)
        except Exception:
            pass

        print self.fsystem.current_dic
        self.fsystem.terminate_thread()

        '''
        print "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
        print "Here comes our new coding!!\n"
        mylist = ['FIL?f1?5?1330560662?5310dab750cabf7e2d1f307554874f9a','RMF?f3?11?1339999999?a73c45107081c08dd4560206b8ef8205']
        print "The difference of the manifests are..."
        print self.fsystem.get_diff_manifest_remote(mylist)
        print "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"

        print self.fsystem.current_dic

        self.fsystem.terminate_thread()


        pwdA= 'passwordA'
        (privateKA,publicKA) = self.security.generate_keys(1024)
        exp_publicKA = self.security.export_key(publicKA)
        hash_A = self.security.calculate_key_hash(exp_publicKA, pwdA)

        #(privateKB,publicKB) = self.security.generate_keys(1024)

        print "Creating the packet..."
        self.packetmanager.create_packet(2, ['SEC'], 0xabcd,0xfeea, 0xfee0, 3150765550, 286331153, "HELLO", "REQUEST", None, None)
        self.packetmanager.append_entry_to_TLVlist('SECURITY', exp_publicKA+'?'+hash_A)
        packet = self.packetmanager.build_packet()

        #self.packetmanager.append_list_to_TLVlist('DATA', ['oneeeeee','twoooooooo','threeeeeeee', 'fourrrrrrr'])
        #self.packetmanager.append_entry_to_TLVlist('DATA', 'data_test')
        #self.packetmanager.append_entry_to_TLVlist('CONTROL', 'control_test')
        #self.packetmanager.append_entry_to_TLVlist('SECURITY', 'security_test')
        #packet = self.packetmanager.build_packet()

        print "This is the packet dump"
        self.packetmanager.hex_packet()

        #raw_data = '\x29\x02\xAB\xCD\xFE\xEA\xFE\xE0\xBB\xCC\xDD\xEE\x11\x11\x11\x11\x01\x01\x4C\xA9\x02\x30\x30\x30\x38\x6F\x6E\x65\x65\x65\x65\x65\x65\x02\x30\x30\x31\x30\x74\x77\x6F\x6F\x6F\x6F\x6F\x6F\x6F\x6F\xFF\x30\x30\x31\x31\x74\x68\x72\x65\x65\x65\x65\x65\x65\x65\x65'
        #raw_packet = self.packetmanager.create_packet(rawdata = raw_data)

        print "\n\n\n"
        print self.packetmanager.get_version()
        print self.packetmanager.get_flags()
        print self.packetmanager.get_senderID()
        print self.packetmanager.get_txlocalID()
        print self.packetmanager.get_txremoteID()
        print self.packetmanager.get_sequence()
        print self.packetmanager.get_ack()
        print self.packetmanager.get_otype()
        print self.packetmanager.get_ocode()
        print "This is the TLV_List"
        print self.packetmanager.get_TLVlist()
        print "This is the get_TLVlist_typevalue"
        print self.packetmanager.get_TLVlist_typevalue()

        print "self.packetmanager.get_TLVlist('SECURITY')"
        print self.packetmanager.get_TLVlist('SECURITY')
        security_payload = self.packetmanager.get_TLVlist('SECURITY')
        recovered_plaintextkey = security_payload[0].split('?')[0]
        recovered_hash = security_payload[0].split('?')[1]

        recovered_key = self.security.import_key(recovered_plaintextkey)
        print recovered_key

        if self.security.calculate_key_hash(recovered_plaintextkey, pwdA) == recovered_hash:
            print "Access granted!"

        '''
        '''
        original_packet = packet[:]

        print "\n\n\n*********************************************************\n\n\n"
        print "The following reprensents a communication between 2 peers"

        password_A= 'ProtocolDesign'
        password_B= 'ProtocolDesig'

        (privateKA,publicKA) = self.security.generate_keys(1024)
        (privateKB,publicKB) = self.security.generate_keys(1024)

        print "Peer-A wants to send"
        self.print_hex(original_packet)

        print "Peer-A encrypts with Public_Key_B"
        encrypted_packet = self.security.encrypt(publicKB, original_packet)
        self.print_hex(encrypted_packet)

        print "Peer-B decrypts with Private_Key_B"
        decrypted_packet = self.security.decrypt(privateKB, encrypted_packet)
        self.print_hex(decrypted_packet)

        if original_packet == decrypted_packet:
            print "Both packets are the same after the crypto!!!"

        #This is the hash sent by A
        exp_publicKA = self.security.export_key(publicKA)
        hash_A = self.security.calculate_key_hash(exp_publicKA, password_A)

        #B calculates the following
        hash_B = self.security.calculate_key_hash(exp_publicKA, password_A)

        if hash_A == hash_B:
            print "Access granted!"
        else:
            print "Wrong password!"
        '''

        return
Exemplo n.º 45
0
class NetWorkClient:
    def __init__(self):
        self.security = Security()
        self.sym_key =None
        self.sock = socket.socket()
        self.AES= AESCrypt()
        self.Database= Database()

    def start(self):
        self.sock.connect((SERVER_ADDRESS, SERVER_PORT))

    def recv_buf(self):
        #content=""
        #while True:
        #    data = self.clientSock.recv(LEN_UNIT_BUF)
        #    if not data:  break
        #    content += data
        #print content
        #return content.split(END_LINE)[0]
        return self.sock.recv(LEN_UNIT_BUF).split(END_LINE)[0]

    def verify_hello(self, data):
        if len(data):
            # Verify Hello at beginning of communication
            if not (data == PROT_START ):
                self.sock.send(ERROR_SOCKET + END_LINE + "Error in protocol establishment ( 'Hello' )" + END_LINE)
                time.sleep(0.5)
                self.sock.close()
                return False
            return True
        return False

    def send(self, data):
        data = self.AES.encryptAES(self.sym_key, data)
        self.sock.send(data)

    def recv(self):
        encrypted_data = self.sock.recv(LEN_UNIT_BUF)
        data = self.AES.decryptAES(self.sym_key, encrypted_data)
        return data

    def run(self):
        connect= False
        while connect== False:
            try:
                self.start()
                self.sock.send(PROT_START)
                data = self.recv_buf()
                if not self.verify_hello(data):
                    return
                self.sym_key = self.security.key_exchange_client(self.sock)
                print self.sym_key
                connect=True
                while data!="get info":
                    data = self.recv()
                    print data
                    if data=="get info":
                        #send all information about client
                        dict=self.Database.get_dict_from_table("WORDS")
                        self.send(self.Database.get_most_used_words(dict))

            except:
                print "still cant find server"
                time.sleep(5)
Exemplo n.º 46
0
def Socket_Server():

    Adress = (("0.0.0.0",8080))
    Server_Socket = socket.socket()
    Server_Socket.bind(Adress)
    Server_Socket.listen(15)


    while True:
        print 'waiting for client connection...'
        (Client_Socket, Client_Adress) = Server_Socket.accept()
        print "Connected From: " + str(Client_Adress[0])

        Sec_Obj = Security()
        sym_key = Sec_Obj.key_exchange(Client_Socket)

        DB_Obj = DB_Managment_Class()

        Local_Obj_Socket = Connecting_Using_Socket(sym_key)
        User_Name_And_Password = Local_Obj_Socket.Socket_Recieve(Client_Socket)## Recieving Client User Name And Password

        DB_Obj.DB_Creation() ## Create DB or Doing Nothing If DB Is Already Exists

        ## Next 5 Lines Extracts The User And Password From Client

        Temp_Arr = User_Name_And_Password.split(',')
        print Temp_Arr[0] + " , " + Temp_Arr[1]

        if len(Temp_Arr) > 2:
            if DB_Obj.If_Client_Already_Exists(str(Client_Adress[0])) == True:
                Local_Obj_Socket.Socket_Send(Client_Socket,"Client Already Exists!")
                continue

            else:
                DB_Obj.Clients_DataBase_Add(str(Client_Adress[0]),Temp_Arr[0]+Temp_Arr[1])
                Local_Obj_Socket.Socket_Send(Client_Socket,"Client: " + Client_Adress[0] + " - " +Temp_Arr[0] + " Added!!!!")
        ##if Temp_Arr[0] == "ori" and Temp_Arr[1] == "123":
            ##print "Before If_Client_Already_Exists" + Client_Adress[0]

        ##Bool_Result = DB_Obj.If_Client_Already_Exists(Client_Adress[0])
        else:
            print "LEN < || =  2"
            print str(Client_Adress[0])
            Bool_Result = DB_Obj.If_Client_Already_Exists(str(Client_Adress[0]))

            Seconed_Bool_Result = DB_Obj.If_Un_And_Pass_Already_Exists(Temp_Arr[0]+Temp_Arr[1])

            if Bool_Result == True and Seconed_Bool_Result == True:
                print
                Local_Obj_Socket.Socket_Send(Client_Socket,"Logged In!")
            else:
                Local_Obj_Socket.Socket_Send(Client_Socket,"You Are Not Registered!")
                continue

        DB_Obj.Insert_DB_Into_File()

        ##try:
        Data_From_Client = Client_Adress[0] + User_Name_And_Password
        ##except:
            ##print "Client Disconected"
            ##Data_From_Client = "Client Disconected:" + Client_Adress[0]
            ##continue

        Pipe_Client_To_Server = Thread(target=Local_Obj_Pipe.Pipe_Client_To_Server(Data_From_Client,))
        Pipe_Client_To_Server.start()


        t1 = Thread(target = Client_Handler,args=(Client_Socket,Client_Adress,Local_Obj_Socket))
        t1.start()
Exemplo n.º 47
0
 def __init__(self):
     self.security = Security()
     self.sym_key =None
     self.sock = socket.socket()
     self.AES= AESCrypt()
Exemplo n.º 48
0
class  SessionWithClient(threading.Thread):
    # -----  D A T A  -----    

    # -----  F U N C T I O N S  -----
    #-----------------------------------------------------------------------------------------------
    #  class definition function
    #-----------------------------------------------------------------------------------------------
    def __init__(self, pythonServer, clientSock, addr, sym_key):
        threading.Thread.__init__(self)
        self.security = Security()
        # reference to parent server
        self.pythonServer = pythonServer
        # new open socket  for client
        self.clientSock = clientSock
        # address connection : IP and Port
        self.addr = addr
        self.sym_key = None
        # Dictionary of ptotocols functions : Key - level  Value - referance to function
 #       self.operFnPtrDict = { 1 : self.oper1Fun, 2 : self.oper1Fun }
        self.AES=AESCrypt()
        self.DBManager = DBManager()
        self.KeyGenerator = KeyGenerator()
        self.EmailSender = EmailSender()

    #-----------------------------------------------------------------------------------------------
    # Receive data from input stream from server socket by loop
    # Each step read LEN_UNIT_BUF bytes
    # After loop we want to get only first part of split by '\r\n'
    # Return : content of input stream from server socket
    #-----------------------------------------------------------------------------------------------  
    def recv_buf(self):
        #content=""
        #while True:
        #    data = self.clientSock.recv(LEN_UNIT_BUF)
        #    if not data:  break
        #    content += data
        #print content
        #return content.split(END_LINE)[0]
        return self.clientSock.recv(LEN_UNIT_BUF).split(END_LINE)[0]

    #-----------------------------------------------------------------------------------------------
    # the function for verify Hello at beginning of communication in data
    #-----------------------------------------------------------------------------------------------  
    def verify_hello(self, data):
        if len(data):
            # Verify Hello at beginning of communication
            if not (data == PROT_START ):
                self.clientSock.send(ERROR_SOCKET + END_LINE + "Error in protocol establishment ( 'Hello' )" + END_LINE)
                time.sleep(0.5)
                self.clientSock.close()
                return False
            return True
        return False
  

    #-----------------------------------------------------------------------------------------------
    #  Operation  1   ---    
    #
    # Description: 
    #-----------------------------------------------------------------------------------------------
    def send(self, data):
        data2= self.AES.encryptAES(self.sym_key,data)
        self.clientSock.send(data2)
    #-----------------------------------------------------------------------------------------------

    def rec(self):
        data = self.clientSock.recv(2048)
        print data

        data2 = self.AES.decryptAES(self.sym_key, data)
        return data2
    #-----------------------------------------------------------------------------------------------

    #-----------------------------------------------------------------------------------------------
    # the main function of the THREAD sessionWithClient class
    #-----------------------------------------------------------------------------------------------



    def run(self):
        try:
            # Wait message beginning of communication from client
            data = self.recv_buf()
            if not self.verify_hello(data):
                return
            self.clientSock.send(PROT_START + END_LINE)
           # self.pythonServer.gui.guiSock.send("Hello " +  self.addr[0] + "#")   # to GUI
            self.sym_key = self.security.key_exchange(self.clientSock)#  in Security
            ip = self.addr[0]
            folder = self.DBManager.folder_by_ip(ip)
            self.send(folder)
            data2 = ""
            while data2!="You failed to login 3 times. Access to folder denied." or data2 != "login successful":
                print data2
                data2 = self.rec()
                message=self.DBManager.run(data2,ip)
                self.send(message)

            if "login failed" in data2:
                self.EmailSender.send(self.DBManager.email_by_ip(ip),folder, ip)
            self.clientSock.close()

        except socket.error , e:
            print str(e) + END_LINE + ERROR_SOCKET + "  from " + str(self.addr[0])
        except Exception as e:
            print str(e) + END_LINE + ERROR_EXCEPT + "  from " + str(self.addr[0])
Exemplo n.º 49
0
	def __init__( self ):
		self.error = ''

		self.config = self.loadConfig()
		self.verbosity, result = self.getConfiguration( "TRACELEVEL", True, True )
		self.Security = Security()
Exemplo n.º 50
0
class iDEALConnector( object ):
	def __init__( self ):
		self.error = ''

		self.config = self.loadConfig()
		self.verbosity, result = self.getConfiguration( "TRACELEVEL", True, True )
		self.Security = Security()

	def GetIssuerList( self ):
		self.clearError()
		configCheck = self.CheckConfig( self.config )

		if configCheck <> unicode('OK'):
			errorResponse = ErrorResponse()
			errorResponse.setErrorCode('001')
			errorResponse.setErrorMessage('Config error: %s' % configCheck)
			errorResponse.setConsumerMessage('')

			return errorResponse

		# Build up the XML header for this request
		xmlMsg = self.getXMLHeader('DirectoryReq', '', '', '', '')
		if not xmlMsg:
			return False

		xmlMsg += u"</DirectoryReq>\n"

		# Post the XML to the server.
		response = self.PostXMLData( xmlMsg )

		# If the response did not work out, return an ErrorResponse object.
		if not self.parseFromXml( 'errorCode', response ) in ['', False]:
			errorResponse = ErrorResponse()

			errorResponse.setErrorCode(self.parseFromXml( 'errorCode', response ))
			errorResponse.setErrorMessage(self.parseFromXml( 'errorMessage', response ))
			errorResponse.setConsumerMessage(self.parseFromXml( 'consumerMessage', response ))

			return errorResponse

		if self.parseFromXml( 'acquirerID', response ) == '':
			errorResponse = ErrorResponse()

			errorResponse.setErrorCode('ING1001')
			errorResponse.setErrorMessage('DirectoryList service probleem')
			errorResponse.setConsumerMessage('')
				
			return errorResponse

		# Create a new DirectoryResponse object with the required information
		res = DirectoryResponse()
		res.setAcquirerID( self.parseFromXml( 'acquirerID', response ) )
		res.setDirectoryDateTimeStamp( self.parseFromXml( 'directoryDateTimeStamp', response ) )

		# While there are issuers to be read from the stream
		while response.find('<issuerID>' ) is not -1:

			# Read the information for the next issuer.
			issuerID	= self.parseFromXml( 'issuerID', response )
			issuerName	= self.parseFromXml( 'issuerName', response )
			issuerList	= self.parseFromXml( 'issuerList', response )

			# Create a new entry and add it to the list
			issuerEntry = IssuerEntry()
			issuerEntry.setIssuerID( issuerID )
			issuerEntry.setIssuerName( issuerName )
			issuerEntry.setIssuerListType( issuerList )
			res.addIssuer( issuerEntry )
				
			# Find the next issuer.
			response = response[response.find('</issuerList>')+13: ]

		return res


	def RequestTransaction( self, issuerId, purchaseId, amount, description, entranceCode, optExpirationPeriod='', optMerchantReturnURL='' ):
		"""
			This function submits a transaction request to the server.

			@param string $issuerId			The issuer Id to send the request to
			@param string $purchaseId		The purchase Id that the merchant generates
			@param integer $amount			The amount in cents for the purchase
			@param string $description		The description of the transaction
			@param string $entranceCode		The entrance code for the visitor of the merchant site. Determined by merchant
			@param string $optExpirationPeriod		Expiration period in specific format. See reference guide. Can be configured in config.
			@param string $optMerchantReturnURL		The return URL (optional) for the visitor. Optional. Can be configured in config.
			@return An instance of AcquirerTransactionResponse or "false" on failure.
		"""
		self.clearError()
		configCheck = self.CheckConfig( self.config )

		if configCheck <> unicode('OK'):
			self.setError( ING_ERROR_MISSING_CONFIG, 'Config error: %s' % configCheck, IDEAL_PRV_GENERIC_ERROR )
			return self.getError()

		if not self.verifyNotNull( issuerId, 'issuerId' ) or \
			not self.verifyNotNull( purchaseId, 'purchaseId' ) or \
			not self.verifyNotNull( amount, 'amount' ) or \
			not self.verifyNotNull( description, 'description' ) or \
			not self.verifyNotNull( entranceCode, 'entranceCode' ):
			errorResponse = self.getError()
			return errorResponse

		# check amount length
		amountOK = self.LengthCheck( 'Amount', amount, 12 )
		if amountOK != "ok":
			return self.getError()

		# check for diacritical characters
		amountOK = self.CheckDiacritical( 'Amount', amount )
		if amountOK != "ok":
			return self.getError()

		# check entrancecode length
		entranceCodeOK = self.LengthCheck( 'Entrancecode', entranceCode, 40 )
		if entranceCodeOK != "ok":
			return self.getError()
		# check for diacritical characters
		entranceCodeOK = self.CheckDiacritical( 'Entrancecode', entranceCode )
		if entranceCodeOK != "ok":
			return self.getError()

		# check purchaseid length
		purchaseIDOK = self.LengthCheck( 'PurchaseID', purchaseId, 16 )
		if purchaseIDOK != "ok":
			return self.getError()
		# check for diacritical characters
		purchaseIDOK = self.CheckDiacritical( 'PurchaseID', purchaseId )
		if purchaseIDOK != "ok":
			return self.getError()

		# According to the specification, these values should be hardcoded.
		currency = 'EUR'
		language = 'nl'

		# Retrieve these values from the configuration file.
		cfgExpirationPeriod, result1 = self.getConfiguration( 'EXPIRATIONPERIOD', True )
		cfgMerchantReturnURL, result2 = self.getConfiguration( 'MERCHANTRETURNURL', True )

		if len( optExpirationPeriod ):
			# If a (valid?) optional setting was specified for the expiration period, use it.
			expirationPeriod = optExpirationPeriod
		else:
			expirationPeriod = cfgExpirationPeriod

		if len( optMerchantReturnURL ):
			# If a (valid?) optional setting was specified for the merchantReturnURL, use it.
			merchantReturnURL = optMerchantReturnURL
		else:
			merchantReturnURL = cfgMerchantReturnURL

		if not self.verifyNotNull( expirationPeriod, 'expirationPeriod' ) or \
			not self.verifyNotNull( merchantReturnURL, 'merchantReturnURL' ):
			return False

		# Build the XML header for the transaction request
		xmlMsg = self.getXMLHeader(
        	'AcquirerTrxReq', 
			issuerId,
			"<Issuer>\n<issuerID>%s</issuerID>\n</Issuer>\n" % issuerId,
			"%s%s%s%s%s%s%s" % (merchantReturnURL, purchaseId, amount, currency, language, description, entranceCode),
			"<merchantReturnURL>%s</merchantReturnURL>\n" % merchantReturnURL )
			
		if xmlMsg in [False, '']:
			return False

		# Add transaction information to the request.
		xmlMsg += "<Transaction>\n<purchaseID>%s</purchaseID>\n" % purchaseId;
		xmlMsg += "<amount>%s</amount>\n" % amount;
		xmlMsg += "<currency>%s</currency>\n" % currency;
		xmlMsg += "<expirationPeriod>%s</expirationPeriod>\n" % expirationPeriod;
		xmlMsg += "<language>%s</language>\n" % language;
		xmlMsg += "<description>%s</description>\n" % description;
		xmlMsg += "<entranceCode>%s</entranceCode>\n" % entranceCode;
		xmlMsg += "</Transaction>\n";
		xmlMsg += "</AcquirerTrxReq>\n";

		# Post the request to the server.
		response = self.PostXMLData( xmlMsg )

		# If the response did not work out, return an ErrorResponse object.
		if not self.parseFromXml( 'errorCode', response ) in ['', False]:
			errorResponse = ErrorResponse()

			errorResponse.setErrorCode(self.parseFromXml( 'errorCode', response ))
			errorResponse.setErrorMessage(self.parseFromXml( 'errorMessage', response ))
			errorResponse.setConsumerMessage(self.parseFromXml( 'consumerMessage', response ))

			return errorResponse

		if self.parseFromXml( 'acquirerID', response ) in ['', False]:
			errorResponse = ErrorResponse()

			errorResponse.setErrorCode('ING1001')
			errorResponse.setErrorMessage('Transactie mislukt (aquirer side)')
			errorResponse.setConsumerMessage('')
				
			return errorResponse

		html_decode_table = {
			"&amp;": "&",
			"&quot;": '"',
			"&apos;": "'",
			"&gt;": ">",
			"&lt;": "<",
			}
		
		def html_decode(text):
			"""Produce entities within text."""
			L=[]
			for c in text:
				L.append(html_decode_table.get(c,c))
			return "".join(L)

		# Build the transaction response object and pass in the data.
		res = AcquirerTransactionResponse()
		res.setAcquirerID( self.parseFromXml( 'acquirerID', response ) )
		res.setIssuerAuthenticationURL( html_decode( self.parseFromXml( 'issuerAuthenticationURL', response ) ) )
		res.setTransactionID( self.parseFromXml( 'transactionID', response ) )
		res.setPurchaseID( self.parseFromXml( 'purchaseID', response ) )

		if not res:
			return response
		
		return res


	def RequestTransactionStatus( self, transactionId ):
		""" RequestTransactionStatus
			This public function makes a transaction status request

			@param string $transactionId	The transaction ID to query. (as returned from the TX request)
			@return An instance of AcquirerStatusResponse or FALSE on failure.
		"""
		self.clearError()
		configCheck = self.CheckConfig( self.config )

		if configCheck <> unicode('OK'):
			errorResponse = ErrorResponse()
			errorResponse.setErrorCode('001')
			errorResponse.setErrorMessage('Config error: %s' % configCheck)
			errorResponse.setConsumerMessage('')

			return errorResponse

		# check TransactionId length
		if not self.LengthCheck( 'TransactionID', transactionId, 16 ).lower() == 'ok'.lower():
			return self.getError()
		if not self.verifyNotNull( transactionId, 'transactionId'):
			return self.getError()

		# Build the status request XML.
		xmlMsg = self.getXMLHeader('AcquirerStatusReq', '', '', transactionId, '')
		if not xmlMsg:
			return False

		# Add transaction information.
		xmlMsg += u"<Transaction>\n<transactionID>%s</transactionID></Transaction>\n" % transactionId
		xmlMsg += u"</AcquirerStatusReq>\n"

		# Post the request to the server.
		response = self.PostXMLData( xmlMsg )
		# If the response did not work out, return an ErrorResponse object.
		if not self.parseFromXml( 'errorCode', response ) in ['', False]:
			errorResponse = ErrorResponse()

			errorResponse.setErrorCode(self.parseFromXml( 'errorCode', response ))
			errorResponse.setErrorMessage(self.parseFromXml( 'errorMessage', response ))
			errorResponse.setConsumerMessage(self.parseFromXml( 'consumerMessage', response ))

			return errorResponse

		if self.parseFromXml( 'acquirerID', response ) in ['', False]:
			errorResponse = ErrorResponse()

			errorResponse.setErrorCode('ING1001')
			errorResponse.setErrorMessage('Status lookup mislukt (aquirer side)')
			errorResponse.setConsumerMessage('')
				
			return errorResponse

		# Build the status response object and pass the data into it.
		res = AcquirerStatusResponse()
		creationTime = self.parseFromXml( 'createDateTimeStamp', response )
		res.setAcquirerID( self.parseFromXml( 'acquirerID', response ) )
		res.setConsumerName( self.parseFromXml( 'consumerName', response ) )
		res.setConsumerAccountNumber( self.parseFromXml( 'consumerAccountNumber', response ) )
		res.setConsumerCity( self.parseFromXml( 'consumerCity', response ) )
		res.setTransactionID( self.parseFromXml( 'transactionID', response ) )
		
		# The initial status is INVALID, so that future modifications to
		# this or remote code will yield alarming conditions.
		res.setStatus( IDEAL_TX_STATUS_INVALID )
		status = self.parseFromXml( 'status', response )

		# Determine status identifier (case-insensitive).
		dStatus = {
			'Success': IDEAL_TX_STATUS_SUCCESS,
			'Cancelled': IDEAL_TX_STATUS_CANCELLED,
			'Expired': IDEAL_TX_STATUS_EXPIRED,
			'Failure': IDEAL_TX_STATUS_FAILURE,
			'Open': IDEAL_TX_STATUS_OPEN
		}

		for statuscode in dStatus.keys():
			if status.lower() == statuscode.lower():
				res.setStatus( dStatus[ statuscode ] )
		# The verification of the response starts here.
		# The message as per the reference guide instructions.
		consumerAccountNumber = res.getConsumerAccountNumber()
		if consumerAccountNumber == False:
			consumerAccountNumber = ''
		message = self.strip( '%s%s%s%s' % ( creationTime, res.getTransactionID(), status, consumerAccountNumber ) )
		# The signature value in the response contains the signed hash
		# (signed by the signing key on the server)
		signature64 = self.parseFromXml( 'signatureValue', response )

		# The signed hash is base64 encoded and inserted into the XML as such
		sig = base64.b64decode( signature64 )

		# The fingerprint is used as the identifier of the public key certificate.
		# It is sent as part of the response XML.
		fingerprint = self.parseFromXml( 'fingerprint', response )

		# The merchant should have the public certificate stored locally.
		certfile = self.getCertificateFileName( fingerprint )
		if certfile in ['', False]:
			return False

		# Verify the message signature
		valid = self.Security.verifyMessage( certfile, str(message), str(sig) )
		if not valid:
			return False

		if not res:
			return response
		
		return res

	def getError( self ):
		""" getError
			This public function returns the ErrorResponse object or "" if it does not exist.
			@return ErrorResponse object or an emptry string "".
		"""
		return self.error

	#-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-#
	#                           private functions                                   #
	#-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-#

	def log( self, desiredVerbosity, message ):
		""" log
			Logs a message to the file.
			@param string desiredVerbosity	The desired verbosity of the message
			@param string message			The message to log
		"""
		# Check if the log file is set. If not set, don't log.
		if 'LOGFILE' not in self.config or self.config['LOGFILE'] == '':
			return

		if desiredVerbosity not in self.verbosity:
			# The desired verbosity is not listed in the configuration
			return

		# Open the log file in 'append' mode.
		pFile = open( SECURE_PATH+'/'+self.config['LOGFILE'], 'a' )
		pFile.write( "%s: %s: %s\r\n" % ( self.getCurrentDateTime(), desiredVerbosity.upper(), message ) )
		pFile.close()

	def setError( self, errCode, errMsg, consumerMsg ):
		""" setError
			Creates a new ErrorResponse object and populates it with the arguments

			@param unknown_type errCode		The error code to return. This is either a code from the platform or an internal code.
			@param unknown_type errMsg		The error message. This is not meant for display to the consumer.
			@param unknown_type consumerMsg	The consumer message. The error message to be shown to the user.
		"""
		self.error = ErrorResponse()
		self.error.setErrorCode( errCode )
		self.error.setErrorMessage( errCode )
		if len( consumerMsg ):
			self.error.setConsumerMessage( consumerMsg )
		else:
			self.error.setConsumerMessage( IDEAL_PRV_GENERIC_ERRORMESSAGE )

	def clearError( self ):
		""" clearError
			Clears the error conditions.
		"""
		#iDEALConnector_error = 0
		#iDEALConnector_errstr = ''
		self.error = ''

	def getXMLHeader( self, msgType, firstCustomIdInsert, firstCustomFragment, secondCustomIdInsert, secondCustomFragment ):
		""" getXMLHeader
			Builds up the XML message header.

			@param string msgType				The type of message to construct.
			@param string firstCustomIdInsert	The identifier value(s) to prepend to the hash ID.
			@param string firstCustomFragment	The fragment to insert in the header before the general part.
			@param string secondCustomIdInsert	The identifier value(s) to append to the hash ID.
			@param string secondCustomFragment	The XML fragment to append to the header after the general part.
			@return string
		"""
		# Determine the (string) timestamp for the header and hash id.
		timestamp = self.getCurrentDateTime()

		# Merchant ID and sub ID come from the configuration file.
		merchantId, result = self.getConfiguration( "MERCHANTID", False )
		subId, result = self.getConfiguration( "SUBID", False )

		if not result:
			return False

		# Build the hash ID
		message = self.strip( "%s%s%s%s%s" % ( str(timestamp), str(firstCustomIdInsert), str(merchantId), str(subId), str(secondCustomIdInsert) ) )
		# Create the certificate fingerprint used to sign the message. This is passed in to identify
		# the public key of the merchant and is used for authentication and integrity checks.
		privateCert, result = self.getConfiguration( "PRIVATECERT", False )
		if not result:
			return False

		token = self.Security.createCertFingerprint( privateCert )

		if not token:
			return False

		# Calculate the base-64'd hash of the hashId and store it in tokenCode.
		tokenCode = self.calculateHash( message )

		if not tokenCode:
			return False

		# Start building the header.
#		xmlHeader = u'<?xml version="1.0" encoding="UTF-8"?>\n<%s xmlns="http://www.idealdesk.com/Message" version="1.1.0">\n<createDateTimeStamp>%s</createDateTimeStamp>\n' % ( msgType, timestamp )

		xmlHeader = u"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
		xmlHeader += u"<" + msgType + " xmlns=\"http://www.idealdesk.com/Message\" version=\"1.1.0\">\n"
		xmlHeader += u"<createDateTimeStamp>" + timestamp + "</createDateTimeStamp>\n"

		if len( firstCustomFragment ):
			# If there is a custom fragment to prepend, insert it here.
			xmlHeader += unicode(firstCustomFragment + "\n")

		# The general parts of the header
#		xmlHeader += u'<Merchant>\n<merchantID>%s</merchantID>\n<subID>%s</subID>\n<authentication>SHA1_RSA</authentication>\n<token>%s</token>\n<tokenCode>%s</tokenCode>\n' % ( self.encode_html( merchantId ), subId, token, tokenCode )

		xmlHeader += u"<Merchant>\n"
		xmlHeader += u"<merchantID>" +self.encode_html( merchantId )+ "</merchantID>\n"
		xmlHeader += u"<subID>" +subId+ "</subID>\n"
		xmlHeader += u"<authentication>SHA1_RSA</authentication>\n"
		xmlHeader += u"<token>" +unicode(token)+ "</token>\n"
		xmlHeader += u"<tokenCode>" +unicode(tokenCode)+ "</tokenCode>\n"

		if len( secondCustomFragment ):
			# If there is a fragment to append, append it here.
			xmlHeader += secondCustomFragment
		# Close the header and return it.
		xmlHeader += u'</Merchant>\n'

		return xmlHeader

	def strip( self, message ):
		""" strip
			Strips whitespace from a string.

			@param string $message	The string to strip.
			@return string			The stripped string.
		"""
		return message.replace(" ", "").replace("\t", "").replace("\n", "")

	def encode_html( self, text):
		""" encode_html
			Encodes HTML entity codes to characters

			@param string text	The text to encode
			@return string 		The encoded text
		"""
		html_escape_table = {
			"&": "&amp;",
			'"': "&quot;",
			"'": "&apos;",
			">": "&gt;",
			"<": "&lt;",
			}
		
		def html_escape(text):
			"""Produce entities within text."""
			L=[]
			for c in text:
				L.append(html_escape_table.get(c,c))
			return "".join(L)

		return html_escape( text )
#		return htmlspecialchars(strtr($text, $trans), ENT_QUOTES)

	def getCurrentDateTime( self ):
		""" getCurrentDateTime
			Gets current date and time.

			@return string	Current date and time.
		"""
		ts = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())
		return ts

	def loadConfig( self ):
		""" loadConfig
			Loads the configuration for the MPI interface

			@return array().  An array of the configuration elements
		"""
		dConfData = {}
		
		try:
			# Check if the file exists and read until the end.
			pFile = open( SECURE_PATH + '/config.conf', 'r' )
		except:
			return dConfData
		else:
			dFileBuffer = pFile.readlines()
			pFile.close()
		
		for sLine in dFileBuffer:
			# filter out the commented lines
			if sLine.startswith('#'):
				continue
			dConf = sLine.split('=')
			if len(dConf) == 2: # let's say: having configname and value
				dConfData[ dConf[0].strip().upper() ] = dConf[1].strip()

		return dConfData

	def CheckConfig( self, dConfData ):
		""" CheckConfig

			Checks if the Configuration is set correctly. If an option is not set correctly, it will return an error. This has
			to be checked in the begin of every function that needs these settings and if an error occurs, it must rethrown
			to show it to the user.

			@return string	Error message when configsetting is missing, if no errors occur, ok is thrown back
		"""
		if dConfData['MERCHANTID'] == '':
			return u'MERCHANTID is missing'
		elif len( dConfData['MERCHANTID'] ) > 9:
			return u'MERCHANTID too long!'
		elif dConfData['SUBID'] == '':
			return u'SUBID is missing'
		elif len( dConfData['SUBID'] ) > 6:
			return u'SUBID too long!'
		elif dConfData['ACQUIRERURL'] == '':
			return u'ACQUIRERURL is missing'
		elif dConfData['MERCHANTRETURNURL'] == '':
			return u'MERCHANTRETURNURL is missing'
		elif len( dConfData['MERCHANTRETURNURL'] ) > 512:
			return u'MERCHANTRETURNURL too long!'
		elif dConfData['EXPIRATIONPERIOD'] == '':
			return u'EXPIRATIONPERIOD is missing'
		else:
			return unicode('OK')

	def getConfiguration( self, name, allowMissing, result=False ):
		""" getConfiguration
			Safely get a configuration item.
			Returns the value when name was found, otherwise an emptry string ("").
			If "allowMissing" is set to true, it does not generate an error.

			@param string	name		The name of the configuration item.
			@param boolean	allowMissing	
			@param boolean	result		Not used, built-in for inter-api compatibility
			@return tupple	(The value as specified in the configuration file, boolean result)
		"""
		bResult = ( name in self.config.keys() ) & ( len( self.config.get( name, '') ) > 0 )
		if not bResult and not allowMissing:
			self.log( TRACE_ERROR, 'The configuration item %s is not configured in the configuraton file.' % name )
			self.setError( ING_ERROR_MISSING_CONFIG, 'Missing configuration: %s' % name, IDEAL_PRV_GENERIC_ERROR )
		return ( self.config.get( name, '' ), bResult )

	def calculateHash( self, message ):
		""" calculateHash
			Calculates the hash of a piece and encodes it with base64.

			@param string message	The message to sign.
			@return string			The signature of the message in base64.
		"""
		# Find keys and sign the message
		priv_key, result = self.getConfiguration( 'PRIVATEKEY', False )
		priv_keypass, result = self.getConfiguration( 'PRIVATEKEYPASS', False )

		tokenCode = self.Security.signMessage( priv_key, priv_keypass, message )
		if not result:
			return False
		
		# encode the signature with base64
		tokenCode = base64.b64encode( tokenCode )
		return tokenCode

	def getCertificateFileName( self, fingerprint ):
		"""
			Gets a valid certificate file name based on the certificate fingerprint.
			Uses configuration items in the config file, which are incremented when new
			security certificates are issued:
			certificate0=ideal1.crt
			certificate1=ideal2.crt
			etc...

			@param string $fingerprint	A hexadecimal representation of a certificate's fingerprint
			@return string	The filename containing the certificate corresponding to the fingerprint
		"""
		# Check if the configuration file contains such an item
		for configValue in self.config.keys():
			if configValue.startswith('CERTIFICATE'):
				certFilename = self.config[ configValue ]
			else:
				continue

			# Generate a fingerprint from the certificate in the file.
			buff = self.Security.createCertFingerprint( certFilename )
			if buff == False:
				# Could not create fingerprint from configured certificate.
				return False

			# Check if the fingerprint is equal to the desired one.
			if fingerprint == buff:
				return certFilename

		self.log( TRACE_ERROR, 'Could not find certificate with fingerprint %s' % fingerprint )
		self.setError( ING_ERROR_COULD_NOT_VERIFY, 'Could not verify message', IDEAL_PRV_GENERIC_ERROR )

		# By default, report no success.
		return False

	def PostXMLData( self, message ):
		""" PostXMLData
			Posts XML data to the server or proxy.

			@param string message	The message to post.
			@return string			The response of the server.
		"""
		sProxy, result = self.getConfiguration( 'PROXY', True )
		if sProxy == '':
			acquirerUrl, result = self.getConfiguration( 'ACQUIRERURL', False )

			if not result:
				return False
			# if Proxy configuration does not exist
			return self.PostToHost( acquirerUrl, message )

		proxyUrl, result = self.getConfiguration( 'PROXYACQURL', False )

		if not result:
			return False
		# if proxy is specified
		return self.PostToHostProxy( sProxy, proxyUrl, message )

	def PostToHost( self, sUrl, sDataToSend ):
		""" PostToHost
			Posts a message to the host.

			@param string sUrl	The URL to send the message to.
			@param string sDataToSend	The data to send
			@return string	The response from the server.
		"""
		# Decompose the URL into specific parts.
		sHost, sPort, sPath = re.findall('([\w]+://[\w\d\.-]+):([\d]+)([\w/]+)', sUrl, re.I)[0]

		# Log the request
		self.log( TRACE_DEBUG, 'sending to %s:%s%s: %s' % ( sHost, sPort, sPath, sDataToSend ) )
		return self.PostToServer( sHost, sPort, sPath, sDataToSend )

	def PostToProxy( self, sProxy, sUrl, sDataToSend ):
		""" PostToProxy
			Posts to a proxy, which is slightly different

			@param string sProxy		The proxy to post to
			@param string sUrl			The URL the proxy should post to.
			@param string sDataToSend	The data to send
			@return string	The response
		"""
		# Decompose the proxyURL into specific parts.
		sHost, sPort = re.findall('([\w]+://[\w\d\.-]+):([\d]+)', sProxy, re.I)[0]

		# Log the request
		self.log( TRACE_DEBUG, 'sending through proxy %s:%s: %s' % ( sHost, sPort, sDataToSend ) )

		# Post to the proxy
		return self.PostToServer( sHost, sPort, sUrl, sDataToSend )

	def PostToServer( self, sHost, sPort, sPath, sDataToSend ):
		"""
			Posts to the server and interprets the result

			@param string sHost		The host to post to
			@param string sPort		The port to use
			@param string sPath		The application path on the remote server
			@param string sDataToSend	The data to send
			@return string	The response of the remote server.
		"""
		sRes = ''
		
		# The connection timeout for the remote server
		timeout, result = self.getConfiguration( 'ACQUIRERTIMEOUT', False )
		if not result:
			return False

		# Open connection and report problems in custom error handler.
		

	def PostToServer( self, sHost, sPort, sPath, sDataToSend ):
		""" PostToServer
			Posts to the server and interprets the result

			@param string $host		The host to post to
			@param string $port		The port to use
			@param string $path		The application path on the remote server
			@param string $data_to_send	The data to send
			@return string	The response of the remote server.
		"""
		sHost = sHost.replace('ssl://', 'https://') # urllib2 doesn't like the ssl:// prefix
		sURL = '%s:%s%s' % ( sHost, sPort, sPath )
		# get the connection timeout (config) for the remote server
		timeout, result = self.getConfiguration( 'ACQUIRERTIMEOUT', False )
		if not result:
			return False

		# open the connection and report problems in custom error handler.
		req = urllib2.Request(url=sURL, data=sDataToSend)
		try:
			f = urllib2.urlopen(req)
		except URLError, e:
			# An error occurred when trying to connect to the server.
			self.log( TRACE_ERROR, "Could not connect to: [%s:%s%s]" % ( sHost, sPort, sPath ) )
			self.setError( ING_ERROR_COULD_NOT_CONNECT, "Could not connect to remote server", IDEAL_PRV_GENERIC_ERROR )
			return False
		else:
Exemplo n.º 51
0
class NetWorkClient:
    def __init__(self):
        self.security = Security()
        self.sym_key =None
        self.sock = socket.socket()
        self.AES= AESCrypt()
        self.ExplorerManager = ExplorerManager()
        self.permmisions =  permmisions()
        self.Folder_Encrypt = Folder_Encrypt()
        self.Pipe = Pipe()


    def start(self):
        self.sock.connect((SERVER_ADDRESS, SERVER_PORT))

    def recv_buf(self):
        #content=""
        #while True:
        #    data = self.clientSock.recv(LEN_UNIT_BUF)
        #    if not data:  break
        #    content += data
        #print content
        #return content.split(END_LINE)[0]
        return self.sock.recv(LEN_UNIT_BUF).split(END_LINE)[0]

    def verify_hello(self, data):
        if len(data):
            # Verify Hello at beginning of communication
            if not (data == PROT_START ):
                self.sock.send(ERROR_SOCKET + END_LINE + "Error in protocol establishment ( 'Hello' )" + END_LINE)
                time.sleep(0.5)
                self.sock.close()
                return False
            return True
        return False

    def send(self, data):
        data = self.AES.encryptAES(self.sym_key, data)
        self.sock.send(data)

    def recv(self):
        encrypted_data = self.sock.recv(LEN_UNIT_BUF)
        data = self.AES.decryptAES(self.sym_key, encrypted_data)
        return data

    def run(self):
        self.start()
        self.sock.send(PROT_START)
        data = self.recv_buf()
        if not self.verify_hello(data):
            return
        self.sym_key = self.security.key_exchange_client(self.sock)
        file_name = self.recv()
        self.permmisions.Access_Denied(file_name)
        print self.ExplorerManager.begin(file_name)
        if self.ExplorerManager.begin(file_name)== "folder open":
            #subprocess.check_call(r"C:\Users\User\Desktop\Project-master\Code\GUI\WindowsFormsApplication5\bin\Debug\WindowsFormsApplication5.exe")
            self.Pipe.pipesend("folder open")
        message = ""
        count=0
        while count<3:
            loggedindetails=self.Pipe.communication()
            print message
            self.send(loggedindetails)
            message = self.recv()
            self.Pipe.pipesend(message)
            count+=1
        if "login failed" in message:
            self.Folder_Encrypt.encrypt_file(os.urandom(32), file_name)
        if message == "login successful":
            self.permmisions.remove_ace(file_name)
Exemplo n.º 52
0
class SessionWithClient(threading.Thread):
    # -----  D A T A  -----    

    # -----  F U N C T I O N S  -----
    # -----------------------------------------------------------------------------------------------
    #  class definition function
    # -----------------------------------------------------------------------------------------------
    def __init__(self, pythonServer, clientSock, addr):
        threading.Thread.__init__(self)
        self.security = Security()
        # reference to parent server
        self.pythonServer = pythonServer
        # new open socket  for client
        self.clientSock = clientSock
        # address connection : IP and Port
        self.addr = addr
        # Dictionary of ptotocols functions : Key - level  Value - referance to function
        #       self.operFnPtrDict = { 1 : self.oper1Fun, 2 : self.oper1Fun }

    # -----------------------------------------------------------------------------------------------
    # Receive data from input stream from server socket by loop
    # Each step read LEN_UNIT_BUF bytes
    # After loop we want to get only first part of split by '\r\n'
    # Return : content of input stream from server socket
    # -----------------------------------------------------------------------------------------------
    def recv_buf(self):
        # content=""
        # while True:
        #    data = self.clientSock.recv(LEN_UNIT_BUF)
        #    if not data:  break
        #    content += data
        # print content
        # return content.split(END_LINE)[0]
        return self.clientSock.recv(LEN_UNIT_BUF).split(END_LINE)[0]

    # -----------------------------------------------------------------------------------------------
    # the function for verify Hello at beginning of communication in data
    # -----------------------------------------------------------------------------------------------
    def verify_hello(self, data):
        if len(data):
            # Verify Hello at beginning of communication
            if not (data == PROT_START):
                self.clientSock.send(ERROR + END_LINE + "Error in protocol establishment ( 'Hello' )" + END_LINE)
                time.sleep(0.5)
                self.clientSock.close()
                return False
            return True
        return False

    # -----------------------------------------------------------------------------------------------
    # the main function of the THREAD sessionWithClient class  
    # -----------------------------------------------------------------------------------------------
    def run(self):
        try:
            # Wait message beginning of communication from client
            data = self.recv_buf()
            if not self.verify_hello(data):
                return
            self.clientSock.send(PROT_START + END_LINE)
            self.pythonServer.gui.guiSock.send("Hello " + self.addr[0] + "#")  # to GUI

            self.security.key_exchange(self.clientSock)  # in Security

            self.clientSock.close()
        except socket.error, e:
            print str(e) + END_LINE + ERROR_SOCKET + "  from " + str(self.addr[0])
        except Exception as e:
            print str(e) + END_LINE + ERROR_EXCEPT + "  from " + str(self.addr[0])
Exemplo n.º 53
0
class SignalServer(Thread):
    
    sock = None
    logger = None
    sender_id = 0
    buf_size = 2000 # TODO This is not nice
    connection_list = [] # List of established connections
    exit_flag = False
    received_packet = None
    fsystem = None
    polltime = 0.5
    updatetime = 5.0 # update time. send update messages to all peers.

    # TODO Throw error in case bind fails (Might do it already...)
    def __init__(self, fsystem, dataserver, ip = "0.0.0.0", port = 5500, sender_id = random.randint(0, 65535),
            q = 0.0, p = 0.0, passwd = ''):
        Thread.__init__(self)

        # TODO Think trough how the program should exit
        #signal.signal(signal.SIGINT, self.signal_handler)
        
        self.fsystem = fsystem
        self.dataserver = dataserver
        self.sender_id = sender_id

        self.logger = logging.getLogger("Signal server")
        self.logger.info("Initializing signal server id: %d at %s" % (self.sender_id, str(time.time())))
        #self.logger.setLevel(logging.WARNING)

        self.sock = LossySocket(socket.AF_INET, socket.SOCK_DGRAM, q = q, p = p)
        self.sock.bind((ip, port))
        self.sock.settimeout(self.polltime) # So we can exit and wont block forever in recvfrom

        self.received_packet = InPacket()
        self.connection_list_lock = thread.allocate_lock()

        self.passwd = passwd
        if len(passwd) != 0:
            self.use_enc = True
            self.security = Security()
            self.privateKey,self.publicKey = self.security.generate_keys(1024)
            self.publicKey_plaintext = self.security.export_key(self.publicKey)
            self.key_hash = self.security.calculate_key_hash(self.publicKey_plaintext, passwd)
        else:
            self.use_enc = False
            self.security = None
            self.privateKey,self.publicKey = None, None
            self.publicKey_plaintext = ''
            self.key_hash = ''



    def run(self):
        
        self.logger.info("Server started at %s" % (str(time.time())))
        while self.exit_flag == False:
            try:
                data, addr = self.sock.recvfrom(self.buf_size)
            except socket.error:
                errno, errstr = sys.exc_info()[:2]
                if errno == socket.timeout:
                    for i, connection in enumerate(self.connection_list):
                        # Check if the connection should send an update message
                        # Also remove broken connections
                        if not connection.check_send_update():
                            connection.stop()
                            del self.connection_list[i]
                    #self.logger.info("socket timeout")
                    continue
                else:
                    self.logger.alarm("error with socket")
            if self.use_enc:
                packet_ok = self.received_packet.packetize_header(data)
            else:
                packet_ok = self.received_packet.packetize_raw(data)

            self.received_packet.receive_time = time.time()
            found = False
            self.connection_list_lock.acquire()
            for connection in self.connection_list:
                if self.received_packet.txremoteID == connection.local_session_id:
                    self.logger.info("packet belongs to existing connection. processing...")
                    found = True
                    if self.use_enc and connection.state == SignalConnection.State.CONNECTED and 'CRY' in self.received_packet.get_flags():
                        data = self.security.decrypt_AES_bin(connection.aes_key, data, 8)
                        #PacketManager.hex_data(data)
                    packet_ok = self.received_packet.packetize_raw(data)
                    self.logger.info("received packet:\n%s" % str(self.received_packet))
                    if not packet_ok:
                        self.logger.warning("Decrypted packet is not valid.")
                        break
                    connection.handle(self.received_packet)
                    break
            if not found:
                if self.use_enc:
                    packet_ok = self.received_packet.packetize_raw(data)
                self.logger.info("received packet:\n%s" % str(self.received_packet))
                if packet_ok and self.received_packet.otype == OPERATION['HELLO'] and \
                        self.received_packet.ocode == CODE['REQUEST']:
                    connection = SignalConnection(server = self, remote_ip = addr[0], remote_port = addr[1], 
                        local_session_id = self.get_new_session_id(random.randint(0, 65535)),
                        remote_session_id = self.received_packet.txlocalID,
                        version = self.received_packet.version,
                        send_ack_no = self.received_packet.sequence,
                        seq_no = random.randint(0, 65535),
                        updatetime = self.updatetime)
    #def __init__(self, server, remote_ip, remote_port, local_session_id, remote_session_id = 0,
    #        version = 1, send_ack_no = random.randint(0, 65534), seq_no = random.randint(0, 65535)):
                    connection.hello_recv(self.received_packet)
                    self.connection_list.append(connection)
                    self.logger.info("hello packet received, new connection established\
(local id %d, remote id %d) and HELLO sent" % (connection.local_session_id, connection.remote_session_id))
                elif not packet_ok:
                    self.logger.warning("Packet is not valid.")
            elif not found and packet_ok:
                self.logger.info("Packet does not belong to any connection and not a valid HELLO. Discarding.")
            self.logger.info("done with packet.\n")
            for i, connection in enumerate(self.connection_list):
                # Check if the connection should send an update message
                # Also remove broken connections
                if not connection.check_send_update():
                    connection.stop()
                    del self.connection_list[i]
            self.connection_list_lock.release()
                


    # destination list should contain (ip, port) tuples
    def init_connections(self, destination_list):
        
        # todo create hello packet
        #self.packetmanager.create_packet(2, 15, 43962, 52428, 56797, 3150765550, 286331153, 85, 102, None, None)

        for destination in destination_list:
            self.logger.info('connecting to ' + destination[0] + ', ' + destination [1])
            #self.sock.sendto("daddaa", (destination[0], int(destination[1])) )
            connection = SignalConnection(self, destination[0], int(destination[1]),
                self.get_new_session_id(random.randint(0, 65535)))
            connection.connect()
            self.connection_list.append(connection)
    
    # Returns an unigue local session_id. Takes a random number from 0 to 65535 as a parameter.
    def get_new_session_id(self, rand_no):
        for connection in self.connection_list:
            if rand_no == connection.local_session_id:
                return get_new_session_id(random.randint(0, 65535))
        return rand_no

    def stop(self):
        for connection in self.connection_list:
            connection.stop()
        self.logger.info("server should stop")
        self.exit_flag = True
Exemplo n.º 54
0
class ClientSession(threading.Thread):
    def __init__(self, client_conn, client_address, db_conn):
        super(ClientSession, self).__init__()

        self.db_conn = db_conn
        self.client_sock = client_conn
        self.client_address = client_address
        self.sec = Security()

    def send(self, data):
        try:
            self.client_sock.send(self.sec.encrypt(json.dumps(data)))
            print "{} - has been sent to the client".format(data)
            return True

        except socket.SO_ERROR:
            print "Couldn't send data to the server"
            return False

    def recv(self, timeout=True):
        try:
            temp_data = self.client_sock.recv(BUFFER_SIZE)
        except socket.SO_ERROR as s_error:
            print s_error
            return

        if timeout:
            self.client_sock.settimeout(10)

        decrypted_data = self.sec.decrypt(temp_data)
        try:
            return json.loads(decrypted_data)

        except Exception as e:
            print decrypted_data
            print e
            return

    def user_handle(self):
        user_data = self.recv(False)
        print user_data

        # -- Checking if the user exists in the database -- #
        USERNAME = user_data[0]
        PASSWORD = user_data[1]

        if not self.db_conn.user_exists(USERNAME, PASSWORD):
            self.send('400 NOT FOUND')
            return self.user_handle()

        return USERNAME, PASSWORD

    def run(self):

        try:
            self.client_sock.send(self.sec.export_public_key())
            (self.sec.aes_key, self.sec.mode, self.sec.iv) = cPickle.loads(self.client_sock.recv(1024))
            self.sec.create_cipher()

        except:
            print "Unable to continue the connection with {}".format(self.client_address)
            return

        (USERNAME, PASSWORD) = self.user_handle()
        # -- ------------------------------------------- -- #

        self.db_conn.Username = USERNAME
        print self.db_conn.Username
        self.db_conn.user_id = self.db_conn.find_user_id()
        self.send('200 OK')  # If the user exists

        UUID = self.recv()[2]
        self.db_conn.computer_id = UUID

        # -- Checking if the computer's UUID exists in the database -- #

        if not self.db_conn.computer_exists():
            self.send('400 NOT FOUND')

            os_version = self.recv()[2]
            print os_version

            computer_name = self.recv()[2]
            print computer_name

            cpu_model = self.recv()[2]
            print cpu_model

            cpu_num = self.recv()[2]
            print cpu_num

            memo_total_ram = self.recv()[2]
            print memo_total_ram

            self.db_conn.add_computer(os_version, computer_name, cpu_model, cpu_num, memo_total_ram)
            print "Computer has been added"
        else:
            self.send('200 OK')
        # -- ------------------------------------------- -- #

        self.db_conn.computer_activation(True)

        while True:
            try:
                data = self.recv()
            except:
                break
            if type(data) is list:
                self.db_conn.update_query(data)

        self.db_conn.computer_activation(False)
        print "Computer is DEAD"