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)
        )
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))
Beispiel #3
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
 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))
 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))