Beispiel #1
0
def slugify(value, substitutions=()):
    '''
    Normalizes string, converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.

    Took from Django sources.
    '''
    # TODO Maybe steal again from current Django 1.5dev
    value = Markup(value).striptags()
    # value must be unicode per se
    import unicodedata
    from unidecode import unidecode
    # unidecode returns str in Py2 and 3, so in Py2 we have to make
    # it unicode again
    value = unidecode(value)
    if isinstance(value, six.binary_type):
        value = value.decode('ascii')
    # still unicode
    value = unicodedata.normalize('NFKD', value).lower()
    for src, dst in substitutions:
        value = value.replace(src.lower(), dst.lower())
    value = re.sub('[^\w\s-]', '', value).strip()
    value = re.sub('[-\s]+', '-', value)
    # we want only ASCII chars
    value = value.encode('ascii', 'ignore')
    # but Pelican should generally use only unicode
    return value.decode('ascii')
Beispiel #2
0
def render():
    arg = ''
    if request.method == 'GET':
        arg = request.args.get('query', '')
        arg = fix(arg)
        arg = Markup(arg.encode('utf-8'))
        r = make_response(render_template('webpage.html', arg = arg))
        r.headers.set("X-XSS-Protection", "0")
        return r
Beispiel #3
0
def render():
    arg = ''
    if request.method == 'GET':
        arg = request.args.get('query', '')
        arg = Markup(arg.encode("utf-8"))
        r = make_response(render_template('webpage-csp-3.html', arg=arg))
        r.headers.set("X-XSS-Protection", "0")
        r.headers[
            'Content-Security-Policy'] = "script-src 'nonce-RiJpMcQWKQRLTKaMPjOajw'"
        return r
Beispiel #4
0
def render():
    arg = ''
    if request.method == 'GET':
        arg = request.args.get('query', '')
        arg = Markup(arg.encode("utf-8"))
        r = make_response(render_template('webpage-csp.html', arg=arg))
        r.headers.set("X-XSS-Protection", "0")
        r.headers[
            'Content-Security-Policy'] = "script-src 'self' http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"
        return r
Beispiel #5
0
def main(args):
	if len(args) == 0:
		print "You need to enter a search term."
		return
	s = ""
	for arg in args:
		s+=arg
	s = s.replace(" ", "+")
	s = s.replace("'", r"")
	response = urllib2.urlopen("https://twitter.com/search?q=" + s + "&src=typd")
	page_source = response.read()
	soup = BeautifulSoup(page_source)
	links = soup.find_all("a", "details with-icn js-details")
	username = soup.find_all("span", "username js-action-profile-name")
	tweets = soup.find_all("p", "js-tweet-text")
	if len(tweets) == 0:
		print "No results."
		return
	tweet = Markup(tweets[0]).striptags()
	username = Markup(username[0]).striptags()
	link = links[0].get('href')
	link = "https://twitter.com" + link
	print username.encode("ascii", "ignore") + ": " + tweet.encode("ascii", "ignore") + " (" + link.encode("ascii", "ignore") + ")";
Beispiel #6
0
def display_content(filter,sort,start,requrl):
	content = "<table border='1px'><tr><th>Date</th><th>Type</th><th>Log</th><th>StackTrace</th></tr>";
	for log in list(collection.find(filter).skip(int(start)).limit(MAX_ROWS).sort('Date', -1 if sort == Desc else 1)):
		content += "<tr class='%s'><td>%s</td><td>%s</td><td>%s</td><td>%s</td>" % ( log['Type'],log['Date'], log['Type'],Markup.escape(log['log']), "-" if not log.has_key('stacktrace') else "<input type='button' value='stacktrace' onclick=\"alert('"+Markup.encode(' '.join(log['stacktrace'].strip().split('\n')))+"');\" />");
	content += "</table>";
	return html(content,sort,start,requrl);
Beispiel #7
0
    def pre_create(self):
        id = is_mongokit_objectid(self.params.get("alert_id"))
        if id:
            alert = dboperation.read("AlertRules", {"_id": id}, True)
            if alert:
                notifications = alert.get("notification", [])
                if notifications:
                    for notification in notifications:
                        if notification.get("type") == "newtestemail":
                            notifications.remove(notification)
                            break
                if self.params.get("notify_newtestemail") == "on":
                    email_template = textual.utf8(
                        self.params.get('email_template'))
                    try:
                        template = Template(email_template)
                    except TemplateSyntaxError:
                        return ((0, 800), {})

                    email_emails = self.params.get('email_emails')

                    if email_emails:
                        email_emails = json.loads(email_emails)
                        email_pattern = re.compile(
                            r"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)*$"
                        )
                        invalid_emails = []
                        for email in email_emails:
                            if not bool(email_pattern.match(email)):
                                invalid_emails.append(email)

                        if invalid_emails:
                            return ((0, 801), {
                                "errors": {
                                    "invalid_emails": invalid_emails
                                }
                            })
                    else:
                        return ((0, 801), {})

                    email_threshold_option = self.params.get(
                        "email_threshold_option")
                    email_threshold_value = self.params.get(
                        "email_threshold_value")
                    if email_threshold_value:
                        email_threshold_value = int(email_threshold_value)
                    template_file = ""
                    if email_template:
                        disk.prepare_path(ALERT_TEMPLATES_PATH)
                        user_id = dboperation.read(
                            "User", {'username': self.user.get_user_name()},
                            True)
                        template_file = 'alert_%s_%s.tmp' % (str(
                            user_id['_id']), base64.b32encode(alert["name"]))
                        template_file_path = os.path.join(
                            ALERT_TEMPLATES_PATH, template_file)
                        email_template = Markup(
                            email_template.decode('utf-8')).unescape()
                        with open(template_file_path, 'w') as f:
                            email_template = email_template.encode('utf-8')
                            format_template = re.sub(
                                '\|\s*(readable|date|time|datetime)\s*}}',
                                self._regex_replacer, email_template)
                            f.write(format_template)
                    else:
                        email_template = "<br>"
                        disk.prepare_path(ALERT_TEMPLATES_PATH)
                        template_file = 'alert_%s_%s.tmp' % (
                            self.user.get_user_name().encode(
                                'ascii', 'ignore'), base64.b32encode(name))
                        template_file_path = os.path.join(
                            ALERT_TEMPLATES_PATH, template_file)
                        email_template = Markup(
                            email_template.decode('utf-8')).unescape()
                        with open(template_file_path, 'w') as f:
                            email_template = email_template.encode('utf-8')
                            format_template = re.sub(
                                '\|\s*(readable|date|time|datetime)\s*}}',
                                self._regex_replacer, email_template)
                            f.write(format_template)

                    notifications.append({'template_file':template_file,'type':'newtestemail', 'notify_newtestemail':True, 'email_emails':email_emails,\
                                          'email_template':email_template, 'threshold':email_threshold_value, 'threshold_option':email_threshold_option})

                return {"notification": notifications}
def padlock():
    # Remove files stored in uploads
    clear_files()

    if request.method == "POST":
        timeTaken = 0
        outputText = ""
        outputFilepath = ""
        outputFilename = ""
        failed = ""

        process = request.form["processInput"]
        dataFormat = request.form["dataFormatInput"]
        cipher = request.form["cipherInput"]
        cipherMode = request.form["cipherModeInput"]
        inputArea = request.form["inputArea"]
        fileUploaded = request.files["fileInput"]

        if cipher == "Triple DES Cipher":
            key1 = request.form["keyInput"]
            key2 = request.form["keyInput2"]
            key3 = request.form["keyInput3"]

            key = (key1, key2, key3)
        else:
            key = request.form["keyInput"]


        if process == "encrypt":
            if dataFormat == "Messages":
                try:
                    outputText, timeTaken = multicrypt.encrypt(plaintext=inputArea, passKey=key, cipher=cipher,
                            dataformat=dataFormat, cipherMode=cipherMode)
                except Exception as e:
                    outputText = "ERROR: Encryption failed!"
                    failed = "failed"
                    print(e)

            elif dataFormat == "Files":
                filename = secure_filename(fileUploaded.filename)
                # Save the file in the upload folder
                fileUploaded.save(os.path.join(app.config['UPLOAD_PATH'], filename))
                try:
                    outputFilepath, timeTaken = multicrypt.encrypt(filename=filename,
                        filepath=UPLOAD_PATH, passKey=key, cipher=cipher,
                            dataformat=dataFormat, cipherMode=cipherMode)

                    # Remove path from output file and return just the filename
                    outputFilename = os.path.basename(outputFilepath)
                    outputText = Markup("File encryption successful!<br>Filename: " + outputFilename)
                except Exception as e:
                    outputText = "ERROR: File encryption failed!"
                    failed = "failed"
                    print(e)

            elif dataFormat == "Images":
                filename = secure_filename(fileUploaded.filename)
                # Save the file in the upload folder
                fileUploaded.save(os.path.join(app.config['UPLOAD_PATH'], filename))
                try:
                    outputFilepath, timeTaken = multicrypt.encrypt(filename=filename,
                        filepath=UPLOAD_PATH, passKey=key, cipher=cipher,
                            dataformat=dataFormat)

                    # Remove path from output file and return just the filename
                    outputFilename = os.path.basename(outputFilepath)
                    outputText = Markup("Image encryption successful!<br>Filename: " + outputFilename)
                except Exception as e:
                    outputText = "ERROR: Image encryption failed!"
                    failed = "failed"
                    print(e)
        else:
            """
            Decryption
            """
            if dataFormat == "Messages":
                try:
                    outputText, timeTaken = multicrypt.decrypt(ciphertext=inputArea, passKey=key, cipher=cipher,
                            dataformat=dataFormat, cipherMode=cipherMode)
                except Exception as e:
                    outputText = "ERROR: Decryption failed!"
                    failed = "failed"
                    print(e)

            elif dataFormat == "Files":
                filename = secure_filename(fileUploaded.filename)
                # Save the file in the upload folder
                fileUploaded.save(os.path.join(app.config['UPLOAD_PATH'], filename))
                try:
                    outputFilepath, timeTaken = multicrypt.decrypt(filename=filename,
                        filepath=UPLOAD_PATH, passKey=key, cipher=cipher,
                            dataformat=dataFormat, cipherMode=cipherMode)

                    # Remove path from output file and return just the filename
                    outputFilename = os.path.basename(outputFilepath)
                    outputText = Markup("File decryption successful!<br>Filename: " + outputFilename)
                except Exception as e:
                    outputText = "ERROR: File decryption failed!"
                    failed = "failed"
                    print(e)

            elif dataFormat == "Images":
                filename = secure_filename(fileUploaded.filename)
                # Save the file in the upload folder
                fileUploaded.save(os.path.join(app.config['UPLOAD_PATH'], filename))
                try:
                    outputFilepath, timeTaken = multicrypt.decrypt(filename=filename,
                        filepath=UPLOAD_PATH, passKey=key, cipher=cipher,
                            dataformat=dataFormat)

                    # Remove path from output file and return just the filename
                    outputFilename = os.path.basename(outputFilepath)
                    outputText = Markup("Image decryption successful!<br>Filename: " + outputFilename)
                except Exception as e:
                    outputText = "ERROR: Image decryption failed!"
                    failed = "failed"
                    print(e)

        # Format time is it is not 0
        if timeTaken != 0:
            timeTakenString = "Time taken: " + time.strftime('%M:%S', time.gmtime(timeTaken))
        else:
            timeTakenString = ""

        # If the filepath is defined, then add a random integer to the end
        # This will prevent caching in the browser for multiple encryption/decryptions
        if outputFilepath:
            outputFilepath += "?temp=" + str(random.randint(1, 1000))

        # Remove non-ascii characters usually found when decrypting
        outputText.encode("ascii", errors="ignore")

        return render_template("padlock.html", inputText=inputArea,
            outputText=outputText, failed=failed, timeTakenString=timeTakenString,
            dataFormatInput=dataFormat, cipherInput=cipher, cipherModeInput=cipherMode,
            outputFilepath=outputFilepath, outputFilename=outputFilename)

    # Initial template when site is started up
    return render_template("padlock.html", dataFormatInput="Messages",
        cipherInput="Caesar Cipher", cipherModeInput="Classic")