2 # Copyright (C) 2001 Stephen Early <steve@greenend.org.uk>
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.
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.
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
18 """VPN sites file manipulation.
20 This program enables VPN site descriptions to be submitted for
21 inclusion in a central database, and allows the resulting database to
22 be turned into a secnet configuration file.
24 A database file can be turned into a secnet configuration file simply:
25 make-secnet-sites.py [infile [outfile]]
27 It would be wise to run secnet with the "--just-check-config" option
28 before installing the output on a live system.
30 The program expects to be invoked via userv to manage the database; it
31 relies on the USERV_USER and USERV_GROUP environment variables. The
32 command line arguments for this invocation are:
34 make-secnet-sites.py -u header-filename groupfiles-directory output-file \
37 All but the last argument are expected to be set by userv; the 'group'
38 argument is provided by the user. A suitable userv configuration file
44 cd ~/secnet/sites-test/
45 execute ~/secnet/make-secnet-sites.py -u vpnheader groupfiles sites
47 This program is part of secnet. It relies on the "ipaddr" library from
61 def __init__(self,name):
68 def __init__(self,name,vpn):
77 def __init__(self,name,location):
80 self.location=location
86 self.set=ipaddr.ip_set()
89 self.set.append(ipaddr.network(x[0],x[1],
90 ipaddr.DEMAND_NETWORK))
92 # I'd like to do this:
93 # return self.set.is_subset(s)
94 # but there isn't an is_subset() method
95 # Instead we see if we intersect with the complement of s
97 i=sc.intersection(self.set)
101 if (self.w[0]=='restrict-nets'): rn='# '
102 return '%s%s %s;'%(rn,self.w[0],
103 string.join(map(lambda x:'"%s/%s"'%(x.ip_str(),
104 x.mask.netmask_bits_str),
105 self.set.as_list_of_networks()),","))
108 def __init__(self,w):
111 return 'dh diffie-hellman("%s","%s");'%(self.w[1],self.w[2])
114 def __init__(self,w):
116 if (w[1]!='md5' and w[1]!='sha1'):
117 complain("unknown hash type %s"%(w[1]))
119 return 'hash %s;'%(self.w[1])
122 def __init__(self,w):
125 return '# Contact email address: <%s>'%(self.w[1])
128 def __init__(self,w):
131 return '%s %s;'%(self.w[0],self.w[1])
134 def __init__(self,w):
137 return 'address "%s"; port %s;'%(self.w[1],self.w[2])
140 def __init__(self,w):
143 return 'key rsa-public("%s","%s");'%(self.w[2],self.w[3])
146 def __init__(self,w):
149 return '# netlink-options "soft";'
153 print ("%s line %d: "%(file,line))+msg
154 complaints=complaints+1
158 complaints=complaints+1
160 # We don't allow redefinition of properties (because that would allow things
161 # like restrict-nets to be redefined, which would be bad)
163 if (obj.allow_defs | allow_defs):
164 if (obj.defs.has_key(w[0])):
165 complain("%s is already defined"%(w[0]))
170 # Process a line of configuration file
172 global allow_defs, group, current_vpn, current_location, current_object
176 if keyword=='end-definitions':
179 current_location=None
183 if vpns.has_key(w[1]):
184 current_vpn=vpns[w[1]]
185 current_object=current_vpn
188 current_vpn=vpn(w[1])
189 vpns[w[1]]=current_vpn
190 current_object=current_vpn
192 complain("no new VPN definitions allowed")
194 if (current_vpn==None):
195 complain("no VPN defined yet")
197 # Keywords that can apply at all levels
198 if mldefs.has_key(w[0]):
199 set(current_object,mldefs,w)
201 if keyword=='location':
202 if (current_vpn.locations.has_key(w[1])):
203 current_location=current_vpn.locations[w[1]]
204 current_object=current_location
205 if (group and not allow_defs and
206 current_location.group!=group):
207 complain(("must be group %s to access "+
208 "location %s")%(current_location.group,
212 if reserved.has_key(w[1]):
213 complain("reserved location name")
215 current_location=location(w[1],current_vpn)
216 current_vpn.locations[w[1]]=current_location
217 current_object=current_location
219 complain("no new location definitions allowed")
221 if (current_location==None):
222 complain("no locations defined yet")
225 current_location.group=w[1]
228 if (current_location.sites.has_key(w[1])):
229 current_object=current_location.sites[w[1]]
231 if reserved.has_key(w[1]):
232 complain("reserved site name")
234 current_object=site(w[1],current_location)
235 current_location.sites[w[1]]=current_object
237 if keyword=='endsite':
238 if isinstance(current_object,site):
239 current_object=current_object.location
241 complain("not currently defining a site")
243 # Keywords that can only apply to sites
244 if isinstance(current_object,site):
245 if sitedefs.has_key(w[0]):
246 set(current_object,sitedefs,w)
249 if sitedefs.has_key(w[0]):
250 complain("keyword '%s' can only be used in the "
251 "context of a site definition"%(w[0]))
253 complain("unknown keyword '%s'"%(w[0]))
255 def pfile(name,lines):
261 if (i[0]=='#'): continue
262 if (i[len(i)-1]=='\n'): i=i[:len(i)-1] # strip trailing LF
266 w.write("# secnet sites file autogenerated by make-secnet-sites.py "
267 +"version %s\n"%VERSION)
268 w.write("# %s\n\n"%time.asctime(time.localtime(time.time())))
270 # Raw VPN data section of file
271 w.write("vpn-data {\n")
272 for i in vpns.values():
273 w.write(" %s {\n"%i.name)
274 for d in i.defs.values():
275 w.write(" %s\n"%d.out())
277 for l in i.locations.values():
278 w.write(" %s {\n"%l.name)
279 for d in l.defs.values():
280 w.write(" %s\n"%d.out())
281 for s in l.sites.values():
282 w.write(" %s {\n"%s.name)
283 w.write(' name "%s/%s/%s";\n'%
284 (i.name,l.name,s.name))
285 for d in s.defs.values():
286 w.write(" %s\n"%d.out())
292 # Per-VPN flattened lists
294 for i in vpns.values():
295 w.write(" %s {\n"%(i.name))
296 for l in i.locations.values():
297 slist=map(lambda x:"vpn-data/%s/%s/%s"%
298 (i.name,l.name,x.name),
300 w.write(" %s %s;\n"%(l.name,string.join(slist,",")))
301 w.write("\n all-sites %s;\n"%
302 string.join(i.locations.keys(),","))
306 # Flattened list of sites
307 w.write("all-sites %s;\n"%string.join(map(lambda x:"vpn/%s/all-sites"%
310 # Are we being invoked from userv?
312 # If we are, which group does the caller want to modify?
318 current_location=None
325 # Things that can be defined at any level
334 'renegotiate-time':num,
338 # Things that can only be defined for sites
343 'mobile':mobileoption
346 # Reserved vpn/location/site names
347 reserved={'all-sites':None}
348 reserved.update(mldefs)
349 reserved.update(sitedefs)
351 # Each site must have the following defined at some level:
353 'dh':"Diffie-Hellman group",
354 'networks':"network list",
355 'pubkey':"public key",
356 'hash':"hash function"
360 pfile("stdin",sys.stdin.readlines())
363 if sys.argv[1]=='-u':
365 print "Wrong number of arguments"
369 groupfiledir=sys.argv[3]
370 sitesfile=sys.argv[4]
372 if not os.environ.has_key("USERV_USER"):
373 print "Environment variable USERV_USER not found"
375 user=os.environ["USERV_USER"]
376 # Check that group is in USERV_GROUP
377 if not os.environ.has_key("USERV_GROUP"):
378 print "Environment variable USERV_GROUP not found"
380 ugs=os.environ["USERV_GROUP"]
382 for i in string.split(ugs):
385 print "caller not in group %s"%group
388 headerinput=f.readlines()
390 pfile(header,headerinput)
391 userinput=sys.stdin.readlines()
392 pfile("user input",userinput)
395 print "Too many arguments"
398 pfile(sys.argv[1],f.readlines())
402 of=open(sys.argv[2],'w')
404 # Sanity check section
406 # Delete locations that have no sites defined
407 for i in vpns.values():
408 for l in i.locations.keys():
409 if (len(i.locations[l].sites.values())==0):
412 # Delete VPNs that have no locations with sites defined
413 for i in vpns.keys():
414 if (len(vpns[i].locations.values())==0):
418 for i in vpns.values():
419 if i.defs.has_key('restrict-nets'):
420 vr=i.defs['restrict-nets']
423 for l in i.locations.values():
424 if l.defs.has_key('restrict-nets'):
425 lr=l.defs['restrict-nets']
426 if (not lr.subsetof(vr)):
427 moan("location %s/%s restrict-nets is invalid"%
431 for s in l.sites.values():
432 sn="%s/%s/%s"%(i.name,l.name,s.name)
433 for r in required.keys():
434 if (not (s.defs.has_key(r) or
437 moan("site %s missing parameter %s"%
439 if s.defs.has_key('restrict-nets'):
440 sr=s.defs['restrict-nets']
441 if (not sr.subsetof(lr)):
442 moan("site %s restrict-nets not valid"%
446 if not s.defs.has_key('networks'): continue
447 nets=s.defs['networks']
448 if (not nets.subsetof(sr)):
449 moan("site %s networks exceed restriction"%sn)
453 if complaints==1: print "There was 1 problem."
454 else: print "There were %d problems."%(complaints)
458 # Put the user's input into their group file, and rebuild the main
460 f=open(groupfiledir+"/T"+group,'w')
461 f.write("# Section submitted by user %s, %s\n"%
462 (user,time.asctime(time.localtime(time.time()))))
463 f.write("# Checked by make-secnet-sites.py version %s\n\n"%VERSION)
464 for i in userinput: f.write(i)
467 os.rename(groupfiledir+"/T"+group,groupfiledir+"/R"+group)
468 f=open(sitesfile+"-tmp",'w')
469 f.write("# sites file autogenerated by make-secnet-sites.py\n")
470 f.write("# generated %s, invoked by %s\n"%
471 (time.asctime(time.localtime(time.time())),user))
472 f.write("# use make-secnet-sites.py to turn this file into a\n")
473 f.write("# valid /etc/secnet/sites.conf file\n\n")
474 for i in headerinput: f.write(i)
475 files=os.listdir(groupfiledir)
478 j=open(groupfiledir+"/"+i)
481 f.write("# end of sites file\n")
483 os.rename(sitesfile+"-tmp",sitesfile)