Class: Msf::Plugin::Wmap::WmapCommandDispatcher

Inherits:
Object
  • Object
show all
Includes:
Ui::Console::CommandDispatcher
Defined in:
plugins/wmap.rb

Instance Attribute Summary collapse

Attributes included from Ui::Console::CommandDispatcher

#driver

Attributes included from Rex::Ui::Text::DispatcherShell::CommandDispatcher

#shell, #tab_complete_items

Instance Method Summary collapse

Methods included from Ui::Console::CommandDispatcher

#active_module, #active_module=, #active_session, #active_session=, #build_range_array, #docs_dir, #framework, #initialize, #log_error, #remove_lines

Methods included from Rex::Ui::Text::DispatcherShell::CommandDispatcher

#cmd_help, #cmd_help_help, #cmd_help_tabs, #deprecated_cmd, #deprecated_commands, #deprecated_help, #docs_dir, #help_to_s, #initialize, #print, #print_error, #print_good, #print_line, #print_status, #print_warning, #tab_complete_directory, #tab_complete_filenames, #tab_complete_generic, #tab_complete_source_address, #update_prompt

Instance Attribute Details

#killwhenstopObject

Kill process when exiting


22
23
24
# File 'plugins/wmap.rb', line 22

def killwhenstop
  @killwhenstop
end

#lastsitesObject

Temp location of previously obtained sites


16
17
18
# File 'plugins/wmap.rb', line 16

def lastsites
  @lastsites
end

#masstopObject

Flag to stop everything


21
22
23
# File 'plugins/wmap.rb', line 21

def masstop
  @masstop
end

#njobsObject

Max number of jobs


18
19
20
# File 'plugins/wmap.rb', line 18

def njobs
  @njobs
end

#nmaxdisplayObject

Flag to stop displaying the same mesg


19
20
21
# File 'plugins/wmap.rb', line 19

def nmaxdisplay
  @nmaxdisplay
end

#rpcarrObject

Array or rpc connections


17
18
19
# File 'plugins/wmap.rb', line 17

def rpcarr
  @rpcarr
end

#runlocalObject

Flag to run local modules only


20
21
22
# File 'plugins/wmap.rb', line 20

def runlocal
  @runlocal
end

#targetsObject

Targets


15
16
17
# File 'plugins/wmap.rb', line 15

def targets
  @targets
end

#wmapmodulesObject

Enabled Wmap modules


14
15
16
# File 'plugins/wmap.rb', line 14

def wmapmodules
  @wmapmodules
end

Instance Method Details

#active_rpc_nodesObject


2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
# File 'plugins/wmap.rb', line 2163

def active_rpc_nodes
  if self.rpcarr.length == 0
    return 0
  else
    idx = 0
    self.rpcarr.each do |k,conn|
      if conn
        idx += 1
      end
    end
    return idx
  end
end

#add_web_site(url) ⇒ Object

Reusing code from hdmoore

Allow the URL to be supplied as VHOST,URL if a custom VHOST should be used. This allows for things like: localhost,192.168.0.2/admin/


1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
# File 'plugins/wmap.rb', line 1310

def add_web_site(url)

    vhost = nil

    # Allow the URL to be supplied as VHOST,URL if a custom VHOST
    # should be used. This allows for things like:
    #   localhost,http://192.168.0.2/admin/

    if url !~ /^http/
      vhost,url = url.split(",", 2)
      if url.to_s.empty?
        url = vhost
        vhost = nil
      end
    end

    # Prefix http:// when the URL has no specified parameter
    if url !~ /^[a-z0-9A-Z]+:\/\//
      url = "http://" + url
    end

    uri = URI.parse(url) rescue nil
    if not uri
      print_error("Could not understand URL: #{url}")
      return
    end

    if uri.scheme !~ /^https?/
      print_error("Only http and https URLs are accepted: #{url}")
      return
    end

    ssl = false
    if uri.scheme == 'https'
      ssl = true
    end

    site = self.framework.db.report_web_site(:wait => true, :host => uri.host, :port => uri.port, :vhost => vhost, :ssl => ssl, :workspace => self.framework.db.workspace)

    return site
end

#cmd_wmap_modules(*args) ⇒ Object


67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'plugins/wmap.rb', line 67

def cmd_wmap_modules(*args)
  args.push("-h") if args.length == 0

  while (arg = args.shift)
    case arg
    when '-l'
      view_modules
      return
    when '-r'
      load_wmap_modules(true)
      return
    when '-h'
      print_status("Usage: wmap_modules [options]")
      print_line("\t-h 		Display this help text")
      print_line("\t-l  		List all wmap enabled modules")
      print_line("\t-r		Reload wmap modules")

      print_line("")
      return
    else
      print_error("Unknown flag.")
      return
    end
  end
end

#cmd_wmap_nodes(*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
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
# File 'plugins/wmap.rb', line 226

def cmd_wmap_nodes(*args)

  if not self.rpcarr
    self.rpcarr=Hash.new()
  end

  args.push("-h") if args.length == 0

  while (arg = args.shift)
    case arg
    when '-a'
      h = args.shift
      r = args.shift
      s = args.shift
      u = args.shift
      p = args.shift

      res = rpc_add_node(h,r,s,u,p,false)
      if res
        print_status("Node created.")
      else
        print_error("Unable to create node")
      end
    when '-c'
      idref = args.shift

      if not idref
        print_error("No id defined")
        return
      end
      if idref.upcase == 'ALL'
        print_status("All nodes removed")
        self.rpcarr = Hash.new()
      else
        idx=0
        self.rpcarr.each do |k,v|
          if idx == idref.to_i
            self.rpcarr.delete(k)
            print_status("Node deleted #{k}")
          end
          idx += 1
        end
      end
    when '-d'
      host = args.shift
      port = args.shift
      user = args.shift
      pass = args.shift
      dbname = args.shift

      res = rpc_db_nodes(host,port,user,pass,dbname)
      if res
        print_status("OK.")
      else
        print_error("Error")
      end
    when '-l'
      rpc_list_nodes
      return
    when '-j'
      rpc_view_jobs
      return
    when '-k'
      node = args.shift
      jid = args.shift
      rpc_kill_node(node,jid)
      return
    when '-h'
      print_status("Usage: wmap_nodes [options]")
      print_line("\t-h                            Display this help text")
      print_line("\t-c id                         Remove id node (Use ALL for ALL nodes")
      print_line("\t-a host port ssl user pass    Add node")
      print_line("\t-d host port user pass db     Force all nodes to connect to db")
      print_line("\t-j                            View detailed jobs")
      print_line("\t-k ALL|id ALL|job_id          Kill jobs on node")
      print_line("\t-l                            List all current nodes")

      print_line("")
      return
    else
      print_error("Unknown flag.")
      return
    end
  end
end

#cmd_wmap_run(*args) ⇒ Object


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
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
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
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
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
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
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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
# File 'plugins/wmap.rb', line 312

def cmd_wmap_run(*args)
  # Stop everything
  self.masstop = false
  self.killwhenstop  = true

  trap("INT") {
    print_error("Stopping execution...")
    self.masstop = true
    if self.killwhenstop
      rpc_kill_node('ALL','ALL')
    end
  }

  # Max numbers of concurrent jobs per node
  self.njobs = 25
  self.nmaxdisplay = false
  self.runlocal = false

  # Formating
  sizeline = 60

  wmap_show = 2**0
  wmap_expl = 2**1

  # Exclude files can be modified by setting datastore['WMAP_EXCLUDE']
  wmap_exclude_files = '.*\.(gif|jpg|png*)$'

  run_wmap_ssl = true
  run_wmap_server = true
  run_wmap_dir_file = true
  run_wmap_query = true
  run_wmap_unique_query = true
  run_wmap_generic = true

  # If module supports datastore['VERBOSE']
  moduleverbose = false

  showprogress = false

  if not self.rpcarr
    self.rpcarr = Hash.new()
  end

  if not run_wmap_ssl
    print_status("Loading of wmap ssl modules disabled.")
  end
  if not run_wmap_server
    print_status("Loading of wmap server modules disabled.")
  end
  if not run_wmap_dir_file
    print_status("Loading of wmap dir and file modules disabled.")
  end
  if not run_wmap_query
    print_status("Loading of wmap query modules disabled.")
  end
  if not run_wmap_unique_query
    print_status("Loading of wmap unique query modules disabled.")
  end
  if not run_wmap_generic
    print_status("Loading of wmap generic modules disabled.")
  end

  stamp = Time.now.to_f
  mode  = 0

  eprofile = []
  using_p = false
  using_m = false
  usinginipath = false

  mname = ''
  inipathname = '/'

  args.push("-h") if args.length == 0

  while (arg = args.shift)
    case arg
    when '-t'
      mode |= wmap_show
    when '-e'
      mode |= wmap_expl

      profile = args.shift

      if profile
        print_status("Using profile #{profile}.")

        begin
          File.open(profile).each do |str|
            if not str.include? '#'
              # Not a comment
              modname = str.strip
              if not modname.empty?
                eprofile << modname
              end
            end
            using_p = true
          end
        rescue
          print_error("Profile not found or invalid.")
          return
        end
      else
        print_status("Using ALL wmap enabled modules.")
      end
    when '-m'
      mode |= wmap_expl

      mname = args.shift

      if mname
        print_status("Using module #{mname}.")
      end
      using_m = true
    when '-p'
      mode |= wmap_expl

      inipathname = args.shift

      if inipathname
        print_status("Using initial path #{inipathname}.")
      end
      usinginipath = true

    when '-h'
      print_status("Usage: wmap_run [options]")
      print_line("\t-h                        Display this help text")
      print_line("\t-t                        Show all enabled modules")
      print_line("\t-m [regex]                Launch only modules that name match provided regex.")
      print_line("\t-p [regex]                Only test path defined by regex.")
      print_line("\t-e [/path/to/profile]     Launch profile modules against all matched targets.")
      print_line("\t                          (No profile file runs all enabled modules.)")
      print_line("")
      return
    else
      print_error("Unknown flag")
      return
    end
  end

  if (self.rpcarr.length == 0) and (mode & wmap_show == 0)
    print_error("NO WMAP NODES DEFINED. Executing local modules")
    self.runlocal = true
  end

  if self.targets == nil
    print_error("Targets have not been selected.")
    return
  end

  if self.targets.keys.length == 0
    print_error("Targets have not been selected.")
    return
  end

  execmod = true
  if (mode & wmap_show != 0)
    execmod = false
  end

  self.targets.each_with_index do |t, idx|

    selected_host = t[1][:host]
    selected_port = t[1][:port]
    selected_ssl  = t[1][:ssl]
    selected_vhost = t[1][:vhost]

    print_status ("Testing target:")
    print_status ("\tSite: #{selected_vhost} (#{selected_host})")
    print_status ("\tPort: #{selected_port} SSL: #{selected_ssl}")
    print_line '='* sizeline
    print_status("Testing started. #{(Time.now )}")

    if not selected_ssl
      run_wmap_ssl = false
      #print_status ("Target is not SSL. SSL modules disabled.")
    end

    # wmap_dir, wmap_file
    matches = Hash.new()

    # wmap_server
    matches1 = Hash.new()

    # wmap_query
    matches2 = Hash.new()

    # wmap_ssl
    matches3 = Hash.new()

    # wmap_unique_query
    matches5 = Hash.new()

    # wmap_generic
    matches10 = Hash.new()

    # OPTIONS
    opt_str = nil
    jobify  = false

    # This will be clean later
    load_wmap_modules(false)

    self.wmapmodules.each do |w|
      case w[2]
      when :wmap_server
        if run_wmap_server
          matches1[w]=true
        end
      when :wmap_query
        if run_wmap_query
          matches2[w]=true
        end
      when :wmap_unique_query
        if run_wmap_unique_query
          matches5[w]=true
        end
      when :wmap_generic
        if run_wmap_generic
          matches10[w]=true
        end
      when :wmap_dir, :wmap_file
        if run_wmap_dir_file
          matches[w]=true
        end
      when :wmap_ssl
        if run_wmap_ssl
          matches3[w]=true
        end
      else
        # Black Hole
      end
    end

    # Execution order (orderid)
    matches = sort_by_orderid(matches)
    matches1 = sort_by_orderid(matches1)
    matches2 = sort_by_orderid(matches2)
    matches3 = sort_by_orderid(matches3)
    matches5 = sort_by_orderid(matches5)
    matches10 = sort_by_orderid(matches10)

    #
    # Handle modules that need to be run before all tests IF SERVER is SSL, once usually again the SSL web server.
    # :wmap_ssl
    #

    print_status "\n=[ SSL testing ]="
    print_line "=" * sizeline

    if not selected_ssl
      print_status ("Target is not SSL. SSL modules disabled.")
    end

    idx = 0
    matches3.each_key do |xref|
      if self.masstop
        print_error("STOPPED.")
        return
      end

      # Module not part of profile or not match
      if ( using_p and eprofile.include? xref[0].split('/').last ) or (using_m and xref[0].to_s.match(mname)) or (not using_m and not using_p)
        idx += 1

        begin
          # Module options hash
          modopts = Hash.new()

          #
          # The code is just a proof-of-concept and will be expanded in the future
          #
          print_status "Module #{xref[0]}"

          if (mode & wmap_expl != 0)

            #
            # For modules to have access to the global datastore
            # i.e. set -g DOMAIN test.com
            #
            self.framework.datastore.each do |gkey,gval|
              modopts[gkey]=gval
            end

            #
            # Parameters passed in hash xref
            #
            modopts['RHOST'] = selected_host
            modopts['RHOSTS'] = selected_host
            modopts['RPORT'] = selected_port.to_s
            modopts['SSL'] = selected_ssl
            modopts['VHOST'] = selected_vhost.to_s
            modopts['VERBOSE'] = moduleverbose
            modopts['ShowProgress'] = showprogress
            modopts['RunAsJob'] = jobify

            begin
              if execmod
                rpcnode = rpc_round_exec(xref[0],xref[1], modopts, self.njobs)
              end
            rescue ::Exception
              print_status(" >> Exception during launch from #{xref[0]}: #{$!}")
            end
          end

        rescue ::Exception
          print_status(" >> Exception from #{xref[0]}: #{$!}")
        end
      end
    end

    #
    # Handle modules that need to be run before all tests, once usually again the web server.
    # :wmap_server
    #
    print_status "\n=[ Web Server testing ]="
    print_line "=" * sizeline

    idx = 0
    matches1.each_key do |xref|

      if self.masstop
        print_error("STOPPED.")
        return
      end

      # Module not part of profile or not match
      if ( using_p and eprofile.include? xref[0].split('/').last ) or (using_m and xref[0].to_s.match(mname)) or (not using_m and not using_p)
        idx += 1

        begin
          # Module options hash
          modopts = Hash.new()

          #
          # The code is just a proof-of-concept and will be expanded in the future
          #

          print_status "Module #{xref[0]}"

          if (mode & wmap_expl != 0)

            #
            # For modules to have access to the global datastore
            # i.e. set -g DOMAIN test.com
            #
            self.framework.datastore.each do |gkey,gval|
              modopts[gkey]=gval
            end

            #
            # Parameters passed in hash xref
            #
            modopts['RHOST'] = selected_host
            modopts['RHOSTS'] = selected_host
            modopts['RPORT'] = selected_port.to_s
            modopts['SSL'] = selected_ssl
            modopts['VHOST'] = selected_vhost.to_s
            modopts['VERBOSE'] = moduleverbose
            modopts['ShowProgress'] = showprogress
            modopts['RunAsJob'] = jobify

            begin
              if execmod
                rpcnode = rpc_round_exec(xref[0],xref[1], modopts, self.njobs)
              end
            rescue ::Exception
              print_status(" >> Exception during launch from #{xref[0]}: #{$!}")
            end
          end

        rescue ::Exception
          print_status(" >> Exception from #{xref[0]}: #{$!}")
        end
      end
    end

    #
    # Handle modules to be run at every path/file
    # wmap_dir, wmap_file
    #
    print_status "\n=[ File/Dir testing ]="
    print_line "=" * sizeline

    idx = 0
    matches.each_key do |xref|

      if self.masstop
        print_error("STOPPED.")
        return
      end

      # Module not part of profile or not match
      if ( using_p and eprofile.include? xref[0].split('/').last ) or (using_m and xref[0].to_s.match(mname)) or (not using_m and not using_p)
        idx+=1

        begin
          # Module options hash
          modopts = Hash.new()

          #
          # The code is just a proof-of-concept and will be expanded in the future
          #

          print_status "Module #{xref[0]}"

          if (mode & wmap_expl != 0)
            #
            # For modules to have access to the global datastore
            # i.e. set -g DOMAIN test.com
            #
            self.framework.datastore.each do |gkey,gval|
              modopts[gkey]=gval
            end

            #
            # Parameters passed in hash xref
            #
            modopts['RHOST'] = selected_host
            modopts['RHOSTS'] = selected_host
            modopts['RPORT'] = selected_port.to_s
            modopts['SSL'] = selected_ssl
            modopts['VHOST'] = selected_vhost.to_s
            modopts['VERBOSE'] = moduleverbose
            modopts['ShowProgress'] = showprogress
            modopts['RunAsJob'] = jobify

            #
            # Run the plugins that only need to be
            # launched once.
            #

            wtype = xref[2]

            h = self.framework.db.workspace.hosts.find_by_address(selected_host)
            s = h.services.find_by_port(selected_port)
            w = s.web_sites.find_by_vhost(selected_vhost)

            test_tree = load_tree(w)
            test_tree.each do |node|

              if self.masstop
                print_error("STOPPED.")
                return
              end

              p = node.current_path
              testpath = Pathname.new(p)
              strpath = testpath.cleanpath(false).to_s

              #
              # Fixing paths
              #

              if node.is_leaf? and not node.is_root?
                #
                # Later we can add here more checks to see if its a file
                #
              else
                if node.is_root?
                  strpath = "/"
                else
                  strpath = strpath.chomp + "/"
                end
              end

              strpath = strpath.gsub("//", "/")
              #print_status("Testing path: #{strpath}")

              #
              # Launch plugin depending module type.
              # Module type depends on main input type.
              # Code may be the same but it depend on final
              # versions of plugins
              #

              case wtype
              when :wmap_file
                if node.is_leaf? and not node.is_root?
                  #
                  # Check if an exclusion regex has been defined
                  #
                  if self.framework.datastore['WMAP_EXCLUDE']
                    excludefilestr = self.framework.datastore['WMAP_EXCLUDE']
                  else
                    excludefilestr = wmap_exclude_files
                  end

                  if not strpath.match(excludefilestr)
                    if (not usinginipath) or (usinginipath and strpath.match(inipathname))
                      modopts['PATH'] = strpath
                      print_status("Path: #{strpath}")

                      begin
                        if execmod
                          rpcnode = rpc_round_exec(xref[0],xref[1], modopts, self.njobs)
                        end
                      rescue ::Exception
                        print_status(" >> Exception during launch from #{xref[0]}: #{$!}")
                      end
                    end
                  end
                end
              when :wmap_dir
                if (node.is_leaf? and not strpath.include? ".") or node.is_root? or not node.is_leaf?
                  if (not usinginipath) or (usinginipath and strpath.match(inipathname))

                    modopts['PATH'] = strpath
                    print_status("Path: #{strpath}")

                    begin
                      if execmod
                        rpcnode = rpc_round_exec(xref[0],xref[1], modopts, njobs)
                      end
                    rescue ::Exception
                      print_status(" >> Exception during launch from #{xref[0]}: #{$!}")
                    end
                  end
                end
              end
            end
          end
        rescue ::Exception
          print_status(" >> Exception from #{xref[0]}: #{$!}")
        end
      end
    end

    #
    # Run modules for each request to play with URI with UNIQUE query parameters.
    # wmap_unique_query
    #
    print_status "\n=[ Unique Query testing ]="
    print_line "=" * sizeline

    idx = 0
    matches5.each_key do |xref|

      if self.masstop
        print_error("STOPPED.")
        return
      end

      # Module not part of profile or not match
      if ( using_p and eprofile.include? xref[0].split('/').last ) or (using_m and xref[0].to_s.match(mname)) or (not using_m and not using_p)
        idx += 1

        begin
          # Module options hash
          modopts = Hash.new()

          #
          # The code is just a proof-of-concept and will be expanded in the future
          #

          print_status "Module #{xref[0]}"

          if (mode & wmap_expl != 0)
            #
            # For modules to have access to the global datastore
            # i.e. set -g DOMAIN test.com
            #
            self.framework.datastore.each do |gkey,gval|
              modopts[gkey]=gval
            end

            #
            # Parameters passed in hash xref
            #

            modopts['RHOST'] = selected_host
            modopts['RHOSTS'] = selected_host
            modopts['RPORT'] = selected_port.to_s
            modopts['SSL'] = selected_ssl
            modopts['VHOST'] = selected_vhost.to_s
            modopts['VERBOSE'] = moduleverbose
            modopts['ShowProgress'] = showprogress
            modopts['RunAsJob'] = jobify

            #
            # Run the plugins for each request that have a distinct
            # GET/POST  URI QUERY string.
            #

            utest_query = Hash.new()

            h = self.framework.db.workspace.hosts.find_by_address(selected_host)
            s = h.services.find_by_port(selected_port)
            w = s.web_sites.find_by_vhost(selected_vhost)

            w.web_forms.each do |form|

              if self.masstop
                print_error("STOPPED.")
                return
              end

              #
              # Only test unique query strings by comparing signature to previous tested signatures 'path,p1,p2,pn'
              #

              datastr = ""
              typestr = ""

              temparr = []

              #print_status "---------"
              #print_status form.params
              #print_status "+++++++++"

              form.params.each do |p|
                pn, pv, pt = p
                if pn
                  if not pn.empty?
                    if not pv or pv.empty?
                      #TODO add value based on param name
                      pv = "aaa"
                    end

                    #temparr << pn.to_s + "=" + Rex::Text.uri_encode(pv.to_s)
                    temparr << pn.to_s + "=" + pv.to_s
                  end
                else
                  print_error("Blank parameter name. Form #{form.path}")
                end
              end

              datastr = temparr.join("&") if (temparr and not temparr.empty?)

              if (utest_query.has_key?(signature(form.path,datastr)) == false)

                modopts['METHOD'] = form.method.upcase
                modopts['PATH'] =  form.path
                modopts['QUERY'] = form.query
                if form.method.upcase == 'GET'
                  modopts['QUERY'] = datastr
                  modopts['DATA'] = ""
                end
                if form.method.upcase == 'POST'
                  modopts['DATA'] = datastr
                end
                modopts['TYPES'] = typestr

                #
                # TODO: Add headers, etc.
                #
                if (not usinginipath) or (usinginipath and form.path.match(inipathname))

                  print_status "Path #{form.path}"
                  #print_status("Unique PATH #{modopts['PATH']}")
                  #print_status("Unique GET #{modopts['QUERY']}")
                  #print_status("Unique POST #{modopts['DATA']}")
                  #print_status("MODOPTS: #{modopts}")

                  begin
                    if execmod
                      rpcnode = rpc_round_exec(xref[0],xref[1], modopts, self.njobs)
                    end
                    utest_query[signature(form.path,datastr)]=1
                  rescue ::Exception
                    print_status(" >> Exception during launch from #{xref[0]}: #{$!}")
                  end
                end
              else
                #print_status("Already tested")
              end
            end
          end

        rescue ::Exception
          print_status(" >> Exception from #{xref[0]}: #{$!}")
        end
      end
    end

    #
    # Run modules for each request to play with URI query parameters.
    # This approach will reduce the complexity of the Tree used before
    # and will make this shotgun implementation much simple.
    # wmap_query
    #
    print_status "\n=[ Query testing ]="
    print_line "=" * sizeline

    idx = 0
    matches2.each_key do |xref|

      if self.masstop
        print_error("STOPPED.")
        return
      end

      # Module not part of profile or not match
      if not ( using_p and eprofile.include? xref[0].split('/').last ) or (using_m and xref[0].to_s.match(mname)) or (not using_m and not using_p)
        idx += 1

        begin
          # Module options hash
          modopts = Hash.new()

          #
          # The code is just a proof-of-concept and will be expanded in the future
          #

          print_status "Module #{xref[0]}"

          if (mode & wmap_expl != 0)

            #
            # For modules to have access to the global datastore
            # i.e. set -g DOMAIN test.com
            #
            self.framework.datastore.each do |gkey,gval|
              modopts[gkey]=gval
            end

            #
            # Parameters passed in hash xref
            #

            modopts['RHOST'] = selected_host
            modopts['RHOSTS'] = selected_host
            modopts['RPORT'] = selected_port.to_s
            modopts['SSL'] = selected_ssl
            modopts['VHOST'] = selected_vhost.to_s
            modopts['VERBOSE'] = moduleverbose
            modopts['ShowProgress'] = showprogress
            modopts['RunAsJob'] = jobify

            #
            # Run the plugins for each request that have a distinct
            # GET/POST  URI QUERY string.
            #

            h = self.framework.db.workspace.hosts.find_by_address(selected_host)
            s = h.services.find_by_port(selected_port)
            w = s.web_sites.find_by_vhost(selected_vhost)

            w.web_forms.each do |req|

              if self.masstop
                print_error("STOPPED.")
                return
              end

              datastr = ""
              typestr = ""

              temparr = []

              req.params.each do |p|
                pn, pv, pt = p
                if pn
                  if not pn.empty?
                    if not pv or pv.empty?
                      #TODO add value based on param name
                      pv = "aaa"
                    end
                    #temparr << pn.to_s + "=" + Rex::Text.uri_encode(pv.to_s)
                    temparr << pn.to_s + "=" + pv.to_s
                  end
                else
                  print_error("Blank parameter name. Form #{req.path}")
                end
              end

              datastr = temparr.join("&") if (temparr and not temparr.empty?)

              modopts['METHOD'] = req.method.upcase
              modopts['PATH'] =  req.path
              if req.method.upcase == 'GET'
                modopts['QUERY'] = datastr
                modopts['DATA'] = ""
              end
              modopts['DATA'] = datastr if req.method.upcase == 'POST'
              modopts['TYPES'] = typestr

              #
              # TODO: Add method, headers, etc.
              #
              if (not usinginipath) or (usinginipath and req.path.match(inipathname))

                print_status "Path #{req.path}"
                #print_status("Query PATH #{modopts['PATH']}")
                #print_status("Query GET #{modopts['QUERY']}")
                #print_status("Query POST #{modopts['DATA']}")
                #print_status("Query TYPES #{typestr}")

                begin
                  if execmod
                    rpcnode = rpc_round_exec(xref[0],xref[1], modopts, self.njobs)
                  end
                rescue ::Exception
                  print_status(" >> Exception during launch from #{xref[0]}: #{$!}")
                end
              end
            end
          end

        rescue ::Exception
          print_status(" >> Exception from #{xref[0]}: #{$!}")
        end
      end
    end

    #
    # Handle modules that need to be after all tests, once.
    # Good place to have modules that analize the test results and/or
    # launch exploits.
    # :wmap_generic
    #
    print_status "\n=[ General testing ]="
    print_line "=" * sizeline

    idx = 0
    matches10.each_key do |xref|

      if self.masstop
        print_error("STOPPED.")
        return
      end

      # Module not part of profile or not match
      if not ( using_p and eprofile.include? xref[0].split('/').last ) or (using_m and xref[0].to_s.match(mname)) or (not using_m and not using_p)
        idx += 1


        begin
          # Module options hash
          modopts = Hash.new()

          #
          # The code is just a proof-of-concept and will be expanded in the future
          #

          print_status "Module #{xref[0]}"

          if (mode & wmap_expl != 0)

            #
            # For modules to have access to the global datastore
            # i.e. set -g DOMAIN test.com
            #
            self.framework.datastore.each do |gkey,gval|
              modopts[gkey]=gval
            end

            #
            # Parameters passed in hash xref
            #

            modopts['RHOST'] = selected_host
            modopts['RHOSTS'] = selected_host
            modopts['RPORT'] = selected_port.to_s
            modopts['SSL'] = selected_ssl
            modopts['VHOST'] = selected_vhost.to_s
            modopts['VERBOSE'] = moduleverbose
            modopts['ShowProgress'] = showprogress
            modopts['RunAsJob'] = jobify

            #
            # Run the plugins that only need to be
            # launched once.
            #

            begin
              if execmod
                rpcnode = rpc_round_exec(xref[0],xref[1], modopts, self.njobs)
              end
            rescue ::Exception
              print_status(" >> Exception during launch from #{xref[0]}: #{$!}")
            end
          end

        rescue ::Exception
          print_status(" >> Exception from #{xref[0]}: #{$!}")
        end
      end
    end


    if (mode & wmap_expl != 0)
      print_line "+" * sizeline

      if not self.runlocal
        if execmod
          rpc_list_nodes()
          print_status("Note: Use wmap_nodes -l to list node status for completion")
        end
      end

      print_line("Launch completed in #{(Time.now.to_f - stamp)} seconds.")
      print_line "+" * sizeline
    end

    print_status("Done.")
  end

# EOM
end

#cmd_wmap_sites(*args) ⇒ Object


124
125
126
127
128
129
130
131
132
133
134
135
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
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
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 'plugins/wmap.rb', line 124

def cmd_wmap_sites(*args)
  args.push("-h") if args.length == 0

  while (arg = args.shift)
    case arg
    when '-a'
      site = args.shift
      if site
        s = add_web_site(site)
        if s
          print_status("Site created.")
        else
          print_error("Unable to create site")
        end
      else
        print_error("No site provided.")
      end
    when '-d'
      del_idx = args
      if !del_idx.empty?
        delete_sites(del_idx.select {|d| d =~ /^[0-9]*$/}.map(&:to_i).uniq)
        return
      else
        print_error("No index provided.")
      end
    when '-l'
      view_sites
      return
    when '-s'
      u = args.shift
      l = args.shift
      o = args.shift

      return unless u

      if l == nil or l.empty?
        l = 200
        o = 'true'
      else
        # Add check if unicode parameters is the second one
        if l == 'true' or l == 'false'
          o = l
          l = 200
        else
          l = l.to_i
        end
      end

      o = (o == 'true')

      if u.include? 'http'
        # Parameters are in url form
        view_site_tree(u,l,o)
      else
          # Parameters are digits
          if !self.lastsites or self.lastsites.length == 0
          view_sites
          print_status ("Web sites ids. referenced from previous table.")
        end

        target_whitelist = []
        ids = u.to_s.split(/,/)

        ids.each do |id|
          next if id.to_s.strip.empty?

          if id.to_i > self.lastsites.length
            print_error("Skipping id #{id}...")
          else
            target_whitelist << self.lastsites[id.to_i]
            #print_status("Loading #{self.lastsites[id.to_i]}.")
          end
        end

        # Skip the DB entirely if no matches
        return if target_whitelist.length == 0

          unless self.targets
            self.targets = Hash.new()
          end

        target_whitelist.each do |ent|
          view_site_tree(ent,l,o)
        end
      end
      return
    when '-h'
      print_status("Usage: wmap_sites [options]")
      print_line("\t-h        Display this help text")
      print_line("\t-a [url]  Add site (vhost,url)")
      print_line("\t-d [ids]  Delete sites (separate ids with space)")
      print_line("\t-l        List all available sites")
      print_line("\t-s [id]   Display site structure (vhost,url|ids) (level) (unicode output true/false)")
      print_line("")
      return
    else
      print_error("Unknown flag.")
      return
    end
  end
end

#cmd_wmap_targets(*args) ⇒ Object


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
# File 'plugins/wmap.rb', line 93

def cmd_wmap_targets(*args)
  args.push("-h") if args.length == 0

  while (arg = args.shift)
    case arg
    when '-c'
      self.targets = Hash.new()
    when '-l'
      view_targets
      return
    when '-t'
      process_urls(args.shift)
    when '-d'
      process_ids(args.shift)
    when '-h'
      print_status("Usage: wmap_targets [options]")
      print_line("\t-h 		Display this help text")
      print_line("\t-t [urls]	Define target sites (vhost1,url[space]vhost2,url) ")
      print_line("\t-d [ids]	Define target sites (id1, id2, id3 ...)")
      print_line("\t-c 		Clean target sites list")
      print_line("\t-l  		List all target sites")

      print_line("")
      return
    else
      print_error("Unknown flag.")
      return
    end
  end
end

#cmd_wmap_vulns(*args) ⇒ Object


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'plugins/wmap.rb', line 44

def cmd_wmap_vulns(*args)
  args.push("-h") if args.length == 0

  while (arg = args.shift)
    case arg
    when '-l'
      view_vulns
      return
    when '-h'
      print_status("Usage: wmap_vulns [options]")
      print_line("\t-h 		Display this help text")
      print_line("\t-l 		Display web vulns table")

      print_line("")
      return
    else
      print_error("Unknown flag.")
      return
    end
  end
end

#commandsObject

The initial command set


33
34
35
36
37
38
39
40
41
42
# File 'plugins/wmap.rb', line 33

def commands
  {
    "wmap_targets"  => "Manage targets",
    "wmap_sites"   => "Manage sites",
    "wmap_nodes" => "Manage nodes",
    "wmap_run"   => "Test targets",
    "wmap_modules"  => "Manage wmap modules",
    "wmap_vulns"  => "Display web vulns",
  }
end

#delete_sites(wmap_index) ⇒ Object


1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
# File 'plugins/wmap.rb', line 1241

def delete_sites(wmap_index)
  idx  = 0
  to_del = {}
  # Rebuild the index from wmap_sites -l
  self.framework.db.hosts.each do |bdhost|
    bdhost.services.each do |serv|
      serv.web_sites.each do |web|
        # If the index of this site matches any deletion index,
        # add to our hash, saving the index for later output
        to_del[idx] = web if wmap_index.any? {|w| w.to_i == idx}
        idx += 1
      end
    end
  end
  to_del.each do |widx,wsite|
    if wsite.delete
      print_status("Deleted #{wsite.vhost} on #{wsite.service.host.address} at index #{widx}")
    else
      print_error("Could note delete {wsite.vhost} on #{wsite.service.host.address} at index #{widx}")
    end
  end
end

#load_tree(s) ⇒ Object

Load website structure into a tree


1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
# File 'plugins/wmap.rb', line 1577

def load_tree(s)
  wtree = Tree.new(s.vhost)

  # Load site pages
  s.web_pages.order('path asc').each do |req|
    if req.code != 404
      load_tree_core(req, wtree)
    end
  end

  # Load site forms
  s.web_forms.each do |req|
    load_tree_core(req, wtree)
  end

  wtree
end

#load_tree_core(req, wtree) ⇒ Object

Private function to avoid duplicate code


1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
# File 'plugins/wmap.rb', line 1563

def load_tree_core(req, wtree)
  pathchr = '/'
  tarray = req.path.to_s.split(pathchr)
  tarray.delete("")
  tpath = Pathname.new(pathchr)
  tarray.each do |df|
    wtree.add_at_path(tpath.to_s,df)
    tpath = tpath + Pathname.new(df.to_s)
  end
end

#load_wmap_modules(reload) ⇒ Object

Load all wmap modules


2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
# File 'plugins/wmap.rb', line 2238

def load_wmap_modules(reload)
  if reload or not self.wmapmodules
    print_status("Loading wmap modules...")

    self.wmapmodules=[]

    idx = 0
    [ [ framework.auxiliary, 'auxiliary' ], [framework.exploits, 'exploit' ] ].each do |mtype|
      # Scan all exploit modules for matching references
      mtype[0].each_module do |n,m|
        e = m.new

        # Only include wmap_enabled plugins
        if e.respond_to?("wmap_enabled")
          penabled = e.wmap_enabled

          if penabled
            self.wmapmodules << [mtype[1]+'/'+n,mtype[1],e.wmap_type,e.orderid]
            idx += 1
          end
        end
      end
    end
    print_status("#{idx} wmap enabled modules loaded.")
  end
end

#local_module_exec(mod, mtype, opts, nmaxjobs) ⇒ Object


1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
# File 'plugins/wmap.rb', line 1733

def local_module_exec(mod,mtype, opts, nmaxjobs)
  jobify = false

  modinst = framework.modules.create(mod)

  if(not modinst)
    print_error("Unknown module")
    return
  end

  sess = nil

  case mtype
    when 'auxiliary'
      Msf::Simple::Auxiliary.run_simple(modinst, {
        'Action'   => opts['ACTION'],
        'LocalOutput' => driver.output,
        'RunAsJob' => jobify,
        'Options'  => opts
      })
    when 'exploit'
      if not opts['PAYLOAD']
        opts['PAYLOAD'] = WmapCommandDispatcher::Exploit.choose_payload(modinst, opts['TARGET'])
      end

      sess = Msf::Simple::Exploit.exploit_simple(modinst, {
        'Payload'  => opts['PAYLOAD'],
        'Target'   => opts['TARGET'],
        'LocalOutput' => driver.output,
        'RunAsJob' => jobify,
        'Options'  => opts
      })
    else
      print_error("Wrong mtype.")
  end

  if sess
    if (jobify == false and sess.interactive?)
      print_line
      driver.run_single("sessions -q -i #{sess.sid}")
    else
      print_status("Session #{sess.sid} created in the background.")
    end
  end
end

#nameObject


26
27
28
# File 'plugins/wmap.rb', line 26

def name
  "wmap"
end

1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
# File 'plugins/wmap.rb', line 1595

def print_file(filename)
  ext = File.extname(filename)
  if %w(.txt .md).include? ext
    print '%bld%red'
  elsif %w(.css .js).include? ext
    print '%grn'
  end

  print_line("#{ filename }%clr")
end

Print Tree structure. Less ugly Modified by Jon P.


1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
# File 'plugins/wmap.rb', line 1650

def print_tree(tree, ip, max_level, unicode)
  indent = 4
  if  tree != nil and tree.depth <= max_level
    if tree.depth == 0
      print_line "\n" + (' ' * indent) + "%cya[#{tree.name}] (#{ip})%clr"
    end

    i = 1
    c = tree.children.count
    tree.children.each_pair do |_,child|
      print_tree_recursive(child, max_level, indent, [], !(i < c), unicode)
      i += 1
    end

  end
end

Recursive function for printing the tree structure


1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
# File 'plugins/wmap.rb', line 1609

def print_tree_recursive(tree, max_level, indent, prefix, is_last, unicode)
  if  tree != nil and tree.depth <= max_level
    print (' ' * indent)

    # Prefix serve to print the superior hierarchy
    prefix.each { |bool|
      if unicode
        print (bool ? ' ' : '') + (' ' * 3)
      else
        print (bool ? ' ' : '|') + (' ' * 3)
      end
    }
    if unicode
      # The last children is special
      print (is_last ? '' : '') + ('' * 2) + ' '
    else
      print (is_last ? '`' : '|') + ('-' * 2) + ' '
    end

    c = tree.children.count

    if c > 0
      print_line "%bld%blu#{ tree.name }%clr (#{ c.to_s })"
    else
      print_file tree.name
    end

    i = 1
    new_prefix = prefix + [is_last]
    tree.children.each_pair { |_,child|
      is_last = !(i < c)
      print_tree_recursive(child, max_level, indent, new_prefix, is_last, unicode)
      i += 1
    }
  end
end

#process_ids(idsstr) ⇒ Object

Code by hdm. Modified two lines by et lastsites contains a temporary array with vhost,url strings so the id can be referenced in the array and prevent new sites added in the db to corrupt previous id list.


1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
# File 'plugins/wmap.rb', line 1457

def process_ids(idsstr)

  if !self.lastsites or self.lastsites.length == 0
    view_sites
    print_status ("Web sites ids. referenced from previous table.")
  end

  target_whitelist = []
  ids = idsstr.to_s.split(/,/)

  ids.each do |id|
    next if id.to_s.strip.empty?

    if id.to_i > self.lastsites.length
      print_error("Skipping id #{id}...")
    else
      target_whitelist << self.lastsites[id.to_i]
      print_status("Loading #{self.lastsites[id.to_i]}.")
    end
  end

  # Skip the DB entirely if no matches
  return if target_whitelist.length == 0

  if not self.targets
    self.targets = Hash.new()
  end

  target_whitelist.each do |ent|
    process_urls(ent)
  end
end

#process_urls(urlstr) ⇒ Object

Code by hdm. Modified two lines by et


1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
# File 'plugins/wmap.rb', line 1354

def process_urls(urlstr)

  target_whitelist = []

  urls = urlstr.to_s.split(/\s+/)


  urls.each do |url|
    next if url.to_s.strip.empty?
    vhost = nil

    # Allow the URL to be supplied as VHOST,URL if a custom VHOST
    # should be used. This allows for things like:
    #   localhost,http://192.168.0.2/admin/

    if url !~ /^http/
      vhost,url = url.split(",", 2)
      if url.to_s.empty?
        url = vhost
        vhost = nil
      end
    end

    # Prefix http:// when the URL has no specified parameter
    if url !~ /^[a-z0-9A-Z]+:\/\//
      url = "http://" + url
    end

    uri = URI.parse(url) rescue nil
    if not uri
      print_error("Could not understand URL: #{url}")
      next
    end

    if uri.scheme !~ /^https?/
      print_error("Only http and https URLs are accepted: #{url}")
      next
    end

    target_whitelist << [vhost || uri.host, uri]
  end

  # Skip the DB entirely if no matches
  return if target_whitelist.length == 0

  if not self.targets
    # First time targets are defined
    self.targets = Hash.new()
  end

  target_whitelist.each do |ent|
    vhost,target = ent

    host = self.framework.db.workspace.hosts.find_by_address(target.host)
    if not host
      print_error("No matching host for #{target.host}")
      next
    end
    serv = host.services.find_by_port_and_proto(target.port, 'tcp')
    if not serv
      print_error("No matching service for #{target.host}:#{target.port}")
      next
    end

    #print_status "aaa"
    #print_status framework.db.workspace.name

    sites = serv.web_sites.where('vhost = ? and service_id = ?', vhost, serv.id)

    sites.each do |site|
      # Initial defaul path
      inipath = target.path
      if target.path.empty?
        inipath = '/'
      end

      #site.web_forms.where(path: target.path).each do |form|
        ckey = [ site.vhost, host.address, serv.port, inipath].join("|")

        if not self.targets[ckey]
          self.targets[ckey] = WebTarget.new
          self.targets[ckey].merge!({
            :vhost => site.vhost,
            :host  => host.address,
            :port  => serv.port,
            :ssl   => (serv.name == "https"),
            :path  => inipath
          })
          #self.targets[ckey][inipath] = []
        else
          print_status("Target already set in targets list.")
        end

        # Store the form object in the hash for this path
        #self.targets[ckey][inipath] << inipath
      #end
    end
  end
end

#queryparse(query) ⇒ Object


1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
# File 'plugins/wmap.rb', line 1679

def queryparse(query)
  params = Hash.new()

  query.split(/[&;]/n).each do |pairs|
    key, value = pairs.split('=',2)
    if params.has_key?(key)
      #Error
    else
      params[key] = value
    end
  end
  params
end

#quit?Boolean

Returns:

  • (Boolean)

2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
# File 'plugins/wmap.rb', line 2024

def quit?
  begin
    while c = driver.input.read_nonblock(1)
      print_status("Quited")
      return true if c == 'Q'
    end
    false
  rescue Errno::EINTR
    false
  rescue Errno::EAGAIN
    false
  rescue EOFError
    true
  end
end

#rpc_add_node(host, port, ssl, user, pass, bypass_exist) ⇒ Object


1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
# File 'plugins/wmap.rb', line 1693

def rpc_add_node(host,port,ssl,user,pass,bypass_exist)

  if not self.rpcarr
    self.rpcarr = Hash.new()
  end

  begin
    istr = "#{host}|#{port}|#{ssl}|#{user}|#{pass}"
    if self.rpcarr.has_key?(istr) and not bypass_exist and self.rpcarr[istr] != nil
      print_error("Connection already exists #{istr}")
    else
      begin
        temprpc = ::Msf::RPC::Client.new(
          :host => host,
          :port => port,
          :ssl => ssl
        )
      rescue
        print_error "Unable to connect"
        #raise ConnectionError
        return
      end

      res = temprpc.( user , pass)

      if not res
        print_error("Unable to authenticate to #{host}:#{port}.")
        return
      else
        res = temprpc.call('core.version')
      end

      print_status("Connected to #{host}:#{port} [#{res['version']}].")
      self.rpcarr[istr] = temprpc
    end
  rescue
    print_error("Unable to connect")
  end
end

#rpc_db_nodes(host, port, user, pass, name) ⇒ Object


1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
# File 'plugins/wmap.rb', line 1868

def rpc_db_nodes(host,port,user,pass,name)
  rpc_reconnect_nodes()

  if active_rpc_nodes == 0
    print_error("No active nodes at this time")
    return
  end

  self.rpcarr.each do |k,v|
    if v
      res = v.call('db.driver',{:driver => 'postgresql'})
      res = v.call('db.connect',{:database => name, :host => host, :port => port, :username => user, :password => pass})
      res = v.call('db.status')

      if res['db'] == name
        print_status("db_connect #{res} #{host}:#{port} OK")
      else
        print_error("Error db_connect #{res}  #{host}:#{port}")
      end
    else
      print_error("No connection to node #{k}")
    end
  end
end

#rpc_kill_node(i, j) ⇒ Object


1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
# File 'plugins/wmap.rb', line 1931

def rpc_kill_node(i,j)

  if not i
    print_error("Nodes not defined")
    return
  end

  if not j
    print_error("Node jobs defined")
    return
  end

  rpc_reconnect_nodes()

  if active_rpc_nodes == 0
    print_error("No active nodes at this time")
    return
  end

  idx=0
  self.rpcarr.each do |k,rpccon|
    if idx == i.to_i or i.upcase == 'ALL'
      #begin
        if not rpccon
          print_error("No connection to node #{idx}")
        else
          n = rpccon.call('job.list')
          n.each do |id,name|
            if j==id.to_s or j.upcase == 'ALL'
              rpccon.call('job.stop',id)
              print_status("Node #{idx} Killed job id #{id} #{name}")
            end
          end
        end
      #rescue
      #	print_error("No connection")
      #end
    end
    idx += 1
  end
end

#rpc_list_nodesObject


2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
# File 'plugins/wmap.rb', line 2113

def rpc_list_nodes()
  indent = '     '

  tbl = Rex::Text::Table.new(
    'Indent'  => indent.length,
    'Header'  => 'Nodes',
    'Columns' =>
      [
        'Id',
        'Host',
        'Port',
        'SSL',
        'User',
        'Pass',
        'Status',
        '#jobs',
      ])

  idx=0

  rpc_reconnect_nodes()

  self.rpcarr.each do |k,rpccon|

    arrk = k.split('|')

    if not rpccon
      v = "NOCONN"
      n = ""
    else
      begin
        v = rpccon.call('core.version')['version']
      rescue
        v = "ERROR"
      end

      begin
        n = rpccon.call('job.list').length
      rescue
        n = ""
      end
    end

    tbl << [ idx.to_s, arrk[0], arrk[1], arrk[2], arrk[3], arrk[4], v, n]
    idx += 1
  end

  print_status tbl.to_s + "\n"
end

#rpc_mon_nodesObject


2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
# File 'plugins/wmap.rb', line 2040

def rpc_mon_nodes()
  # Pretty monitor

  color = self.opts["ConsoleDriver"].output.supports_color? rescue false

  colors = [
             '%grn',
         '%blu',
         '%yel',
         '%whi'
       ]

  #begin
    loop do
      rpc_reconnect_nodes()

      idx = 0
      self.rpcarr.each do |k,rpccon|

        arrk = k.split('|')

        v = "NOCONN"
        n = 1
        c = '%red'

        if not rpccon
          v = "NOCONN"
          n = 1
          c = '%red'
        else
          begin
            v = ""
            c = '%blu'
          rescue
            v = "ERROR"
            c = '%red'
          end

          begin
            n = rpccon.call('job.list').length
            c = '%blu'
          rescue
            n = 1
            v = "NOCONN"
            c = '%red'
          end
        end

        #begin
          if not @stdio
            @stdio = Rex::Ui::Text::Output::Stdio.new
          end

          if color == true
            @stdio.auto_color
          else
            @stdio.disable_color
          end
          msg = "[#{idx}] #{"%bld#{c}||%clr"*n} #{n} #{v}\n"
          @stdio.print_raw(@stdio.substitute_colors(msg))

        #rescue
          #blah
        #end
        sleep(2)
        idx += 1
      end
    end
  #rescue
  #	print_status("End.")
  #end
end

#rpc_reconnect_nodesObject


1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
# File 'plugins/wmap.rb', line 1893

def rpc_reconnect_nodes()
  begin
    # Sucky 5 mins token timeout.

    idx = nil
    self.rpcarr.each do |k,rpccon|
      if rpccon
        idx = k
        begin
          currentjobs = rpccon.call('job.list').length
        rescue
          tarr = k.split("|")
          rflag = false

          res = rpccon.(tarr[3],tarr[4])

          if res
            rflag = true
            print_error("Reauth to node #{tarr[0]}:#{tarr[1]}")
            break
          else
            raise ConnectionError
          end
        end
      end
    end
  rescue
    print_error("ERROR CONNECTING TO NODE.  Disabling #{idx} use wmap_nodes -a to reconnect")
    self.rpcarr[idx] = nil
    if active_rpc_nodes == 0
      print_error("No active nodes")
      self.masstop = true
    else
      #blah
    end
  end
end

#rpc_round_exec(mod, mtype, opts, nmaxjobs) ⇒ Object


1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
# File 'plugins/wmap.rb', line 1779

def rpc_round_exec(mod,mtype, opts, nmaxjobs)

  res = nil
  idx = 0

  if active_rpc_nodes == 0
    if not self.runlocal
      print_error("All active nodes not working or removed")
      return
    end
    res = true
  else
    rpc_reconnect_nodes()
  end

  if self.masstop
    return
  end

  while not res
    if active_rpc_nodes == 0
      print_error("All active nodes not working or removed")
      return
    end

    #find the node with less jobs load.
    minjobs = nmaxjobs
    minconn = nil
    nid = 0
    self.rpcarr.each do |k,rpccon|
      if not rpccon
        print_error("Skipping inactive node #{nid} #{k}")
      else
        begin
          currentjobs = rpccon.call('job.list').length

          if currentjobs < minjobs
            minconn = rpccon
            minjobs = currentjobs
          end

          if currentjobs == nmaxjobs
            if self.nmaxdisplay == false
              print_error("Node #{nid} reached max number of jobs #{nmaxjobs}")
              print_error("Waiting for available node/slot...")
              self.nmaxdisplay = true
            end
          end
          #print_status("Node #{nid}   #currentjobs #{currentjobs} #min #{minjobs}")
        rescue
          print_error("Unable to connect. Node #{tarr[0]}:#{tarr[1]}")
          self.rpcarr[k]=nil

          if active_rpc_nodes == 0
            print_error("All active nodes ,not working or removed")
            return
          else
            print_error("Sending job to next node")
            next
          end
        end
      end
      nid += 1
    end

    if minjobs < nmaxjobs
      res=minconn.call('module.execute', mtype, mod, opts)
      self.nmaxdisplay = false
      #print_status(">>>#{res} #{mod}")

      if res
        if res.has_key?("job_id")
          return
        else
          print_error("Unable to execute module in node #{k} #{res}")
        end
      end
    else
      #print_status("Max number of jobs #{nmaxjobs} reached in node #{k}")
    end

    idx += 1
  end

  if self.runlocal and not self.masstop
    local_module_exec(mod,mtype, opts, nmaxjobs)
  end
end

#rpc_view_jobsObject


1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
# File 'plugins/wmap.rb', line 1973

def rpc_view_jobs()
  indent = '     '

  rpc_reconnect_nodes()

  if active_rpc_nodes == 0
    print_error("No active nodes at this time")
    return
  end

  idx=0
  self.rpcarr.each do |k,rpccon|
    if not rpccon
      print_status("[Node ##{idx}: #{k} DISABLED/NO CONNECTION]")
    else

      arrk = k.split('|')
      print_status("[Node ##{idx}: #{arrk[0]} Port:#{arrk[1]} SSL:#{arrk[2]} User:#{arrk[3]}]")

      begin
        n = rpccon.call('job.list')

        tbl = Rex::Text::Table.new(
          'Indent'  => indent.length,
          'Header'  => 'Jobs',
          'Columns' =>
            [
              'Id',
              'Job name',
              'Target',
              'PATH',
            ])

        n.each do |id,name|
          jinfo = rpccon.call('job.info',id)
          dstore = jinfo['datastore']
          tbl << [ id.to_s, name,dstore['VHOST']+":"+dstore['RPORT'],dstore['PATH']]
        end

        print_status tbl.to_s + "\n"

      rescue
        print_status("[Node ##{idx} #{k} DISABLED/NO CONNECTION]")
      end
    end
    idx += 1
  end
end

#signature(fpath, fquery) ⇒ Object


1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
# File 'plugins/wmap.rb', line 1667

def signature(fpath,fquery)
  hsig = Hash.new()

  hsig = queryparse(fquery)

  #
  # Signature of the form ',p1,p2,pn' then to be appended to path: path,p1,p2,pn
  #

  sigstr = fpath + "," + hsig.map{|p| p[0].to_s}.join(",")
end

#sort_by_orderid(m) ⇒ Object

Yes sorting hashes dont make sense but actually it does when you are enumerating one. And sort_by of a hash returns an array so this is the reason for this ugly piece of code


2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
# File 'plugins/wmap.rb', line 2223

def sort_by_orderid(m)
  temphash=Hash.new()
  temparr=[]

  temparr = m.sort_by do |xref,v|
      xref[3]
  end

  temparr.each do |b|
    temphash[b[0]] = b[1]
  end
  temphash
end

#view_modulesObject


2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
# File 'plugins/wmap.rb', line 2177

def view_modules
  indent = '     '

  wmaptype = [:wmap_ssl,
        :wmap_server,
        :wmap_dir,
        :wmap_file,
        :wmap_unique_query,
        :wmap_query,
        :wmap_generic
        ]

  if not self.wmapmodules
    load_wmap_modules(true)
  end

  wmaptype.each do |modt|

    tbl = Rex::Text::Table.new(
      'Indent'  => indent.length,
      'Header'  =>  modt.to_s,
      'Columns' =>
        [
          'Name',
          'OrderID',
        ])

    idx = 0
    self.wmapmodules.each do |w|
      oid = w[3]
      if w[3] == 0xFFFFFF
        oid = ":last"
      end

      if w[2] == modt
        tbl << [w[0],oid]
        idx += 1
      end
    end

    print_status tbl.to_s + "\n"
  end
end

#view_site_tree(urlstr, md, ld) ⇒ Object


1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
# File 'plugins/wmap.rb', line 1490

def view_site_tree(urlstr, md, ld)
  if not urlstr
    return
  end

  site_whitelist = []

  urls = urlstr.to_s.split(/\s+/)

  urls.each do |url|
    next if url.to_s.strip.empty?
    vhost = nil

    # Allow the URL to be supplied as VHOST,URL if a custom VHOST
    # should be used. This allows for things like:
    #   localhost,http://192.168.0.2/admin/

    if url !~ /^http/
      vhost,url = url.split(",", 2)

      if url.to_s.empty?
        url = vhost
        vhost = nil
      end
    end

    # Prefix http:// when the URL has no specified parameter
    if url !~ /^[a-z0-9A-Z]+:\/\//
      url = "http://" + url
    end

    uri = URI.parse(url) rescue nil
    if not uri
      print_error("Could not understand URL: #{url}")
      next
    end

    if uri.scheme !~ /^https?/
      print_error("Only http and https URLs are accepted: #{url}")
      next
    end

    site_whitelist << [vhost || uri.host, uri]
  end

  # Skip the DB entirely if no matches
  return if site_whitelist.length == 0

  site_whitelist.each do |ent|
    vhost,target = ent

    host = self.framework.db.workspace.hosts.find_by_address(target.host)
    unless host
      print_error("No matching host for #{target.host}")
      next
    end
    serv = host.services.find_by_port_and_proto(target.port, 'tcp')
    unless serv
      print_error("No matching service for #{target.host}:#{target.port}")
      next
    end

    sites = serv.web_sites.where('vhost = ? and service_id = ?', vhost, serv.id)

    sites.each do |site|
      t = load_tree(site)
      print_tree(t,target.host,md,ld)
      print_line("\n")
    end
  end
end

#view_sitesObject


1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
# File 'plugins/wmap.rb', line 1265

def view_sites
  # Clean temporary sites list
  self.lastsites = []

  indent = '     '

  tbl = Rex::Text::Table.new(
    'Indent'  => indent.length,
    'Header'  => 'Available sites',
    'Columns' =>
      [
        'Id',
        'Host',
        'Vhost',
        'Port',
        'Proto',
        '# Pages',
        '# Forms',
      ])

  idx  = 0
  self.framework.db.hosts.each do |bdhost|
    bdhost.services.each do |serv|
      serv.web_sites.each do |web|
        c = web.web_pages.count
        f = web.web_forms.count
        tbl << [ idx.to_s, bdhost.address, web.vhost, serv.port, serv.name, c.to_s, f.to_s ]
        idx += 1

        turl = web.vhost + "," + serv.name + "://" +bdhost.address.to_s + ":" + serv.port.to_s + "/"
        self.lastsites << turl
      end
    end
  end

  print_status tbl.to_s + "\n"

end

#view_targetsObject


1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
# File 'plugins/wmap.rb', line 1213

def view_targets
  if self.targets == nil or self.targets.keys.length == 0
    print_status "No targets have been defined"
    return
  end

  indent = '     '

  tbl = Rex::Text::Table.new(
    'Indent'  => indent.length,
    'Header'  => 'Defined targets',
    'Columns' =>
      [
        'Id',
        'Vhost',
        'Host',
        'Port',
        'SSL',
        'Path',
      ])

  self.targets.each_with_index { |t, idx|
    tbl << [ idx.to_s, t[1][:vhost], t[1][:host], t[1][:port], t[1][:ssl], "\t"+t[1][:path].to_s ]
  }

  print_status tbl.to_s + "\n"
end

#view_vulnsObject


2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
# File 'plugins/wmap.rb', line 2265

def view_vulns
  framework.db.hosts.each do |host|
    host.services.each do |serv|
      serv.web_sites.each do |site|
        site.web_vulns.each do |wv|
          print_status("+ [#{host.address}] (#{site.vhost}): #{wv.category} #{wv.path}")
          print_status("\t#{wv.name} #{wv.description}")
          print_status("\t#{wv.method} #{wv.proof}")
        end
      end
    end
  end
end