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.
53 from __future__ import print_function
54 from __future__ import unicode_literals
55 from builtins import int
66 # entry 0 is "near the executable", or maybe from PYTHONPATH=.,
67 # which we don't want to preempt
68 sys.path.insert(1,"/usr/local/share/secnet")
69 sys.path.insert(1,"/usr/share/secnet")
74 from sys import version_info
75 if version_info.major == 2: # for python2
77 sys.stdin = codecs.getreader('utf-8')(sys.stdin)
78 sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
80 open=lambda f,m='r': io.open(f,m,encoding='utf-8')
82 # Are we being invoked from userv?
84 # If we are, which group does the caller want to modify?
93 print("Wrong number of arguments")
97 groupfiledir=sys.argv[3]
100 if "USERV_USER" not in os.environ:
101 print("Environment variable USERV_USER not found")
103 user=os.environ["USERV_USER"]
104 # Check that group is in USERV_GROUP
105 if "USERV_GROUP" not in os.environ:
106 print("Environment variable USERV_GROUP not found")
108 ugs=os.environ["USERV_GROUP"]
110 for i in ugs.split():
113 print("caller not in group %s"%group)
116 if sys.argv[1]=='-P':
120 print("Too many arguments")
122 inputfile=sys.argv[1]
125 of=open(sys.argv[2],'w')
127 # Classes describing possible datatypes in the configuration file
130 "Common protocol for configuration types."
132 complain("%s %s already has property %s defined"%
133 (obj.type,obj.name,w[0]))
136 "A list of some kind of configuration type."
137 def __init__(self,subtype,w):
139 self.list=[subtype(w)]
141 self.list.append(self.subtype(w))
143 return ', '.join(map(str, self.list))
145 return lambda w: conflist(subtype, w)
147 class single_ipaddr (basetype):
149 def __init__(self,w):
150 self.addr=ipaddress.ip_address(w[1])
152 return '"%s"'%self.addr
154 class networks (basetype):
155 "A set of IP addresses specified as a list of networks"
156 def __init__(self,w):
157 self.set=ipaddrset.IPAddressSet()
159 x=ipaddress.ip_network(i,strict=True)
162 return ",".join(map((lambda n: '"%s"'%n), self.set.networks()))
164 class dhgroup (basetype):
165 "A Diffie-Hellman group"
166 def __init__(self,w):
170 return 'diffie-hellman("%s","%s")'%(self.mod,self.gen)
172 class hash (basetype):
173 "A choice of hash function"
174 def __init__(self,w):
176 if (self.ht!='md5' and self.ht!='sha1'):
177 complain("unknown hash type %s"%(self.ht))
179 return '%s'%(self.ht)
181 class email (basetype):
183 def __init__(self,w):
186 return '<%s>'%(self.addr)
188 class boolean (basetype):
190 def __init__(self,w):
191 if re.match('[TtYy1]',w[1]):
193 elif re.match('[FfNn0]',w[1]):
196 complain("invalid boolean value");
198 return ['False','True'][self.b]
200 class num (basetype):
202 def __init__(self,w):
207 class address (basetype):
208 "A DNS name and UDP port number"
209 def __init__(self,w):
212 if (self.port<1 or self.port>65535):
213 complain("invalid port number")
215 return '"%s"; port %d'%(self.adr,self.port)
217 class rsakey (basetype):
219 def __init__(self,w):
224 return 'rsa-public("%s","%s")'%(self.e,self.n)
226 # Possible properties of configuration nodes
228 'contact':(email,"Contact address"),
229 'dh':(dhgroup,"Diffie-Hellman group"),
230 'hash':(hash,"Hash function"),
231 'key-lifetime':(num,"Maximum key lifetime (ms)"),
232 'setup-timeout':(num,"Key setup timeout (ms)"),
233 'setup-retries':(num,"Maximum key setup packet retries"),
234 'wait-time':(num,"Time to wait after unsuccessful key setup (ms)"),
235 'renegotiate-time':(num,"Time after key setup to begin renegotiation (ms)"),
236 'restrict-nets':(networks,"Allowable networks"),
237 'networks':(networks,"Claimed networks"),
238 'pubkey':(rsakey,"RSA public site key"),
239 'peer':(single_ipaddr,"Tunnel peer IP address"),
240 'address':(address,"External contact address and port"),
241 'mobile':(boolean,"Site is mobile"),
245 "Simply output a property - the default case"
246 return "%s %s;\n"%(name,value)
248 # All levels support these properties
250 'contact':(lambda name,value:"# Contact email address: %s\n"%(value)),
257 'renegotiate-time':sp,
258 'restrict-nets':(lambda name,value:"# restrict-nets %s\n"%value),
262 "A level in the configuration hierarchy"
266 require_properties={}
267 def __init__(self,w):
272 def indent(self,w,t):
274 def prop_out(self,n):
275 return self.allow_properties[n](n,str(self.properties[n]))
276 def output_props(self,w,ind):
277 for i in self.properties.keys():
278 if self.allow_properties[i]:
280 w.write("%s"%self.prop_out(i))
281 def output_data(self,w,ind,np):
283 w.write("%s {\n"%(self.name))
284 self.output_props(w,ind+2)
285 if self.depth==1: w.write("\n");
286 for c in self.children.values():
287 c.output_data(w,ind+2,np+self.name+"/")
291 class vpnlevel(level):
292 "VPN level in the configuration hierarchy"
296 allow_properties=global_properties.copy()
298 'contact':"VPN admin contact address"
300 def __init__(self,w):
301 level.__init__(self,w)
302 def output_vpnflat(self,w,ind,h):
303 "Output flattened list of site names for this VPN"
305 w.write("%s {\n"%(self.name))
306 for i in self.children.keys():
307 self.children[i].output_vpnflat(w,ind+2,
308 h+"/"+self.name+"/"+i)
311 w.write("all-sites %s;\n"%
312 ','.join(self.children.keys()))
316 class locationlevel(level):
317 "Location level in the configuration hierarchy"
321 allow_properties=global_properties.copy()
323 'contact':"Location admin contact address",
325 def __init__(self,w):
326 level.__init__(self,w)
328 def output_vpnflat(self,w,ind,h):
330 # The "h=h,self=self" abomination below exists because
331 # Python didn't support nested_scopes until version 2.1
332 w.write("%s %s;\n"%(self.name,','.join(
333 map(lambda x,h=h,self=self:
334 h+"/"+x,self.children.keys()))))
336 class sitelevel(level):
337 "Site level (i.e. a leafnode) in the configuration hierarchy"
341 allow_properties=global_properties.copy()
342 allow_properties.update({
346 'pubkey':(lambda n,v:"key %s;\n"%v),
350 'dh':"Diffie-Hellman group",
351 'contact':"Site admin contact address",
352 'networks':"Networks claimed by the site",
353 'hash':"hash function",
354 'peer':"Gateway address of the site",
355 'pubkey':"RSA public key of the site",
357 def __init__(self,w):
358 level.__init__(self,w)
359 def output_data(self,w,ind,np):
361 w.write("%s {\n"%(self.name))
363 w.write("name \"%s\";\n"%(np+self.name))
364 self.output_props(w,ind+2)
366 w.write("link netlink {\n");
368 w.write("routes %s;\n"%str(self.properties["networks"]))
370 w.write("ptp-address %s;\n"%str(self.properties["peer"]))
376 # Levels in the configuration file
378 levels={'vpn':vpnlevel, 'location':locationlevel, 'site':sitelevel}
380 # Reserved vpn/location/site names
381 reserved={'all-sites':None}
382 reserved.update(keywords)
383 reserved.update(levels)
386 "Complain about a particular input line"
388 print(("%s line %d: "%(file,line))+msg)
389 complaints=complaints+1
391 "Complain about something in general"
394 complaints=complaints+1
396 root=level(['root','root']) # All vpns are children of this node
398 allow_defs=0 # Level above which new definitions are permitted
401 def set_property(obj,w):
402 "Set a property on a configuration node"
403 if w[0] in obj.properties:
404 obj.properties[w[0]].add(obj,w)
406 obj.properties[w[0]]=keywords[w[0]][0](w)
408 def pline(i,allow_include=False):
409 "Process a configuration file line"
410 global allow_defs, obstack, root
411 w=i.rstrip('\n').split()
412 if len(w)==0: return [i]
414 current=obstack[len(obstack)-1]
415 if keyword=='end-definitions':
416 allow_defs=sitelevel.depth
419 if keyword=='include':
420 if not allow_include:
421 complain("include not permitted here")
424 complain("include requires one argument")
426 newfile=os.path.join(os.path.dirname(file),w[1])
427 return pfilepath(newfile,allow_include=allow_include)
428 if keyword in levels:
429 # We may go up any number of levels, but only down by one
430 newdepth=levels[keyword].depth
431 currentdepth=len(obstack) # actually +1...
432 if newdepth<=currentdepth:
433 obstack=obstack[:newdepth]
434 if newdepth>currentdepth:
435 complain("May not go from level %d to level %d"%
436 (currentdepth-1,newdepth))
437 # See if it's a new one (and whether that's permitted)
439 current=obstack[len(obstack)-1]
440 if w[1] in current.children:
442 current=current.children[w[1]]
443 if service and group and current.depth==2:
444 if group!=current.group:
445 complain("Incorrect group!")
448 # Ignore depth check for now
449 nl=levels[keyword](w)
450 if nl.depth<allow_defs:
451 complain("New definitions not allowed at "
453 # we risk crashing if we continue
455 current.children[w[1]]=nl
457 obstack.append(current)
459 if keyword not in current.allow_properties:
460 complain("Property %s not allowed at %s level"%
461 (keyword,current.type))
463 elif current.depth == vpnlevel.depth < allow_defs:
464 complain("Not allowed to set VPN properties here")
467 set_property(current,w)
470 complain("unknown keyword '%s'"%(keyword))
472 def pfilepath(pathname,allow_include=False):
474 outlines=pfile(pathname,f.readlines(),allow_include=allow_include)
478 def pfile(name,lines,allow_include=False):
486 if (i[0]=='#'): continue
487 outlines += pline(i,allow_include=allow_include)
491 "Output include file for secnet configuration"
492 w.write("# secnet sites file autogenerated by make-secnet-sites "
493 +"version %s\n"%VERSION)
494 w.write("# %s\n"%time.asctime(time.localtime(time.time())))
495 w.write("# Command line: %s\n\n"%' '.join(sys.argv))
497 # Raw VPN data section of file
498 w.write(prefix+"vpn-data {\n")
499 for i in root.children.values():
500 i.output_data(w,2,"")
503 # Per-VPN flattened lists
504 w.write(prefix+"vpn {\n")
505 for i in root.children.values():
506 i.output_vpnflat(w,2,prefix+"vpn-data")
509 # Flattened list of sites
510 w.write(prefix+"all-sites %s;\n"%",".join(
511 map(lambda x:"%svpn/%s/all-sites"%(prefix,x),
512 root.children.keys())))
518 # Sanity check section
519 # Delete nodes where leaf=0 that have no children
522 "Number of leafnodes below node n"
524 for i in n.children.keys():
525 if live(n.children[i]): return 1
528 "Delete nodes that have no leafnode children"
529 for i in list(n.children.keys()):
530 delempty(n.children[i])
531 if not live(n.children[i]):
534 # Check that all constraints are met (as far as I can tell
535 # restrict-nets/networks/peer are the only special cases)
537 def checkconstraints(n,p,ra):
539 new_p.update(n.properties)
540 for i in n.require_properties.keys():
542 moan("%s %s is missing property %s"%
544 for i in new_p.keys():
545 if i not in n.allow_properties:
546 moan("%s %s has forbidden property %s"%
548 # Check address range restrictions
549 if "restrict-nets" in n.properties:
550 new_ra=ra.intersection(n.properties["restrict-nets"].set)
553 if "networks" in n.properties:
554 if not n.properties["networks"].set <= new_ra:
555 moan("%s %s networks out of bounds"%(n.type,n.name))
556 if "peer" in n.properties:
557 if not n.properties["networks"].set.contains(
558 n.properties["peer"].addr):
559 moan("%s %s peer not in networks"%(n.type,n.name))
560 for i in n.children.keys():
561 checkconstraints(n.children[i],new_p,new_ra)
564 headerinput=pfilepath(header,allow_include=True)
565 userinput=sys.stdin.readlines()
566 pfile("user input",userinput)
568 if inputfile is None:
569 pfile("stdin",sys.stdin.readlines())
574 checkconstraints(root,{},ipaddrset.complete_set())
577 if complaints==1: print("There was 1 problem.")
578 else: print("There were %d problems."%(complaints))
582 # Put the user's input into their group file, and rebuild the main
584 f=open(groupfiledir+"/T"+group,'w')
585 f.write("# Section submitted by user %s, %s\n"%
586 (user,time.asctime(time.localtime(time.time()))))
587 f.write("# Checked by make-secnet-sites version %s\n\n"%VERSION)
588 for i in userinput: f.write(i)
591 os.rename(groupfiledir+"/T"+group,groupfiledir+"/R"+group)
592 f=open(sitesfile+"-tmp",'w')
593 f.write("# sites file autogenerated by make-secnet-sites\n")
594 f.write("# generated %s, invoked by %s\n"%
595 (time.asctime(time.localtime(time.time())),user))
596 f.write("# use make-secnet-sites to turn this file into a\n")
597 f.write("# valid /etc/secnet/sites.conf file\n\n")
598 for i in headerinput: f.write(i)
599 files=os.listdir(groupfiledir)
602 j=open(groupfiledir+"/"+i)
605 f.write("# end of sites file\n")
607 os.rename(sitesfile+"-tmp",sitesfile)