build system: More release checklist updates
[secnet] / make-secnet-sites
CommitLineData
3454dce4 1#! /usr/bin/env python
3b83c932 2# Copyright (C) 2001-2002 Stephen Early <steve@greenend.org.uk>
3454dce4
SE
3#
4# This program is free software; you can redistribute it and/or modify
5# it under the terms of the GNU General Public License as published by
6# the Free Software Foundation; either version 2 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program; if not, write to the Free Software
16# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
18"""VPN sites file manipulation.
19
20This program enables VPN site descriptions to be submitted for
21inclusion in a central database, and allows the resulting database to
22be turned into a secnet configuration file.
23
24A database file can be turned into a secnet configuration file simply:
25make-secnet-sites.py [infile [outfile]]
26
27It would be wise to run secnet with the "--just-check-config" option
28before installing the output on a live system.
29
30The program expects to be invoked via userv to manage the database; it
31relies on the USERV_USER and USERV_GROUP environment variables. The
32command line arguments for this invocation are:
33
34make-secnet-sites.py -u header-filename groupfiles-directory output-file \
35 group
36
37All but the last argument are expected to be set by userv; the 'group'
38argument is provided by the user. A suitable userv configuration file
39fragment is:
40
41reset
42no-disconnect-hup
43no-suppress-args
44cd ~/secnet/sites-test/
08f344d3 45execute ~/secnet/make-secnet-sites.py -u vpnheader groupfiles sites
3454dce4
SE
46
47This program is part of secnet. It relies on the "ipaddr" library from
48Cendio Systems AB.
49
50"""
51
52import string
53import time
54import sys
55import os
3b83c932 56import getopt
040040f3 57import re
8dea8d37 58
3b83c932 59# The ipaddr library is installed as part of secnet
8dea8d37
SE
60sys.path.append("/usr/local/share/secnet")
61sys.path.append("/usr/share/secnet")
3454dce4
SE
62import ipaddr
63
00152558 64VERSION="0.1.18"
3b83c932
SE
65
66# Classes describing possible datatypes in the configuration file
67
68class single_ipaddr:
69 "An IP address"
70 def __init__(self,w):
71 self.addr=ipaddr.ipaddr(w[1])
72 def __str__(self):
73 return '"%s"'%self.addr.ip_str()
74
75class networks:
76 "A set of IP addresses specified as a list of networks"
3454dce4 77 def __init__(self,w):
3454dce4
SE
78 self.set=ipaddr.ip_set()
79 for i in w[1:]:
80 x=string.split(i,"/")
81 self.set.append(ipaddr.network(x[0],x[1],
82 ipaddr.DEMAND_NETWORK))
3b83c932
SE
83 def __str__(self):
84 return string.join(map(lambda x:'"%s/%s"'%(x.ip_str(),
85 x.mask.netmask_bits_str),
86 self.set.as_list_of_networks()),",")
3454dce4
SE
87
88class dhgroup:
3b83c932 89 "A Diffie-Hellman group"
3454dce4 90 def __init__(self,w):
b2a56f7c
SE
91 self.mod=w[1]
92 self.gen=w[2]
3b83c932
SE
93 def __str__(self):
94 return 'diffie-hellman("%s","%s")'%(self.mod,self.gen)
3454dce4
SE
95
96class hash:
3b83c932 97 "A choice of hash function"
3454dce4 98 def __init__(self,w):
b2a56f7c
SE
99 self.ht=w[1]
100 if (self.ht!='md5' and self.ht!='sha1'):
101 complain("unknown hash type %s"%(self.ht))
3b83c932
SE
102 def __str__(self):
103 return '%s'%(self.ht)
3454dce4
SE
104
105class email:
3b83c932 106 "An email address"
3454dce4 107 def __init__(self,w):
b2a56f7c 108 self.addr=w[1]
3b83c932
SE
109 def __str__(self):
110 return '<%s>'%(self.addr)
3454dce4 111
040040f3
IJ
112class boolean:
113 "A boolean"
114 def __init__(self,w):
115 if re.match('[TtYy1]',w[1]):
116 self.b=True
117 elif re.match('[FfNn0]',w[1]):
118 self.b=False
119 else:
120 complain("invalid boolean value");
121 def __str__(self):
122 return ['False','True'][self.b]
123
3454dce4 124class num:
3b83c932 125 "A decimal number"
3454dce4 126 def __init__(self,w):
b2a56f7c 127 self.n=string.atol(w[1])
3b83c932
SE
128 def __str__(self):
129 return '%d'%(self.n)
3454dce4
SE
130
131class address:
3b83c932 132 "A DNS name and UDP port number"
3454dce4 133 def __init__(self,w):
b2a56f7c
SE
134 self.adr=w[1]
135 self.port=string.atoi(w[2])
136 if (self.port<1 or self.port>65535):
137 complain("invalid port number")
3b83c932
SE
138 def __str__(self):
139 return '"%s"; port %d'%(self.adr,self.port)
3454dce4
SE
140
141class rsakey:
3b83c932 142 "An RSA public key"
3454dce4 143 def __init__(self,w):
b2a56f7c
SE
144 self.l=string.atoi(w[1])
145 self.e=w[2]
146 self.n=w[3]
3b83c932
SE
147 def __str__(self):
148 return 'rsa-public("%s","%s")'%(self.e,self.n)
149
150# Possible properties of configuration nodes
151keywords={
152 'contact':(email,"Contact address"),
153 'dh':(dhgroup,"Diffie-Hellman group"),
154 'hash':(hash,"Hash function"),
155 'key-lifetime':(num,"Maximum key lifetime (ms)"),
156 'setup-timeout':(num,"Key setup timeout (ms)"),
157 'setup-retries':(num,"Maximum key setup packet retries"),
158 'wait-time':(num,"Time to wait after unsuccessful key setup (ms)"),
159 'renegotiate-time':(num,"Time after key setup to begin renegotiation (ms)"),
160 'restrict-nets':(networks,"Allowable networks"),
161 'networks':(networks,"Claimed networks"),
162 'pubkey':(rsakey,"RSA public site key"),
163 'peer':(single_ipaddr,"Tunnel peer IP address"),
a25b1149 164 'address':(address,"External contact address and port"),
040040f3 165 'mobile':(boolean,"Site is mobile"),
3b83c932
SE
166}
167
168def sp(name,value):
169 "Simply output a property - the default case"
170 return "%s %s;\n"%(name,value)
171
172# All levels support these properties
173global_properties={
174 'contact':(lambda name,value:"# Contact email address: %s\n"%(value)),
175 'dh':sp,
176 'hash':sp,
177 'key-lifetime':sp,
178 'setup-timeout':sp,
179 'setup-retries':sp,
180 'wait-time':sp,
181 'renegotiate-time':sp,
a25b1149 182 'restrict-nets':(lambda name,value:"# restrict-nets %s\n"%value),
3b83c932
SE
183}
184
185class level:
186 "A level in the configuration hierarchy"
187 depth=0
188 leaf=0
189 allow_properties={}
190 require_properties={}
191 def __init__(self,w):
192 self.name=w[1]
193 self.properties={}
194 self.children={}
195 def indent(self,w,t):
196 w.write(" "[:t])
197 def prop_out(self,n):
198 return self.allow_properties[n](n,str(self.properties[n]))
199 def output_props(self,w,ind):
200 for i in self.properties.keys():
201 if self.allow_properties[i]:
202 self.indent(w,ind)
203 w.write("%s"%self.prop_out(i))
204 def output_data(self,w,ind,np):
205 self.indent(w,ind)
206 w.write("%s {\n"%(self.name))
207 self.output_props(w,ind+2)
208 if self.depth==1: w.write("\n");
209 for c in self.children.values():
210 c.output_data(w,ind+2,np+self.name+"/")
211 self.indent(w,ind)
212 w.write("};\n")
213
214class vpnlevel(level):
215 "VPN level in the configuration hierarchy"
216 depth=1
217 leaf=0
218 type="vpn"
219 allow_properties=global_properties.copy()
220 require_properties={
221 'contact':"VPN admin contact address"
222 }
223 def __init__(self,w):
224 level.__init__(self,w)
225 def output_vpnflat(self,w,ind,h):
226 "Output flattened list of site names for this VPN"
227 self.indent(w,ind)
228 w.write("%s {\n"%(self.name))
229 for i in self.children.keys():
230 self.children[i].output_vpnflat(w,ind+2,
231 h+"/"+self.name+"/"+i)
232 w.write("\n")
233 self.indent(w,ind+2)
234 w.write("all-sites %s;\n"%
235 string.join(self.children.keys(),','))
236 self.indent(w,ind)
237 w.write("};\n")
238
239class locationlevel(level):
240 "Location level in the configuration hierarchy"
241 depth=2
242 leaf=0
243 type="location"
244 allow_properties=global_properties.copy()
245 require_properties={
246 'contact':"Location admin contact address",
247 }
248 def __init__(self,w):
249 level.__init__(self,w)
250 self.group=w[2]
251 def output_vpnflat(self,w,ind,h):
252 self.indent(w,ind)
253 # The "h=h,self=self" abomination below exists because
254 # Python didn't support nested_scopes until version 2.1
255 w.write("%s %s;\n"%(self.name,string.join(
256 map(lambda x,h=h,self=self:
257 h+"/"+x,self.children.keys()),',')))
258
259class sitelevel(level):
260 "Site level (i.e. a leafnode) in the configuration hierarchy"
261 depth=3
262 leaf=1
263 type="site"
264 allow_properties=global_properties.copy()
265 allow_properties.update({
266 'address':sp,
267 'networks':None,
268 'peer':None,
a25b1149 269 'pubkey':(lambda n,v:"key %s;\n"%v),
040040f3 270 'mobile':sp,
3b83c932
SE
271 })
272 require_properties={
273 'dh':"Diffie-Hellman group",
274 'contact':"Site admin contact address",
275 'address':"Site external access address",
276 'networks':"Networks claimed by the site",
277 'hash':"hash function",
278 'peer':"Gateway address of the site",
a25b1149 279 'pubkey':"RSA public key of the site",
3b83c932 280 }
3454dce4 281 def __init__(self,w):
3b83c932
SE
282 level.__init__(self,w)
283 def output_data(self,w,ind,np):
284 self.indent(w,ind)
285 w.write("%s {\n"%(self.name))
286 self.indent(w,ind+2)
287 w.write("name \"%s\";\n"%(np+self.name))
288 self.output_props(w,ind+2)
289 self.indent(w,ind+2)
290 w.write("link netlink {\n");
291 self.indent(w,ind+4)
292 w.write("routes %s;\n"%str(self.properties["networks"]))
293 self.indent(w,ind+4)
294 w.write("ptp-address %s;\n"%str(self.properties["peer"]))
295 self.indent(w,ind+2)
296 w.write("};\n")
297 self.indent(w,ind)
298 w.write("};\n")
299
300# Levels in the configuration file
301# (depth,properties)
302levels={'vpn':vpnlevel, 'location':locationlevel, 'site':sitelevel}
303
304# Reserved vpn/location/site names
305reserved={'all-sites':None}
306reserved.update(keywords)
307reserved.update(levels)
3454dce4
SE
308
309def complain(msg):
3b83c932 310 "Complain about a particular input line"
3454dce4
SE
311 global complaints
312 print ("%s line %d: "%(file,line))+msg
313 complaints=complaints+1
314def moan(msg):
3b83c932 315 "Complain about something in general"
3454dce4
SE
316 global complaints
317 print msg;
318 complaints=complaints+1
319
3b83c932
SE
320root=level(['root','root']) # All vpns are children of this node
321obstack=[root]
322allow_defs=0 # Level above which new definitions are permitted
323
324def set_property(obj,w):
325 "Set a property on a configuration node"
326 if obj.properties.has_key(w[0]):
327 complain("%s %s already has property %s defined"%
328 (obj.type,obj.name,w[0]))
329 else:
330 obj.properties[w[0]]=keywords[w[0]][0](w)
3454dce4 331
3454dce4 332def pline(i):
3b83c932
SE
333 "Process a configuration file line"
334 global allow_defs, obstack, root
3454dce4
SE
335 w=string.split(i)
336 if len(w)==0: return
337 keyword=w[0]
3b83c932 338 current=obstack[len(obstack)-1]
3454dce4 339 if keyword=='end-definitions':
3b83c932
SE
340 allow_defs=sitelevel.depth
341 obstack=[root]
3454dce4 342 return
3b83c932
SE
343 if levels.has_key(keyword):
344 # We may go up any number of levels, but only down by one
345 newdepth=levels[keyword].depth
346 currentdepth=len(obstack) # actually +1...
347 if newdepth<=currentdepth:
348 obstack=obstack[:newdepth]
349 if newdepth>currentdepth:
350 complain("May not go from level %d to level %d"%
351 (currentdepth-1,newdepth))
352 # See if it's a new one (and whether that's permitted)
353 # or an existing one
354 current=obstack[len(obstack)-1]
355 if current.children.has_key(w[1]):
356 # Not new
357 current=current.children[w[1]]
358 if service and group and current.depth==2:
359 if group!=current.group:
360 complain("Incorrect group!")
3454dce4 361 else:
3b83c932
SE
362 # New
363 # Ignore depth check for now
364 nl=levels[keyword](w)
365 if nl.depth<allow_defs:
366 complain("New definitions not allowed at "
367 "level %d"%nl.depth)
368 current.children[w[1]]=nl
369 current=nl
370 obstack.append(current)
3454dce4 371 return
3b83c932
SE
372 if current.allow_properties.has_key(keyword):
373 set_property(current,w)
3454dce4 374 return
3454dce4 375 else:
3b83c932
SE
376 complain("Property %s not allowed at %s level"%
377 (keyword,current.type))
378 return
379
380 complain("unknown keyword '%s'"%(keyword))
3454dce4
SE
381
382def pfile(name,lines):
3b83c932 383 "Process a file"
3454dce4
SE
384 global file,line
385 file=name
386 line=0
387 for i in lines:
388 line=line+1
389 if (i[0]=='#'): continue
390 if (i[len(i)-1]=='\n'): i=i[:len(i)-1] # strip trailing LF
391 pline(i)
392
393def outputsites(w):
3b83c932
SE
394 "Output include file for secnet configuration"
395 w.write("# secnet sites file autogenerated by make-secnet-sites "
3454dce4 396 +"version %s\n"%VERSION)
3b83c932
SE
397 w.write("# %s\n"%time.asctime(time.localtime(time.time())))
398 w.write("# Command line: %s\n\n"%string.join(sys.argv))
3454dce4
SE
399
400 # Raw VPN data section of file
401 w.write("vpn-data {\n")
3b83c932
SE
402 for i in root.children.values():
403 i.output_data(w,2,"")
3454dce4
SE
404 w.write("};\n")
405
406 # Per-VPN flattened lists
407 w.write("vpn {\n")
3b83c932
SE
408 for i in root.children.values():
409 i.output_vpnflat(w,2,"vpn-data")
3454dce4
SE
410 w.write("};\n")
411
412 # Flattened list of sites
413 w.write("all-sites %s;\n"%string.join(map(lambda x:"vpn/%s/all-sites"%
3b83c932 414 x,root.children.keys()),","))
3454dce4
SE
415
416# Are we being invoked from userv?
417service=0
418# If we are, which group does the caller want to modify?
419group=None
420
3454dce4
SE
421line=0
422file=None
423complaints=0
424
3454dce4
SE
425if len(sys.argv)<2:
426 pfile("stdin",sys.stdin.readlines())
427 of=sys.stdout
428else:
429 if sys.argv[1]=='-u':
430 if len(sys.argv)!=6:
431 print "Wrong number of arguments"
432 sys.exit(1)
433 service=1
434 header=sys.argv[2]
435 groupfiledir=sys.argv[3]
436 sitesfile=sys.argv[4]
437 group=sys.argv[5]
438 if not os.environ.has_key("USERV_USER"):
439 print "Environment variable USERV_USER not found"
440 sys.exit(1)
441 user=os.environ["USERV_USER"]
442 # Check that group is in USERV_GROUP
443 if not os.environ.has_key("USERV_GROUP"):
444 print "Environment variable USERV_GROUP not found"
445 sys.exit(1)
446 ugs=os.environ["USERV_GROUP"]
447 ok=0
448 for i in string.split(ugs):
449 if group==i: ok=1
450 if not ok:
451 print "caller not in group %s"%group
452 sys.exit(1)
453 f=open(header)
08f344d3 454 headerinput=f.readlines()
3454dce4 455 f.close()
08f344d3 456 pfile(header,headerinput)
3454dce4
SE
457 userinput=sys.stdin.readlines()
458 pfile("user input",userinput)
459 else:
460 if len(sys.argv)>3:
461 print "Too many arguments"
462 sys.exit(1)
463 f=open(sys.argv[1])
464 pfile(sys.argv[1],f.readlines())
465 f.close()
466 of=sys.stdout
467 if len(sys.argv)>2:
468 of=open(sys.argv[2],'w')
469
470# Sanity check section
3b83c932
SE
471# Delete nodes where leaf=0 that have no children
472
473def live(n):
474 "Number of leafnodes below node n"
475 if n.leaf: return 1
476 for i in n.children.keys():
477 if live(n.children[i]): return 1
478 return 0
479def delempty(n):
480 "Delete nodes that have no leafnode children"
481 for i in n.children.keys():
482 delempty(n.children[i])
483 if not live(n.children[i]):
484 del n.children[i]
485delempty(root)
486
487# Check that all constraints are met (as far as I can tell
488# restrict-nets/networks/peer are the only special cases)
489
490def checkconstraints(n,p,ra):
491 new_p=p.copy()
492 new_p.update(n.properties)
493 for i in n.require_properties.keys():
494 if not new_p.has_key(i):
495 moan("%s %s is missing property %s"%
496 (n.type,n.name,i))
497 for i in new_p.keys():
498 if not n.allow_properties.has_key(i):
499 moan("%s %s has forbidden property %s"%
500 (n.type,n.name,i))
501 # Check address range restrictions
502 if n.properties.has_key("restrict-nets"):
503 new_ra=ra.intersection(n.properties["restrict-nets"].set)
3454dce4 504 else:
3b83c932
SE
505 new_ra=ra
506 if n.properties.has_key("networks"):
507 # I'd like to do this:
508 # n.properties["networks"].set.is_subset(new_ra)
509 # but there isn't an is_subset() method
510 # Instead we see if we intersect with the complement of new_ra
511 rac=new_ra.complement()
512 i=rac.intersection(n.properties["networks"].set)
513 if not i.is_empty():
514 moan("%s %s networks out of bounds"%(n.type,n.name))
515 if n.properties.has_key("peer"):
516 if not n.properties["networks"].set.contains(
517 n.properties["peer"].addr):
518 moan("%s %s peer not in networks"%(n.type,n.name))
519 for i in n.children.keys():
520 checkconstraints(n.children[i],new_p,new_ra)
521
522checkconstraints(root,{},ipaddr.complete_set)
3454dce4
SE
523
524if complaints>0:
525 if complaints==1: print "There was 1 problem."
526 else: print "There were %d problems."%(complaints)
527 sys.exit(1)
528
529if service:
530 # Put the user's input into their group file, and rebuild the main
531 # sites file
08f344d3 532 f=open(groupfiledir+"/T"+group,'w')
3454dce4
SE
533 f.write("# Section submitted by user %s, %s\n"%
534 (user,time.asctime(time.localtime(time.time()))))
3b83c932 535 f.write("# Checked by make-secnet-sites version %s\n\n"%VERSION)
3454dce4
SE
536 for i in userinput: f.write(i)
537 f.write("\n")
538 f.close()
08f344d3
SE
539 os.rename(groupfiledir+"/T"+group,groupfiledir+"/R"+group)
540 f=open(sitesfile+"-tmp",'w')
ff05a229 541 f.write("# sites file autogenerated by make-secnet-sites\n")
08f344d3
SE
542 f.write("# generated %s, invoked by %s\n"%
543 (time.asctime(time.localtime(time.time())),user))
ff05a229 544 f.write("# use make-secnet-sites to turn this file into a\n")
08f344d3
SE
545 f.write("# valid /etc/secnet/sites.conf file\n\n")
546 for i in headerinput: f.write(i)
547 files=os.listdir(groupfiledir)
548 for i in files:
549 if i[0]=='R':
550 j=open(groupfiledir+"/"+i)
551 f.write(j.read())
552 j.close()
553 f.write("# end of sites file\n")
554 f.close()
555 os.rename(sitesfile+"-tmp",sitesfile)
3454dce4
SE
556else:
557 outputsites(of)