Class: Rex::Post::Meterpreter::Extensions::Stdapi::Fs::File

Inherits:
IO
  • Object
show all
Includes:
File
Defined in:
lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb

Overview

This class implements the Rex::Post::File interface and wraps interaction with files on the remote machine.

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from File

atime, blockdev?, chardev?, chmod, chown, ctime, directory?, dirname, executable?, executable_real?, extname, file?, fnmatch, fnmatch?, ftype, grpowned?, join, lchmod, lchown, link, lstat, mtime, owned?, #path, pipe?, readable?, readable_real?, setgid?, setuid?, size, socket?, sticky?, symlink?, writeable?, writeable_real?, zero?

Methods inherited from IO

#close, #sysread, #syswrite

Methods inherited from IO

#binmode, #close, #close_read, #close_write, #closed?, #each, #each_byte, #each_line, #eof?, #fcntl, #flush, #fsync, #getc, #gets, #ioctl, #isatty, #lineno, #print, #printf, #putc, #puts, #read, #readchar, #readline, #readlines, #rewind, #stat, #sync, #sysread, #syswrite, #tell, #tty?, #ungetc, #write

Constructor Details

#initialize(name, mode = "r", perms = 0) ⇒ File

Initializes and opens the specified file with the specified permissions.



362
363
364
365
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 362

def initialize(name, mode = "r", perms = 0)
  self.client = self.class.client
  self.filed  = _open(name, mode, perms)
end

Class Attribute Details

.clientObject

Returns the value of attribute client.



29
30
31
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 29

def client
  @client
end

Class Method Details

.basename(*a) ⇒ Object

Returns the base name of the supplied file path to the caller.



107
108
109
110
111
112
113
114
115
116
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 107

def File.basename(*a)
  path = a[0]

  # Allow both kinds of dir serparators since lots and lots of code
  # assumes one or the other so this ends up getting called with strings
  # like: "C:\\foo/bar"
  path =~ %r#.*[/\\](.*)$#

  Rex::FileUtils.clean_path($1 || path)
end

.download(dest, *src_files, &stat) ⇒ Object

Download one or more files from the remote computer to the local directory supplied in destination.

If a block is given, it will be called before each file is downloaded and again when each download is complete.



283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 283

def File.download(dest, *src_files, &stat)
  src_files.each { |src|
    if (::File.basename(dest) != File.basename(src))
      # The destination when downloading is a local file so use this
      # system's separator
      dest += ::File::SEPARATOR + File.basename(src)
    end

    stat.call('downloading', src, dest) if (stat)
    result = download_file(dest, src)
    stat.call(result, src, dest) if (stat)
  }
end

.download_file(dest_file, src_file) ⇒ Object

Download a single file.



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
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 300

def File.download_file(dest_file, src_file)
  src_fd = client.fs.file.new(src_file, "rb")

  # Check for changes
  src_stat = client.fs.filestat.new(src_file)
  if ::File.exists?(dest_file)
    dst_stat = ::File.stat(dest_file)
    if src_stat.size == dst_stat.size && src_stat.mtime == dst_stat.mtime
      return 'skipped'
    end
  end

  # Make the destination path if necessary
  dir = ::File.dirname(dest_file)
  ::FileUtils.mkdir_p(dir) if dir and not ::File.directory?(dir)

  dst_fd = ::File.new(dest_file, "wb")

  # Keep transferring until EOF is reached...
  begin
    while ((data = src_fd.read) != nil)
      dst_fd.write(data)
    end
  rescue EOFError
  ensure
    src_fd.close
    dst_fd.close
  end

  # Clone the times from the remote file
  ::File.utime(src_stat.atime, src_stat.mtime, dest_file)
  return 'download'
end

.exists?(name) ⇒ Boolean

Returns true if the remote file name exists, false otherwise

Returns:

  • (Boolean)


187
188
189
190
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 187

def File.exists?(name)
  r = client.fs.filestat.new(name) rescue nil
  r ? true : false
end

.expand_path(path) ⇒ Object

Expands a file path, substituting all environment variables, such as %TEMP%.

Examples:

client.fs.file.expand_path("%appdata%")
# => "C:\\Documents and Settings\\user\\Application Data"
client.fs.file.expand_path("asdf")
# => "asdf"

NOTE: This method is fairly specific to Windows. It has next to no relation to the ::File.expand_path method! In particular, it does not do ~ expansion or environment variable expansion on non-Windows systems. For these reasons, this method may be deprecated in the future. Use it with caution.



134
135
136
137
138
139
140
141
142
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 134

def File.expand_path(path)
  request = Packet.create_request('stdapi_fs_file_expand_path')

  request.add_tlv(TLV_TYPE_FILE_PATH, client.unicode_filter_decode( path ))

  response = client.send_request(request)

  return client.unicode_filter_encode(response.get_tlv_value(TLV_TYPE_FILE_PATH))
end

.is_glob?(name) ⇒ Boolean

Returns:

  • (Boolean)


272
273
274
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 272

def File.is_glob?(name)
  /\*|\[|\?/ === name
end

.md5(path) ⇒ Object

Calculates the MD5 (16-bytes raw) of a remote file



148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 148

def File.md5(path)
  request = Packet.create_request('stdapi_fs_md5')

  request.add_tlv(TLV_TYPE_FILE_PATH, client.unicode_filter_decode( path ))

  response = client.send_request(request)

  # older meterpreter binaries will send FILE_NAME containing the hash
  hash = response.get_tlv_value(TLV_TYPE_FILE_HASH) ||
    response.get_tlv_value(TLV_TYPE_FILE_NAME)
  return hash
end

.mv(oldname, newname) ⇒ Object Also known as: move, rename

Performs a rename from oldname to newname



213
214
215
216
217
218
219
220
221
222
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 213

def File.mv(oldname, newname)
  request = Packet.create_request('stdapi_fs_file_move')

  request.add_tlv(TLV_TYPE_FILE_NAME, client.unicode_filter_decode( oldname ))
  request.add_tlv(TLV_TYPE_FILE_PATH, client.unicode_filter_decode( newname ))

  response = client.send_request(request)

  return response
end

.open(name, mode = "r", perms = 0) ⇒ Object

With no associated block, File.open is a synonym for ::new. If the optional code block is given, it will be passed the opened file as an argument, and the File object will automatically be closed when the block terminates. In this instance, File.open returns the value of the block.

(doc stolen from www.ruby-doc.org/core-1.9.3/File.html#method-c-open)



342
343
344
345
346
347
348
349
350
351
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 342

def File.open(name, mode="r", perms=0)
  f = new(name, mode, perms)
  if block_given?
    ret = yield f
    f.close
    return ret
  else
    return f
  end
end

.rm(name) ⇒ Object Also known as: unlink, delete

Performs a delete on the remote file name



195
196
197
198
199
200
201
202
203
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 195

def File.rm(name)
  request = Packet.create_request('stdapi_fs_delete_file')

  request.add_tlv(TLV_TYPE_FILE_PATH, client.unicode_filter_decode( name ))

  response = client.send_request(request)

  return response
end

.search(root = nil, glob = "*.*", recurse = true, timeout = -1 )) ⇒ Object

Search for files matching glob starting in directory root.

Returns an Array (possibly empty) of Hashes. Each element has the following keys:

‘path’

The directory in which the file was found

‘name’

File name

‘size’

Size of the file, in bytes

Example:

client.fs.file.search(client.fs.dir.pwd, "*.txt")
# => [{"path"=>"C:\\Documents and Settings\\user\\Desktop", "name"=>"foo.txt", "size"=>0}]

Raises a RequestError if root is not a directory.



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
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 75

def File.search( root=nil, glob="*.*", recurse=true, timeout=-1 )

  files = ::Array.new

  request = Packet.create_request( 'stdapi_fs_search' )

  root = client.unicode_filter_decode(root) if root
  root = root.chomp( '\\' ) if root

  request.add_tlv( TLV_TYPE_SEARCH_ROOT, root )
  request.add_tlv( TLV_TYPE_SEARCH_GLOB, glob )
  request.add_tlv( TLV_TYPE_SEARCH_RECURSE, recurse )

  # we set the response timeout to -1 to wait indefinatly as a
  # search could take an indeterminate ammount of time to complete.
  response = client.send_request( request, timeout )
  if( response.result == 0 )
    response.each( TLV_TYPE_SEARCH_RESULTS ) do | results |
      files << {
        'path' => client.unicode_filter_encode(results.get_tlv_value(TLV_TYPE_FILE_PATH).chomp( '\\' )),
        'name' => client.unicode_filter_encode(results.get_tlv_value(TLV_TYPE_FILE_NAME)),
        'size' => results.get_tlv_value(TLV_TYPE_FILE_SIZE)
      }
    end
  end

  return files
end

.separatorObject Also known as: Separator, SEPARATOR

Return the directory separator, i.e.: “/” on unix, “\” on windows



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 35

def File.separator()
  # The separator won't change, so cache it to prevent sending
  # unnecessary requests.
  return @separator if @separator

  request = Packet.create_request('stdapi_fs_separator')

  # Fall back to the old behavior of always assuming windows.  This
  # allows meterpreter executables built before the addition of this
  # command to continue functioning.
  begin
    response = client.send_request(request)
    @separator = response.get_tlv_value(TLV_TYPE_STRING)
  rescue RequestError
    @separator = "\\"
  end

  return @separator
end

.sha1(path) ⇒ Object

Calculates the SHA1 (20-bytes raw) of a remote file



164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 164

def File.sha1(path)
  request = Packet.create_request('stdapi_fs_sha1')

  request.add_tlv(TLV_TYPE_FILE_PATH, client.unicode_filter_decode( path ))

  response = client.send_request(request)

  # older meterpreter binaries will send FILE_NAME containing the hash
  hash = response.get_tlv_value(TLV_TYPE_FILE_HASH) ||
    response.get_tlv_value(TLV_TYPE_FILE_NAME)
  return hash
end

.stat(name) ⇒ Object

Performs a stat on a file and returns a FileStat instance.



180
181
182
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 180

def File.stat(name)
  return client.fs.filestat.new( name )
end

.upload(destination, *src_files, &stat) ⇒ Object

Upload one or more files to the remote remote directory supplied in destination.

If a block is given, it will be called before each file is uploaded and again when each upload is complete.



236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 236

def File.upload(destination, *src_files, &stat)
  src_files.each { |src|
    dest = destination

    stat.call('uploading', src, dest) if (stat)
    if (self.basename(destination) != ::File.basename(src))
      dest += self.separator + ::File.basename(src)
    end

    upload_file(dest, src)
    stat.call('uploaded', src, dest) if (stat)
  }
end

.upload_file(dest_file, src_file, &stat) ⇒ Object

Upload a single file.



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 253

def File.upload_file(dest_file, src_file, &stat)
  # Open the file on the remote side for writing and read
  # all of the contents of the local file
  stat.call('uploading', src_file, dest_file) if (stat)
  dest_fd = client.fs.file.new(dest_file, "wb")
  src_buf = ''

  ::File.open(src_file, 'rb') { |f|
    src_buf = f.read(f.stat.size)
  }

  begin
    dest_fd.write(src_buf)
  ensure
    dest_fd.close
  end
  stat.call('uploaded', src_file, dest_file) if (stat)
end

Instance Method Details

#eofObject

Returns whether or not the file has reach EOF.



376
377
378
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 376

def eof
  return self.filed.eof
end

#posObject

Returns the current position of the file pointer.



383
384
385
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 383

def pos
  return self.filed.tell
end

#seek(offset, whence = ::IO::SEEK_SET) ⇒ Object

Synonym for sysseek.



390
391
392
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 390

def seek(offset, whence = ::IO::SEEK_SET)
  return self.sysseek(offset, whence)
end

#sysseek(offset, whence = ::IO::SEEK_SET) ⇒ Object

Seeks to the supplied offset based on the supplied relativity.



397
398
399
# File 'lib/rex/post/meterpreter/extensions/stdapi/fs/file.rb', line 397

def sysseek(offset, whence = ::IO::SEEK_SET)
  return self.filed.seek(offset, whence)
end