Module: Msf::Post::File

Defined Under Namespace

Classes: FileStat

Instance Method Summary collapse

Methods included from Common

#clear_screen, #cmd_exec, #cmd_exec_get_pid, #command_exists?, #get_env, #get_envs, #peer, #report_virtualization, #rhost, #rport

Instance Method Details

#_read_file_meterpreter(file_name) ⇒ String (protected)

Meterpreter-specific file read. Returns contents of remote file file_name as a String or nil if there was an error

You should never call this method directly. Instead, call #read_file which will call this if it is appropriate for the given session.

Returns:

  • (String)

532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
# File 'lib/msf/core/post/file.rb', line 532

def _read_file_meterpreter(file_name)
  fd = session.fs.file.new(file_name, "rb")

  data = fd.read
  until fd.eof?
    data << fd.read
  end

  data
rescue EOFError
  # Sometimes fd isn't marked EOF in time?
  ''
rescue ::Rex::Post::Meterpreter::RequestError => e
  print_error("Failed to open file: #{file_name}: #{e}")
  return nil
ensure
  fd.close if fd
end

#_unix_max_line_lengthInteger (protected)

Calculate the maximum line length for a unix shell.

Returns:

  • (Integer)

687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
# File 'lib/msf/core/post/file.rb', line 687

def _unix_max_line_length
  # Based on autoconf's arg_max calculator, see
  # http://www.in-ulm.de/~mascheck/various/argmax/autoconf_check.html
  calc_line_max = 'i=0 max= new= str=abcd; \
    while (test "X"`echo "X$str" 2>/dev/null` = "XX$str") >/dev/null 2>&1 && \
        new=`expr "X$str" : ".*" 2>&1` && \
        test "$i" != 17 && \
        max=$new; do \
      i=`expr $i + 1`; str=$str$str;\
    done; echo $max'
  line_max = session.shell_command_token(calc_line_max).to_i

  # Fall back to a conservative 4k which should work on even the most
  # restrictive of embedded shells.
  line_max = (line_max == 0 ? 4096 : line_max)
  vprint_status("Max line length is #{line_max}")

  line_max
end

#_write_file_unix_shell(file_name, data, append = false) ⇒ void (protected)

This method returns an undefined value.

Write data to the remote file file_name.

Truncates if append is false, appends otherwise.

You should never call this method directly. Instead, call #write_file or #append_file which will call this if it is appropriate for the given session.


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
# File 'lib/msf/core/post/file.rb', line 561

def _write_file_unix_shell(file_name, data, append=false)
  redirect = (append ? ">>" : ">")

  # Short-circuit an empty string. The : builtin is part of posix
  # standard and should theoretically exist everywhere.
  if data.length == 0
    session.shell_command_token(": #{redirect} #{file_name}")
    return
  end

  d = data.dup
  d.force_encoding("binary") if d.respond_to? :force_encoding

  chunks = []
  command = nil
  encoding = :hex
  cmd_name = ""

  line_max = _unix_max_line_length
  # Leave plenty of room for the filename we're writing to and the
  # command to echo it out
  line_max -= file_name.length
  line_max -= 64

  # Ordered by descending likeliness to work
  [
    # POSIX standard requires %b which expands octal (but not hex)
    # escapes in the argument. However, some versions (notably
    # FreeBSD) truncate input on nulls, so "printf %b '\0\101'"
    # produces a 0-length string. Some also allow octal escapes
    # without a format string, and do not truncate, so start with
    # that and try %b if it doesn't work. The standalone version seems
    # to be more likely to work than the buitin version, so try it
    # first.
    #
    # Both of these work for sure on Linux and FreeBSD
    { :cmd => %q^/usr/bin/printf 'CONTENTS'^ , :enc => :octal, :name => "printf" },
    { :cmd => %q^printf 'CONTENTS'^ , :enc => :octal, :name => "printf" },
    # Works on Solaris
    { :cmd => %q^/usr/bin/printf %b 'CONTENTS'^ , :enc => :octal, :name => "printf" },
    { :cmd => %q^printf %b 'CONTENTS'^ , :enc => :octal, :name => "printf" },
    # Perl supports both octal and hex escapes, but octal is usually
    # shorter (e.g. 0 becomes \0 instead of \x00)
    { :cmd => %q^perl -e 'print("CONTENTS")'^ , :enc => :octal, :name => "perl" },
    # POSIX awk doesn't have \xNN escapes, use gawk to ensure we're
    # getting the GNU version.
    { :cmd => %q^gawk 'BEGIN {ORS="";print "CONTENTS"}' </dev/null^ , :enc => :hex, :name => "awk" },
    # xxd's -p flag specifies a postscript-style hexdump of unadorned hex
    # digits, e.g. ABCD would be 41424344
    { :cmd => %q^echo 'CONTENTS'|xxd -p -r^ , :enc => :bare_hex, :name => "xxd" },
    # Use echo as a last resort since it frequently doesn't support -e
    # or -n.  bash and zsh's echo builtins are apparently the only ones
    # that support both.  Most others treat all options as just more
    # arguments to print. In particular, the standalone /bin/echo or
    # /usr/bin/echo appear never to have -e so don't bother trying
    # them.
    { :cmd => %q^echo -ne 'CONTENTS'^ , :enc => :hex },
  ].each { |foo|
    # Some versions of printf mangle %.
    test_str = "\0\xff\xfe#{Rex::Text.rand_text_alpha_upper(4)}\x7f%%\r\n"
    #test_str = "\0\xff\xfe"
    case foo[:enc]
    when :hex
      cmd = foo[:cmd].sub("CONTENTS"){ Rex::Text.to_hex(test_str) }
    when :octal
      cmd = foo[:cmd].sub("CONTENTS"){ Rex::Text.to_octal(test_str) }
    when :bare_hex
      cmd = foo[:cmd].sub("CONTENTS"){ Rex::Text.to_hex(test_str,'') }
    end
    a = session.shell_command_token("#{cmd}")

    if test_str == a
      command = foo[:cmd]
      encoding = foo[:enc]
      cmd_name = foo[:name]
      break
    else
      vprint_status("#{cmd} Failed: #{a.inspect} != #{test_str.inspect}")
    end
  }

  if command.nil?
    raise RuntimeError, "Can't find command on the victim for writing binary data", caller
  end

  # each byte will balloon up to 4 when we encode
  # (A becomes \x41 or \101)
  max = line_max/4

  i = 0
  while (i < d.length)
    slice = d.slice(i...(i+max))
    case encoding
    when :hex
      chunks << Rex::Text.to_hex(slice)
    when :octal
      chunks << Rex::Text.to_octal(slice)
    when :bare_hex
      chunks << Rex::Text.to_hex(slice,'')
    end
    i += max
  end

  vprint_status("Writing #{d.length} bytes in #{chunks.length} chunks of #{chunks.first.length} bytes (#{encoding}-encoded), using #{cmd_name}")

  # The first command needs to use the provided redirection for either
  # appending or truncating.
  cmd = command.sub("CONTENTS") { chunks.shift }
  session.shell_command_token("#{cmd} #{redirect} \"#{file_name}\"")

  # After creating/truncating or appending with the first command, we
  # need to append from here on out.
  chunks.each { |chunk|
    vprint_status("Next chunk is #{chunk.length} bytes")
    cmd = command.sub("CONTENTS") { chunk }

    session.shell_command_token("#{cmd} >> '#{file_name}'")
  }

  true
end

#append_file(file_name, data) ⇒ void

This method returns an undefined value.

Platform-agnostic file append. Appends given object content to a remote file. Returns Boolean true if successful

NOTE: *This is not binary-safe on Windows shell sessions!*

Parameters:

  • file_name (String)

    Remote file name to write

  • data (String)

    Contents to put in the file


396
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'lib/msf/core/post/file.rb', line 396

def append_file(file_name, data)
  if session.type == "meterpreter"
    fd = session.fs.file.new(file_name, "ab")
    fd.write(data)
    fd.close
  elsif session.respond_to? :shell_command_token
    if session.platform == 'windows'
      session.shell_command_token("<nul set /p=\"#{data}\" >> \"#{file_name}\"")
    else
      _write_file_unix_shell(file_name, data, true)
    end
  end
  true
end

#attributes(path) ⇒ Object

Retrieve file attributes for path on the remote system

Parameters:

  • path (String)

    Remote filename to check


266
267
268
269
270
# File 'lib/msf/core/post/file.rb', line 266

def attributes(path)
  raise "`attributes' method does not support Windows systems" if session.platform == 'windows'

  cmd_exec("lsattr -l '#{path}'").to_s.scan(/^#{path}\s+(.+)$/).flatten.first.to_s.split(', ')
end

#cd(path) ⇒ void

This method returns an undefined value.

Change directory in the remote session to path, which may be relative or absolute.


33
34
35
36
37
38
39
40
# File 'lib/msf/core/post/file.rb', line 33

def cd(path)
  e_path = expand_path(path) rescue path
  if session.type == "meterpreter"
    session.fs.dir.chdir(e_path)
  else
    session.shell_command_token("cd \"#{e_path}\"")
  end
end

#chmod(path, mode = 0700) ⇒ Object

Sets the permissions on a remote file

Parameters:

  • path (String)

    Path on the remote filesystem

  • mode (Fixnum) (defaults to: 0700)

    Mode as an octal number


439
440
441
442
443
444
445
446
447
448
449
# File 'lib/msf/core/post/file.rb', line 439

def chmod(path, mode = 0700)
  if session.platform == 'windows'
    raise "`chmod' method does not support Windows systems"
  end

  if session.type == 'meterpreter' && session.commands.include?(Rex::Post::Meterpreter::Extensions::Stdapi::COMMAND_ID_STDAPI_FS_CHMOD)
    session.fs.file.chmod(path, mode)
  else
    cmd_exec("chmod #{mode.to_s(8)} '#{path}'")
  end
end

#dir(directory) ⇒ Array Also known as: ls

Returns a list of the contents of the specified directory

Parameters:

  • directory (String)

    the directory to list

Returns:

  • (Array)

    the contents of the directory


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
# File 'lib/msf/core/post/file.rb', line 71

def dir(directory)
  if session.type == 'meterpreter'
    return session.fs.dir.entries(directory)
  end

  if session.platform == 'windows'
    return session.shell_command_token("dir #{directory}").split(/[\r\n]+/)
  end

  if command_exists?('ls')
    return session.shell_command_token("ls #{directory}").split(/[\r\n]+/)
  end

  # Result on systems without ls command
  if directory[-1] != '/'
    directory = directory + "/"
  end
  result = []
  data = session.shell_command_token("for fn in #{directory}*; do echo $fn; done")
  parts = data.split("\n")
  parts.each do |line|
    line = line.split("/")[-1]
    result.insert(-1, line)
  end

  result
end

#directory?(path) ⇒ Boolean

See if path exists on the remote system and is a directory

Parameters:

  • path (String)

    Remote filename to check

Returns:

  • (Boolean)

124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/msf/core/post/file.rb', line 124

def directory?(path)
  if session.type == 'meterpreter'
    stat = session.fs.file.stat(path) rescue nil
    return false unless stat
    return stat.directory?
  else
    if session.platform == 'windows'
      f = cmd_exec("cmd.exe /C IF exist \"#{path}\\*\" ( echo true )")
    else
      f = session.shell_command_token("test -d \"#{path}\" && echo true")
    end
    return false if f.nil? || f.empty?
    return false unless f =~ /true/
    true
  end
end

#executable?(path) ⇒ Boolean

See if path on the remote system exists and is executable

Parameters:

  • path (String)

    Remote path to check

Returns:

  • (Boolean)

    true if path exists and is executable


195
196
197
198
199
# File 'lib/msf/core/post/file.rb', line 195

def executable?(path)
  raise "`executable?' method does not support Windows systems" if session.platform == 'windows'

  cmd_exec("test -x '#{path}' && echo true").to_s.include? 'true'
end

#exist?(path) ⇒ Boolean Also known as: exists?

Check for existence of path on the remote file system

Parameters:

  • path (String)

    Remote filename to check

Returns:

  • (Boolean)

244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/msf/core/post/file.rb', line 244

def exist?(path)
  if session.type == 'meterpreter'
    stat = session.fs.file.stat(path) rescue nil
    return !!(stat)
  else
    if session.platform == 'windows'
      f = cmd_exec("cmd.exe /C IF exist \"#{path}\" ( echo true )")
    else
      f = cmd_exec("test -e \"#{path}\" && echo true")
    end
    return false if f.nil? || f.empty?
    return false unless f =~ /true/
    true
  end
end

#expand_path(path) ⇒ String

Expand any environment variables to return the full path specified by path.

Returns:

  • (String)

145
146
147
148
149
150
151
# File 'lib/msf/core/post/file.rb', line 145

def expand_path(path)
  if session.type == "meterpreter"
    return session.fs.file.expand_path(path)
  else
    return cmd_exec("echo #{path}")
  end
end

#exploit_data(data_directory, file) ⇒ Object

Read a local exploit file binary from the data directory

Parameters:

  • path (String)

    Directory in the exploits folder

  • path (String)

    Filename in the data folder


456
457
458
459
# File 'lib/msf/core/post/file.rb', line 456

def exploit_data(data_directory, file)
  file_path = ::File.join(::Msf::Config.data_directory, "exploits", data_directory, file)
  ::File.binread(file_path)
end

#file?(path) ⇒ Boolean Also known as: file_exist?

See if path exists on the remote system and is a regular file

Parameters:

  • path (String)

    Remote filename to check

Returns:

  • (Boolean)

157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/msf/core/post/file.rb', line 157

def file?(path)
  if session.type == 'meterpreter'
    stat = session.fs.file.stat(path) rescue nil
    return false unless stat
    return stat.file?
  else
    if session.platform == 'windows'
      f = cmd_exec("cmd.exe /C IF exist \"#{path}\" ( echo true )")
      if f =~ /true/
        f = cmd_exec("cmd.exe /C IF exist \"#{path}\\\\\" ( echo false ) ELSE ( echo true )")
      end
    else
      f = session.shell_command_token("test -f \"#{path}\" && echo true")
    end
    return false if f.nil? || f.empty?
    return false unless f =~ /true/
    true
  end
end

#file_local_write(local_file_name, data) ⇒ void

This method returns an undefined value.

Writes a given string to a given local file

Parameters:

  • local_file_name (String)
  • data (String)

278
279
280
281
282
283
284
285
286
287
288
# File 'lib/msf/core/post/file.rb', line 278

def file_local_write(local_file_name, data)
  fname = Rex::FileUtils.clean_path(local_file_name)
  unless ::File.exist?(fname)
    ::FileUtils.touch(fname)
  end
  output = ::File.open(fname, "a")
  data.each_line do |d|
    output.puts(d)
  end
  output.close
end

#file_remote_digestmd5(file_name) ⇒ String

Note:

THIS DOWNLOADS THE FILE

Returns a MD5 checksum of a given remote file

Parameters:

  • file_name (String)

    Remote file name

Returns:

  • (String)

    Hex digest of file contents


296
297
298
299
300
301
302
303
# File 'lib/msf/core/post/file.rb', line 296

def file_remote_digestmd5(file_name)
  data = read_file(file_name)
  chksum = nil
  if data
    chksum = Digest::MD5.hexdigest(data)
  end
  return chksum
end

#file_remote_digestsha1(file_name) ⇒ String

Note:

THIS DOWNLOADS THE FILE

Returns a SHA1 checksum of a given remote file

Parameters:

  • file_name (String)

    Remote file name

Returns:

  • (String)

    Hex digest of file contents


311
312
313
314
315
316
317
318
# File 'lib/msf/core/post/file.rb', line 311

def file_remote_digestsha1(file_name)
  data = read_file(file_name)
  chksum = nil
  if data
    chksum = Digest::SHA1.hexdigest(data)
  end
  return chksum
end

#file_remote_digestsha2(file_name) ⇒ String

Note:

THIS DOWNLOADS THE FILE

Returns a SHA2 checksum of a given remote file

Parameters:

  • file_name (String)

    Remote file name

Returns:

  • (String)

    Hex digest of file contents


326
327
328
329
330
331
332
333
# File 'lib/msf/core/post/file.rb', line 326

def file_remote_digestsha2(file_name)
  data = read_file(file_name)
  chksum = nil
  if data
    chksum = Digest::SHA256.hexdigest(data)
  end
  return chksum
end

#immutable?(path) ⇒ Boolean

See if path on the remote system exists and is immutable

Parameters:

  • path (String)

    Remote path to check

Returns:

  • (Boolean)

    true if path exists and is immutable


221
222
223
224
225
# File 'lib/msf/core/post/file.rb', line 221

def immutable?(path)
  raise "`immutable?' method does not support Windows systems" if session.platform == 'windows'

  attributes(path).include?('Immutable')
end

#initialize(info = {}) ⇒ Object


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/msf/core/post/file.rb', line 10

def initialize(info = {})
  super(update_info(
    info,
    'Compat' => { 'Meterpreter' => { 'Commands' => %w{
      core_channel_*
      stdapi_fs_chdir
      stdapi_fs_delete_dir
      stdapi_fs_delete_file
      stdapi_fs_file_expand_path
      stdapi_fs_file_move
      stdapi_fs_getwd
      stdapi_fs_ls
      stdapi_fs_mkdir
      stdapi_fs_stat
    } } }
  ))
end

#mkdir(path) ⇒ Object

create and mark directory for cleanup


102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/msf/core/post/file.rb', line 102

def mkdir(path)
  result = nil
  vprint_status("Creating directory #{path}")
  if session.type == 'meterpreter'
    # behave like mkdir -p and don't throw an error if the directory exists
    result = session.fs.dir.mkdir(path) unless directory?(path)
  else
    if session.platform == 'windows'
      result = cmd_exec("mkdir \"#{path}\"")
    else
      result = cmd_exec("mkdir -p '#{path}'")
    end
  end
  vprint_status("#{path} created")
  register_dir_for_cleanup(path)
  result
end

#pwdString

Note:

This may be inaccurate on shell sessions running on Windows before XP/2k3

Returns the current working directory in the remote session

Returns:

  • (String)

49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/msf/core/post/file.rb', line 49

def pwd
  if session.type == "meterpreter"
    return session.fs.dir.getwd
  else
    if session.platform == 'windows'
      # XXX: %CD% only exists on XP and newer, figure something out for NT4
      # and 2k
      return session.shell_command_token("echo %CD%")
    else
      if command_exists?("pwd")
        return session.shell_command_token("pwd").to_s.strip
      else
        # Result on systems without pwd command
        return session.shell_command_token("echo $PWD").to_s.strip
      end
    end
  end
end

#read_file(file_name) ⇒ String, Array

Platform-agnostic file read. Returns contents of remote file file_name as a String.

Parameters:

  • file_name (String)

    Remote file name to read

Returns:

  • (String)

    Contents of the file

  • (Array)

    of strings(lines)


344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/msf/core/post/file.rb', line 344

def read_file(file_name)
  if session.type == 'meterpreter'
    return _read_file_meterpreter(file_name)
  end

  return nil unless session.type == 'shell'

  if session.platform == 'windows'
    return session.shell_command_token("type \"#{file_name}\"")
  end

  return nil unless readable?(file_name)

  if command_exists?('cat')
    return session.shell_command_token("cat \"#{file_name}\"")
  end

  # Result on systems without cat command
  session.shell_command_token("while read line; do echo $line; done <#{file_name}")
end

#readable?(path) ⇒ Boolean

See if path on the remote system exists and is readable

Parameters:

  • path (String)

    Remote path to check

Returns:

  • (Boolean)

    true if path exists and is readable


234
235
236
237
238
# File 'lib/msf/core/post/file.rb', line 234

def readable?(path)
  raise "`readable?' method does not support Windows systems" if session.platform == 'windows'

  cmd_exec("test -r '#{path}' && echo true").to_s.include? 'true'
end

#rename_file(old_file, new_file) ⇒ Object Also known as: move_file, mv_file

Rename a remote file.

Parameters:

  • old_file (String)

    Remote file name to move

  • new_file (String)

    The new name for the remote file


508
509
510
511
512
513
514
515
516
517
518
# File 'lib/msf/core/post/file.rb', line 508

def rename_file(old_file, new_file)
  if session.type == "meterpreter"
    return (session.fs.file.mv(old_file, new_file).result == 0)
  else
    if session.platform == 'windows'
      cmd_exec(%Q|move /y "#{old_file}" "#{new_file}"|) =~ /moved/
    else
      cmd_exec(%Q|mv -f "#{old_file}" "#{new_file}"|).empty?
    end
  end
end

#rm_f(*remote_files) ⇒ void Also known as: file_rm

This method returns an undefined value.

Delete remote files

Parameters:

  • remote_files (Array<String>)

    List of remote filenames to delete


467
468
469
470
471
472
473
474
475
476
477
478
479
# File 'lib/msf/core/post/file.rb', line 467

def rm_f(*remote_files)
  remote_files.each do |remote|
    if session.type == "meterpreter"
      session.fs.file.delete(remote) if exist?(remote)
    else
      if session.platform == 'windows'
        cmd_exec("del /q /f \"#{remote}\"")
      else
        cmd_exec("rm -f \"#{remote}\"")
      end
    end
  end
end

#rm_rf(*remote_dirs) ⇒ void Also known as: dir_rm

This method returns an undefined value.

Delete remote directories

Parameters:

  • remote_dirs (Array<String>)

    List of remote directories to delete


487
488
489
490
491
492
493
494
495
496
497
498
499
# File 'lib/msf/core/post/file.rb', line 487

def rm_rf(*remote_dirs)
  remote_dirs.each do |remote|
    if session.type == "meterpreter"
      session.fs.dir.rmdir(remote) if exist?(remote)
    else
      if session.platform == 'windows'
        cmd_exec("rd /s /q \"#{remote}\"")
      else
        cmd_exec("rm -rf \"#{remote}\"")
      end
    end
  end
end

#setuid?(path) ⇒ Boolean

See if path on the remote system is a setuid file

Parameters:

  • path (String)

    Remote filename to check

Returns:

  • (Boolean)

183
184
185
186
# File 'lib/msf/core/post/file.rb', line 183

def setuid?(path)
  stat = stat(path)
  stat.setuid?
end

#stat(filename) ⇒ Object (protected)


707
708
709
710
711
712
713
714
715
# File 'lib/msf/core/post/file.rb', line 707

def stat(filename)
  if session.type == 'meterpreter'
    return session.fs.file.stat(filename)
  else
    raise NotImplementedError if session.platform == 'windows'
    raise "`stat' command doesn't exist on target system" unless command_exists?('stat')
    return FileStat.new(filename, session)
  end
end

#upload_and_chmodx(path, data) ⇒ Object

Upload a binary and write it as an executable file remote on the remote filesystem.

Parameters:

  • remote (String)

    Destination file name on the remote filesystem

  • data (String)

    Data to be uploaded


428
429
430
431
432
# File 'lib/msf/core/post/file.rb', line 428

def upload_and_chmodx(path, data)
  print_status "Writing '#{path}' (#{data.size} bytes) ..."
  write_file path, data
  chmod(path)
end

#upload_file(remote, local) ⇒ void

This method returns an undefined value.

Read a local file local and write it as remote on the remote file system

Parameters:

  • remote (String)

    Destination file name on the remote filesystem

  • local (String)

    Local file whose contents will be uploaded


418
419
420
# File 'lib/msf/core/post/file.rb', line 418

def upload_file(remote, local)
  write_file(remote, ::File.read(local))
end

#writable?(path) ⇒ Boolean

See if path on the remote system exists and is writable

Parameters:

  • path (String)

    Remote path to check

Returns:

  • (Boolean)

    true if path exists and is writable


208
209
210
211
212
# File 'lib/msf/core/post/file.rb', line 208

def writable?(path)
  raise "`writable?' method does not support Windows systems" if session.platform == 'windows'

  cmd_exec("test -w '#{path}' && echo true").to_s.include? 'true'
end

#write_file(file_name, data) ⇒ void

This method returns an undefined value.

Platform-agnostic file write. Writes given object content to a remote file.

NOTE: *This is not binary-safe on Windows shell sessions!*

Parameters:

  • file_name (String)

    Remote file name to write

  • data (String)

    Contents to put in the file


372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/msf/core/post/file.rb', line 372

def write_file(file_name, data)
  if session.type == "meterpreter"
    fd = session.fs.file.new(file_name, "wb")
    fd.write(data)
    fd.close
  elsif session.respond_to? :shell_command_token
    if session.platform == 'windows'
      session.shell_command_token("echo #{data} > \"#{file_name}\"")
    else
      _write_file_unix_shell(file_name, data)
    end
  end
  true
end