1 #! /usr/bin/env python3
3 # This file is part of secnet.
4 # See README for full list of copyright holders.
6 # secnet is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # secnet is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # version 3 along with secnet; if not, see
18 # https://www.gnu.org/licenses/gpl.html.
20 """VPN sites file manipulation.
22 This program enables VPN site descriptions to be submitted for
23 inclusion in a central database, and allows the resulting database to
24 be turned into a secnet configuration file.
26 A database file can be turned into a secnet configuration file simply:
27 make-secnet-sites.py [infile [outfile]]
29 It would be wise to run secnet with the "--just-check-config" option
30 before installing the output on a live system.
32 The program expects to be invoked via userv to manage the database; it
33 relies on the USERV_USER and USERV_GROUP environment variables. The
34 command line arguments for this invocation are:
36 make-secnet-sites.py -u header-filename groupfiles-directory output-file \
39 All but the last argument are expected to be set by userv; the 'group'
40 argument is provided by the user. A suitable userv configuration file
46 cd ~/secnet/sites-test/
47 execute ~/secnet/make-secnet-sites.py -u vpnheader groupfiles sites
49 This program is part of secnet.
53 from __future__ import print_function
54 from __future__ import unicode_literals
55 from builtins import int
68 # entry 0 is "near the executable", or maybe from PYTHONPATH=.,
69 # which we don't want to preempt
70 sys.path.insert(1,"/usr/local/share/secnet")
71 sys.path.insert(1,"/usr/share/secnet")
75 from argparseactionnoyes import ActionNoYes
79 from sys import version_info
80 if version_info.major == 2: # for python2
82 sys.stdin = codecs.getreader('utf-8')(sys.stdin)
83 sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
85 open=lambda f,m='r': io.open(f,m,encoding='utf-8')
87 max={'rsa_bits':8200,'name':33,'dh_bits':8200}
91 print(repr(args), file=sys.stderr)
93 def base91s_encode(bindata):
94 return base91.encode(bindata).replace('"',"-")
96 def base91s_decode(string):
97 return base91.decode(string.replace("-",'"'))
100 def __init__(self,s,tline=None,tfile=None):
103 self._line=line if tline is None else tline
104 self._file=file if tfile is None else tfile
109 return not self.__eq__(e)
111 raise RuntimeError('direct use of Tainted value')
113 return 'Tainted(%s)' % repr(self._s)
115 def _bad(self,what,why):
116 assert(self._ok is not True)
118 complain('bad parameter: %s: %s' % (what, why))
121 def _max_ok(self,what,maxlen):
122 if len(self._s) > maxlen:
123 return self._bad(what,'too long (max %d)' % maxlen)
126 def _re_ok(self,bad,what,maxlen=None):
127 if maxlen is None: maxlen=max[what]
128 self._max_ok(what,maxlen)
129 if self._ok is False: return False
130 if bad.search(self._s):
131 #print(repr(self), file=sys.stderr)
132 return self._bad(what,'bad syntax')
135 def _rtnval(self, is_ok, ifgood, ifbad=''):
137 assert(self._ok is not False)
141 assert(self._ok is not True)
145 def _rtn(self, is_ok, ifbad=''):
146 return self._rtnval(is_ok, self._s, ifbad)
150 def raw_mark_ok(self):
151 # caller promises to throw if syntax was dangeorus
152 return self._rtn(True)
155 if self._ok is False: return ''
156 if self._ok is True: return self._s
157 print('%s:%d: unchecked/unknown additional data "%s"' %
158 (self._file,self._line,self._s),
162 bad_name=re.compile(r'^[^a-zA-Z]|[^-_0-9a-zA-Z]')
163 # secnet accepts _ at start of names, but we reserve that
165 def name(self,what='name'):
166 ok=self._re_ok(Tainted.bad_name,what)
168 '_line%d_%s' % (self._line, id(self)))
171 ok=self._s in keywords or self._s in levels
173 complain('unknown keyword %s' % self._s)
176 bad_hex=re.compile(r'[^0-9a-fA-F]')
177 def bignum_16(self,kind,what):
178 maxlen=(max[kind+'_bits']+3)/4
179 ok=self._re_ok(Tainted.bad_hex,what,maxlen)
182 bad_num=re.compile(r'[^0-9]')
183 def bignum_10(self,kind,what):
184 maxlen=math.ceil(max[kind+'_bits'] / math.log10(2))
185 ok=self._re_ok(Tainted.bad_num,what,maxlen)
188 def number(self,minn,maxx,what='number'):
190 ok=self._re_ok(Tainted.bad_num,what,10)
194 ok=self._bad(what,'out of range %d..%d'
196 return self._rtnval(ok,v,minn)
198 def hexid(self,byteslen,what):
199 ok=self._re_ok(Tainted.bad_hex,what,byteslen*2)
201 if len(self._s) < byteslen*2:
202 ok=self._bad(what,'too short')
203 return self._rtn(ok,ifbad='00'*byteslen)
205 bad_host=re.compile(r'[^-\][_.:0-9a-zA-Z]')
206 # We permit _ so we can refer to special non-host domains
207 # which have A and AAAA RRs. This is a crude check and we may
208 # still produce config files with syntactically invalid
209 # domains or addresses, but that is OK.
211 ok=self._re_ok(Tainted.bad_host,'host/address',255)
214 bad_email=re.compile(r'[^-._0-9a-z@!$%^&*=+~/]')
215 # ^ This does not accept all valid email addresses. That's
216 # not really possible with this input syntax. It accepts
217 # all ones that don't require quoting anywhere in email
218 # protocols (and also accepts some invalid ones).
220 ok=self._re_ok(Tainted.bad_email,'email address',1023)
223 bad_groupname=re.compile(r'^[^_A-Za-z]|[^-+_0-9A-Za-z]')
225 ok=self._re_ok(Tainted.bad_groupname,'group name',64)
228 bad_base91=re.compile(r'[^!-~]|[\'\"\\]')
229 def base91(self,what='base91'):
230 ok=self._re_ok(Tainted.bad_base91,what,4096)
247 ap = argparse.ArgumentParser(description='process secnet sites files')
248 ap.add_argument('--userv', '-u', action='store_true',
249 help='userv service fragment update mode')
250 ap.add_argument('--conf-key-prefix', action=ActionNoYes,
252 help='prefix conf file key names derived from sites data')
253 ap.add_argument('--prefix', '-P', nargs=1,
255 ap.add_argument('--debug', '-D', action='count', default=0)
256 ap.add_argument('arg',nargs=argparse.REMAINDER)
258 debug_level = av.debug
260 service = 1 if av.userv else 0
261 prefix = '' if av.prefix is None else av.prefix[0]
262 key_prefix = av.conf_key_prefix
265 print("Wrong number of arguments")
267 (header, groupfiledir, sitesfile, group) = av.arg
268 group = Tainted(group,0,'command line')
269 # untrusted argument from caller
270 if "USERV_USER" not in os.environ:
271 print("Environment variable USERV_USER not found")
273 user=os.environ["USERV_USER"]
274 # Check that group is in USERV_GROUP
275 if "USERV_GROUP" not in os.environ:
276 print("Environment variable USERV_GROUP not found")
278 ugs=os.environ["USERV_GROUP"]
280 for i in ugs.split():
283 print("caller not in group %s"%group)
287 print("Too many arguments")
289 (inputfile, outputfile) = (av.arg + [None]*2)[0:2]
293 # Classes describing possible datatypes in the configuration file
296 "Common protocol for configuration types."
298 complain("%s %s already has property %s defined"%
299 (obj.type,obj.name,w[0].raw()))
302 "A list of some kind of configuration type."
303 def __init__(self,subtype,w):
305 self.list=[subtype(w)]
307 self.list.append(self.subtype(w))
309 return ', '.join(map(str, self.list))
311 return lambda w: conflist(subtype, w)
313 class single_ipaddr (basetype):
315 def __init__(self,w):
316 self.addr=ipaddress.ip_address(w[1].raw_mark_ok())
318 return '"%s"'%self.addr
320 class networks (basetype):
321 "A set of IP addresses specified as a list of networks"
322 def __init__(self,w):
323 self.set=ipaddrset.IPAddressSet()
325 x=ipaddress.ip_network(i.raw_mark_ok(),strict=True)
328 return ",".join(map((lambda n: '"%s"'%n), self.set.networks()))
330 class dhgroup (basetype):
331 "A Diffie-Hellman group"
332 def __init__(self,w):
333 self.mod=w[1].bignum_16('dh','dh mod')
334 self.gen=w[2].bignum_16('dh','dh gen')
336 return 'diffie-hellman("%s","%s")'%(self.mod,self.gen)
338 class hash (basetype):
339 "A choice of hash function"
340 def __init__(self,w):
343 if (self.ht!='md5' and self.ht!='sha1'):
344 complain("unknown hash type %s"%(self.ht))
349 return '%s'%(self.ht)
351 class email (basetype):
353 def __init__(self,w):
354 self.addr=w[1].email()
356 return '<%s>'%(self.addr)
358 class boolean (basetype):
360 def __init__(self,w):
362 if re.match('[TtYy1]',v.raw()):
365 elif re.match('[FfNn0]',v.raw()):
369 complain("invalid boolean value");
371 return ['False','True'][self.b]
373 class num (basetype):
375 def __init__(self,w):
376 self.n=w[1].number(0,0x7fffffff)
380 class address (basetype):
381 "A DNS name and UDP port number"
382 def __init__(self,w):
384 self.port=w[2].number(1,65536,'port')
386 return '"%s"; port %d'%(self.adr,self.port)
388 class rsakey (basetype):
390 def __init__(self,w):
391 self.l=w[1].number(0,max['rsa_bits'],'rsa len')
392 self.e=w[2].bignum_10('rsa','rsa e')
393 self.n=w[3].bignum_10('rsa','rsa n')
394 if len(w) >= 5: w[4].email()
396 return 'rsa-public("%s","%s")'%(self.e,self.n)
398 # Possible properties of configuration nodes
400 'contact':(email,"Contact address"),
401 'dh':(dhgroup,"Diffie-Hellman group"),
402 'hash':(hash,"Hash function"),
403 'key-lifetime':(num,"Maximum key lifetime (ms)"),
404 'setup-timeout':(num,"Key setup timeout (ms)"),
405 'setup-retries':(num,"Maximum key setup packet retries"),
406 'wait-time':(num,"Time to wait after unsuccessful key setup (ms)"),
407 'renegotiate-time':(num,"Time after key setup to begin renegotiation (ms)"),
408 'restrict-nets':(networks,"Allowable networks"),
409 'networks':(networks,"Claimed networks"),
410 'pubkey':(listof(rsakey),"RSA public site key"),
411 'peer':(single_ipaddr,"Tunnel peer IP address"),
412 'address':(address,"External contact address and port"),
413 'mobile':(boolean,"Site is mobile"),
417 "Simply output a property - the default case"
418 return "%s %s;\n"%(name,value)
420 # All levels support these properties
422 'contact':(lambda name,value:"# Contact email address: %s\n"%(value)),
429 'renegotiate-time':sp,
430 'restrict-nets':(lambda name,value:"# restrict-nets %s\n"%value),
434 "A level in the configuration hierarchy"
438 require_properties={}
439 def __init__(self,w):
440 self.type=w[0].keyword()
441 self.name=w[1].name()
444 def indent(self,w,t):
446 def prop_out(self,n):
447 return self.allow_properties[n](n,str(self.properties[n]))
448 def output_props(self,w,ind):
449 for i in sorted(self.properties.keys()):
450 if self.allow_properties[i]:
452 w.write("%s"%self.prop_out(i))
454 return ((self.type[0].upper() if key_prefix else '')
456 def output_data(self,w,path):
459 w.write("%s {\n"%(self.kname()))
460 self.output_props(w,ind+2)
461 if self.depth==1: w.write("\n");
462 for k in sorted(self.children.keys()):
464 c.output_data(w,path+(c,))
468 class vpnlevel(level):
469 "VPN level in the configuration hierarchy"
473 allow_properties=global_properties.copy()
475 'contact':"VPN admin contact address"
477 def __init__(self,w):
478 level.__init__(self,w)
479 def output_vpnflat(self,w,path):
480 "Output flattened list of site names for this VPN"
483 w.write("%s {\n"%(self.kname()))
484 for i in self.children.keys():
485 self.children[i].output_vpnflat(w,path+(self,))
488 w.write("all-sites %s;\n"%
489 ','.join(map(lambda i: i.kname(),
490 self.children.values())))
494 class locationlevel(level):
495 "Location level in the configuration hierarchy"
499 allow_properties=global_properties.copy()
501 'contact':"Location admin contact address",
503 def __init__(self,w):
504 level.__init__(self,w)
505 self.group=w[2].groupname()
506 def output_vpnflat(self,w,path):
509 # The "path=path,self=self" abomination below exists because
510 # Python didn't support nested_scopes until version 2.1
513 w.write("%s %s;\n"%(self.kname(),','.join(
514 map(lambda x,path=path,self=self:
515 '/'.join([prefix+"vpn-data"] + list(map(
518 self.children.values()))))
520 class sitelevel(level):
521 "Site level (i.e. a leafnode) in the configuration hierarchy"
525 allow_properties=global_properties.copy()
526 allow_properties.update({
534 'dh':"Diffie-Hellman group",
535 'contact':"Site admin contact address",
536 'networks':"Networks claimed by the site",
537 'hash':"hash function",
538 'peer':"Gateway address of the site",
539 'pubkey':"RSA public key of the site",
541 def __init__(self,w):
542 level.__init__(self,w)
543 def output_data(self,w,path):
545 np='/'.join(map(lambda i: i.name, path))
547 w.write("%s {\n"%(self.kname()))
549 w.write("name \"%s\";\n"%(np,))
551 w.write("key %s;\n"%str(self.properties["pubkey"].list[0]))
552 self.output_props(w,ind+2)
554 w.write("link netlink {\n");
556 w.write("routes %s;\n"%str(self.properties["networks"]))
558 w.write("ptp-address %s;\n"%str(self.properties["peer"]))
564 # Levels in the configuration file
566 levels={'vpn':vpnlevel, 'location':locationlevel, 'site':sitelevel}
569 "Complain about a particular input line"
570 moan(("%s line %d: "%(file,line))+msg)
572 "Complain about something in general"
575 if complaints is None: sys.exit(1)
576 complaints=complaints+1
578 class UntaintedRoot():
579 def __init__(self,s): self._s=s
580 def name(self): return self._s
581 def keyword(self): return self._s
583 root=level([UntaintedRoot(x) for x in ['root','root']])
584 # All vpns are children of this node
586 allow_defs=0 # Level above which new definitions are permitted
588 def set_property(obj,w):
589 "Set a property on a configuration node"
591 propname=prop.raw_mark_ok()
592 kw=keywords[propname]
593 if len(kw) >= 3: propname=kw[2] # for aliases
594 if propname in obj.properties:
595 obj.properties[propname].add(obj,w)
597 obj.properties[propname]=kw[0](w)
603 # called when we enter a new node,
604 # in particular, at the start of each site
607 def pline(il,filterstate,allow_include=False):
608 "Process a configuration file line"
609 global allow_defs, obstack, root
610 w=il.rstrip('\n').split()
611 if len(w)==0: return ['']
612 w=list([Tainted(x) for x in w])
614 current=obstack[len(obstack)-1]
615 copyout_core=lambda: ' '.join([ww.output() for ww in w])
616 indent=' '*len(obstack)
617 copyout=lambda: [indent + copyout_core() + '\n']
618 if keyword=='end-definitions':
619 keyword.raw_mark_ok()
620 allow_defs=sitelevel.depth
623 if keyword=='include':
624 if not allow_include:
625 complain("include not permitted here")
628 complain("include requires one argument")
630 newfile=os.path.join(os.path.dirname(file),w[1].raw_mark_ok())
631 # ^ user of "include" is trusted so raw_mark_ok is good
632 return pfilepath(newfile,allow_include=allow_include)
633 if keyword.raw() in levels:
634 # We may go up any number of levels, but only down by one
635 newdepth=levels[keyword.raw_mark_ok()].depth
636 currentdepth=len(obstack) # actually +1...
637 if newdepth<=currentdepth:
638 obstack=obstack[:newdepth]
639 if newdepth>currentdepth:
640 complain("May not go from level %d to level %d"%
641 (currentdepth-1,newdepth))
642 # See if it's a new one (and whether that's permitted)
644 current=obstack[len(obstack)-1]
646 if tname in current.children:
648 current=current.children[tname]
649 if service and group and current.depth==2:
650 if group!=current.group:
651 complain("Incorrect group!")
655 # Ignore depth check for now
656 nl=levels[keyword.raw()](w)
657 if nl.depth<allow_defs:
658 complain("New definitions not allowed at "
660 # we risk crashing if we continue
662 current.children[tname]=nl
665 obstack.append(current)
667 if keyword.raw() not in current.allow_properties:
668 complain("Property %s not allowed at %s level"%
669 (keyword.raw(),current.type))
671 elif current.depth == vpnlevel.depth < allow_defs:
672 complain("Not allowed to set VPN properties here")
675 set_property(current,w)
678 complain("unknown keyword '%s'"%(keyword.raw()))
680 def pfilepath(pathname,allow_include=False):
682 outlines=pfile(pathname,f.readlines(),allow_include=allow_include)
686 def pfile(name,lines,allow_include=False):
692 filterstate = FilterState()
695 if (i[0]=='#'): continue
696 outlines += pline(i,filterstate,allow_include=allow_include)
700 "Output include file for secnet configuration"
701 w.write("# secnet sites file autogenerated by make-secnet-sites "
702 +"version %s\n"%VERSION)
703 w.write("# %s\n"%time.asctime(time.localtime(time.time())))
704 w.write("# Command line: %s\n\n"%' '.join(sys.argv))
706 # Raw VPN data section of file
707 w.write(prefix+"vpn-data {\n")
708 for i in root.children.values():
709 i.output_data(w,(i,))
712 # Per-VPN flattened lists
713 w.write(prefix+"vpn {\n")
714 for i in root.children.values():
715 i.output_vpnflat(w,())
718 # Flattened list of sites
719 w.write(prefix+"all-sites %s;\n"%",".join(
720 map(lambda x:"%svpn/%s/all-sites"%(prefix,x.kname()),
721 root.children.values())))
727 # Sanity check section
728 # Delete nodes where leaf=0 that have no children
731 "Number of leafnodes below node n"
733 for i in n.children.keys():
734 if live(n.children[i]): return 1
737 "Delete nodes that have no leafnode children"
738 for i in list(n.children.keys()):
739 delempty(n.children[i])
740 if not live(n.children[i]):
743 # Check that all constraints are met (as far as I can tell
744 # restrict-nets/networks/peer are the only special cases)
746 def checkconstraints(n,p,ra):
748 new_p.update(n.properties)
749 for i in n.require_properties.keys():
751 moan("%s %s is missing property %s"%
753 for i in new_p.keys():
754 if i not in n.allow_properties:
755 moan("%s %s has forbidden property %s"%
757 # Check address range restrictions
758 if "restrict-nets" in n.properties:
759 new_ra=ra.intersection(n.properties["restrict-nets"].set)
762 if "networks" in n.properties:
763 if not n.properties["networks"].set <= new_ra:
764 moan("%s %s networks out of bounds"%(n.type,n.name))
765 if "peer" in n.properties:
766 if not n.properties["networks"].set.contains(
767 n.properties["peer"].addr):
768 moan("%s %s peer not in networks"%(n.type,n.name))
769 for i in n.children.keys():
770 checkconstraints(n.children[i],new_p,new_ra)
773 headerinput=pfilepath(header,allow_include=True)
774 userinput=sys.stdin.readlines()
775 pfile("user input",userinput)
777 if inputfile is None:
778 pfile("stdin",sys.stdin.readlines())
783 checkconstraints(root,{},ipaddrset.complete_set())
786 if complaints==1: print("There was 1 problem.")
787 else: print("There were %d problems."%(complaints))
789 complaints=None # arranges to crash if we complain later
792 # Put the user's input into their group file, and rebuild the main
794 f=open(groupfiledir+"/T"+group.groupname(),'w')
795 f.write("# Section submitted by user %s, %s\n"%
796 (user,time.asctime(time.localtime(time.time()))))
797 f.write("# Checked by make-secnet-sites version %s\n\n"%VERSION)
798 for i in userinput: f.write(i)
801 os.rename(groupfiledir+"/T"+group.groupname(),
802 groupfiledir+"/R"+group.groupname())
803 f=open(sitesfile+"-tmp",'w')
804 f.write("# sites file autogenerated by make-secnet-sites\n")
805 f.write("# generated %s, invoked by %s\n"%
806 (time.asctime(time.localtime(time.time())),user))
807 f.write("# use make-secnet-sites to turn this file into a\n")
808 f.write("# valid /etc/secnet/sites.conf file\n\n")
809 for i in headerinput: f.write(i)
810 files=os.listdir(groupfiledir)
813 j=open(groupfiledir+"/"+i)
816 f.write("# end of sites file\n")
818 os.rename(sitesfile+"-tmp",sitesfile)
820 if outputfile is None:
823 tmp_outputfile=outputfile+'~tmp~'
824 of=open(tmp_outputfile,'w')
826 if outputfile is not None:
827 os.rename(tmp_outputfile,outputfile)