예제 #1
0
    def generate_cookie_value(self, account, agent):
        cookie_secret = config.get("auth", "cookie_secret")
        account_id = str(account.account_id)
        string = (account_id + account.password + cookie_secret + agent)
        hash = hashlib.md5(string).hexdigest()

        return account_id + "-" + hash
예제 #2
0
파일: account.py 프로젝트: gtie/VegaDNS-API
    def get_global_acl_labels(self):
        config_labels = config.get("global_record_acls",
                                   "acl_labels").strip('"')
        if len(config_labels) == 0:
            return []

        return [x.strip() for x in config_labels.split(",")]
예제 #3
0
파일: account.py 프로젝트: gtie/VegaDNS-API
    def generate_cookie_value(self, account, agent):
        cookie_secret = config.get("auth", "cookie_secret")
        account_id = str(account.account_id)
        string = (account_id + str(account.password) + cookie_secret + agent)
        hash = hashlib.md5(string.encode('utf-8')).hexdigest()

        return account_id + "-" + hash
예제 #4
0
파일: account.py 프로젝트: gtie/VegaDNS-API
    def in_global_acl_emails(self, email):
        # load emails and verify
        emails = [
            x.strip() for x in config.get("global_record_acls",
                                          "acl_emails").strip('"').split(",")
        ]
        if email in emails:
            return True

        return False
예제 #5
0
def send(to, subject, body, extra_headers=False):
    if config.get('email', 'email_method') == "sendmail":
        transport = sendmail.Sendmail()
    else:
        transport = smtp.SMTP()

    try:
        transport.send(to, subject, body, extra_headers)
    except Exception as e:
        # don't block on email issues
        logger.exception(e)
예제 #6
0
def send(to, subject, body, extra_headers=False):
    if config.get('email', 'email_method') == "sendmail":
        transport = sendmail.Sendmail()
    else:
        transport = smtp.SMTP()

    try:
        transport.send(to, subject, body, extra_headers)
    except Exception, e:
        # don't block on email issues
        logger.exception(e)
예제 #7
0
파일: token.py 프로젝트: gtie/VegaDNS-API
    def post(self):
        # FIXME - add rate limiting

        # validate request
        grant_type = request.form.get('grant_type', '')
        if grant_type == "":
            abort(400, message="invalid_request")
        if grant_type != 'client_credentials':
            abort(400, message="unsupported_grant_type")

        # validate client (apikey)
        if request.authorization is not None:
            # preferred, use basic authorization
            key = request.authorization.username
            secret = request.authorization.password
        else:
            # alternatively, look in post params
            key = request.form.get('client_id', None)
            secret = request.form.get('client_secret', None)

        if not key or not secret:
            abort(400, message="invalid_request")

        now = int(time.time())
        expire_time = int(config.get('oauth', 'token_expire_time'))

        try:
            apikey = self.get_apikey(key, secret)
        except peewee.DoesNotExist:
            abort(400, message="invalid_client")

        try:
            # look up existing token first, make sure it's good for at least
            # ten minutes
            token = self.get_token(apikey.apikey_id, now + 600)
        except peewee.DoesNotExist:
            # create one if needed
            token = OauthAccessToken()
            token.account_id = apikey.account_id.account_id
            token.apikey_id = apikey.apikey_id
            token.access_token = str(uuid.uuid4())
            token.grant_type = 'client_credentials'
            token.expires_at = now + expire_time
            try:
                token.save()
            except Exception:
                abort(500, 'unable to generate token')

        return {
            'access_token': token.access_token,
            'token_type': 'bearer',
            'expires_in': token.expires_at - now
        }
예제 #8
0
파일: token.py 프로젝트: shupp/VegaDNS-API
    def post(self):
        # FIXME - add rate limiting

        # validate request
        grant_type = request.form.get('grant_type', '')
        if grant_type == "":
            abort(400, message="invalid_request")
        if grant_type != 'client_credentials':
            abort(400, message="unsupported_grant_type")

        # validate client (apikey)
        if request.authorization is not None:
            # preferred, use basic authorization
            key = request.authorization.username
            secret = request.authorization.password
        else:
            # alternatively, look in post params
            key = request.form.get('client_id', None)
            secret = request.form.get('client_secret', None)

        if not key or not secret:
            abort(400, message="invalid_request")

        now = int(time.time())
        expire_time = int(config.get('oauth', 'token_expire_time'))

        try:
            apikey = self.get_apikey(key, secret)
        except peewee.DoesNotExist:
            abort(400, message="invalid_client")

        try:
            # look up existing token first, make sure it's good for at least
            # ten minutes
            token = self.get_token(apikey.apikey_id, now + 600)
        except peewee.DoesNotExist:
            # create one if needed
            token = OauthAccessToken()
            token.account_id = apikey.account_id.account_id
            token.apikey_id = apikey.apikey_id
            token.access_token = str(uuid.uuid4())
            token.grant_type = 'client_credentials'
            token.expires_at = now + expire_time
            try:
                token.save()
            except:
                abort(500, 'unable to generate token')

        return {
            'access_token': token.access_token,
            'token_type': 'bearer',
            'expires_in': token.expires_at - now
        }
예제 #9
0
    def post(self):
        email = request.form.get("email", None)

        if email is None:
            abort(400, message="email is required")

        if not Validate().email(email):
            abort(400, message="invalid email address")

        try:
            account = ModelAccount.get(ModelAccount.email == email)
        except peewee.DoesNotExist:
            abort(400, message="email does not exist")

        # create token
        now = round(time.time())

        token = ModelToken()
        token.account_id = account.account_id
        token.token_value = token.generateToken()
        token.date_created = now

        token.save()

        # cleanup old tokens
        oldtokens = ModelToken.delete().where(
            ModelToken.date_created < now - ModelToken.EXPIRE_IN
        )
        oldtokens.execute()

        # prep email data
        name = account.first_name + " " + account.last_name
        url = config.get(
            'ui_server', 'ui_url'
        ) + "#passwordReset?token=" + token.token_value
        data = {
            'name': name,
            'url': url,
        }
        body = vegadns.api.email.parseTemplate('password_reset_request', data)
        to = account.email
        subject = "VegaDNS Password Reset Request"

        # send email
        common = vegadns.api.email.common.Common()
        vegadns.api.email.send(to, subject, body)

        return {'status': 'ok'}
예제 #10
0
파일: common.py 프로젝트: shupp/VegaDNS-API
    def ip_authenticate(self):
        if len(request.access_route):
            ip = request.access_route[0]
        else:
            raise AuthException('No remote IP set')

        trusted = config.get('ip_auth', 'trusted_ips')
        if not trusted:
            raise AuthException('IP not authorized: ' + ip)

        trusted = "".join(trusted.split())  # remove whitespace
        trusted_list = trusted.split(',')
        try:
            ip_range = IpRangeList(*trusted_list)
        except:
            raise AuthException('Error parsing IP acl list')

        if ip not in ip_range:
            raise AuthException('IP not authorized: ' + ip)

        self.authUsed = "ip"
예제 #11
0
파일: common.py 프로젝트: gtie/VegaDNS-API
    def ip_authenticate(self):
        if len(request.access_route):
            ip = request.access_route[0]
        else:
            raise Unauthorized('No remote IP set')

        trusted = config.get('ip_auth', 'trusted_ips')
        if not trusted:
            raise Unauthorized('IP not authorized: ' + ip)

        trusted = "".join(trusted.split())  # remove whitespace
        trusted_list = trusted.split(',')
        try:
            ip_range = IPSet(trusted_list)
        except Exception:
            raise Unauthorized('Error parsing IP acl list')

        if ip not in ip_range:
            raise Unauthorized('IP not authorized: ' + ip)

        self.authUsed = "ip"
예제 #12
0
파일: db.py 프로젝트: shupp/VegaDNS-API
import logging

from vegadns.api.config import config
from peewee import MySQLDatabase

logger = logging.getLogger(__name__)


database = MySQLDatabase(
    config.get('mysql', 'database'),
    **{
        'host': config.get('mysql', 'host'),
        'password': config.get('mysql', 'password'),
        'user': config.get('mysql', 'user'),
        'ssl': {'ca': v for k, v in config.items('mysql') if k == 'ssl_ca'}
      }
)
예제 #13
0
    def send(self):
        redis_enabled = config.get(
            'update_notifications',
            'enable_redis_notifications'
        )

        if redis_enabled in ["True", "true"]:
            redis_host = config.get('update_notifications', 'redis_host')
            redis_port = config.get('update_notifications', 'redis_port')
            redis_channel = config.get('update_notifications', 'redis_channel')

            try:
                r = redis.Redis(host=redis_host, port=redis_port)
                r.publish(redis_channel, "UPDATE")
            except Exception as e:
                logger.critical(e)

        consul_enabled = config.get(
            'update_notifications',
            'enable_consul_notifications'
        )

        if consul_enabled in ["True", "true"]:
            consul_host = config.get('update_notifications', 'consul_host')
            consul_port = config.get('update_notifications', 'consul_port')
            consul_scheme = config.get('update_notifications', 'consul_scheme')
            consul_key = config.get('update_notifications', 'consul_key')
            consul_token = config.get('update_notifications', 'consul_token')
            consul_verify_ssl = config.get(
                'update_notifications', 'consul_verify_ssl'
            )

            # Make sure consul_verify_ssl is type bool
            if (consul_verify_ssl is True or
                    consul_verify_ssl in ["True", "true"]):
                consul_verify_ssl = True
            else:
                consul_verify_ssl = False

            # Make sure consul_token string or None
            if (consul_token is None or
                    len(consul_token) == 0 or
                    consul_token in ["none", "None"]):
                consul_token = None

            try:
                c = consul.Consul(
                    host=consul_host,
                    port=consul_port,
                    scheme=consul_scheme,
                    token=consul_token,
                    verify=consul_verify_ssl
                )
                c.kv.put(consul_key, str(uuid.uuid4()))
            except Exception as e:
                logger.critical(e)
예제 #14
0
파일: smtp.py 프로젝트: w796933/VegaDNS-API
    def send(self, to, subject, body, extra_headers):
        # FIXME extra_headers
        smtp_host = config.get("email", "smtp_host")
        smtp_port = config.get("email", "smtp_port")

        smtp_keyfile = None
        if len(config.get("email", "smtp_keyfile")):
            smtp_keyfile = config.get("email", "smtp_keyfile")

        smtp_certfile = None
        if len(config.get("email", "smtp_certfile")):
            smtp_certfile = config.get("email", "smtp_certfile")

        if config.get('email', 'smtp_ssl') in ["True", "true"]:
            server = smtplib.SMTP_SSL(smtp_host, smtp_port, None, smtp_keyfile,
                                      smtp_certfile)
        else:
            server = smtplib.SMTP(smtp_host, smtp_port)
            # server.set_debuglevel(logging.DEBUG)

            if config.get("email", "smtp_tls") in ["True", "true"]:
                server.starttls(smtp_keyfile, smtp_certfile)

        if config.get("email", "smtp_auth") in ["True", "true"]:
            server.login(config.get('email', 'smtp_user'),
                         config.get('email', 'smtp_password'))

        message = 'Subject: %s\n\n%s' % (subject, body)
        server.sendmail(self.get_support_email(), to, message)
        server.quit()
예제 #15
0
    def get(self, format):
        if format != 'tinydns':
            abort(400, message="invalid format: " + format)

        records = self.get_records()

        domains = {}

        for record in records:
            if record.domain_id.domain not in domains:
                domains[record.domain_id.domain] = []

            domains[record.domain_id.domain].append(record)

        organized = []
        for key, val in sorted(domains.items()):
            organized.append({'domain_name': key, 'records': val})

        locations = self.get_locations()
        prefixes = self.get_prefixes()
        locationdata = "# locations\n"

        # need to build this manually since peewee join results are limiting
        for location in locations:
            temp_list = []

            for prefix in prefixes:
                if prefix.location_id != location.location_id:
                    continue
                else:
                    if prefix.prefix_type == "ipv4":
                        temp_list.append(prefix.prefix)
                    else:
                        temp_list.append("s" +
                                         str(prefix.prefix).replace(":", ""))

            if len(temp_list) == 0:
                locationdata += "%" + location.location + "\n"
            else:
                for i in temp_list:
                    locationdata += "%" + location.location + ":" + i + "\n"

        datafile = locationdata + "\n"
        tinydns = ExportTinydnsData()
        datafile += tinydns.export_domains(organized, locations)

        generation_record_host = config.get('monitoring',
                                            'vegadns_generation_txt_record')
        if generation_record_host \
           and Validate().record_hostname(generation_record_host):

            timestamp = self.get_latest_log_timestamp()
            md5 = hashlib.md5(datafile + "\n").hexdigest()

            model = ModelRecord()
            model.type = RecordType().set('TXT')
            model.host = generation_record_host
            model.val = str(timestamp) + "-" + md5
            model.ttl = 3600

            generation_record_line = tinydns.data_line_from_model(model)

            datafile += "\n\n# VegaDNS Generation TXT Record\n"
            datafile += generation_record_line.rstrip("\n")

        response = make_response(datafile)
        response.headers['content-type'] = 'text/plain'

        return response
예제 #16
0
파일: export.py 프로젝트: shupp/VegaDNS-API
    def get(self, format):
        if format != 'tinydns':
            abort(400, message="invalid format: " + format)

        records = self.get_records()

        domains = {}

        for record in records:
            if record.domain_id.domain not in domains:
                domains[record.domain_id.domain] = []

            domains[record.domain_id.domain].append(record)

        organized = []
        for key, val in sorted(domains.items()):
            organized.append(
                {
                    'domain_name': key,
                    'records': val
                }
            )

        locations = self.get_locations()
        prefixes = self.get_prefixes()
        locationdata = "# locations\n"

        # need to build this manually since peewee join results are limiting
        for location in locations:
            temp_list = []

            for prefix in prefixes:
                if prefix.location_id != location.location_id:
                    continue
                else:
                    if prefix.prefix_type == "ipv4":
                        temp_list.append(prefix.prefix)
                    else:
                        temp_list.append(
                            "s" + str(prefix.prefix).replace(
                                ":", ""
                            )
                        )

            if len(temp_list) == 0:
                locationdata += "%" + location.location + "\n"
            else:
                for i in temp_list:
                    locationdata += "%" + location.location + ":" + i + "\n"

        datafile = locationdata + "\n"
        tinydns = ExportTinydnsData()
        datafile += tinydns.export_domains(organized, locations)

        generation_record_host = config.get(
            'monitoring',
            'vegadns_generation_txt_record'
        )
        if generation_record_host \
           and Validate().record_hostname(generation_record_host):

            timestamp = self.get_latest_log_timestamp()
            md5 = hashlib.md5(datafile + "\n").hexdigest()

            model = ModelRecord()
            model.type = RecordType().set('TXT')
            model.host = generation_record_host
            model.val = str(timestamp) + "-" + md5
            model.ttl = 3600

            generation_record_line = tinydns.data_line_from_model(model)

            datafile += "\n\n# VegaDNS Generation TXT Record\n"
            datafile += generation_record_line.rstrip("\n")

        response = make_response(datafile)
        response.headers['content-type'] = 'text/plain'

        return response
예제 #17
0
파일: db.py 프로젝트: w796933/VegaDNS-API
import logging

from vegadns.api.config import config
from peewee import MySQLDatabase

logger = logging.getLogger(__name__)

database = MySQLDatabase(
    config.get('mysql', 'database'), **{
        'host': config.get('mysql', 'host'),
        'password': config.get('mysql', 'password'),
        'user': config.get('mysql', 'user'),
        'ssl': {'ca': v
                for k, v in config.items('mysql') if k == 'ssl_ca'}
    })
예제 #18
0
    def get_support_email(self):
        support_name = config.get('email', 'support_name').strip("\"")
        support_email = config.get('email', 'support_email').strip("\"")

        return "\"" + support_name + "\" <" + support_email + ">"