-
Notifications
You must be signed in to change notification settings - Fork 680
Expand file tree
/
Copy pathevil-winrm.rb
More file actions
executable file
·1891 lines (1680 loc) · 153 KB
/
evil-winrm.rb
File metadata and controls
executable file
·1891 lines (1680 loc) · 153 KB
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env ruby
# frozen_string_literal: true
# Author: CyberVaca
# Twitter: https://twitter.com/CyberVaca_
# Based on the Alamot's original code
# Dependencies
require 'English'
require 'winrm'
require 'winrm-fs'
require 'stringio'
require 'base64'
require 'readline'
require 'optionparser'
require 'io/console'
require 'time'
require 'fileutils'
require 'logger'
require 'shellwords'
# Constants
# Version
VERSION = '3.9'
# Msg types
TYPE_INFO = 0
TYPE_ERROR = 1
TYPE_WARNING = 2
TYPE_DATA = 3
TYPE_SUCCESS = 4
# Global vars
# Available commands
$LIST = %w[Bypass-4MSI services upload download clear cls menu exit]
$COMMANDS = $LIST.dup
$CMDS = $COMMANDS.clone
$LISTASSEM = [''].sort
$DONUTPARAM1 = ['-process_id']
$DONUTPARAM2 = ['-donutfile']
# menu and show-global-methods commands
$MENU_CMD = ""
$SHOW_GLOBAL_METHODS_CMD = ""
$WORDS_RANDOM_CASE = [
'[Runtime.InteropServices.Marshal]',
'System.Runtime.InteropServices.Marshal',
'System.Reflection.Emit.AssemblyBuilderAccess',
'System.Reflection.CallingConventions',
'System.Reflection.AssemblyName',
'System.MulticastDelegate',
'GetDelegateForFunctionPointer',
'Import-PowerShellDataFile',
'ImportSystemModules',
'New-TemporaryFile',
'.MakeByRefType',
'.CreateType',
'.DefineConstructor',
'.DefineMethod',
'.DefineDynamicModule',
'function ',
'WriteByte',
'[Ref]',
'Assembly.GetType',
'GetField',
'[System.Net.WebUtility]',
'HtmlDecode',
'Reflection.BindingFlags',
'NonPublic',
'Static',
'GetValue',
'ForEach-Object',
'Where-Object',
'Select-Object',
'.name',
'showmethods',
'function:',
'.CommandType',
'-contains',
'-notmatch',
'-like',
'-notlike',
'-notcontains',
'-and',
'ls ',
'$global',
'-Property'
]
# Colors and path completion
$colors_enabled = true
$check_rpath_completion = true
# Path for ps1 scripts and exec files
$scripts_path = ''
$executables_path = ''
# Connection vars initialization
$host = ''
$port = '5985'
$user = ''
$password = ''
$url = 'wsman'
$default_service = 'HTTP'
$full_logging_path = "#{Dir.home}/evil-winrm-logs"
$user_agent = "Microsoft WinRM Client"
$ccache_file = nil
$original_krb5ccname = nil
$kerberos_cleanup_registered = false
# Redefine download method from winrm-fs
module WinRM
module FS
class FileManager
def download(remote_path, local_path, chunk_size = 1024 * 1024, first = true, size: -1)
@logger.debug("downloading: #{remote_path} -> #{local_path} #{chunk_size}")
index = 0
return download_dir(remote_path, local_path, chunk_size, false) if remote_path.match?(/(\*\.?|\*\*|\.?\*|\*)/)
output = _output_from_file(remote_path, chunk_size, index)
return download_dir(remote_path, local_path, chunk_size, true) if output.exitcode == 2
return false if output.exitcode >= 1
File.open(local_path, 'wb') do |fd|
begin
out = _write_file(fd, output)
index += out.length
until out.empty?
yield index, size if size != -1
output = _output_from_file(remote_path, chunk_size, index)
return false if output.exitcode >= 1
out = _write_file(fd, output)
index += out.length
end
rescue EstandardError => err
@logger.debug("IO Failed: " + err.to_s)
raise
end
end
end
def download_dir(remote_path, local_path, chunk_size, first)
index_exp = remote_path.index(/(\*\.?|\*\*|\.?\*|\*)/) || 0
remote_file_path = remote_path
if index_exp > 0
index_last_folder = remote_file_path.rindex(/[\\\/]/, index_exp)
remote_file_path = remote_file_path[0..index_last_folder-1]
end
FileUtils.mkdir_p(local_path) unless File.directory?(local_path)
command = "Get-ChildItem #{remote_path} | Select-Object Name"
@connection.shell(:powershell) { |e| e.run(command) }.stdout.strip.split(/\n/).drop(2).each do |file|
download(File.join(remote_file_path.to_s, file.strip), File.join(local_path, file.strip), chunk_size, false)
end
end
true
end
end
end
# Class creation
class EvilWinRM
# Initialization
def initialize
@psLoaded = false
@directories = {}
@cache_ttl = 10
@executables = []
@functions = []
@Bypass_4MSI_loaded = false
end
# Remote path completion compatibility check
def completion_check
if $check_rpath_completion == true
begin
Readline.quoting_detection_proc
@completion_enabled = true
rescue NotImplementedError, NoMethodError => e
@completion_enabled = false
print_message("Remote path completions is disabled due to ruby limitation: #{e}", TYPE_WARNING)
print_message('For more information, check Evil-WinRM GitHub: https://github.com/Hackplayers/evil-winrm#Remote-path-completion', TYPE_DATA)
end
else
@completion_enabled = false
print_message('Remote path completion is disabled', TYPE_WARNING)
end
end
# Arguments
def arguments
options = { port: $port, url: $url, service: $service, user_agent: $user_agent }
optparse = OptionParser.new do |opts|
opts.banner = 'Usage: evil-winrm -i IP -u USER [-s SCRIPTS_PATH] [-e EXES_PATH] [-P PORT] [-a USERAGENT] [-p PASS] [-H HASH] [-U URL] [-S] [-c PUBLIC_KEY_PATH ] [-k PRIVATE_KEY_PATH ] [-r REALM] [-K TICKET_FILE] [--spn SPN_PREFIX] [-l]'
opts.on('-S', '--ssl', 'Enable ssl') do |_val|
$ssl = true
options[:port] = '5986'
end
opts.on('-c', '--pub-key PUBLIC_KEY_PATH', 'Local path to public key certificate') do |val|
options[:pub_key] = val
end
opts.on('-k', '--priv-key PRIVATE_KEY_PATH', 'Local path to private key certificate') do |val|
options[:priv_key] = val
end
opts.on('-r', '--realm DOMAIN',
'Kerberos auth, it has to be set also in /etc/krb5.conf file using this format -> CONTOSO.COM = { kdc = fooserver.contoso.com }') do |val|
options[:realm] = val.upcase
end
opts.on('-s', '--scripts PS_SCRIPTS_PATH', 'Powershell scripts local path') do |val|
options[:scripts] = val
end
opts.on('--spn SPN_PREFIX', 'SPN prefix for Kerberos auth (default HTTP)') { |val| options[:service] = val }
opts.on('-K', '--ccache TICKET_FILE', 'Path to Kerberos ticket file (ccache or kirbi format, auto-detected)') { |val| options[:ccache] = val }
opts.on('-e', '--executables EXES_PATH', 'C# executables local path') { |val| options[:executables] = val }
opts.on('-i', '--ip IP', 'Remote host IP or hostname. FQDN for Kerberos auth (required)') do |val|
options[:ip] = val
end
opts.on('-U', '--url URL', 'Remote url endpoint (default /wsman)') { |val| options[:url] = val }
opts.on('-u', '--user USER', 'Username (required if not using kerberos)') { |val| options[:user] = val }
opts.on('-p', '--password PASS', 'Password') { |val| options[:password] = val }
opts.on('-H', '--hash HASH', 'NTHash') do |val|
if !options[:password].nil? && !val.nil?
print_header
print_message('You must choose either password or hash auth. Both at the same time are not allowed', TYPE_ERROR)
custom_exit(1, false)
end
unless val.match(/^[a-fA-F0-9]{32}$/)
print_header
print_message('Invalid hash format', TYPE_ERROR)
custom_exit(1, false)
end
options[:password] = "00000000000000000000000000000000:#{val}"
end
opts.on('-P', '--port PORT', 'Remote host port (default 5985)') { |val| options[:port] = val }
opts.on('-a', '--user-agent USERAGENT', 'Specify connection user-agent (default Microsoft WinRM Client)') do |val|
options[:user_agent] = val
end
opts.on('-V', '--version', 'Show version') do |_val|
puts("v#{VERSION}")
custom_exit(0, false)
end
opts.on('-n', '--no-colors', 'Disable colors') do |_val|
$colors_enabled = false
end
opts.on('-N', '--no-rpath-completion', 'Disable remote path completion') do |_val|
$check_rpath_completion = false
end
opts.on('-l', '--log', 'Log the WinRM session') do |_val|
$log = true
$filepath = ''
$logfile = ''
$logger = ''
end
opts.on('-h', '--help', 'Display this help message') do
print_header
puts
puts(opts)
custom_exit(0, false)
end
end
begin
optparse.parse!
mandatory = if options[:realm].nil? && options[:priv_key].nil? && options[:pub_key].nil?
%i[ip user]
else
[:ip]
end
missing = mandatory.select { |param| options[param].nil? }
raise OptionParser::MissingArgument, missing.join(', ') unless missing.empty?
rescue OptionParser::InvalidOption, OptionParser::MissingArgument
print_header
print_message($ERROR_INFO.to_s, TYPE_ERROR, true, $logger)
puts
puts(optparse)
custom_exit(1, false)
end
if options[:password].nil? && options[:realm].nil? && options[:priv_key].nil? && options[:pub_key].nil?
options[:password] = $stdin.getpass(prompt = 'Enter Password: ')
end
$host = options[:ip]
$user = options[:user]
$password = options[:password]
$port = options[:port]
$scripts_path = options[:scripts]
$executables_path = options[:executables]
$url = options[:url]
$pub_key = options[:pub_key]
$priv_key = options[:priv_key]
$realm = options[:realm]
$service = options[:service]
$user_agent = options[:user_agent]
$ccache_file = options[:ccache]
unless $log.nil?
FileUtils.mkdir_p $full_logging_path
FileUtils.mkdir_p "#{$full_logging_path}/#{Time.now.strftime('%Y%d%m')}"
FileUtils.mkdir_p "#{$full_logging_path}/#{Time.now.strftime('%Y%d%m')}/#{$host}"
$filepath = "#{$full_logging_path}/#{Time.now.strftime('%Y%d%m')}/#{$host}/#{Time.now.strftime('%H%M%S')}"
$logger = Logger.new($filepath)
$logger.formatter = proc do |_severity, datetime, _progname, msg|
"#{datetime}: #{msg}\n"
end
end
return if $realm.nil?
return unless $service.nil?
$service = $default_service
end
# Print script header
def print_header
print_message("Evil-WinRM shell v#{VERSION}", TYPE_INFO, false)
end
# Generate connection object
def connection_initialization
# If using Kerberos and host is an IP, ask user if they want to resolve it to FQDN
if (!$ccache_file.nil? || !$realm.nil?) && is_ip_address?($host)
puts
print_message("IP address detected (#{$host}). Kerberos requires FQDN. Do you want to attempt reverse DNS lookup?", TYPE_WARNING, true, $logger)
print_message('Press "y" to attempt DNS resolution, press any other key to cancel', TYPE_WARNING, true, $logger)
response = $stdin.getch.downcase
puts
if response == 'y'
print_message("Attempting reverse DNS lookup to get FQDN for Kerberos...", TYPE_INFO, true, $logger)
fqdn = resolve_ip_to_fqdn($host, $realm)
if fqdn
print_message("[+] Resolved IP #{$host} to FQDN: #{fqdn}", TYPE_SUCCESS, true, $logger)
$host = fqdn
else
print_message("Could not resolve IP #{$host} to FQDN.", TYPE_ERROR, true, $logger)
print_message("When using Kerberos tickets, you must provide an FQDN instead of an IP address.", TYPE_ERROR, true, $logger)
custom_exit(1, false)
end
else
print_message("DNS resolution cancelled by user.", TYPE_ERROR, true, $logger)
print_message("When using Kerberos tickets, you must provide an FQDN instead of an IP address.", TYPE_ERROR, true, $logger)
custom_exit(1, false)
end
end
# Configure Kerberos ticket file if provided (supports both ccache and kirbi)
if !$ccache_file.nil?
expanded_path = File.expand_path($ccache_file)
unless File.exist?(expanded_path)
print_message("Kerberos ticket file not found: #{expanded_path}", TYPE_ERROR, true, $logger)
custom_exit(1, false)
end
unless File.readable?(expanded_path)
print_message("Kerberos ticket file is not readable: #{expanded_path}", TYPE_ERROR, true, $logger)
custom_exit(1, false)
end
# Check if file is not empty
if File.size(expanded_path) == 0
print_message("Kerberos ticket file is empty: #{expanded_path}", TYPE_ERROR, true, $logger)
custom_exit(1, false)
end
# Detect ticket type
ticket_type = detect_ticket_type(expanded_path)
# Convert kirbi to ccache if needed
if ticket_type == :kirbi
ccache_path = convert_kirbi_to_ccache(expanded_path)
ticket_type_name = "kirbi"
else
# Already ccache format
ccache_path = expanded_path
ticket_type_name = "ccache"
end
# Only modify ENV if it's not already set to avoid memory issues
# If user has already set KRB5CCNAME, we'll use that instead
if ENV['KRB5CCNAME'].nil? || ENV['KRB5CCNAME'].empty?
# Save original (nil) value
$original_krb5ccname = ENV['KRB5CCNAME']
# Set KRB5CCNAME environment variable
ENV['KRB5CCNAME'] = ccache_path
print_message("Using #{ticket_type_name} Kerberos ticket file: #{expanded_path}", TYPE_INFO, true, $logger)
else
# User already has KRB5CCNAME set, save original and warn them
$original_krb5ccname = ENV['KRB5CCNAME']
print_message("KRB5CCNAME is already set to: #{ENV['KRB5CCNAME']}. Using existing value instead of #{expanded_path}", TYPE_WARNING, true, $logger)
end
# Register at_exit handler to clean up KRB5CCNAME before any automatic cleanup
# This prevents malloc errors when the process exits (especially when shell is idle)
unless $kerberos_cleanup_registered
at_exit do
begin
if defined?($original_krb5ccname) && !$original_krb5ccname.nil?
ENV['KRB5CCNAME'] = $original_krb5ccname
elsif defined?($original_krb5ccname) && $original_krb5ccname.nil?
# Only delete if we set it (if original was nil)
ENV.delete('KRB5CCNAME') if ENV.key?('KRB5CCNAME')
end
rescue => e
# Ignore errors during cleanup
end
end
$kerberos_cleanup_registered = true
end
end
if $ssl
$conn = if $pub_key && $priv_key
WinRM::Connection.new(
endpoint: "https://#{$host}:#{$port}/#{$url}",
user: $user,
password: $password,
no_ssl_peer_verification: true,
transport: :ssl,
client_cert: $pub_key,
client_key: $priv_key,
user_agent: $user_agent
)
elsif !$realm.nil?
WinRM::Connection.new(
endpoint: "https://#{$host}:#{$port}/#{$url}",
user: '',
password: '',
transport: :kerberos,
realm: $realm,
no_ssl_peer_verification: true,
user_agent: $user_agent
)
else
WinRM::Connection.new(
endpoint: "https://#{$host}:#{$port}/#{$url}",
user: $user,
password: $password,
no_ssl_peer_verification: true,
transport: :ssl,
user_agent: $user_agent
)
end
elsif !$realm.nil?
$conn = WinRM::Connection.new(
endpoint: "http://#{$host}:#{$port}/#{$url}",
user: '',
password: '',
transport: :kerberos,
realm: $realm,
service: $service,
user_agent: $user_agent
)
else
$conn = WinRM::Connection.new(
endpoint: "http://#{$host}:#{$port}/#{$url}",
user: $user,
password: $password,
no_ssl_peer_verification: true,
user_agent: $user_agent
)
end
end
# Detect if a docker environment
def docker_detection
return true if File.exist?('/.dockerenv')
false
end
# Define colors
def colorize(text, color = 'default')
colors = { 'default' => '38', 'blue' => '34', 'red' => '31', 'yellow' => '1;33', 'magenta' => '35',
'green' => '1;32' }
color_code = colors[color]
"\001\033[0;#{color_code}m\002#{text}\001\033[0m\002"
end
# Messsage printing
def print_message(msg, msg_type=TYPE_INFO, prefix_print=true, log=nil)
if msg_type == TYPE_INFO then
msg_prefix = "Info: "
color = "blue"
elsif msg_type == TYPE_WARNING then
msg_prefix = "Warning: "
color = "yellow"
elsif msg_type == TYPE_ERROR then
msg_prefix = "Error: "
color = "red"
elsif msg_type == TYPE_DATA then
msg_prefix = "Data: "
color = 'magenta'
elsif msg_type == TYPE_SUCCESS then
color = 'green'
else
msg_prefix = ""
color = "default"
end
if !prefix_print then
msg_prefix = ""
end
puts(' ')
if $colors_enabled then
puts(self.colorize("#{msg_prefix}#{msg}", color))
else
puts("#{msg_prefix}#{msg}")
end
if !log.nil?
log.info("#{msg_prefix}#{msg}")
end
end
# SSL validation
def check_ssl(pub_key, priv_key)
pub_key = pub_key.to_s
priv_key = priv_key.to_s
if $ssl
unless pub_key.empty? && priv_key.empty? then
unless [pub_key, priv_key].all? {|f| File.exist?(f) } then
print_message("Path to provided public certificate file \"#{pub_key}\" can't be found. Check filename or path", TYPE_ERROR, true, $logger) unless File.exist?(pub_key)
print_message("Path to provided private certificate file \"#{priv_key}\" can't be found. Check filename or path", TYPE_ERROR, true, $logger) unless File.exist?(priv_key)
custom_exit(1)
end
end
print_message('SSL enabled', TYPE_WARNING)
else
print_message("Useless cert/s provided, SSL is not enabled", TYPE_WARNING, true, $logger) unless pub_key.empty? && priv_key.empty?
end
end
# Directories validation
def check_directories(path, purpose)
if path == ''
print_message("The directory used for #{purpose} can't be empty. Please set a path", TYPE_ERROR, true, $logger)
custom_exit(1)
end
if !(/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM).nil?
# Windows
path.concat('\\') if path[-1] != '\\'
elsif path[-1] != '/'
# Unix
path.concat('/')
end
unless File.directory?(path)
print_message("The directory \"#{path}\" used for #{purpose} was not found", TYPE_ERROR, true, $logger)
custom_exit(1)
end
case purpose
when 'scripts'
$scripts_path = path
when 'executables'
$executables_path = path
end
end
# Silent warnings
def silent_warnings
old_stderr = $stderr
$stderr = StringIO.new
yield
ensure
$stderr = old_stderr
end
# Read powershell script files
def read_scripts(scripts)
files = Dir.entries(scripts).select { |f| File.file? File.join(scripts, f) } || []
files.grep(/^*\.(ps1|psd1|psm1)$/)
end
# Read executable files
def read_executables(executables)
Dir.glob("#{executables}*.exe", File::FNM_DOTMATCH)
end
# Read local files and directories names
def paths(a_path)
parts = get_dir_parts(a_path)
my_dir = parts[0]
grep_for = parts[1]
my_dir = File.expand_path(my_dir)
my_dir += '/' unless my_dir[-1] == '/'
files = Dir.glob("#{my_dir}*", File::FNM_DOTMATCH)
directories = Dir.glob("#{my_dir}*").select { |f| File.directory? f }
result = (files + directories) || []
result.grep(/^#{Regexp.escape(my_dir)}#{grep_for}/i).uniq
end
# Custom exit
def custom_exit(exit_code = 0, message_print = true)
if message_print
case exit_code
when 0
print_message("Exiting with code #{exit_code}", TYPE_INFO, true, $logger)
when 1
print_message("Exiting with code #{exit_code}", TYPE_ERROR, true, $logger)
when 130
print_message('Exiting...', TYPE_INFO, true, $logger)
else
print_message("Exiting with code #{exit_code}", TYPE_ERROR, true, $logger)
end
end
# Restore KRB5CCNAME environment variable before exiting to avoid memory issues
begin
if defined?($original_krb5ccname) && !$original_krb5ccname.nil?
ENV['KRB5CCNAME'] = $original_krb5ccname
elsif defined?($original_krb5ccname) && $original_krb5ccname.nil?
# Only delete if we set it (if original was nil)
ENV.delete('KRB5CCNAME') if ENV.key?('KRB5CCNAME')
end
rescue => e
# Ignore errors during cleanup
end
# Close connection explicitly before exiting to avoid memory issues with Kerberos
begin
if defined?($conn) && !$conn.nil?
# Try to close the connection gracefully
$conn = nil
end
rescue => e
# Ignore errors during cleanup
end
# Use exit! to bypass at_exit handlers that might cause memory issues
# This prevents the malloc error when using Kerberos
exit!(exit_code)
end
# Progress bar
def progress_bar(bytes_done, total_bytes)
progress = ((bytes_done.to_f / total_bytes) * 100).round
progress_bar = (progress / 10).round
progress_string = '▓' * (progress_bar - 1).clamp(0, 9)
progress_string = "#{progress_string}▒#{'░' * (10 - progress_bar)}"
message = "Progress: #{progress}% : |#{progress_string}| \r"
$stdout.print message
end
# Get filesize
def filesize(shell, path)
shell.run("(get-item '#{path}').length").output.strip.to_i
end
# Clear screen
def clear_screen
system('clear') || system('cls') || puts("\033[2J\033[H")
end
# Get history file path based on host and user
def get_history_file_path
history_dir = File.join(Dir.home, '.evil-winrm', 'history')
FileUtils.mkdir_p(history_dir) unless Dir.exist?(history_dir)
# Create a safe filename from host and user
safe_host = ($host || 'unknown').gsub(/[^a-zA-Z0-9._-]/, '_')
safe_user = ($user || 'unknown').gsub(/[^a-zA-Z0-9._-]/, '_')
history_filename = "#{safe_host}_#{safe_user}.hist"
File.join(history_dir, history_filename)
end
# Load history from file
def load_history
history_file = get_history_file_path
return unless File.exist?(history_file)
begin
File.readlines(history_file).each do |line|
line = line.chomp
Readline::HISTORY.push(line) unless line.empty?
end
rescue => e
# Silently fail if history can't be loaded
end
end
# Save command to history file
def save_to_history(command)
return if command.nil? || command.strip.empty? || command.strip == 'exit'
history_file = get_history_file_path
begin
File.open(history_file, 'a') do |f|
f.puts(command)
end
rescue => e
# Silently fail if history can't be saved
end
end
# Resolve IP address to FQDN using reverse DNS lookup
# Returns the best FQDN when multiple PTR records exist (prioritizes server FQDN over domain name)
# If only domain is found, attempts to construct and verify server FQDN using forward DNS
# Also checks /etc/hosts for manual entries
def resolve_ip_to_fqdn(ip_address, realm = nil)
require 'socket'
require 'resolv'
begin
resolver = Resolv::DNS.new
hostnames = []
# Step 0: Check /etc/hosts for manual entries (highest priority)
if File.exist?('/etc/hosts') && File.readable?('/etc/hosts')
begin
File.readlines('/etc/hosts').each do |line|
# Skip comments and empty lines
next if line.strip.empty? || line.strip.start_with?('#')
# Parse line: IP hostname1 hostname2 ...
parts = line.split
next if parts.empty?
# Check if first part matches our IP
if parts[0] == ip_address
# Add all hostnames from this line
parts[1..-1].each do |hostname|
# Only consider FQDNs (contain at least one dot)
if hostname && hostname.include?('.')
hostnames << hostname unless hostnames.include?(hostname)
end
end
end
end
if !hostnames.empty?
print_message("Found FQDN(s) in /etc/hosts: #{hostnames.join(', ')}", TYPE_INFO, true, $logger)
end
rescue => e
# If we can't read /etc/hosts, continue with DNS lookup
end
end
# Step 1: Get all PTR records (reverse DNS)
begin
ptr_name = Resolv::IPv4.create(ip_address).to_name
ptr_records = resolver.getresources(ptr_name, Resolv::DNS::Resource::IN::PTR)
ptr_records.each do |ptr|
hostname = ptr.name.to_s
if hostname && hostname.include?('.')
hostnames << hostname unless hostnames.include?(hostname)
end
end
rescue Resolv::ResolvError, Resolv::ResolvTimeout
# If Resolv::DNS fails, try Resolv.getname as fallback
begin
hostname = Resolv.getname(ip_address)
if hostname && hostname.include?('.')
hostnames << hostname unless hostnames.include?(hostname)
end
rescue Resolv::ResolvError
# Continue to Socket fallback
end
end
# If no results from Resolv, try Socket.getnameinfo
if hostnames.empty?
begin
hostname = Socket.getnameinfo([Socket::AF_INET, nil, ip_address], Socket::NI_NAMEREQD)[0]
if hostname && hostname.include?('.')
hostnames << hostname unless hostnames.include?(hostname)
end
rescue SocketError
# All methods failed
end
end
# Step 2: If we only got the domain name, try to find the server FQDN
# Remove duplicates before checking
hostnames.uniq!
# Only do this if we don't already have a server FQDN (3+ parts) from /etc/hosts or DNS
has_server_fqdn = hostnames.any? { |h| h.split('.').length >= 3 }
domain_only = hostnames.find { |h| h.split('.').length == 2 }
# Only attempt forward DNS lookup if:
# 1. We don't already have a server FQDN
# 2. We have a domain-only result
# 3. We have a realm to work with
if !has_server_fqdn && domain_only && realm
# Try common DC hostname patterns
domain = domain_only.downcase
realm_domain = realm.downcase
# Common DC naming patterns
candidates = [
"dc01.#{domain}",
"dc1.#{domain}",
"dc.#{domain}",
"dc01.#{realm_domain}",
"dc1.#{realm_domain}",
"dc.#{realm_domain}",
"ad.#{domain}",
"ad.#{realm_domain}",
"ad01.#{domain}",
"ad01.#{realm_domain}"
]
# Remove duplicates from candidates (in case we already have it)
candidates.reject! { |c| hostnames.include?(c) }
# Verify each candidate with forward DNS lookup
candidates.each do |candidate|
begin
addresses = resolver.getaddresses(candidate)
# Check if any of the resolved addresses match our IP
if addresses.any? { |addr| addr.to_s == ip_address }
hostnames << candidate unless hostnames.include?(candidate)
print_message("Found server FQDN via forward DNS lookup: #{candidate}", TYPE_INFO, true, $logger)
# Stop after finding first valid server FQDN
break
end
rescue Resolv::ResolvError
# This candidate doesn't resolve, skip it
end
end
end
return nil if hostnames.empty?
# Step 3: Select the best FQDN
# If we have multiple results, prioritize the server FQDN over domain name
if hostnames.length > 1
# Sort by: more dots first, then by length (longer = more specific)
sorted = hostnames.sort_by { |h| [-h.count('.'), -h.length] }
# Prefer hostnames that look like server names (have a hostname prefix before the domain)
# e.g., "dc01.futuristic.tech" over "futuristic.tech"
best = sorted.find { |h| h.split('.').length >= 3 } || sorted.first
print_message("Multiple DNS names found: #{hostnames.join(', ')}. Selected: #{best}", TYPE_INFO, true, $logger)
return best
else
result = hostnames.first
# If we only have domain, warn the user
if result.split('.').length == 2
print_message("Only domain name found (#{result}). Server FQDN not detected. Kerberos may still work.", TYPE_WARNING, true, $logger)
end
return result
end
rescue => e
# Any other error
return nil
end
end
# Check if a string is an IP address
def is_ip_address?(str)
# Match IPv4 address pattern
ipv4_pattern = /^(\d{1,3}\.){3}\d{1,3}$/
return true if str.match?(ipv4_pattern)
# Match IPv6 address pattern (simplified)
ipv6_pattern = /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/
return true if str.match?(ipv6_pattern)
false
end
# Detect ticket file type (kirbi or ccache)
def detect_ticket_type(file_path)
# Check by extension first
ext = File.extname(file_path).downcase
return :kirbi if ext == '.kirbi'
return :ccache if ext == '.ccache'
# If no extension or unknown, try to detect by file content
# Kirbi files typically start with specific ASN.1 structures
# CCache files have a different structure
begin
first_bytes = File.binread(file_path, 4)
# Kirbi files often start with specific ASN.1 tags
# This is a heuristic - not 100% reliable but works for most cases
if first_bytes[0] == 0x76 || first_bytes[0] == 0x6a || first_bytes[0] == 0x61
return :kirbi
end
# CCache files have a different structure
return :ccache
rescue => e
# If we can't read, default to ccache
return :ccache
end
end
# Convert kirbi ticket to ccache format
def convert_kirbi_to_ccache(kirbi_path)
# Validate input file first
expanded_kirbi = File.expand_path(kirbi_path)
unless File.exist?(expanded_kirbi)
print_message("Kirbi ticket file not found: #{expanded_kirbi}", TYPE_ERROR, true, $logger)
custom_exit(1, false)
end
unless File.readable?(expanded_kirbi)
print_message("Kirbi ticket file is not readable: #{expanded_kirbi}", TYPE_ERROR, true, $logger)
custom_exit(1, false)
end
# Check if file is not empty
if File.size(expanded_kirbi) == 0
print_message("Kirbi ticket file is empty: #{expanded_kirbi}", TYPE_ERROR, true, $logger)
custom_exit(1, false)
end
# Generate output path (same directory, change extension)
output_dir = File.dirname(expanded_kirbi)
output_name = File.basename(expanded_kirbi, '.kirbi') + '.ccache'
ccache_path = File.join(output_dir, output_name)
# Try to find ticket converter (multiple possible names)
converter_names = [
'ticket_converter.py',
'impacket-ticketConverter',
'impacket-ticketConverter.py',
'ticketConverter.py',
'ticketConverter'
]
converter_paths = []
# Check in PATH for each name
converter_names.each do |name|
cmd = `which #{name} 2>/dev/null`.strip
converter_paths << cmd unless cmd.empty?
end
# Also check common installation paths
converter_names.each do |name|
converter_paths << name # Current directory
converter_paths << "/usr/local/bin/#{name}"
converter_paths << "/usr/bin/#{name}"
converter_paths << File.join(Dir.home, '.local', 'bin', name)
converter_paths << File.join(Dir.home, name)
end
# Remove duplicates and empty strings
converter_paths.uniq!
converter_paths.reject!(&:empty?)
converter_found = nil
converter_paths.each do |path|
if File.exist?(path) && File.executable?(path)
converter_found = path
break
end
end
unless converter_found
print_message("Ticket converter not found. Please install one of: ticket_converter.py, impacket-ticketConverter, or impacket-ticketConverter.py.", TYPE_ERROR, true, $logger)
print_message("Sources: https://github.com/Zer1t0/ticket_converter or https://github.com/SecureAuthCorp/impacket", TYPE_INFO, true, $logger)
custom_exit(1, false)
end
# Check if it's a Python script or shell script
is_python = false
begin
first_line = File.readlines(converter_found).first
if first_line
# Check for Python shebang
if first_line.match?(/^#!.*python/)
is_python = true
# Check for shell shebang (bash, sh, etc.) - if it's shell, it's not Python
elsif first_line.match?(/^#!.*\/(bin\/)?(bash|sh|zsh)/)
is_python = false
# Check extension
elsif File.extname(converter_found) == '.py'
is_python = true
end
elsif File.extname(converter_found) == '.py'
is_python = true
end
rescue => e
# If we can't read, check extension or assume it's executable and try directly
is_python = (File.extname(converter_found) == '.py')