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
54 from __future__ import print_function
65 sys.path.insert(0,"/usr/local/share/secnet")
66 sys.path.insert(0,"/usr/share/secnet")
71 # Are we being invoked from userv?
73 # If we are, which group does the caller want to modify?
82 print("Wrong number of arguments")
86 groupfiledir=sys.argv[3]
89 if not os.environ.has_key("USERV_USER"):
90 print("Environment variable USERV_USER not found")
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")
97 ugs=os.environ["USERV_GROUP"]
99 for i in string.split(ugs):
102 print("caller not in group %s"%group)
105 if sys.argv[1]=='-P':
109 print("Too many arguments")
111 inputfile=sys.argv[1]
114 of=open(sys.argv[2],'w')
116 # Classes describing possible datatypes in the configuration file
119 "Common protocol for configuration types."
121 complain("%s %s already has property %s defined"%
122 (obj.type,obj.name,w[0]))
125 "A list of some kind of configuration type."
126 def __init__(self,subtype,w):
128 self.list=[subtype(w)]
130 self.list.append(self.subtype(w))
132 return ', '.join(map(str, self.list))
134 return lambda w: conflist(subtype, w)
136 class single_ipaddr (basetype):
138 def __init__(self,w):
139 self.addr=ipaddr.IPAddress(w[1])
141 return '"%s"'%self.addr
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()
148 x=ipaddr.IPNetwork(i,strict=True)
151 return ",".join(map((lambda n: '"%s"'%n), self.set.networks()))
153 class dhgroup (basetype):
154 "A Diffie-Hellman group"
155 def __init__(self,w):
159 return 'diffie-hellman("%s","%s")'%(self.mod,self.gen)
161 class hash (basetype):
162 "A choice of hash function"
163 def __init__(self,w):
165 if (self.ht!='md5' and self.ht!='sha1'):
166 complain("unknown hash type %s"%(self.ht))
168 return '%s'%(self.ht)
170 class email (basetype):
172 def __init__(self,w):
175 return '<%s>'%(self.addr)
177 class boolean (basetype):
179 def __init__(self,w):
180 if re.match('[TtYy1]',w[1]):
182 elif re.match('[FfNn0]',w[1]):
185 complain("invalid boolean value");
187 return ['False','True'][self.b]
189 class num (basetype):
191 def __init__(self,w):
192 self.n=string.atol(w[1])
196 class address (basetype):
197 "A DNS name and UDP port number"
198 def __init__(self,w):
200 self.port=string.atoi(w[2])
201 if (self.port<1 or self.port>65535):
202 complain("invalid port number")
204 return '"%s"; port %d'%(self.adr,self.port)
206 class rsakey (basetype):
208 def __init__(self,w):
209 self.l=string.atoi(w[1])
213 return 'rsa-public("%s","%s")'%(self.e,self.n)
215 # Possible properties of configuration nodes
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"),
234 "Simply output a property - the default case"
235 return "%s %s;\n"%(name,value)
237 # All levels support these properties
239 'contact':(lambda name,value:"# Contact email address: %s\n"%(value)),
246 'renegotiate-time':sp,
247 'restrict-nets':(lambda name,value:"# restrict-nets %s\n"%value),
251 "A level in the configuration hierarchy"
255 require_properties={}
256 def __init__(self,w):
260 def indent(self,w,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]:
268 w.write("%s"%self.prop_out(i))
269 def output_data(self,w,ind,np):
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+"/")
279 class vpnlevel(level):
280 "VPN level in the configuration hierarchy"
284 allow_properties=global_properties.copy()
286 'contact':"VPN admin contact address"
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"
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)
299 w.write("all-sites %s;\n"%
300 string.join(self.children.keys(),','))
304 class locationlevel(level):
305 "Location level in the configuration hierarchy"
309 allow_properties=global_properties.copy()
311 'contact':"Location admin contact address",
313 def __init__(self,w):
314 level.__init__(self,w)
316 def output_vpnflat(self,w,ind,h):
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()),',')))
324 class sitelevel(level):
325 "Site level (i.e. a leafnode) in the configuration hierarchy"
329 allow_properties=global_properties.copy()
330 allow_properties.update({
334 'pubkey':(lambda n,v:"key %s;\n"%v),
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",
345 def __init__(self,w):
346 level.__init__(self,w)
347 def output_data(self,w,ind,np):
349 w.write("%s {\n"%(self.name))
351 w.write("name \"%s\";\n"%(np+self.name))
352 self.output_props(w,ind+2)
354 w.write("link netlink {\n");
356 w.write("routes %s;\n"%str(self.properties["networks"]))
358 w.write("ptp-address %s;\n"%str(self.properties["peer"]))
364 # Levels in the configuration file
366 levels={'vpn':vpnlevel, 'location':locationlevel, 'site':sitelevel}
368 # Reserved vpn/location/site names
369 reserved={'all-sites':None}
370 reserved.update(keywords)
371 reserved.update(levels)
374 "Complain about a particular input line"
376 print(("%s line %d: "%(file,line))+msg)
377 complaints=complaints+1
379 "Complain about something in general"
382 complaints=complaints+1
384 root=level(['root','root']) # All vpns are children of this node
386 allow_defs=0 # Level above which new definitions are permitted
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)
394 obj.properties[w[0]]=keywords[w[0]][0](w)
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]
402 current=obstack[len(obstack)-1]
403 if keyword=='end-definitions':
404 allow_defs=sitelevel.depth
407 if keyword=='include':
408 if not allow_include:
409 complain("include not permitted here")
412 complain("include requires one argument")
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)
427 current=obstack[len(obstack)-1]
428 if current.children.has_key(w[1]):
430 current=current.children[w[1]]
431 if service and group and current.depth==2:
432 if group!=current.group:
433 complain("Incorrect group!")
436 # Ignore depth check for now
437 nl=levels[keyword](w)
438 if nl.depth<allow_defs:
439 complain("New definitions not allowed at "
441 # we risk crashing if we continue
443 current.children[w[1]]=nl
445 obstack.append(current)
447 if not current.allow_properties.has_key(keyword):
448 complain("Property %s not allowed at %s level"%
449 (keyword,current.type))
451 elif current.depth == vpnlevel.depth < allow_defs:
452 complain("Not allowed to set VPN properties here")
455 set_property(current,w)
458 complain("unknown keyword '%s'"%(keyword))
460 def pfilepath(pathname,allow_include=False):
462 outlines=pfile(pathname,f.readlines(),allow_include=allow_include)
466 def pfile(name,lines,allow_include=False):
474 if (i[0]=='#'): continue
475 outlines += pline(i,allow_include=allow_include)
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))
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,"")
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")
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()),","))
506 # Sanity check section
507 # Delete nodes where leaf=0 that have no children
510 "Number of leafnodes below node n"
512 for i in n.children.keys():
513 if live(n.children[i]): return 1
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]):
522 # Check that all constraints are met (as far as I can tell
523 # restrict-nets/networks/peer are the only special cases)
525 def checkconstraints(n,p,ra):
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"%
532 for i in new_p.keys():
533 if not n.allow_properties.has_key(i):
534 moan("%s %s has forbidden property %s"%
536 # Check address range restrictions
537 if n.properties.has_key("restrict-nets"):
538 new_ra=ra.intersection(n.properties["restrict-nets"].set)
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)
552 headerinput=pfilepath(header,allow_include=True)
553 userinput=sys.stdin.readlines()
554 pfile("user input",userinput)
556 if inputfile is None:
557 pfile("stdin",sys.stdin.readlines())
562 checkconstraints(root,{},ipaddrset.complete_set())
565 if complaints==1: print("There was 1 problem.")
566 else: print("There were %d problems."%(complaints))
570 # Put the user's input into their group file, and rebuild the main
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)
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)
590 j=open(groupfiledir+"/"+i)
593 f.write("# end of sites file\n")
595 os.rename(sitesfile+"-tmp",sitesfile)