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
81 from sys import version_info
82 if version_info.major == 2: # for python2
84 sys.stdin = codecs.getreader('utf-8')(sys.stdin)
85 sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
87 open=lambda f,m='r': io.open(f,m,encoding='utf-8')
89 max={'rsa_bits':8200,'name':33,'dh_bits':8200,'algname':127}
93 print(repr(args), file=sys.stderr)
95 def base91s_encode(bindata):
96 return base91.encode(bindata).replace('"',"-")
98 def base91s_decode(string):
99 return base91.decode(string.replace("-",'"'))
102 def __init__(self,s,tline=None,tfile=None):
105 self._line=line if tline is None else tline
106 self._file=file if tfile is None else tfile
111 return not self.__eq__(e)
113 raise RuntimeError('direct use of Tainted value')
115 return 'Tainted(%s)' % repr(self._s)
117 def _bad(self,what,why):
118 assert(self._ok is not True)
120 complain('bad parameter: %s: %s' % (what, why))
123 def _max_ok(self,what,maxlen):
124 if len(self._s) > maxlen:
125 return self._bad(what,'too long (max %d)' % maxlen)
128 def _re_ok(self,bad,what,maxlen=None):
129 if maxlen is None: maxlen=max[what]
130 self._max_ok(what,maxlen)
131 if self._ok is False: return False
132 if bad.search(self._s):
133 #print(repr(self), file=sys.stderr)
134 return self._bad(what,'bad syntax')
137 def _rtnval(self, is_ok, ifgood, ifbad=''):
139 assert(self._ok is not False)
143 assert(self._ok is not True)
147 def _rtn(self, is_ok, ifbad=''):
148 return self._rtnval(is_ok, self._s, ifbad)
152 def raw_mark_ok(self):
153 # caller promises to throw if syntax was dangeorus
154 return self._rtn(True)
157 if self._ok is False: return ''
158 if self._ok is True: return self._s
159 print('%s:%d: unchecked/unknown additional data "%s"' %
160 (self._file,self._line,self._s),
164 bad_name=re.compile(r'^[^a-zA-Z]|[^-_0-9a-zA-Z]')
165 # secnet accepts _ at start of names, but we reserve that
167 def name(self,what='name'):
168 ok=self._re_ok(Tainted.bad_name,what)
170 '_line%d_%s' % (self._line, id(self)))
173 ok=self._s in keywords or self._s in levels
175 complain('unknown keyword %s' % self._s)
178 bad_hex=re.compile(r'[^0-9a-fA-F]')
179 def bignum_16(self,kind,what):
180 maxlen=(max[kind+'_bits']+3)/4
181 ok=self._re_ok(Tainted.bad_hex,what,maxlen)
184 bad_num=re.compile(r'[^0-9]')
185 def bignum_10(self,kind,what):
186 maxlen=math.ceil(max[kind+'_bits'] / math.log10(2))
187 ok=self._re_ok(Tainted.bad_num,what,maxlen)
190 def number(self,minn,maxx,what='number'):
192 ok=self._re_ok(Tainted.bad_num,what,10)
196 ok=self._bad(what,'out of range %d..%d'
198 return self._rtnval(ok,v,minn)
200 def hexid(self,byteslen,what):
201 ok=self._re_ok(Tainted.bad_hex,what,byteslen*2)
203 if len(self._s) < byteslen*2:
204 ok=self._bad(what,'too short')
205 return self._rtn(ok,ifbad='00'*byteslen)
207 bad_host=re.compile(r'[^-\][_.:0-9a-zA-Z]')
208 # We permit _ so we can refer to special non-host domains
209 # which have A and AAAA RRs. This is a crude check and we may
210 # still produce config files with syntactically invalid
211 # domains or addresses, but that is OK.
213 ok=self._re_ok(Tainted.bad_host,'host/address',255)
216 bad_email=re.compile(r'[^-._0-9a-z@!$%^&*=+~/]')
217 # ^ This does not accept all valid email addresses. That's
218 # not really possible with this input syntax. It accepts
219 # all ones that don't require quoting anywhere in email
220 # protocols (and also accepts some invalid ones).
222 ok=self._re_ok(Tainted.bad_email,'email address',1023)
225 bad_groupname=re.compile(r'^[^_A-Za-z]|[^-+_0-9A-Za-z]')
227 ok=self._re_ok(Tainted.bad_groupname,'group name',64)
230 bad_base91=re.compile(r'[^!-~]|[\'\"\\]')
231 def base91(self,what='base91'):
232 ok=self._re_ok(Tainted.bad_base91,what,4096)
235 class ArgActionLambda(argparse.Action):
236 def __init__(self, fn, **kwargs):
238 argparse.Action.__init__(self,**kwargs)
239 def __call__(self,ap,ns,values,option_string):
240 self.fn(values,ns,ap,option_string)
243 def site_start(self,pubkeys_path):
244 self._pa=pubkeys_path
245 self._fs = FilterState()
246 def site_serial(self,serial): pass
247 def write_key(self,k): pass
248 def site_finish(self,confw): pass
250 class PkmSingle(PkmBase):
252 help = 'write one public key per site to sites.conf'
253 def site_start(self,pubkeys_path):
254 PkmBase.site_start(self,pubkeys_path)
256 def write_key(self,k):
257 if k.okforonlykey(output_version,self._fs):
259 def site_finish(self,confw):
260 if len(self._outk) == 0:
261 complain("site with no public key");
262 elif len(self._outk) != 1:
263 debugrepr('outk ', self._outk)
265 "site with multiple public keys, without --pubkeys-install (maybe --output-version=1 would help"
268 confw.write("key %s;\n"%str(self._outk[0]))
270 class PkmInstall(PkmBase):
272 help = 'install public keys in public key directory'
273 def site_start(self,pubkeys_path):
274 PkmBase.site_start(self,pubkeys_path)
275 self._pw=open(self._pa+'~tmp','w')
276 def site_serial(self,serial):
277 self._pw.write('serial %s\n' % serial)
278 def write_key(self,k):
279 wout=k.forpub(output_version,self._fs)
280 self._pw.write(' '.join(wout))
282 def site_finish(self,confw):
284 os.rename(self._pa+'~tmp',self._pa+'~update')
285 PkmElide.site_finish(self,confw)
287 class PkmElide(PkmBase):
289 help = 'no public keys in sites.conf output nor in directory'
290 def site_finish(self,confw):
291 confw.write("peer-keys \"%s\";\n"%self._pa);
294 # Base case is reading a sites file from self.inputfilee.
295 # And writing a sites file to self.sitesfile.
296 def positional_args(self, av):
298 print("Too many arguments")
300 (self.inputfile, self.outputfile) = (av.arg + [None]*2)[0:2]
302 if self.inputfile is None:
303 self.inputlines = pfile("stdin",sys.stdin.readlines())
305 self.inputlines = pfilepath(self.inputfile)
307 if self.outputfile is None:
310 f=open(self.outputfile+"-tmp",'w')
311 f.write("# sites file autogenerated by make-secnet-sites\n")
312 self.write_out_heading(f)
313 f.write("# use make-secnet-sites to turn this file into a\n")
314 f.write("# valid /etc/secnet/sites.conf file\n\n")
315 self.write_out_contents(f)
316 f.write("# end of sites file\n")
317 if self.outputfile is not None:
319 os.rename(self.outputfile+"-tmp",self.outputfile)
321 class OpConf(OpBase):
323 help = 'sites.conf generation mode (default)'
324 def check_group(self,group,w): pass
326 if self.outputfile is None:
329 tmp_outputfile=self.outputfile+'~tmp~'
330 of=open(tmp_outputfile,'w')
332 if self.outputfile is not None:
333 os.rename(tmp_outputfile,self.outputfile)
335 class OpFilter(OpBase):
337 help = 'sites file filtering mode'
338 def positional_arXgs(self, av):
340 print("Too many arguments")
341 (self.inputfile,) = (av.arg + [None])[0:1]
342 self.outputfile = None
343 def write_out_heading(self,f):
344 f.write("# --filter --output-version=%d\n"%output_version)
345 def write_out_contents(self,f):
346 for i in self.inputlines: f.write(i)
348 class OpUserv(OpBase):
349 opts = ['--userv','-u']
350 help = 'userv service fragment update mode'
351 def positional_args(self, av):
353 print("Wrong number of arguments")
355 (self.header, self.groupfiledir,
356 self.outputfile, self.group) = av.arg
357 self.group = Tainted(self.group,0,'command line')
358 # untrusted argument from caller
359 if "USERV_USER" not in os.environ:
360 print("Environment variable USERV_USER not found")
362 self.user=os.environ["USERV_USER"]
363 # Check that group is in USERV_GROUP
364 if "USERV_GROUP" not in os.environ:
365 print("Environment variable USERV_GROUP not found")
367 ugs=os.environ["USERV_GROUP"]
369 for i in ugs.split():
370 if self.group==i: ok=1
372 print("caller not in group %s"%group)
374 def check_group(self,group,w):
375 if group!=self.group: complain("Incorrect group!")
378 self.headerinput=pfilepath(self.header,allow_include=True)
379 self.userinput=sys.stdin.readlines()
380 pfile("user input",self.userinput)
382 # Put the user's input into their group file, and
383 # rebuild the main sites file
384 f=open(self.groupfiledir+"/T"+self.group.groupname(),'w')
385 f.write("# Section submitted by user %s, %s\n"%
386 (self.user,time.asctime(time.localtime(time.time()))))
387 f.write("# Checked by make-secnet-sites version %s\n\n"
389 for i in self.userinput: f.write(i)
392 os.rename(self.groupfiledir+"/T"+self.group.groupname(),
393 self.groupfiledir+"/R"+self.group.groupname())
394 OpBase.write_out(self)
395 def write_out_heading(self,f):
396 f.write("# generated %s, invoked by %s\n"%
397 (time.asctime(time.localtime(time.time())),
399 def write_out_contents(self,f):
400 for i in self.headerinput: f.write(i)
401 files=os.listdir(self.groupfiledir)
404 j=open(self.groupfiledir+"/"+i)
413 global output_version
417 ap = argparse.ArgumentParser(description='process secnet sites files')
419 ap.add_argument(*how().opts, action=ArgActionLambda,
421 fn=(lambda v,ns,*x: setattr(ns,'opmode',how)),
426 ap.add_argument('--conf-key-prefix', action=ActionNoYes,
428 help='prefix conf file key names derived from sites data')
430 ap.add_argument('--pubkeys-'+how().opt, action=ArgActionLambda,
432 fn=(lambda v,ns,*x: setattr(ns,'pkm',how)),
437 ap.add_argument('--pubkeys-dir', nargs=1,
438 help='public key directory',
439 default=['/var/lib/secnet/pubkeys'])
440 ap.add_argument('--output-version', nargs=1, type=int,
441 help='sites file output version',
442 default=[max_version])
443 ap.add_argument('--prefix', '-P', nargs=1,
445 ap.add_argument('--debug', '-D', action='count', default=0)
446 ap.add_argument('arg',nargs=argparse.REMAINDER)
448 debug_level = av.debug
450 opmode = getattr(av,'opmode',OpConf)()
451 prefix = '' if av.prefix is None else av.prefix[0]
452 key_prefix = av.conf_key_prefix
453 output_version = av.output_version[0]
454 pubkeys_dir = av.pubkeys_dir[0]
455 pubkeys_mode = getattr(av,'pkm',PkmSingle)
456 opmode.positional_args(av)
460 # Classes describing possible datatypes in the configuration file
463 "Common protocol for configuration types."
465 complain("%s %s already has property %s defined"%
466 (obj.type,obj.name,w[0].raw()))
467 def forsites(self,version,copy,fs):
471 "A list of some kind of configuration type."
472 def __init__(self,subtype,w):
474 self.list=[subtype(w)]
476 self.list.append(self.subtype(w))
478 return ', '.join(map(str, self.list))
479 def forsites(self,version,copy,fs):
480 most_recent=self.list[len(self.list)-1]
481 return most_recent.forsites(version,copy,fs)
483 return lambda w: conflist(subtype, w)
485 class single_ipaddr (basetype):
487 def __init__(self,w):
488 self.addr=ipaddress.ip_address(w[1].raw_mark_ok())
490 return '"%s"'%self.addr
492 class networks (basetype):
493 "A set of IP addresses specified as a list of networks"
494 def __init__(self,w):
495 self.set=ipaddrset.IPAddressSet()
497 x=ipaddress.ip_network(i.raw_mark_ok(),strict=True)
500 return ",".join(map((lambda n: '"%s"'%n), self.set.networks()))
502 class dhgroup (basetype):
503 "A Diffie-Hellman group"
504 def __init__(self,w):
505 self.mod=w[1].bignum_16('dh','dh mod')
506 self.gen=w[2].bignum_16('dh','dh gen')
508 return 'diffie-hellman("%s","%s")'%(self.mod,self.gen)
510 class hash (basetype):
511 "A choice of hash function"
512 def __init__(self,w):
515 if (self.ht not in ('md5', 'sha1', 'sha512')):
516 complain("unknown hash type %s"%(self.ht))
521 return '%s'%(self.ht)
523 class email (basetype):
525 def __init__(self,w):
526 self.addr=w[1].email()
528 return '<%s>'%(self.addr)
530 class boolean (basetype):
532 def __init__(self,w):
534 if re.match('[TtYy1]',v.raw()):
537 elif re.match('[FfNn0]',v.raw()):
541 complain("invalid boolean value");
543 return ['False','True'][self.b]
545 class num (basetype):
547 def __init__(self,w):
548 self.n=w[1].number(0,0x7fffffff)
552 class serial (basetype):
553 def __init__(self,w):
554 self.i=w[1].hexid(4,'serial')
557 def forsites(self,version,copy,fs):
558 if version < 2: return []
561 class address (basetype):
562 "A DNS name and UDP port number"
563 def __init__(self,w):
565 self.port=w[2].number(1,65536,'port')
567 return '"%s"; port %d'%(self.adr,self.port)
569 class inpub (basetype):
570 def forsites(self,version,xcopy,fs):
571 return self.forpub(version,fs)
573 class pubkey (inpub):
574 "Some kind of publie key"
575 def __init__(self,w):
576 self.a=w[1].name('algname')
577 self.d=w[2].base91();
579 return 'make-public("%s","%s")'%(self.a,self.d)
580 def forpub(self,version,fs):
581 if version < 2: return []
582 return ['pub', self.a, self.d]
583 def okforonlykey(self,version,fs):
584 return len(self.forpub(version,fs)) != 0
586 class rsakey (pubkey):
587 "An old-style RSA public key"
588 def __init__(self,w):
589 self.l=w[1].number(0,max['rsa_bits'],'rsa len')
590 self.e=w[2].bignum_10('rsa','rsa e')
591 self.n=w[3].bignum_10('rsa','rsa n')
592 if len(w) >= 5: w[4].email()
594 self.d=base91s_encode(b'%d %s %s' %
596 self.e.encode('ascii'),
597 self.n.encode('ascii')))
598 # ^ this allows us to use the pubkey.forsites()
599 # method for output in versions>=2
601 return 'rsa-public("%s","%s")'%(self.e,self.n)
602 # this specialisation means we can generate files
603 # compatible with old secnet executables
604 def forpub(self,version,fs):
606 if fs.pkg != '00000000': return []
607 return ['pubkey', str(self.l), self.e, self.n]
608 return pubkey.forpub(self,version,fs)
610 class rsakey_newfmt(rsakey):
611 "An old-style RSA public key in new-style sites format"
612 # This is its own class simply to have its own constructor.
613 def __init__(self,w):
615 assert(self.a == 'rsa1')
618 w_inner=list(map(Tainted,
620 base91s_decode(self.d)
623 except UnicodeDecodeError:
624 complain('rsa1 key in new format has bad base91')
625 #print(repr(w_inner), file=sys.stderr)
626 rsakey.__init__(self,w_inner)
628 class pubkey_group(inpub):
629 "Public key group introducer"
630 # appears in the site's list of keys mixed in with the keys
631 def __init__(self,w,fallback):
632 self.i=w[1].hexid(4,'pkg-id')
633 self.fallback=fallback
634 def forpub(self,version,fs):
636 if version < 2: return []
637 return ['pkgf' if self.fallback else 'pkg', self.i]
638 def okforonlykey(self,version,fs):
639 self.forpub(version,fs)
643 #print(repr(w), file=sys.stderr)
646 elif w[0]=='pub' and w[1]=='rsa1':
647 return rsakey_newfmt(w)
651 return pubkey_group(w,False)
653 return pubkey_group(w,True)
657 # Possible properties of configuration nodes
659 'contact':(email,"Contact address"),
660 'dh':(dhgroup,"Diffie-Hellman group"),
661 'hash':(hash,"Hash function"),
662 'key-lifetime':(num,"Maximum key lifetime (ms)"),
663 'setup-timeout':(num,"Key setup timeout (ms)"),
664 'setup-retries':(num,"Maximum key setup packet retries"),
665 'wait-time':(num,"Time to wait after unsuccessful key setup (ms)"),
666 'renegotiate-time':(num,"Time after key setup to begin renegotiation (ms)"),
667 'restrict-nets':(networks,"Allowable networks"),
668 'networks':(networks,"Claimed networks"),
669 'serial':(serial,"public key set serial"),
670 'pkg':(listof(somepubkey),"start of public key group",'pub'),
671 'pkgf':(listof(somepubkey),"start of fallback public key group",'pub'),
672 'pub':(listof(somepubkey),"new style public site key"),
673 'pubkey':(listof(somepubkey),"Old-style RSA public site key",'pub'),
674 'peer':(single_ipaddr,"Tunnel peer IP address"),
675 'address':(address,"External contact address and port"),
676 'mobile':(boolean,"Site is mobile"),
680 "Simply output a property - the default case"
681 return "%s %s;\n"%(name,value)
683 # All levels support these properties
685 'contact':(lambda name,value:"# Contact email address: %s\n"%(value)),
692 'renegotiate-time':sp,
693 'restrict-nets':(lambda name,value:"# restrict-nets %s\n"%value),
697 "A level in the configuration hierarchy"
701 require_properties={}
702 def __init__(self,w):
703 self.type=w[0].keyword()
704 self.name=w[1].name()
707 def indent(self,w,t):
709 def prop_out(self,n):
710 return self.allow_properties[n](n,str(self.properties[n]))
711 def output_props(self,w,ind):
712 for i in sorted(self.properties.keys()):
713 if self.allow_properties[i]:
715 w.write("%s"%self.prop_out(i))
717 return ((self.type[0].upper() if key_prefix else '')
719 def output_data(self,w,path):
722 w.write("%s {\n"%(self.kname()))
723 self.output_props(w,ind+2)
724 if self.depth==1: w.write("\n");
725 for k in sorted(self.children.keys()):
727 c.output_data(w,path+(c,))
731 class vpnlevel(level):
732 "VPN level in the configuration hierarchy"
736 allow_properties=global_properties.copy()
738 'contact':"VPN admin contact address"
740 def __init__(self,w):
741 level.__init__(self,w)
742 def output_vpnflat(self,w,path):
743 "Output flattened list of site names for this VPN"
746 w.write("%s {\n"%(self.kname()))
747 for i in self.children.keys():
748 self.children[i].output_vpnflat(w,path+(self,))
751 w.write("all-sites %s;\n"%
752 ','.join(map(lambda i: i.kname(),
753 self.children.values())))
757 class locationlevel(level):
758 "Location level in the configuration hierarchy"
762 allow_properties=global_properties.copy()
764 'contact':"Location admin contact address",
766 def __init__(self,w):
767 level.__init__(self,w)
768 self.group=w[2].groupname()
769 def output_vpnflat(self,w,path):
772 # The "path=path,self=self" abomination below exists because
773 # Python didn't support nested_scopes until version 2.1
776 w.write("%s %s;\n"%(self.kname(),','.join(
777 map(lambda x,path=path,self=self:
778 '/'.join([prefix+"vpn-data"] + list(map(
781 self.children.values()))))
783 class sitelevel(level):
784 "Site level (i.e. a leafnode) in the configuration hierarchy"
788 allow_properties=global_properties.copy()
789 allow_properties.update({
801 'dh':"Diffie-Hellman group",
802 'contact':"Site admin contact address",
803 'networks':"Networks claimed by the site",
804 'hash':"hash function",
805 'peer':"Gateway address of the site",
807 def mangle_name(self):
808 return self.name.replace('/',',')
809 def pubkeys_path(self):
810 return pubkeys_dir + '/peer.' + self.mangle_name()
811 def __init__(self,w):
812 level.__init__(self,w)
813 def output_data(self,w,path):
815 np='/'.join(map(lambda i: i.name, path))
817 w.write("%s {\n"%(self.kname()))
819 w.write("name \"%s\";\n"%(np,))
823 debugrepr('pkm ',pkm)
824 pkm.site_start(self.pubkeys_path())
825 if 'serial' in self.properties:
826 pkm.site_serial(self.properties['serial'])
828 for k in self.properties["pub"].list:
829 debugrepr('pubkeys ', k)
834 self.output_props(w,ind+2)
836 w.write("link netlink {\n");
838 w.write("routes %s;\n"%str(self.properties["networks"]))
840 w.write("ptp-address %s;\n"%str(self.properties["peer"]))
846 # Levels in the configuration file
848 levels={'vpn':vpnlevel, 'location':locationlevel, 'site':sitelevel}
851 "Complain about a particular input line"
852 moan(("%s line %d: "%(file,line))+msg)
854 "Complain about something in general"
857 if complaints is None: sys.exit(1)
858 complaints=complaints+1
860 class UntaintedRoot():
861 def __init__(self,s): self._s=s
862 def name(self): return self._s
863 def keyword(self): return self._s
865 root=level([UntaintedRoot(x) for x in ['root','root']])
866 # All vpns are children of this node
868 allow_defs=0 # Level above which new definitions are permitted
870 def set_property(obj,w):
871 "Set a property on a configuration node"
873 propname=prop.raw_mark_ok()
874 kw=keywords[propname]
875 if len(kw) >= 3: propname=kw[2] # for aliases
876 if propname in obj.properties:
877 obj.properties[propname].add(obj,w)
879 obj.properties[propname]=kw[0](w)
880 return obj.properties[propname]
886 # called when we enter a new node,
887 # in particular, at the start of each site
888 self.pkg = '00000000'
890 def pline(il,filterstate,allow_include=False):
891 "Process a configuration file line"
892 global allow_defs, obstack, root
893 w=il.rstrip('\n').split()
894 if len(w)==0: return ['']
895 w=list([Tainted(x) for x in w])
897 current=obstack[len(obstack)-1]
898 copyout_core=lambda: ' '.join([ww.output() for ww in w])
899 indent=' '*len(obstack)
900 copyout=lambda: [indent + copyout_core() + '\n']
901 if keyword=='end-definitions':
902 keyword.raw_mark_ok()
903 allow_defs=sitelevel.depth
906 if keyword=='include':
907 if not allow_include:
908 complain("include not permitted here")
911 complain("include requires one argument")
913 newfile=os.path.join(os.path.dirname(file),w[1].raw_mark_ok())
914 # ^ user of "include" is trusted so raw_mark_ok is good
915 return pfilepath(newfile,allow_include=allow_include)
916 if keyword.raw() in levels:
917 # We may go up any number of levels, but only down by one
918 newdepth=levels[keyword.raw_mark_ok()].depth
919 currentdepth=len(obstack) # actually +1...
920 if newdepth<=currentdepth:
921 obstack=obstack[:newdepth]
922 if newdepth>currentdepth:
923 complain("May not go from level %d to level %d"%
924 (currentdepth-1,newdepth))
925 # See if it's a new one (and whether that's permitted)
927 current=obstack[len(obstack)-1]
929 if tname in current.children:
931 current=current.children[tname]
933 opmode.check_group(current.group, w)
936 # Ignore depth check for now
937 nl=levels[keyword.raw()](w)
938 if nl.depth<allow_defs:
939 complain("New definitions not allowed at "
941 # we risk crashing if we continue
943 current.children[tname]=nl
946 obstack.append(current)
948 if keyword.raw() not in current.allow_properties:
949 complain("Property %s not allowed at %s level"%
950 (keyword.raw(),current.type))
952 elif current.depth == vpnlevel.depth < allow_defs:
953 complain("Not allowed to set VPN properties here")
956 prop=set_property(current,w)
958 out=prop.forsites(output_version,out,filterstate)
959 if len(out)==0: return [indent + '#', copyout_core(), '\n']
960 return [indent + ' '.join(out) + '\n']
962 complain("unknown keyword '%s'"%(keyword.raw()))
964 def pfilepath(pathname,allow_include=False):
966 outlines=pfile(pathname,f.readlines(),allow_include=allow_include)
970 def pfile(name,lines,allow_include=False):
976 filterstate = FilterState()
979 if (i[0]=='#'): continue
980 outlines += pline(i,filterstate,allow_include=allow_include)
984 "Output include file for secnet configuration"
985 w.write("# secnet sites file autogenerated by make-secnet-sites "
986 +"version %s\n"%VERSION)
987 w.write("# %s\n"%time.asctime(time.localtime(time.time())))
988 w.write("# Command line: %s\n\n"%' '.join(sys.argv))
990 # Raw VPN data section of file
991 w.write(prefix+"vpn-data {\n")
992 for i in root.children.values():
993 i.output_data(w,(i,))
996 # Per-VPN flattened lists
997 w.write(prefix+"vpn {\n")
998 for i in root.children.values():
999 i.output_vpnflat(w,())
1002 # Flattened list of sites
1003 w.write(prefix+"all-sites %s;\n"%",".join(
1004 map(lambda x:"%svpn/%s/all-sites"%(prefix,x.kname()),
1005 root.children.values())))
1011 # Sanity check section
1012 # Delete nodes where leaf=0 that have no children
1015 "Number of leafnodes below node n"
1017 for i in n.children.keys():
1018 if live(n.children[i]): return 1
1021 "Delete nodes that have no leafnode children"
1022 for i in list(n.children.keys()):
1023 delempty(n.children[i])
1024 if not live(n.children[i]):
1027 # Check that all constraints are met (as far as I can tell
1028 # restrict-nets/networks/peer are the only special cases)
1030 def checkconstraints(n,p,ra):
1032 new_p.update(n.properties)
1033 for i in n.require_properties.keys():
1035 moan("%s %s is missing property %s"%
1037 for i in new_p.keys():
1038 if i not in n.allow_properties:
1039 moan("%s %s has forbidden property %s"%
1041 # Check address range restrictions
1042 if "restrict-nets" in n.properties:
1043 new_ra=ra.intersection(n.properties["restrict-nets"].set)
1046 if "networks" in n.properties:
1047 if not n.properties["networks"].set <= new_ra:
1048 moan("%s %s networks out of bounds"%(n.type,n.name))
1049 if "peer" in n.properties:
1050 if not n.properties["networks"].set.contains(
1051 n.properties["peer"].addr):
1052 moan("%s %s peer not in networks"%(n.type,n.name))
1053 for i in n.children.keys():
1054 checkconstraints(n.children[i],new_p,new_ra)
1059 checkconstraints(root,{},ipaddrset.complete_set())
1062 if complaints==1: print("There was 1 problem.")
1063 else: print("There were %d problems."%(complaints))
1065 complaints=None # arranges to crash if we complain later