Class: DRab::DRabMessage

Inherits:
Object
  • Object
show all
Defined in:
lib/drab/drab.rb

Defined Under Namespace

Modules: Types

Constant Summary collapse

BLACKLISTED_BASIC_OBJECT_METHODS =
Set.new([
    "send",
    "__send__",
    "method",
    "methods",
    "inspect",
    "private_methods",
    "protected_methods",
    "public_method",
    "public_methods",
    "public_send",
    "singleton_class",
    "singleton_method",
    "singleton_methods",
    "taint",
    "trust",
    "untaint",
    "untrust",
    "instance_eval",
    "instance_exec",
    "method_missing",
    "singleton_method_added",
    "singleton_method_removed",
    "instance_variables",
    "instance_variable_get",
    "instance_variable_set",
    "instance_variable_defined?",
    "remove_instance_variable",
])
BLACKLISTED_MODULE_METHODS =
Set.new([
    "used_modules",
    "alias_method",
    "append_features",
    "attr",
    "attr_reader",
    "attr_accessor",
    "attr_writer",
    "define_method",
    "extend_object",
    "extended",
    "include",
    "included",
    "included_modules",
    "instance_method",
    "instance_methods",
    "module_eval",
    "module_exec",
    "prepend",
    "private_class_method",
    "private_constant",
    "private_instance_methods",
    "protected_instance_methods",
    "public_class_method",
    "public_instance_method",
    "public_instance_methods",
    "remove_class_variable",
    "constants",
    "nesting",
    "ancestors",
    "autoload",
    "class_eval",
    "class_exec",
    "class_variable_get",
    "class_variable_set",
    "class_variables",
    "const_get",
    "const_set",
    "const_missing",
    "deprecate_constants",
    "method_added",
    "method_removed",
    "method_undefined",
    "method_function",
    "prepend_features",
    "prepended",
    "private",
    "refine",
    "remove_const",
    "remove_method",
    "undef_method",
    "using",
])
BLACKLISTED_REPL_METHODS =
Set.new([
    "pry",
    "binding",
    "__binding__",
    "remote_pry",
    "remote_pray",
    "pry_remote",
    "pray_remote"
])

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ DRabMessage

Returns a new instance of DRabMessage.



180
181
182
183
# File 'lib/drab/drab.rb', line 180

def initialize(config)
  @load_limit = config[:load_limit]
  @argc_limit = config[:argc_limit]
end

Instance Method Details

#dump(obj, error = false, as_json = false) ⇒ Object



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
# File 'lib/drab/drab.rb', line 185

def dump(obj, error=false, as_json = false)
  if as_json
    str = JSON::dump(obj)
    return [str.size].pack('N') + str
  end

  if obj.is_a?(DRabUndumped)
    obj = make_proxy(obj, error)
  elsif obj.is_a?(Proc)
    obj = make_proxy(obj, error)        
  elsif obj.is_a?(DRabArray)
    p = dump(DRabArray::Token.new(obj.get.size), error)
    obj.get.each { |o| p += dump(o) }
    return p
  end

  begin
    str = Marshal::dump(obj)
  rescue
    #str = Marshal::dump(make_proxy(obj, error))
    STDERR.puts "failed to marshal value of type " + obj.class.to_s + ", not exposing a proxy"
    str = Marshal::dump(nil)
  end
  [str.size].pack('N') + str
end

#kill_instance_methods(obj, msg) ⇒ Object



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
# File 'lib/drab/drab.rb', line 509

def kill_instance_methods(obj, msg)
  if [ "object_id", "__id__" ].include?(msg)
    return
  end

  if obj.is_a?(DRabUndumped)
    if obj.class.class_variable_get(:@@drab_whitelist).include?("to_s")
      if msg === "respond_to?"
        return
      end
    end
    if obj.class.class_variable_get(:@@drab_whitelist).include?(msg)
      return
    else
      puts "unwhitelisted method call attempted: #{msg} on" + obj.class.to_s
      raise Exception.new("unwhitelisted method call attempted")
    end
  end
  
  if BLACKLISTED_BASIC_OBJECT_METHODS.include?(msg)
    puts "dangerous BasicObject method called: #{msg} on " + obj.class.to_s
    raise Exception.new("dangerous BasicObject method called")
  end

  if BLACKLISTED_MODULE_METHODS.include?(msg)
    puts "dangerous Module method called: #{msg} on " + obj.class.to_s
    raise Exception.new("dangerous Module method called")
  end

  if BLACKLISTED_REPL_METHODS.include?(msg)
    puts "dangerous repl method called: #{msg} on " + obj.class.to_s
    raise Exception.new("dangerous repl method called")
  end

end

#load(soc, as_json = false) ⇒ Object

Raises:



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
# File 'lib/drab/drab.rb', line 211

def load(soc, as_json = false)
  begin
    sz = soc.read(4)
  rescue
    raise(DRabConnError, $!.message, $!.backtrace)
  end
  raise(DRabConnError, 'connection closed') if sz.nil?
  raise(DRabConnError, 'premature header') if sz.size < 4
  sz = sz.unpack('N')[0]
  raise(DRabConnError, "too large packet #{sz}") if @load_limit < sz
  begin
    str = soc.read(sz)
  rescue
    raise(DRabConnError, $!.message, $!.backtrace)
  end
  raise(DRabConnError, 'connection closed') if str.nil?
  raise(DRabConnError, 'premature marshal format(can\'t read)') if str.size < sz
  
  if not as_json
    begin
      typ, structure = parse_marshal(str)
    rescue Exception => e
    end
  end

  DRab.mutex.synchronize do
    begin
      save = Thread.current[:drab_untaint]
      Thread.current[:drab_untaint] = []
      if as_json
        JSON::load(str)
      else
        if typ.between?(Types::Bln, Types::Arr)
          Marshal::load(str)
        elsif typ === Types::Err
          Exception.new(s.to_s)
        else
          STDERR.puts "got weird object: " + str.inspect + "\nwith structure: " + structure.inspect
          nil
        end
      end
    rescue NameError, ArgumentError => e
      puts e
      puts e.backtrace
      DRabUnknown.new($!, str)
    ensure
      Thread.current[:drab_untaint].each do |x|
        x.untaint
      end
      Thread.current[:drab_untaint] = save
    end
  end
end

#match_structures(template, target) ⇒ Object



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
# File 'lib/drab/drab.rb', line 281

def match_structures(template, target)
  begin
    if not (template.is_a?(Array) and target.is_a?(Array))
      return false
    end

    if template.size != target.size
      return false
    end

    return (0...template.size).collect do |n|
      if template[n].is_a?(Array)
        hld = match_structures(template[n], target[n])
        if !hld
          return [false]
        else
          next hld
        end
      end

      if template[n] === target[n]
        next true
      end

      if template[n].is_a?(String) and target[n].is_a?(String)
        if template[n] === "*"
          next true
        elsif template[n].start_with?("*")
          next target[n].end_with?(template[n][1..-1])
        elsif template[n].end_with?("*")
          next target[n].start_with?(template[n][0..-2])
        else
          return [false]
        end
      end
    end.inject { |t, n| t and n }
  rescue Exception => e
    STDERR.puts e
    STDERR.puts e.backtrace
  end     
  return false
end

#parse_marshal(str) ⇒ Object



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
# File 'lib/drab/drab.rb', line 337

def parse_marshal(str)
  begin
    # i don't know why, but if this runs in the current thread,
    # the __recursive_key__ state in PP, as invoked by pry, gets mangled
    msthread = Thread.new { Thread.current[:structure] = Marshal::Structure::load(str) }
    msthread.join
    parsed_str = msthread[:structure]
    if parsed_str === :true or parsed_str === :false
      return Types::Bln
    elsif parsed_str === :nil
      return Types::Nil
    elsif parsed_str === [:symbol, 0, "write"] # :write
      return Types::Sym
    elsif parsed_str === [:symbol, 0, "readline"] # :readline
      return Types::Sym
    elsif parsed_str.size === 2 and parsed_str[0] === :fixnum and parsed_str[1].is_a?(Integer)
      return Types::Num
    elsif match_structures([ # json DRab::DRabObject
      :user_defined,
      0,
      [:symbol, 0, "DRab::DRabObject"],
      "*"
    ], parsed_str)
      return [Types::DRb, parsed_str]
    elsif match_structures([ # json DRab::DRabObject
      :instance_variables,
      [
        :user_defined,
        0,
        [:symbol, 0, "DRab::DRabObject"],
        "*"
      ],
      1,
      [:symbol, 1, "E"],
      :true
    ], parsed_str)
      return [Types::DRb, parsed_str]
    elsif match_structures([ # string
      :string,
      0,
      "*"
    ], parsed_str)
      return Types::Str
    elsif match_structures([ # string
      :instance_variables,
      [:string, 0, "*"],
      1,
      [:symbol, 0, "E"],
      :false
    ], parsed_str)
      return Types::Str
    elsif match_structures([ # json DRab::DRabArray::Token
      :instance_variables,
      [
        :user_defined,
        0,
        [:symbol, 0, "DRab::DRabArray::Token"],
        "*"
      ],
      1,
      [:symbol, 1, "E"],
      :true
    ], parsed_str)
      return [Types::Arr, parsed_str]
    elsif match_structures([
      [:object, 0, [:symbol, 0, "*Error"]]
    ], parsed_str[0..2])
      return [Types::Err, parsed_str]
    else
      return [Types::Ukn, parsed_str]
    end
  rescue Exception => e
    STDERR.puts e
    STDERR.puts e.backtrace
  end
  return [Types::Ukn, parsed_str]
end

#recv_reply(stream) ⇒ Object



636
637
638
639
640
641
642
643
644
645
646
# File 'lib/drab/drab.rb', line 636

def recv_reply(stream)
  recv_secret(stream)
  succ = load(stream)
  result = load(stream)
  if result.is_a?(DRabArray::Token)
    r = result.size.times.collect {|| load(stream) }
    [succ, r]
  else
    [succ, result]
  end
end

#recv_request(stream) ⇒ Object

/jtd

Raises:



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
# File 'lib/drab/drab.rb', line 596

def recv_request(stream)
  recv_secret(stream)
  ref = load(stream, true)
  if not ref.is_a? Integer and not ref.is_a? NilClass
    raise Exception.new "non-numeric ref id"
  end
  ro = DRab.to_obj(ref)

  msg = load(stream, true)
  if not msg.is_a? String
    raise Exception.new "non-string msg name"
  end

  #note: obviously, blacklisting a few things is not enough, we also need
  #      to make sure that arbitrary objects can't just be wrapped by id
  #      or deserialized, and maybe do to limit the sorts of
  #      objects that can be passed to only primative or "DRab-aware" types.
  kill_instance_methods(ro, msg)

  argc = load(stream, true)
  if not argc.is_a? Integer
    raise Exception.new "non-numeric argc"
  end
  raise(DRabConnError, "too many arguments") if @argc_limit < argc
  argv = Array.new(argc, nil)
  argc.times do |n|
    argv[n] = load(stream)
  end
  block = nil

  return ro, msg, argv, block
end

#recv_secret(stream) ⇒ Object



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
# File 'lib/drab/drab.rb', line 565

def recv_secret(stream)
  if DRab.current_server.secret != nil
    shared_secret = DRab.current_server.secret
    received_secret = nil

    begin
      sz = stream.read(4)
    rescue
      raise(DRabConnError, $!.message, $!.backtrace)
    end
    raise(DRabConnError, 'connection closed') if sz.nil?
    raise(DRabConnError, 'secret size wrong size') if sz.size != 4
    sz = sz.unpack('N')[0]
    raise(DRabConnError, 'secret size wrong') if sz != shared_secret.size
    begin
      received_secret = stream.read(sz)
    rescue
      raise(DRabConnError, $!.message, $!.backtrace)
    end
    raise(DRabConnError, 'connection closed') if received_secret.nil?
    raise(DRabConnError, 'premature secret (can\'t read)') if received_secret.size < sz

    if received_secret.length != shared_secret.length
      stream.close
    elsif !secure_compare(shared_secret, received_secret)
      stream.close
    end
  end
end

#secure_compare(a, b) ⇒ Object

taken from rails/ActiveSupport/MessageVerifier/secure_compare



555
556
557
558
559
560
561
562
563
# File 'lib/drab/drab.rb', line 555

def secure_compare(a, b)
  return false unless a.bytesize == b.bytesize

  l = a.unpack "C#{a.bytesize}"

  res = 0
  b.each_byte { |byte| res |= byte ^ l.shift }
  res == 0
end

#send_reply(stream, succ, result) ⇒ Object



629
630
631
632
633
634
# File 'lib/drab/drab.rb', line 629

def send_reply(stream, succ, result)
  send_secret(stream)
  stream.write(dump(succ) + dump(result, !succ))
rescue
  raise(DRabConnError, $!.message, $!.backtrace)
end

#send_request(stream, ref, msg_id, arg, b) ⇒ Object



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/drab/drab.rb', line 265

def send_request(stream, ref, msg_id, arg, b)
  ary = []
  ary.push(dump(ref.__drabref, false, true))
  ary.push(dump(msg_id.id2name, false, true))
  ary.push(dump(arg.length, false, true))
  arg.each do |e|
    ary.push(dump(e))
  end
  #ary.push(dump(b))

  send_secret(stream)
  stream.write(ary.join(''))
rescue
  raise(DRabConnError, $!.message, $!.backtrace)
end

#send_secret(stream) ⇒ Object

jtd: adding symkey auth here



547
548
549
550
551
552
# File 'lib/drab/drab.rb', line 547

def send_secret(stream)
  if DRab.current_server.secret != nil
    shared_secret = DRab.current_server.secret
    stream.write([shared_secret.size].pack('N') + shared_secret)
  end
end