Ejemplo n.º 1
0
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "h:z",
                   ["help", "zone="])
    except getopt.GetoptError:
        usage()
    
    # Default:
    zone = "lycos.com."
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
        if o in ("-z", "--zone"):
            zone = str(a)
    
        # Add a trailing dot, if we don't have one
    if not zone[len(zone) - 1] == '.':
        zone += '.'
        
    conn = route53.connect(aws_access_key_id='xxx', aws_secret_access_key='yyy',)
        
    print "Determined domain name: " + zone
    
    allZones = conn.list_hosted_zones(2000)
    for thisZone in allZones:
        if thisZone.name == zone:
           thisZone.delete(True)
           print "Deleted zone: ", zone
Ejemplo n.º 2
0
 def get_client(self, GoDaddyConfig):
     if Route53Config.aws_access_key_id == '' or Route53Config.aws_secret_access_key == '':
         print(f'{color.red}[!] Add Route53 keys to config file{color.end}')
         exit()
     return route53.connect(
         aws_access_key_id=Route53Config.aws_access_key_id,
         aws_secret_access_key=Route53Config.aws_secret_access_key)
Ejemplo n.º 3
0
def route53_connect():
    settings = get_current_registry().settings
    connect = route53.connect(
      aws_access_key_id = settings.get('aws_access_key_id', None),
      aws_secret_access_key = settings.get('aws_secret_access_key', None),
    )
    return connect
Ejemplo n.º 4
0
def route53_connect():
    settings = get_current_registry().settings
    connect = route53.connect(
        aws_access_key_id=settings.get('aws_access_key_id', None),
        aws_secret_access_key=settings.get('aws_secret_access_key', None),
    )
    return connect
Ejemplo n.º 5
0
    def push_to_route53(self,
                        profile,
                        connection=None,
                        subdomain_to_remove=None):
        """Pushes a new record to AWS route53. Removes an outdated record from AWS route53 if required."""
        if connection is None:
            connection = route53.connect(
                settings.AWS_ACCESS_KEY_ID,
                settings.AWS_SECRET_ACCESS_KEY,
            )

        for zone in connection.list_hosted_zones():
            if zone.name == f'{settings.DOMAIN}.':
                record_name = f'{profile.subdomain}.{settings.DOMAIN}.'
                records_names_set = set()

                if subdomain_to_remove:
                    for record_set in zone.record_sets:
                        records_names_set.add(record_set.name)
                        if record_set.name == f'{subdomain_to_remove}.{settings.DOMAIN}.':
                            record_set.delete()

                if record_name not in records_names_set:
                    zone.create_cname_record(
                        record_name,
                        values=[f'{settings.DOMAIN}'],
                        ttl=2800,
                    )
Ejemplo n.º 6
0
 def _get_connection(self):
     if not hasattr(self, 'conn'):
         self.conn = route53.connect(
             aws_access_key_id=self.aws_access_key_id,
             aws_secret_access_key=self.aws_secret_access_key,
         )
     return self.conn
Ejemplo n.º 7
0
def compare_domains(domains, uid, domain_output_dir):
    conn = route53.connect(aws_access_key_id=key_id, aws_secret_access_key=key_secret,)

    results = {}
    domains = handle_domains(domains)
    zones = find_host_zones(conn, domains)
    for domain in domains:
        zone = zones.get(domain)
        if zone is None:
            print 'domain zone not found: %s'%domain
            hosted_zone_id, nameservers = create_host_zone(conn, domain, uid, domain_output_dir)
            create_record_sets(hosted_zone_id, domain, domain_output_dir)
            actual_nameservers = do_nslookup(domain)
            res = compare_nameservers(nameservers, actual_nameservers)
            ret_code = 0 if res else -1
            results[domain] = dict(ret=ret_code, ns=nameservers)
            continue

        if 1:
            records = get_alias_records(zone)
            if len(records) < len(regions)*2:
                print 'records not enough(%d): %s'%(len(records), domain)
                results[domain] = dict(ret=-1, ns=['alias_records not enough'])
                continue

        route53_nameservers = zone.nameservers
        actual_nameservers = do_nslookup(domain)

        res = compare_nameservers(route53_nameservers, actual_nameservers)
        print domain, res, route53_nameservers

        ret_code = 0 if res else -1
        results[domain] = dict(ret=ret_code, ns=route53_nameservers)

    return results
Ejemplo n.º 8
0
def pointIP(url, ip):
    print "Apuntamos la maquina"
    conn = route53.connect(
        aws_access_key_id='AKIAIRXB2NBW6JBJSMRQ',
        aws_secret_access_key='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',
    )

    zone = conn.get_hosted_zone_by_id('ZPEB3E12BAWA8')
    name_to_match = url + '.'

    encontrado = False
    for record_set in zone.record_sets:
        print(record_set.name)
        if record_set.name == name_to_match:
            encontrado = True
            # De momento hago un update porque pueden existir dos urls iguales
            record_set.delete()
            print "Borrado"
            new_record, change_info = zone.create_a_record(
                name=name_to_match,
                values=[str(ip)],
            )
            break

    if not encontrado:
        print "Lo creamos"
        new_record, change_info = zone.create_a_record(
            name=name_to_match,
            values=[str(ip)],
        )
Ejemplo n.º 9
0
def _get_record_sets(zone_id, config):
    conn = route53.connect(
        aws_access_key_id=config['aws_access_key_id'],
        aws_secret_access_key=config['aws_secret_access_key'])
    try:
        zone = conn.get_hosted_zone_by_id(zone_id)
    except TypeError as type_error:
        logger.exception(type_error)
        raise UpdateDnsFailed("Unable to connect to route53")
    return zone.record_sets
Ejemplo n.º 10
0
    def get_connection(self):

        print("Connecting to AWS Route53...")
        self.conn = route53.connect(
            aws_access_key_id=self.aws_access_key_id,
            aws_secret_access_key=self.aws_secret_access_key,
        )

        ## Verify connection was successful??

        pass
Ejemplo n.º 11
0
def get_route53_connection():
    """
    All unit tests go through here for Route53Connection objects.

    :rtype: Route53Connection
    """

    return route53.connect(
        aws_access_key_id=AWS_ACCESS_KEY_ID,
        aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
    )
Ejemplo n.º 12
0
def get_route53_connection():
    """
    All unit tests go through here for Route53Connection objects.

    :rtype: Route53Connection
    """

    return route53.connect(
        aws_access_key_id=AWS_ACCESS_KEY_ID,
        aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
    )
Ejemplo n.º 13
0
def create_or_update_a_record(domain, new_ips, **kwargs):
    """
    Create or update A record for IP addresses of load
    balancer

    :param str domain: New subdomain name in existing zone
    :param list new_ips: IP addresses of load balancer
    :param dict kwargs: additional params such as aws-access-key-id and
        aws-secret-access-key for access to AWS ROUTE 53
    :return:
    """
    assert isinstance(new_ips, list)
    conn = route53.connect(
        aws_access_key_id=kwargs['aws-access-key-id'],
        aws_secret_access_key=kwargs['aws-secret-access-key'])

    for zone in conn.list_hosted_zones():
        # [:-1] without end point
        if zone.name[:-1] in domain:
            for dns_record in zone.record_sets:
                # [:-1] without end point
                if domain == dns_record.name[:-1]:
                    if set(new_ips) != set(dns_record.records):
                        dns_record.records = new_ips
                        dns_record.save()

                        logger.debug(
                            'Replace record in zone "{zone}" with '
                            'domain "{domain}" '
                            'and ip "{ips}"'.format(
                                zone=zone.name, domain=domain, ips=new_ips
                            ))
                    else:
                        logger.debug(
                            'Domain "{domain}" with '
                            'ip "{ips}" in zone "{zone}" '
                            'already exists'.format(
                                zone=zone.name, domain=domain, ips=new_ips
                            ))

                    break
            else:
                zone.create_a_record(domain, new_ips)
                logger.debug(
                    'Create new record in zone "{zone}" with '
                    '"{domain}" '
                    'and ip "{ips}"'.format(
                        zone=zone.name, domain=domain, ips=new_ips
                    ))
            break
    else:
        raise ValueError("Zone for domain {} not found. "
                         "Need to configure the zone".format(domain))
Ejemplo n.º 14
0
    def test_hmac_signing(self):
        """
        Makes sure our HMAC signing methods are matching expected output
        for a pre-determined key/value.
        """

        conn = route53.connect(
            aws_access_key_id='BLAHBLAH',
            aws_secret_access_key='wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
        )
        trans = BaseTransport(conn)
        signed = trans._hmac_sign_string('Thu, 14 Aug 2008 17:08:48 GMT')
        self.assertEquals(signed, 'PjAJ6buiV6l4WyzmmuwtKE59NJXVg5Dr3Sn4PCMZ0Yk=')
Ejemplo n.º 15
0
    def configure(self, dictionary):
        if 'access_key_id' in dictionary:
            self.aws_access_key_id = dictionary['access_key_id']
        if 'secret_access_key' in dictionary:
            self.aws_secret_access_key = dictionary['secret_access_key']
        if 'zone_id' in dictionary:
            self.zone_id = dictionary['zone_id']
            logger.debug("aws zone id = %s", self.zone_id)

        self.conn = route53.connect(
                aws_access_key_id=self.aws_access_key_id,
                aws_secret_access_key=self.aws_secret_access_key
        )
Ejemplo n.º 16
0
def retreive_aws_data():
    global ndict
    ndict = {}
    conn = route53.connect(
        aws_access_key_id='key',
        aws_secret_access_key='access_key',
    )
    for zone in conn.list_hosted_zones():
        for record_set in zone.record_sets:
            if record_set.rrset_type == 'A':
                for i in record_set.records:
                    fill_dns_dict(i, record_set.name)
    return ndict
Ejemplo n.º 17
0
    def test_hmac_signing(self):
        """
        Makes sure our HMAC signing methods are matching expected output
        for a pre-determined key/value.
        """

        conn = route53.connect(
            aws_access_key_id='BLAHBLAH',
            aws_secret_access_key='wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
        )
        trans = BaseTransport(conn)
        signed = trans._hmac_sign_string('Thu, 14 Aug 2008 17:08:48 GMT')
        self.assertEquals(signed, 'PjAJ6buiV6l4WyzmmuwtKE59NJXVg5Dr3Sn4PCMZ0Yk=')
Ejemplo n.º 18
0
def delete_hostzones(domains, domain_output_dir):
    conn = route53.connect(aws_access_key_id=key_id, aws_secret_access_key=key_secret,)

    domains = handle_domains(domains)
    zones = find_host_zones(conn, domains)
    for domain in domains:
        zone = zones.get(domain)
        if zone:
            #for rec in zone.record_sets:
            #    rec.delete()
            zone.delete(force=True)

            msg = 'delete_hostzones %s %s'%(domain, zone.id)
            write_domain_log(domain, msg, domain_output_dir)
Ejemplo n.º 19
0
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "h:f",
                   ["help", "file="])
    except getopt.GetoptError:
        usage()
    
    # Default:
    filename = "/Users/jpranevich/lycos-dns/mockup.zone"
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
        if o in ("-f", "--file"):
            filename = str(a)
    
    conn = route53.connect(aws_access_key_id='xxx', aws_secret_access_key='yyy',)
    
    zone = loadFile(filename)
    for key in zone.keys():
        for key2 in zone[key].keys():
            print key, key2, zone[key][key2]
    
    # Now, we have the data, we need to determine what domain name this is for
    # We can get that from the SOA record (Z), first field
    fqdn = zone['Z'].keys()[0]
        
    # Add a trailing dot, if we don't have one
    if not fqdn[len(fqdn) - 1] == '.':
        fqdn += '.'
        
    print "Determined domain name: " + fqdn
    
    found = False
    hostedZone = ''
    allZones = conn.list_hosted_zones(2000)
    for thisZone in allZones:
        if thisZone.name == fqdn:
            found = True
            hostedZone = thisZone
            print "Found it! ", fqdn, thisZone
            break;
      
    if not found:
        hostedZone, changeInfo = conn.create_hosted_zone(fqdn)
    
    # Handle the 'A' records
    doARecords(hostedZone, zone['+'])
        
    # Handle the 'CNAME' records
    doCNAMERecords(hostedZone, zone['C'])
Ejemplo n.º 20
0
 def __init__(self, config_file='config.yml'):
     with open(config_file, 'r') as f:
         self.config = yaml.load(f)
     self._update_env_list()
     if self.config.get('endpoint_zone', False):
         conn = route53.connect(
             aws_access_key_id=self.config.get('aws_access_key'),
             aws_secret_access_key=self.config.get('aws_secret_key')
             )
         for z in conn.list_hosted_zones():
             if z.name == self.config.get('endpoint_zone'):
                 self.endpoint_zone = conn.get_hosted_zone_by_id(z.id)
     else:
         self.endpoint_zone = False
Ejemplo n.º 21
0
def processRoute53Request():
    while True:
        if not QueueOfRouteRequests.empty():
            Lock.acquire()
            request = QueueOfRouteRequests.get()
            Lock.release()

            success = False

            while not success:
                try:
                    conn = route53.connect(
                        aws_access_key_id='AKIAIDMPG7XNEGWQ7YJA',
                        aws_secret_access_key=
                        '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',
                    )
                    VPNzone = conn.get_hosted_zone_by_id('ZPEB3E12BAWA8')

                    url = request[0]
                    ip = request[1]
                    action = request[2]

                    name_to_match = url + '.'
                    finded = False

                    for record_set in VPNzone.record_sets:
                        if record_set.name == name_to_match:
                            finded = True
                            record_set.delete()
                            if action == "ADD":
                                new_record, change_info = VPNzone.create_a_record(
                                    name=name_to_match,
                                    values=[str(ip)],
                                )
                            break

                    if not finded and action == "ADD":
                        new_record, change_info = VPNzone.create_a_record(
                            name=name_to_match,
                            values=[str(ip)],
                        )

                    success = True

                except:
                    success = False

            print "Completed Handle for {}".format(request)
Ejemplo n.º 22
0
def get_route53_zone(domain):
    route53_conn = route53.connect(
        aws_access_key_id=os.environ['AWS_ACCESS_KEY'],
        aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY'])
    route53_id = None
    fqdn = tldextract.extract(domain)
    tld = fqdn.domain + '.' + fqdn.suffix
    # fetch Route53 hosted zone
    for zone in route53_conn.list_hosted_zones():
        # remove trailing . from zone name
        if zone.name[:-1] == tld:
            route53_id = zone.id
    if route53_id is None:
        raise ValueError(
            'domain {} not found in Route53 hosted zones'.format(tld))
    # create txt record for the specified domain
    return route53_conn.get_hosted_zone_by_id(route53_id)
Ejemplo n.º 23
0
def update_route53():
    conn = route53.connect(
            aws_access_key_id=AWS_ACCESS_KEY,
            aws_secret_access_key=AWS_SECRET_KEY)

    zone = conn.get_hosted_zone_by_id(HOSTED_ZONE_ID)
    
    current_ip = current_IP()

    for record_set in zone.record_sets:
        if record_set.rrset_type == 'A':
            record_set.records = [current_ip]
            record_set.save()
            break

    with open("/tmp/last_ip_address", 'w') as last_ip:
        last_ip.write(current_ip)
Ejemplo n.º 24
0
def delete_a_record(domain, **kwargs):
    """
    Delete A record to domain

    :param domain: domain which will have been deleted
    :param dict kwargs: additional params such as email and
        token and certtoken for access to Cloudflare API
    :return: None
    """
    kwargs.pop('name')
    conn = route53.connect(
        aws_access_key_id=kwargs['aws-access-key-id'],
        aws_secret_access_key=kwargs['aws-secret-access-key'])

    for zone in conn.list_hosted_zones():
        # [:-1] without end point
        if zone.name[:-1] in domain:
            for dns_record in zone.record_sets:

                if domain == dns_record.name[:-1]:
                    dns_record.delete()
Ejemplo n.º 25
0
    def update_route53(self, host, address):
        if context.app.options.get('NO_ROUTE53_UPDATE'):
            LOG.info('skipping route53 update for %s',
                     host.name)
            return

        LOG.info('updating route53 for %s', host.name)

        amz = route53.connect(
            aws_access_key_id=host.credentials.accesskey,
            aws_secret_access_key=host.credentials.secretkey)

        try:
            zone = next(z for z in amz.list_hosted_zones()
                        if z.name == host.zone + '.')
            rs = next(r for r in zone.record_sets
                      if r.name == host.name + '.')
        except (StopIteration, TypeError):
            raise NotFound()

        rs.records = [address]
        rs.save()
Ejemplo n.º 26
0
def Update_AWS():
    #Sets your AWS credentials for connection.
    conn = route53.connect(
        aws_access_key_id=Config["aws_access_key"],
        aws_secret_access_key=Config["aws_secret_access_key"],
                            )
    #Connects to your hosted zone.
    zone = conn.get_hosted_zone_by_id(Config["hosted_zone_ID"])

    #Filters through the records in your hosted zone. 
    #The Route53 API doesn't offer an elegant way of filtering records so this is it.
    for record_set in zone.record_sets:
        print(record_set)

        #When the your record is found it get deleted 
        #And is then recreated down the line.
        if record_set.name == Config["record_name"]:
            record_set.delete()
            break
    #Your record is created with updated IP
    new_record, change_info = zone.create_a_record(
        name=Config["record_name"],
        values=[api_ip]
    )

yamlconfighandle=yaml.load(open('credentials.yml'))
baseurl= yamlconfighandle['Credentials'][0]
client_token=yamlconfighandle['Credentials'][1]
client_secret=yamlconfighandle['Credentials'][2]
access_token=yamlconfighandle['Credentials'][3]
s = requests.Session()
s.auth = EdgeGridAuth(
client_token=client_token,
client_secret=client_secret,
access_token=access_token
)
# Connecting to route 53
conn = route53.connect(
   aws_access_key_id='XXXX',
   aws_secret_access_key='XXX',
)

def creatCertEnrollment(contractid,commonname,altnames):
  #Function to create cert enrollment.
  #Extract the short contracid. Example, if contractid is ctr_G-123GHS, the shortcontractid=G-123GHS
  headers = {"content-type": "application/vnd.akamai.cps.enrollment.v7+json","Accept":"application/vnd.akamai.cps.enrollment-status.v1+json"}
  hostname="test.prasadtest.akamaidevops.com"
  data={'ra': 'lets-encrypt', 'validationType': 'dv', 'certificateType': 'san', 'networkConfiguration': {'geography': 'core', 'secureNetwork': 'enhanced-tls', 'mustHaveCiphers': 'ak-akamai-default', 'preferredCiphers': 'ak-akamai-default', 'sniOnly': True, 'quicEnabled': False, 'disallowedTlsVersions': ['TLSv1', 'TLSv1_1'], 'dnsNameSettings': {'cloneDnsNames': False, 'dnsNames': None}}, 'signatureAlgorithm': 'SHA-256', 'changeManagement': False, 'csr': {'cn': commonname, 'c': 'US', 'st': 'MA', 'l': 'Cambridge', 'o': 'Akamai', 'ou': 'IT', 'sans': altnames}, 'org': {'name': 'Akamai Technologies', 'addressLineOne': '150 Broadway', 'addressLineTwo': None, 'city': 'Cambridge', 'region': 'MA', 'postalCode': '02142', 'country': 'US', 'phone': '617-555-0111'}, 'adminContact': {'firstName': 'Test', 'lastName': 'Test', 'phone': '111-111-1111', 'email': '*****@*****.**', 'addressLineOne': '150 Broadway', 'addressLineTwo': None, 'city': 'Cambridge', 'country': 'US', 'organizationName': 'Akamai', 'postalCode': '02142', 'region': 'MA', 'title': 'Customer'}, 'techContact': {'firstName': 'Akamai', 'lastName': 'Akamai', 'phone': '111-111-1111', 'email': '*****@*****.**', 'addressLineOne': '150 Broadway', 'addressLineTwo': None, 'city': 'Cambridge', 'country': 'US', 'organizationName': 'Akamai', 'postalCode': '02142', 'region': 'MA', 'title': 'Script'}, 'enableMultiStackedCertificates': False}
  result=s.post(urljoin(baseurl,'/cps/v2/enrollments?contractId='+contractid+''), data=json.dumps(data), headers=headers)
  return result
def checkCertEnrollment(enrollmentID,changeID):
  headers = {"Accept":"application/vnd.akamai.cps.change.v2+json"}
  result=s.get(urljoin(baseurl,'/cps/v2/enrollments/'+enrollmentID+'/changes/'+changeID+''),headers=headers)
  return result
def Convert(string):
Ejemplo n.º 28
0
def _connect(access_key, secret_key):
    return route53.connect(aws_access_key_id=access_key,
                           aws_secret_access_key=secret_key)
Ejemplo n.º 29
0
argp.add_argument('-t', '--ttl', help='TTL for CNAME records', default=300)
argp.add_argument('-K', '--aws-access-key', help='AWS API access key', dest='aws_access_key')
argp.add_argument('-S', '--aws-secret-key', help='AWS API secret key', dest='aws_secret_key')
args = argp.parse_args()

if (args.aws_access_key is None) and ('AWS_ACCESS_KEY' in os.environ):
    args.aws_access_key = os.environ['AWS_ACCESS_KEY']
if (args.aws_secret_key is None) and ('AWS_SECRET_ACCESS_KEY' in os.environ):
    args.aws_secret_key = os.environ['AWS_SECRET_ACCESS_KEY']

ec2conn = boto.ec2.connect_to_region(args.region, aws_access_key_id=args.aws_access_key, aws_secret_access_key=args.aws_secret_key)
if ec2conn is None:
    log.fatal("Failed to connect to region: %s", args.region)
    sys.exit(1)

route53conn = route53.connect(aws_access_key_id=args.aws_access_key,
            aws_secret_access_key=args.aws_secret_key)
targetZone = route53conn.get_hosted_zone_by_id(args.zone_id)


def getEc2Instances():
    r = ec2conn.get_all_instances()
    instances = []
    for res in r:
        for ins in res.instances:
            instances.append(ins)
    if len(instances) == 0:
        log.fatal("Found 0 active ec2 instances within region: %s", args.region)
    log.info('Found %i instances', len(instances))
    return instances

def getRoute53Records():
Ejemplo n.º 30
0
from BaseHTTPServer import BaseHTTPRequestHandler
import urlparse
import MySQLdb
from time import sleep
from time import gmtime, strftime
import os
import subprocess
import digitalocean
import route53
import random
import threading

conn = route53.connect(
    aws_access_key_id='AKIAIRXB2NBW6JBJSMRQ',
    aws_secret_access_key='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',
)

APIToken = '82bede0e660f5872d5988a4785fa6a10aa8f55cb7e52882906ca89c1b6a2c773'
sshKeyList = [
    "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD04ZoHu9qszy61gVeggjYiR/KLdZrFOpT6qiULOj1xc4ZX6TuHLFE1WklzYjRhqukVNPRlsg3lxG8yBOxSQmAmKYQgJr2lA0JqORpRWWodDqKp7a0WKuaur6UJeTSqUUrOJq/hktUcTLlD3x5miumx1g8+QjkSi4zVe4UXenv8fnddcZJD8LxU6aNJzDmlEDw/3YjADdUhxTS6n95WfoRPD9oS96BlEIBNhsSZExtchs84CNR/g8Rp+QxchySQ/nqaJO6yHBKK/ZUFySQYwg+UfRPxWK9z8JV+VFrWVKZSJ7qiuWCnr9R4IMMLhKhpwFUuqqO57AZghQY4JyQ5XUxh root@Paula"
]
''''
0 -> USA
1 -> Germany
2 -> Singapore
3 -> UK
4 -> Amsterdam
5 -> Canada
'''
providers = ['DigitalOcean', 'vultr']
Ejemplo n.º 31
0
    myPrint(
        "No NS records found for " + victimDomain +
        "\nPlease check the domain name and try again.", "ERROR")
    exit(1)
for nameserver in nsRecords:
    targetNS.append(str(nameserver))

#strip leading and trailing spaces
for index in range(len(targetNS)):
    targetNS[index] = targetNS[index].strip()
    #strip trailing .
    targetNS[index] = targetNS[index].strip(".")

myPrint("Target NS: " + str(targetNS), "INFO")
conn = route53.connect(
    aws_access_key_id=accessKey,
    aws_secret_access_key=secretKey,
)

created_zones = []
successful_zone = []
counter = 0
try:

    while counter < 10000:
        counter = counter + 1
        myPrint("Iteration Count: " + str(counter), "INFO_WS")
        try:
            new_zone = 0
            new_zone, change_info = conn.create_hosted_zone(
                # in honor of bagipro, we love your reports, we hope you never stop researching and participating in bug bounty
                victimDomain,
Ejemplo n.º 32
0
# This script adds A records to a domain of your choice hosted on Amazon Route 53
import csv
import route53
import os

files = ['arecordimport.csv']

# Connect to AWS
conn = route53.connect(
    aws_access_key_id='YOUR_KEY_HERE',
    aws_secret_access_key='YOUR_SECRET_KEY_HERE',
)

zone = conn.get_hosted_zone_by_id('ZONE_ID_HERE')

for filename in files:
    filepath = os.path.join('C:\\PATH_TO_CSV_HERE', filename)
    print(filepath)
    with open(filepath) as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            name = row['fqdn']
            value = row['ip']
            print('Adding url: ' + name)
            print('Binding to: ' + value)


            change_info = zone.create_a_record(
                # Must be FQDN
                name=name,
                # A list of IP address entries, in the case fo an A record.
Ejemplo n.º 33
0
    def save_txt_record(self, hostname: str, data: list, commit=True):
        ''' commit host changes to zone '''
        newvalues = [f'"{x}"' for x in data if x.strip() > '']

        if not self.rr_conn:
            logger.debug(f'Open credentialed connection to route53.')
            self.rr_conn = route53.connect(
                aws_access_key_id=self.site.aws_access_key_id,
                aws_secret_access_key=self.site.aws_secret_access_key)
            pass

        if not self.rr_zone:
            logger.debug(f'open zone {self.site.route53}.')
            try:
                self.rr_zone = self.rr_conn.get_hosted_zone_by_id(
                    self.site.route53)
            except:
                logger.error(f'Failed to load zone: {self.site.route53}.')
                raise
            pass

        if not len(self.rr_recs):
            logger.debug(f'search records for domain {self.site.domain}.')
            for x in self.rr_zone.record_sets:
                if x.rrset_type == 'TXT' and x.name.find(
                        self.site.domain) > -1:
                    logger.trace(f'located record: {x.name}')
                    self.rr_recs.append(x)
                    continue
                continue
            pass

        record = None
        for x in self.rr_recs:
            if x.name == hostname or f'{hostname}.' == x.name:
                record = x
                break
            continue

        if record:
            logger.trace(
                f'Update: replace{CR}    {record.records}{CR}with:{CR}    {newvalues}'
            )
            if record.records == newvalues:
                logger.debug(f'No update needed {hostname}')
                pass
            record.records = newvalues
            if commit:
                record.save()
            else:
                logger.warning(
                    f'Would have saved changes: {hostname} // {newvalues}.')
                pass
        else:
            logger.debug(f'create new host record')
            if commit:
                self.rr_zone.create_txt_record(hostname, newvalues)
            else:
                logger.error(
                    f'Would have committed: {hostname} // {newvalues}')
                pass
            pass

        return True
Ejemplo n.º 34
0
import route53

### include . after the domain name!
hosted_zone_name = 'www.aoroute53.com.'

running_instances = [('18.188.87.216', 'us-east-2'),
                     ('184.169.192.17', 'us-west-1')]
#print "ip addr: ", instance[0]
#print "region: ", instance[1]

####################################
## enter AWS API credentials
####################################
connection = route53.connect(
    aws_access_key_id='AKIAJLI2ZIBDVQVY43CA',
    aws_secret_access_key='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',
)

#########################################
## list all hosted zones in AWS/Route 53
#########################################

for zone in connection.list_hosted_zones():
    # You can then do various things to the zone.
    print(zone.name)

###########################################################
## create a record set for the hosted zone
###########################################################
## ip addr1 = 18.188.87.216 Ohio region
## ip addr2 = 184.169.192.17 N.Cal region
Ejemplo n.º 35
0
# This script lists the domains and corrisponding zone IDs
import route53

#Login To AWS
conn = route53.connect(
    aws_access_key_id='YOUR ACCESS KEY HERE',
    aws_secret_access_key='YOUR SECRET KEY HERE',
)

for zone in conn.list_hosted_zones():
    print('Domain Name:' + " " + zone.name)
    print('Zone ID:' + " " + zone.id)
    print('\n')
Ejemplo n.º 36
0
#!/usr/bin/env python

import route53,sys

def fill_dns(ipaddr, hostname):
    if ndict.has_key(ipaddr) and hostname not in ndict[ipaddr]:
            ndict[ipaddr].append(hostname)
    else:
        ndict[ipaddr] = [hostname, ]
    return

conn = route53.connect(
    aws_access_key_id='key',
    aws_secret_access_key='access_key',
)

ndict = {}

for zone in conn.list_hosted_zones():
    for record_set in zone.record_sets:
        if record_set.rrset_type == 'A':
            for i in record_set.records:
                fill_dns(i, record_set.name)

print(ndict)

Ejemplo n.º 37
0
 def __init__(self, zone):
     access_id = os.getenv('AWS_ACCESS_KEY_ID')
     secret_key = os.getenv('AWS_SECRET_ACCESS_KEY')
     self.client = route53.connect(access_id, secret_key)
     self.zone = None
     self.set_zone(zone)
Ejemplo n.º 38
0
 def connectRoute53(self):
     self.r53 = route53.connect(
         aws_access_key_id=self.config.AWSAccessKeyId,
         aws_secret_access_key=self.config.AWSSecretAccessKey
         )
Ejemplo n.º 39
0
def get_conn():
    return route53.connect(aws_access_key_id=key_id, aws_secret_access_key=key_secret,)
Ejemplo n.º 40
0
# parse command-line arguments
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
parser.add_argument("-n", type=str, help="fqdn, eg: host.domain.com.", default=default_hostname)
parser.add_argument("-i", type=str, help="ip address", default=default_ip)
parser.add_argument("-t", type=int, help="ttl value", default=300)
parser.add_argument("-z", type=str, help="zone id", default=default_zone)
group.add_argument("-l", "--list", action="store_true", help="list current records")
group.add_argument("-c", "--create", action="store_true", help="create new record")
group.add_argument("-g", "--change", action="store_true", help="change record ip")
group.add_argument("-d", "--delete", action="store_true", help="CAUTION: delete record; specify '-n fqdn' to delete")
args = parser.parse_args()

# initialize connection to aws
conn = route53.connect(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)

def list_records():
    # list hosted zones & record sets
    print("listing current records")
    for zone in conn.list_hosted_zones():
        print(zone.name)
        for record_set in zone.record_sets:
            print(record_set)

def create_record(zone_id, name, ip, ttl):
    # create new record set
    zone = conn.get_hosted_zone_by_id(zone_id)
    print("creating new record in zone: ", zone.name, name)
    try:
        new_record, change_info = zone.create_a_record(name=name,values=[ip],ttl=ttl)
Ejemplo n.º 41
0
def connect():
        return route53.connect(
                aws_access_key_id=key_id,
                aws_secret_access_key=access_key
        )
Ejemplo n.º 42
0
#!/usr/local/bin/python3

import sys
import route53

if __name__ == "__main__":
    if len(sys.argv) == 1:
        print("Usage: " + sys.argv[0] + " <aws_hosted_zone_id> ...")
        sys.exit(1)

    conn = route53.connect(aws_access_key_id='<SOME_ACCESS_KEY>',
                           aws_secret_access_key='<THE_SECRET>')

    match_id = ''.join(sys.argv[1:])
    zone = conn.get_hosted_zone_by_id(match_id)
    print("# Imports for: " + match_id)
    print("")
    print("terraform import aws_route53_zone." +
          zone.name.replace(".", "_")[:-1] + " " + match_id)

    num_records = 0
    for record_set in zone.record_sets:
        num_records += 1
        tf_record_name = record_set.name.replace(".", "_")[:-1]
        print("terraform import aws_route53_record." + tf_record_name + " " +
              match_id + "_" + record_set.name[:-1] + "_" +
              record_set.rrset_type)

    print("# Num Records: " + str(num_records))
Ejemplo n.º 43
0
def _connect(access_key, secret_key):
    return route53.connect(aws_access_key_id=access_key, aws_secret_access_key=secret_key)
Ejemplo n.º 44
0
 def __init__(self, zone):
     access_id = os.getenv('AWS_ACCESS_KEY_ID')
     secret_key = os.getenv('AWS_SECRET_ACCESS_KEY')
     self.client = route53.connect(access_id, secret_key)
     self.zone = None
     self.set_zone(zone)