Exemplo n.º 1
0
    def public_download(self, shareId, **kwargs):
        user = None
        message, publicShare, config = None, None, cherrypy.request.app.config['filelocker']
        orgConfig = get_config_dict_from_objects(session.query(ConfigParameter).filter(ConfigParameter.name.like('org_%')).all())
        cherrypy.response.timeout = 36000
        shareId = strip_tags(shareId)

        try:
            publicShare = session.query(PublicShare).filter(PublicShare.id==shareId).one()
            if cherrypy.session.has_key("public_share_id") == False or cherrypy.session.get("public_share_id") != publicShare.id:
                password = kwargs['password'] if kwargs.has_key("password") else None
                if publicShare.password == None or (password is not None and Encryption.compare_password_hash(password, publicShare.password)):
                    cherrypy.session['public_share_id'] = publicShare.id
                elif password == None:
                    message = "This file share is password protected."
                    publicShare = None
                elif password is not None and Encryption.compare_password_hash(password, publicShare.password) == False:
                    message = "Invalid password"
                    publicShare = None
                else:
                    publicShare = None
        except sqlalchemy.orm.exc.NoResultFound:
            message = "Invalid Share ID"
            shareId = None
        except Exception, e:
            message = "Unable to access download page: %s " % str(e)
Exemplo n.º 2
0
def encrypt_message(message):
    config = cherrypy.request.app.config["filelocker"]
    try:
        message.encryption_key = Encryption.generatePassword()
        f = open(os.path.join(config["vault"], "m%s" % str(message.id)), "wb")
        encrypter, salt = Encryption.new_encrypter(message.encryption_key)
        padding, endOfFile = (0, False)
        newFile = StringIO.StringIO(message.body)
        f.write(salt)
        data = newFile.read(1024 * 8)
        # If File is only one block long, handle it here
        if len(data) < (1024 * 8):
            padding = 16 - (len(data) % 16)
            if padding == 16:
                paddingByte = "%X" % 0
            else:
                paddingByte = "%X" % padding
            for i in range(padding):
                data += paddingByte
            f.write(encrypter.encrypt(data))
        else:
            while 1:
                if endOfFile:
                    break
                else:
                    next_data = newFile.read(1024 * 8)
                    # this only happens if we are at the end, meaning the next block is the last
                    # so we have to handle the padding by aggregating the two blocks and determining pad
                    if len(next_data) < (1024 * 8):
                        data += next_data
                        padding = 16 - (len(data) % 16)
                        if padding == 16:
                            paddingByte = "%X" % 0
                        else:
                            paddingByte = "%X" % padding
                        for i in range(padding):
                            data += paddingByte
                        endOfFile = True
                f.write(encrypter.encrypt(data))
                data = next_data
        newFile.close()
        f.close()
    except IOError, ioe:
        cherrypy.log.error(
            "[%s] [encrypt_message] [There was an IOError while checking in new file: %s]"
            % (message.owner_id, str(ioe))
        )
        raise Exception(
            "There was an IO error while uploading: %s. The administrator has been notified of this error." % str(ioe)
        )
Exemplo n.º 3
0
def encrypt_message(message):
    config = cherrypy.request.app.config['filelocker']
    try:
        message.encryption_key = Encryption.generatePassword()
        f = open(os.path.join(config['vault'], "m%s" % str(message.id)), "wb")
        encrypter, salt = Encryption.new_encrypter(message.encryption_key)
        padding, endOfFile = (0, False)
        newFile = StringIO.StringIO(message.body)
        f.write(salt)
        data = newFile.read(1024 * 8)
        #If File is only one block long, handle it here
        if len(data) < (1024 * 8):
            padding = 16 - (len(data) % 16)
            if padding == 16:
                paddingByte = "%X" % 0
            else:
                paddingByte = "%X" % padding
            for i in range(padding):
                data += paddingByte
            f.write(encrypter.encrypt(data))
        else:
            while 1:
                if endOfFile: break
                else:
                    next_data = newFile.read(1024 * 8)
                    #this only happens if we are at the end, meaning the next block is the last
                    #so we have to handle the padding by aggregating the two blocks and determining pad
                    if len(next_data) < (1024 * 8):
                        data += next_data
                        padding = 16 - (len(data) % 16)
                        if padding == 16: paddingByte = "%X" % 0
                        else: paddingByte = "%X" % padding
                        for i in range(padding):
                            data += paddingByte
                        endOfFile = True
                f.write(encrypter.encrypt(data))
                data = next_data
        newFile.close()
        f.close()
    except IOError, ioe:
        cherrypy.log.error(
            "[%s] [encrypt_message] [There was an IOError while checking in new file: %s]"
            % (message.owner_id, str(ioe)))
        raise Exception(
            "There was an IO error while uploading: %s. The administrator has been notified of this error."
            % str(ioe))
Exemplo n.º 4
0
    def public_download(self, shareId, **kwargs):
        user = None
        message, publicShare, config = None, None, cherrypy.request.app.config[
            'filelocker']
        orgConfig = get_config_dict_from_objects(
            session.query(ConfigParameter).filter(
                ConfigParameter.name.like('org_%')).all())
        cherrypy.response.timeout = 36000
        shareId = strip_tags(shareId)

        try:
            publicShare = session.query(PublicShare).filter(
                PublicShare.id == shareId).one()
            if cherrypy.session.has_key(
                    "public_share_id") == False or cherrypy.session.get(
                        "public_share_id") != publicShare.id:
                password = kwargs['password'] if kwargs.has_key(
                    "password") else None
                if publicShare.password == None or (
                        password is not None
                        and Encryption.compare_password_hash(
                            password, publicShare.password)):
                    cherrypy.session['public_share_id'] = publicShare.id
                elif password == None:
                    message = "This file share is password protected."
                    publicShare = None
                elif password is not None and Encryption.compare_password_hash(
                        password, publicShare.password) == False:
                    message = "Invalid password"
                    publicShare = None
                else:
                    publicShare = None
        except sqlalchemy.orm.exc.NoResultFound:
            message = "Invalid Share ID"
            shareId = None
        except Exception, e:
            message = "Unable to access download page: %s " % str(e)
Exemplo n.º 5
0
    def getfileinfo(self, filename):

        if not os.path.exists(filename):
            return False

        file_name = os.path.basename(filename)
        file_md5 = Encryption.fileEncry(filename)
        file_size = os.path.getsize(filename)

        file_dict = {
            'filename': file_name,
            'filemd5': file_md5,
            'filesize': file_size
        }
        return file_dict
Exemplo n.º 6
0
def decrypt_message(message):
    config = cherrypy.request.app.config['filelocker']
    messageBody = ""
    try:
        path = os.path.join(config['vault'], "m" + str(message.id))
        bodyfile = open(path, 'rb')
        salt = bodyfile.read(16)
        decrypter = Encryption.new_decrypter(message.encryption_key, salt)
        endOfFile = False
        readData = bodyfile.read(1024 * 8)
        data = decrypter.decrypt(readData)
        #If the data is less than one block long, just process it and send it out
        if len(data) < (1024 * 8):
            padding = int(str(data[-1:]), 16)

            #A 0 represents that the file had a multiple of 16 bytes, and 16 bytes of padding were added
            if padding == 0:
                padding = 16
            endOfFile = True
            messageBody += data[:len(data) - padding]
        else:
            #For multiblock files
            while True:
                if endOfFile:
                    break
                next_data = decrypter.decrypt(bodyfile.read(1024 * 8))
                if (next_data is not None and
                        next_data != "") and not len(next_data) < (1024 * 8):
                    yData = data
                    data = next_data
                    messageBody += yData
                #This prevents padding going across block boundaries by aggregating the last two blocks and processing
                #as a whole if the next block is less than a full block (signifying end of file)
                else:
                    data = data + next_data
                    padding = int(str(data[-1:]), 16)
                    #A 0 represents that the file had a multiple of 16 bytes, and 16 bytes of padding were added
                    if padding == 0:
                        padding = 16
                    endOfFile = True
                    messageBody += data[:len(data) - padding]
        return messageBody
    except Exception, e:
        raise Exception("Couldn't decrypt message body: %s" % str(e))
Exemplo n.º 7
0
def decrypt_message(message):
    config = cherrypy.request.app.config["filelocker"]
    messageBody = ""
    try:
        path = os.path.join(config["vault"], "m" + str(message.id))
        bodyfile = open(path, "rb")
        salt = bodyfile.read(16)
        decrypter = Encryption.new_decrypter(message.encryption_key, salt)
        endOfFile = False
        readData = bodyfile.read(1024 * 8)
        data = decrypter.decrypt(readData)
        # If the data is less than one block long, just process it and send it out
        if len(data) < (1024 * 8):
            padding = int(str(data[-1:]), 16)

            # A 0 represents that the file had a multiple of 16 bytes, and 16 bytes of padding were added
            if padding == 0:
                padding = 16
            endOfFile = True
            messageBody += data[: len(data) - padding]
        else:
            # For multiblock files
            while True:
                if endOfFile:
                    break
                next_data = decrypter.decrypt(bodyfile.read(1024 * 8))
                if (next_data is not None and next_data != "") and not len(next_data) < (1024 * 8):
                    yData = data
                    data = next_data
                    messageBody += yData
                # This prevents padding going across block boundaries by aggregating the last two blocks and processing
                # as a whole if the next block is less than a full block (signifying end of file)
                else:
                    data = data + next_data
                    padding = int(str(data[-1:]), 16)
                    # A 0 represents that the file had a multiple of 16 bytes, and 16 bytes of padding were added
                    if padding == 0:
                        padding = 16
                    endOfFile = True
                    messageBody += data[: len(data) - padding]
        return messageBody
    except Exception, e:
        raise Exception("Couldn't decrypt message body: %s" % str(e))
Exemplo n.º 8
0
                     500, "Invalid password"
                 ) if format == "content_only" else cherrypy.HTTPRedirect(
                     config['root_url'] +
                     '/upload_request?requestId=%s&msg=3' % requestId)
             requestOwner = session.query(User).filter(
                 User.id == uploadRequest.owner_id).one()
         except cherrypy.HTTPError, httpe:
             raise httpe
         except cherrypy.HTTPRedirect, httpr:
             raise httpr
         except Exception, e:
             messages.append(str(e))
     elif password is not None and password != "":  # if they do have a password and requestId, try to load the whole upload ticket
         uploadRequest = session.query(UploadRequest).filter(
             UploadRequest.id == requestId).one()
         if Encryption.compare_password_hash(password,
                                             uploadRequest.password):
             cherrypy.session['uploadRequest'] = uploadRequest.get_copy(
             )
             requestOwner = session.query(User).filter(
                 User.id == uploadRequest.owner_id).one()
         else:
             uploadRequest = None
             raise cherrypy.HTTPError(
                 500, "Invalid password"
             ) if format == "content_only" else cherrypy.HTTPRedirect(
                 config['root_url'] +
                 '/upload_request?requestId=%s&msg=3' % requestId)
 elif cherrypy.session.has_key("uploadRequest"):
     uploadRequest = cherrypy.session.get("uploadRequest")
     requestOwner = session.query(User).filter(
         User.id == uploadRequest.owner_id).one()
Exemplo n.º 9
0
            ext = ""
            i = flFile.name.rfind('.')
            if i != -1:
                ext = flFile.name[i:].lower()
            content_type = mimetypes.types_map.get(ext, "text/plain")
        response.headers['Content-Type'] = content_type
        if disposition is not None:
            cd = '%s; filename="%s"' % (disposition, flFile.name)
            response.headers["Content-Disposition"] = cd

        # Set Content-Length and use an iterable (file object)
        #   this way CP won't load the whole file in memory
        c_len = st.st_size
        bodyfile = open(path, 'rb')
        salt = bodyfile.read(16)
        decrypter = Encryption.new_decrypter(flFile.encryption_key, salt)
        try:
            response.body = self.enc_file_generator(user, decrypter, bodyfile,
                                                    flFile.id, publicShareId)
            return response.body
        except cherrypy.HTTPError, he:
            raise he

    def enc_file_generator(self,
                           user,
                           decrypter,
                           dFile,
                           fileId=None,
                           publicShareId=None):
        endOfFile = False
        readData = dFile.read(1024 * 8)
Exemplo n.º 10
0
# [ Abdu_Almisrati ]
# [ fb/r00tly ]
# [ Coded By Almisrati ]
# [ 4/27/2020 - Time 6:02 PM ]
# [ Encryption ]
# [ It's Working on Python 3.7 ]
#________________________


from lib.Encryption import *


En = Encryption()

while True:

    choices = input("\033[1;36m  > Enter The Encryption Number Here : \033[0m")

 
    try:
        
        choices = int(choices)
        if choices == 1:
            En.MD5()
        elif choices == 2:
            En.SHA1()
        elif choices == 3:
            En.SHA224()
        elif choices == 4:
            En.SHA256()
        elif choices == 5:
Exemplo n.º 11
0
        fileCommand = session.query(ConfigParameter).filter(ConfigParameter.name=="file_command").one().value
        fileres = os.popen("%s %s" % (fileCommand, filePath), "r")
        data = fileres.read().strip()
        fileres.close()
        if data.find(";") >= 0:
            (ftype, lo) = data.split(";")
            del(lo)
            flFile.type = ftype.strip()
        else:
            flFile.type = data.strip()
    except Exception, e:
        cherrypy.log.error("[%s] [checkInFile] [Unable to determine file type: %s]" % (user.id, str(e)))

    #Logic is a little strange here - if the user supplied an encryptionKey, then don't save it with the file
    encryptionKey = None
    flFile.encryption_key = Encryption.generatePassword()
    encryptionKey = flFile.encryption_key
    os.umask(077)
    newFile = open(filePath, "rb")
    f = open(os.path.join(config['vault'], str(flFile.id)), "wb")
    encrypter, salt = Encryption.new_encrypter(encryptionKey)
    padding, endOfFile = (0, False)
    f.write(salt)
    data = newFile.read(1024*8)
    #If File is only one block long, handle it here
    if len(data) < (1024*8):
        padding = 16-(len(data)%16)
        if padding == 16:
            paddingByte = "%X" % 0
        else:
            paddingByte = "%X" % padding
Exemplo n.º 12
0
                    if uploadRequest.password == None and uploadRequest.type == "single":
                        cherrypy.session['uploadRequest'] = uploadRequest.get_copy()
                    else:
                        messages.append("This upload request requires a password before you can upload files")
                        uploadRequest = None
                        raise cherrypy.HTTPError(500, "Invalid password") if format == "content_only" else cherrypy.HTTPRedirect(config['root_url']+'/upload_request?requestId=%s&msg=3' % requestId)
                    requestOwner = session.query(User).filter(User.id == uploadRequest.owner_id).one()
                except cherrypy.HTTPError, httpe:
                    raise httpe
                except cherrypy.HTTPRedirect, httpr:
                    raise httpr
                except Exception, e:
                    messages.append(str(e))
            elif password is not None and password!="": # if they do have a password and requestId, try to load the whole upload ticket
                uploadRequest = session.query(UploadRequest).filter(UploadRequest.id == requestId).one()
                if Encryption.compare_password_hash(password, uploadRequest.password):
                    cherrypy.session['uploadRequest'] = uploadRequest.get_copy()
                    requestOwner = session.query(User).filter(User.id == uploadRequest.owner_id).one()
                else:
                    uploadRequest = None
                    raise cherrypy.HTTPError(500, "Invalid password") if format == "content_only" else cherrypy.HTTPRedirect(config['root_url']+'/upload_request?requestId=%s&msg=3' % requestId)
        elif cherrypy.session.has_key("uploadRequest"):
            uploadRequest = cherrypy.session.get("uploadRequest")
            requestOwner = session.query(User).filter(User.id == uploadRequest.owner_id).one()
        else:
            raise cherrypy.HTTPError(500, "Unable to load upload request") if format == "content_only" else cherrypy.HTTPRedirect("%s/upload_request?msg=1" % (config['root_url']))

        if uploadRequest is not None:
            fileList = session.query(File).filter(File.upload_request_id==uploadRequest.id).all()
            for flFile in fileList:
                flFile.documentType = "document"
Exemplo n.º 13
0
 def create_message(self, subject, body, recipientIds, expiration, format="json", requestOrigin="", **kwargs):
     user, sMessages, fMessages = cherrypy.session.get("user"), [], []
     if requestOrigin != cherrypy.session["request-origin"]:
         fMessages.append("Missing request key!!")
     else:
         try:
             maxDays = int(
                 session.query(ConfigParameter).filter(ConfigParameter.name == "max_file_life_days").one().value
             )
             maxExpiration = datetime.datetime.today() + datetime.timedelta(days=maxDays)
             expiration = (
                 datetime.datetime(*time.strptime(strip_tags(expiration), "%m/%d/%Y")[0:5])
                 if (
                     kwargs.has_key("expiration")
                     and strip_tags(expiration) is not None
                     and expiration.lower() != "never"
                 )
                 else maxExpiration
             )
             recipientIdList = split_list_sanitized(recipientIds)
             subject = strip_tags(subject)
             if subject is None or subject.strip() == "":
                 raise Exception("Subject cannot be blank")
             # Process the expiration data for the file
             if expiration is None and (
                 AccountService.user_has_permission(user, "expiration_exempt") == False
                 and AccountService.user_has_permission(user, "admin") == False
             ):  # Check permission before allowing a non-expiring upload
                 expiration = maxExpiration
             else:
                 if (
                     maxExpiration < expiration
                     and AccountService.user_has_permission(user, "expiration_exempt") == False
                 ):
                     raise Exception(
                         "Expiration date must be between now and %s." % maxExpiration.strftime("%m/%d/%Y")
                     )
             if body is None or body.strip() == "":
                 raise Exception("Message body cannot be blank")
             newMessage = Message(
                 subject=subject,
                 body=body,
                 date_sent=datetime.datetime.now(),
                 owner_id=user.id,
                 date_expires=expiration,
                 encryption_key=Encryption.generatePassword(),
             )
             session.add(newMessage)
             session.commit()
             encrypt_message(newMessage)
             for recipientId in recipientIdList:
                 rUser = AccountService.get_user(recipientId)
                 if rUser is not None:
                     newMessage.message_shares.append(MessageShare(message_id=newMessage.id, recipient_id=rUser.id))
                     session.add(
                         AuditLog(
                             user.id,
                             "Send Message",
                             '%s sent a message with subject: "%s" to %s(%s)'
                             % (user.id, newMessage.subject, rUser.display_name, rUser.id),
                             rUser.id,
                             None,
                         )
                     )
                 else:
                     fMessages.append("Could not send to user with ID:%s - Invalid user ID" % str(recipientId))
             session.commit()
             sMessages.append('Message "%s" sent.' % subject)
         except ValueError:
             fMessages.append("Invalid expiration date format. Date must be in mm/dd/yyyy format.")
         except Exception, e:
             cherrypy.log.error("[%s] [create_message] [Could not create message: %s]" % (user.id, str(e)))
             fMessages.append("Could not send message: %s" % str(e))
Exemplo n.º 14
0
            ext = ""
            i = flFile.name.rfind('.')
            if i != -1:
                ext = flFile.name[i:].lower()
            content_type = mimetypes.types_map.get(ext, "text/plain")
        response.headers['Content-Type'] = content_type
        if disposition is not None:
            cd = '%s; filename="%s"' % (disposition, flFile.name)
            response.headers["Content-Disposition"] = cd

        # Set Content-Length and use an iterable (file object)
        #   this way CP won't load the whole file in memory
        c_len = st.st_size
        bodyfile = open(path, 'rb')
        salt = bodyfile.read(16)
        decrypter = Encryption.new_decrypter(flFile.encryption_key, salt)
        try:
            response.body = self.enc_file_generator(user, decrypter, bodyfile, flFile.id, publicShareId)
            return response.body
        except cherrypy.HTTPError, he:
            raise he

    def enc_file_generator(self, user, decrypter, dFile, fileId=None, publicShareId=None):
        endOfFile = False
        readData = dFile.read(1024*8)
        data = decrypter.decrypt(readData)
        #If the data is less than one block long, just process it and send it out
        #try:
        if len(data) < (1024*8):
            padding = int(str(data[-1:]),16)
            #A 0 represents that the file had a multiple of 16 bytes, and 16 bytes of padding were added
Exemplo n.º 15
0
 def create_message(self,
                    subject,
                    body,
                    recipientIds,
                    expiration,
                    format="json",
                    requestOrigin="",
                    **kwargs):
     user, sMessages, fMessages = cherrypy.session.get("user"), [], []
     if requestOrigin != cherrypy.session['request-origin']:
         fMessages.append("Missing request key!!")
     else:
         try:
             maxDays = int(
                 session.query(ConfigParameter).filter(
                     ConfigParameter.name ==
                     'max_file_life_days').one().value)
             maxExpiration = datetime.datetime.today() + datetime.timedelta(
                 days=maxDays)
             expiration = datetime.datetime(
                 *time.strptime(strip_tags(expiration), "%m/%d/%Y")[0:5]
             ) if (kwargs.has_key('expiration')
                   and strip_tags(expiration) is not None
                   and expiration.lower() != "never") else maxExpiration
             recipientIdList = split_list_sanitized(recipientIds)
             subject = strip_tags(subject)
             if subject is None or subject.strip() == "":
                 raise Exception("Subject cannot be blank")
             #Process the expiration data for the file
             if expiration is None and (
                     AccountService.user_has_permission(
                         user, "expiration_exempt") == False
                     and AccountService.user_has_permission(
                         user, "admin") == False
             ):  #Check permission before allowing a non-expiring upload
                 expiration = maxExpiration
             else:
                 if maxExpiration < expiration and AccountService.user_has_permission(
                         user, "expiration_exempt") == False:
                     raise Exception(
                         "Expiration date must be between now and %s." %
                         maxExpiration.strftime("%m/%d/%Y"))
             if body is None or body.strip() == "":
                 raise Exception("Message body cannot be blank")
             newMessage = Message(
                 subject=subject,
                 body=body,
                 date_sent=datetime.datetime.now(),
                 owner_id=user.id,
                 date_expires=expiration,
                 encryption_key=Encryption.generatePassword())
             session.add(newMessage)
             session.commit()
             encrypt_message(newMessage)
             for recipientId in recipientIdList:
                 rUser = AccountService.get_user(recipientId)
                 if rUser is not None:
                     newMessage.message_shares.append(
                         MessageShare(message_id=newMessage.id,
                                      recipient_id=rUser.id))
                     session.add(
                         AuditLog(
                             user.id, "Send Message",
                             "%s sent a message with subject: \"%s\" to %s(%s)"
                             % (user.id, newMessage.subject,
                                rUser.display_name, rUser.id), rUser.id,
                             None))
                 else:
                     fMessages.append(
                         "Could not send to user with ID:%s - Invalid user ID"
                         % str(recipientId))
             session.commit()
             sMessages.append("Message \"%s\" sent." % subject)
         except ValueError:
             fMessages.append(
                 "Invalid expiration date format. Date must be in mm/dd/yyyy format."
             )
         except Exception, e:
             cherrypy.log.error(
                 "[%s] [create_message] [Could not create message: %s]" %
                 (user.id, str(e)))
             fMessages.append("Could not send message: %s" % str(e))
Exemplo n.º 16
0
import sys
from os.path import abspath, dirname
sys.path.insert(0, abspath(dirname(dirname(__file__))))
import getpass
from lib import FTPServerClass
from lib import UserCheck
from lib import Encryption

if __name__ == '__main__':

    print('-------> Run FTP Server <---------')
    while True:
        username = input('Username:'******'Password:'******'Password:'******'FTPserver'),
                                           config_dic.get('FTPport'))
            print('启动FTP Server服务,开始等待链接')
            ftp.run()
        else:
            user_input = input('账号或者密码错误,是否请重试 (y/n): ')
            if user_input == 'y' or user_input == 'Y':
                continue
            else:
                print('Bye Bye')
                break