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")
74 from argparseactionnoyes import ActionNoYes
78 from sys import version_info
79 if version_info.major == 2: # for python2
81 sys.stdin = codecs.getreader('utf-8')(sys.stdin)
82 sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
84 open=lambda f,m='r': io.open(f,m,encoding='utf-8')
86 max={'rsa_bits':8200,'name':33,'dh_bits':8200}
90 print(repr(args), file=sys.stderr)
93 def __init__(self,s,tline=None,tfile=None):
96 self._line=line if tline is None else tline
97 self._file=file if tfile is None else tfile
102 return not self.__eq__(e)
104 raise RuntimeError('direct use of Tainted value')
106 return 'Tainted(%s)' % repr(self._s)
108 def _bad(self,what,why):
109 assert(self._ok is not True)
111 complain('bad parameter: %s: %s' % (what, why))
114 def _max_ok(self,what,maxlen):
115 if len(self._s) > maxlen:
116 return self._bad(what,'too long (max %d)' % maxlen)
119 def _re_ok(self,bad,what,maxlen=None):
120 if maxlen is None: maxlen=max[what]
121 self._max_ok(what,maxlen)
122 if self._ok is False: return False
123 if bad.search(self._s):
124 #print(repr(self), file=sys.stderr)
125 return self._bad(what,'bad syntax')
128 def _rtnval(self, is_ok, ifgood, ifbad=''):
130 assert(self._ok is not False)
134 assert(self._ok is not True)
138 def _rtn(self, is_ok, ifbad=''):
139 return self._rtnval(is_ok, self._s, ifbad)
143 def raw_mark_ok(self):
144 # caller promises to throw if syntax was dangeorus
145 return self._rtn(True)
148 if self._ok is False: return ''
149 if self._ok is True: return self._s
150 print('%s:%d: unchecked/unknown additional data "%s"' %
151 (self._file,self._line,self._s),
155 bad_name=re.compile(r'^[^a-zA-Z]|[^-_0-9a-zA-Z]')
156 # secnet accepts _ at start of names, but we reserve that
158 def name(self,what='name'):
159 ok=self._re_ok(Tainted.bad_name,what)
161 '_line%d_%s' % (self._line, id(self)))
164 ok=self._s in keywords or self._s in levels
166 complain('unknown keyword %s' % self._s)
169 bad_hex=re.compile(r'[^0-9a-fA-F]')
170 def bignum_16(self,kind,what):
171 maxlen=(max[kind+'_bits']+3)/4
172 ok=self._re_ok(Tainted.bad_hex,what,maxlen)
175 bad_num=re.compile(r'[^0-9]')
176 def bignum_10(self,kind,what):
177 maxlen=math.ceil(max[kind+'_bits'] / math.log10(2))
178 ok=self._re_ok(Tainted.bad_num,what,maxlen)
181 def number(self,minn,maxx,what='number'):
183 ok=self._re_ok(Tainted.bad_num,what,10)
187 ok=self._bad(what,'out of range %d..%d'
189 return self._rtnval(ok,v,minn)
191 def hexid(self,byteslen,what):
192 ok=self._re_ok(Tainted.bad_hex,what,byteslen*2)
194 if len(self._s) < byteslen*2:
195 ok=self._bad(what,'too short')
196 return self._rtn(ok,ifbad='00'*byteslen)
198 bad_host=re.compile(r'[^-\][_.:0-9a-zA-Z]')
199 # We permit _ so we can refer to special non-host domains
200 # which have A and AAAA RRs. This is a crude check and we may
201 # still produce config files with syntactically invalid
202 # domains or addresses, but that is OK.
204 ok=self._re_ok(Tainted.bad_host,'host/address',255)
207 bad_email=re.compile(r'[^-._0-9a-z@!$%^&*=+~/]')
208 # ^ This does not accept all valid email addresses. That's
209 # not really possible with this input syntax. It accepts
210 # all ones that don't require quoting anywhere in email
211 # protocols (and also accepts some invalid ones).
213 ok=self._re_ok(Tainted.bad_email,'email address',1023)
216 bad_groupname=re.compile(r'^[^_A-Za-z]|[^-+_0-9A-Za-z]')
218 ok=self._re_ok(Tainted.bad_groupname,'group name',64)
221 bad_base91=re.compile(r'[^!-~]|[\'\"\\]')
222 def base91(self,what='base91'):
223 ok=self._re_ok(Tainted.bad_base91,what,4096)
240 ap = argparse.ArgumentParser(description='process secnet sites files')
241 ap.add_argument('--userv', '-u', action='store_true',
242 help='userv service fragment update mode')
243 ap.add_argument('--conf-key-prefix', action=ActionNoYes,
245 help='prefix conf file key names derived from sites data')
246 ap.add_argument('--prefix', '-P', nargs=1,
248 ap.add_argument('--debug', '-D', action='count', default=0)
249 ap.add_argument('arg',nargs=argparse.REMAINDER)
251 debug_level = av.debug
253 service = 1 if av.userv else 0
254 prefix = '' if av.prefix is None else av.prefix[0]
255 key_prefix = av.conf_key_prefix
258 print("Wrong number of arguments")
260 (header, groupfiledir, sitesfile, group) = av.arg
261 group = Tainted(group,0,'command line')
262 # untrusted argument from caller
263 if "USERV_USER" not in os.environ:
264 print("Environment variable USERV_USER not found")
266 user=os.environ["USERV_USER"]
267 # Check that group is in USERV_GROUP
268 if "USERV_GROUP" not in os.environ:
269 print("Environment variable USERV_GROUP not found")
271 ugs=os.environ["USERV_GROUP"]
273 for i in ugs.split():
276 print("caller not in group %s"%group)
280 print("Too many arguments")
282 (inputfile, outputfile) = (av.arg + [None]*2)[0:2]
286 # Classes describing possible datatypes in the configuration file
289 "Common protocol for configuration types."
291 complain("%s %s already has property %s defined"%
292 (obj.type,obj.name,w[0].raw()))
295 "A list of some kind of configuration type."
296 def __init__(self,subtype,w):
298 self.list=[subtype(w)]
300 self.list.append(self.subtype(w))
302 return ', '.join(map(str, self.list))
304 return lambda w: conflist(subtype, w)
306 class single_ipaddr (basetype):
308 def __init__(self,w):
309 self.addr=ipaddress.ip_address(w[1].raw_mark_ok())
311 return '"%s"'%self.addr
313 class networks (basetype):
314 "A set of IP addresses specified as a list of networks"
315 def __init__(self,w):
316 self.set=ipaddrset.IPAddressSet()
318 x=ipaddress.ip_network(i.raw_mark_ok(),strict=True)
321 return ",".join(map((lambda n: '"%s"'%n), self.set.networks()))
323 class dhgroup (basetype):
324 "A Diffie-Hellman group"
325 def __init__(self,w):
326 self.mod=w[1].bignum_16('dh','dh mod')
327 self.gen=w[2].bignum_16('dh','dh gen')
329 return 'diffie-hellman("%s","%s")'%(self.mod,self.gen)
331 class hash (basetype):
332 "A choice of hash function"
333 def __init__(self,w):
336 if (self.ht!='md5' and self.ht!='sha1'):
337 complain("unknown hash type %s"%(self.ht))
342 return '%s'%(self.ht)
344 class email (basetype):
346 def __init__(self,w):
347 self.addr=w[1].email()
349 return '<%s>'%(self.addr)
351 class boolean (basetype):
353 def __init__(self,w):
355 if re.match('[TtYy1]',v.raw()):
358 elif re.match('[FfNn0]',v.raw()):
362 complain("invalid boolean value");
364 return ['False','True'][self.b]
366 class num (basetype):
368 def __init__(self,w):
369 self.n=w[1].number(0,0x7fffffff)
373 class address (basetype):
374 "A DNS name and UDP port number"
375 def __init__(self,w):
377 self.port=w[2].number(1,65536,'port')
379 return '"%s"; port %d'%(self.adr,self.port)
381 class rsakey (basetype):
383 def __init__(self,w):
384 self.l=w[1].number(0,max['rsa_bits'],'rsa len')
385 self.e=w[2].bignum_10('rsa','rsa e')
386 self.n=w[3].bignum_10('rsa','rsa n')
387 if len(w) >= 5: w[4].email()
389 return 'rsa-public("%s","%s")'%(self.e,self.n)
391 # Possible properties of configuration nodes
393 'contact':(email,"Contact address"),
394 'dh':(dhgroup,"Diffie-Hellman group"),
395 'hash':(hash,"Hash function"),
396 'key-lifetime':(num,"Maximum key lifetime (ms)"),
397 'setup-timeout':(num,"Key setup timeout (ms)"),
398 'setup-retries':(num,"Maximum key setup packet retries"),
399 'wait-time':(num,"Time to wait after unsuccessful key setup (ms)"),
400 'renegotiate-time':(num,"Time after key setup to begin renegotiation (ms)"),
401 'restrict-nets':(networks,"Allowable networks"),
402 'networks':(networks,"Claimed networks"),
403 'pubkey':(listof(rsakey),"RSA public site key"),
404 'peer':(single_ipaddr,"Tunnel peer IP address"),
405 'address':(address,"External contact address and port"),
406 'mobile':(boolean,"Site is mobile"),
410 "Simply output a property - the default case"
411 return "%s %s;\n"%(name,value)
413 # All levels support these properties
415 'contact':(lambda name,value:"# Contact email address: %s\n"%(value)),
422 'renegotiate-time':sp,
423 'restrict-nets':(lambda name,value:"# restrict-nets %s\n"%value),
427 "A level in the configuration hierarchy"
431 require_properties={}
432 def __init__(self,w):
433 self.type=w[0].keyword()
434 self.name=w[1].name()
437 def indent(self,w,t):
439 def prop_out(self,n):
440 return self.allow_properties[n](n,str(self.properties[n]))
441 def output_props(self,w,ind):
442 for i in sorted(self.properties.keys()):
443 if self.allow_properties[i]:
445 w.write("%s"%self.prop_out(i))
447 return ((self.type[0].upper() if key_prefix else '')
449 def output_data(self,w,path):
452 w.write("%s {\n"%(self.kname()))
453 self.output_props(w,ind+2)
454 if self.depth==1: w.write("\n");
455 for k in sorted(self.children.keys()):
457 c.output_data(w,path+(c,))
461 class vpnlevel(level):
462 "VPN level in the configuration hierarchy"
466 allow_properties=global_properties.copy()
468 'contact':"VPN admin contact address"
470 def __init__(self,w):
471 level.__init__(self,w)
472 def output_vpnflat(self,w,path):
473 "Output flattened list of site names for this VPN"
476 w.write("%s {\n"%(self.kname()))
477 for i in self.children.keys():
478 self.children[i].output_vpnflat(w,path+(self,))
481 w.write("all-sites %s;\n"%
482 ','.join(map(lambda i: i.kname(),
483 self.children.values())))
487 class locationlevel(level):
488 "Location level in the configuration hierarchy"
492 allow_properties=global_properties.copy()
494 'contact':"Location admin contact address",
496 def __init__(self,w):
497 level.__init__(self,w)
498 self.group=w[2].groupname()
499 def output_vpnflat(self,w,path):
502 # The "path=path,self=self" abomination below exists because
503 # Python didn't support nested_scopes until version 2.1
506 w.write("%s %s;\n"%(self.kname(),','.join(
507 map(lambda x,path=path,self=self:
508 '/'.join([prefix+"vpn-data"] + list(map(
511 self.children.values()))))
513 class sitelevel(level):
514 "Site level (i.e. a leafnode) in the configuration hierarchy"
518 allow_properties=global_properties.copy()
519 allow_properties.update({
527 'dh':"Diffie-Hellman group",
528 'contact':"Site admin contact address",
529 'networks':"Networks claimed by the site",
530 'hash':"hash function",
531 'peer':"Gateway address of the site",
532 'pubkey':"RSA public key of the site",
534 def __init__(self,w):
535 level.__init__(self,w)
536 def output_data(self,w,path):
538 np='/'.join(map(lambda i: i.name, path))
540 w.write("%s {\n"%(self.kname()))
542 w.write("name \"%s\";\n"%(np,))
544 w.write("key %s;\n"%str(self.properties["pubkey"].list[0]))
545 self.output_props(w,ind+2)
547 w.write("link netlink {\n");
549 w.write("routes %s;\n"%str(self.properties["networks"]))
551 w.write("ptp-address %s;\n"%str(self.properties["peer"]))
557 # Levels in the configuration file
559 levels={'vpn':vpnlevel, 'location':locationlevel, 'site':sitelevel}
562 "Complain about a particular input line"
563 moan(("%s line %d: "%(file,line))+msg)
565 "Complain about something in general"
568 if complaints is None: sys.exit(1)
569 complaints=complaints+1
571 class UntaintedRoot():
572 def __init__(self,s): self._s=s
573 def name(self): return self._s
574 def keyword(self): return self._s
576 root=level([UntaintedRoot(x) for x in ['root','root']])
577 # All vpns are children of this node
579 allow_defs=0 # Level above which new definitions are permitted
581 def set_property(obj,w):
582 "Set a property on a configuration node"
584 propname=prop.raw_mark_ok()
585 kw=keywords[propname]
586 if len(kw) >= 3: propname=kw[2] # for aliases
587 if propname in obj.properties:
588 obj.properties[propname].add(obj,w)
590 obj.properties[propname]=kw[0](w)
593 def pline(il,allow_include=False):
594 "Process a configuration file line"
595 global allow_defs, obstack, root
596 w=il.rstrip('\n').split()
597 if len(w)==0: return ['']
598 w=list([Tainted(x) for x in w])
600 current=obstack[len(obstack)-1]
601 copyout=lambda: [' '*len(obstack) +
602 ' '.join([ww.output() for ww in w]) +
604 if keyword=='end-definitions':
605 keyword.raw_mark_ok()
606 allow_defs=sitelevel.depth
609 if keyword=='include':
610 if not allow_include:
611 complain("include not permitted here")
614 complain("include requires one argument")
616 newfile=os.path.join(os.path.dirname(file),w[1].raw_mark_ok())
617 # ^ user of "include" is trusted so raw_mark_ok is good
618 return pfilepath(newfile,allow_include=allow_include)
619 if keyword.raw() in levels:
620 # We may go up any number of levels, but only down by one
621 newdepth=levels[keyword.raw_mark_ok()].depth
622 currentdepth=len(obstack) # actually +1...
623 if newdepth<=currentdepth:
624 obstack=obstack[:newdepth]
625 if newdepth>currentdepth:
626 complain("May not go from level %d to level %d"%
627 (currentdepth-1,newdepth))
628 # See if it's a new one (and whether that's permitted)
630 current=obstack[len(obstack)-1]
632 if tname in current.children:
634 current=current.children[tname]
635 if service and group and current.depth==2:
636 if group!=current.group:
637 complain("Incorrect group!")
641 # Ignore depth check for now
642 nl=levels[keyword.raw()](w)
643 if nl.depth<allow_defs:
644 complain("New definitions not allowed at "
646 # we risk crashing if we continue
648 current.children[tname]=nl
650 obstack.append(current)
652 if keyword.raw() not in current.allow_properties:
653 complain("Property %s not allowed at %s level"%
654 (keyword.raw(),current.type))
656 elif current.depth == vpnlevel.depth < allow_defs:
657 complain("Not allowed to set VPN properties here")
660 set_property(current,w)
663 complain("unknown keyword '%s'"%(keyword.raw()))
665 def pfilepath(pathname,allow_include=False):
667 outlines=pfile(pathname,f.readlines(),allow_include=allow_include)
671 def pfile(name,lines,allow_include=False):
679 if (i[0]=='#'): continue
680 outlines += pline(i,allow_include=allow_include)
684 "Output include file for secnet configuration"
685 w.write("# secnet sites file autogenerated by make-secnet-sites "
686 +"version %s\n"%VERSION)
687 w.write("# %s\n"%time.asctime(time.localtime(time.time())))
688 w.write("# Command line: %s\n\n"%' '.join(sys.argv))
690 # Raw VPN data section of file
691 w.write(prefix+"vpn-data {\n")
692 for i in root.children.values():
693 i.output_data(w,(i,))
696 # Per-VPN flattened lists
697 w.write(prefix+"vpn {\n")
698 for i in root.children.values():
699 i.output_vpnflat(w,())
702 # Flattened list of sites
703 w.write(prefix+"all-sites %s;\n"%",".join(
704 map(lambda x:"%svpn/%s/all-sites"%(prefix,x.kname()),
705 root.children.values())))
711 # Sanity check section
712 # Delete nodes where leaf=0 that have no children
715 "Number of leafnodes below node n"
717 for i in n.children.keys():
718 if live(n.children[i]): return 1
721 "Delete nodes that have no leafnode children"
722 for i in list(n.children.keys()):
723 delempty(n.children[i])
724 if not live(n.children[i]):
727 # Check that all constraints are met (as far as I can tell
728 # restrict-nets/networks/peer are the only special cases)
730 def checkconstraints(n,p,ra):
732 new_p.update(n.properties)
733 for i in n.require_properties.keys():
735 moan("%s %s is missing property %s"%
737 for i in new_p.keys():
738 if i not in n.allow_properties:
739 moan("%s %s has forbidden property %s"%
741 # Check address range restrictions
742 if "restrict-nets" in n.properties:
743 new_ra=ra.intersection(n.properties["restrict-nets"].set)
746 if "networks" in n.properties:
747 if not n.properties["networks"].set <= new_ra:
748 moan("%s %s networks out of bounds"%(n.type,n.name))
749 if "peer" in n.properties:
750 if not n.properties["networks"].set.contains(
751 n.properties["peer"].addr):
752 moan("%s %s peer not in networks"%(n.type,n.name))
753 for i in n.children.keys():
754 checkconstraints(n.children[i],new_p,new_ra)
757 headerinput=pfilepath(header,allow_include=True)
758 userinput=sys.stdin.readlines()
759 pfile("user input",userinput)
761 if inputfile is None:
762 pfile("stdin",sys.stdin.readlines())
767 checkconstraints(root,{},ipaddrset.complete_set())
770 if complaints==1: print("There was 1 problem.")
771 else: print("There were %d problems."%(complaints))
773 complaints=None # arranges to crash if we complain later
776 # Put the user's input into their group file, and rebuild the main
778 f=open(groupfiledir+"/T"+group.groupname(),'w')
779 f.write("# Section submitted by user %s, %s\n"%
780 (user,time.asctime(time.localtime(time.time()))))
781 f.write("# Checked by make-secnet-sites version %s\n\n"%VERSION)
782 for i in userinput: f.write(i)
785 os.rename(groupfiledir+"/T"+group.groupname(),
786 groupfiledir+"/R"+group.groupname())
787 f=open(sitesfile+"-tmp",'w')
788 f.write("# sites file autogenerated by make-secnet-sites\n")
789 f.write("# generated %s, invoked by %s\n"%
790 (time.asctime(time.localtime(time.time())),user))
791 f.write("# use make-secnet-sites to turn this file into a\n")
792 f.write("# valid /etc/secnet/sites.conf file\n\n")
793 for i in headerinput: f.write(i)
794 files=os.listdir(groupfiledir)
797 j=open(groupfiledir+"/"+i)
800 f.write("# end of sites file\n")
802 os.rename(sitesfile+"-tmp",sitesfile)
804 if outputfile is None:
807 tmp_outputfile=outputfile+'~tmp~'
808 of=open(tmp_outputfile,'w')
810 if outputfile is not None:
811 os.rename(tmp_outputfile,outputfile)