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")
76 from sys import version_info
77 if version_info.major == 2: # for python2
79 sys.stdin = codecs.getreader('utf-8')(sys.stdin)
80 sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
82 open=lambda f,m='r': io.open(f,m,encoding='utf-8')
84 max={'rsa_bits':8200,'name':33,'dh_bits':8200}
96 return not self.__eq__(e)
98 raise RuntimeError('direct use of Tainted value')
100 return 'Tainted(%s)' % repr(self._s)
102 def _bad(self,what,why):
103 assert(self._ok is not True)
105 complain('bad parameter: %s: %s' % (what, why))
108 def _max_ok(self,what,maxlen):
109 if len(self._s) > maxlen:
110 self._bad(what,'too long (max %d)' % maxlen)
113 def _re_ok(self,bad,what,maxlen=None):
114 if maxlen is None: maxlen=max[what]
115 self._max_ok(what,maxlen)
116 if self._ok is False: return self
117 if bad.search(self._s): return self._bad(what,'bad syntax')
120 def _rtnval(self, is_ok, ifgood, ifbad=''):
122 assert(self._ok is not False)
126 assert(self._ok is not True)
130 def _rtn(self, is_ok, ifbad=''):
131 return self._rtnval(is_ok, self._s, ifbad)
135 def raw_mark_ok(self):
136 # caller promises to throw if syntax was dangeorus
137 return self._rtn(True)
139 bad_name=re.compile(r'^[^a-zA-Z]|[^-_0-9a-zA-Z]')
140 # secnet accepts _ at start of names, but we reserve that
143 ok=self._re_ok(Tainted.bad_name,'name')
145 '_line%d_%s' % (self._line, id(self)))
148 ok=self._s in keywords or self._s in levels
150 complain('unknown keyword %s' % self._s)
153 bad_hex=re.compile(r'[^0-9a-fA-F]')
154 def bignum_16(self,kind,what):
155 maxlen=(max[kind+'_bits']+3)/4
156 ok=self._re_ok(Tainted.bad_hex,what,maxlen)
159 bad_num=re.compile(r'[^0-9]')
160 def bignum_10(self,kind,what):
161 maxlen=math.ceil(max[kind+'_bits'] / math.log10(2))
162 ok=self._re_ok(Tainted.bad_num,what,maxlen)
165 def number(self,minn,maxx,what='number'):
167 ok=self._re_ok(Tainted.bad_num,what,10)
171 ok=self._bad(what,'out of range %d..%d'
173 return self._rtnval(ok,v,minn)
175 bad_host=re.compile(r'[^-\][_.:0-9a-zA-Z]')
176 # We permit _ so we can refer to special non-host domains
177 # which have A and AAAA RRs. This is a crude check and we may
178 # still produce config files with syntactically invalid
179 # domains or addresses, but that is OK.
181 ok=self._re_ok(Tainted.bad_host,'host/address',255)
184 bad_email=re.compile(r'[^-._0-9a-z@!$%^&*=+~/]')
185 # ^ This does not accept all valid email addresses. That's
186 # not really possible with this input syntax. It accepts
187 # all ones that don't require quoting anywhere in email
188 # protocols (and also accepts some invalid ones).
190 ok=self._re_ok(Tainted.bad_email,'email address',1023)
193 bad_groupname=re.compile(r'^[^_A-Za-z]|[^-+_0-9A-Za-z]')
195 ok=self._re_ok(Tainted.bad_groupname,'group name',64)
208 ap = argparse.ArgumentParser(description='process secnet sites files')
209 ap.add_argument('--userv', '-u', action='store_true',
210 help='userv service fragment update mode')
211 ap.add_argument('--prefix', '-P', nargs=1,
213 ap.add_argument('arg',nargs=argparse.REMAINDER)
215 #print(repr(av), file=sys.stderr)
216 service = 1 if av.userv else 0
219 print("Wrong number of arguments")
221 (header, groupfiledir, sitesfile, group) = av.arg
222 if "USERV_USER" not in os.environ:
223 print("Environment variable USERV_USER not found")
225 user=os.environ["USERV_USER"]
226 # Check that group is in USERV_GROUP
227 if "USERV_GROUP" not in os.environ:
228 print("Environment variable USERV_GROUP not found")
230 ugs=os.environ["USERV_GROUP"]
232 for i in ugs.split():
235 print("caller not in group %s"%group)
239 print("Too many arguments")
241 (inputfile, outputfile) = (av.arg + [None]*2)[0:2]
242 if outputfile is None: of=sys.stdout
243 else: of=open(sys.argv[2],'w')
247 # Classes describing possible datatypes in the configuration file
250 "Common protocol for configuration types."
252 complain("%s %s already has property %s defined"%
253 (obj.type,obj.name,w[0].raw()))
256 "A list of some kind of configuration type."
257 def __init__(self,subtype,w):
259 self.list=[subtype(w)]
261 self.list.append(self.subtype(w))
263 return ', '.join(map(str, self.list))
265 return lambda w: conflist(subtype, w)
267 class single_ipaddr (basetype):
269 def __init__(self,w):
270 self.addr=ipaddress.ip_address(w[1].raw_mark_ok())
272 return '"%s"'%self.addr
274 class networks (basetype):
275 "A set of IP addresses specified as a list of networks"
276 def __init__(self,w):
277 self.set=ipaddrset.IPAddressSet()
279 x=ipaddress.ip_network(i.raw_mark_ok(),strict=True)
282 return ",".join(map((lambda n: '"%s"'%n), self.set.networks()))
284 class dhgroup (basetype):
285 "A Diffie-Hellman group"
286 def __init__(self,w):
287 self.mod=w[1].bignum_16('dh','dh mod')
288 self.gen=w[2].bignum_16('dh','dh gen')
290 return 'diffie-hellman("%s","%s")'%(self.mod,self.gen)
292 class hash (basetype):
293 "A choice of hash function"
294 def __init__(self,w):
297 if (self.ht!='md5' and self.ht!='sha1'):
298 complain("unknown hash type %s"%(self.ht))
303 return '%s'%(self.ht)
305 class email (basetype):
307 def __init__(self,w):
308 self.addr=w[1].email()
310 return '<%s>'%(self.addr)
312 class boolean (basetype):
314 def __init__(self,w):
316 if re.match('[TtYy1]',v.raw()):
319 elif re.match('[FfNn0]',v.raw()):
323 complain("invalid boolean value");
325 return ['False','True'][self.b]
327 class num (basetype):
329 def __init__(self,w):
330 self.n=w[1].number(0,0x7fffffff)
334 class address (basetype):
335 "A DNS name and UDP port number"
336 def __init__(self,w):
338 self.port=w[2].number(1,65536,'port')
340 return '"%s"; port %d'%(self.adr,self.port)
342 class rsakey (basetype):
344 def __init__(self,w):
345 self.l=w[1].number(0,max['rsa_bits'],'rsa len')
346 self.e=w[2].bignum_10('rsa','rsa e')
347 self.n=w[3].bignum_10('rsa','rsa n')
349 return 'rsa-public("%s","%s")'%(self.e,self.n)
351 # Possible properties of configuration nodes
353 'contact':(email,"Contact address"),
354 'dh':(dhgroup,"Diffie-Hellman group"),
355 'hash':(hash,"Hash function"),
356 'key-lifetime':(num,"Maximum key lifetime (ms)"),
357 'setup-timeout':(num,"Key setup timeout (ms)"),
358 'setup-retries':(num,"Maximum key setup packet retries"),
359 'wait-time':(num,"Time to wait after unsuccessful key setup (ms)"),
360 'renegotiate-time':(num,"Time after key setup to begin renegotiation (ms)"),
361 'restrict-nets':(networks,"Allowable networks"),
362 'networks':(networks,"Claimed networks"),
363 'pubkey':(rsakey,"RSA public site key"),
364 'peer':(single_ipaddr,"Tunnel peer IP address"),
365 'address':(address,"External contact address and port"),
366 'mobile':(boolean,"Site is mobile"),
370 "Simply output a property - the default case"
371 return "%s %s;\n"%(name,value)
373 # All levels support these properties
375 'contact':(lambda name,value:"# Contact email address: %s\n"%(value)),
382 'renegotiate-time':sp,
383 'restrict-nets':(lambda name,value:"# restrict-nets %s\n"%value),
387 "A level in the configuration hierarchy"
391 require_properties={}
392 def __init__(self,w):
393 self.type=w[0].keyword()
394 self.name=w[1].name()
397 def indent(self,w,t):
399 def prop_out(self,n):
400 return self.allow_properties[n](n,str(self.properties[n]))
401 def output_props(self,w,ind):
402 for i in self.properties.keys():
403 if self.allow_properties[i]:
405 w.write("%s"%self.prop_out(i))
406 def output_data(self,w,ind,np):
408 w.write("%s {\n"%(self.name))
409 self.output_props(w,ind+2)
410 if self.depth==1: w.write("\n");
411 for c in self.children.values():
412 c.output_data(w,ind+2,np+self.name+"/")
416 class vpnlevel(level):
417 "VPN level in the configuration hierarchy"
421 allow_properties=global_properties.copy()
423 'contact':"VPN admin contact address"
425 def __init__(self,w):
426 level.__init__(self,w)
427 def output_vpnflat(self,w,ind,h):
428 "Output flattened list of site names for this VPN"
430 w.write("%s {\n"%(self.name))
431 for i in self.children.keys():
432 self.children[i].output_vpnflat(w,ind+2,
433 h+"/"+self.name+"/"+i)
436 w.write("all-sites %s;\n"%
437 ','.join(self.children.keys()))
441 class locationlevel(level):
442 "Location level in the configuration hierarchy"
446 allow_properties=global_properties.copy()
448 'contact':"Location admin contact address",
450 def __init__(self,w):
451 level.__init__(self,w)
452 self.group=w[2].groupname()
453 def output_vpnflat(self,w,ind,h):
455 # The "h=h,self=self" abomination below exists because
456 # Python didn't support nested_scopes until version 2.1
457 w.write("%s %s;\n"%(self.name,','.join(
458 map(lambda x,h=h,self=self:
459 h+"/"+x,self.children.keys()))))
461 class sitelevel(level):
462 "Site level (i.e. a leafnode) in the configuration hierarchy"
466 allow_properties=global_properties.copy()
467 allow_properties.update({
471 'pubkey':(lambda n,v:"key %s;\n"%v),
475 'dh':"Diffie-Hellman group",
476 'contact':"Site admin contact address",
477 'networks':"Networks claimed by the site",
478 'hash':"hash function",
479 'peer':"Gateway address of the site",
480 'pubkey':"RSA public key of the site",
482 def __init__(self,w):
483 level.__init__(self,w)
484 def output_data(self,w,ind,np):
486 w.write("%s {\n"%(self.name))
488 w.write("name \"%s\";\n"%(np+self.name))
489 self.output_props(w,ind+2)
491 w.write("link netlink {\n");
493 w.write("routes %s;\n"%str(self.properties["networks"]))
495 w.write("ptp-address %s;\n"%str(self.properties["peer"]))
501 # Levels in the configuration file
503 levels={'vpn':vpnlevel, 'location':locationlevel, 'site':sitelevel}
505 # Reserved vpn/location/site names
506 reserved={'all-sites':None}
507 reserved.update(keywords)
508 reserved.update(levels)
511 "Complain about a particular input line"
513 print(("%s line %d: "%(file,line))+msg)
514 complaints=complaints+1
516 "Complain about something in general"
519 complaints=complaints+1
521 class UntaintedRoot():
522 def __init__(self,s): self._s=s
523 def name(self): return self._s
524 def keyword(self): return self._s
526 root=level([UntaintedRoot(x) for x in ['root','root']])
527 # All vpns are children of this node
529 allow_defs=0 # Level above which new definitions are permitted
532 def set_property(obj,w):
533 "Set a property on a configuration node"
535 if prop.raw() in obj.properties:
536 obj.properties[prop.raw_mark_ok()].add(obj,w)
538 obj.properties[prop.raw()]=keywords[prop.raw_mark_ok()][0](w)
540 def pline(i,allow_include=False):
541 "Process a configuration file line"
542 global allow_defs, obstack, root
543 w=i.rstrip('\n').split()
544 if len(w)==0: return [i]
545 w=list([Tainted(x) for x in w])
547 current=obstack[len(obstack)-1]
548 if keyword=='end-definitions':
549 keyword.raw_mark_ok()
550 allow_defs=sitelevel.depth
553 if keyword=='include':
554 if not allow_include:
555 complain("include not permitted here")
558 complain("include requires one argument")
560 newfile=os.path.join(os.path.dirname(file),w[1].raw_mark_ok())
561 # ^ user of "include" is trusted so raw_mark_ok is good
562 return pfilepath(newfile,allow_include=allow_include)
563 if keyword.raw() in levels:
564 # We may go up any number of levels, but only down by one
565 newdepth=levels[keyword.raw_mark_ok()].depth
566 currentdepth=len(obstack) # actually +1...
567 if newdepth<=currentdepth:
568 obstack=obstack[:newdepth]
569 if newdepth>currentdepth:
570 complain("May not go from level %d to level %d"%
571 (currentdepth-1,newdepth))
572 # See if it's a new one (and whether that's permitted)
574 current=obstack[len(obstack)-1]
576 if tname in current.children:
578 current=current.children[tname]
579 if service and group and current.depth==2:
580 if group!=current.group:
581 complain("Incorrect group!")
584 # Ignore depth check for now
585 nl=levels[keyword.raw()](w)
586 if nl.depth<allow_defs:
587 complain("New definitions not allowed at "
589 # we risk crashing if we continue
591 current.children[tname]=nl
593 obstack.append(current)
595 if keyword.raw() not in current.allow_properties:
596 complain("Property %s not allowed at %s level"%
597 (keyword.raw(),current.type))
599 elif current.depth == vpnlevel.depth < allow_defs:
600 complain("Not allowed to set VPN properties here")
603 set_property(current,w)
606 complain("unknown keyword '%s'"%(keyword.raw()))
608 def pfilepath(pathname,allow_include=False):
610 outlines=pfile(pathname,f.readlines(),allow_include=allow_include)
614 def pfile(name,lines,allow_include=False):
622 if (i[0]=='#'): continue
623 outlines += pline(i,allow_include=allow_include)
627 "Output include file for secnet configuration"
628 w.write("# secnet sites file autogenerated by make-secnet-sites "
629 +"version %s\n"%VERSION)
630 w.write("# %s\n"%time.asctime(time.localtime(time.time())))
631 w.write("# Command line: %s\n\n"%' '.join(sys.argv))
633 # Raw VPN data section of file
634 w.write(prefix+"vpn-data {\n")
635 for i in root.children.values():
636 i.output_data(w,2,"")
639 # Per-VPN flattened lists
640 w.write(prefix+"vpn {\n")
641 for i in root.children.values():
642 i.output_vpnflat(w,2,prefix+"vpn-data")
645 # Flattened list of sites
646 w.write(prefix+"all-sites %s;\n"%",".join(
647 map(lambda x:"%svpn/%s/all-sites"%(prefix,x),
648 root.children.keys())))
654 # Sanity check section
655 # Delete nodes where leaf=0 that have no children
658 "Number of leafnodes below node n"
660 for i in n.children.keys():
661 if live(n.children[i]): return 1
664 "Delete nodes that have no leafnode children"
665 for i in list(n.children.keys()):
666 delempty(n.children[i])
667 if not live(n.children[i]):
670 # Check that all constraints are met (as far as I can tell
671 # restrict-nets/networks/peer are the only special cases)
673 def checkconstraints(n,p,ra):
675 new_p.update(n.properties)
676 for i in n.require_properties.keys():
678 moan("%s %s is missing property %s"%
680 for i in new_p.keys():
681 if i not in n.allow_properties:
682 moan("%s %s has forbidden property %s"%
684 # Check address range restrictions
685 if "restrict-nets" in n.properties:
686 new_ra=ra.intersection(n.properties["restrict-nets"].set)
689 if "networks" in n.properties:
690 if not n.properties["networks"].set <= new_ra:
691 moan("%s %s networks out of bounds"%(n.type,n.name))
692 if "peer" in n.properties:
693 if not n.properties["networks"].set.contains(
694 n.properties["peer"].addr):
695 moan("%s %s peer not in networks"%(n.type,n.name))
696 for i in n.children.keys():
697 checkconstraints(n.children[i],new_p,new_ra)
700 headerinput=pfilepath(header,allow_include=True)
701 userinput=sys.stdin.readlines()
702 pfile("user input",userinput)
704 if inputfile is None:
705 pfile("stdin",sys.stdin.readlines())
710 checkconstraints(root,{},ipaddrset.complete_set())
713 if complaints==1: print("There was 1 problem.")
714 else: print("There were %d problems."%(complaints))
716 complaints=None # arranges to crash if we complain later
719 # Put the user's input into their group file, and rebuild the main
721 f=open(groupfiledir+"/T"+group,'w')
722 f.write("# Section submitted by user %s, %s\n"%
723 (user,time.asctime(time.localtime(time.time()))))
724 f.write("# Checked by make-secnet-sites version %s\n\n"%VERSION)
725 for i in userinput: f.write(i)
728 os.rename(groupfiledir+"/T"+group,groupfiledir+"/R"+group)
729 f=open(sitesfile+"-tmp",'w')
730 f.write("# sites file autogenerated by make-secnet-sites\n")
731 f.write("# generated %s, invoked by %s\n"%
732 (time.asctime(time.localtime(time.time())),user))
733 f.write("# use make-secnet-sites to turn this file into a\n")
734 f.write("# valid /etc/secnet/sites.conf file\n\n")
735 for i in headerinput: f.write(i)
736 files=os.listdir(groupfiledir)
739 j=open(groupfiledir+"/"+i)
742 f.write("# end of sites file\n")
744 os.rename(sitesfile+"-tmp",sitesfile)