Module: Rex::Proto::MSSQL::ClientMixin

Extended by:
Forwardable
Includes:
Msf::Module::UI::Message, Rex::Proto::MsTds
Included in:
Client
Defined in:
lib/rex/proto/mssql/client_mixin.rb

Overview

A base mixin of useful mssql methods for parsing structures etc

Defined Under Namespace

Modules: ENVCHANGE

Constant Summary collapse

ENCRYPT_OFF =

Encryption

0x00
ENCRYPT_ON =

Encryption is available but off.

0x01
ENCRYPT_NOT_SUP =

Encryption is available and on.

0x02
ENCRYPT_REQ =

Encryption is not available.

0x03
TYPE_SQL_BATCH =

Packet Type

1
TYPE_PRE_TDS7_LOGIN =

(Client) SQL command

2
TYPE_RPC =

(Client) Pre-login with version < 7 (unused)

3
TYPE_TABLE_RESPONSE =

(Client) RPC

4
TYPE_ATTENTION_SIGNAL =

Request Completion, Error and Info Messages, Attention Acknowledgement

6
TYPE_BULK_LOAD =

(Client) Attention

7
TYPE_TRANSACTION_MANAGER_REQUEST =

(Client) SQL Command with binary data

14
TYPE_TDS7_LOGIN =

(Client) Transaction request manager

16
TYPE_SSPI_MESSAGE =

(Client) Login

17
TYPE_PRE_LOGIN_MESSAGE =

(Client) Login

18
STATUS_NORMAL =

Status

MsTdsStatus::NORMAL
STATUS_END_OF_MESSAGE =
MsTdsStatus::END_OF_MESSAGE
STATUS_IGNORE_EVENT =
MsTdsStatus::IGNORE_EVENT
STATUS_RESETCONNECTION =
MsTdsStatus::RESETCONNECTION
STATUS_RESETCONNECTIONSKIPTRAN =
MsTdsStatus::RESECCONNECTIONTRAN

Instance Method Summary collapse

Methods included from Msf::Module::UI::Message

#print_error, #print_good, #print_prefix, #print_status, #print_warning

Methods included from Msf::Module::UI::Message::Verbose

#vprint_error, #vprint_good, #vprint_status, #vprint_warning

Instance Method Details

#mssql_parse_done(data, info) ⇒ Object

Parse a “done” TDS token



631
632
633
634
635
# File 'lib/rex/proto/mssql/client_mixin.rb', line 631

def mssql_parse_done(data, info)
  status, cmd, rows = data.slice!(0, 8).unpack('vvV')
  info[:done] = { :status => status, :cmd => cmd, :rows => rows }
  info
end

#mssql_parse_env(data, info) ⇒ Object

Parse an “environment change” TDS token



655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
# File 'lib/rex/proto/mssql/client_mixin.rb', line 655

def mssql_parse_env(data, info)
  len  = data.slice!(0, 2).unpack('v')[0]
  buff = data.slice!(0, len)
  type = buff.slice!(0, 1).unpack('C')[0]

  nval = ''
  nlen = buff.slice!(0, 1).unpack('C')[0] || 0
  nval = buff.slice!(0, nlen * 2).gsub("\x00", '') if nlen > 0

  oval = ''
  olen = buff.slice!(0, 1).unpack('C')[0] || 0
  oval = buff.slice!(0, olen * 2).gsub("\x00", '') if olen > 0

  info[:envs] ||= []
  info[:envs] << { :type => type, :old => oval, :new => nval }

  self.current_database = nval if type == ENVCHANGE::DATABASE

  info
end

#mssql_parse_error(data, info) ⇒ Object

Parse an “error” TDS token



640
641
642
643
644
645
646
647
648
649
650
# File 'lib/rex/proto/mssql/client_mixin.rb', line 640

def mssql_parse_error(data, info)
  len  = data.slice!(0, 2).unpack('v')[0]
  buff = data.slice!(0, len)

  errno, state, sev, elen = buff.slice!(0, 8).unpack('VCCv')
  emsg = buff.slice!(0, elen * 2)
  emsg.gsub!("\x00", '')

  info[:errors] << "SQL Server Error ##{errno} (State:#{state} Severity:#{sev}): #{emsg}"
  info
end

#mssql_parse_info(data, info) ⇒ Object

Parse an “information” TDS token



679
680
681
682
683
684
685
686
687
688
689
690
# File 'lib/rex/proto/mssql/client_mixin.rb', line 679

def mssql_parse_info(data, info)
  len  = data.slice!(0, 2).unpack('v')[0]
  buff = data.slice!(0, len)

  errno, state, sev, elen = buff.slice!(0, 8).unpack('VCCv')
  emsg = buff.slice!(0, elen * 2)
  emsg.gsub!("\x00", '')

  info[:infos] ||= []
  info[:infos] << "SQL Server Info ##{errno} (State:#{state} Severity:#{sev}): #{emsg}"
  info
end

#mssql_parse_login_ack(data, info) ⇒ Object

Parse a “login ack” TDS token



695
696
697
698
699
# File 'lib/rex/proto/mssql/client_mixin.rb', line 695

def (data, info)
  len = data.slice!(0, 2).unpack('v')[0]
  _buff = data.slice!(0, len)
  info[:login_ack] = true
end

#mssql_parse_nbcrow(data, info) ⇒ Object

Parse a “NBCROW” (Null Bitmap Compressed Row) TDS token This token is used in SQL Server 2019+ for compressed row data See: learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tds/7e12206c-0e1b-4c8c-b2e5-2ad8b0e3b9b0



719
720
721
722
723
724
725
726
727
728
729
# File 'lib/rex/proto/mssql/client_mixin.rb', line 719

def mssql_parse_nbcrow(data, info)
  # Attempt to parse NBCROW token with fallback to TDS row parsing
  # This fixes the "unsupported token: 169" error with SQL Server 2022
  begin
    return mssql_parse_nbcrow_internal(data, info)
  rescue StandardError => e
    info[:errors] ||= []
    info[:errors] << "NBCROW parsing failed, using TDS fallback: #{e.message}"
    return mssql_parse_tds_row(data, info)
  end
end

#mssql_parse_nbcrow_internal(data, info) ⇒ Object

Internal NBCROW parsing implementation Separated to allow fallback mechanism in main method



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
# File 'lib/rex/proto/mssql/client_mixin.rb', line 735

def mssql_parse_nbcrow_internal(data, info)
  info[:rows] ||= []

  return info if info[:colinfos].nil? || info[:colinfos].empty?
  return info if data.length == 0

  # Read the null bitmap length
  null_bitmap_len = (info[:colinfos].length + 7) / 8

  # Check if we have enough data for the null bitmap
  if data.length < null_bitmap_len
    # Fallback to regular TDS row parsing
    return mssql_parse_tds_row(data, info)
  end

  null_bitmap = data.slice!(0, null_bitmap_len).unpack('C*')

  row = []
  info[:colinfos].each_with_index do |col, col_idx|
    # Check if this column is null using the null bitmap
    byte_idx = col_idx / 8
    bit_idx = col_idx % 8

    # Ensure we don't access beyond the bitmap array
    if byte_idx >= null_bitmap.length
      info[:errors] ||= []
      info[:errors] << "NBCROW null bitmap index out of bounds: #{byte_idx} >= #{null_bitmap.length}"
      return info
    end

    is_null = (null_bitmap[byte_idx] & (1 << bit_idx)) != 0

    if is_null
      row << nil
      next
    end

    # Check if we have enough data remaining for column parsing
    if data.length == 0
      info[:errors] ||= []
      info[:errors] << "Insufficient data remaining for NBCROW column #{col_idx} (#{col[:id]})"
      return info
    end

    # Parse the column data based on type (similar to mssql_parse_tds_row)
    case col[:id]
    when :hex
      return info if data.length < 2
      str = ""
      len = data.slice!(0, 2).unpack('v')[0]
      if len > 0 && len < 65535 && data.length >= len
        str << data.slice!(0, len)
      end
      row << str.unpack("H*")[0]

    when :guid
      return info if data.length < 1
      read_length = data.slice!(0, 1).unpack1('C')
      if read_length == 0
        row << nil
      elsif data.length >= read_length
        row << Rex::Text.to_guid(data.slice!(0, read_length))
      else
        return info
      end

    when :string
      return info if data.length < 2
      str = ""
      len = data.slice!(0, 2).unpack('v')[0]
      if len > 0 && len < 65535 && data.length >= len
        str << data.slice!(0, len)
      end
      row << str.gsub("\x00", '')

    when :ntext
      str = nil
      ptrlen = data.slice!(0, 1).unpack("C")[0]
      ptr = data.slice!(0, ptrlen)
      unless ptrlen == 0
        timestamp = data.slice!(0, 8)
        datalen = data.slice!(0, 4).unpack("V")[0]
        if datalen > 0 && datalen < 65535
          str = data.slice!(0, datalen).gsub("\x00", '')
        else
          str = ''
        end
      end
      row << str

    when :float
      datalen = data.slice!(0, 1).unpack('C')[0]
      case datalen
      when 8
        row << data.slice!(0, datalen).unpack('E')[0]
      when 4
        row << data.slice!(0, datalen).unpack('e')[0]
      else
        row << nil
      end

    when :numeric
      varlen = data.slice!(0, 1).unpack('C')[0]
      if varlen == 0
        row << nil
      else
        sign = data.slice!(0, 1).unpack('C')[0]
        raw = data.slice!(0, varlen - 1)
        value = ''

        case varlen
        when 5
          value = raw.unpack('L')[0]/(10**col[:scale]).to_f
        when 9
          value = raw.unpack('Q')[0]/(10**col[:scale]).to_f
        when 13
          chunks = raw.unpack('L3')
          value = chunks[2] << 64 | chunks[1] << 32 | chunks[0]
          value /= (10**col[:scale]).to_f
        when 17
          chunks = raw.unpack('L4')
          value = chunks[3] << 96 | chunks[2] << 64 | chunks[1] << 32 | chunks[0]
          value /= (10**col[:scale]).to_f
        end
        case sign
        when 1
          row << value
        when 0
          row << value * -1
        end
      end

    when :money
      datalen = data.slice!(0, 1).unpack('C')[0]
      if datalen == 0
        row << nil
      else
        raw = data.slice!(0, datalen)
        rev = raw.slice(4, 4) << raw.slice(0, 4)
        row << rev.unpack('q')[0]/10000.0
      end

    when :smallmoney
      datalen = data.slice!(0, 1).unpack('C')[0]
      if datalen == 0
        row << nil
      else
        row << data.slice!(0, datalen).unpack('l')[0] / 10000.0
      end

    when :smalldatetime
      datalen = data.slice!(0, 1).unpack('C')[0]
      if datalen == 0
        row << nil
      else
        days = data.slice!(0, 2).unpack('S')[0]
        minutes = data.slice!(0, 2).unpack('S')[0] / 1440.0
        row << DateTime.new(1900, 1, 1) + days + minutes
      end

    when :datetime
      datalen = data.slice!(0, 1).unpack('C')[0]
      if datalen == 0
        row << nil
      else
        days = data.slice!(0, 4).unpack('l')[0]
        minutes = data.slice!(0, 4).unpack('l')[0] / 1440.0
        row << DateTime.new(1900, 1, 1) + days + minutes
      end

    when :rawint
      row << data.slice!(0, 4).unpack('V')[0]

    when :bigint
      row << data.slice!(0, 8).unpack("H*")[0]

    when :smallint
      row << data.slice!(0, 2).unpack("v")[0]

    when :smallint3
      row << [data.slice!(0, 3)].pack("Z4").unpack("V")[0]

    when :tinyint
      row << data.slice!(0, 1).unpack("C")[0]

    when :bitn
      has_value = data.slice!(0, 1).unpack("C")[0]
      if has_value == 0
        row << nil
      else
        row << data.slice!(0, 1).unpack("C")[0]
      end

    when :bit
      row << data.slice!(0, 1).unpack("C")[0]

    when :image
      str = ''
      len = data.slice!(0, 1).unpack('C')[0]
      str = data.slice!(0, len) if len && len > 0
      row << str.unpack("H*")[0]

    when :int
      len = data.slice!(0, 1).unpack("C")[0]

      case len
      when 0, 255
        row << nil
      when 1
        row << data.slice!(0, 1).unpack("C")[0]
      when 2
        row << data.slice!(0, 2).unpack('v')[0]
      when 4
        row << data.slice!(0, 4).unpack('V')[0]
      when 5
        row << data.slice!(0, 5).unpack('V')[0] # XXX: missing high byte
      when 8
        row << data.slice!(0, 8).unpack('VV')[0] # XXX: missing high dword
      else
        info[:errors] << "invalid integer size: #{len} #{data[0, 16].unpack("H*")[0]}"
        data.slice!(0, len)
      end
    else
      info[:errors] << "unknown column type: #{col.inspect}"
    end
  end

  info[:rows] << row
  info
end

#mssql_parse_order(data, info) ⇒ Object

Parse an ORDER token (0xA9) Sent when an ORDER BY clause is executed. Contains column ordinals. See: learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tds/252759be-9d74-4435-809d-d55dd860ea78



706
707
708
709
710
711
712
# File 'lib/rex/proto/mssql/client_mixin.rb', line 706

def mssql_parse_order(data, info)
  # Length is a USHORT indicating the byte length of the ColNum list
  len = data.slice!(0, 2).unpack('v')[0]
  # Skip the column ordinal data (each is a USHORT)
  data.slice!(0, len) if len && len > 0
  info
end

#mssql_parse_reply(data, info = nil) ⇒ Object

Parse individual tokens from a TDS reply



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
# File 'lib/rex/proto/mssql/client_mixin.rb', line 372

def mssql_parse_reply(data, info=nil)
  info ||= {}
  info[:errors] = []
  return if not data
  states = []
  until data.empty? || info[:errors].any?
    token = data.slice!(0, 1).unpack('C')[0]
    case token
    when 0x81
      states << :mssql_parse_tds_reply
      mssql_parse_tds_reply(data, info)
    when 0xd1
      states << :mssql_parse_tds_row
      mssql_parse_tds_row(data, info)
    when 0xe3
      states << :mssql_parse_env
      mssql_parse_env(data, info)
    when 0x79
      states << :mssql_parse_ret
      mssql_parse_ret(data, info)
    when 0xfd, 0xfe, 0xff
      states << :mssql_parse_done
      mssql_parse_done(data, info)
    when 0xad
      states << :mssql_parse_login_ack
      (data, info)
    when 0xab
      states << :mssql_parse_info
      mssql_parse_info(data, info)
    when 0xa9
      states << :mssql_parse_order
      mssql_parse_order(data, info)
    when 0xd2
      states << :mssql_parse_nbcrow
      mssql_parse_nbcrow(data, info)
    when 0xaa
      states << :mssql_parse_error
      mssql_parse_error(data, info)
    when nil
      break
    else
      info[:errors] << "unsupported token: #{token}. Previous states: #{states}"
      break
    end
  end
  info
end

#mssql_parse_ret(data, info) ⇒ Object

Parse a “ret” TDS token



622
623
624
625
626
# File 'lib/rex/proto/mssql/client_mixin.rb', line 622

def mssql_parse_ret(data, info)
  ret = data.slice!(0, 4).unpack('N')[0]
  info[:ret] = ret
  info
end

#mssql_parse_tds_reply(data, info) ⇒ Object

Parse a raw TDS reply from the server



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
# File 'lib/rex/proto/mssql/client_mixin.rb', line 233

def mssql_parse_tds_reply(data, info)
  info[:errors] ||= []
  info[:colinfos] ||= []
  info[:colnames] ||= []

  # Parse out the columns
  cols = data.slice!(0, 2).unpack('v')[0]
  0.upto(cols-1) do |col_idx|
    col = {}
    info[:colinfos][col_idx] = col

    col[:utype] = data.slice!(0, 2).unpack('v')[0]
    col[:flags] = data.slice!(0, 2).unpack('v')[0]
    col[:type]  = data.slice!(0, 1).unpack('C')[0]
    case col[:type]
    when 48
      col[:id] = :tinyint

    when 52
      col[:id] = :smallint

    when 56
      col[:id] = :rawint

    when 61
      col[:id] = :datetime

    when 34
      col[:id]            = :image
      col[:max_size]      = data.slice!(0, 4).unpack('V')[0]
      col[:value_length]  = data.slice!(0, 2).unpack('v')[0]
      col[:value]         = data.slice!(0, col[:value_length]  * 2).gsub("\x00", '')

    when 109
      col[:id] = :float
      col[:value_length] = data.slice!(0, 1).unpack('C')[0]

    when 108
      col[:id] = :numeric
      col[:value_length] = data.slice!(0, 1).unpack('C')[0]
      col[:precision] = data.slice!(0, 1).unpack('C')[0]
      col[:scale] = data.slice!(0, 1).unpack('C')[0]

    when 60
      col[:id] = :money

    when 110
      col[:value_length] = data.slice!(0, 1).unpack('C')[0]
      case col[:value_length]
      when 8
        col[:id] = :money
      when 4
        col[:id] = :smallmoney
      else
        col[:id] = :unknown
      end

    when 111
      col[:value_length] = data.slice!(0, 1).unpack('C')[0]
      case col[:value_length]
      when 4
        col[:id] = :smalldatetime
      when 8
        col[:id] = :datetime
      else
        col[:id] = :unknown
      end

    when 122
      col[:id] = :smallmoney

    when 59
      col[:id] = :float

    when 58
      col[:id] = :smalldatetime

    when 36
      col[:id] = :guid
      col[:value_length] = data.slice!(0, 1).unpack('C')[0]

    when 38
      col[:id] = :int
      col[:int_size] = data.slice!(0, 1).unpack('C')[0]

    when 50
      col[:id] = :bit

    when 99
      col[:id] = :ntext
      col[:max_size] = data.slice!(0, 4).unpack('V')[0]
      col[:codepage] = data.slice!(0, 2).unpack('v')[0]
      col[:cflags] = data.slice!(0, 2).unpack('v')[0]
      col[:charset_id] =  data.slice!(0, 1).unpack('C')[0]
      col[:namelen] = data.slice!(0, 1).unpack('C')[0]
      col[:table_name] = data.slice!(0, (col[:namelen] * 2) + 1).gsub("\x00", '')

    when 104
      col[:id] = :bitn
      col[:int_size] = data.slice!(0, 1).unpack('C')[0]

    when 127
      col[:id] = :bigint

    when 165
      col[:id] = :hex
      col[:max_size] = data.slice!(0, 2).unpack('v')[0]

    when 173
      col[:id] = :hex # binary(2)
      col[:max_size] = data.slice!(0, 2).unpack('v')[0]

    when 231, 175, 167, 239
      col[:id] = :string
      col[:max_size] = data.slice!(0, 2).unpack('v')[0]
      col[:codepage] = data.slice!(0, 2).unpack('v')[0]
      col[:cflags] = data.slice!(0, 2).unpack('v')[0]
      col[:charset_id] =  data.slice!(0, 1).unpack('C')[0]

    else
      col[:id] = :unknown

      # See https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tds/ce3183a6-9d89-47e8-a02f-de5a1a1303de for details about column types
      info[:errors] << "Unsupported column type: #{col[:type]}. "
      return info
    end

    col[:msg_len] = data.slice!(0, 1).unpack('C')[0]

    if col[:msg_len] && col[:msg_len] > 0
      col[:name] = data.slice!(0, col[:msg_len] * 2).gsub("\x00", '')
    end
    info[:colnames] << (col[:name] || 'NULL')
  end
end

#mssql_parse_tds_row(data, info) ⇒ Object

Parse a single row of a TDS reply



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
# File 'lib/rex/proto/mssql/client_mixin.rb', line 423

def mssql_parse_tds_row(data, info)
  info[:rows] ||= []
  row = []

  info[:colinfos].each do |col|

    if(data.length == 0)
      row << "<EMPTY>"
      next
    end

    case col[:id]
    when :hex
      len = data.slice!(0, 2).unpack('v')[0]
      if len == 65535
        row << nil
      elsif len > 0
        row << data.slice!(0, len).unpack("H*")[0]
      else
        row << ''
      end

    when :guid
      read_length = data.slice!(0, 1).unpack1('C')
      if read_length == 0
        row << nil
      else
        row << Rex::Text.to_guid(data.slice!(0, read_length))
      end

    when :string
      len = data.slice!(0, 2).unpack('v')[0]
      if len == 65535
        row << nil
      elsif len > 0
        row << data.slice!(0, len).gsub("\x00", '')
      else
        row << ''
      end

    when :ntext
      str = nil
      ptrlen = data.slice!(0, 1).unpack("C")[0]
      ptr = data.slice!(0, ptrlen)
      unless ptrlen == 0
        timestamp = data.slice!(0, 8)
        datalen = data.slice!(0, 4).unpack("V")[0]
        if datalen > 0 && datalen < 65535
          str = data.slice!(0, datalen).gsub("\x00", '')
        else
          str = ''
        end
      end
      row << str

    when :float
      datalen = data.slice!(0, 1).unpack('C')[0]
      case datalen
      when 8
        row << data.slice!(0, datalen).unpack('E')[0]
      when 4
        row << data.slice!(0, datalen).unpack('e')[0]
      else
        row << nil
      end

    when :numeric
      varlen = data.slice!(0, 1).unpack('C')[0]
      if varlen == 0
        row << nil
      else
        sign = data.slice!(0, 1).unpack('C')[0]
        raw = data.slice!(0, varlen - 1)
        value = ''

        case varlen
        when 5
          value = raw.unpack('L')[0]/(10**col[:scale]).to_f
        when 9
          value = raw.unpack('Q')[0]/(10**col[:scale]).to_f
        when 13
          chunks = raw.unpack('L3')
          value = chunks[2] << 64 | chunks[1] << 32 | chunks[0]
          value /= (10**col[:scale]).to_f
        when 17
          chunks = raw.unpack('L4')
          value = chunks[3] << 96 | chunks[2] << 64 | chunks[1] << 32 | chunks[0]
          value /= (10**col[:scale]).to_f
        end
        case sign
        when 1
          row << value
        when 0
          row << value * -1
        end
      end

    when :money
      datalen = data.slice!(0, 1).unpack('C')[0]
      if datalen == 0
        row << nil
      else
        raw = data.slice!(0, datalen)
        rev = raw.slice(4, 4) << raw.slice(0, 4)
        row << rev.unpack('q')[0]/10000.0
      end

    when :smallmoney
      datalen = data.slice!(0, 1).unpack('C')[0]
      if datalen == 0
        row << nil
      else
        row << data.slice!(0, datalen).unpack('l')[0] / 10000.0
      end

    when :smalldatetime
      datalen = data.slice!(0, 1).unpack('C')[0]
      if datalen == 0
        row << nil
      else
        days = data.slice!(0, 2).unpack('S')[0]
        minutes = data.slice!(0, 2).unpack('S')[0] / 1440.0
        row << DateTime.new(1900, 1, 1) + days + minutes
      end

    when :datetime
      datalen = data.slice!(0, 1).unpack('C')[0]
      if datalen == 0
        row << nil
      else
        days = data.slice!(0, 4).unpack('l')[0]
        minutes = data.slice!(0, 4).unpack('l')[0] / 1440.0
        row << DateTime.new(1900, 1, 1) + days + minutes
      end

    when :rawint
      row << data.slice!(0, 4).unpack('V')[0]

    when :bigint
      row << data.slice!(0, 8).unpack("H*")[0]

    when :smallint
      row << data.slice!(0, 2).unpack("v")[0]

    when :smallint3
      row << [data.slice!(0, 3)].pack("Z4").unpack("V")[0]

    when :tinyint
      row << data.slice!(0, 1).unpack("C")[0]

    when :bitn
      has_value = data.slice!(0, 1).unpack("C")[0]
      if has_value == 0
        row << nil
      else
        row << data.slice!(0, 1).unpack("C")[0]
      end

    when :bit
      row << data.slice!(0, 1).unpack("C")[0]

    when :image
      str = ''
      len = data.slice!(0, 1).unpack('C')[0]
      str = data.slice!(0, len) if len && len > 0
      row << str.unpack("H*")[0]

    when :int
      len = data.slice!(0, 1).unpack("C")[0]

      case len
      when 0, 255
        row << nil
      when 1
        row << data.slice!(0, 1).unpack("C")[0]
      when 2
        row << data.slice!(0, 2).unpack('v')[0]
      when 4
        row << data.slice!(0, 4).unpack('V')[0]
      when 5
        row << data.slice!(0, 5).unpack('V')[0] # XXX: missing high byte
      when 8
        row << data.slice!(0, 8).unpack('VV')[0] # XXX: missing high dword
      else
        info[:errors] << "invalid integer size: #{len} #{data[0, 16].unpack("H*")[0]}"
        data.slice!(0, len)
      end
    else
      info[:errors] << "unknown column type: #{col.inspect}"
    end
  end

  info[:rows] << row
  info
end

#mssql_prelogin_packetObject



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
# File 'lib/rex/proto/mssql/client_mixin.rb', line 92

def mssql_prelogin_packet
  pkt_data_token = ""
  pkt_data = ""

  pkt_hdr = MsTdsHeader.new(
    packet_type: MsTdsType::PRE_LOGIN_MESSAGE
  )

  version = [0x55010008, 0x0000].pack("Vv")

  # if manually set, we will honour
  if tdsencryption == true
    encryption = ENCRYPT_ON
  else
    encryption = ENCRYPT_NOT_SUP
  end

  instoptdata = "MSSQLServer\0"

  threadid = "\0\0" + Rex::Text.rand_text(2)

  idx = 21 # size of pkt_data_token
  pkt_data_token << [
      0x00, # Token 0 type Version
      idx , # VersionOffset
      version.length, # VersionLength

      0x01, # Token 1 type Encryption
      idx = idx + version.length, # EncryptionOffset
      0x01, # EncryptionLength

      0x02, # Token 2 type InstOpt
      idx = idx + 1, # InstOptOffset
      instoptdata.length, # InstOptLength

      0x03, # Token 3 type Threadid
      idx + instoptdata.length, # ThreadIdOffset
      0x04, # ThreadIdLength

      0xFF
  ].pack('CnnCnnCnnCnnC')

  pkt_data << pkt_data_token
  pkt_data << version
  pkt_data << encryption
  pkt_data << instoptdata
  pkt_data << threadid

  pkt_hdr.packet_length += pkt_data.length

  pkt = pkt_hdr.to_binary_s + pkt_data
  pkt
end

#mssql_print_reply(info) ⇒ Object



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
# File 'lib/rex/proto/mssql/client_mixin.rb', line 62

def mssql_print_reply(info)
  print_status("SQL Query: #{info[:sql]}")

  if info[:done] && info[:done][:rows].to_i > 0
    print_status("Row Count: #{info[:done][:rows]} (Status: #{info[:done][:status]} Command: #{info[:done][:cmd]})")
  end

  if info[:errors] && !info[:errors].empty?
    info[:errors].each do |err|
      print_error(err)
    end
  end

  if info[:rows] && !info[:rows].empty?

    tbl = Rex::Text::Table.new(
      'Indent'    => 1,
      'Header'    => "Response",
      'Columns'   => info[:colnames],
      'SortIndex' => -1
    )

    info[:rows].each do |row|
      tbl << row.map{ |x| x.nil? ? 'nil' : x }
    end

    print_line(tbl.to_s)
  end
end

#mssql_send_recv(req, timeout = 15, check_status = true) ⇒ Object



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
# File 'lib/rex/proto/mssql/client_mixin.rb', line 166

def mssql_send_recv(req, timeout=15, check_status = true)
  sock.put(req)

  # Read the 8 byte header to get the length and status
  # Read the length to get the data
  # If the status is 0, read another header and more data

  done = false
  resp = ""

  while(not done)
    head = sock.get_once(8, timeout)
    if !(head && head.length == 8)
      return false
    end

    # Is this the last buffer?
    if head[1, 1] == "\x01" || !check_status
      done = true
    end

    # Grab this block's length
    rlen = head[2, 2].unpack('n')[0] - 8

    while(rlen > 0)
      buff = sock.get_once(rlen, timeout)
      return if not buff
      resp << buff
      rlen -= buff.length
    end
  end

  resp
end

#mssql_xpcmdshell(cmd, doprint = false, opts = {}) ⇒ Object



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
# File 'lib/rex/proto/mssql/client_mixin.rb', line 201

def mssql_xpcmdshell(cmd, doprint=false, opts={})
  force_enable = false
  begin
    res = query("EXEC master..xp_cmdshell '#{cmd}'", false, opts)
    if res[:errors] && !res[:errors].empty?
      if res[:errors].join =~ /xp_cmdshell/
        if force_enable
          print_error("The xp_cmdshell procedure is not available and could not be enabled")
          raise RuntimeError, "Failed to execute command"
        else
          print_status("The server may have xp_cmdshell disabled, trying to enable it...")
          query(mssql_xpcmdshell_enable())
          raise RuntimeError, "xp_cmdshell disabled"
        end
      end
    end

    mssql_print_reply(res) if doprint

    return res

  rescue RuntimeError => e
    if e.to_s =~ /xp_cmdshell disabled/
      force_enable = true
      retry
    end
    raise e
  end
end

#parse_prelogin_response(resp) ⇒ Object



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/rex/proto/mssql/client_mixin.rb', line 146

def parse_prelogin_response(resp)
  data = {}
  if resp.length > 5 # minimum size for response specification
    version_index = resp.slice(1, 2).unpack('n')[0]

    major = resp.slice(version_index, 1).unpack('C')[0]
    minor = resp.slice(version_index+1, 1).unpack('C')[0]
    build = resp.slice(version_index+2, 2).unpack('n')[0]

    enc_index = resp.slice(6, 2).unpack('n')[0]
    data[:encryption] = resp.slice(enc_index, 1).unpack('C')[0]
  end

  if major && minor && build
    data[:version] = "#{major}.#{minor}.#{build}"
  end

  return data
end