chiark / gitweb /
make-secnet-sites: Support `pkg' and `pkgf'
[secnet.git] / make-secnet-sites
1 #! /usr/bin/env python3
2 #
3 # This file is part of secnet.
4 # See README for full list of copyright holders.
5 #
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.
10
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.
15
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.
19
20 """VPN sites file manipulation.
21
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.
25
26 A database file can be turned into a secnet configuration file simply:
27 make-secnet-sites.py [infile [outfile]]
28
29 It would be wise to run secnet with the "--just-check-config" option
30 before installing the output on a live system.
31
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:
35
36 make-secnet-sites.py -u header-filename groupfiles-directory output-file \
37   group
38
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
41 fragment is:
42
43 reset
44 no-disconnect-hup
45 no-suppress-args
46 cd ~/secnet/sites-test/
47 execute ~/secnet/make-secnet-sites.py -u vpnheader groupfiles sites
48
49 This program is part of secnet.
50
51 """
52
53 from __future__ import print_function
54 from __future__ import unicode_literals
55 from builtins import int
56
57 import string
58 import time
59 import sys
60 import os
61 import getopt
62 import re
63 import argparse
64 import math
65
66 import ipaddress
67
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")
72 import ipaddrset
73 import base91
74
75 from argparseactionnoyes import ActionNoYes
76
77 VERSION="0.1.18"
78
79 max_version = 2
80
81 from sys import version_info
82 if version_info.major == 2:  # for python2
83     import codecs
84     sys.stdin = codecs.getreader('utf-8')(sys.stdin)
85     sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
86     import io
87     open=lambda f,m='r': io.open(f,m,encoding='utf-8')
88
89 max={'rsa_bits':8200,'name':33,'dh_bits':8200,'algname':127}
90
91 def debugrepr(*args):
92         if debug_level > 0:
93                 print(repr(args), file=sys.stderr)
94
95 def base91s_encode(bindata):
96         return base91.encode(bindata).replace('"',"-")
97
98 def base91s_decode(string):
99         return base91.decode(string.replace("-",'"'))
100
101 class Tainted:
102         def __init__(self,s,tline=None,tfile=None):
103                 self._s=s
104                 self._ok=None
105                 self._line=line if tline is None else tline
106                 self._file=file if tfile is None else tfile
107         def __eq__(self,e):
108                 return self._s==e
109         def __ne__(self,e):
110                 # for Python2
111                 return not self.__eq__(e)
112         def __str__(self):
113                 raise RuntimeError('direct use of Tainted value')
114         def __repr__(self):
115                 return 'Tainted(%s)' % repr(self._s)
116
117         def _bad(self,what,why):
118                 assert(self._ok is not True)
119                 self._ok=False
120                 complain('bad parameter: %s: %s' % (what, why))
121                 return False
122
123         def _max_ok(self,what,maxlen):
124                 if len(self._s) > maxlen:
125                         return self._bad(what,'too long (max %d)' % maxlen)
126                 return True
127
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')
135                 return True
136
137         def _rtnval(self, is_ok, ifgood, ifbad=''):
138                 if is_ok:
139                         assert(self._ok is not False)
140                         self._ok=True
141                         return ifgood
142                 else:
143                         assert(self._ok is not True)
144                         self._ok=False
145                         return ifbad
146
147         def _rtn(self, is_ok, ifbad=''):
148                 return self._rtnval(is_ok, self._s, ifbad)
149
150         def raw(self):
151                 return self._s
152         def raw_mark_ok(self):
153                 # caller promises to throw if syntax was dangeorus
154                 return self._rtn(True)
155
156         def output(self):
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),
161                       file=sys.stderr)
162                 sys.exit(1)
163
164         bad_name=re.compile(r'^[^a-zA-Z]|[^-_0-9a-zA-Z]')
165         # secnet accepts _ at start of names, but we reserve that
166         bad_name_counter=0
167         def name(self,what='name'):
168                 ok=self._re_ok(Tainted.bad_name,what)
169                 return self._rtn(ok,
170                                  '_line%d_%s' % (self._line, id(self)))
171
172         def keyword(self):
173                 ok=self._s in keywords or self._s in levels
174                 if not ok:
175                         complain('unknown keyword %s' % self._s)
176                 return self._rtn(ok)
177
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)
182                 return self._rtn(ok)
183
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)
188                 return self._rtn(ok)
189
190         def number(self,minn,maxx,what='number'):
191                 # not for bignums
192                 ok=self._re_ok(Tainted.bad_num,what,10)
193                 if ok:
194                         v=int(self._s)
195                         if v<minn or v>maxx:
196                                 ok=self._bad(what,'out of range %d..%d'
197                                              % (minn,maxx))
198                 return self._rtnval(ok,v,minn)
199
200         def hexid(self,byteslen,what):
201                 ok=self._re_ok(Tainted.bad_hex,what,byteslen*2)
202                 if ok:
203                         if len(self._s) < byteslen*2:
204                                 ok=self._bad(what,'too short')
205                 return self._rtn(ok,ifbad='00'*byteslen)
206
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.
212         def host(self):
213                 ok=self._re_ok(Tainted.bad_host,'host/address',255)
214                 return self._rtn(ok)
215
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).
221         def email(self):
222                 ok=self._re_ok(Tainted.bad_email,'email address',1023)
223                 return self._rtn(ok)
224
225         bad_groupname=re.compile(r'^[^_A-Za-z]|[^-+_0-9A-Za-z]')
226         def groupname(self):
227                 ok=self._re_ok(Tainted.bad_groupname,'group name',64)
228                 return self._rtn(ok)
229
230         bad_base91=re.compile(r'[^!-~]|[\'\"\\]')
231         def base91(self,what='base91'):
232                 ok=self._re_ok(Tainted.bad_base91,what,4096)
233                 return self._rtn(ok)
234
235 class ArgActionLambda(argparse.Action):
236         def __init__(self, fn, **kwargs):
237                 self.fn=fn
238                 argparse.Action.__init__(self,**kwargs)
239         def __call__(self,ap,ns,values,option_string):
240                 self.fn(values,ns,ap,option_string)
241
242 def parse_args():
243         global service
244         global inputfile
245         global header
246         global groupfiledir
247         global sitesfile
248         global outputfile
249         global group
250         global user
251         global of
252         global prefix
253         global key_prefix
254         global debug_level
255         global output_version
256         global pubkeys_dir
257         global pubkeys_install
258
259         ap = argparse.ArgumentParser(description='process secnet sites files')
260         ap.add_argument('--userv', '-u', action='store_true',
261                         help='userv service fragment update mode')
262         ap.add_argument('--conf-key-prefix', action=ActionNoYes,
263                         default=True,
264                  help='prefix conf file key names derived from sites data')
265         ap.add_argument('--pubkeys-install', action='store_true',
266                         help='install public keys in public key directory')
267         ap.add_argument('--pubkeys-dir',  nargs=1,
268                         help='public key directory',
269                         default=['/var/lib/secnet/pubkeys'])
270         ap.add_argument('--output-version', nargs=1, type=int,
271                         help='sites file output version',
272                         default=[max_version])
273         ap.add_argument('--prefix', '-P', nargs=1,
274                         help='set prefix')
275         ap.add_argument('--debug', '-D', action='count', default=0)
276         ap.add_argument('arg',nargs=argparse.REMAINDER)
277         av = ap.parse_args()
278         debug_level = av.debug
279         debugrepr('av',av)
280         service = 1 if av.userv else 0
281         prefix = '' if av.prefix is None else av.prefix[0]
282         key_prefix = av.conf_key_prefix
283         output_version = av.output_version[0]
284         pubkeys_dir = av.pubkeys_dir[0]
285         pubkeys_install = av.pubkeys_install
286         if service:
287                 if len(av.arg)!=4:
288                         print("Wrong number of arguments")
289                         sys.exit(1)
290                 (header, groupfiledir, sitesfile, group) = av.arg
291                 group = Tainted(group,0,'command line')
292                 # untrusted argument from caller
293                 if "USERV_USER" not in os.environ:
294                         print("Environment variable USERV_USER not found")
295                         sys.exit(1)
296                 user=os.environ["USERV_USER"]
297                 # Check that group is in USERV_GROUP
298                 if "USERV_GROUP" not in os.environ:
299                         print("Environment variable USERV_GROUP not found")
300                         sys.exit(1)
301                 ugs=os.environ["USERV_GROUP"]
302                 ok=0
303                 for i in ugs.split():
304                         if group==i: ok=1
305                 if not ok:
306                         print("caller not in group %s"%group)
307                         sys.exit(1)
308         else:
309                 if len(av.arg)>3:
310                         print("Too many arguments")
311                         sys.exit(1)
312                 (inputfile, outputfile) = (av.arg + [None]*2)[0:2]
313
314 parse_args()
315
316 # Classes describing possible datatypes in the configuration file
317
318 class basetype:
319         "Common protocol for configuration types."
320         def add(self,obj,w):
321                 complain("%s %s already has property %s defined"%
322                         (obj.type,obj.name,w[0].raw()))
323         def forsites(self,version,copy,fs):
324                 return copy
325
326 class conflist:
327         "A list of some kind of configuration type."
328         def __init__(self,subtype,w):
329                 self.subtype=subtype
330                 self.list=[subtype(w)]
331         def add(self,obj,w):
332                 self.list.append(self.subtype(w))
333         def __str__(self):
334                 return ', '.join(map(str, self.list))
335         def forsites(self,version,copy,fs):
336                 most_recent=self.list[len(self.list)-1]
337                 return most_recent.forsites(version,copy,fs)
338 def listof(subtype):
339         return lambda w: conflist(subtype, w)
340
341 class single_ipaddr (basetype):
342         "An IP address"
343         def __init__(self,w):
344                 self.addr=ipaddress.ip_address(w[1].raw_mark_ok())
345         def __str__(self):
346                 return '"%s"'%self.addr
347
348 class networks (basetype):
349         "A set of IP addresses specified as a list of networks"
350         def __init__(self,w):
351                 self.set=ipaddrset.IPAddressSet()
352                 for i in w[1:]:
353                         x=ipaddress.ip_network(i.raw_mark_ok(),strict=True)
354                         self.set.append([x])
355         def __str__(self):
356                 return ",".join(map((lambda n: '"%s"'%n), self.set.networks()))
357
358 class dhgroup (basetype):
359         "A Diffie-Hellman group"
360         def __init__(self,w):
361                 self.mod=w[1].bignum_16('dh','dh mod')
362                 self.gen=w[2].bignum_16('dh','dh gen')
363         def __str__(self):
364                 return 'diffie-hellman("%s","%s")'%(self.mod,self.gen)
365
366 class hash (basetype):
367         "A choice of hash function"
368         def __init__(self,w):
369                 hname=w[1]
370                 self.ht=hname.raw()
371                 if (self.ht!='md5' and self.ht!='sha1'):
372                         complain("unknown hash type %s"%(self.ht))
373                         self.ht=None
374                 else:
375                         hname.raw_mark_ok()
376         def __str__(self):
377                 return '%s'%(self.ht)
378
379 class email (basetype):
380         "An email address"
381         def __init__(self,w):
382                 self.addr=w[1].email()
383         def __str__(self):
384                 return '<%s>'%(self.addr)
385
386 class boolean (basetype):
387         "A boolean"
388         def __init__(self,w):
389                 v=w[1]
390                 if re.match('[TtYy1]',v.raw()):
391                         self.b=True
392                         v.raw_mark_ok()
393                 elif re.match('[FfNn0]',v.raw()):
394                         self.b=False
395                         v.raw_mark_ok()
396                 else:
397                         complain("invalid boolean value");
398         def __str__(self):
399                 return ['False','True'][self.b]
400
401 class num (basetype):
402         "A decimal number"
403         def __init__(self,w):
404                 self.n=w[1].number(0,0x7fffffff)
405         def __str__(self):
406                 return '%d'%(self.n)
407
408 class serial (basetype):
409         def __init__(self,w):
410                 self.i=w[1].hexid(4,'serial')
411         def __str__(self):
412                 return self.i
413         def forsites(self,version,copy,fs):
414                 if version < 2: return []
415                 return copy
416
417 class address (basetype):
418         "A DNS name and UDP port number"
419         def __init__(self,w):
420                 self.adr=w[1].host()
421                 self.port=w[2].number(1,65536,'port')
422         def __str__(self):
423                 return '"%s"; port %d'%(self.adr,self.port)
424
425 class pubkey (basetype):
426         "Some kind of publie key"
427         def __init__(self,w):
428                 self.a=w[1].name('algname')
429                 self.d=w[2].base91();
430         def __str__(self):
431                 return 'make-public("%s","%s")'%(self.a,self.d)
432         def forsites(self,version,xcopy,fs):
433                 if version < 2: return []
434                 return ['pub', self.a, self.d]
435         # forsites for properties which are from
436         # keywords with kw[2]=='pub' may not use copy.
437         # This is because the property values can be
438         # written out in sites file format during sites.conf
439         # construction (with --pubkeys-install), in which case
440         # the original input line is no longer available.
441
442 class rsakey (pubkey):
443         "An RSA public key"
444         def __init__(self,w):
445                 self.l=w[1].number(0,max['rsa_bits'],'rsa len')
446                 self.e=w[2].bignum_10('rsa','rsa e')
447                 self.n=w[3].bignum_10('rsa','rsa n')
448                 if len(w) >= 5: w[4].email()
449                 self.a='rsa1'
450                 self.d=base91s_encode(b'%d %s %s' %
451                                       (self.l,
452                                        self.e.encode('ascii'),
453                                        self.n.encode('ascii')))
454                 # ^ this allows us to use the pubkey.forsites()
455                 # method for output in versions>=2
456         def __str__(self):
457                 return 'rsa-public("%s","%s")'%(self.e,self.n)
458                 # this specialisation means we can generate files
459                 # compatible with old secnet executables
460         def forsites(self,version,xcopy,fs):
461                 if version < 2:
462                         return ['pubkey', str(self.l), self.e, self.n]
463                 return pubkey.forsites(self,version,xcopy,fs)
464
465 class rsakey_newfmt(rsakey):
466         "An old-style RSA public key in new-style sites format"
467         # This is its own class simply to have its own constructor.
468         def __init__(self,w):
469                 self.a=w[1].name()
470                 assert(self.a == 'rsa1')
471                 self.d=w[2].base91()
472                 try:
473                         w_inner=list(map(Tainted,
474                                         ['X-PUB-RSA1'] +
475                                         base91s_decode(self.d)
476                                         .decode('ascii')
477                                         .split(' ')))
478                 except UnicodeDecodeError:
479                         complain('rsa1 key in new format has bad base91')
480                 #print(repr(w_inner), file=sys.stderr)
481                 rsakey.__init__(self,w_inner)
482
483 class pubkey_group(basetype):
484         "Public key group introducer"
485         # appears in the site's list of keys mixed in with the keys
486         def __init__(self,w,fallback):
487                 self.i=w[1].hexid(4,'pkg-id')
488                 self.fallback=fallback
489         def forsites(self,version,xcopy,fs):
490                 fs.pkg=self.i
491                 if version < 2: return []
492                 return ['pkgf' if self.fallback else 'pkg', self.i]
493         
494 def somepubkey(w):
495         #print(repr(w), file=sys.stderr)
496         if w[0]=='pubkey':
497                 return rsakey(w)
498         elif w[0]=='pub' and w[1]=='rsa1':
499                 return rsakey_newfmt(w)
500         elif w[0]=='pub':
501                 return pubkey(w)
502         elif w[0]=='pkg':
503                 return pubkey_group(w,False)
504         elif w[0]=='pkgf':
505                 return pubkey_group(w,True)
506         else:
507                 assert(False)
508
509 # Possible properties of configuration nodes
510 keywords={
511  'contact':(email,"Contact address"),
512  'dh':(dhgroup,"Diffie-Hellman group"),
513  'hash':(hash,"Hash function"),
514  'key-lifetime':(num,"Maximum key lifetime (ms)"),
515  'setup-timeout':(num,"Key setup timeout (ms)"),
516  'setup-retries':(num,"Maximum key setup packet retries"),
517  'wait-time':(num,"Time to wait after unsuccessful key setup (ms)"),
518  'renegotiate-time':(num,"Time after key setup to begin renegotiation (ms)"),
519  'restrict-nets':(networks,"Allowable networks"),
520  'networks':(networks,"Claimed networks"),
521  'serial':(serial,"public key set serial"),
522  'pkg':(listof(somepubkey),"start of public key group",'pub'),
523  'pkgf':(listof(somepubkey),"start of fallback public key group",'pub'),
524  'pub':(listof(somepubkey),"new style public site key"),
525  'pubkey':(listof(somepubkey),"RSA public site key",'pub'),
526  'peer':(single_ipaddr,"Tunnel peer IP address"),
527  'address':(address,"External contact address and port"),
528  'mobile':(boolean,"Site is mobile"),
529 }
530
531 def sp(name,value):
532         "Simply output a property - the default case"
533         return "%s %s;\n"%(name,value)
534
535 # All levels support these properties
536 global_properties={
537         'contact':(lambda name,value:"# Contact email address: %s\n"%(value)),
538         'dh':sp,
539         'hash':sp,
540         'key-lifetime':sp,
541         'setup-timeout':sp,
542         'setup-retries':sp,
543         'wait-time':sp,
544         'renegotiate-time':sp,
545         'restrict-nets':(lambda name,value:"# restrict-nets %s\n"%value),
546 }
547
548 class level:
549         "A level in the configuration hierarchy"
550         depth=0
551         leaf=0
552         allow_properties={}
553         require_properties={}
554         def __init__(self,w):
555                 self.type=w[0].keyword()
556                 self.name=w[1].name()
557                 self.properties={}
558                 self.children={}
559         def indent(self,w,t):
560                 w.write("                 "[:t])
561         def prop_out(self,n):
562                 return self.allow_properties[n](n,str(self.properties[n]))
563         def output_props(self,w,ind):
564                 for i in sorted(self.properties.keys()):
565                         if self.allow_properties[i]:
566                                 self.indent(w,ind)
567                                 w.write("%s"%self.prop_out(i))
568         def kname(self):
569                 return ((self.type[0].upper() if key_prefix else '')
570                         + self.name)
571         def output_data(self,w,path):
572                 ind = 2*len(path)
573                 self.indent(w,ind)
574                 w.write("%s {\n"%(self.kname()))
575                 self.output_props(w,ind+2)
576                 if self.depth==1: w.write("\n");
577                 for k in sorted(self.children.keys()):
578                         c=self.children[k]
579                         c.output_data(w,path+(c,))
580                 self.indent(w,ind)
581                 w.write("};\n")
582
583 class vpnlevel(level):
584         "VPN level in the configuration hierarchy"
585         depth=1
586         leaf=0
587         type="vpn"
588         allow_properties=global_properties.copy()
589         require_properties={
590          'contact':"VPN admin contact address"
591         }
592         def __init__(self,w):
593                 level.__init__(self,w)
594         def output_vpnflat(self,w,path):
595                 "Output flattened list of site names for this VPN"
596                 ind=2*(len(path)+1)
597                 self.indent(w,ind)
598                 w.write("%s {\n"%(self.kname()))
599                 for i in self.children.keys():
600                         self.children[i].output_vpnflat(w,path+(self,))
601                 w.write("\n")
602                 self.indent(w,ind+2)
603                 w.write("all-sites %s;\n"%
604                         ','.join(map(lambda i: i.kname(),
605                                      self.children.values())))
606                 self.indent(w,ind)
607                 w.write("};\n")
608
609 class locationlevel(level):
610         "Location level in the configuration hierarchy"
611         depth=2
612         leaf=0
613         type="location"
614         allow_properties=global_properties.copy()
615         require_properties={
616          'contact':"Location admin contact address",
617         }
618         def __init__(self,w):
619                 level.__init__(self,w)
620                 self.group=w[2].groupname()
621         def output_vpnflat(self,w,path):
622                 ind=2*(len(path)+1)
623                 self.indent(w,ind)
624                 # The "path=path,self=self" abomination below exists because
625                 # Python didn't support nested_scopes until version 2.1
626                 #
627                 #"/"+self.name+"/"+i
628                 w.write("%s %s;\n"%(self.kname(),','.join(
629                         map(lambda x,path=path,self=self:
630                             '/'.join([prefix+"vpn-data"] + list(map(
631                                     lambda i: i.kname(),
632                                     path+(self,x)))),
633                             self.children.values()))))
634
635 class sitelevel(level):
636         "Site level (i.e. a leafnode) in the configuration hierarchy"
637         depth=3
638         leaf=1
639         type="site"
640         allow_properties=global_properties.copy()
641         allow_properties.update({
642          'address':sp,
643          'networks':None,
644          'peer':None,
645          'serial':None,
646          'pkg':None,
647          'pkgf':None,
648          'pub':None,
649          'pubkey':None,
650          'mobile':sp,
651         })
652         require_properties={
653          'dh':"Diffie-Hellman group",
654          'contact':"Site admin contact address",
655          'networks':"Networks claimed by the site",
656          'hash':"hash function",
657          'peer':"Gateway address of the site",
658         }
659         def mangle_name(self):
660                 return self.name.replace('/',',')
661         def pubkeys_path(self):
662                 return pubkeys_dir + '/peer.' + self.mangle_name()
663         def __init__(self,w):
664                 level.__init__(self,w)
665         def output_data(self,w,path):
666                 ind=2*len(path)
667                 np='/'.join(map(lambda i: i.name, path))
668                 self.indent(w,ind)
669                 w.write("%s {\n"%(self.kname()))
670                 self.indent(w,ind+2)
671                 w.write("name \"%s\";\n"%(np,))
672                 self.indent(w,ind+2)
673                 if pubkeys_install:
674                         pa=self.pubkeys_path()
675                         pw=open(pa+'~tmp','w')
676                         if 'serial' in self.properties:
677                                 pw.write('serial %s\n' %
678                                          self.properties['serial'])
679                         fs=FilterState()
680                         for k in self.properties["pub"].list:
681                                 debugrepr('pubkeys install', k)
682                                 wout=k.forsites(max_version,None,fs)
683                                 pw.write(' '.join(wout))
684                                 pw.write('\n')
685                         pw.close()
686                         os.rename(pa+'~tmp',pa+'~update')
687                         w.write("peer-keys \"%s\";\n"%pa);
688                 else:
689                         use = None
690                         indefault = True
691                         for k in self.properties["pub"].list:
692                                 debugrepr('pub write', (use,indefault,k))
693                                 if isinstance(k,pubkey):
694                                         if indefault:
695                                                 use = k
696                                                 break
697                                         if use is None:
698                                                 use = k
699                                 else:
700                                         raise RuntimeError('bad '+repr(k))
701                         if use is None:
702                                 complain("site with no public key");
703                         w.write("key %s;\n"%str(use))
704                 self.output_props(w,ind+2)
705                 self.indent(w,ind+2)
706                 w.write("link netlink {\n");
707                 self.indent(w,ind+4)
708                 w.write("routes %s;\n"%str(self.properties["networks"]))
709                 self.indent(w,ind+4)
710                 w.write("ptp-address %s;\n"%str(self.properties["peer"]))
711                 self.indent(w,ind+2)
712                 w.write("};\n")
713                 self.indent(w,ind)
714                 w.write("};\n")
715
716 # Levels in the configuration file
717 # (depth,properties)
718 levels={'vpn':vpnlevel, 'location':locationlevel, 'site':sitelevel}
719
720 def complain(msg):
721         "Complain about a particular input line"
722         moan(("%s line %d: "%(file,line))+msg)
723 def moan(msg):
724         "Complain about something in general"
725         global complaints
726         print(msg);
727         if complaints is None: sys.exit(1)
728         complaints=complaints+1
729
730 class UntaintedRoot():
731         def __init__(self,s): self._s=s
732         def name(self): return self._s
733         def keyword(self): return self._s
734
735 root=level([UntaintedRoot(x) for x in ['root','root']])
736 # All vpns are children of this node
737 obstack=[root]
738 allow_defs=0   # Level above which new definitions are permitted
739
740 def set_property(obj,w):
741         "Set a property on a configuration node"
742         prop=w[0]
743         propname=prop.raw_mark_ok()
744         kw=keywords[propname]
745         if len(kw) >= 3: propname=kw[2] # for aliases
746         if propname in obj.properties:
747                 obj.properties[propname].add(obj,w)
748         else:
749                 obj.properties[propname]=kw[0](w)
750         return obj.properties[propname]
751
752 class FilterState:
753         def __init__(self):
754                 self.reset()
755         def reset(self):
756                 # called when we enter a new node,
757                 # in particular, at the start of each site
758                 self.pkg = '00000000'
759
760 def pline(il,filterstate,allow_include=False):
761         "Process a configuration file line"
762         global allow_defs, obstack, root
763         w=il.rstrip('\n').split()
764         if len(w)==0: return ['']
765         w=list([Tainted(x) for x in w])
766         keyword=w[0]
767         current=obstack[len(obstack)-1]
768         copyout_core=lambda: ' '.join([ww.output() for ww in w])
769         indent='    '*len(obstack)
770         copyout=lambda: [indent + copyout_core() + '\n']
771         if keyword=='end-definitions':
772                 keyword.raw_mark_ok()
773                 allow_defs=sitelevel.depth
774                 obstack=[root]
775                 return copyout()
776         if keyword=='include':
777                 if not allow_include:
778                         complain("include not permitted here")
779                         return []
780                 if len(w) != 2:
781                         complain("include requires one argument")
782                         return []
783                 newfile=os.path.join(os.path.dirname(file),w[1].raw_mark_ok())
784                 # ^ user of "include" is trusted so raw_mark_ok is good
785                 return pfilepath(newfile,allow_include=allow_include)
786         if keyword.raw() in levels:
787                 # We may go up any number of levels, but only down by one
788                 newdepth=levels[keyword.raw_mark_ok()].depth
789                 currentdepth=len(obstack) # actually +1...
790                 if newdepth<=currentdepth:
791                         obstack=obstack[:newdepth]
792                 if newdepth>currentdepth:
793                         complain("May not go from level %d to level %d"%
794                                 (currentdepth-1,newdepth))
795                 # See if it's a new one (and whether that's permitted)
796                 # or an existing one
797                 current=obstack[len(obstack)-1]
798                 tname=w[1].name()
799                 if tname in current.children:
800                         # Not new
801                         current=current.children[tname]
802                         if service and group and current.depth==2:
803                                 if group!=current.group:
804                                         complain("Incorrect group!")
805                                 w[2].groupname()
806                 else:
807                         # New
808                         # Ignore depth check for now
809                         nl=levels[keyword.raw()](w)
810                         if nl.depth<allow_defs:
811                                 complain("New definitions not allowed at "
812                                         "level %d"%nl.depth)
813                                 # we risk crashing if we continue
814                                 sys.exit(1)
815                         current.children[tname]=nl
816                         current=nl
817                 filterstate.reset()
818                 obstack.append(current)
819                 return copyout()
820         if keyword.raw() not in current.allow_properties:
821                 complain("Property %s not allowed at %s level"%
822                         (keyword.raw(),current.type))
823                 return []
824         elif current.depth == vpnlevel.depth < allow_defs:
825                 complain("Not allowed to set VPN properties here")
826                 return []
827         else:
828                 prop=set_property(current,w)
829                 out=[copyout_core()]
830                 out=prop.forsites(output_version,out,filterstate)
831                 if len(out)==0: return [indent + '#', copyout_core(), '\n']
832                 return [indent + ' '.join(out) + '\n']
833
834         complain("unknown keyword '%s'"%(keyword.raw()))
835
836 def pfilepath(pathname,allow_include=False):
837         f=open(pathname)
838         outlines=pfile(pathname,f.readlines(),allow_include=allow_include)
839         f.close()
840         return outlines
841
842 def pfile(name,lines,allow_include=False):
843         "Process a file"
844         global file,line
845         file=name
846         line=0
847         outlines=[]
848         filterstate = FilterState()
849         for i in lines:
850                 line=line+1
851                 if (i[0]=='#'): continue
852                 outlines += pline(i,filterstate,allow_include=allow_include)
853         return outlines
854
855 def outputsites(w):
856         "Output include file for secnet configuration"
857         w.write("# secnet sites file autogenerated by make-secnet-sites "
858                 +"version %s\n"%VERSION)
859         w.write("# %s\n"%time.asctime(time.localtime(time.time())))
860         w.write("# Command line: %s\n\n"%' '.join(sys.argv))
861
862         # Raw VPN data section of file
863         w.write(prefix+"vpn-data {\n")
864         for i in root.children.values():
865                 i.output_data(w,(i,))
866         w.write("};\n")
867
868         # Per-VPN flattened lists
869         w.write(prefix+"vpn {\n")
870         for i in root.children.values():
871                 i.output_vpnflat(w,())
872         w.write("};\n")
873
874         # Flattened list of sites
875         w.write(prefix+"all-sites %s;\n"%",".join(
876                 map(lambda x:"%svpn/%s/all-sites"%(prefix,x.kname()),
877                         root.children.values())))
878
879 line=0
880 file=None
881 complaints=0
882
883 # Sanity check section
884 # Delete nodes where leaf=0 that have no children
885
886 def live(n):
887         "Number of leafnodes below node n"
888         if n.leaf: return 1
889         for i in n.children.keys():
890                 if live(n.children[i]): return 1
891         return 0
892 def delempty(n):
893         "Delete nodes that have no leafnode children"
894         for i in list(n.children.keys()):
895                 delempty(n.children[i])
896                 if not live(n.children[i]):
897                         del n.children[i]
898
899 # Check that all constraints are met (as far as I can tell
900 # restrict-nets/networks/peer are the only special cases)
901
902 def checkconstraints(n,p,ra):
903         new_p=p.copy()
904         new_p.update(n.properties)
905         for i in n.require_properties.keys():
906                 if i not in new_p:
907                         moan("%s %s is missing property %s"%
908                                 (n.type,n.name,i))
909         for i in new_p.keys():
910                 if i not in n.allow_properties:
911                         moan("%s %s has forbidden property %s"%
912                                 (n.type,n.name,i))
913         # Check address range restrictions
914         if "restrict-nets" in n.properties:
915                 new_ra=ra.intersection(n.properties["restrict-nets"].set)
916         else:
917                 new_ra=ra
918         if "networks" in n.properties:
919                 if not n.properties["networks"].set <= new_ra:
920                         moan("%s %s networks out of bounds"%(n.type,n.name))
921                 if "peer" in n.properties:
922                         if not n.properties["networks"].set.contains(
923                                 n.properties["peer"].addr):
924                                 moan("%s %s peer not in networks"%(n.type,n.name))
925         for i in n.children.keys():
926                 checkconstraints(n.children[i],new_p,new_ra)
927
928 if service:
929         headerinput=pfilepath(header,allow_include=True)
930         userinput=sys.stdin.readlines()
931         pfile("user input",userinput)
932 else:
933         if inputfile is None:
934                 pfile("stdin",sys.stdin.readlines())
935         else:
936                 pfilepath(inputfile)
937
938 delempty(root)
939 checkconstraints(root,{},ipaddrset.complete_set())
940
941 if complaints>0:
942         if complaints==1: print("There was 1 problem.")
943         else: print("There were %d problems."%(complaints))
944         sys.exit(1)
945 complaints=None # arranges to crash if we complain later
946
947 if service:
948         # Put the user's input into their group file, and rebuild the main
949         # sites file
950         f=open(groupfiledir+"/T"+group.groupname(),'w')
951         f.write("# Section submitted by user %s, %s\n"%
952                 (user,time.asctime(time.localtime(time.time()))))
953         f.write("# Checked by make-secnet-sites version %s\n\n"%VERSION)
954         for i in userinput: f.write(i)
955         f.write("\n")
956         f.close()
957         os.rename(groupfiledir+"/T"+group.groupname(),
958                   groupfiledir+"/R"+group.groupname())
959         f=open(sitesfile+"-tmp",'w')
960         f.write("# sites file autogenerated by make-secnet-sites\n")
961         f.write("# generated %s, invoked by %s\n"%
962                 (time.asctime(time.localtime(time.time())),user))
963         f.write("# use make-secnet-sites to turn this file into a\n")
964         f.write("# valid /etc/secnet/sites.conf file\n\n")
965         for i in headerinput: f.write(i)
966         files=os.listdir(groupfiledir)
967         for i in files:
968                 if i[0]=='R':
969                         j=open(groupfiledir+"/"+i)
970                         f.write(j.read())
971                         j.close()
972         f.write("# end of sites file\n")
973         f.close()
974         os.rename(sitesfile+"-tmp",sitesfile)
975 else:
976         if outputfile is None:
977                 of=sys.stdout
978         else:
979                 tmp_outputfile=outputfile+'~tmp~'
980                 of=open(tmp_outputfile,'w')
981         outputsites(of)
982         if outputfile is not None:
983                 os.rename(tmp_outputfile,outputfile)