-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.rb
executable file
·630 lines (542 loc) · 15.4 KB
/
app.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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
require 'bundler'
require 'sinatra'
require 'webrick/https'
require 'sinatra/json'
require 'sinatra/namespace'
require 'sinatra/base'
require 'sinatra/reloader'
require 'sinatra/custom_logger'
require 'logger'
require 'sequel'
require 'sqlite3'
require 'json'
require 'logger'
require 'pry'
require 'mail'
require 'listen'
require 'dotenv/load'
require 'bcrypt'
require 'openssl'
require 'jwt'
require 'rack/attack'
require 'active_support/time'
require 'active_support/cache'
require_relative 'src/server/notifications'
require_relative 'src/server/log_parser.rb'
require_relative 'src/server/api.rb'
##
# Connect to SQLite
DB = Sequel.connect('sqlite://hashpass.db')
DB[:active].delete
##
# Hash model
class Hashes < Sequel::Model(DB[:hashes])
end
##
# Attack History model
class History < Sequel::Model(DB[:history])
end
##
# Dictionary model
class Dics < Sequel::Model(DB[:dictionaries])
end
##
# Rules model
class Rules < Sequel::Model(DB[:rules])
end
##
# RottenPi model
class Rotten < Sequel::Model(DB[:rotten])
end
##
# User model
class User < Sequel::Model
include BCrypt
def password
@password ||= Password.new(password_hash)
end
def password=(new_password)
@password = Password.create(new_password)
self.password_hash = @password
end
end
class Rack::Attack
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
if ENV['APP_ENV'] == 'development'
Rack::Attack.safelist("localhost") { |req| req.ip == "127.0.0.1" }
end
# Block too many login attempts
throttle('hplogin', limit: 90, period: 90.seconds) do |req|
if req.path == '/hplogin' && req.post?
req.ip
end
end
# Block too many requests
throttle('req/ip', limit: 137, period: 5.minutes) do |req|
ignore = ['status','running','pending','cracked', 'heartbeat', 'getcmd', 'command', 'agent']
unless ignore.any? { |i| req.path.include?(i) }
req.ip
end
end
end
##
# Public (user not authorized)
class Public < Sinatra::Base
helpers Sinatra::CustomLogger
set :environment, :production if ENV['APP_ENV'] == 'production'
configure :development, :production do
logger = Logger.new(File.open("#{root}/logs/#{environment}.log", 'a'))
logger.level = Logger::DEBUG if development?
set :logger, logger
end
def initialize
super
end
not_found do
File.read(File.join('public', 'app.html'))
end
def ip(request)
"[#{ request.env['REMOTE_ADDR'] }] --> "
end
get '/wpa/:ssid' do
response.headers['Cache-Control'] = 'public, max-age=1'
exists = DB[:hashes].where(name: params['ssid']).first
if exists
ssid = params['ssid']
password = DB[:hashes].where(name: params['ssid']).get(:loot)
if password
password = password.delete("\n").rstrip
else
return [201, {}, ['']]
end
conf = <<~HEREDOC
update_config=1
network={
ssid="#{ ssid }"
psk="#{ password }"
}
HEREDOC
File.write("wpa/#{ ssid }_wpa_supplicant.conf", conf)
send_file("./wpa/#{ ssid }_wpa_supplicant.conf",
:filename => ".wpa/#{ ssid }_wpa_supplicant.conf",
:type => 'Application/octet-stream'
)
else
[201, {}, ['']]
end
end
# get '/agent/attackplan' do
# plan = [
# # {
# # actions: ['pmkid', 'shutdown:60']
# # },
# {
# ssid: "The Darkside",
# actions: ['recon']
# },
# # {
# # ssid: 'Bird1',
# # actions: ['recon', 'shutdown']
# # }
# # ssid: ["Luna Secret Rlouter"],
# # ssid: ["Luna's Wooffi"]
# ].to_json
# end
post '/agent-upload' do
puts "Agent Upload! #{request.body}"
logger.info "#{ request.inspect } Agent uploading files: #{ params[:files] }."
# verify_scope request, 'create' do |req, username|
api = API.new
puts "params: #{ params }"
p api.agent_upload(params[:files], params[:ssid])
json success: true
# end
end
get '/agent/logs/:ssid' do
response.headers['Cache-Control'] = 'public, max-age=1'
begin
json Dir["agent/#{ params['ssid'] }/log/*"].map! { |f| f.split('/').last }
rescue
[201, {}, ['']]
next
end
end
get '/agent/log/:ssid/:log' do
begin
File.read("agent/#{ params['ssid'] }/log/#{ params['log'] }")
rescue
[201, {}, ['']]
next
end
end
get '/agent/ssh' do
`/root/hashpass/src/server/oterm.sh /root/hashpass/src/server/autos.sh`
[200, {}, ['']]
end
get '/' do
logger.info "#{ request.inspect } get / ."
File.read(File.join('public', 'app.html'))
end
post '/hplogin' do
request.body.rewind
params = JSON.parse(request.body.read)
@user = User.first(email: params['handle'])
if @user.nil? || params['handle'].empty?
logger.warn "#{ ip(request) } User #{params['handle']} doesn't exist."
halt 401
elsif params['handle'].empty?
logger.warn "#{ ip(request) } User didn't supply username."
halt 401
elsif @user.password == params['password']
logger.info "++ #{ ip(request) } User #{params['handle']} (#{@user.role}) logged in."
hmac_secret = ENV['SECRET']
scope =
if @user.role == 'admin'
['create', 'read', 'update', 'delete', 'user_management', 'loot']
else
['create', 'read', 'update', 'loot']
end
payload = {
exp: Time.now.to_i + 60 * 60 * 24,
iat: Time.now.to_i,
iss: ENV['JWT_ISSUER'],
scopes: scope,
user: {
username: @user.email
}
}
token = JWT.encode(payload, hmac_secret, 'HS256')
decoded_token = JWT.decode token, hmac_secret, true, { algorithm: 'HS256' }
{ token: token }.to_json
else
logger.warn "#{ request.inspect } Wrong password for #{@user.email} (#{ params['password'] })."
halt 401
end
end
end
##
# JSON Web Tokens
class JwtAuth
def initialize app
@app = app
end
def call env
begin
options = { algorithm: 'HS256', iss: ENV['JWT_ISSUER'] }
bearer = env.fetch('HTTP_AUTHORIZATION', '').slice(7..-1)
payload, header = JWT.decode bearer, ENV['SECRET'], true, options
env[:scopes] = payload['scopes']
env[:user] = payload['user']
@app.call env
rescue JWT::DecodeError
[ 401, { 'Content-Type' => 'text/html' }, [File.read(File.join('public', 'app.html'))] ]
rescue JWT::ExpiredSignature
[ 403, { 'Content-Type' => 'text/html' }, [File.read(File.join('public', 'app.html'))] ]
rescue JWT::InvalidIssuerError
[ 403, { 'Content-Type' => 'text/html' }, [File.read(File.join('public', 'app.html'))] ]
rescue JWT::InvalidIatError
[ 403, { 'Content-Type' => 'text/html' }, [File.read(File.join('public', 'app.html'))] ]
end
end
end
##
# API
class Api < Sinatra::Base
use JwtAuth
register Sinatra::Namespace
helpers Sinatra::CustomLogger
api = API.new
notifications = Notifications.new
set :environment, :production if ENV['APP_ENV'] == 'production'
configure :development do
register Sinatra::Reloader
end
configure :development, :production do
logger = Logger.new(File.open("#{root}/logs/#{environment}.log", 'a'))
logger.level = Logger::DEBUG if development?
set :logger, logger
end
def initialize
super
end
def ip(request)
"[#{ request.env['REMOTE_ADDR'] }] --> "
end
def verify_scope req, scope
scopes, user = req.env.values_at :scopes, :user
username = user['username'].to_sym if user['username']
if scopes.include?(scope)
yield req, username
else
halt 403
end
end
not_found do
api.main_page
end
# Agent updates
['checkin', 'checkout', 'heartbeat', 'command'].each do |endpoint|
post "/agent/#{ endpoint }" do
verify_scope request, 'update' do |req, username|
request.body.rewind
param = JSON.parse(request.body.read)
DB[:rotten].insert(
user: request.env[:user]['username'],
event: endpoint.upcase,
result: param['result'],
function: param['function'],
arguments: param['arguments'],
timestamp: Time.now.to_s
)
[200, {}, ['']]
end
end
end
post '/agent/newcommand' do
puts "params: #{params}"
verify_scope request, 'create' do |req, username|
request.body.rewind
param = JSON.parse(request.body.read)
puts "param: #{param}"
DB[:rotten_cmd].insert(
user: param['user'],
function: param['function'],
arguments: param['arguments'],
timestamp: Time.now.to_s
)
[200, {}, ['']]
end
end
get '/agent/commands' do
verify_scope request, 'read' do |req, username|
status 204 if DB[:rotten_cmd].all.empty?
json DB[:rotten_cmd].all
end
end
get '/agent/:user/getcmd' do
cmd = DB[:rotten_cmd].where(user: params['user']).all
DB[:rotten_cmd].where(user: params['user']).delete
json cmd
end
delete '/agent/rotten/command/:id' do
verify_scope request, 'delete' do |req, username|
deleted = DB[:rotten_cmd].where(id: params['id']).delete
json deleted: deleted if deleted
end
end
delete '/agent/rotten/commands' do
verify_scope request, 'delete' do |req, username|
deleted = DB[:rotten_cmd].delete
[200, {}, ['']] if deleted
end
end
get '/agent/rotten' do
verify_scope request, 'read' do |req, username|
status 204 if DB[:rotten].all.empty?
json DB[:rotten].all
end
end
delete '/agent/rotten' do
verify_scope request, 'delete' do |req, username|
deleted = DB[:rotten].delete
[200, {}, ['']] if deleted
end
end
get '/start' do
verify_scope request, 'update' do |req, username|
logger.info "#{ ip(request) } Starting attack."
pending = DB[:pending].first
active = DB[:active].first
if active.nil? && pending
api.promote
json pid: api.start(active)
end
json pid: api.start(active)
end
end
get '/stop/:id' do
verify_scope request, 'update' do |req, username|
logger.info "#{ ip(request) } Stopping attack."
api.stop
json killed: true
end
end
post '/upload' do
puts "Upload! #{request}"
logger.info "#{ request.inspect } Uploading files: #{ params[:files] }."
verify_scope request, 'create' do |req, username|
p api.upload(params[:files])
json success: true
end
end
get '/status' do
verify_scope request, 'read' do |req, username|
if DB[:active].first
active = DB[:active].first
json api.status(active)
else
status 204
end
end
end
get '/dics' do
verify_scope request, 'read' do |req, username|
status 204 if DB[:dictionaries].all.empty?
json DB[:dictionaries].reverse_order(:size).all
end
end
post '/dic' do
verify_scope request, 'create' do |req, username|
logger.info "#{ ip(request) } Created dictionary #{ params['name'] }."
request.body.rewind
json api.insert_dic(JSON.parse(request.body.read))
end
end
delete '/dic/:id' do
verify_scope request, 'delete' do |req, username|
deleted = Dics.where(id: params['id']).delete
json deleted: deleted if deleted
end
end
get '/rules' do
verify_scope request, 'read' do |req, username|
status 204 if DB[:rules].all.empty?
json DB[:rules].all
end
end
post '/rule' do
verify_scope request, 'create' do |req, username|
logger.info "#{ ip(request) } Created rule #{ params['name'] }."
request.body.rewind
json api.insert_rule(JSON.parse(request.body.read)).values
end
end
delete '/rule/:id' do
verify_scope request, 'delete' do |req, username|
logger.info "#{ ip(request) } Created rule #{ params['id'] }."
deleted = Rules.where(id: params['id']).delete
json deleted: deleted if deleted
end
end
get '/users' do
verify_scope request, 'user_management' do |req, username|
status 204 if DB[:users].all.empty?
json DB[:users].all
end
end
post '/user' do
verify_scope request, 'user_management' do |req, username|
request.body.rewind
param = JSON.parse(request.body.read)
logger.warn "!! #{ ip(request) } Created User #{ param['name'] } !!"
@new_user =
User.new(
email: param['name'],
password: param['password'],
role: param['role'])
json @new_user.save
end
end
delete '/user/:id' do
verify_scope request, 'user_management' do |req, username|
logger.warn "!! #{ ip(request) } #{username} deleted user #{ params['id'] } !!"
deleted = User.where(id: params['id']).delete
json deleted: deleted if deleted
end
end
get '/hashes' do
verify_scope request, 'read' do |req, username|
status 204 if DB[:hashes].all.empty?
json DB[:hashes].reverse_order(:added).all
end
end
get '/history' do
verify_scope request, 'read' do |req, username|
status 204 if DB[:history].all.empty?
json DB[:history].reverse_order(:started_on).all
end
end
get '/history/:id' do
verify_scope request, 'read' do |req, username|
history =
DB[:history]
.where(hashid: params['id'])
.reverse_order(:started_on)
.all
json history ? history : 'not found'
end
end
delete '/hashes/:id' do
verify_scope request, 'delete' do |req, username|
logger.warn "#{ ip(request) } Deleted hash #{ params['id'] }."
deleted = Hashes.where(id: params['id']).delete
json deleted: deleted if deleted
end
end
post '/hashes/insert' do
verify_scope request, 'create' do |req, username|
logger.info "#{ ip(request) } Created Hash #{ params['name'] }."
request.body.rewind
api.insert_hash(JSON.parse(request.body.read))
end
end
namespace '/running' do
get do
verify_scope request, 'read' do |req, username|
status 204 if DB[:active].all.empty?
json running: DB[:active].all
end
end
delete do
verify_scope request, 'delete' do |req, username|
logger.info "#{ ip(request) } Deleted running."
json success: true if DB[:active].delete
end
end
get '/promote' do
verify_scope request, 'update' do |req, username|
json success: api.promote
end
end
end
namespace '/pending' do
get do
verify_scope request, 'read' do |req, username|
json pending: DB[:pending].all
end
end
delete do
verify_scope request, 'delete' do |req, username|
logger.info "#{ ip(request) } Deleted queue."
DB[:pending].delete
json success: true
end
end
post do
verify_scope request, 'create' do |req, username|
logger.info "#{ ip(request) } Added to queue."
request.body.rewind
json success: true if api.new(JSON.parse(request.body.read))
end
end
end
namespace '/cracked' do
get do
verify_scope request, 'loot' do |req, username|
status 204 if DB[:cracked].all.empty?
json cracked: DB[:cracked].all
end
end
delete do
verify_scope request, 'delete' do |req, username|
logger.info "#{ ip(request) } Slingn crack."
json success: true if DB[:cracked].delete
end
end
get '/:id' do
verify_scope request, 'loot' do |req, username|
json cracked: DB[:cracked].where(id: params['id']).first
end
end
end
end