#!/usr/bin/env python # -*- coding: utf-8 -*- """API client to core-networks""" import requests import os import json import urlparse import configparser import sys import logging import tldextract def setup_logger(): # seup logging logger = logging.getLogger("certbot_dns_corenetworks") logging.basicConfig(level=logging.INFO) # silence logging from requests module logging.getLogger('requests').setLevel(logging.CRITICAL) # create console handler ch = logging.StreamHandler() ch.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s- %(levelname)s - %(message)s') ch.setFormatter(formatter) # add handler to logger logger.addHandler(ch) logger.propagate = False return logger def load_config(logger): try: config_path = os.path.join( os.path.expanduser("~"), ".certbot_dns_corenetworks", "config.ini") config = configparser.ConfigParser() config.read(config_path) data = {} data["API_HOST"] = config['API']['HOST'] data["API_USER"] = config['API']['USER'] data["PASSWORD"] = config['API']['PASSWORD'] data["ZONE"] = config['DNS']['ZONE'] except KeyError, e: logger.error("Key %s not found in config" % (e)) sys.exit(1) return data def get_auth_token(user, passwd, host, logger): data = {} data["login"] = user data["password"] = passwd json_data = json.dumps(data) url = urlparse.urljoin(host, os.path.join("auth", "token")) try: r = requests.post(url, data=json_data) r.raise_for_status() except requests.exceptions.HTTPError, e: logger.error(e) sys.exit(1) return r def get_zone(token, host, zone, logger): url = urlparse.urljoin(host, os.path.join("dnszones", zone)) headers = {"Authorization": "Bearer %s" % (token)} try: r = requests.get(url, headers=headers) r.raise_for_status() except requests.exceptions.HTTPError, e: logger.error(e) sys.exit(1) return r def set_record(token, host, zone, logger): url = urlparse.urljoin(host, os.path.join("dnszones", zone, "records/")) headers = {"Authorization": "Bearer %s" % (token)} try: custom_cache_extract = tldextract.TLDExtract( cache_file=os.path.join(os.path.expanduser("~"), "tld_set")) subdomain = custom_cache_extract(os.environ['CERTBOT_DOMAIN']).subdomain if subdomain: certbot_domain = "_acme-challenge.%s" % (subdomain) else: certbot_domain = "_acme-challenge" certbot_validation = os.environ['CERTBOT_VALIDATION'] except KeyError, e: logger.error("Environment Variable %s not set" % (e)) sys.exit(1) data = {} data["name"] = certbot_domain data["ttl"] = 120 data["type"] = "TXT" data["data"] = certbot_validation json_data = json.dumps(data) try: r = requests.post(url, headers=headers, data=json_data) r.raise_for_status() except requests.exceptions.HTTPError, e: logger.error(e) sys.exit(1) return r def main(): """Main logic entrypoint""" logger = setup_logger() config = load_config(logger) # get auth token logger.info("Try to get auth token") r_token = get_auth_token(config["API_USER"], config["PASSWORD"], config["API_HOST"], logger) auth_token = r_token.json()["token"] logger.info("Authentication successful") # verify dns zone r_zone = get_zone(auth_token, config["API_HOST"], config["ZONE"], logger) zone_name = r_zone.json()["name"] zone_active = r_zone.json()["active"] if zone_active: logger.info("Zone '%s' verified (active)" % (zone_name)) else: logger.error("Zone '%s' verified (not active)" % (zone_name)) sys.exit(1) # add txt record z_record = set_record(auth_token, config["API_HOST"], zone_name, logger) if __name__ == "__main__": main()