<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
import subprocess
from flask import flash, redirect, url_for, request


def error_cmd():
    flash("Only show / traceroute / ping / whois / help commands are allowed !")
    return redirect(url_for('bird'))


def launch_cmd(final_cmd):
    try:
        results = subprocess.check_output(final_cmd, shell='True')
    except subprocess.CalledProcessError, e:
        results = e.output
    finally:
        return results


def help_cmd():
    help = """
            show protocols => show bgp session status
            show route => show received routes
            show route filtered => show received routes before filtering
            show route export AS-NAME => show advertised-routes
            show route for network all => show all AS-Path for a given network
            ping(6) ip/domain-name => ping command
            traceroute(6) ip/domain-name => traceroute command"""
    return(help)


def writelogs(final_cmd):
    now = datetime.datetime.now()
    date = now.strftime("%Y-%m-%d at %H:%M")
    ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    f = open('/var/log/birdy.log', 'a')
    log = str(date) + " : IP " + str(ip) + " was connected and enter : " \
        + "'" + str(final_cmd) + "'" + "\n"
    f.write(log)
    f.close()
<file_sep>#! /usr/bin/env python
# -*- coding:utf-8 -*-

from birdy import app
from flask import render_template, request
from functions import error_cmd, launch_cmd, help_cmd, writelogs
from forms import CommandForm

import subprocess
import re


@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

    final_cmd = "birdc show protocols"
    results = subprocess.check_output(final_cmd, shell='True')
    return render_template('home.html',
                           results=results)


@app.errorhandler(500)
def internal_error(e):
    return render_template('404.html'), 500

    final_cmd = "birdc show protocols"
    results = subprocess.check_output(final_cmd, shell='True')
    return render_template('home.html',
                           results=results)


@app.route('/', methods=['GET', 'POST'])
def bird():

    final_cmd, results = "birdc show protocols", ""
    form = CommandForm(request.form)

    if request.method == "POST" and form.validate():
        # Logs
        writelogs(form.cmd.data)

        # Forbidden chars
        if ";" not in form.cmd.data and \
           "&" not in form.cmd.data and \
           "$" not in form.cmd.data and \
           "!" not in form.cmd.data and \
           "-" not in form.cmd.data and \
           "`" not in form.cmd.data and \
           "<" not in form.cmd.data and \
           ">" not in form.cmd.data:

            # Help allowed
            if form.cmd.data.startswith('help'):
                final_cmd = "help"
                results = help_cmd()

            # Ping allowed
            elif form.cmd.data.startswith('ping'):
                final_cmd = re.sub('ping', 'ping -n -i 0.1 -c 2',
                                   form.cmd.data)
                results = launch_cmd(final_cmd)

            # Traceroute allowed
            elif form.cmd.data.startswith('traceroute'):
                final_cmd = re.sub('traceroute',
                                   'traceroute -w 2 -q 1 -m 10',
                                   form.cmd.data)
                results = launch_cmd(final_cmd)

            # Whois allowed
            elif form.cmd.data.startswith('whois'):
                final_cmd = re.sub('whois',
                                   'whois -h whois.dn42',
                                   form.cmd.data)
                results = launch_cmd(final_cmd)

            # bird show allowed
            elif form.cmd.data.startswith('show'):
                final_cmd = "birdc " + form.cmd.data
                results = launch_cmd(final_cmd)

            # final_cmd = birdc show protocols and print error message
            else:
                results = launch_cmd(final_cmd)
                error_cmd()
            form.cmd.data = ""
        else:
            results = launch_cmd(final_cmd)
            error_cmd()
    else:
        results = launch_cmd(final_cmd)
    return render_template('home.html', form=form,
                           final_cmd=final_cmd,
                           results=results)


@app.route('/ipv6', methods=['GET', 'POST'])
def bird6():

    final_cmd, results = "birdc6 show protocols", ""
    form = CommandForm(request.form)

    if request.method == "POST" and form.validate():
        # Logs
        writelogs(form.cmd.data)

        # Forbidden chars
        if ";" not in form.cmd.data and \
           "&" not in form.cmd.data and \
           "$" not in form.cmd.data and \
           "!" not in form.cmd.data and \
           "-" not in form.cmd.data and \
           "`" not in form.cmd.data and \
           "<" not in form.cmd.data and \
           ">" not in form.cmd.data:

            # Help allowed
            if form.cmd.data.startswith('help'):
                final_cmd = "help"
                results = help_cmd()

            # Ping allowed
            elif form.cmd.data.startswith('ping6'):
                final_cmd = re.sub('ping6', 'ping6 -n -i 0.1 -c 2',
                                   form.cmd.data)
                results = launch_cmd(final_cmd)

            # Traceroute allowed
            elif form.cmd.data.startswith('traceroute6'):
                final_cmd = re.sub('traceroute6',
                                   'traceroute6 -w 2 -q 1 -m 10',
                                   form.cmd.data)
                results = launch_cmd(final_cmd)

            # Whois allowed
            elif form.cmd.data.startswith('whois'):
                final_cmd = re.sub('whois',
                                   'whois -h whois.dn42',
                                   form.cmd.data)
                results = launch_cmd(final_cmd)

            # bird show allowed
            elif form.cmd.data.startswith('show'):
                final_cmd = "birdc6 " + form.cmd.data
                results = launch_cmd(final_cmd)

            # final_cmd = birdc show protocols and print error message
            else:
                results = launch_cmd(final_cmd)
                error_cmd()
            form.cmd.data = ""
        else:
            results = launch_cmd(final_cmd)
            error_cmd()
    else:
        results = launch_cmd(final_cmd)
    return render_template('home.html', form=form,
                           final_cmd=final_cmd,
                           results=results)


@app.route('/status')
def status():
    ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    return render_template('status.html', ip=str(ip))
<file_sep>{% block doc -%}
<!DOCTYPE html>
<html{% block html_attribs %}{% endblock html_attribs %}>
{%- block html %}
  <head>
    {%- block head %}
    <title>{% block title %}{% endblock title %}</title>

    {%- block metas %}
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {%- endblock metas %}

    {%- block styles %}
    <!-- Bootstrap -->
    <link rel='ICON' type='image/x-icon' href='/static/img/bsd-logo.jpg'>
    <link href="/static/css/bootstrap.css" rel="stylesheet">
    {%- endblock styles %}
    {%- endblock head %}
  </head>
  <body{% block body_attribs %}{% endblock body_attribs %}>
    {% block body -%}
    {% block navbar %}
    {%- endblock navbar %}
    {% block content -%}
    {%- endblock content %}

    {% block scripts %}
    <script src="/static/js/jquery.js"></script>
    <script src="/static/js/bootstrap.js"></script>
    {%- endblock scripts %}
    {%- endblock body %}
    
    <div id="copyright">
    <hr><p align="right" style="margin-right:20px;"><font size=0.8em><a href="https://github.com/nicolasvion/birdy-src" target="_blank">Birdy</a> on the <a href="https://dn42.us" target="_blank">DN42 Network</a> - Created by <a href="http://nicolas.vion.science/cv/cv.pdf" target="_blank">n1colas</a></font></p>
    </div>

  </body>
{%- endblock html %}
</html>
{% endblock doc -%}
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask
from flask.ext.bootstrap import Bootstrap

app = Flask(__name__)
bootstrap = Bootstrap(app)
app.config['SECRET_KEY'] = '<KEY>{9qsm:{*]6&-TP9F|s#<JPT!_g/\>;\
                            74NXK/}z>.[)P~:Lk|Jrs~h8b=x"3X*<P7^\vJ5b_FNjF'

from birdy import views
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from wtforms import Form, StringField, SubmitField, validators


class CommandForm(Form):
    cmd = StringField("Enter bird command (ex : show route) :",
                      [validators.Required()])
    submit = SubmitField('Submit')
<file_sep># birdy-src
A small looking glass for bird
