Class: MPW::MPW

Inherits:
Object
  • Object
show all
Defined in:
lib/mpw/mpw.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, wallet_file, gpg_pass = nil, gpg_exe = nil) ⇒ MPW

Constructor



30
31
32
33
34
35
36
37
38
39
# File 'lib/mpw/mpw.rb', line 30

def initialize(key, wallet_file, gpg_pass=nil, gpg_exe=nil)
	@key         = key
	@gpg_pass    = gpg_pass
	@gpg_exe     = gpg_exe
	@wallet_file = wallet_file

	if @gpg_exe
		GPGME::Engine.set_info(GPGME::PROTOCOL_OpenPGP, @gpg_exe, "#{Dir.home}/.gnupg")
	end
end

Class Method Details

.password(options = {}) ⇒ Object

Generate a random password @args: options -> :length, :special, :alpha, :numeric @rtrn: a random string



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/mpw/mpw.rb', line 455

def self.password(options={})
	if not options.include?(:length) or options[:length].to_i <= 0
		length = 8
	elsif options[:length].to_i >= 32768
		length = 32768
	else
		length = options[:length].to_i
	end

	chars = []
	chars += [*('!'..'?')] - [*('0'..'9')]        if options.include?(:special)
	chars += [*('A'..'Z'),*('a'..'z')]            if options.include?(:alpha)
	chars += [*('0'..'9')]                        if options.include?(:numeric)
	chars = [*('A'..'Z'),*('a'..'z'),*('0'..'9')] if chars.empty?

	result = ''
	while length > 62 do
		result << chars.sample(62).join
		length -= 62
	end
	result << chars.sample(length).join

	return result
end

Instance Method Details

#add(item) ⇒ Object

Add a new item @args: item -> Object MPW::Item



228
229
230
231
232
233
234
235
236
# File 'lib/mpw/mpw.rb', line 228

def add(item)
	if not item.instance_of?(Item)
		raise I18n.t('error.bad_class')
	elsif item.empty?
		raise I18n.t('error.add.empty')
	else
		@data.push(item)
	end
end

#add_key(key, file = nil) ⇒ Object

Add a public key args: key -> new public key

file -> public gpg file to import


191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/mpw/mpw.rb', line 191

def add_key(key, file=nil)
	if not file.nil? and File.exists?(file)
		data = File.open(file).read
		GPGME::Key.import(data, armor: true)
	else
		data = GPGME::Key.export(key, armor: true).read
	end

	if data.to_s.empty?
		raise I18n.t('error.export_key')
	end

	@keys[key] = data
end

#delete_key(key) ⇒ Object

Delete a public key args: key -> public key to delete



208
209
210
# File 'lib/mpw/mpw.rb', line 208

def delete_key(key)
	@keys.delete(key)
end

#export(file) ⇒ Object

Export to yaml @args: file -> file where you export the data



278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/mpw/mpw.rb', line 278

def export(file)
	data = {}
	@data.each do |item|
		data.merge!(item.id => {'id'        => item.id,
		                        'name'      => item.name,
		                        'group'     => item.group,
		                        'host'      => item.host,
		                        'protocol'  => item.protocol,
		                        'user'      => item.user,
		                        'password'  => get_password(item.id),
		                        'port'      => item.port,
		                        'comment'   => item.comment,
		                        'last_edit' => item.last_edit,
		                        'created'   => item.created,
		                       }
		            )
	end

	File.open(file, 'w') {|f| f << data.to_yaml}
rescue Exception => e 
	raise "#{I18n.t('error.export', file: file)}\n#{e}"
end

#get_last_syncObject

Get last sync



324
325
326
327
328
# File 'lib/mpw/mpw.rb', line 324

def get_last_sync
	return @config['sync']['last_sync'].to_i
rescue
	return 0
end

#get_otp_code(id) ⇒ Object

Get an otp code @args: id -> the item id @rtrn: an otp code



438
439
440
441
442
443
444
# File 'lib/mpw/mpw.rb', line 438

def	get_otp_code(id)
	if not @otp_keys.has_key?(id)
		return 0
	else
		return ROTP::TOTP.new(decrypt(@otp_keys[id])).now
	end
end

#get_otp_remaining_timeObject

Get remaining time before expire otp code @rtrn: return time in seconde



448
449
450
# File 'lib/mpw/mpw.rb', line 448

def get_otp_remaining_time
	return (Time.now.utc.to_i / 30 + 1) * 30 - Time.now.utc.to_i
end

#get_password(id) ⇒ Object

Get a password args: id -> the item id



168
169
170
171
172
173
174
175
176
# File 'lib/mpw/mpw.rb', line 168

def get_password(id)
	password = decrypt(@passwords[id])
	
	if /^\$[a-zA-Z0-9]{4,9}::(?<password>.+)$/ =~ password
		return Regexp.last_match('password')
	else
		return password
	end
end

#import(file) ⇒ Object

Import to yaml @args: file -> path to file import



303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/mpw/mpw.rb', line 303

def import(file)
	YAML::load_file(file).each_value do |row| 
		item = Item.new(name:     row['name'], 
		                group:    row['group'],
		                host:     row['host'],
		                protocol: row['protocol'],
		                user:     row['user'],
		                port:     row['port'],
		                comment:  row['comment'],
		               )

		raise 'Item is empty' if item.empty?

		@data.push(item)
		set_password(item.id, row['password'])
	end
rescue Exception => e 
	raise "#{I18n.t('error.import', file: file)}\n#{e}"
end

#list(options = {}) ⇒ Object

Search in some csv data @args: options -> a hash with paramaters @rtrn: a list with the resultat of the search



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/mpw/mpw.rb', line 241

def list(options={})
	result = []

	search   = options[:search].to_s.downcase
	group    = options[:group].to_s.downcase

	@data.each do |item|
		next if item.empty?
		next if not group.empty?    and not group.eql?(item.group.downcase)
		
		name    = item.name.to_s.downcase
		host    = item.host.to_s.downcase
		comment = item.comment.to_s.downcase

		if not name =~ /^.*#{search}.*$/ and not host =~ /^.*#{search}.*$/ and not comment =~ /^.*#{search}.*$/ 
			next
		end

		result.push(item)
	end

	return result
end

#read_dataObject

Read mpw file



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
# File 'lib/mpw/mpw.rb', line 42

def read_data
	@config    = {}
	@data      = []
	@keys      = {}
	@passwords = {}
	@otp_keys  = {}

	data       = nil

	return if not File.exists?(@wallet_file)

	Gem::Package::TarReader.new(File.open(@wallet_file)) do |tar|
		tar.each do |f| 
			case f.full_name
				when 'wallet/config.gpg'
					@config = YAML.load(decrypt(f.read))

				when 'wallet/meta.gpg'
					data = decrypt(f.read)

				when /^wallet\/keys\/(?<key>.+)\.pub$/
					key = Regexp.last_match('key')

					if GPGME::Key.find(:public, key).length == 0
						GPGME::Key.import(f.read, armor: true)
					end

					@keys[key] = f.read

				when /^wallet\/passwords\/(?<id>[a-zA-Z0-9]+)\.gpg$/
					@passwords[Regexp.last_match('id')] = f.read

				when /^wallet\/otp_keys\/(?<id>[a-zA-Z0-9]+)\.gpg$/
					@otp_keys[Regexp.last_match('id')] = f.read

				else
					next
			end
		end
	end

	if not data.nil? and not data.empty?
		YAML.load(data).each_value do |d|
			@data.push(Item.new(id:        d['id'],
			                    name:      d['name'],
			                    group:     d['group'],
			                    host:      d['host'],
			                    protocol:  d['protocol'],
			                    user:      d['user'],
			                    port:      d['port'],
			                    comment:   d['comment'],
			                    last_edit: d['last_edit'],
			                    created:   d['created'],
			                   )
			          )
		end
	end

	add_key(@key) if @keys[@key].nil?
rescue Exception => e
	raise "#{I18n.t('error.mpw_file.read_data')}\n#{e}"
end

#search_by_id(id) ⇒ Object

Search in some csv data @args: id -> the id item @rtrn: a row with the result of the search



268
269
270
271
272
273
274
# File 'lib/mpw/mpw.rb', line 268

def search_by_id(id)
	@data.each do |item|
		return item if item.id == id
	end

	return nil
end

#set_config(config) ⇒ Object

Set config args: config -> a hash with config options



214
215
216
217
218
219
220
221
222
223
224
# File 'lib/mpw/mpw.rb', line 214

def set_config(config)
	@config['sync'] = {} if @config['sync'].nil?

	@config['sync']['type']      = config['sync']['type']
	@config['sync']['host']      = config['sync']['host']
	@config['sync']['port']      = config['sync']['port']
	@config['sync']['user']      = config['sync']['user']
	@config['sync']['password']  = config['sync']['password']
	@config['sync']['path']      = config['sync']['path']
	@config['sync']['last_sync'] = @config['sync']['last_sync'].nil? ? 0 : @config['sync']['last_sync']
end

#set_otp_key(id, key) ⇒ Object

Set an opt key args: id -> the item id

key -> the new key


431
432
433
# File 'lib/mpw/mpw.rb', line 431

def set_otp_key(id, key)
	@otp_keys[id] = encrypt(key)
end

#set_password(id, password) ⇒ Object

Set a password args: id -> the item id

password -> the new password


181
182
183
184
185
186
# File 'lib/mpw/mpw.rb', line 181

def set_password(id, password)
	salt     = MPW::password(length: Random.rand(4..9))
	password = "$#{salt}::#{password}"

	@passwords[id] = encrypt(password)
end

#sync(force = false) ⇒ Object

Sync data with remote file @args: force -> force the sync



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
# File 'lib/mpw/mpw.rb', line 332

def sync(force=false)
	return if @config.empty? or @config['sync']['type'].to_s.empty?
	return if get_last_sync + 300 > Time.now.to_i and not force

	tmp_file  = "#{@wallet_file}.sync"
	
	case @config['sync']['type']
	when 'sftp', 'scp', 'ssh'
		require "mpw/sync/ssh"
		sync = SyncSSH.new(@config['sync'])
	when 'ftp'
		require 'mpw/sync/ftp'
		sync = SyncFTP.new(@config['sync'])
	else
		raise I18n.t('error.sync.unknown_type')
	end

	sync.connect
	sync.get(tmp_file)

	remote = MPW.new(@key, tmp_file, @gpg_pass, @gpg_exe)
	remote.read_data

	File.unlink(tmp_file) if File.exist?(tmp_file)

	return if remote.get_last_sync == @config['last_update']

	if not remote.to_s.empty?
		@data.each do |item|
			update = false

			remote.list.each do |r|
				next if item.id != r.id

				# Update item
				if item.last_edit < r.last_edit
					item.update(name:      r.name,
					            group:     r.group,
					            host:      r.host,
					            protocol:  r.protocol,
					            user:      r.user,
					            port:      r.port,
					            comment:   r.comment
					           )
					set_password(item.id, remote.get_password(item.id))
				end

				r.delete
				update = true

				break
			end

			# Remove an old item
			if not update and item.last_sync.to_i < get_last_sync and item.last_edit < get_last_sync
				item.delete
			end
		end
	end

	# Add item
	remote.list.each do |r|
		next if r.last_edit <= get_last_sync

		item = Item.new(id:        r.id,
		                name:      r.name,
		                group:     r.group,
		                host:      r.host,
		                protocol:  r.protocol,
		                user:      r.user,
		                port:      r.port,
		                comment:   r.comment,
		                created:   r.created,
		                last_edit: r.last_edit
		               )

		set_password(item.id, remote.get_password(item.id))
		add(item)
	end

	remote = nil

	@data.each do |item|
		item.set_last_sync
	end

	@config['sync']['last_sync'] = Time.now.to_i

	write_data
	sync.update(@wallet_file)
rescue Exception => e
	File.unlink(tmp_file) if File.exist?(tmp_file)

	raise "#{I18n.t('error.sync.general')}\n#{e}"
end

#write_dataObject

Encrypt a file



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
# File 'lib/mpw/mpw.rb', line 106

def write_data
	data     = {}
	tmp_file = "#{@wallet_file}.tmp"

	@data.each do |item|
		next if item.empty?

		data.merge!(item.id => {'id'        => item.id,
		                        'name'      => item.name,
	                            'group'     => item.group,
		                        'host'      => item.host,
		                        'protocol'  => item.protocol,
		                        'user'      => item.user,
		                        'port'      => item.port,
		                        'comment'   => item.comment,
		                        'last_edit' => item.last_edit,
		                        'created'   => item.created,
		                       }
		           )
	end

	@config['last_update'] = Time.now.to_i

	Gem::Package::TarWriter.new(File.open(tmp_file, 'w+')) do |tar|
		data_encrypt = encrypt(data.to_yaml)
		tar.add_file_simple('wallet/meta.gpg', 0400, data_encrypt.length) do |io|
			io.write(data_encrypt)
		end

		config = encrypt(@config.to_yaml)
		tar.add_file_simple('wallet/config.gpg', 0400, config.length) do |io|
			io.write(config)
		end

		@passwords.each do |id, password|
			tar.add_file_simple("wallet/passwords/#{id}.gpg", 0400, password.length) do |io|
				io.write(password)
			end
		end

		@otp_keys.each do |id, key|
			tar.add_file_simple("wallet/otp_keys/#{id}.gpg", 0400, key.length) do |io|
				io.write(key)
			end
		end

		@keys.each do |id, key|
			tar.add_file_simple("wallet/keys/#{id}.pub", 0400, key.length) do |io|
				io.write(key)
			end
		end
	end

	File.rename(tmp_file, @wallet_file)
rescue Exception => e
	File.unlink(tmp_file)

	raise "#{I18n.t('error.mpw_file.write_data')}\n#{e}"
end