3 # This file is part of secnet.
4 # See README for full list of copyright holders.
6 # secnet is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # secnet is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # version 3 along with secnet; if not, see
18 # https://www.gnu.org/licenses/gpl.html.
20 """VPN sites file manipulation.
22 This program enables VPN site descriptions to be submitted for
23 inclusion in a central database, and allows the resulting database to
24 be turned into a secnet configuration file.
26 A database file can be turned into a secnet configuration file simply:
27 make-secnet-sites.py [infile [outfile]]
29 It would be wise to run secnet with the "--just-check-config" option
30 before installing the output on a live system.
32 The program expects to be invoked via userv to manage the database; it
33 relies on the USERV_USER and USERV_GROUP environment variables. The
34 command line arguments for this invocation are:
36 make-secnet-sites.py -u header-filename groupfiles-directory output-file \
39 All but the last argument are expected to be set by userv; the 'group'
40 argument is provided by the user. A suitable userv configuration file
46 cd ~/secnet/sites-test/
47 execute ~/secnet/make-secnet-sites.py -u vpnheader groupfiles sites
49 This program is part of secnet. It relies on the "ipaddr" library from
63 sys.path.insert(0,"/usr/local/share/secnet")
64 sys.path.insert(0,"/usr/share/secnet")
69 # Classes describing possible datatypes in the configuration file
72 "Common protocol for configuration types."
75 class single_ipaddr (basetype):
78 self.addr=ipaddr.IPAddress(w[1])
80 return '"%s"'%self.addr
82 class networks (basetype):
83 "A set of IP addresses specified as a list of networks"
85 self.set=ipaddrset.IPAddressSet()
87 x=ipaddr.IPNetwork(i,strict=True)
90 return ",".join(map((lambda n: '"%s"'%n), self.set.networks()))
92 class dhgroup (basetype):
93 "A Diffie-Hellman group"
98 return 'diffie-hellman("%s","%s")'%(self.mod,self.gen)
100 class hash (basetype):
101 "A choice of hash function"
102 def __init__(self,w):
104 if (self.ht not in ('md5', 'sha1', 'sha512')):
105 complain("unknown hash type %s"%(self.ht))
107 return '%s'%(self.ht)
109 class email (basetype):
111 def __init__(self,w):
114 return '<%s>'%(self.addr)
116 class boolean (basetype):
118 def __init__(self,w):
119 if re.match('[TtYy1]',w[1]):
121 elif re.match('[FfNn0]',w[1]):
124 complain("invalid boolean value");
126 return ['False','True'][self.b]
128 class num (basetype):
130 def __init__(self,w):
131 self.n=string.atol(w[1])
135 class address (basetype):
136 "A DNS name and UDP port number"
137 def __init__(self,w):
139 self.port=string.atoi(w[2])
140 if (self.port<1 or self.port>65535):
141 complain("invalid port number")
143 return '"%s"; port %d'%(self.adr,self.port)
145 class rsakey (basetype):
147 def __init__(self,w):
148 self.l=string.atoi(w[1])
152 return 'rsa-public("%s","%s")'%(self.e,self.n)
154 # Possible properties of configuration nodes
156 'contact':(email,"Contact address"),
157 'dh':(dhgroup,"Diffie-Hellman group"),
158 'hash':(hash,"Hash function"),
159 'key-lifetime':(num,"Maximum key lifetime (ms)"),
160 'setup-timeout':(num,"Key setup timeout (ms)"),
161 'setup-retries':(num,"Maximum key setup packet retries"),
162 'wait-time':(num,"Time to wait after unsuccessful key setup (ms)"),
163 'renegotiate-time':(num,"Time after key setup to begin renegotiation (ms)"),
164 'restrict-nets':(networks,"Allowable networks"),
165 'networks':(networks,"Claimed networks"),
166 'pubkey':(rsakey,"RSA public site key"),
167 'peer':(single_ipaddr,"Tunnel peer IP address"),
168 'address':(address,"External contact address and port"),
169 'mobile':(boolean,"Site is mobile"),
173 "Simply output a property - the default case"
174 return "%s %s;\n"%(name,value)
176 # All levels support these properties
178 'contact':(lambda name,value:"# Contact email address: %s\n"%(value)),
185 'renegotiate-time':sp,
186 'restrict-nets':(lambda name,value:"# restrict-nets %s\n"%value),
190 "A level in the configuration hierarchy"
194 require_properties={}
195 def __init__(self,w):
199 def indent(self,w,t):
201 def prop_out(self,n):
202 return self.allow_properties[n](n,str(self.properties[n]))
203 def output_props(self,w,ind):
204 for i in self.properties.keys():
205 if self.allow_properties[i]:
207 w.write("%s"%self.prop_out(i))
208 def output_data(self,w,ind,np):
210 w.write("%s {\n"%(self.name))
211 self.output_props(w,ind+2)
212 if self.depth==1: w.write("\n");
213 for c in self.children.values():
214 c.output_data(w,ind+2,np+self.name+"/")
218 class vpnlevel(level):
219 "VPN level in the configuration hierarchy"
223 allow_properties=global_properties.copy()
225 'contact':"VPN admin contact address"
227 def __init__(self,w):
228 level.__init__(self,w)
229 def output_vpnflat(self,w,ind,h):
230 "Output flattened list of site names for this VPN"
232 w.write("%s {\n"%(self.name))
233 for i in self.children.keys():
234 self.children[i].output_vpnflat(w,ind+2,
235 h+"/"+self.name+"/"+i)
238 w.write("all-sites %s;\n"%
239 string.join(self.children.keys(),','))
243 class locationlevel(level):
244 "Location level in the configuration hierarchy"
248 allow_properties=global_properties.copy()
250 'contact':"Location admin contact address",
252 def __init__(self,w):
253 level.__init__(self,w)
255 def output_vpnflat(self,w,ind,h):
257 # The "h=h,self=self" abomination below exists because
258 # Python didn't support nested_scopes until version 2.1
259 w.write("%s %s;\n"%(self.name,string.join(
260 map(lambda x,h=h,self=self:
261 h+"/"+x,self.children.keys()),',')))
263 class sitelevel(level):
264 "Site level (i.e. a leafnode) in the configuration hierarchy"
268 allow_properties=global_properties.copy()
269 allow_properties.update({
273 'pubkey':(lambda n,v:"key %s;\n"%v),
277 'dh':"Diffie-Hellman group",
278 'contact':"Site admin contact address",
279 'networks':"Networks claimed by the site",
280 'hash':"hash function",
281 'peer':"Gateway address of the site",
282 'pubkey':"RSA public key of the site",
284 def __init__(self,w):
285 level.__init__(self,w)
286 def output_data(self,w,ind,np):
288 w.write("%s {\n"%(self.name))
290 w.write("name \"%s\";\n"%(np+self.name))
291 self.output_props(w,ind+2)
293 w.write("link netlink {\n");
295 w.write("routes %s;\n"%str(self.properties["networks"]))
297 w.write("ptp-address %s;\n"%str(self.properties["peer"]))
303 # Levels in the configuration file
305 levels={'vpn':vpnlevel, 'location':locationlevel, 'site':sitelevel}
307 # Reserved vpn/location/site names
308 reserved={'all-sites':None}
309 reserved.update(keywords)
310 reserved.update(levels)
313 "Complain about a particular input line"
315 print ("%s line %d: "%(file,line))+msg
316 complaints=complaints+1
318 "Complain about something in general"
321 complaints=complaints+1
323 root=level(['root','root']) # All vpns are children of this node
325 allow_defs=0 # Level above which new definitions are permitted
328 def set_property(obj,w):
329 "Set a property on a configuration node"
330 if obj.properties.has_key(w[0]):
331 complain("%s %s already has property %s defined"%
332 (obj.type,obj.name,w[0]))
334 obj.properties[w[0]]=keywords[w[0]][0](w)
336 def pline(i,allow_include=False):
337 "Process a configuration file line"
338 global allow_defs, obstack, root
339 w=string.split(i.rstrip('\n'))
340 if len(w)==0: return [i]
342 current=obstack[len(obstack)-1]
343 if keyword=='end-definitions':
344 allow_defs=sitelevel.depth
347 if keyword=='include':
348 if not allow_include:
349 complain("include not permitted here")
352 complain("include requires one argument")
354 newfile=os.path.join(os.path.dirname(file),w[1])
355 return pfilepath(newfile,allow_include=allow_include)
356 if levels.has_key(keyword):
357 # We may go up any number of levels, but only down by one
358 newdepth=levels[keyword].depth
359 currentdepth=len(obstack) # actually +1...
360 if newdepth<=currentdepth:
361 obstack=obstack[:newdepth]
362 if newdepth>currentdepth:
363 complain("May not go from level %d to level %d"%
364 (currentdepth-1,newdepth))
365 # See if it's a new one (and whether that's permitted)
367 current=obstack[len(obstack)-1]
368 if current.children.has_key(w[1]):
370 current=current.children[w[1]]
371 if service and group and current.depth==2:
372 if group!=current.group:
373 complain("Incorrect group!")
376 # Ignore depth check for now
377 nl=levels[keyword](w)
378 if nl.depth<allow_defs:
379 complain("New definitions not allowed at "
381 # we risk crashing if we continue
383 current.children[w[1]]=nl
385 obstack.append(current)
387 if not current.allow_properties.has_key(keyword):
388 complain("Property %s not allowed at %s level"%
389 (keyword,current.type))
391 elif current.depth == vpnlevel.depth < allow_defs:
392 complain("Not allowed to set VPN properties here")
395 set_property(current,w)
398 complain("unknown keyword '%s'"%(keyword))
400 def pfilepath(pathname,allow_include=False):
402 outlines=pfile(pathname,f.readlines(),allow_include=allow_include)
406 def pfile(name,lines,allow_include=False):
414 if (i[0]=='#'): continue
415 outlines += pline(i,allow_include=allow_include)
419 "Output include file for secnet configuration"
420 w.write("# secnet sites file autogenerated by make-secnet-sites "
421 +"version %s\n"%VERSION)
422 w.write("# %s\n"%time.asctime(time.localtime(time.time())))
423 w.write("# Command line: %s\n\n"%string.join(sys.argv))
425 # Raw VPN data section of file
426 w.write(prefix+"vpn-data {\n")
427 for i in root.children.values():
428 i.output_data(w,2,"")
431 # Per-VPN flattened lists
432 w.write(prefix+"vpn {\n")
433 for i in root.children.values():
434 i.output_vpnflat(w,2,prefix+"vpn-data")
437 # Flattened list of sites
438 w.write(prefix+"all-sites %s;\n"%string.join(
439 map(lambda x:"%svpn/%s/all-sites"%(prefix,x),
440 root.children.keys()),","))
442 # Are we being invoked from userv?
444 # If we are, which group does the caller want to modify?
452 pfile("stdin",sys.stdin.readlines())
455 if sys.argv[1]=='-u':
457 print "Wrong number of arguments"
461 groupfiledir=sys.argv[3]
462 sitesfile=sys.argv[4]
464 if not os.environ.has_key("USERV_USER"):
465 print "Environment variable USERV_USER not found"
467 user=os.environ["USERV_USER"]
468 # Check that group is in USERV_GROUP
469 if not os.environ.has_key("USERV_GROUP"):
470 print "Environment variable USERV_GROUP not found"
472 ugs=os.environ["USERV_GROUP"]
474 for i in string.split(ugs):
477 print "caller not in group %s"%group
479 headerinput=pfilepath(header,allow_include=True)
480 userinput=sys.stdin.readlines()
481 pfile("user input",userinput)
483 if sys.argv[1]=='-P':
487 print "Too many arguments"
489 pfilepath(sys.argv[1])
492 of=open(sys.argv[2],'w')
494 # Sanity check section
495 # Delete nodes where leaf=0 that have no children
498 "Number of leafnodes below node n"
500 for i in n.children.keys():
501 if live(n.children[i]): return 1
504 "Delete nodes that have no leafnode children"
505 for i in n.children.keys():
506 delempty(n.children[i])
507 if not live(n.children[i]):
511 # Check that all constraints are met (as far as I can tell
512 # restrict-nets/networks/peer are the only special cases)
514 def checkconstraints(n,p,ra):
516 new_p.update(n.properties)
517 for i in n.require_properties.keys():
518 if not new_p.has_key(i):
519 moan("%s %s is missing property %s"%
521 for i in new_p.keys():
522 if not n.allow_properties.has_key(i):
523 moan("%s %s has forbidden property %s"%
525 # Check address range restrictions
526 if n.properties.has_key("restrict-nets"):
527 new_ra=ra.intersection(n.properties["restrict-nets"].set)
530 if n.properties.has_key("networks"):
531 if not n.properties["networks"].set <= new_ra:
532 moan("%s %s networks out of bounds"%(n.type,n.name))
533 if n.properties.has_key("peer"):
534 if not n.properties["networks"].set.contains(
535 n.properties["peer"].addr):
536 moan("%s %s peer not in networks"%(n.type,n.name))
537 for i in n.children.keys():
538 checkconstraints(n.children[i],new_p,new_ra)
540 checkconstraints(root,{},ipaddrset.complete_set())
543 if complaints==1: print "There was 1 problem."
544 else: print "There were %d problems."%(complaints)
548 # Put the user's input into their group file, and rebuild the main
550 f=open(groupfiledir+"/T"+group,'w')
551 f.write("# Section submitted by user %s, %s\n"%
552 (user,time.asctime(time.localtime(time.time()))))
553 f.write("# Checked by make-secnet-sites version %s\n\n"%VERSION)
554 for i in userinput: f.write(i)
557 os.rename(groupfiledir+"/T"+group,groupfiledir+"/R"+group)
558 f=open(sitesfile+"-tmp",'w')
559 f.write("# sites file autogenerated by make-secnet-sites\n")
560 f.write("# generated %s, invoked by %s\n"%
561 (time.asctime(time.localtime(time.time())),user))
562 f.write("# use make-secnet-sites to turn this file into a\n")
563 f.write("# valid /etc/secnet/sites.conf file\n\n")
564 for i in headerinput: f.write(i)
565 files=os.listdir(groupfiledir)
568 j=open(groupfiledir+"/"+i)
571 f.write("# end of sites file\n")
573 os.rename(sitesfile+"-tmp",sitesfile)