chiark / gitweb /
make-secnet-sites: Put parens around print() statements
[secnet.git] / make-secnet-sites
1 #! /usr/bin/env python
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. It relies on the "ipaddr" library from
50 Cendio Systems AB.
51
52 """
53
54 from __future__ import print_function
55
56 import string
57 import time
58 import sys
59 import os
60 import getopt
61 import re
62
63 import ipaddr
64
65 sys.path.insert(0,"/usr/local/share/secnet")
66 sys.path.insert(0,"/usr/share/secnet")
67 import ipaddrset
68
69 VERSION="0.1.18"
70
71 # Are we being invoked from userv?
72 service=0
73 # If we are, which group does the caller want to modify?
74 group=None
75
76 if len(sys.argv)<2:
77         inputfile=None
78         of=sys.stdout
79 else:
80         if sys.argv[1]=='-u':
81                 if len(sys.argv)!=6:
82                         print("Wrong number of arguments")
83                         sys.exit(1)
84                 service=1
85                 header=sys.argv[2]
86                 groupfiledir=sys.argv[3]
87                 sitesfile=sys.argv[4]
88                 group=sys.argv[5]
89                 if not os.environ.has_key("USERV_USER"):
90                         print("Environment variable USERV_USER not found")
91                         sys.exit(1)
92                 user=os.environ["USERV_USER"]
93                 # Check that group is in USERV_GROUP
94                 if not os.environ.has_key("USERV_GROUP"):
95                         print("Environment variable USERV_GROUP not found")
96                         sys.exit(1)
97                 ugs=os.environ["USERV_GROUP"]
98                 ok=0
99                 for i in string.split(ugs):
100                         if group==i: ok=1
101                 if not ok:
102                         print("caller not in group %s"%group)
103                         sys.exit(1)
104         else:
105                 if sys.argv[1]=='-P':
106                         prefix=sys.argv[2]
107                         sys.argv[1:3]=[]
108                 if len(sys.argv)>3:
109                         print("Too many arguments")
110                         sys.exit(1)
111                 inputfile=sys.argv[1]
112                 of=sys.stdout
113                 if len(sys.argv)>2:
114                         of=open(sys.argv[2],'w')
115
116 # Classes describing possible datatypes in the configuration file
117
118 class basetype:
119         "Common protocol for configuration types."
120         def add(self,obj,w):
121                 complain("%s %s already has property %s defined"%
122                         (obj.type,obj.name,w[0]))
123
124 class conflist:
125         "A list of some kind of configuration type."
126         def __init__(self,subtype,w):
127                 self.subtype=subtype
128                 self.list=[subtype(w)]
129         def add(self,obj,w):
130                 self.list.append(self.subtype(w))
131         def __str__(self):
132                 return ', '.join(map(str, self.list))
133 def listof(subtype):
134         return lambda w: conflist(subtype, w)
135
136 class single_ipaddr (basetype):
137         "An IP address"
138         def __init__(self,w):
139                 self.addr=ipaddr.IPAddress(w[1])
140         def __str__(self):
141                 return '"%s"'%self.addr
142
143 class networks (basetype):
144         "A set of IP addresses specified as a list of networks"
145         def __init__(self,w):
146                 self.set=ipaddrset.IPAddressSet()
147                 for i in w[1:]:
148                         x=ipaddr.IPNetwork(i,strict=True)
149                         self.set.append([x])
150         def __str__(self):
151                 return ",".join(map((lambda n: '"%s"'%n), self.set.networks()))
152
153 class dhgroup (basetype):
154         "A Diffie-Hellman group"
155         def __init__(self,w):
156                 self.mod=w[1]
157                 self.gen=w[2]
158         def __str__(self):
159                 return 'diffie-hellman("%s","%s")'%(self.mod,self.gen)
160
161 class hash (basetype):
162         "A choice of hash function"
163         def __init__(self,w):
164                 self.ht=w[1]
165                 if (self.ht!='md5' and self.ht!='sha1'):
166                         complain("unknown hash type %s"%(self.ht))
167         def __str__(self):
168                 return '%s'%(self.ht)
169
170 class email (basetype):
171         "An email address"
172         def __init__(self,w):
173                 self.addr=w[1]
174         def __str__(self):
175                 return '<%s>'%(self.addr)
176
177 class boolean (basetype):
178         "A boolean"
179         def __init__(self,w):
180                 if re.match('[TtYy1]',w[1]):
181                         self.b=True
182                 elif re.match('[FfNn0]',w[1]):
183                         self.b=False
184                 else:
185                         complain("invalid boolean value");
186         def __str__(self):
187                 return ['False','True'][self.b]
188
189 class num (basetype):
190         "A decimal number"
191         def __init__(self,w):
192                 self.n=string.atol(w[1])
193         def __str__(self):
194                 return '%d'%(self.n)
195
196 class address (basetype):
197         "A DNS name and UDP port number"
198         def __init__(self,w):
199                 self.adr=w[1]
200                 self.port=string.atoi(w[2])
201                 if (self.port<1 or self.port>65535):
202                         complain("invalid port number")
203         def __str__(self):
204                 return '"%s"; port %d'%(self.adr,self.port)
205
206 class rsakey (basetype):
207         "An RSA public key"
208         def __init__(self,w):
209                 self.l=string.atoi(w[1])
210                 self.e=w[2]
211                 self.n=w[3]
212         def __str__(self):
213                 return 'rsa-public("%s","%s")'%(self.e,self.n)
214
215 # Possible properties of configuration nodes
216 keywords={
217  'contact':(email,"Contact address"),
218  'dh':(dhgroup,"Diffie-Hellman group"),
219  'hash':(hash,"Hash function"),
220  'key-lifetime':(num,"Maximum key lifetime (ms)"),
221  'setup-timeout':(num,"Key setup timeout (ms)"),
222  'setup-retries':(num,"Maximum key setup packet retries"),
223  'wait-time':(num,"Time to wait after unsuccessful key setup (ms)"),
224  'renegotiate-time':(num,"Time after key setup to begin renegotiation (ms)"),
225  'restrict-nets':(networks,"Allowable networks"),
226  'networks':(networks,"Claimed networks"),
227  'pubkey':(rsakey,"RSA public site key"),
228  'peer':(single_ipaddr,"Tunnel peer IP address"),
229  'address':(address,"External contact address and port"),
230  'mobile':(boolean,"Site is mobile"),
231 }
232
233 def sp(name,value):
234         "Simply output a property - the default case"
235         return "%s %s;\n"%(name,value)
236
237 # All levels support these properties
238 global_properties={
239         'contact':(lambda name,value:"# Contact email address: %s\n"%(value)),
240         'dh':sp,
241         'hash':sp,
242         'key-lifetime':sp,
243         'setup-timeout':sp,
244         'setup-retries':sp,
245         'wait-time':sp,
246         'renegotiate-time':sp,
247         'restrict-nets':(lambda name,value:"# restrict-nets %s\n"%value),
248 }
249
250 class level:
251         "A level in the configuration hierarchy"
252         depth=0
253         leaf=0
254         allow_properties={}
255         require_properties={}
256         def __init__(self,w):
257                 self.name=w[1]
258                 self.properties={}
259                 self.children={}
260         def indent(self,w,t):
261                 w.write("                 "[:t])
262         def prop_out(self,n):
263                 return self.allow_properties[n](n,str(self.properties[n]))
264         def output_props(self,w,ind):
265                 for i in self.properties.keys():
266                         if self.allow_properties[i]:
267                                 self.indent(w,ind)
268                                 w.write("%s"%self.prop_out(i))
269         def output_data(self,w,ind,np):
270                 self.indent(w,ind)
271                 w.write("%s {\n"%(self.name))
272                 self.output_props(w,ind+2)
273                 if self.depth==1: w.write("\n");
274                 for c in self.children.values():
275                         c.output_data(w,ind+2,np+self.name+"/")
276                 self.indent(w,ind)
277                 w.write("};\n")
278
279 class vpnlevel(level):
280         "VPN level in the configuration hierarchy"
281         depth=1
282         leaf=0
283         type="vpn"
284         allow_properties=global_properties.copy()
285         require_properties={
286          'contact':"VPN admin contact address"
287         }
288         def __init__(self,w):
289                 level.__init__(self,w)
290         def output_vpnflat(self,w,ind,h):
291                 "Output flattened list of site names for this VPN"
292                 self.indent(w,ind)
293                 w.write("%s {\n"%(self.name))
294                 for i in self.children.keys():
295                         self.children[i].output_vpnflat(w,ind+2,
296                                 h+"/"+self.name+"/"+i)
297                 w.write("\n")
298                 self.indent(w,ind+2)
299                 w.write("all-sites %s;\n"%
300                         string.join(self.children.keys(),','))
301                 self.indent(w,ind)
302                 w.write("};\n")
303
304 class locationlevel(level):
305         "Location level in the configuration hierarchy"
306         depth=2
307         leaf=0
308         type="location"
309         allow_properties=global_properties.copy()
310         require_properties={
311          'contact':"Location admin contact address",
312         }
313         def __init__(self,w):
314                 level.__init__(self,w)
315                 self.group=w[2]
316         def output_vpnflat(self,w,ind,h):
317                 self.indent(w,ind)
318                 # The "h=h,self=self" abomination below exists because
319                 # Python didn't support nested_scopes until version 2.1
320                 w.write("%s %s;\n"%(self.name,string.join(
321                         map(lambda x,h=h,self=self:
322                                 h+"/"+x,self.children.keys()),',')))
323
324 class sitelevel(level):
325         "Site level (i.e. a leafnode) in the configuration hierarchy"
326         depth=3
327         leaf=1
328         type="site"
329         allow_properties=global_properties.copy()
330         allow_properties.update({
331          'address':sp,
332          'networks':None,
333          'peer':None,
334          'pubkey':(lambda n,v:"key %s;\n"%v),
335          'mobile':sp,
336         })
337         require_properties={
338          'dh':"Diffie-Hellman group",
339          'contact':"Site admin contact address",
340          'networks':"Networks claimed by the site",
341          'hash':"hash function",
342          'peer':"Gateway address of the site",
343          'pubkey':"RSA public key of the site",
344         }
345         def __init__(self,w):
346                 level.__init__(self,w)
347         def output_data(self,w,ind,np):
348                 self.indent(w,ind)
349                 w.write("%s {\n"%(self.name))
350                 self.indent(w,ind+2)
351                 w.write("name \"%s\";\n"%(np+self.name))
352                 self.output_props(w,ind+2)
353                 self.indent(w,ind+2)
354                 w.write("link netlink {\n");
355                 self.indent(w,ind+4)
356                 w.write("routes %s;\n"%str(self.properties["networks"]))
357                 self.indent(w,ind+4)
358                 w.write("ptp-address %s;\n"%str(self.properties["peer"]))
359                 self.indent(w,ind+2)
360                 w.write("};\n")
361                 self.indent(w,ind)
362                 w.write("};\n")
363
364 # Levels in the configuration file
365 # (depth,properties)
366 levels={'vpn':vpnlevel, 'location':locationlevel, 'site':sitelevel}
367
368 # Reserved vpn/location/site names
369 reserved={'all-sites':None}
370 reserved.update(keywords)
371 reserved.update(levels)
372
373 def complain(msg):
374         "Complain about a particular input line"
375         global complaints
376         print(("%s line %d: "%(file,line))+msg)
377         complaints=complaints+1
378 def moan(msg):
379         "Complain about something in general"
380         global complaints
381         print(msg);
382         complaints=complaints+1
383
384 root=level(['root','root'])   # All vpns are children of this node
385 obstack=[root]
386 allow_defs=0   # Level above which new definitions are permitted
387 prefix=''
388
389 def set_property(obj,w):
390         "Set a property on a configuration node"
391         if obj.properties.has_key(w[0]):
392                 obj.properties[w[0]].add(obj,w)
393         else:
394                 obj.properties[w[0]]=keywords[w[0]][0](w)
395
396 def pline(i,allow_include=False):
397         "Process a configuration file line"
398         global allow_defs, obstack, root
399         w=string.split(i.rstrip('\n'))
400         if len(w)==0: return [i]
401         keyword=w[0]
402         current=obstack[len(obstack)-1]
403         if keyword=='end-definitions':
404                 allow_defs=sitelevel.depth
405                 obstack=[root]
406                 return [i]
407         if keyword=='include':
408                 if not allow_include:
409                         complain("include not permitted here")
410                         return []
411                 if len(w) != 2:
412                         complain("include requires one argument")
413                         return []
414                 newfile=os.path.join(os.path.dirname(file),w[1])
415                 return pfilepath(newfile,allow_include=allow_include)
416         if levels.has_key(keyword):
417                 # We may go up any number of levels, but only down by one
418                 newdepth=levels[keyword].depth
419                 currentdepth=len(obstack) # actually +1...
420                 if newdepth<=currentdepth:
421                         obstack=obstack[:newdepth]
422                 if newdepth>currentdepth:
423                         complain("May not go from level %d to level %d"%
424                                 (currentdepth-1,newdepth))
425                 # See if it's a new one (and whether that's permitted)
426                 # or an existing one
427                 current=obstack[len(obstack)-1]
428                 if current.children.has_key(w[1]):
429                         # Not new
430                         current=current.children[w[1]]
431                         if service and group and current.depth==2:
432                                 if group!=current.group:
433                                         complain("Incorrect group!")
434                 else:
435                         # New
436                         # Ignore depth check for now
437                         nl=levels[keyword](w)
438                         if nl.depth<allow_defs:
439                                 complain("New definitions not allowed at "
440                                         "level %d"%nl.depth)
441                                 # we risk crashing if we continue
442                                 sys.exit(1)
443                         current.children[w[1]]=nl
444                         current=nl
445                 obstack.append(current)
446                 return [i]
447         if not current.allow_properties.has_key(keyword):
448                 complain("Property %s not allowed at %s level"%
449                         (keyword,current.type))
450                 return []
451         elif current.depth == vpnlevel.depth < allow_defs:
452                 complain("Not allowed to set VPN properties here")
453                 return []
454         else:
455                 set_property(current,w)
456                 return [i]
457
458         complain("unknown keyword '%s'"%(keyword))
459
460 def pfilepath(pathname,allow_include=False):
461         f=open(pathname)
462         outlines=pfile(pathname,f.readlines(),allow_include=allow_include)
463         f.close()
464         return outlines
465
466 def pfile(name,lines,allow_include=False):
467         "Process a file"
468         global file,line
469         file=name
470         line=0
471         outlines=[]
472         for i in lines:
473                 line=line+1
474                 if (i[0]=='#'): continue
475                 outlines += pline(i,allow_include=allow_include)
476         return outlines
477
478 def outputsites(w):
479         "Output include file for secnet configuration"
480         w.write("# secnet sites file autogenerated by make-secnet-sites "
481                 +"version %s\n"%VERSION)
482         w.write("# %s\n"%time.asctime(time.localtime(time.time())))
483         w.write("# Command line: %s\n\n"%string.join(sys.argv))
484
485         # Raw VPN data section of file
486         w.write(prefix+"vpn-data {\n")
487         for i in root.children.values():
488                 i.output_data(w,2,"")
489         w.write("};\n")
490
491         # Per-VPN flattened lists
492         w.write(prefix+"vpn {\n")
493         for i in root.children.values():
494                 i.output_vpnflat(w,2,prefix+"vpn-data")
495         w.write("};\n")
496
497         # Flattened list of sites
498         w.write(prefix+"all-sites %s;\n"%string.join(
499                 map(lambda x:"%svpn/%s/all-sites"%(prefix,x),
500                         root.children.keys()),","))
501
502 line=0
503 file=None
504 complaints=0
505
506 # Sanity check section
507 # Delete nodes where leaf=0 that have no children
508
509 def live(n):
510         "Number of leafnodes below node n"
511         if n.leaf: return 1
512         for i in n.children.keys():
513                 if live(n.children[i]): return 1
514         return 0
515 def delempty(n):
516         "Delete nodes that have no leafnode children"
517         for i in n.children.keys():
518                 delempty(n.children[i])
519                 if not live(n.children[i]):
520                         del n.children[i]
521
522 # Check that all constraints are met (as far as I can tell
523 # restrict-nets/networks/peer are the only special cases)
524
525 def checkconstraints(n,p,ra):
526         new_p=p.copy()
527         new_p.update(n.properties)
528         for i in n.require_properties.keys():
529                 if not new_p.has_key(i):
530                         moan("%s %s is missing property %s"%
531                                 (n.type,n.name,i))
532         for i in new_p.keys():
533                 if not n.allow_properties.has_key(i):
534                         moan("%s %s has forbidden property %s"%
535                                 (n.type,n.name,i))
536         # Check address range restrictions
537         if n.properties.has_key("restrict-nets"):
538                 new_ra=ra.intersection(n.properties["restrict-nets"].set)
539         else:
540                 new_ra=ra
541         if n.properties.has_key("networks"):
542                 if not n.properties["networks"].set <= new_ra:
543                         moan("%s %s networks out of bounds"%(n.type,n.name))
544                 if n.properties.has_key("peer"):
545                         if not n.properties["networks"].set.contains(
546                                 n.properties["peer"].addr):
547                                 moan("%s %s peer not in networks"%(n.type,n.name))
548         for i in n.children.keys():
549                 checkconstraints(n.children[i],new_p,new_ra)
550
551 if service:
552         headerinput=pfilepath(header,allow_include=True)
553         userinput=sys.stdin.readlines()
554         pfile("user input",userinput)
555 else:
556         if inputfile is None:
557                 pfile("stdin",sys.stdin.readlines())
558         else:
559                 pfilepath(inputfile)
560
561 delempty(root)
562 checkconstraints(root,{},ipaddrset.complete_set())
563
564 if complaints>0:
565         if complaints==1: print("There was 1 problem.")
566         else: print("There were %d problems."%(complaints))
567         sys.exit(1)
568
569 if service:
570         # Put the user's input into their group file, and rebuild the main
571         # sites file
572         f=open(groupfiledir+"/T"+group,'w')
573         f.write("# Section submitted by user %s, %s\n"%
574                 (user,time.asctime(time.localtime(time.time()))))
575         f.write("# Checked by make-secnet-sites version %s\n\n"%VERSION)
576         for i in userinput: f.write(i)
577         f.write("\n")
578         f.close()
579         os.rename(groupfiledir+"/T"+group,groupfiledir+"/R"+group)
580         f=open(sitesfile+"-tmp",'w')
581         f.write("# sites file autogenerated by make-secnet-sites\n")
582         f.write("# generated %s, invoked by %s\n"%
583                 (time.asctime(time.localtime(time.time())),user))
584         f.write("# use make-secnet-sites to turn this file into a\n")
585         f.write("# valid /etc/secnet/sites.conf file\n\n")
586         for i in headerinput: f.write(i)
587         files=os.listdir(groupfiledir)
588         for i in files:
589                 if i[0]=='R':
590                         j=open(groupfiledir+"/"+i)
591                         f.write(j.read())
592                         j.close()
593         f.write("# end of sites file\n")
594         f.close()
595         os.rename(sitesfile+"-tmp",sitesfile)
596 else:
597         outputsites(of)