-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathvpnmaker.rb
478 lines (385 loc) · 12.2 KB
/
vpnmaker.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
require 'rubygems'
require 'fileutils'
require 'yaml'
require 'erb'
require 'socket'
class String
def path(p)
File.join(File.dirname(__FILE__), p)
end
end
class HashBinding < Object
def self.from_hash(h)
hb = self.new
h.each do |k, v|
hb.instance_variable_set("@#{k}", v)
end
hb
end
def binding; super; end # normally private
end
module VPNMaker
class ConfigGenerator
def initialize(mgr)
@mgr = mgr
end
def client_conf(client)
{
:gen_host => Socket.gethostname,
:server => @mgr.config[:server],
:client => @mgr.config[:client]
}.merge(client)
end
def server_conf
{
:gen_host => Socket.gethostname
}.merge(@mgr.config[:server])
end
def apply_erb(name, cnf)
erb = File.read(__FILE__.path(name))
ERB.new(erb).result(HashBinding.from_hash(cnf).binding)
end
def server; apply_erb('server.erb', server_conf); end
def client(client)
apply_erb('client.erb', client_conf(client));
end
end
class KeyDB
def initialize(path)
@path = path
@db = File.exists?(path) ? YAML.load_file(path) : {}
@touched = false
end
def [](k); @db[k]; end
def []=(k, v)
@db[k] = v
@db[:modified] = Time.now
@touched = true
end
def touched!
@touched = true
@db[:modified] = Time.now
end
def datadir; self[:datadir]; end
def data_path(k)
File.join(File.dirname(@path), self.datadir, k)
end
def dump(k, v, overwrite=false)
p = data_path(k)
raise "#{k} already exists" if File.exists?(p) && !overwrite
File.open(p, 'w') {|f| f.write(v)}
@touched = true
end
def data(k)
File.exists?(data_path(k)) ? File.read(data_path(k)) : nil
end
def disk_version
File.exists?(@path) ? YAML.load_file(@path)[:version] : 0
end
def sync
if disk_version == @db[:version]
if @touched
FileUtils.mkdir_p(self.datadir)
@db[:version] += 1
File.open(@path, 'w') {|f| f.write(@db.to_yaml)}
true
else
false
end
else
raise "Disk version of #{@path} (#{disk_version}) != loaded version (#{@db[:version]}). " + \
"Try reloading and making your changes again."
end
end
def version; @db[:version]; end
end
class KeyConfig
def initialize(path)
@config = YAML.load_file(path)
end
def [](k); @config[k]; end
end
class KeyTracker
attr_reader :builder
attr_reader :db
attr_reader :config
def self.generate(name, path=nil)
path ||= '/tmp'
dir = File.join(File.expand_path(path), name + '.vpn')
FileUtils.mkdir_p(dir)
datadir = "#{name}_data"
dbpath = File.join(dir, "#{name}.db.yaml")
d = KeyDB.new(dbpath)
d[:version] = 0
d[:modified] = Time.now
d[:users] = {}
d[:datadir] = datadir
d.sync
end
def assert_user(user)
raise "User doesn't exist: #{user}" unless @db[:users][user]
end
def ca; @db[:ca]; end
def set_ca(key, crt, crl, index, serial)
raise "CA already set" if @db[:ca]
@db[:ca] = {:modified => Time.now}
@db.dump('ca.key', key)
@db.dump('ca.crt', crt)
@db.dump('crl.pem', crl)
@db.dump('index.txt', index)
@db.dump('serial', serial)
@db.touched!
@db.sync
end
def set_server_key(key, crt, index, serial)
raise "Server key already set" if @db[:server]
@db[:server] = {:modified => Time.now}
@db.dump('server.key', key)
@db.dump('server.crt', crt)
@db.dump('index.txt', index, true)
@db.dump('serial', serial, true)
@db.touched!
@db.sync
end
def set_ta_key(ta)
raise "TA key already set" if @db[:ta]
@db[:ta] = {:modified => Time.now}
@db.dump('ta.key', ta)
@db.touched!
@db.sync
end
def set_dh(dh)
raise "DH key already set" if @db[:dh]
@db[:dh] = {:modified => Time.now}
@db.dump('dh.pem', dh)
@db.touched!
@db.sync
end
def add_key(user, key, crt, p12, ver)
@db.dump("#{user}-#{ver}.key", key)
@db.dump("#{user}-#{ver}.crt", crt)
@db.dump("#{user}-#{ver}.p12", p12)
end
def key(user, ver, type)
@db.data("#{user}-#{ver}.#{type}")
end
def add_user(user, name, email, key, crt, p12, index, serial)
raise "User must be a non-empty string" unless user.is_a?(String) && user.size > 0
raise "User already exists: #{user}" if @db[:users][user]
@db[:users][user] = {
:user => user,
:name => name,
:email => email,
:active_key => 0,
:revoked => [],
:modified => Time.now
}
@db.dump('serial', serial, true)
@db.dump('index.txt', index, true)
add_key(user, key, crt, p12, 0)
@db.touched!
@db.sync
end
def add_user_key(user, name, email, key, crt, p12, index, serial)
assert_user(user)
u = @db[:users][user]
u[:modified] = Time.now
u[:active_key] += 1
add_key(user, key, crt, p12, u[:active_key])
@db.dump('serial', serial, true)
@db.dump('index.txt', index, true)
@db.touched!
@db.sync
end
def user_key_revoked(user, version, crl, index)
assert_user(user)
raise "Verison must be an int" unless version.kind_of?(Integer)
u = @db[:users][user]
u[:revoked] << version
u[:modified] = Time.now
@db.dump('index.txt', index, true)
@db.dump('crl.pem', crl, true)
@db.touched!
@db.sync
end
def revoked?(user, version)
assert_user(user)
@db[:users][user][:revoked].include?(version)
end
def active_key_version(user)
assert_user(user)
@db[:users][user][:active_key]
end
def user(user)
assert_user(user)
@db[:users][user]
end
def users; @db[:users]; end
def initialize(name, dir)
@db = KeyDB.new(File.join(dir, name + '.db.yaml'))
@config = KeyConfig.new(File.join(dir, name + '.config.yaml'))
@builder = KeyBuilder.new(self, @config)
end
end
def self.generate(name, path)
KeyTracker.generate(name, path)
end
class Manager
attr_reader :tracker
def self.vpn_name(dir); dir =~ /(^|\/)([^\/\.]+)\.vpn/ ? $2 : nil; end
def initialize(dir)
name = self.class.vpn_name(File.expand_path(dir))
@tracker = KeyTracker.new(name, File.expand_path(dir))
end
def config; @tracker.config; end
def build_ca; @tracker.builder.build_ca; end
def build_server
@tracker.builder.build_server_key
@tracker.builder.build_ta_key
@tracker.builder.build_dh_key
end
def create_user(user, name, email, pass=nil)
@tracker.builder.build_key(user, name, email, pass, :add_user)
end
def revoke_all(user)
cur = @tracker.active_key_version(user)
while cur >= 0
unless @tracker.revoked?(user, cur)
@tracker.builder.revoke_key(user, cur)
end
cur -= 1
end
end
def regenerate_user(user, pass=nil)
revoke_all(user)
u = @tracker.user(user)
@tracker.builder.build_key(user, u[:name], u[:email], pass, :add_user_key)
end
def delete_user(user)
revoke_all(user)
end
def users
@tracker.users.keys
end
def user(user)
@tracker.user(user)
end
def config_generator; ConfigGenerator.new(self); end
end
class KeyBuilder
def initialize(tracker, config)
@tmpdir = '/tmp/keybuilder'
clean_tmpdir
@tracker = tracker
@config = config
end
def clean_tmpdir
FileUtils.rm_rf(@tmpdir)
FileUtils.mkdir_p(@tmpdir)
end
def cnfpath; "/tmp/openssl-#{$$}.cnf"; end
def opensslvars
{
:key_size => 1024,
:key_dir => @tmpdir,
:key_country => @config[:key_properties][:country],
:key_province => @config[:key_properties][:province],
:key_city => @config[:key_properties][:city],
:key_org => @config[:key_properties][:organization],
:key_email => @config[:key_properties][:email],
:key_org => @config[:key_properties][:organization],
:key_ou => 'Organization Unit',
:key_cn => 'Common Name',
:key_name => 'Name'
}
end
def init
`touch #{@dir}/index.txt`
`echo 01 > #{@dir}/serial`
end
def opensslcnf(hash={})
c = cnfpath
File.open(cnfpath, 'w') do |f|
f.write(ERB.new(File.read(__FILE__.path('openssl.erb'))).\
result(HashBinding.from_hash(opensslvars.merge(hash)).binding))
end
c
end
# Build Diffie-Hellman parameters for the server side of an SSL/TLS connection.
def build_dh_key(keysize=1024)
`openssl dhparam -out #{tmppath('dh.pem')} #{keysize}`
@tracker.set_dh(tmpfile('dh.pem'))
end
def ca
@tracker[:ca]
end
def gen_crl
`openssl ca -gencrl -crldays 3650 -keyfile #{tmppath('ca.key')} -cert #{tmppath('ca.crt')} -out #{tmppath('crl.pem')} -config #{opensslcnf}`
end
def build_ca
index = tmppath('index.txt')
FileUtils.touch(index)
`openssl req -batch -days 3650 -nodes -new -x509 -keyout #{@tmpdir}/ca.key -out #{@tmpdir}/ca.crt -config #{opensslcnf}`
gen_crl
@tracker.set_ca(tmpfile('ca.key'), tmpfile('ca.crt'), tmpfile('crl.pem'), tmpfile('index.txt'), "01\n")
end
def build_server_key
place_file('ca.crt')
place_file('ca.key')
place_file('index.txt')
place_file('serial')
`openssl req -batch -days 3650 -nodes -new -keyout #{tmppath('server.key')} -out #{tmppath('server.csr')} -extensions server -config #{opensslcnf}`
`openssl ca -batch -days 3650 -out #{tmppath('server.crt')} -in #{tmppath('server.csr')} -extensions server -config #{opensslcnf}`
@tracker.set_server_key(tmpfile('server.key'), tmpfile('server.crt'), tmpfile('index.txt'), tmpfile('serial'))
end
def build_ta_key
`openvpn --genkey --secret #{tmppath('ta.key')}`
@tracker.set_ta_key(tmpfile('ta.key'))
end
def place_file(name)
if data = @tracker.db.data(name)
File.open(File.join(@tmpdir, name), 'w') {|f| f.write(data)}
else
raise "No data for #{name}"
end
end
def tmppath(f, extn=nil); File.join(@tmpdir, extn ? "#{f}.#{extn}" : f); end
def tmpfile(*args); File.read(tmppath(*args)); end
def build_key(user, name, email, pass, delegate)
h = {:key_cn => user, :key_name => name, :key_email => email}
place_file('ca.crt')
place_file('ca.key')
place_file('index.txt')
place_file('serial')
if pass
pass_spec = "-passin 'pass:#{pass}' -passout 'pass:#{pass}'"
else
pass_spec = '-nodes'
end
`openssl req -batch -days 3650 -new -keyout #{tmppath(user, 'key')} -out #{tmppath(user, 'csr')} -config #{opensslcnf(h)} #{pass_spec}`
`openssl ca -batch -days 3650 -out #{tmppath(user, 'crt')} -in #{tmppath(user, 'csr')} -config #{opensslcnf(h)}`
# TODO: this still asks for the export password
`openssl pkcs12 -export -clcerts -in #{tmppath(user, 'crt')} -inkey #{tmppath(user, 'key')} -out #{tmppath(user, 'p12')} #{pass_spec}`
@tracker.send(delegate, user, name, email, tmpfile(user, 'key'), tmpfile(user, 'crt'), tmpfile(user, 'p12'), tmpfile('index.txt'), tmpfile('serial'))
end
def revoke_key(user, version)
h = {:key_cn => ""}
place_file('ca.crt')
place_file('ca.key')
place_file('crl.pem')
place_file('index.txt')
place_file('serial')
user_crt = tmppath(user, 'crt')
rev_crt = tmppath('rev-test.crt')
File.open(user_crt, 'w') {|f| f.write(@tracker.key(user, version, 'crt'))}
`openssl ca -revoke #{user_crt} -keyfile #{tmppath('ca.key')} -cert #{tmppath('ca.crt')} -config #{opensslcnf(h)}`
gen_crl
File.open(rev_crt, 'w') {|f| f.write(File.read(tmppath('ca.crt'))); f.write(File.read(tmppath('crl.pem')))}
if `openssl verify -CAfile #{rev_crt} -crl_check #{user_crt}` =~ /certificate revoked/
@tracker.user_key_revoked(user, version, tmpfile('crl.pem'), tmpfile('index.txt'))
else
raise "Revocation verification failed: openssl isn't recognizing it"
end
end
end
end