Commit b921f24d authored by Zenon Mousmoulas's avatar Zenon Mousmoulas

Import servdata consumer script and templates to

contrib/extras.
parent 4b9b1628
## -*- coding: utf-8 -*-
<%!
import re
%>\
% for inst in insts:
% if inst['type'] in (2, 3) and 'clients' in inst:
#{{{${' ' + inst['id'] if 'id' in inst else ''}
% for client in inst['clients']:
client ${client} {
secret = ${hosts[client]['secret']}
<%
ipaddr = re.split(r'/(?=[0-9]{1,2}$)', hosts[client]['host'])
%>\
ipaddr = ${ipaddr[0]}
% if len(ipaddr) > 1:
netmask = ${ipaddr[1]}
% endif
nastype = other
% if 'id' in inst:
grnetopname = 1${inst['id']}
% endif
eduroamspco = GR
}
% endfor
#}}}
% endif
% endfor
## -*- coding: utf-8 -*-
<%!
import re
def realm_disarm(text):
return re.sub(r'\*\.', r'_wildcard_.', text)
def realm_regex(text):
if text.find('*.') == 0:
text = re.sub(r'\.', r'\\\\.', text)
text = re.sub(r'\*(?=\\\\\.)', r'.+', text)
return '"~%s$"' % text
else:
return text
def wildcard_realm_least_precedence(a, b):
if a.find('*.') == 0 and b.find('*.') != 0:
return -1
elif b.find('*.') == 0 and a.find('*.') != 0:
return 1
else:
return 0
%>\
% for inst in insts:
% if inst['type'] in (1, 3) and 'realms' in inst:
#{{{${' ' + inst['id'] if 'id' in inst else ''}
<%doc>
The following one-liner does the equivalent of:
inst_servers = set()
for r in inst['realms']:
if 'proxy_to' in inst['realms'][r]:
inst_servers.update(inst['realms'][r]['proxy_to'])
for srv in inst_servers:
</%doc>\
% for srv in set([s for r in inst['realms'] for s in inst['realms'][r]['proxy_to'] if 'proxy_to' in inst['realms'][r]]):
home_server ${srv} {
type = ${hosts[srv]['rad_pkt_type']}
ipaddr = ${hosts[srv]['host']}
port = ${hosts[srv]['auth_port'] if hosts[srv]['rad_pkt_type'] in ('auth', 'auth+acct') else hosts[srv]['acct_port']}
secret = ${hosts[srv]['secret']}
response_window = 20
zombie_period = 40
revive_interval = 120
status_check = ${'status-server' if hosts[srv]['status_server'] else 'request'}
% if not hosts[srv]['status_server']:
username = "eduroam-status_check"
password = "eduroam-status_check"
% endif
check_interval = 30
num_answers_to_alive = 3
}
% endfor
% for realm in sorted([r for r in inst['realms'] if 'proxy_to' in inst['realms'][r]], cmp=wildcard_realm_least_precedence, reverse=True):
home_server_pool ${realm | realm_disarm} {
type = fail-over
% for srv in inst['realms'][realm]['proxy_to']:
home_server = ${srv}
% endfor
}
realm ${realm | realm_regex} {
pool = ${realm | realm_disarm}
nostrip
}
% endfor
#}}}
% endif
% endfor
## -*- coding: utf-8 -*-
<%!
import re
def realm_regex(text):
if text.find('*.') == 0:
text = re.sub(r'\.', r'\\.', text)
text = re.sub(r'\*(?=\\.)', r'.+', text)
return '"/@%s$"' % text
else:
return text
def wildcard_realm_least_precedence(a, b):
if a.find('*.') == 0 and b.find('*.') != 0:
return -1
elif b.find('*.') == 0 and a.find('*.') != 0:
return 1
else:
return 0
%>\
% for inst in insts:
% if True in [c in inst for c in ['clients', 'realms']]:
#{{{${' ' + inst['id'] if 'id' in inst else ''}
% if inst['type'] in (2, 3) and 'clients' in inst:
% for client in inst['clients']:
rewrite rewrite-${client}-sp {
include /etc/radsecproxy.conf.d/rewrite-default-sp.conf
% if 'id' in inst:
addAttribute 126:1${inst['id']}
% endif
}
client ${client} {
host ${clients[client]['host']}
IPv4Only on
type udp
secret ${clients[client]['secret']}
fticksVISCOUNTRY GR
% if 'id' in inst:
fticksVISINST 1${inst['id']}
% endif
rewriteIn rewrite-${client}-sp
}
% endfor
% endif
% if inst['type'] in (1, 3) and 'realms' in inst:
<%doc>
The following one-liner does the equivalent of:
inst_servers = set()
for r in inst['realms']:
if 'proxy_to' in inst['realms'][r]:
inst_servers.update(inst['realms'][r]['proxy_to'])
for srv in inst_servers:
</%doc>\
% for srv in set([s for r in inst['realms'] for s in inst['realms'][r]['proxy_to'] if 'proxy_to' in inst['realms'][r]]):
rewrite rewrite-${srv}-idp {
include /etc/radsecproxy.conf.d/rewrite-default-idp.conf
}
server ${srv}${'-acct' if servers[srv]['rad_pkt_type'] == 'acct' else ''} {
host ${servers[srv]['host']}
IPv4Only on
type udp
port ${servers[srv]['auth_port'] if servers[srv]['rad_pkt_type'] in ('auth', 'auth+acct') else servers[srv]['acct_port']}
secret ${servers[srv]['secret']}
% if servers[srv]['status_server'] and servers[srv]['rad_pkt_type'] in ('auth', 'auth+acct'):
StatusServer on
% endif
rewriteIn rewrite-${srv}-idp
}
% if servers[srv]['rad_pkt_type'] == 'auth+acct':
server ${srv}-acct {
host ${servers[srv]['host']}
IPv4Only on
type udp
port ${servers[srv]['acct_port']}
secret ${servers[srv]['secret']}
% if servers[srv]['status_server']:
#StatusServer on
% endif
rewriteIn rewrite-${srv}-idp
}
% endif
% endfor
% for realm in sorted([r for r in inst['realms'] if 'proxy_to' in inst['realms'][r]], cmp=wildcard_realm_least_precedence, reverse=True):
realm ${realm | realm_regex} {
% for srv in inst['realms'][realm]['proxy_to']:
% if servers[srv]['rad_pkt_type'] in ('auth', 'auth+acct'):
server ${srv}
% endif
% if servers[srv]['rad_pkt_type'] in ('acct', 'auth+acct'):
accountingserver ${srv}-acct
% endif
% endfor
}
% endfor
% endif
#}}}
% endif
% endfor
#!/usr/bin/env python
# -*- coding: utf-8 -*- vim:encoding=utf-8:
# vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab
import sys, os
import re
from optparse import OptionParser, OptionValueError, OptionGroup
from yaml import load
try:
from yaml import \
CLoader as Loader
except ImportError:
from yaml import Loader
import requests
from mako.template import Template
from mako.lookup import TemplateLookup
def exit_with_error(msg = ""):
sys.stderr.write(msg + "\n")
sys.exit(1)
class ServerDataReader:
def __init__(self, src):
self.src = src
if re.match(r"^https?://", self.src) is not None:
try:
resp = requests.get(src)
except ConnectionError:
exit_with_error("Connection failed for %s" % src)
if resp.status_code > 304 or not resp.ok:
exit_with_error("Fetch failed from %s" % src)
self.rawdata = resp.text
else:
try:
with open(src, "r") as f:
self.rawdata = f.read()
except EnvironmentError:
exit_with_error("Read from %s failed" % src)
if not len(self.rawdata) > 0:
exit_with_error("Read 0 length data, ignoring")
self.data = load(self.rawdata)
if not isinstance(self.data, dict) or \
False in [i in self.data for i in ['clients',
'servers',
'institutions']
]:
exit_with_error("Read unexpected data")
def get_data(self, category):
if not category in self.data:
exit_with_error("'%s' data not found" % category)
return self.data[category]
class ServerDataWriter:
def __init__(self, *args, **kwargs):
self.tplccdir = kwargs['tplccdir'] if 'tplccdir' in kwargs else None
self.tpldirs = kwargs['tpldirs'] if 'tpldirs' in kwargs else [os.curdir]
if 'tpls' not in kwargs or not isinstance(kwargs['tpls'], dict):
exit_with_error("Output templates not defined")
tpls_dict = {a: kwargs['tpls'][a] if a in kwargs['tpls'] and \
isinstance(kwargs['tpls'][a], dict) else {} \
for a in ['files', 'parmap']}
self.tpls = type(
self.__class__.__name__ + \
".Templates",
(object,),
tpls_dict
)
tplookup_kwargs = {
"directories": self.tpldirs,
"output_encoding": 'utf-8',
"encoding_errors": 'replace',
"strict_undefined": True
}
if self.tplccdir:
tplookup_kwargs["module_directory"] = self.tplccdir
self.tplookup = TemplateLookup(**tplookup_kwargs)
def render_tpl(self, tpl):
if tpl not in self.tpls.files:
exit_with_error("Template file not specified for template %s" % tpl)
elif not self.tplookup.has_template(self.tpls.files[tpl]):
exit_with_error("Template file not found: %s" % self.tpls.files[tpl])
t = self.tplookup.get_template(self.tpls.files[tpl])
return t.render(**self.tpls.parmap[tpl])
def main():
sr = ServerDataReader('https://www.eduroam.gr/static/admins/serv_data')
tpls = { 'files': {},
'parmap': {} }
t = 'freeradius-clients'
tpls['files'][t] = "%s.tpl" % t
tpls['parmap'][t] = {
"insts": sr.get_data('institutions'),
"hosts": sr.get_data('clients')
}
t = 'freeradius-proxy'
tpls['files'][t] = "%s.tpl" % t
tpls['parmap'][t] = {
"insts": sr.get_data('institutions'),
"hosts": sr.get_data('servers')
}
t = 'radsecproxy'
tpls['files'][t] = "%s.tpl" % t
tpls['parmap'][t] = {
"insts": sr.get_data('institutions'),
"clients": sr.get_data('clients'),
"servers": sr.get_data('servers')
}
sw = ServerDataWriter(tplccdir="/tmp",
tpldirs=["/home/zmousm"],
tpls=tpls)
print sw.render_tpl('radsecproxy')
if __name__ == "__main__":
main()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment